repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat(klaus): reuse the live Claude child and close SDK contract gaps

849739fcc9f9f02fc61f5d613b5e45914936549c

Oliver Krylow <o.krylow@isp-insoft.de> ·

SSH signature · not checked

Browse filesCompare 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)

+1576 / −54 text lines

Diff layout

CHANGELOG.md

Modified

+6 / −1 text lines

33## 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 runtimes
6- 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 retries
7- 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 file
8- 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 turn
9- 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 human
510- 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
611- Make Ultra workflow `report` values available to agents as well as human-facing output, while preserving full-output references for oversized reports
712- 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
256261- Add tldr live summaries; model footer; quota parsers; jj-aware workspace
257262 status
258263- Fix session startup races, stale telemetry, aux LLM calls, provider secret
259 leaksNo final newline
264 leaks

docs/super/specs/2026-08-21-klaus-plan-spec.md

Modified

+1 / −0 text lines

654654On the next provider invocation, Klaus sends the queued Pi message through a new or publicly resumed SDK query.
655655If 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.
656The proposed [Klaus Live Child Reuse Specification](2026-09-17-klaus-live-child-reuse-spec.md) defines that proof and the reuse contract.
657658Ordering 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
2
3**Date:** 2026-09-17
4**Status:** Implemented on 2026-09-17; measured gate met
5**Provider:** `klaus`
6**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.
7
8## Authority
9
10This document amends the binding [Klaus Plan and Specification](2026-08-21-klaus-plan-spec.md).
11Every law in that document stays in force unless this document names the clause it changes.
13That 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.
17This 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.
21## Measured baseline
23Measured 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.
25| Marker | Offset |
26| --- | --- |
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 |
33Child spawn plus the initialize handshake costs about 960 ms per query.
34The 332 ms before it is dominated by the one-time runtime resolution, which is already cached per process.
35Every Pi turn that is not a parked-tool continuation pays the 960 ms today, because Klaus opens a new query per turn.
37## Outcome contract
39When 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.
49## Non-goals
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.
58## Design
60### Reuse instead of prewarm
62Klaus keeps the finished query open for a bounded window and sends the next Pi turn through its public input stream with `Query.streamInput()`.
63The prompt generator stays open until Klaus closes the query, which is already possible because every query now runs in streaming input mode.
65Prewarming 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.
67### Reuse eligibility
69A 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.
79Anything else discards the child and takes the existing path: public resume, fork, or canonical replay.
81### Tool swap
83When 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.
91Tool swap never rewrites history: earlier tool calls in Pi's history stay exactly as Pi holds them.
93### Lifecycle
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`.
103### Failure handling
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.
109## Measured result
111Recorded on 2026-09-17 by `mise run //extensions/klaus:bench`, ten paired samples against the fake endpoint, Agent SDK `0.3.261`.
113| Turn | Median |
114| --- | --- |
115| Cold turn | 1752 ms |
116| Reused turn | 32 ms |
117| Saved | 1720 ms |
119The saving exceeds the 500 ms gate, so the reuse path stays.
121## Phases
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.
143## Verification
145Unit and E2E tests live in the existing `extensions/klaus/__tests__` and `extensions/klaus/__e2e__` suites and run through existing Mise tasks.
147Required evidence:
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.
157Benchmark:
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.
162## Risks
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

145145 content_block: {
146146 type: "tool_use",
147147 id: "toolu_klaus_1",
148 name: "mcp__klaus__echo",
148 name: "echo",
149149 input: {},
150150 },
151151 },
313313 queryHandle = await startSdkQuery(request, "fake", {
314314 onReady: async () => undefined,
315315 onActivity: () => undefined,
316 onNotice: () => undefined,
316317 onContent: (event) => content.push(event),
317318 onToolBoundary: () =>
318319 finished.reject(new Error("Unexpected tool boundary.")),
370371 {
371372 onReady: async () => undefined,
372373 onActivity: () => undefined,
374 onNotice: () => undefined,
373375 onContent: () => undefined,
374376 onToolBoundary: () =>
375377 finished.reject(new Error("Unexpected tool boundary.")),
418420 queryHandle = await startSdkQuery(request, "fake", {
419421 onReady: async () => undefined,
420422 onActivity: () => undefined,
423 onNotice: () => undefined,
421424 onContent: (event) => {
422425 if (event.type === "tool-end") toolEnds.push(event);
423426 },
446449 const messages = messageRequests();
447450 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"');
449452 expect(JSON.stringify(messages[1]?.body)).toContain("hello");
450453 },
451454 10 * 60_000,
519522 const messages = messageRequests();
520523 expect(messages.length).toBeGreaterThanOrEqual(2);
521524 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"');
524527 },
525528 10 * 60_000,
526529 );
550553 {
551554 onReady: async () => undefined,
552555 onActivity: () => undefined,
556 onNotice: () => undefined,
553557 onContent: () => undefined,
554558 onToolBoundary: () =>
555559 firstFinished.reject(new Error("Unexpected tool boundary.")),
584588 {
585589 onReady: async () => undefined,
586590 onActivity: () => undefined,
591 onNotice: () => undefined,
587592 onContent: () => undefined,
588593 onToolBoundary: () =>
589594 secondFinished.reject(new Error("Unexpected tool boundary.")),
615620 {
616621 onReady: async () => undefined,
617622 onActivity: () => undefined,
623 onNotice: () => undefined,
618624 onContent: () => undefined,
619625 onToolBoundary: () =>
620626 branchFinished.reject(new Error("Unexpected tool boundary.")),

extensions/klaus/__e2e__/provider-scenarios.test.ts

Modified

+563 / −10 text lines

1import { mkdtemp, rm, writeFile } from "node:fs/promises";
12import {
23 createServer,
34 type IncomingMessage,
45 type ServerResponse,
56} from "node:http";
7import { tmpdir } from "node:os";
8import { join } from "node:path";
69import {
710 createTestSession,
811 type TestSession,
180183 ];
186/** The child reports its Claude session id inside the request metadata, which
187 * is the only public signal that two turns shared one process. */
188function childSessionId(captured: CapturedRequest | undefined): string {
189 const metadata = (captured?.body as { metadata?: { user_id?: string } })
190 ?.metadata;
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;
196}
183198async function within<T>(
184199 promise: Promise<T>,
185200 milliseconds: number,
215230interface DirectResult {
216231 content: KlausContentEvent[];
232 notices: string[];
217233 metadata: Record<string, string>;
218234 result?: {
219235 usage: KlausUsage;
230246 onHandle?: (handle: KlausQueryHandle) => Promise<void>,
231247): Promise<DirectResult> {
232248 const content: KlausContentEvent[] = [];
249 const notices: string[] = [];
233250 let metadata: Record<string, string> = {};
234251 const terminal = Promise.withResolvers<DirectResult>();
235252 let settled = false;
236 const finish = (value: Omit<DirectResult, "content" | "metadata">): void => {
253 const finish = (
254 value: Omit<DirectResult, "content" | "metadata" | "notices">,
255 ): void => {
237256 if (settled) return;
238257 settled = true;
239 terminal.resolve({ content, metadata, ...value });
258 terminal.resolve({ content, notices, metadata, ...value });
240259 };
241260 let handle: KlausQueryHandle;
242261 try {
245264 metadata = value;
246265 },
247266 onActivity: () => undefined,
267 onNotice: (message) => notices.push(message),
248268 onContent: (event) => content.push(event),
249269 onToolBoundary: () => undefined,
250270 onResult: (result) => finish({ result }),
253273 } catch (error) {
254274 return {
255275 content,
276 notices,
256277 metadata,
257278 error: error instanceof Error ? error : new Error(String(error)),
258279 };
284305 }
285306 await Promise.all(servers.splice(0).map((server) => server.close()));
286307 delete process.env.KLAUS_E2E_BASE_URL;
308 delete process.env.KLAUS_REUSE_LEASE_MS;
287309});
289311async function useServer(scenario: Scenario): Promise<FakeAnthropic> {
426448 content_block: {
427449 type: "tool_use",
428450 id: "toolu_bad",
429 name: "mcp__klaus__echo",
451 name: "echo",
430452 input: {},
431453 },
432454 },
472494 content_block: {
473495 type: "tool_use",
474496 id: "toolu_one",
475 name: "mcp__klaus__echo",
497 name: "echo",
476498 input: {},
477499 },
478500 },
482504 content_block: {
483505 type: "tool_use",
484506 id: "toolu_two",
485 name: "mcp__klaus__echo",
507 name: "echo",
486508 input: {},
487509 },
488510 },
537559 {
538560 onReady: async () => undefined,
539561 onActivity: () => undefined,
562 onNotice: () => undefined,
540563 onContent: (event) => content.push(event),
541564 onToolBoundary: () => boundary.resolve(),
542565 onResult: () => terminal.resolve(),
621644 content_block: {
622645 type: "tool_use",
623646 id,
624 name: "mcp__klaus__echo",
647 name: "echo",
625648 input: {},
626649 },
627650 },
735758 content_block: {
736759 type: "tool_use",
737760 id: "toolu_edit",
738 name: "mcp__klaus__echo",
761 name: "echo",
739762 input: {},
740763 },
741764 },
807830 { type: "text", text: "edited history used" },
808831 ]);
809832 const replay = JSON.stringify(server.messageRequests().at(-1)?.body);
810 expect(server.messageRequests()).toHaveLength(3);
833 /** Interrupting the abandoned query stops the child before it spends a
834 * request on the discarded turn, so only the first turn and the canonical
835 * replay reach the API. */
836 expect(server.messageRequests()).toHaveLength(2);
811837 expect(replay).toContain("edited");
812838 expect(replay).toContain('\\"role\\":\\"toolResult\\"');
813839 expect(replay).not.toContain('"tool_use_id":"toolu_edit"');
839865 content_block: {
840866 type: "tool_use",
841867 id: "toolu_sessionless",
842 name: "mcp__klaus__echo",
868 name: "echo",
843869 input: {},
844870 },
845871 },
13021328 const body = server.messageRequests()[0]?.body;
13031329 const serialized = JSON.stringify(body);
1304 expect(serialized).toContain("mcp__klaus__exact_tool");
1330 expect(serialized).toContain('"name":"exact_tool"');
13051331 expect(serialized).toContain("Exact tool description.");
13061332 expect(serialized).toContain('"minimum":1');
13071333 expect(serialized).toContain('"maximum":9');
13161342 expect(serialized).not.toContain(`"name":"${builtin}"`);
13181344 }, 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) =>
1348 sse(
1349 response,
1350 textFrames(index, index === 1 ? "first answer" : "second answer"),
1351 ),
1352 );
1353 const { t, model } = await providerSession();
1354 const sessionId = "reuse-scenario";
1355 const question = {
1356 role: "user" as const,
1357 content: "first question",
1358 timestamp: 1,
1359 };
1361 const first = await t.session.modelRuntime.completeSimple(
1362 model,
1363 { messages: [question] },
1364 { sessionId },
1365 );
1366 const second = await t.session.modelRuntime.completeSimple(
1367 model,
1368 {
1369 messages: [
1370 question,
1371 first,
1372 { role: "user", content: "second question", timestamp: 3 },
1373 ],
1374 },
1375 { sessionId },
1376 );
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);
1382 /** A reused child keeps its Claude session; a resumed or forked child
1383 * reports a new one. */
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"');
1388 /** The cold first turn carried one replay envelope; the reused turn adds a
1389 * plain user message instead of a second envelope. */
1390 expect(replay.split("<klaus-history-json>")).toHaveLength(2);
1391 }, 120_000);
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}`)),
1396 );
1397 const { t, model } = await providerSession();
1398 const sessionId = "reuse-edited";
1399 const question = {
1400 role: "user" as const,
1401 content: "original question",
1402 timestamp: 1,
1403 };
1405 const first = await t.session.modelRuntime.completeSimple(
1406 model,
1407 { messages: [question] },
1408 { sessionId },
1409 );
1410 const second = await t.session.modelRuntime.completeSimple(
1411 model,
1412 {
1413 messages: [
1414 { ...question, content: "edited question" },
1415 first,
1416 { role: "user", content: "follow up", timestamp: 3 },
1417 ],
1418 },
1419 { sessionId },
1420 );
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");
1429 }, 120_000);
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}`)),
1434 );
1435 const { t, model } = await providerSession();
1436 const sessionId = "reuse-system-prompt";
1437 const question = {
1438 role: "user" as const,
1439 content: "first question",
1440 timestamp: 1,
1441 };
1443 const first = await t.session.modelRuntime.completeSimple(
1444 model,
1445 { systemPrompt: "Prompt A.", messages: [question] },
1446 { sessionId },
1447 );
1448 await t.session.modelRuntime.completeSimple(
1449 model,
1450 {
1451 systemPrompt: "Prompt B.",
1452 messages: [
1453 question,
1454 first,
1455 { role: "user", content: "second question", timestamp: 3 },
1456 ],
1457 },
1458 { sessionId },
1459 );
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.");
1465 }, 120_000);
1467 it("parks a tool call from a reused child and settles it", async () => {
1468 const server = await useServer((_request, index, response) => {
1469 if (index === 2) {
1470 sse(response, [
1471 messageStart(index),
1472 {
1473 type: "content_block_start",
1474 index: 0,
1475 content_block: {
1476 type: "tool_use",
1477 id: "toolu_reused",
1478 name: "echo",
1479 input: {},
1480 },
1481 },
1482 {
1483 type: "content_block_delta",
1484 index: 0,
1485 delta: {
1486 type: "input_json_delta",
1487 partial_json: '{"value":"reused"}',
1488 },
1489 },
1490 { type: "content_block_stop", index: 0 },
1491 {
1492 type: "message_delta",
1493 delta: { stop_reason: "tool_use", stop_sequence: null },
1494 usage: { output_tokens: 4 },
1495 },
1496 { type: "message_stop" },
1497 ]);
1498 return;
1499 }
1500 sse(response, textFrames(index, `answer ${index}`));
1501 });
1502 const { t, model } = await providerSession();
1503 const sessionId = "reuse-tool";
1504 const tools = [
1505 {
1506 name: "echo",
1507 description: "Echo.",
1508 parameters: Type.Object({ value: Type.String() }),
1509 },
1510 ];
1511 const question = {
1512 role: "user" as const,
1513 content: "first question",
1514 timestamp: 1,
1515 };
1517 const first = await t.session.modelRuntime.completeSimple(
1518 model,
1519 { messages: [question], tools },
1520 { sessionId },
1521 );
1522 const follow = { role: "user" as const, content: "use echo", timestamp: 3 };
1523 const second = await t.session.modelRuntime.completeSimple(
1524 model,
1525 { messages: [question, first, follow], tools },
1526 { sessionId },
1527 );
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(
1531 model,
1532 {
1533 messages: [
1534 question,
1535 first,
1536 follow,
1537 second,
1538 {
1539 role: "toolResult",
1540 toolCallId: call.id,
1541 toolName: call.name,
1542 content: [{ type: "text", text: "echo output" }],
1543 isError: false,
1544 timestamp: 4,
1545 },
1546 ],
1547 tools,
1548 },
1549 { sessionId },
1550 );
1552 expect(third.errorMessage).toBeUndefined();
1553 const requests = server.messageRequests();
1554 expect(requests).toHaveLength(3);
1555 /** One child served the plain turn, the tool turn, and the continuation. */
1556 expect(new Set(requests.map((entry) => childSessionId(entry))).size).toBe(
1557 1,
1558 );
1559 expect(JSON.stringify(requests[2]?.body)).toContain("echo output");
1560 }, 120_000);
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}`)),
1565 );
1566 const { t, model } = await providerSession();
1567 const sessionId = "reuse-tool-swap";
1568 const question = {
1569 role: "user" as const,
1570 content: "first question",
1571 timestamp: 1,
1572 };
1573 const echo = {
1574 name: "echo",
1575 description: "Echo.",
1576 parameters: Type.Object({ value: Type.String() }),
1577 };
1578 const probe = {
1579 name: "probe",
1580 description: "Probe.",
1581 parameters: Type.Object({}),
1582 };
1584 const first = await t.session.modelRuntime.completeSimple(
1585 model,
1586 { messages: [question], tools: [echo] },
1587 { sessionId },
1588 );
1589 const second = await t.session.modelRuntime.completeSimple(
1590 model,
1591 {
1592 messages: [
1593 question,
1594 first,
1595 { role: "user", content: "second question", timestamp: 3 },
1596 ],
1597 tools: [probe],
1598 },
1599 { sessionId },
1600 );
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);
1610 }, 120_000);
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}`)),
1616 );
1617 const { t, model } = await providerSession();
1618 const sessionId = "reuse-lease";
1619 const question = {
1620 role: "user" as const,
1621 content: "first question",
1622 timestamp: 1,
1623 };
1625 const first = await t.session.modelRuntime.completeSimple(
1626 model,
1627 { messages: [question] },
1628 { sessionId },
1629 );
1630 await new Promise((resolve) => setTimeout(resolve, 1500));
1631 const second = await t.session.modelRuntime.completeSimple(
1632 model,
1633 {
1634 messages: [
1635 question,
1636 first,
1637 { role: "user", content: "second question", timestamp: 3 },
1638 ],
1639 },
1640 { sessionId },
1641 );
1643 expect(second.errorMessage).toBeUndefined();
1644 const requests = server.messageRequests();
1645 expect(requests).toHaveLength(2);
1646 /** The expired child is gone, so the next turn resumes into a new one. */
1647 expect(childSessionId(requests[0])).not.toBe(childSessionId(requests[1]));
1648 }, 120_000);
1650 it("surfaces child API retries as notices", async () => {
1651 const server = await useServer((_request, index, response) => {
1652 if (index <= 2) {
1653 response.writeHead(500, { "content-type": "application/json" });
1654 response.end(
1655 JSON.stringify({
1656 type: "error",
1657 error: { type: "api_error", message: "upstream exploded" },
1658 }),
1659 );
1660 return;
1661 }
1662 sse(response, textFrames(index, "recovered after retries"));
1663 });
1665 const result = await directQuery(request());
1667 expect(result.error).toBeUndefined();
1668 expect(result.content).toContainEqual({
1669 type: "text-end",
1670 index: 0,
1671 text: "recovered after retries",
1672 });
1673 expect(result.notices.join("\n")).toContain("retrying the Claude request");
1674 expect(server.messageRequests().length).toBeGreaterThanOrEqual(3);
1675 }, 120_000);
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")),
1680 );
1681 const directory = await mkdtemp(join(tmpdir(), "klaus-memory-"));
1682 try {
1683 await writeFile(
1684 join(directory, "CLAUDE.md"),
1685 "# Project memory\n\nKLAUS_AMBIENT_MEMORY_SENTINEL must never reach the API.\n",
1686 "utf8",
1687 );
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",
1694 );
1695 } finally {
1696 await rm(directory, {
1697 recursive: true,
1698 force: true,
1699 maxRetries: 20,
1700 retryDelay: 250,
1701 }).catch(() => undefined);
1702 }
1703 }, 60_000);
1705 it("forwards a tool result larger than the child MCP output cap", async () => {
1706 const server = await useServer((_request, index, response) => {
1707 if (index === 1) {
1708 sse(response, [
1709 messageStart(index),
1710 {
1711 type: "content_block_start",
1712 index: 0,
1713 content_block: {
1714 type: "tool_use",
1715 id: "toolu_bulk",
1716 name: "echo",
1717 input: {},
1718 },
1719 },
1720 {
1721 type: "content_block_delta",
1722 index: 0,
1723 delta: {
1724 type: "input_json_delta",
1725 partial_json: '{"value":"bulk"}',
1726 },
1727 },
1728 { type: "content_block_stop", index: 0 },
1729 {
1730 type: "message_delta",
1731 delta: { stop_reason: "tool_use", stop_sequence: null },
1732 usage: { output_tokens: 4 },
1733 },
1734 { type: "message_stop" },
1735 ]);
1736 return;
1737 }
1738 sse(response, textFrames(index, "bulk result accepted"));
1739 });
1740 /** Roughly 200 KB, about twice the default 25000-token MCP output cap. */
1741 const bulk = `${"klaus-bulk-line\n".repeat(13_000)}KLAUS_BULK_TAIL_SENTINEL`;
1743 const result = await directQuery(
1744 request({
1745 tools: [
1746 {
1747 name: "echo",
1748 description: "Echo.",
1749 inputSchema: { type: "object" },
1750 },
1751 ],
1752 }),
1753 async (handle) => {
1754 await handle.bridge.waitForPending(["toolu_bulk"]);
1755 expect(
1756 handle.bridge.settle({
1757 id: "toolu_bulk",
1758 content: [{ type: "text", text: bulk }],
1759 isError: false,
1760 }),
1761 ).toBe(true);
1762 },
1763 );
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);
1769 }, 60_000);
1771 it(
1772 "keeps a parked tool call alive past the auto-background window",
1773 async () => {
1774 const server = await useServer((_request, index, response) => {
1775 if (index === 1) {
1776 sse(response, [
1777 messageStart(index),
1778 {
1779 type: "content_block_start",
1780 index: 0,
1781 content_block: {
1782 type: "tool_use",
1783 id: "toolu_parked",
1784 name: "echo",
1785 input: {},
1786 },
1787 },
1788 {
1789 type: "content_block_delta",
1790 index: 0,
1791 delta: {
1792 type: "input_json_delta",
1793 partial_json: '{"value":"slow"}',
1794 },
1795 },
1796 { type: "content_block_stop", index: 0 },
1797 {
1798 type: "message_delta",
1799 delta: { stop_reason: "tool_use", stop_sequence: null },
1800 usage: { output_tokens: 4 },
1801 },
1802 { type: "message_stop" },
1803 ]);
1804 return;
1805 }
1806 sse(response, textFrames(index, "slow result accepted"));
1807 });
1809 const result = await directQuery(
1810 request({
1811 tools: [
1812 {
1813 name: "echo",
1814 description: "Echo.",
1815 inputSchema: { type: "object" },
1816 },
1817 ],
1818 }),
1819 async (handle) => {
1820 await handle.bridge.waitForPending(["toolu_parked"]);
1821 /** Longer than the 120000 ms default after which the child moves a
1822 * running MCP call to a background task. */
1823 await new Promise((resolve) => setTimeout(resolve, 150_000));
1824 expect(
1825 handle.bridge.settle({
1826 id: "toolu_parked",
1827 content: [{ type: "text", text: "KLAUS_PARKED_SENTINEL" }],
1828 isError: false,
1829 }),
1830 ).toBe(true);
1831 },
1832 );
1834 expect(result.error).toBeUndefined();
1835 expect(server.messageRequests()).toHaveLength(2);
1836 expect(JSON.stringify(server.messageRequests()[1]?.body)).toContain(
1837 "KLAUS_PARKED_SENTINEL",
1838 );
1839 },
1840 10 * 60_000,
1841 );
1843 it("keeps every retry of a broken stream streaming", async () => {
1844 const server = await useServer((_request, index, response) => {
1845 if (index === 1) {
1846 response.writeHead(200, {
1847 "content-type": "text/event-stream",
1848 "cache-control": "no-cache",
1849 connection: "keep-alive",
1850 });
1851 response.write(
1852 `event: message_start\ndata: ${JSON.stringify(messageStart(index))}\n\n`,
1853 );
1854 response.destroy();
1855 return;
1856 }
1857 sse(response, textFrames(index, "stream retried"));
1858 });
1860 const result = await directQuery(request());
1862 expect(result.error).toBeUndefined();
1863 expect(result.content).toContainEqual({
1864 type: "text-end",
1865 index: 0,
1866 text: "stream retried",
1867 });
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 });
1871 }, 60_000);
13191872});

extensions/klaus/__e2e__/reuse-benchmark.test.ts

Added
new file mode 100644

+182 / −0 text lines

1import { createServer, type ServerResponse } from "node:http";
2import {
3 createTestSession,
4 type TestSession,
5} from "@marcfargas/pi-test-harness";
6import { afterEach, describe, expect, it } from "vitest";
7import klaus from "../index";
8
9/** Phase 4 of the live-child-reuse specification: prove that reusing an idle
10 * child saves at least 500 ms median per turn. Opt in with KLAUS_BENCH=1,
11 * because it spends one child spawn per sample. */
12const enabled = process.env.KLAUS_BENCH === "1";
13const SAMPLES = Number(process.env.KLAUS_BENCH_SAMPLES ?? 10);
14const GATE_MS = 500;
16let session: TestSession | undefined;
17let closeServer: (() => Promise<void>) | undefined;
19function sse(response: ServerResponse, text: string, index: number): void {
20 const frames: unknown[] = [
21 {
22 type: "message_start",
23 message: {
24 id: `msg_bench_${index}`,
25 type: "message",
26 role: "assistant",
27 model: "claude-sonnet-5",
28 content: [],
29 stop_reason: null,
30 stop_sequence: null,
31 usage: {
32 input_tokens: 5,
33 output_tokens: 0,
34 cache_creation_input_tokens: 0,
35 cache_read_input_tokens: 0,
36 },
37 },
38 },
39 {
40 type: "content_block_start",
41 index: 0,
42 content_block: { type: "text", text: "" },
43 },
44 {
45 type: "content_block_delta",
46 index: 0,
47 delta: { type: "text_delta", text },
48 },
49 { type: "content_block_stop", index: 0 },
50 {
51 type: "message_delta",
52 delta: { stop_reason: "end_turn", stop_sequence: null },
53 usage: { output_tokens: 2 },
54 },
55 { type: "message_stop" },
56 ];
57 response.writeHead(200, {
58 "content-type": "text/event-stream",
59 "cache-control": "no-cache",
60 connection: "keep-alive",
61 });
62 for (const frame of frames) {
63 response.write(
64 `event: ${(frame as { type: string }).type}\ndata: ${JSON.stringify(frame)}\n\n`,
65 );
66 }
67 response.end();
68}
70async function startServer(): Promise<string> {
71 let index = 0;
72 const server = createServer(async (request, response) => {
73 for await (const _chunk of request) {
74 // Drain the request body before answering.
75 }
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 }));
79 return;
80 }
81 index += 1;
82 sse(response, `answer ${index}`, index);
83 });
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.");
88 }
89 closeServer = async () => {
90 server.closeAllConnections();
91 await new Promise<void>((resolve, reject) =>
92 server.close((error) => (error ? reject(error) : resolve())),
93 );
94 };
95 return `http://127.0.0.1:${address.port}`;
96}
98function 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);
104}
106afterEach(async () => {
107 if (session) {
108 await session.session.extensionRunner.emit({
109 type: "session_shutdown",
110 reason: "quit",
111 });
112 session.dispose();
113 session = undefined;
114 }
115 await closeServer?.();
116 closeServer = undefined;
117 delete process.env.KLAUS_E2E_BASE_URL;
118});
120describe.skipIf(!enabled)("Klaus idle child reuse benchmark", () => {
121 it(
122 "saves child spawn and initialize time on the second turn",
123 async () => {
124 process.env.KLAUS_E2E_BASE_URL = await startServer();
125 session = await createTestSession({
126 cwd: process.cwd(),
127 extensionFactories: [klaus],
128 });
129 const runtime = session.session.modelRuntime;
130 Object.defineProperty(runtime, "isUsingOAuth", {
131 configurable: true,
132 value: () => true,
133 });
134 Object.defineProperty(runtime, "getAuth", {
135 configurable: true,
136 value: async () => ({ auth: { apiKey: "fake" }, source: "OAuth" }),
137 });
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}`;
145 const question = {
146 role: "user" as const,
147 content: "first question",
148 timestamp: 1,
149 };
150 const coldStart = performance.now();
151 const first = await runtime.completeSimple(
152 model,
153 { messages: [question] },
154 { sessionId },
155 );
156 cold.push(performance.now() - coldStart);
157 const reusedStart = performance.now();
158 await runtime.completeSimple(
159 model,
160 {
161 messages: [
162 question,
163 first,
164 { role: "user", content: "second question", timestamp: 3 },
165 ],
166 },
167 { sessionId },
168 );
169 reused.push(performance.now() - reusedStart);
170 }
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`,
177 );
178 expect(saved).toBeGreaterThanOrEqual(GATE_MS);
179 },
180 30 * 60_000,
181 );
182});

extensions/klaus/__tests__/runtime.test.ts

Modified

+16 / −0 text lines

7070 CLAUDE_CONFIG_DIR: runtime.configDir,
7171 CLAUDE_CODE_OAUTH_TOKEN: "fake",
7272 CLAUDE_AGENT_SDK_CLIENT_APP: "klaus/1",
73 CLAUDE_AGENT_SDK_MCP_NO_PREFIX: "1",
7374 CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1",
7475 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,
7591 ANTHROPIC_BASE_URL: "http://127.0.0.1:43210",
7692 ANTHROPIC_CUSTOM_HEADERS: "X-Custom: present\nX-Empty: ",
7793 });

extensions/klaus/__tests__/tool-bridge.test.ts

Modified

+67 / −1 text lines

6464 expect(bridge.toolNames()).toEqual(["echo", "second tool"]);
6565 });
67 it("keeps the first identity for a repeated tool use id", async () => {
68 const { bridge, client } = await connectedBridge();
69 /** The `PreToolUse` hook reports every call, then `canUseTool` reports the
70 * same call again whenever permissions prompt. */
71 bridge.allow("echo", { value: "hook" }, "call-1");
72 bridge.allow("echo", { value: "hook" }, "call-1");
74 const result = client.callTool({
75 name: "echo",
76 arguments: { value: "hook", [TOOL_ID_FIELD]: "call-1" },
77 });
78 await bridge.waitForPending(["call-1"]);
79 expect(bridge.pendingIds()).toEqual(["call-1"]);
80 expect(
81 bridge.settle({
82 id: "call-1",
83 content: [{ type: "text", text: "hook" }],
84 isError: false,
85 }),
86 ).toBe(true);
88 expect(await result).toMatchObject({
89 isError: false,
90 content: [{ type: "text", text: "hook" }],
91 });
92 });
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({
99 name: "echo",
100 arguments: { value: "big", [TOOL_ID_FIELD]: "call-big" },
101 });
102 await bridge.waitForPending(["call-big"]);
103 bridge.settle({
104 id: "call-big",
105 content: [{ type: "text", text: oversized }],
106 isError: false,
107 });
109 const settled = (await result) as {
110 content: Array<{ type: string; text: string }>;
111 };
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");
116 });
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();
123 /** Claude persists any MCP result above this limit to a file Klaus deletes,
124 * so every tool must declare the ceiling instead of the 100000 default. */
125 for (const tool of listed.tools) {
126 expect(tool._meta).toEqual({
127 "anthropic/maxResultSizeChars": 500_000,
128 });
129 }
130 });
67132 it("counts tool listing, permission, call, and settlement as activity", async () => {
68133 const activity = vi.fn();
69134 const { bridge, client } = await connectedBridge([echo], activity);
218283 it("rejects a duplicate in-flight call ID without disturbing the original", async () => {
219284 const { bridge, client } = await connectedBridge();
220285 bridge.allow("echo", { value: "one" }, "duplicate");
221 bridge.allow("echo", { value: "two" }, "duplicate");
222286 const first = client.callTool({
223287 name: "echo",
224288 arguments: { value: "one", [TOOL_ID_FIELD]: "duplicate" },
225289 });
226290 await bridge.waitForPending(["duplicate"]);
291 /** Claude re-dispatches an identity after a transport gap. */
292 bridge.allow("echo", { value: "two" }, "duplicate");
227293 const duplicate = await client.callTool({
228294 name: "echo",
229295 arguments: { value: "two", [TOOL_ID_FIELD]: "duplicate" },

extensions/klaus/mise.toml

Modified

+6 / −0 text lines

1[tasks.bench]
2description = "Benchmark Klaus idle child reuse"
3depends = ["//:install"]
4env = { KLAUS_BENCH = "1" }
5run = "npx vitest run --config vitest.e2e.config.ts __e2e__/reuse-benchmark.test.ts"
6
17[tasks.e2e]
28description = "Run Klaus fake-auth process E2E"
39depends = ["//:install"]

extensions/klaus/src/agent-sdk.ts

Modified

+228 / −21 text lines

4141 };
44export interface KlausTurn {
45 prompt: string;
46 images?: KlausRequest["images"];
47}
4449export interface KlausQueryHandle {
4550 bridge: ToolBridge;
4651 close(reason: string): Promise<void>;
52 /** True while the child is alive, has no turn in flight, and can accept the
53 * next Pi turn through its open input stream. */
54 isIdle(): boolean;
55 /** Send the next Pi turn into the running child instead of paying another
56 * spawn and initialize round trip. */
57 send(turn: KlausTurn, callbacks: KlausQueryCallbacks): void;
58 /** Replace the tool list of an idle child so a Pi tool-list change does not
59 * cost a canonical replay. */
60 setTools(tools: KlausRequest["tools"]): Promise<void>;
61}
63interface PromptChannel {
64 stream: AsyncGenerator<SDKUserMessage>;
65 push(message: SDKUserMessage): void;
66 end(): void;
67}
69/** Streaming input mode keeps the child waiting for the next turn, so Klaus
70 * owns the message stream instead of yielding one prompt and ending it. */
71function createPromptChannel(first: SDKUserMessage): PromptChannel {
72 const queue: SDKUserMessage[] = [first];
73 let notify: (() => void) | undefined;
74 let ended = false;
75 async function* stream(): AsyncGenerator<SDKUserMessage> {
76 while (true) {
77 const next = queue.shift();
78 if (next) {
79 dbg?.("sdk.prompt.yield", {
80 promptLength: next.message.content.length,
81 });
82 yield next;
83 continue;
84 }
85 if (ended) return;
86 await new Promise<void>((resolve) => {
87 notify = resolve;
88 });
89 }
90 }
91 const wake = (): void => {
92 const pending = notify;
93 notify = undefined;
94 pending?.();
95 };
96 return {
97 stream: stream(),
98 push(message) {
99 queue.push(message);
100 wake();
101 },
102 end() {
103 ended = true;
104 wake();
105 },
106 };
49109function effort(level: KlausRequest["thinking"]): EffortLevel | undefined {
159219 throw new Error(`Unsupported Klaus image type ${value}.`);
162async function* sdkPrompt(
163 request: KlausRequest,
164): AsyncGenerator<SDKUserMessage> {
165 dbg?.("sdk.prompt.yield", {
166 promptLength: request.prompt.length,
167 imageCount: request.images?.length ?? 0,
222function userMessage(turn: KlausTurn): SDKUserMessage {
223 dbg?.("sdk.prompt.build", {
224 promptLength: turn.prompt.length,
225 imageCount: turn.images?.length ?? 0,
168226 });
169 yield {
227 return {
170228 type: "user",
171229 message: {
172230 role: "user",
173231 content: [
174 { type: "text", text: request.prompt },
175 ...(request.images ?? []).map((image) => ({
232 { type: "text", text: turn.prompt },
233 ...(turn.images ?? []).map((image) => ({
176234 type: "image" as const,
177235 source: {
178236 type: "base64" as const,
222280 clientApp: runtime.env.CLAUDE_AGENT_SDK_CLIENT_APP,
223281 betas: runtime.betas,
224282 });
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;
226286 dbg?.("sdk.bridge.ready", { toolNames: bridge.toolNames() });
227287 const abortController = new AbortController();
228288 const blocks = new Map<number, BlockState>();
289 const channel = createPromptChannel(userMessage(request));
229290 let queryHandle: Query | undefined;
230291 let pumpPromise: Promise<void> | undefined;
231292 let cleanupPromise: Promise<void> | undefined;
232293 let closePromise: Promise<void> | undefined;
233294 let closed = false;
295 let turnActive = true;
296 let reusable = false;
234297 let stderr = "";
235298 const messageState: MessageState = {
236299 usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
237300 reportedUsage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
238301 };
302 /** Every turn reports its own usage and content indices, so no per-turn
303 * accounting may leak into the next turn on the same child. */
304 const startTurn = (): void => {
305 blocks.clear();
306 messageState.usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
307 messageState.reportedUsage = {
308 input: 0,
309 output: 0,
310 cacheRead: 0,
311 cacheWrite: 0,
312 };
313 messageState.deferredOutputLimit = undefined;
314 messageState.responseId = undefined;
315 messageState.responseModel = undefined;
316 turnActive = true;
317 reusable = false;
318 };
320 /** Claude only serves control requests such as `interrupt()` in streaming
321 * input mode, so every query uses the generator prompt. */
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)),
329 ]);
330 dbg?.("sdk.interrupt.end", { reason });
331 };
240333 const cleanup = (reason: string): Promise<void> => {
241334 dbg?.("sdk.cleanup.request", { reason, existing: Boolean(cleanupPromise) });
256349 closePromise ??= (async () => {
257350 if (!closed) {
258351 dbg?.("sdk.close.abort", { reason });
352 await gracefulStop(reason);
259353 closed = true;
354 reusable = false;
355 channel.end();
260356 abortController.abort(reason);
261357 queryHandle?.close();
262358 }
275371 clientApp: runtime.env.CLAUDE_AGENT_SDK_CLIENT_APP,
276372 });
277373 queryHandle = query({
278 prompt:
279 request.images && request.images.length > 0
280 ? sdkPrompt(request)
281 : request.prompt,
374 prompt: channel.stream,
282375 options: {
283376 abortController,
284377 cwd: request.cwd,
293386 includePartialMessages: true,
294387 persistSession: true,
295388 sessionStore: request.sessionStore,
389 /** Klaus deletes the child config directory when the query ends, so
390 * the mirrored transcript is the only durable copy and must not sit
391 * in a batch when a turn is interrupted. */
392 sessionStoreFlush: "eager",
296393 resume: request.resume,
297394 resumeSessionAt: request.resumeAt,
298395 forkSession: request.forkSession,
317414 dbg?.("sdk.stderr", { text });
318415 stderr = `${stderr}${data}`.slice(-4096);
319416 },
417 /** `canUseTool` runs only when a tool call would prompt, so the tool
418 * use id is captured here as well, where Claude reports every call
419 * regardless of how permissions resolve. */
420 hooks: {
421 PreToolUse: [
422 {
423 hooks: [
424 async (input, toolUseId) => {
425 if (input.hook_event_name !== "PreToolUse" || !toolUseId) {
426 return { continue: true };
427 }
428 dbg?.("sdk.hook.preToolUse", {
429 name: input.tool_name,
430 toolUseId,
431 });
432 bridge.allow(
433 input.tool_name,
434 (input.tool_input ?? {}) as Record<string, unknown>,
435 toolUseId,
436 );
437 return { continue: true };
438 },
439 ],
440 },
441 ],
442 },
320443 canUseTool: async (name, input, options) => {
321444 dbg?.("sdk.canUseTool", {
322445 name,
351474 eventType:
352475 message.type === "stream_event" ? message.event.type : undefined,
353476 });
354 callbacks.onActivity();
477 active.onActivity();
355478 if (
356479 (message.type === "assistant" || message.type === "user") &&
357480 message.uuid
361484 const terminal = await handleMessage(
362485 message,
363486 blocks,
364 callbacks,
487 active,
365488 messageState,
366489 () => {
367490 if (closed) return;
370493 queryHandle?.close();
371494 },
372495 );
496 if (message.type === "result") {
497 turnActive = false;
498 reusable =
499 !closed && message.subtype === "success" && !message.is_error;
500 }
373501 if (terminal) {
502 turnActive = false;
503 reusable = false;
374504 closed = true;
375505 abortController.abort("Klaus stopped max-token recovery.");
376506 queryHandle?.close();
382512 const detail = redact(stderr.trim(), oauthToken);
383513 const message = redact(errorText(error), oauthToken);
384514 dbg?.("sdk.pump.error", { message, detail });
385 callbacks.onError(
386 new Error(detail ? `${message}: ${detail}` : message),
387 );
515 active.onError(new Error(detail ? `${message}: ${detail}` : message));
388516 }
389517 } finally {
390518 dbg?.("sdk.pump.finally", { closed });
519 turnActive = false;
520 reusable = false;
391521 if (!closed) closed = true;
392522 await cleanup("Klaus query finished.");
393523 if (messageState.deferredOutputLimit) {
394 callbacks.onResult(messageState.deferredOutputLimit);
524 active.onResult(messageState.deferredOutputLimit);
395525 }
396526 }
397527 };
398528 pumpPromise = pump();
399529 dbg?.("sdk.handle.ready");
400 return { bridge, close };
530 return {
531 get bridge() {
532 return bridge;
533 },
534 close,
535 isIdle: () => reusable && !closed && !turnActive,
536 /** Claude caches a server's tool list for as long as that server stays
537 * registered, so a swap publishes a fresh bridge under a fresh name and
538 * drops the previous one. */
539 setTools: async (tools) => {
540 if (!reusable || closed || turnActive) {
541 throw new Error("Klaus query cannot change tools right now.");
542 }
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 },
550 });
551 bridge = next;
552 await previous.close("Klaus replaced the tool bridge.");
553 },
554 send: (turn, turnCallbacks) => {
555 if (!reusable || closed || turnActive) {
556 throw new Error("Klaus query cannot accept another turn.");
557 }
558 dbg?.("sdk.send", {
559 promptLength: turn.prompt.length,
560 imageCount: turn.images?.length ?? 0,
561 });
562 for (const image of turn.images ?? []) imageMediaType(image.mimeType);
563 active = turnCallbacks;
564 startTurn();
565 channel.push(userMessage(turn));
566 },
567 };
403570async function handleMessage(
438605 );
439606 return false;
440607 }
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,
613 });
614 if (message.attempt > 1) {
615 callbacks.onNotice(
616 `Klaus is retrying the Claude request (attempt ${message.attempt} of ${message.max_retries}).`,
617 );
618 }
619 return false;
620 }
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,
626 });
627 callbacks.onNotice(
628 `Claude denied the ${message.tool_name} tool call without asking Klaus: ${message.message}`,
629 );
630 return false;
631 }
632 if (message.type === "system" && message.subtype === "worker_shutting_down") {
633 dbg?.("sdk.message.workerShuttingDown", { reason: message.reason });
634 callbacks.onError(
635 new Error(`Klaus child shut down before finishing: ${message.reason}`),
636 );
637 return false;
638 }
639 if (
640 message.type === "system" &&
641 message.subtype === "informational" &&
642 message.level === "warning"
643 ) {
644 dbg?.("sdk.message.informational", { content: message.content });
645 callbacks.onNotice(`Klaus child warning: ${message.content}`);
646 return false;
647 }
441648 if (
442649 message.type === "rate_limit_event" &&
443650 message.rate_limit_info.status === "rejected"

extensions/klaus/src/coordinator.ts

Modified

+220 / −8 text lines

5151 timer?: ReturnType<typeof setTimeout>;
5252 timeoutMs?: number;
5353 idleLease?: ReturnType<typeof setTimeout>;
54 /** Set while this child is idle between turns and may take the next one. */
55 reuseLease?: ReturnType<typeof setTimeout>;
56 sdkSessionId?: string;
57 position?: string;
58 messageCount?: number;
59 /** Lineage of the turns this child already holds, computed without tools so
60 * a tool-list change can be answered with a swap instead of a replay. */
61 lineageFingerprint?: string;
5462 abort?: () => void;
5563 signal?: AbortSignal;
5664 secondary: boolean;
8694 dir: string;
97/** How long a finished child stays alive waiting for the next turn. Tests may
98 * shorten it, because proving expiry must not cost two minutes per run. */
99function reuseLeaseMs(): number {
100 const override = process.env.VITEST
101 ? Number(process.env.KLAUS_REUSE_LEASE_MS)
102 : Number.NaN;
103 return Number.isSafeInteger(override) && override > 0 ? override : 2 * 60_000;
104}
89106type ResolveOAuth = (modelId: string) => Promise<string>;
90107type CurrentCwd = () => string;
91108type CurrentSession = () => SessionScope | undefined;
550567 return;
551568 }
552569 }
553 await this.start(sink, model, context, options, tools);
570 await this.start(
571 sink,
572 model,
573 context,
574 options,
575 tools,
576 false,
577 batch.results.length === 0
578 ? this.findReusable(options.sessionId)
579 : undefined,
580 );
554581 } catch (error) {
555582 dbg?.("coordinator.invoke.error", {
556583 error: error instanceof Error ? error.message : String(error),
559586 }
560587 }
589 /** `reusable` is an idle child from this session's previous turn. It is used
590 * only when this turn resolves to exactly the delta the child already
591 * expects, and it is closed on any other outcome. */
562592 private async start(
563593 sink: PiSink,
564594 model: Model<Api>,
566596 options: SimpleStreamOptions,
567597 tools: KlausRequest["tools"],
568598 forceCold = false,
599 reusable?: ActiveQuery,
569600 ): Promise<void> {
570601 dbg?.("coordinator.start.begin", {
571602 modelId: model.id,
630661 found: Boolean(completed),
631662 messageCount: completed?.messageCount,
632663 });
664 const offered =
665 reusable && !forceCold && reusable.handle?.isIdle() === true
666 ? this.reuseFit(reusable, context, model, options, tools, identity)
667 : undefined;
668 dbg?.("coordinator.start.reuseFit", {
669 offered: Boolean(reusable),
670 fit: offered?.fit,
671 });
672 const reuse = offered ? reusable : undefined;
673 if (reusable && !reuse) {
674 await this.closeState(
675 reusable,
676 "Klaus cannot reuse the idle child for this turn.",
677 );
678 }
679 const reuseBoundary = reuse?.messageCount;
633680 const deltaContext: Context = {
634681 systemPrompt: context.systemPrompt,
635 messages: completed
636 ? context.messages.slice(completed.messageCount)
637 : context.messages,
682 messages:
683 reuseBoundary !== undefined
684 ? context.messages.slice(reuseBoundary)
685 : completed
686 ? context.messages.slice(completed.messageCount)
687 : context.messages,
638688 tools: context.tools,
639689 };
640690 const linearResume =
641 completed !== undefined &&
691 (reuse !== undefined || completed !== undefined) &&
642692 deltaContext.messages.length === 1 &&
643693 isTextUser(deltaContext.messages[0]);
644 const canResume = completed !== undefined;
694 const canResume = reuse === undefined && completed !== undefined;
645695 dbg?.("coordinator.start.resumePlan", {
646696 linearResume,
647697 canResume,
698 reused: Boolean(reuse),
648699 deltaMessageCount: deltaContext.messages.length,
649700 });
650701 const staging = new StagingSessionStore(completed?.store ?? store);
730781 persisted: scope?.persisted,
731782 dir: scope?.dir,
732783 });
733 const state: ActiveQuery = {
784 if (
785 reuse &&
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))
792 ) {
793 dbg?.("coordinator.start.reuseRejectedByHook");
794 await this.closeState(
795 reuse,
796 "Klaus onPayload changed a reused turn; replaying canonically.",
797 );
798 await this.start(sink, model, context, options, tools, true);
799 return;
800 }
801 const state: ActiveQuery = reuse ?? {
734802 id: Symbol("klaus-query"),
735803 sessionId: options.sessionId,
736804 sink,
753821 store: completed?.store ?? store,
754822 staging,
755823 };
756 this.addState(state);
824 if (reuse) {
825 if (state.reuseLease) clearTimeout(state.reuseLease);
826 state.reuseLease = undefined;
827 state.sink = sink;
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;
835 } else {
836 this.addState(state);
837 }
757838 dbg?.("coordinator.start.stateAdded", {
758839 sessionId: state.sessionId,
759840 secondary: state.secondary,
760841 committable: state.committable,
842 reused: Boolean(reuse),
761843 });
762844 this.armTimeout(state, transformed.timeoutMs);
763845 this.replaceAbort(state, options.signal);
776858 dbg?.("coordinator.callback.activity", { closed: state.closed });
777859 this.touchState(state, state.timeoutMs);
778860 },
861 onNotice: (message) => {
862 dbg?.("coordinator.callback.notice", { message });
863 this.warn(message);
864 },
779865 onContent: (event) => {
780866 dbg?.("coordinator.callback.content", {
781867 type: event.type,
867953 store: state.store,
868954 };
869955 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(
960 {
961 systemPrompt: state.context.systemPrompt,
962 messages: [...state.context.messages, resultSink.output],
963 },
964 `${state.modelId}\0${state.cwd}`,
965 );
870966 if (this.checkpointRoot(state.sessionId)) {
871967 this.pendingCheckpoints.set(state.sessionId, completed);
872968 }
885981 result.stopReason,
886982 );
887983 }
984 if (this.keepForReuse(state)) return;
888985 await this.closeState(state, "Klaus query completed.");
889986 })().catch((error) => {
890987 resultSink?.error(error);
9241021 void this.closeState(state, error.message);
9251022 },
9261023 };
1024 if (reuse) {
1025 try {
1026 if (offered?.fit === "swap") {
1027 dbg?.("coordinator.reuse.swapTools", {
1028 toolNames: tools.map((tool) => tool.name),
1029 });
1030 await state.handle?.setTools(tools);
1031 }
1032 if (state.metadata) {
1033 await options.onResponse?.(
1034 { status: 200, headers: state.metadata },
1035 model,
1036 );
1037 }
1038 if (state.closed) return;
1039 dbg?.("coordinator.reuse.send", {
1040 sessionId: state.sessionId,
1041 promptLength: transformed.prompt.length,
1042 });
1043 state.handle?.send(
1044 { prompt: transformed.prompt, images: transformed.images },
1045 callbacks,
1046 );
1047 } catch (error) {
1048 dbg?.("coordinator.reuse.error", {
1049 error: error instanceof Error ? error.message : String(error),
1050 });
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);
1054 }
1055 return;
1056 }
9271057 try {
9281058 dbg?.("coordinator.oauth.resolve.start", { modelId: model.id });
9291059 const oauth = await this.resolveOAuth(model.id);
1084 /** Decides whether an idle child can take this turn, and whether it needs a
1085 * tool swap first. Lineage is compared without tools so a Pi tool-list change
1086 * alone does not force a canonical replay. */
1087 private reuseFit(
1088 state: ActiveQuery,
1089 context: Context,
1090 model: Model<Api>,
1091 options: SimpleStreamOptions,
1092 tools: KlausRequest["tools"],
1093 identity: string,
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;
1099 if (
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)
1108 ) {
1109 return undefined;
1110 }
1111 const lineage = contextFingerprint(
1112 {
1113 systemPrompt: context.systemPrompt,
1114 messages: context.messages.slice(0, boundary),
1115 },
1116 identity,
1117 );
1118 if (state.lineageFingerprint !== lineage) return undefined;
1119 return {
1120 fit:
1121 JSON.stringify(state.tools) === JSON.stringify(tools)
1122 ? "reuse"
1123 : "swap",
1124 };
1125 }
1127 /** A finished child keeps running for a short window so the next turn in the
1128 * same session skips the child spawn and initialize round trip. */
1129 private keepForReuse(state: ActiveQuery): boolean {
1130 const reusable =
1131 !state.closed &&
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,
1139 reusable,
1140 });
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."),
1148 reuseLeaseMs(),
1149 );
1150 return true;
1151 }
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,
1157 );
1158 dbg?.("coordinator.findReusable", { sessionId, found: Boolean(found) });
1159 return found;
1160 }
9541162 private findContinuation(
9551163 sessionId: string | undefined,
9561164 results: PiToolResult[],
9631171 return [...(this.bySession.get(sessionId) ?? [])].find(
9641172 (state) =>
9651173 !state.closed &&
1174 /** An idle child between turns holds no parked call, so its tool ids
1175 * from the finished turn must never capture a continuation. */
1176 state.reuseLease === undefined &&
9661177 results.every((result) => state.toolCallIds.has(result.id)),
9671178 );
10881299 state.closePromise = (async () => {
10891300 if (state.timer) clearTimeout(state.timer);
10901301 if (state.idleLease) clearTimeout(state.idleLease);
1302 if (state.reuseLease) clearTimeout(state.reuseLease);
10911303 if (state.signal && state.abort) {
10921304 state.signal.removeEventListener("abort", state.abort);

extensions/klaus/src/protocol.ts

Modified

+3 / −0 text lines

8585export interface KlausQueryCallbacks {
8686 onReady(metadata: Record<string, string>): Promise<void>;
8787 onActivity(): void;
88 /** Child-side conditions the human should see even though the turn continues,
89 * such as API retries and permission denials Claude decided on its own. */
90 onNotice(message: string): void;
8891 onContent(event: KlausContentEvent): void;
8992 onToolBoundary(result: {
9093 usage: KlausUsage;

extensions/klaus/src/runtime/index.ts

Modified

+35 / −0 text lines

111111 env.CLAUDE_CONFIG_DIR = configDir;
112112 env.CLAUDE_CODE_OAUTH_TOKEN = oauthToken;
113113 env.CLAUDE_AGENT_SDK_CLIENT_APP = "klaus/1";
114 /** Pi owns every tool Klaus exposes, so the child presents them under their
115 * Pi names instead of the `mcp__klaus__` MCP namespace. The bridge still
116 * strips that prefix, so resumed sessions and runtimes without this flag
117 * keep working. */
118 env.CLAUDE_AGENT_SDK_MCP_NO_PREFIX = "1";
114119 env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC = "1";
115120 env.CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY = "0";
121 /** Pi sends its whole tool list on every request, so the child must define
122 * every tool upfront instead of deferring them behind MCP tool search. */
123 env.ENABLE_TOOL_SEARCH = "false";
124 /** A Klaus tool call stays parked until Pi executes it, which includes human
125 * approval and has no upper bound, so neither automatic backgrounding nor the
126 * idle watchdog may abandon it. */
127 env.CLAUDE_CODE_MCP_AUTO_BACKGROUND_MS = "0";
128 env.CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT = "0";
129 /** Klaus only forwards `stream_event` content, so a silent non-streaming
130 * retry would hand Pi an empty but successful turn. */
131 env.CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK = "1";
132 /** Text results are bounded by the per-tool `anthropic/maxResultSizeChars`
133 * the bridge declares; this raises the remaining token cap that still governs
134 * image content in Pi tool results. */
135 env.MAX_MCP_OUTPUT_TOKENS = "1000000";
136 /** Pi owns the system prompt and the tool list, so every ambient Claude Code
137 * context source stays off: memory files, bundled and managed skills,
138 * built-in subagents, workflows, cron, background tasks, and checkpoints. */
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";
148 /** Child temp files land inside the per-query config directory, so the
149 * existing cleanup removes them. */
150 env.CLAUDE_CODE_TMPDIR = configDir;
116151 if (maxTokens !== undefined) {
117152 if (!Number.isSafeInteger(maxTokens) || maxTokens < 1) {
118153 throw new Error(

extensions/klaus/src/tool-bridge.ts

Modified

+65 / −9 text lines

3030export const TOOL_ID_FIELD = "__klausToolUseID";
32/** Claude caps MCP tool results at 100000 characters by default and replaces
33 * anything larger with a `<persisted-output>` pointer into its own temp
34 * directory, which Klaus deletes when the query ends. Declaring the per-tool
35 * limit raises that threshold to Claude's ceiling so Pi results reach the model
36 * intact; Pi already truncates its own tool output. */
37const MAX_RESULT_SIZE_CHARS = 500_000;
39const TRUNCATION_NOTE =
40 "\n[Klaus truncated this tool result at Claude's 500000-character result limit.]";
42/** Beyond the declared ceiling Claude persists the result to a file inside the
43 * per-query config directory and shows the model a pointer, and Klaus deletes
44 * that directory when the query ends. Truncating here keeps the loss visible to
45 * the model instead of handing it a dead path. */
46function 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 });
55 continue;
56 }
57 if (truncated) continue;
58 if (item.text.length <= remaining) {
59 remaining -= item.text.length;
60 bounded.push({ ...item });
61 continue;
62 }
63 const kept = item.text.slice(
64 0,
65 Math.max(0, remaining - TRUNCATION_NOTE.length),
66 );
67 dbg?.("bridge.settle.truncated", {
68 originalLength: item.text.length,
69 keptLength: kept.length,
70 });
71 bounded.push({ type: "text", text: `${kept}${TRUNCATION_NOTE}` });
72 truncated = true;
73 remaining = 0;
74 }
75 return bounded;
76}
3278const originalName = (name: string): string =>
3379 name.startsWith("mcp__klaus__") ? name.slice("mcp__klaus__".length) : name;
75121 name: tool.name,
76122 description: tool.description,
77123 inputSchema: tool.inputSchema,
124 _meta: {
125 "anthropic/maxResultSizeChars": MAX_RESULT_SIZE_CHARS,
126 },
78127 })),
79128 };
80129 });
124173 );
125174 }
176 /** Claude reaches this through both the `PreToolUse` hook and `canUseTool`,
177 * and only the hook is guaranteed, so the first identity for a tool use id
178 * wins and later duplicates are ignored. */
127179 allow(name: string, input: Record<string, unknown>, id: string): void {
180 const duplicate = this.permissions.some((call) => call.id === id);
128181 dbg?.("bridge.allow", {
129182 name,
130183 id,
131184 inputKeys: Object.keys(input),
185 duplicate,
132186 });
133187 this.onActivity();
188 if (duplicate) return;
134189 this.permissions.push({ id, name: originalName(name), input });
135190 }
140195 return names;
141196 }
198 /** Pi owns the active tool list, so a live child adopts the new list instead
199 * of forcing a canonical replay. */
200 replaceTools(tools: KlausTool[]): void {
201 dbg?.("bridge.replaceTools", {
202 toolNames: tools.map((tool) => tool.name),
203 });
204 this.tools = new Map(tools.map((tool) => [tool.name, tool]));
205 }
143207 hasSchemaChange(tools: KlausTool[]): boolean {
144208 const changed =
145209 JSON.stringify([...this.tools.values()]) !== JSON.stringify(tools);
184248 this.pending.delete(result.id);
185249 this.settled.add(result.id);
186250 pending.resolve({
187 content: result.content.map((item) =>
188 item.type === "text"
189 ? { type: "text" as const, text: item.text }
190 : {
191 type: "image" as const,
192 data: item.data,
193 mimeType: item.mimeType,
194 },
195 ),
251 content: boundedContent(result.content),
196252 isError: result.isError,
197253 });
198254 dbg?.("bridge.settle.end", { id: result.id });