pi-ext bugabingas pi extensions
owned by bugabinga
README Source History Refs Reviews Compare Notes Search Review guide CI runs feat(klaus): reuse the live Claude child and close SDK contract gaps 849739fcc9f9f02fc61f5d613b5e45914936549c
Oliver Krylow <o.krylow@isp-insoft.de > · 17 Sep 2026
SSH signature · not checked
Browse files Compare with HEAD
Expose Pi tools under their own names through CLAUDE_AGENT_SDK_MCP_NO_PREFIX, while the bridge still accepts prefixed names from resumed sessions.
Capture tool identities from the PreToolUse hook, because canUseTool only runs when a call would prompt and a permission rule can answer it first.
Declare anthropic/maxResultSizeChars and truncate above it, so a large Pi tool result is no longer replaced by a pointer into a deleted temp directory.
Run every query in streaming input mode and interrupt the child instead of killing it, which also stops an abandoned turn from spending an extra request.
Isolate the child from ambient Claude Code context, deferred tool loading, MCP tool backgrounding, and non-streaming retries, and flush mirrored transcripts eagerly.
Surface child API retries, self-decided permission denials, warnings, and worker shutdowns to the human.
Reuse the finished child for the next turn in the same session, swap its tool list in place when Pi changes tools, and drop it after a two-minute idle lease or any lineage change.
Record the behavior in a binding specification and measure it: cold turn 1752 ms, reused turn 32 ms.
Changed files (14) Diff layout Auto Unified Split
+6 / −1 text lines
3 3 ## Unreleased ## Unreleased
5 + - Expose Klaus tools to Claude under their Pi names instead of the `mcp__klaus__` prefix, while still accepting prefixed names from resumed sessions and older runtimes6 + - Stop Klaus from replacing large Pi tool results with a `<persisted-output>` pointer into a deleted temp directory, and isolate the Klaus child from ambient Claude Code context, deferred tool loading, tool backgrounding, and non-streaming retries7 + - Capture Klaus tool identities from Claude's `PreToolUse` hook so tool calls keep working when a permission rule answers them without asking Klaus, and truncate tool results at Claude's result-size ceiling instead of losing them to a persisted file8 + - Reuse the running Claude child for the next turn in a Klaus session instead of spawning one per turn, swap its tool list in place when Pi changes tools, and drop it after a two-minute idle lease or any lineage change, saving about 1.7 seconds per follow-up turn9 + - Run every Klaus query in streaming input mode, interrupt the child instead of killing it so an abandoned turn no longer spends an extra request, flush mirrored transcripts eagerly, and surface child API retries, self-decided permission denials, warnings, and worker shutdowns to the human5 10 - Add Bak for asynchronous S3-compatible session backup and conflict-safe restore, with host initialization, manual backup, refresh, and status commands, durable retries, safe partial-failure handling, and no filesystem or network work during Pi startup- Add Bak for asynchronous S3-compatible session backup and conflict-safe restore, with host initialization, manual backup, refresh, and status commands, durable retries, safe partial-failure handling, and no filesystem or network work during Pi startup6 11 - Make Ultra workflow `report` values available to agents as well as human-facing output, while preserving full-output references for oversized reports- Make Ultra workflow `report` values available to agents as well as human-facing output, while preserving full-output references for oversized reports7 12 - Refine Ultra model-tier selection around residual judgement: default to `small`, use `tiny` only for deterministic work, decompose when context or risk benefits exceed handoff cost, and block rather than compensate for missing facts or authority- Refine Ultra model-tier selection around residual judgement: default to `small`, use `tiny` only for deterministic work, decompose when context or risk benefits exceed handoff cost, and block rather than compensate for missing facts or authority256 261 - Add tldr live summaries; model footer; quota parsers; jj-aware workspace- Add tldr live summaries; model footer; quota parsers; jj-aware workspace258 263 - Fix session startup races, stale telemetry, aux LLM calls, provider secret- Fix session startup races, stale telemetry, aux LLM calls, provider secret259 - leaksNo final newline docs/super/specs/2026-08-21-klaus-plan-spec.md Modified +1 / −0 text lines
654 654 On the next provider invocation, Klaus sends the queued Pi message through a new or publicly resumed SDK query.On the next provider invocation, Klaus sends the queued Pi message through a new or publicly resumed SDK query.655 655 If a compatible streaming-input query remains open at that boundary, Klaus may use its public input stream only after exact-version E2E proves equivalent ordering and persistence.If a compatible streaming-input query remains open at that boundary, Klaus may use its public input stream only after exact-version E2E proves equivalent ordering and persistence.
656 + The proposed [Klaus Live Child Reuse Specification](2026-09-17-klaus-live-child-reuse-spec.md) defines that proof and the reuse contract.657 658 Ordering rules:Ordering rules:docs/super/specs/2026-09-17-klaus-live-child-reuse-spec.md Added new file mode 100644+174 / −0 text lines
1 + # Klaus Live Child Reuse Specification 4 + **Status:** Implemented on 2026-09-17; measured gate met6 + **Objective:** Remove the Claude child spawn and initialization cost from every Pi turn by reusing an already-running query, without weakening Pi's ownership of canonical history.10 + This document amends the binding [Klaus Plan and Specification](2026-08-21-klaus-plan-spec.md).11 + Every law in that document stays in force unless this document names the clause it changes.13 + That specification already pre-authorizes this work under proof:15 + > If a compatible streaming-input query remains open at that boundary, Klaus may use its public input stream only after exact-version E2E proves equivalent ordering and persistence.17 + This document turns that conditional permission into a measurable contract.19 + `extensions/klaus/AGENTS.md` still applies: inspect and test the exact installed Pi and Claude Agent SDK APIs before design or code changes, and never rely on memory or summaries.23 + Measured on 2026-09-17 with Agent SDK `0.3.261`, Claude Code `2.1.261`, Windows, `KLAUS_DEBUG_LOG` timestamps around one fake-endpoint E2E turn.27 + | `sdk.start` | 0 ms |28 + | `runtime.create.ready` | 332 ms |29 + | `sdk.query.call` | 340 ms |30 + | `sdk.message.init` | 1327 ms |31 + | first `sdk.streamEvent` | 1346 ms |33 + Child spawn plus the initialize handshake costs about 960 ms per query.34 + The 332 ms before it is dominated by the one-time runtime resolution, which is already cached per process.35 + Every Pi turn that is not a parked-tool continuation pays the 960 ms today, because Klaus opens a new query per turn.39 + When this work is done, all of the following are true.41 + - A Pi turn that continues an unedited lineage reuses the open Claude child and pays no spawn or initialize cost.42 + - Reuse is invisible in the outbound Anthropic request: a reused turn and a freshly resumed turn produce the same canonical message sequence for the same Pi history.43 + - Pi remains the sole source of canonical history, ordering, tools, and steering order.44 + - Any mismatch between Pi's lineage and the reused child's lineage ends the child and falls back to public resume or canonical replay.45 + - A tool-list change alone no longer forces canonical replay.46 + - No Claude child outlives its reuse window, its Pi session, or an abort.47 + - Reuse saves at least 500 ms median per reused turn, measured by the benchmark in this document, or the work is reverted.51 + - Prewarming a child before a turn exists.52 + - Pooling children across Pi sessions.53 + - Holding a child open across session switch, fork, compaction, or shutdown.54 + - Injecting steering or follow-up into an in-flight turn.55 + - Any change to Pi APIs, Pi history, or the replay envelope.56 + - Any use of private Claude Code behavior or transcript internals.60 + ### Reuse instead of prewarm 62 + Klaus keeps the finished query open for a bounded window and sends the next Pi turn through its public input stream with `Query.streamInput()`.63 + The prompt generator stays open until Klaus closes the query, which is already possible because every query now runs in streaming input mode.65 + Prewarming with `startup()` is rejected: it pays the spawn cost for turns that never arrive, needs the same option-equality machinery, and cannot reuse the child's warm state.69 + A pending Pi request may reuse an open query only when every one of these holds.71 + - The request carries the same `sessionId` as the open query.72 + - The open query has delivered a terminal result and has no pending tool calls.73 + - The recorded Klaus checkpoint for that session matches the request lineage under the existing cache-match rules of the binding specification.74 + - Pi's new history equals the history the child already has, plus the new turn's user message.75 + - Effective system instructions, Klaus model, cwd, request headers, child environment, max tokens, thinking level, and thinking budget are unchanged.76 + - The active tool schemas are unchanged, or change only as allowed by the tool-swap rule below.77 + - The Klaus cache protocol version is unchanged.79 + Anything else discards the child and takes the existing path: public resume, fork, or canonical replay.83 + When the only ineligible field is the tool list, Klaus replaces the tool set on the live child instead of discarding it.85 + - Klaus publishes a fresh bridge under a fresh server name through `Query.setMcpServers()` and closes the previous bridge.86 + - Republishing the same server name with the same instance was measured to keep the child's cached tool list, so the generation counter in the server name is load-bearing.87 + - The server name stays invisible to the model because the child runs with `CLAUDE_AGENT_SDK_MCP_NO_PREFIX`.88 + - The next outbound request must contain exactly the new tool definitions and no stale ones.89 + - A swap failure is not retried; it discards the child.91 + Tool swap never rewrites history: earlier tool calls in Pi's history stay exactly as Pi holds them.95 + - A reusable child lives under a dedicated sliding idle lease of two minutes.96 + - The lease refreshes on provider re-entry for that session, SDK activity, and MCP activity.97 + - The existing 15-minute parked-tool lease is unchanged and takes precedence while tool calls are parked.98 + - Lease expiry interrupts the child, closes the query, and removes the child from reuse.99 + - Session switch, fork, compaction, and shutdown close the child, as they do today.100 + - Abort wins: an aborted turn interrupts the child and ends its reuse eligibility.101 + - Klaus holds at most one reusable idle child per `sessionId`.105 + - A reused turn that fails before emitting content falls back to the existing replayable-resume path.106 + - A child that reports `worker_shutting_down`, a mirror error, or a transport failure is discarded, never reused.107 + - Reuse never suppresses or delays an error that Pi would otherwise see.111 + Recorded on 2026-09-17 by `mise run //extensions/klaus:bench`, ten paired samples against the fake endpoint, Agent SDK `0.3.261`.115 + | Cold turn | 1752 ms |116 + | Reused turn | 32 ms |119 + The saving exceeds the 500 ms gate, so the reuse path stays.123 + ### Phase 1: reuse plumbing 125 + **Entry:** current `main` with streaming input mode and hook-based tool identity in place.126 + **Exit:** a second turn in one session reuses the open child, the fake endpoint receives the same canonical request as the non-reuse path, and full `//extensions/klaus:e2e` passes unchanged except for request counts explained in the test.128 + ### Phase 2: eligibility and lifecycle 130 + **Entry:** phase 1 merged.131 + **Exit:** every eligibility rule and every lifecycle rule above has a test; edited history, changed system prompt, changed model, changed thinking, abort, lease expiry, and session events each provably discard the child and produce today's behavior.133 + ### Phase 3: tool swap 135 + **Entry:** phase 2 merged.136 + **Exit:** a tool-list change across a turn boundary keeps the child, the next request carries only the new tool definitions, and the existing canonical-replay test for tool changes is replaced by an explicit swap test with recorded rationale.138 + ### Phase 4: measurement and decision 140 + **Entry:** phases 1 to 3 merged.141 + **Exit:** the benchmark below is recorded in the repository; either the 500 ms median gate is met and the spec status becomes implemented, or the work is reverted and this document records the measured reason.145 + Unit and E2E tests live in the existing `extensions/klaus/__tests__` and `extensions/klaus/__e2e__` suites and run through existing Mise tasks.149 + - Byte-level equality of the outbound Anthropic request body between a reused turn and the equivalent non-reused turn, ignoring ids, timestamps, and usage.150 + - Ordering proof for steering and follow-up: queued Pi messages enter the next model turn in Pi's order.151 + - Parked tool calls still park, settle, and continue across reuse boundaries.152 + - Abort during a reused turn interrupts the child and leaves no process behind.153 + - Lease expiry closes the child and a later turn still succeeds through resume or replay.154 + - Tool swap produces exactly the new tool definitions.155 + - Process cleanup after every path: completion, abort, expiry, session event, and failure.159 + - Measure `sdk.start` to first `sdk.streamEvent` for a fresh query and for a reused turn, at least ten samples each, on one machine, with the fake endpoint.160 + - Record medians and the delta in the repository alongside the SDK version.164 + - Claude injects content into a live session that Pi never sees, so request-equality tests must run on every SDK upgrade.165 + - A long-lived child holds an OAuth token, a temp config directory, and resident memory for up to the idle lease.166 + - Reuse increases the number of states the coordinator must model, which is the part of Klaus that guarantees canonical history.167 + - `setMcpServers()` behavior for an in-process SDK server is unproven for this version and must be demonstrated before phase 3 lands.169 + ## Rejected alternatives 171 + - `startup()` and `WarmQuery` prewarming: pays spawn cost speculatively and cannot reuse warm session state.172 + - Keeping one child alive per Pi session indefinitely: unbounded idle process cost for a personal tool.173 + - Letting a tool-list change ride on the old tool definitions: diverges from Pi's authoritative tool set.174 + - Reusing a child across differing system prompts by patching settings mid-session: the SDK resolves system prompt options once at startup, so the running session would keep the original value.extensions/klaus/__e2e__/fake-anthropic.test.ts Modified +10 / −4 text lines
145 145 content_block : { content_block : {146 146 type : "tool_use" , type : "tool_use" ,147 147 id : "toolu_klaus_1" , id : "toolu_klaus_1" ,148 - name : "mcp__klaus__echo" ,149 149 input : {}, input : {},313 313 queryHandle = await startSdkQuery (request, "fake" , { queryHandle = await startSdkQuery (request, "fake" , {314 314 onReady : async () => undefined , onReady : async () => undefined ,315 315 onActivity : () => undefined , onActivity : () => undefined ,
316 + onNotice : () => undefined ,316 317 onContent : (event) => content.push (event ), onContent : (event) => content.push (event ),317 318 onToolBoundary : () => onToolBoundary : () => 318 319 finished.reject (new Error ("Unexpected tool boundary." )), finished.reject (new Error ("Unexpected tool boundary." )),371 372 onReady : async () => undefined , onReady : async () => undefined ,372 373 onActivity : () => undefined , onActivity : () => undefined ,
374 + onNotice : () => undefined ,373 375 onContent : () => undefined , onContent : () => undefined ,374 376 onToolBoundary : () => onToolBoundary : () => 375 377 finished.reject (new Error ("Unexpected tool boundary." )), finished.reject (new Error ("Unexpected tool boundary." )),418 420 queryHandle = await startSdkQuery (request, "fake" , { queryHandle = await startSdkQuery (request, "fake" , {419 421 onReady : async () => undefined , onReady : async () => undefined ,420 422 onActivity : () => undefined , onActivity : () => undefined ,
423 + onNotice : () => undefined ,421 424 onContent : (event) => { onContent : (event) => {422 425 if (event .type === "tool-end" ) toolEnds.push (event ); if (event .type === "tool-end" ) toolEnds.push (event );446 449 const messages = messageRequests (); const messages = messageRequests ();447 450 expect (messages).toHaveLength (2 ); expect (messages).toHaveLength (2 );448 - expect (JSON .stringify (messages[0 ]?.body )).toContain ("mcp__klaus__echo " );451 + expect (JSON .stringify (messages[0 ]?.body )).toContain (' "name ":"echo" ' );449 452 expect (JSON .stringify (messages[1 ]?.body )).toContain ("hello" ); expect (JSON .stringify (messages[1 ]?.body )).toContain ("hello" );451 454 10 * 60_000 , 10 * 60_000 ,519 522 const messages = messageRequests (); const messages = messageRequests ();520 523 expect (messages.length ).toBeGreaterThanOrEqual (2 ); expect (messages.length ).toBeGreaterThanOrEqual (2 );521 524 const replayBody = JSON .stringify (messages.at (- 1 )?.body ); const replayBody = JSON .stringify (messages.at (- 1 )?.body );522 - expect (replayBody).toContain ("mcp__klaus__new_tool" );523 - expect (replayBody).not.toContain ("mcp__klaus__echo " );525 + expect (replayBody).toContain ('"name":"new_tool"' );526 + expect (replayBody).not.toContain (' "name ":"echo" ' );525 528 10 * 60_000 , 10 * 60_000 ,551 554 onReady : async () => undefined , onReady : async () => undefined ,552 555 onActivity : () => undefined , onActivity : () => undefined ,
556 + onNotice : () => undefined ,553 557 onContent : () => undefined , onContent : () => undefined ,554 558 onToolBoundary : () => onToolBoundary : () => 555 559 firstFinished.reject (new Error ("Unexpected tool boundary." )), firstFinished.reject (new Error ("Unexpected tool boundary." )),585 589 onReady : async () => undefined , onReady : async () => undefined ,586 590 onActivity : () => undefined , onActivity : () => undefined ,
591 + onNotice : () => undefined ,587 592 onContent : () => undefined , onContent : () => undefined ,588 593 onToolBoundary : () => onToolBoundary : () => 589 594 secondFinished.reject (new Error ("Unexpected tool boundary." )), secondFinished.reject (new Error ("Unexpected tool boundary." )),616 621 onReady : async () => undefined , onReady : async () => undefined ,617 622 onActivity : () => undefined , onActivity : () => undefined ,
623 + onNotice : () => undefined ,618 624 onContent : () => undefined , onContent : () => undefined ,619 625 onToolBoundary : () => onToolBoundary : () => 620 626 branchFinished.reject (new Error ("Unexpected tool boundary." )), branchFinished.reject (new Error ("Unexpected tool boundary." )),extensions/klaus/__e2e__/provider-scenarios.test.ts Modified +563 / −10 text lines
1 + import { mkdtemp, rm, writeFile } from "node:fs/promises" ;2 3 createServer, createServer,3 4 type IncomingMessage, type IncomingMessage,4 5 type ServerResponse, type ServerResponse,5 6 } from "node:http" ;} from "node:http" ;
7 + import { tmpdir } from "node:os" ;8 + import { join } from "node:path" ;7 10 createTestSession, createTestSession,8 11 type TestSession, type TestSession,
188 + function childSessionId (captured: CapturedRequest | undefined ): string {189 + const metadata = (captured?.body as { metadata?: { user_id?: string } })191 + if (! metadata?.user_id) throw new Error ("Request carried no user metadata." );192 + const parsed = JSON .parse (metadata.user_id) as { session_id?: string };193 + if (! parsed.session_id)194 + throw new Error ("Request metadata had no session id." );195 + return parsed.session_id;183 198 async function within <T >(async function within <T >(184 199 promise: Promise <T >, promise: Promise <T >,185 200 milliseconds: number , milliseconds: number ,215 230 interface DirectResult {interface DirectResult {216 231 content: KlausContentEvent []; content: KlausContentEvent [];217 233 metadata: Record <string , string >; metadata: Record <string , string >;218 234 result?: { result?: {219 235 usage: KlausUsage ; usage: KlausUsage ;230 246 onHandle?: (handle: KlausQueryHandle ) => Promise <void> , onHandle?: (handle: KlausQueryHandle ) => Promise <void> ,231 247 ): Promise < DirectResult> {): Promise < DirectResult> {232 248 const content: KlausContentEvent[] = []; const content: KlausContentEvent[] = [];
249 + const notices: string[] = [];233 250 let metadata: Record< string, string> = {}; let metadata: Record< string, string> = {};234 251 const terminal = Promise .withResolvers <DirectResult >(); const terminal = Promise .withResolvers <DirectResult >();235 252 let settled = false ; let settled = false ;236 - const finish = ( value: Omit <DirectResult , "content" | "metadata" > ) : void = > { 254 + value: Omit <DirectResult , "content" | "metadata" | " notices " >, 237 256 if (settled) return ; if (settled) return ;238 257 settled = true ; settled = true ;239 - terminal.resolve ({ content, metadata, ... value });258 + terminal.resolve ({ content, notices , metadata, ... value });241 260 let handle: KlausQueryHandle ; let handle: KlausQueryHandle ;245 264 metadata = value; metadata = value;247 266 onActivity : () => undefined , onActivity : () => undefined ,
267 + onNotice : (message) => notices.push (message),248 268 onContent : (event) => content.push (event ), onContent : (event) => content.push (event ),249 269 onToolBoundary : () => undefined , onToolBoundary : () => undefined ,250 270 onResult : (result) => finish ({ result }), onResult : (result) => finish ({ result }),253 273 } catch (error) { } catch (error) {256 277 metadata, metadata,257 278 error: error instanceof Error ? error : new Error (String (error)), error: error instanceof Error ? error : new Error (String (error)),285 306 await Promise .all (servers.splice (0 ).map ((server) => server.close ())); await Promise .all (servers.splice (0 ).map ((server) => server.close ()));286 307 delete process .env .KLAUS_E2E_BASE_URL; delete process .env .KLAUS_E2E_BASE_URL;
308 + delete process .env .KLAUS_REUSE_LEASE_MS;289 311 async function useServer (scenario: Scenario ): Promise <FakeAnthropic > {async function useServer (scenario: Scenario ): Promise <FakeAnthropic > {426 448 content_block : { content_block : {427 449 type : "tool_use" , type : "tool_use" ,428 450 id : "toolu_bad" , id : "toolu_bad" ,429 - name : "mcp__klaus__echo" ,430 452 input : {}, input : {},472 494 content_block : { content_block : {473 495 type : "tool_use" , type : "tool_use" ,474 496 id : "toolu_one" , id : "toolu_one" ,475 - name : "mcp__klaus__echo" ,476 498 input : {}, input : {},482 504 content_block : { content_block : {483 505 type : "tool_use" , type : "tool_use" ,484 506 id : "toolu_two" , id : "toolu_two" ,485 - name : "mcp__klaus__echo" ,486 508 input : {}, input : {},538 560 onReady : async () => undefined , onReady : async () => undefined ,539 561 onActivity : () => undefined , onActivity : () => undefined ,
562 + onNotice : () => undefined ,540 563 onContent : (event) => content.push (event ), onContent : (event) => content.push (event ),541 564 onToolBoundary : () => boundary.resolve (), onToolBoundary : () => boundary.resolve (),542 565 onResult : () => terminal.resolve (), onResult : () => terminal.resolve (),621 644 content_block : { content_block : {622 645 type : "tool_use" , type : "tool_use" ,624 - name : "mcp__klaus__echo" ,625 648 input : {}, input : {},735 758 content_block : { content_block : {736 759 type : "tool_use" , type : "tool_use" ,737 760 id : "toolu_edit" , id : "toolu_edit" ,738 - name : "mcp__klaus__echo" ,739 762 input : {}, input : {},807 830 { type : "text" , text : "edited history used" }, { type : "text" , text : "edited history used" },809 832 const replay = JSON .stringify (server.messageRequests ().at (- 1 )?.body ); const replay = JSON .stringify (server.messageRequests ().at (- 1 )?.body );810 - expect (server.messageRequests ()).toHaveLength (3 );836 + expect (server.messageRequests ()).toHaveLength (2 );811 837 expect (replay).toContain ("edited" ); expect (replay).toContain ("edited" );812 838 expect (replay).toContain ('\\"role\\":\\"toolResult\\"' ); expect (replay).toContain ('\\"role\\":\\"toolResult\\"' );813 839 expect (replay).not.toContain ('"tool_use_id":"toolu_edit"' ); expect (replay).not.toContain ('"tool_use_id":"toolu_edit"' );839 865 content_block : { content_block : {840 866 type : "tool_use" , type : "tool_use" ,841 867 id : "toolu_sessionless" , id : "toolu_sessionless" ,842 - name : "mcp__klaus__echo" ,843 869 input : {}, input : {},1302 1328 const body = server.messageRequests ()[0 ]?.body ; const body = server.messageRequests ()[0 ]?.body ;1303 1329 const serialized = JSON .stringify (body); const serialized = JSON .stringify (body);1304 - expect (serialized).toContain ("mcp__klaus__exact_tool" );1330 + expect (serialized).toContain ('"name":"exact_tool"' );1305 1331 expect (serialized).toContain ("Exact tool description." ); expect (serialized).toContain ("Exact tool description." );1306 1332 expect (serialized).toContain ('"minimum":1' ); expect (serialized).toContain ('"minimum":1' );1307 1333 expect (serialized).toContain ('"maximum":9' ); expect (serialized).toContain ('"maximum":9' );1316 1342 expect (serialized).not.toContain (`"name":"${builtin}"` ); expect (serialized).not.toContain (`"name":"${builtin}"` );1318 1344 }, 60_000 ); }, 60_000 );
1346 + it ("reuses the idle child for the next turn in the same session" , async () => {1347 + const server = await useServer ((_request, index, response) => 1350 + textFrames (index, index === 1 ? "first answer" : "second answer" ),1353 + const { t, model } = await providerSession ();1354 + const sessionId = "reuse-scenario" ;1356 + role: "user" as const ,1357 + content: "first question" ,1361 + const first = await t.session.modelRuntime.completeSimple (1363 + { messages: [question] },1366 + const second = await t.session.modelRuntime.completeSimple (1372 + { role: "user" , content: "second question" , timestamp: 3 },1378 + expect (first.content ).toEqual ([{ type: "text" , text: "first answer" }]);1379 + expect (second.content ).toEqual ([{ type: "text" , text: "second answer" }]);1380 + const requests = server.messageRequests ();1381 + expect (requests).toHaveLength (2 );1384 + expect (childSessionId (requests[0 ])).toBe (childSessionId (requests[1 ]));1385 + const replay = JSON .stringify (requests[1 ]?.body );1386 + expect (replay).toContain ('"text":"second question"' );1387 + expect (replay).toContain ('"text":"first answer"' );1390 + expect (replay.split ("<klaus-history-json>" )).toHaveLength (2 );1393 + it ("discards the idle child when Pi edits the prior turn" , async () => {1394 + const server = await useServer ((_request, index, response) => 1395 + sse (response, textFrames (index, `answer ${index}` )),1397 + const { t, model } = await providerSession ();1398 + const sessionId = "reuse-edited" ;1400 + role: "user" as const ,1401 + content: "original question" ,1405 + const first = await t.session.modelRuntime.completeSimple (1407 + { messages: [question] },1410 + const second = await t.session.modelRuntime.completeSimple (1414 + { ... question, content: "edited question" },1416 + { role: "user" , content: "follow up" , timestamp: 3 },1422 + expect (second.errorMessage).toBeUndefined ();1423 + const requests = server.messageRequests ();1424 + expect (requests).toHaveLength (2 );1425 + expect (childSessionId (requests[0 ])).not.toBe (childSessionId (requests[1 ]));1426 + const replay = JSON .stringify (requests[1 ]?.body );1427 + expect (replay).toContain ("edited question" );1428 + expect (replay).toContain ("follow up" );1431 + it ("discards the idle child when the system prompt changes" , async () => {1432 + const server = await useServer ((_request, index, response) => 1433 + sse (response, textFrames (index, `answer ${index}` )),1435 + const { t, model } = await providerSession ();1436 + const sessionId = "reuse-system-prompt" ;1438 + role: "user" as const ,1439 + content: "first question" ,1443 + const first = await t.session.modelRuntime.completeSimple (1445 + { systemPrompt: "Prompt A." , messages: [question] },1448 + await t.session.modelRuntime.completeSimple (1451 + systemPrompt: "Prompt B." ,1455 + { role: "user" , content: "second question" , timestamp: 3 },1461 + const requests = server.messageRequests ();1462 + expect (requests).toHaveLength (2 );1463 + expect (childSessionId (requests[0 ])).not.toBe (childSessionId (requests[1 ]));1464 + expect (JSON .stringify (requests[1 ]?.body )).toContain ("Prompt B." );1467 + it ("parks a tool call from a reused child and settles it" , async () => {1468 + const server = await useServer ((_request, index, response) => {1471 + messageStart (index),1473 + type: "content_block_start" ,1477 + id: "toolu_reused" ,1483 + type: "content_block_delta" ,1486 + type: "input_json_delta" ,1487 + partial_json: '{"value":"reused"}' ,1490 + { type: "content_block_stop" , index: 0 },1492 + type: "message_delta" ,1493 + delta: { stop_reason: "tool_use" , stop_sequence: null },1494 + usage: { output_tokens: 4 },1496 + { type: "message_stop" },1500 + sse (response, textFrames (index, `answer ${index}` ));1502 + const { t, model } = await providerSession ();1503 + const sessionId = "reuse-tool" ;1507 + description: "Echo." ,1508 + parameters: Type.Object ({ value: Type.String () }),1512 + role: "user" as const ,1513 + content: "first question" ,1517 + const first = await t.session.modelRuntime.completeSimple (1519 + { messages: [question], tools },1522 + const follow = { role: "user" as const , content: "use echo" , timestamp: 3 };1523 + const second = await t.session.modelRuntime.completeSimple (1525 + { messages: [question, first, follow], tools },1528 + const call = second.content .find ((item) => item.type === "toolCall" );1529 + if (call?.type !== "toolCall" ) throw new Error ("Claude did not call echo." );1530 + const third = await t.session.modelRuntime.completeSimple (1539 + role: "toolResult" ,1540 + toolCallId: call.id ,1541 + toolName: call.name ,1542 + content: [{ type: "text" , text: "echo output" }],1552 + expect (third.errorMessage).toBeUndefined ();1553 + const requests = server.messageRequests ();1554 + expect (requests).toHaveLength (3 );1556 + expect (new Set (requests.map ((entry) => childSessionId (entry))).size ).toBe (1559 + expect (JSON .stringify (requests[2 ]?.body )).toContain ("echo output" );1562 + it ("swaps tools on the idle child instead of replaying" , async () => {1563 + const server = await useServer ((_request, index, response) => 1564 + sse (response, textFrames (index, `answer ${index}` )),1566 + const { t, model } = await providerSession ();1567 + const sessionId = "reuse-tool-swap" ;1569 + role: "user" as const ,1570 + content: "first question" ,1575 + description: "Echo." ,1576 + parameters: Type.Object ({ value: Type.String () }),1580 + description: "Probe." ,1581 + parameters: Type.Object ({}),1584 + const first = await t.session.modelRuntime.completeSimple (1586 + { messages: [question], tools: [echo] },1589 + const second = await t.session.modelRuntime.completeSimple (1595 + { role: "user" , content: "second question" , timestamp: 3 },1602 + expect (second.errorMessage).toBeUndefined ();1603 + const requests = server.messageRequests ();1604 + expect (requests).toHaveLength (2 );1605 + expect (childSessionId (requests[0 ])).toBe (childSessionId (requests[1 ]));1606 + const swapped = JSON .stringify (requests[1 ]?.body );1607 + expect (swapped).toContain ('"name":"probe"' );1608 + expect (swapped).not.toContain ('"name":"echo"' );1609 + expect (swapped.split ("<klaus-history-json>" )).toHaveLength (2 );1612 + it ("drops the idle child when its reuse lease expires" , async () => {1613 + process .env .KLAUS_REUSE_LEASE_MS = "250" ;1614 + const server = await useServer ((_request, index, response) => 1615 + sse (response, textFrames (index, `answer ${index}` )),1617 + const { t, model } = await providerSession ();1618 + const sessionId = "reuse-lease" ;1620 + role: "user" as const ,1621 + content: "first question" ,1625 + const first = await t.session.modelRuntime.completeSimple (1627 + { messages: [question] },1630 + await new Promise ((resolve) => setTimeout (resolve, 1500 ));1631 + const second = await t.session.modelRuntime.completeSimple (1637 + { role: "user" , content: "second question" , timestamp: 3 },1643 + expect (second.errorMessage).toBeUndefined ();1644 + const requests = server.messageRequests ();1645 + expect (requests).toHaveLength (2 );1647 + expect (childSessionId (requests[0 ])).not.toBe (childSessionId (requests[1 ]));1650 + it ("surfaces child API retries as notices" , async () => {1651 + const server = await useServer ((_request, index, response) => {1653 + response.writeHead (500 , { "content-type" : "application/json" });1657 + error: { type: "api_error" , message: "upstream exploded" },1662 + sse (response, textFrames (index, "recovered after retries" ));1665 + const result = await directQuery (request ());1667 + expect (result.error).toBeUndefined ();1668 + expect (result.content ).toContainEqual ({1671 + text: "recovered after retries" ,1673 + expect (result.notices.join ("\n" )).toContain ("retrying the Claude request" );1674 + expect (server.messageRequests ().length ).toBeGreaterThanOrEqual (3 );1677 + it ("keeps ambient CLAUDE.md memory out of the child request" , async () => {1678 + const server = await useServer ((_request, index, response) => 1679 + sse (response, textFrames (index, "memory checked" )),1681 + const directory = await mkdtemp (join (tmpdir (), "klaus-memory-" ));1684 + join (directory, "CLAUDE.md" ),1685 + "# Project memory\n\nKLAUS_AMBIENT_MEMORY_SENTINEL must never reach the API.\n" ,1689 + const result = await directQuery (request ({ cwd: directory }));1691 + expect (result.error).toBeUndefined ();1692 + expect (JSON .stringify (server.messageRequests ())).not.toContain (1693 + "KLAUS_AMBIENT_MEMORY_SENTINEL" ,1696 + await rm (directory, {1701 + }).catch (() => undefined );1705 + it ("forwards a tool result larger than the child MCP output cap" , async () => {1706 + const server = await useServer ((_request, index, response) => {1709 + messageStart (index),1711 + type: "content_block_start" ,1721 + type: "content_block_delta" ,1724 + type: "input_json_delta" ,1725 + partial_json: '{"value":"bulk"}' ,1728 + { type: "content_block_stop" , index: 0 },1730 + type: "message_delta" ,1731 + delta: { stop_reason: "tool_use" , stop_sequence: null },1732 + usage: { output_tokens: 4 },1734 + { type: "message_stop" },1738 + sse (response, textFrames (index, "bulk result accepted" ));1741 + const bulk = `${"klaus-bulk-line\n". repeat (13_000)}KLAUS_BULK_TAIL_SENTINEL` ;1743 + const result = await directQuery (1748 + description: "Echo." ,1749 + inputSchema: { type: "object" },1753 + async (handle) => {1754 + await handle.bridge.waitForPending (["toolu_bulk" ]);1756 + handle.bridge.settle ({1758 + content: [{ type: "text" , text: bulk }],1765 + expect (result.error).toBeUndefined ();1766 + const followup = JSON .stringify (server.messageRequests ()[1 ]?.body );1767 + expect (followup).toContain ("KLAUS_BULK_TAIL_SENTINEL" );1768 + expect (followup).not.toMatch (/truncat/ i );1772 + "keeps a parked tool call alive past the auto-background window" ,1774 + const server = await useServer ((_request, index, response) => {1777 + messageStart (index),1779 + type: "content_block_start" ,1783 + id: "toolu_parked" ,1789 + type: "content_block_delta" ,1792 + type: "input_json_delta" ,1793 + partial_json: '{"value":"slow"}' ,1796 + { type: "content_block_stop" , index: 0 },1798 + type: "message_delta" ,1799 + delta: { stop_reason: "tool_use" , stop_sequence: null },1800 + usage: { output_tokens: 4 },1802 + { type: "message_stop" },1806 + sse (response, textFrames (index, "slow result accepted" ));1809 + const result = await directQuery (1814 + description: "Echo." ,1815 + inputSchema: { type: "object" },1819 + async (handle) => {1820 + await handle.bridge.waitForPending (["toolu_parked" ]);1823 + await new Promise ((resolve) => setTimeout (resolve, 150_000 ));1825 + handle.bridge.settle ({1826 + id: "toolu_parked" ,1827 + content: [{ type: "text" , text: "KLAUS_PARKED_SENTINEL" }],1834 + expect (result.error).toBeUndefined ();1835 + expect (server.messageRequests ()).toHaveLength (2 );1836 + expect (JSON .stringify (server.messageRequests ()[1 ]?.body )).toContain (1837 + "KLAUS_PARKED_SENTINEL" ,1843 + it ("keeps every retry of a broken stream streaming" , async () => {1844 + const server = await useServer ((_request, index, response) => {1846 + response.writeHead (200 , {1847 + "content-type" : "text/event-stream" ,1848 + "cache-control" : "no-cache" ,1849 + connection: "keep-alive" ,1852 + `event: message_start\ndata: ${ JSON . stringify ( messageStart (index))}\n\n` ,1854 + response.destroy ();1857 + sse (response, textFrames (index, "stream retried" ));1860 + const result = await directQuery (request ());1862 + expect (result.error).toBeUndefined ();1863 + expect (result.content ).toContainEqual ({1866 + text: "stream retried" ,1868 + const bodies = server.messageRequests ().map ((captured) => captured.body );1869 + expect (bodies.length ).toBeGreaterThanOrEqual (2 );1870 + for (const body of bodies) expect (body).toMatchObject ({ stream: true });extensions/klaus/__e2e__/reuse-benchmark.test.ts Added new file mode 100644+182 / −0 text lines
1 + import { createServer, type ServerResponse } from "node:http" ;5 + } from "@marcfargas/pi-test-harness" ;6 + import { afterEach, describe, expect, it } from "vitest" ;7 + import klaus from "../index" ;12 + const enabled = process .env .KLAUS_BENCH === "1" ;13 + const SAMPLES = Number (process .env .KLAUS_BENCH_SAMPLES ?? 10 );16 + let session: TestSession | undefined ;17 + let closeServer: (() => Promise <void >) | undefined ;19 + function sse (response: ServerResponse , text: string , index: number ): void {20 + const frames: unknown [] = [22 + type: "message_start" ,24 + id: `msg_bench_${index}` ,27 + model: "claude-sonnet-5" ,34 + cache_creation_input_tokens: 0 ,35 + cache_read_input_tokens: 0 ,40 + type: "content_block_start" ,42 + content_block: { type: "text" , text: "" },45 + type: "content_block_delta" ,47 + delta: { type: "text_delta" , text },49 + { type: "content_block_stop" , index: 0 },51 + type: "message_delta" ,52 + delta: { stop_reason: "end_turn" , stop_sequence: null },53 + usage: { output_tokens: 2 },55 + { type: "message_stop" },57 + response.writeHead (200 , {58 + "content-type" : "text/event-stream" ,59 + "cache-control" : "no-cache" ,60 + connection: "keep-alive" ,62 + for (const frame of frames) {64 + `event: ${(frame as { type : string }). type }\ndata: ${ JSON . stringify (frame)}\n\n` ,70 + async function startServer (): Promise <string > {72 + const server = createServer (async (request, response) => {73 + for await (const _chunk of request) {76 + if (request.url?.startsWith ("/v1/messages/count_tokens" )) {77 + response.writeHead (200 , { "content-type" : "application/json" });78 + response.end (JSON .stringify ({ input_tokens: 5 }));82 + sse (response, `answer ${index}` , index);84 + await new Promise <void >((resolve) => server.listen (0 , "127.0.0.1" , resolve));85 + const address = server.address ();86 + if (! address || typeof address === "string" ) {87 + throw new Error ("Benchmark server failed to bind." );89 + closeServer = async () => {90 + server.closeAllConnections ();91 + await new Promise <void >((resolve, reject) => 92 + server.close ((error) => (error ? reject (error) : resolve ())),95 + return `http://127.0.0.1:${address. port }` ;98 + function median (values: number []): number {99 + const sorted = [... values].sort ((left, right) => left - right);100 + const middle = Math .floor (sorted.length / 2 );101 + return sorted.length % 2 === 0 102 + ? ((sorted[middle - 1 ] ?? 0 ) + (sorted[middle] ?? 0 )) / 2 103 + : (sorted[middle] ?? 0 );106 + afterEach (async () => {108 + await session.session.extensionRunner.emit ({109 + type: "session_shutdown" ,113 + session = undefined ;115 + await closeServer ?.();116 + closeServer = undefined ;117 + delete process .env .KLAUS_E2E_BASE_URL;120 + describe.skipIf (! enabled)("Klaus idle child reuse benchmark" , () => {122 + "saves child spawn and initialize time on the second turn" ,124 + process .env .KLAUS_E2E_BASE_URL = await startServer ();125 + session = await createTestSession ({127 + extensionFactories: [klaus],129 + const runtime = session.session.modelRuntime;130 + Object .defineProperty (runtime, "isUsingOAuth" , {134 + Object .defineProperty (runtime, "getAuth" , {136 + value : async () => ({ auth: { apiKey: "fake" }, source: "OAuth" }),138 + const model = runtime.getModel ("klaus" , "claude-sonnet-5" );139 + if (! model) throw new Error ("Klaus model was not registered." );141 + const cold: number [] = [];142 + const reused: number [] = [];143 + for (let sample = 0 ; sample < SAMPLES; sample += 1 ) {144 + const sessionId = `bench-${sample}` ;146 + role: "user" as const ,147 + content: "first question" ,150 + const coldStart = performance .now ();151 + const first = await runtime.completeSimple (153 + { messages: [question] },156 + cold.push (performance .now () - coldStart);157 + const reusedStart = performance .now ();158 + await runtime.completeSimple (164 + { role: "user" , content: "second question" , timestamp: 3 },169 + reused.push (performance .now () - reusedStart);172 + const coldMedian = median (cold);173 + const reusedMedian = median (reused);174 + const saved = coldMedian - reusedMedian;175 + process .stdout .write (176 + `klaus reuse benchmark: cold ${coldMedian. toFixed (0)} ms, reused ${reusedMedian. toFixed (0)} ms, saved ${saved. toFixed (0)} ms over ${SAMPLES} samples\n` ,178 + expect (saved).toBeGreaterThanOrEqual (GATE_MS);extensions/klaus/__tests__/runtime.test.ts Modified +16 / −0 text lines
70 70 CLAUDE_CONFIG_DIR : runtime.configDir, CLAUDE_CONFIG_DIR : runtime.configDir,71 71 CLAUDE_CODE_OAUTH_TOKEN : "fake" , CLAUDE_CODE_OAUTH_TOKEN : "fake" ,72 72 CLAUDE_AGENT_SDK_CLIENT_APP : "klaus/1" , CLAUDE_AGENT_SDK_CLIENT_APP : "klaus/1" ,
73 + CLAUDE_AGENT_SDK_MCP_NO_PREFIX : "1" ,73 74 CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC : "1" , CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC : "1" ,74 75 CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY : "0" , CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY : "0" ,
76 + ENABLE_TOOL_SEARCH : "false" ,77 + CLAUDE_CODE_MCP_AUTO_BACKGROUND_MS : "0" ,78 + CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT : "0" ,79 + CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK : "1" ,80 + MAX_MCP_OUTPUT_TOKENS : "1000000" ,81 + CLAUDE_CODE_DISABLE_CLAUDE_MDS : "1" ,82 + CLAUDE_CODE_DISABLE_AUTO_MEMORY : "1" ,83 + CLAUDE_CODE_DISABLE_BUNDLED_SKILLS : "1" ,84 + CLAUDE_CODE_DISABLE_POLICY_SKILLS : "1" ,85 + CLAUDE_AGENT_SDK_DISABLE_BUILTIN_AGENTS : "1" ,86 + CLAUDE_CODE_DISABLE_WORKFLOWS : "1" ,87 + CLAUDE_CODE_DISABLE_CRON : "1" ,88 + CLAUDE_CODE_DISABLE_BACKGROUND_TASKS : "1" ,89 + CLAUDE_CODE_DISABLE_FILE_CHECKPOINTING : "1" ,90 + CLAUDE_CODE_TMPDIR : runtime.configDir,75 91 ANTHROPIC_BASE_URL : "http://127.0.0.1:43210" , ANTHROPIC_BASE_URL : "http://127.0.0.1:43210" ,76 92 ANTHROPIC_CUSTOM_HEADERS : "X-Custom: present\nX-Empty: " , ANTHROPIC_CUSTOM_HEADERS : "X-Custom: present\nX-Empty: " ,extensions/klaus/__tests__/tool-bridge.test.ts Modified +67 / −1 text lines
64 64 expect (bridge.toolNames ()).toEqual (["echo" , "second tool" ]); expect (bridge.toolNames ()).toEqual (["echo" , "second tool" ]);
67 + it ("keeps the first identity for a repeated tool use id" , async () => {68 + const { bridge, client } = await connectedBridge ();71 + bridge.allow ("echo" , { value: "hook" }, "call-1" );72 + bridge.allow ("echo" , { value: "hook" }, "call-1" );74 + const result = client.callTool ({76 + arguments: { value: "hook" , [TOOL_ID_FIELD]: "call-1" },78 + await bridge.waitForPending (["call-1" ]);79 + expect (bridge.pendingIds ()).toEqual (["call-1" ]);83 + content: [{ type: "text" , text: "hook" }],88 + expect (await result).toMatchObject ({90 + content: [{ type: "text" , text: "hook" }],94 + it ("truncates a tool result above Claude's result size ceiling" , async () => {95 + const { bridge, client } = await connectedBridge ();96 + const oversized = `${"x". repeat (600_000)}TAIL` ;97 + bridge.allow ("echo" , { value: "big" }, "call-big" );98 + const result = client.callTool ({100 + arguments: { value: "big" , [TOOL_ID_FIELD]: "call-big" },102 + await bridge.waitForPending (["call-big" ]);105 + content: [{ type: "text" , text: oversized }],109 + const settled = (await result) as {110 + content: Array <{ type: string ; text: string }>;112 + const text = settled.content [0 ]?.text ?? "" ;113 + expect (text.length ).toBeLessThanOrEqual (500_000 );114 + expect (text).toContain ("Klaus truncated this tool result" );115 + expect (text).not.toContain ("TAIL" );118 + it ("raises the per-tool result size ceiling above Claude's default" , async () => {119 + const { client } = await connectedBridge ();121 + const listed = await client.listTools ();125 + for (const tool of listed.tools) {126 + expect (tool._meta).toEqual ({127 + "anthropic/maxResultSizeChars" : 500_000 ,67 132 it ("counts tool listing, permission, call, and settlement as activity" , async () => { it ("counts tool listing, permission, call, and settlement as activity" , async () => {68 133 const activity = vi.fn (); const activity = vi.fn ();69 134 const { bridge, client } = await connectedBridge ([echo], activity); const { bridge, client } = await connectedBridge ([echo], activity);218 283 it ("rejects a duplicate in-flight call ID without disturbing the original" , async () => { it ("rejects a duplicate in-flight call ID without disturbing the original" , async () => {219 284 const { bridge, client } = await connectedBridge (); const { bridge, client } = await connectedBridge ();220 285 bridge.allow ("echo" , { value: "one" }, "duplicate" ); bridge.allow ("echo" , { value: "one" }, "duplicate" );221 - bridge.allow ("echo" , { value: "two" }, "duplicate" );
222 286 const first = client.callTool ({ const first = client.callTool ({223 287 name: "echo" , name: "echo" ,224 288 arguments: { value: "one" , [TOOL_ID_FIELD]: "duplicate" }, arguments: { value: "one" , [TOOL_ID_FIELD]: "duplicate" },226 290 await bridge.waitForPending (["duplicate" ]); await bridge.waitForPending (["duplicate" ]);
292 + bridge.allow ("echo" , { value: "two" }, "duplicate" );227 293 const duplicate = await client.callTool ({ const duplicate = await client.callTool ({228 294 name: "echo" , name: "echo" ,229 295 arguments: { value: "two" , [TOOL_ID_FIELD]: "duplicate" }, arguments: { value: "two" , [TOOL_ID_FIELD]: "duplicate" },extensions/klaus/mise.toml Modified +6 / −0 text lines
2 + description = "Benchmark Klaus idle child reuse" 3 + depends = ["//:install" ]4 + env = { KLAUS_BENCH = "1" }5 + run = "npx vitest run --config vitest.e2e.config.ts __e2e__/reuse-benchmark.test.ts" 2 8 description = "Run Klaus fake-auth process E2E" description = "Run Klaus fake-auth process E2E" 3 9 depends = ["//:install" ]depends = ["//:install" ]extensions/klaus/src/agent-sdk.ts Modified +228 / −21 text lines
44 + export interface KlausTurn {46 + images?: KlausRequest ["images" ];44 49 export interface KlausQueryHandle {export interface KlausQueryHandle {45 50 bridge: ToolBridge ; bridge: ToolBridge ;46 51 close (reason: string ): Promise <void >; close (reason: string ): Promise <void >;
57 + send (turn: KlausTurn , callbacks: KlausQueryCallbacks ): void ;60 + setTools (tools: KlausRequest ["tools" ]): Promise <void >;63 + interface PromptChannel {64 + stream: AsyncGenerator <SDKUserMessage >;65 + push (message: SDKUserMessage ): void ;71 + function createPromptChannel (first: SDKUserMessage ): PromptChannel {72 + const queue: SDKUserMessage [] = [first];73 + let notify: (() => void ) | undefined ;75 + async function* stream (): AsyncGenerator <SDKUserMessage > {77 + const next = queue.shift ();79 + dbg ?.("sdk.prompt.yield" , {80 + promptLength: next.message.content .length ,86 + await new Promise <void >((resolve) => {91 + const wake = (): void => {92 + const pending = notify;49 109 function effort (level: KlausRequest ["thinking" ]): EffortLevel | undefined {function effort (level: KlausRequest ["thinking" ]): EffortLevel | undefined {159 219 throw new Error (`Unsupported Klaus image type ${value}.` ); throw new Error (`Unsupported Klaus image type ${value}.` );162 - async function* sdkPrompt (163 - request: KlausRequest ,164 - ): AsyncGenerator <SDKUserMessage > {165 - dbg ?.("sdk.prompt.yield " , {166 - promptLength: request .prompt .length ,167 - imageCount: request .images ?.length ?? 0 ,222 + function userMessage (turn: KlausTurn ): SDKUserMessage {223 + dbg ?.("sdk.prompt.build " , {224 + promptLength: turn .prompt .length ,225 + imageCount: turn .images ?.length ?? 0 ,170 228 type: "user" , type: "user" ,171 229 message: { message: {172 230 role: "user" , role: "user" ,173 231 content: [ content: [174 - { type: "text" , text: request .prompt },175 - ... (request .images ?? []).map ((image) => ({232 + { type: "text" , text: turn .prompt },233 + ... (turn .images ?? []).map ((image) => ({176 234 type: "image" as const , type: "image" as const ,177 235 source: { source: {178 236 type: "base64" as const , type: "base64" as const ,222 280 clientApp : runtime.env.CLAUDE_AGENT_SDK_CLIENT_APP, clientApp : runtime.env.CLAUDE_AGENT_SDK_CLIENT_APP,223 281 betas : runtime.betas, betas : runtime.betas,225 - const bridge = new ToolBridge (request.tools, callbacks .onActivity);283 + let active = callbacks;284 + let bridge = new ToolBridge (request.tools, ( ) => active .onActivity ( )) ;285 + let bridgeGeneration = 0 ;226 286 dbg ?.("sdk.bridge.ready" , { toolNames: bridge.toolNames () }); dbg ?.("sdk.bridge.ready" , { toolNames: bridge.toolNames () });227 287 const abortController = new AbortController (); const abortController = new AbortController ();228 288 const blocks = new Map <number , BlockState >(); const blocks = new Map <number , BlockState >();
289 + const channel = createPromptChannel (userMessage (request));229 290 let queryHandle: Query | undefined ; let queryHandle: Query | undefined ;230 291 let pumpPromise: Promise <void > | undefined ; let pumpPromise: Promise <void > | undefined ;231 292 let cleanupPromise: Promise <void > | undefined ; let cleanupPromise: Promise <void > | undefined ;232 293 let closePromise: Promise <void > | undefined ; let closePromise: Promise <void > | undefined ;233 294 let closed = false ; let closed = false ;
295 + let turnActive = true ;296 + let reusable = false ;234 297 let stderr = "" ; let stderr = "" ;235 298 const messageState: MessageState = { const messageState: MessageState = {236 299 usage: { input: 0 , output: 0 , cacheRead: 0 , cacheWrite: 0 }, usage: { input: 0 , output: 0 , cacheRead: 0 , cacheWrite: 0 },237 300 reportedUsage: { input: 0 , output: 0 , cacheRead: 0 , cacheWrite: 0 }, reportedUsage: { input: 0 , output: 0 , cacheRead: 0 , cacheWrite: 0 },
304 + const startTurn = (): void => {306 + messageState.usage = { input: 0 , output: 0 , cacheRead: 0 , cacheWrite: 0 };307 + messageState.reportedUsage = {313 + messageState.deferredOutputLimit = undefined ;314 + messageState.responseId = undefined ;315 + messageState.responseModel = undefined ;322 + const interruptDeadlineMs = 1_500 ;323 + const gracefulStop = async (reason: string ): Promise <void > => {324 + if (! queryHandle || ! turnActive) return ;325 + dbg ?.("sdk.interrupt.start" , { reason });326 + await Promise .race ([327 + queryHandle.interrupt ().catch (() => undefined ),328 + new Promise ((resolve) => setTimeout (resolve, interruptDeadlineMs)),330 + dbg ?.("sdk.interrupt.end" , { reason });240 333 const cleanup = (reason: string ): Promise <void > => { const cleanup = (reason: string ): Promise <void > => {241 334 dbg ?.("sdk.cleanup.request" , { reason, existing: Boolean (cleanupPromise) }); dbg ?.("sdk.cleanup.request" , { reason, existing: Boolean (cleanupPromise) });256 349 closePromise ??= (async () => { closePromise ??= (async () => {257 350 if (! closed) { if (! closed) {258 351 dbg ?.("sdk.close.abort" , { reason }); dbg ?.("sdk.close.abort" , { reason });
352 + await gracefulStop (reason);259 353 closed = true ; closed = true ;260 356 abortController.abort (reason); abortController.abort (reason);261 357 queryHandle?.close (); queryHandle?.close ();275 371 clientApp : runtime.env.CLAUDE_AGENT_SDK_CLIENT_APP, clientApp : runtime.env.CLAUDE_AGENT_SDK_CLIENT_APP,277 373 queryHandle = query ({ queryHandle = query ({279 - request.images && request.images .length > 0 280 - ? sdkPrompt (request)374 + prompt: channel.stream,282 375 options: { options: {283 376 abortController, abortController,284 377 cwd: request.cwd, cwd: request.cwd,293 386 includePartialMessages : true , includePartialMessages : true ,294 387 persistSession : true , persistSession : true ,295 388 sessionStore : request.sessionStore, sessionStore : request.sessionStore,
392 + sessionStoreFlush : "eager" ,296 393 resume : request.resume, resume : request.resume,297 394 resumeSessionAt : request.resumeAt, resumeSessionAt : request.resumeAt,298 395 forkSession : request.forkSession, forkSession : request.forkSession,317 414 dbg ?.("sdk.stderr" , { text }); dbg ?.("sdk.stderr" , { text });318 415 stderr = `${stderr}${data}` .slice (- 4096 ); stderr = `${stderr}${data}` .slice (- 4096 );
424 + async (input, toolUseId) => {425 + if (input.hook_event_name !== "PreToolUse" || ! toolUseId) {426 + return { continue: true };428 + dbg ?.("sdk.hook.preToolUse" , {429 + name: input.tool_name,434 + (input.tool_input ?? {}) as Record <string , unknown >,437 + return { continue: true };320 443 canUseTool : async (name, input, options) => { canUseTool : async (name, input, options) => {321 444 dbg ?.("sdk.canUseTool" , { dbg ?.("sdk.canUseTool" , {351 474 eventType : eventType :352 475 message.type === "stream_event" ? message.event .type : undefined , message.type === "stream_event" ? message.event .type : undefined ,354 - callbacks.onActivity ();477 + active.onActivity ();356 479 (message.type === "assistant" || message.type === "user" ) && (message.type === "assistant" || message.type === "user" ) && 357 480 message.uuid message.uuid361 484 const terminal = await handleMessage ( const terminal = await handleMessage (365 488 messageState, messageState,367 490 if (closed) return ; if (closed) return ;370 493 queryHandle?.close (); queryHandle?.close ();
496 + if (message.type === "result" ) {499 + ! closed && message.subtype === "success" && ! message.is_error;373 501 if (terminal) { if (terminal) {374 504 closed = true ; closed = true ;375 505 abortController.abort ("Klaus stopped max-token recovery." ); abortController.abort ("Klaus stopped max-token recovery." );376 506 queryHandle?.close (); queryHandle?.close ();382 512 const detail = redact (stderr.trim (), oauthToken); const detail = redact (stderr.trim (), oauthToken);383 513 const message = redact (errorText (error), oauthToken); const message = redact (errorText (error), oauthToken);384 514 dbg ?.("sdk.pump.error" , { message, detail }); dbg ?.("sdk.pump.error" , { message, detail });386 - new Error (detail ? `${message}: ${detail}` : message), 515 + active . onError ( new Error (detail ? `${message}: ${detail}` : message)) ; 389 517 } finally { } finally {390 518 dbg ?.("sdk.pump.finally" , { closed }); dbg ?.("sdk.pump.finally" , { closed });391 521 if (! closed) closed = true ; if (! closed) closed = true ;392 522 await cleanup ("Klaus query finished." ); await cleanup ("Klaus query finished." );393 523 if (messageState.deferredOutputLimit) { if (messageState.deferredOutputLimit) {394 - callbacks .onResult (messageState.deferredOutputLimit);524 + active .onResult (messageState.deferredOutputLimit);398 528 pumpPromise = pump (); pumpPromise = pump ();399 529 dbg ?.("sdk.handle.ready" ); dbg ?.("sdk.handle.ready" );400 - return { bridge, close };535 + isIdle : () => reusable && ! closed && ! turnActive,539 + setTools : async (tools) => {540 + if (! reusable || closed || turnActive) {541 + throw new Error ("Klaus query cannot change tools right now." );543 + dbg ?.("sdk.setTools" , { toolNames: tools.map ((tool) => tool.name ) });544 + const previous = bridge;545 + bridgeGeneration += 1 ;546 + const name = `klaus-${bridgeGeneration}` ;547 + const next = new ToolBridge (tools, () => active.onActivity ());548 + await queryHandle?.setMcpServers ({549 + [name]: { type: "sdk" , name, instance: next.server },552 + await previous.close ("Klaus replaced the tool bridge." );554 + send : (turn, turnCallbacks) => {555 + if (! reusable || closed || turnActive) {556 + throw new Error ("Klaus query cannot accept another turn." );559 + promptLength: turn.prompt .length ,560 + imageCount: turn.images ?.length ?? 0 ,562 + for (const image of turn.images ?? []) imageMediaType (image.mimeType);563 + active = turnCallbacks;565 + channel.push (userMessage (turn));403 570 async function handleMessage (async function handleMessage (439 606 return false ; return false ;
608 + if (message.type === "system" && message.subtype === "api_retry" ) {609 + dbg ?.("sdk.message.apiRetry" , {610 + attempt: message.attempt,611 + maxRetries: message.max_retries,612 + status: message.error_status,614 + if (message.attempt > 1 ) {616 + `Klaus is retrying the Claude request (attempt ${message.attempt} of ${message.max_retries}).` ,621 + if (message.type === "system" && message.subtype === "permission_denied" ) {622 + dbg ?.("sdk.message.permissionDenied" , {623 + name: message.tool_name,624 + toolUseId: message.tool_use_id,625 + reasonType: message.decision_reason_type,628 + `Claude denied the ${message.tool_name} tool call without asking Klaus: ${message.message}` ,632 + if (message.type === "system" && message.subtype === "worker_shutting_down" ) {633 + dbg ?.("sdk.message.workerShuttingDown" , { reason: message.reason });635 + new Error (`Klaus child shut down before finishing: ${message.reason}` ),640 + message.type === "system" && 641 + message.subtype === "informational" && 642 + message.level === "warning" 644 + dbg ?.("sdk.message.informational" , { content: message.content });645 + callbacks.onNotice (`Klaus child warning: ${message. content }` );442 649 message.type === "rate_limit_event" && message.type === "rate_limit_event" && 443 650 message.rate_limit_info.status === "rejected" message.rate_limit_info.status === "rejected" extensions/klaus/src/coordinator.ts Modified +220 / −8 text lines
51 51 timer?: ReturnType<typeof setTimeout> ; timer?: ReturnType<typeof setTimeout> ;52 52 timeoutMs?: number; timeoutMs?: number;53 53 idleLease?: ReturnType<typeof setTimeout> ; idleLease?: ReturnType<typeof setTimeout> ;
55 + reuseLease?: ReturnType<typeof setTimeout> ;56 + sdkSessionId?: string;58 + messageCount?: number;61 + lineageFingerprint?: string;54 62 abort?: () => void ; abort?: () => void ;55 63 signal?: AbortSignal; signal?: AbortSignal;56 64 secondary : boolean; secondary : boolean;86 94 dir : string; dir : string;
99 + function reuseLeaseMs (): number {100 + const override = process .env .VITEST101 + ? Number (process .env .KLAUS_REUSE_LEASE_MS)103 + return Number .isSafeInteger (override) && override > 0 ? override : 2 * 60_000 ;89 106 type ResolveOAuth = (modelId: string ) => Promise <string >;type ResolveOAuth = (modelId: string ) => Promise <string >;90 107 type CurrentCwd = () => string ;type CurrentCwd = () => string ;91 108 type CurrentSession = () => SessionScope | undefined ;type CurrentSession = () => SessionScope | undefined ;553 - await this.start (sink, model, context, options, tools);577 + batch.results.length === 0 578 + ? this.findReusable (options.sessionId)554 581 } catch (error) { } catch (error) {555 582 dbg ?.("coordinator.invoke.error" , { dbg ?.("coordinator.invoke.error" , {556 583 error: error instanceof Error ? error.message : String (error), error: error instanceof Error ? error.message : String (error),562 592 private async start ( private async start (563 593 sink: PiSink, sink: PiSink,564 594 model: Model< Api> , model: Model< Api> ,566 596 options : SimpleStreamOptions, options : SimpleStreamOptions,567 597 tools : KlausRequest["tools" ], tools : KlausRequest["tools" ],568 598 forceCold = false , forceCold = false ,
599 + reusable?: ActiveQuery,569 600 ): Promise <void> { ): Promise <void> {570 601 dbg?.("coordinator.start.begin" , { dbg?.("coordinator.start.begin" , {571 602 modelId: model.id , modelId: model.id ,630 661 found : Boolean (completed), found : Boolean (completed),631 662 messageCount : completed?.messageCount, messageCount : completed?.messageCount,
665 + reusable && ! forceCold && reusable.handle?.isIdle () === true 666 + ? this.reuseFit (reusable, context, model, options, tools, identity)668 + dbg ?.("coordinator.start.reuseFit" , {669 + offered: Boolean (reusable),672 + const reuse = offered ? reusable : undefined ;673 + if (reusable && ! reuse) {674 + await this.closeState (676 + "Klaus cannot reuse the idle child for this turn." ,679 + const reuseBoundary = reuse?.messageCount;633 680 const deltaContext: Context = { const deltaContext: Context = {634 681 systemPrompt: context.systemPrompt, systemPrompt: context.systemPrompt,636 - ? context.messages.slice (completed.messageCount)683 + reuseBoundary !== undefined 684 + ? context.messages.slice (reuseBoundary)686 + ? context.messages.slice (completed.messageCount)638 688 tools: context.tools, tools: context.tools,640 690 const linearResume = const linearResume = 641 - completed !== undefined && 691 + ( reuse !== undefined || completed !== undefined ) && 642 692 deltaContext.messages.length === 1 && deltaContext.messages.length === 1 && 643 693 isTextUser (deltaContext.messages[0 ]); isTextUser (deltaContext.messages[0 ]);644 - const canResume = completed !== undefined ;694 + const canResume = reuse === undefined && completed !== undefined ;645 695 dbg ?.("coordinator.start.resumePlan" , { dbg ?.("coordinator.start.resumePlan" , {646 696 linearResume, linearResume,647 697 canResume, canResume,
698 + reused: Boolean (reuse),648 699 deltaMessageCount: deltaContext.messages.length , deltaMessageCount: deltaContext.messages.length ,650 701 const staging = new StagingSessionStore (completed?.store ?? store); const staging = new StagingSessionStore (completed?.store ?? store);730 781 persisted : scope?.persisted, persisted : scope?.persisted,731 782 dir : scope?.dir , dir : scope?.dir ,733 - const state: ActiveQuery = {786 + (transformed.prompt !== request.prompt || 787 + transformed.systemPrompt !== request.systemPrompt || 788 + transformed.modelId !== request.modelId || 789 + transformed.selector !== request.selector || 790 + transformed.cwd !== request.cwd || 791 + JSON .stringify (transformed.tools) !== JSON .stringify (request.tools))793 + dbg ?.("coordinator.start.reuseRejectedByHook" );794 + await this.closeState (796 + "Klaus onPayload changed a reused turn; replaying canonically." ,798 + await this.start (sink, model, context, options, tools, true );801 + const state: ActiveQuery = reuse ?? {734 802 id: Symbol ("klaus-query" ), id: Symbol ("klaus-query" ),735 803 sessionId: options.sessionId, sessionId: options.sessionId,753 821 store : completed?.store ?? store, store : completed?.store ?? store,756 - this.addState (state);825 + if (state.reuseLease) clearTimeout (state.reuseLease);826 + state.reuseLease = undefined ;828 + state.context = context;829 + state.tools = tools;830 + state.toolCallIds = new Set ();831 + state.emittedContent = false ;832 + state.timeoutMs = transformed.timeoutMs;833 + state.boundaryFingerprint = undefined ;834 + state.boundaryMessageCount = undefined ;836 + this.addState (state);757 838 dbg ?.("coordinator.start.stateAdded" , { dbg ?.("coordinator.start.stateAdded" , {758 839 sessionId: state.sessionId, sessionId: state.sessionId,759 840 secondary: state.secondary, secondary: state.secondary,760 841 committable: state.committable, committable: state.committable,
842 + reused: Boolean (reuse),762 844 this.armTimeout (state, transformed.timeoutMs); this.armTimeout (state, transformed.timeoutMs);763 845 this.replaceAbort (state, options.signal); this.replaceAbort (state, options.signal);776 858 dbg ?.("coordinator.callback.activity" , { closed: state.closed }); dbg ?.("coordinator.callback.activity" , { closed: state.closed });777 859 this.touchState (state, state.timeoutMs); this.touchState (state, state.timeoutMs);
861 + onNotice : (message) => {862 + dbg ?.("coordinator.callback.notice" , { message });779 865 onContent : (event) => { onContent : (event) => {780 866 dbg ?.("coordinator.callback.content" , { dbg ?.("coordinator.callback.content" , {781 867 type: event .type , type: event .type ,867 953 store : state.store, store : state.store,869 955 this.completed.set (state.sessionId, completed); this.completed.set (state.sessionId, completed);
956 + state.sdkSessionId = completed.sdkSessionId;957 + state.position = completed.position;958 + state.messageCount = completed.messageCount;959 + state.lineageFingerprint = contextFingerprint (961 + systemPrompt: state.context.systemPrompt,962 + messages: [... state.context.messages, resultSink.output],964 + `${state.modelId}\0${state.cwd}` ,870 966 if (this.checkpointRoot (state.sessionId)) { if (this.checkpointRoot (state.sessionId)) {871 967 this.pendingCheckpoints.set (state.sessionId, completed); this.pendingCheckpoints.set (state.sessionId, completed);885 981 result.stopReason, result.stopReason,
984 + if (this.keepForReuse (state)) return ;888 985 await this.closeState (state, "Klaus query completed." ); await this.closeState (state, "Klaus query completed." );889 986 })().catch ((error) => { })().catch ((error) => {890 987 resultSink?.error (error); resultSink?.error (error);924 1021 void this.closeState (state, error.message); void this.closeState (state, error.message);
1026 + if (offered?.fit === "swap" ) {1027 + dbg ?.("coordinator.reuse.swapTools" , {1028 + toolNames: tools.map ((tool) => tool.name ),1030 + await state.handle?.setTools (tools);1032 + if (state.metadata) {1033 + await options.onResponse ?.(1034 + { status: 200 , headers: state.metadata },1038 + if (state.closed ) return ;1039 + dbg ?.("coordinator.reuse.send" , {1040 + sessionId: state.sessionId,1041 + promptLength: transformed.prompt .length ,1043 + state.handle?.send (1044 + { prompt: transformed.prompt , images: transformed.images },1048 + dbg ?.("coordinator.reuse.error" , {1049 + error: error instanceof Error ? error.message : String (error),1051 + state.sink = undefined ;1052 + await this.closeState (state, "Klaus could not reuse the idle child." );1053 + await this.start (sink, model, context, options, tools, forceCold);928 1058 dbg ?.("coordinator.oauth.resolve.start" , { modelId: model.id }); dbg ?.("coordinator.oauth.resolve.start" , { modelId: model.id });929 1059 const oauth = await this.resolveOAuth (model.id ); const oauth = await this.resolveOAuth (model.id );
1088 + state: ActiveQuery,1091 + options: SimpleStreamOptions,1092 + tools: KlausRequest["tools" ],1094 + ): { fit: "reuse" | "swap" } | undefined {1095 + const boundary = state.messageCount;1096 + if (boundary === undefined || state.closed ) return undefined ;1097 + const delta = context.messages.slice (boundary);1098 + if (delta.length !== 1 || ! isTextUser (delta[0 ])) return undefined ;1100 + state.modelId !== model.id || 1101 + state.cwd !== this.currentCwd () || 1102 + state.systemPrompt !== (context.systemPrompt ?? "" ) || 1103 + state.thinking !== options.reasoning || 1104 + state.thinkingBudget !== thinkingBudget (options) || 1105 + state.maxTokens !== options.maxTokens || 1106 + ! sameStringRecord (state.headers , options.headers ) || 1107 + ! sameStringRecord (state.env, options.env)1111 + const lineage = contextFingerprint (1113 + systemPrompt: context.systemPrompt,1114 + messages: context.messages.slice (0 , boundary),1118 + if (state.lineageFingerprint !== lineage) return undefined ;1121 + JSON .stringify (state.tools) === JSON .stringify (tools)1129 + private keepForReuse (state: ActiveQuery): boolean {1132 + state.committable && 1133 + Boolean (state.sessionId) && 1134 + Boolean (state.sdkSessionId) && 1135 + Boolean (state.position) && 1136 + state.handle !== undefined ;1137 + dbg ?.("coordinator.keepForReuse" , {1138 + sessionId: state.sessionId,1141 + if (! reusable) return false ;1142 + state.sink = undefined ;1143 + if (state.timer) clearTimeout (state.timer);1144 + state.timer = undefined ;1145 + if (state.reuseLease) clearTimeout (state.reuseLease);1146 + state.reuseLease = setTimeout (1147 + () => void this.closeState (state, "Klaus idle child lease expired." ),1153 + private findReusable (sessionId: string | undefined ): ActiveQuery | undefined {1154 + if (! sessionId) return undefined ;1155 + const found = [... (this.bySession.get (sessionId) ?? [])].find (1156 + (state) => ! state.closed && state.reuseLease !== undefined ,1158 + dbg ?.("coordinator.findReusable" , { sessionId, found: Boolean (found) });954 1162 private findContinuation ( private findContinuation (955 1163 sessionId: string | undefined , sessionId: string | undefined ,956 1164 results: PiToolResult[], results: PiToolResult[],963 1171 return [... (this.bySession.get (sessionId) ?? [])].find ( return [... (this.bySession.get (sessionId) ?? [])].find (964 1172 (state) => (state) => 965 1173 ! state.closed && ! state.closed &&
1176 + state.reuseLease === undefined && 966 1177 results.every ((result) => state.toolCallIds.has (result.id )), results.every ((result) => state.toolCallIds.has (result.id )),1088 1299 state.closePromise = (async () => { state.closePromise = (async () => {1089 1300 if (state.timer) clearTimeout (state.timer); if (state.timer) clearTimeout (state.timer);1090 1301 if (state.idleLease) clearTimeout (state.idleLease); if (state.idleLease) clearTimeout (state.idleLease);
1302 + if (state.reuseLease) clearTimeout (state.reuseLease);1091 1303 if (state.signal && state.abort) { if (state.signal && state.abort) {1092 1304 state.signal.removeEventListener ("abort" , state.abort); state.signal.removeEventListener ("abort" , state.abort);extensions/klaus/src/protocol.ts Modified +3 / −0 text lines
85 85 export interface KlausQueryCallbacks {export interface KlausQueryCallbacks {86 86 onReady (metadata: Record <string , string >): Promise <void >; onReady (metadata: Record <string , string >): Promise <void >;87 87 onActivity (): void ; onActivity (): void ;
90 + onNotice (message: string ): void ;88 91 onContent (event: KlausContentEvent ): void ; onContent (event: KlausContentEvent ): void ;89 92 onToolBoundary (result: { onToolBoundary (result: {90 93 usage: KlausUsage ; usage: KlausUsage ;extensions/klaus/src/runtime/index.ts Modified +35 / −0 text lines
111 111 env.CLAUDE_CONFIG_DIR = configDir; env.CLAUDE_CONFIG_DIR = configDir;112 112 env.CLAUDE_CODE_OAUTH_TOKEN = oauthToken; env.CLAUDE_CODE_OAUTH_TOKEN = oauthToken;113 113 env.CLAUDE_AGENT_SDK_CLIENT_APP = "klaus/1" ; env.CLAUDE_AGENT_SDK_CLIENT_APP = "klaus/1" ;
118 + env.CLAUDE_AGENT_SDK_MCP_NO_PREFIX = "1" ;114 119 env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC = "1" ; env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC = "1" ;115 120 env.CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY = "0" ; env.CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY = "0" ;
123 + env.ENABLE_TOOL_SEARCH = "false" ;127 + env.CLAUDE_CODE_MCP_AUTO_BACKGROUND_MS = "0" ;128 + env.CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT = "0" ;131 + env.CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK = "1" ;135 + env.MAX_MCP_OUTPUT_TOKENS = "1000000" ;139 + env.CLAUDE_CODE_DISABLE_CLAUDE_MDS = "1" ;140 + env.CLAUDE_CODE_DISABLE_AUTO_MEMORY = "1" ;141 + env.CLAUDE_CODE_DISABLE_BUNDLED_SKILLS = "1" ;142 + env.CLAUDE_CODE_DISABLE_POLICY_SKILLS = "1" ;143 + env.CLAUDE_AGENT_SDK_DISABLE_BUILTIN_AGENTS = "1" ;144 + env.CLAUDE_CODE_DISABLE_WORKFLOWS = "1" ;145 + env.CLAUDE_CODE_DISABLE_CRON = "1" ;146 + env.CLAUDE_CODE_DISABLE_BACKGROUND_TASKS = "1" ;147 + env.CLAUDE_CODE_DISABLE_FILE_CHECKPOINTING = "1" ;150 + env.CLAUDE_CODE_TMPDIR = configDir;116 151 if (maxTokens !== undefined ) { if (maxTokens !== undefined ) {117 152 if (! Number .isSafeInteger (maxTokens) || maxTokens < 1 ) { if (! Number .isSafeInteger (maxTokens) || maxTokens < 1 ) {118 153 throw new Error ( throw new Error (extensions/klaus/src/tool-bridge.ts Modified +65 / −9 text lines
30 30 export const TOOL_ID_FIELD = "__klausToolUseID" ;export const TOOL_ID_FIELD = "__klausToolUseID" ;
37 + const MAX_RESULT_SIZE_CHARS = 500_000 ;39 + const TRUNCATION_NOTE = 40 + "\n[Klaus truncated this tool result at Claude's 500000-character result limit.]" ;46 + function boundedContent (47 + content: PiToolResult ["content" ],48 + ): PiToolResult ["content" ] {49 + let remaining = MAX_RESULT_SIZE_CHARS;50 + let truncated = false ;51 + const bounded: PiToolResult ["content" ] = [];52 + for (const item of content) {53 + if (item.type !== "text" ) {54 + bounded.push ({ ... item });57 + if (truncated) continue ;58 + if (item.text .length <= remaining) {59 + remaining -= item.text .length ;60 + bounded.push ({ ... item });63 + const kept = item.text .slice (65 + Math .max (0 , remaining - TRUNCATION_NOTE.length ),67 + dbg ?.("bridge.settle.truncated" , {68 + originalLength: item.text .length ,69 + keptLength: kept.length ,71 + bounded.push ({ type: "text" , text: `${kept}${TRUNCATION_NOTE}` });32 78 const originalName = (name: string ): string => const originalName = (name: string ): string => 33 79 name.startsWith ("mcp__klaus__" ) ? name.slice ("mcp__klaus__" .length ) : name; name.startsWith ("mcp__klaus__" ) ? name.slice ("mcp__klaus__" .length ) : name;75 121 name : tool.name , name : tool.name ,76 122 description : tool.description , description : tool.description ,77 123 inputSchema : tool.inputSchema, inputSchema : tool.inputSchema,
125 + "anthropic/maxResultSizeChars" : MAX_RESULT_SIZE_CHARS,127 179 allow (name: string, input: Record< string, unknown> , id: string): void { allow (name: string, input: Record< string, unknown> , id: string): void {
180 + const duplicate = this.permissions.some ((call) => call.id === id);128 181 dbg ?.("bridge.allow" , { dbg ?.("bridge.allow" , {131 184 inputKeys: Object .keys (input), inputKeys: Object .keys (input),133 187 this.onActivity (); this.onActivity ();
188 + if (duplicate) return ;134 189 this.permissions.push ({ id, name: originalName (name), input }); this.permissions.push ({ id, name: originalName (name), input });140 195 return names; return names;
200 + replaceTools (tools: KlausTool[]): void {201 + dbg ?.("bridge.replaceTools" , {202 + toolNames: tools.map ((tool) => tool.name ),204 + this.tools = new Map (tools.map ((tool) => [tool.name , tool]));143 207 hasSchemaChange (tools: KlausTool[]): boolean { hasSchemaChange (tools: KlausTool[]): boolean {144 208 const changed = const changed = 145 209 JSON .stringify ([... this.tools.values ()]) !== JSON .stringify (tools); JSON .stringify ([... this.tools.values ()]) !== JSON .stringify (tools);184 248 this.pending.delete (result.id ); this.pending.delete (result.id );185 249 this.settled.add (result.id ); this.settled.add (result.id );186 250 pending.resolve ({ pending.resolve ({187 - content: result.content .map ((item) => 188 - item.type === "text" 189 - ? { type: "text" as const , text: item.text }191 - type: "image" as const ,193 - mimeType: item.mimeType,251 + content: boundedContent (result.content ),196 252 isError: result.isError, isError: result.isError,198 254 dbg ?.("bridge.settle.end" , { id: result.id }); dbg ?.("bridge.settle.end" , { id: result.id });