repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

fix(klaus): improve child agent diagnostics

e6c8fe2fa14dcbf7b9675769c39eb24f32fd40b9

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (7)

extensions/klaus/README.md

Modified
37 37 In the TUI the whole visit runs in one animated Bureau of Tokens counter: it opens the sign-in page in the browser, shows a live link (`c` copies it) and code field, exchanges the pasted code, copies the token to the clipboard, and stamps `APPROVED` or `DENIED` in place (`r` retries, Esc cancels).
38 38 The counter is sized to the terminal in three width tiers and prints the token when no clipboard tool is available.
39 39 Outside the TUI it falls back to a plain input dialog and notifications.
40 +- Global `~/.pi/agent/settings.json` setting:
41 + `"klaus": { "debugLog": true }` writes private diagnostic NDJSON to `${XDG_CACHE_HOME:-~/.cache}/pi-ext/klaus/debug.ndjson` after Pi restarts.
42 + Traces include UUIDs, session IDs, checkpoint and mirror timing, but exclude conversation bodies and token values.
43 + Disable the setting and restart Pi to stop logging; remove the file manually when no longer needed.
40 44 - Environment variable:
41 - `KLAUS_DEBUG_LOG` writes structured NDJSON trace records to the specified file when set before Klaus loads.
45 + `KLAUS_DEBUG_LOG` overrides the configured trace destination when set before Klaus loads.
42 46 - Tools and hooks:
43 47 none registered by the extension.

extensions/klaus/__tests__/coordinator.test.ts

Modified
21 21 new Error("Klaus cache corruption: invalid transcript JSON."),
23 23 ).toBe(true);
24 + expect(
25 + isReplayableResumeError(
26 + new Error(
27 + "No message found with message.uuid of: 0854833d-c5fc-4acb-93c7-6c93c1d2e4c1",
28 + ),
29 + ),
30 + ).toBe(true);
26 33 it.each([
27 34 "rate limit: Claude subscription limit rejected the request.",
28 35 "authentication failed",
36 + "Failed to authenticate. API Error: 401 OAuth access token has been revoked.",
29 37 "network connection reset",
30 38 "Klaus session mirror failed: write failed",
31 39 ])("does not replay a full context after %s", (message) => {

extensions/klaus/__tests__/debug.test.ts

Modified
1 -import { mkdtemp, readFile, rm } from "node:fs/promises";
1 +import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
2 2 import { tmpdir } from "node:os";
3 3 import { join } from "node:path";
4 4 import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
6 -let root: string | undefined;
6 +let root = "";
7 7 const originalLog = process.env.KLAUS_DEBUG_LOG;
8 +const originalAgentDir = process.env.PI_CODING_AGENT_DIR;
9 +const originalCacheHome = process.env.XDG_CACHE_HOME;
9 -beforeEach(() => vi.resetModules());
11 +beforeEach(async () => {
12 + vi.resetModules();
13 + root = await mkdtemp(join(tmpdir(), "klaus-debug-test-"));
14 + process.env.PI_CODING_AGENT_DIR = root;
15 + process.env.XDG_CACHE_HOME = root;
16 + delete process.env.KLAUS_DEBUG_LOG;
17 +});
11 19 afterEach(async () => {
12 20 if (originalLog === undefined) delete process.env.KLAUS_DEBUG_LOG;
13 21 else process.env.KLAUS_DEBUG_LOG = originalLog;
22 + if (originalAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
23 + else process.env.PI_CODING_AGENT_DIR = originalAgentDir;
24 + if (originalCacheHome === undefined) delete process.env.XDG_CACHE_HOME;
25 + else process.env.XDG_CACHE_HOME = originalCacheHome;
14 26 if (root) await rm(root, { recursive: true, force: true });
15 - root = undefined;
27 + root = "";
18 30 describe("dbg", () => {
19 31 it("writes one structured trace record when enabled at module load", async () => {
20 - root = await mkdtemp(join(tmpdir(), "klaus-debug-test-"));
21 32 const path = join(root, "trace.ndjson");
22 33 process.env.KLAUS_DEBUG_LOG = path;
23 34 const { dbg } = await import("../src/debug.js");
36 47 it("does not write debug failures into Pi's terminal", async () => {
37 - root = await mkdtemp(join(tmpdir(), "klaus-debug-test-"));
38 48 process.env.KLAUS_DEBUG_LOG = root;
39 49 const stderr = vi.spyOn(process.stderr, "write");
40 50 const { dbg } = await import("../src/debug.js");
48 58 it("skips argument evaluation when disabled at module load", async () => {
49 - delete process.env.KLAUS_DEBUG_LOG;
50 59 const { dbg } = await import("../src/debug.js");
51 60 let evaluated = false;
61 70 expect(dbg).toBeUndefined();
62 71 expect(evaluated).toBe(false);
74 + it("writes to the private user cache when global settings enable logging", async () => {
75 + await writeFile(
76 + join(root, "settings.json"),
77 + JSON.stringify({ klaus: { debugLog: true } }),
78 + );
79 + const { dbg } = await import("../src/debug.js");
80 + dbg?.("test.configured", {
81 + uuid: "message-1",
82 + message: "No message found with message.uuid of: secret",
83 + });
85 + const path = join(root, "pi-ext", "klaus", "debug.ndjson");
86 + const record = JSON.parse((await readFile(path, "utf8")).trim());
87 + expect(record).toMatchObject({
88 + event: "test.configured",
89 + uuid: "message-1",
90 + message: { kind: "missing-resume-uuid" },
91 + });
92 + expect(JSON.stringify(record)).not.toContain("secret");
93 + expect((await stat(path)).mode & 0o777).toBe(0o600);
94 + expect((await stat(join(root, "pi-ext", "klaus"))).mode & 0o777).toBe(
95 + 0o700,
96 + );
97 + });

extensions/klaus/src/agent-sdk.ts

Modified
493 493 subtype: "subtype" in message ? message.subtype : undefined,
494 494 eventType:
495 495 message.type === "stream_event" ? message.event.type : undefined,
496 + uuid: "uuid" in message ? message.uuid : undefined,
497 + sessionId: "session_id" in message ? message.session_id : undefined,
497 499 active.onActivity();
500 502 message.uuid
502 504 messageState.latestPosition = message.uuid;
505 + dbg?.("sdk.position.candidate", {
506 + type: message.type,
507 + uuid: message.uuid,
508 + parentToolUseId: message.parent_tool_use_id,
509 + });
504 511 const terminal = await handleMessage(
505 512 message,
691 698 subtype: message.subtype,
692 699 isError: message.is_error,
693 700 sessionId: message.session_id,
701 + resultUuid: message.uuid,
702 + latestPosition: state.latestPosition,
695 704 if (message.subtype !== "success" || message.is_error) {
696 705 const detail =

extensions/klaus/src/cache.ts

Modified
223 223 async append(key: StoreKey, entries: OpaqueEntry[]): Promise<void> {
224 224 dbg?.("cache.staging.append", {
225 + projectKey: key.projectKey,
225 226 sessionId: key.sessionId,
227 + subpath: key.subpath,
226 228 entryCount: entries.length,
229 + entries: entries
230 + .filter((entry) => entry.type === "user" || entry.type === "assistant")
231 + .map((entry) => ({
232 + type: entry.type,
233 + uuid: entry.uuid,
234 + parentUuid: entry.parentUuid,
235 + isSidechain: entry.isSidechain,
236 + })),
228 238 this.batches.push({
229 239 key: structuredClone(key),
254 264 dbg?.("cache.staging.commit.start", { batchCount: this.batches.length });
255 265 for (const batch of this.batches) {
256 266 await this.target.append(batch.key, batch.entries);
267 + dbg?.("cache.staging.commit.batch", {
268 + projectKey: batch.key.projectKey,
269 + sessionId: batch.key.sessionId,
270 + subpath: batch.key.subpath,
271 + entryCount: batch.entries.length,
272 + });
258 274 this.batches.length = 0;
259 275 dbg?.("cache.staging.commit.end");

extensions/klaus/src/coordinator.ts

Modified
445 445 return;
447 447 checkpoint.piLeafId = piLeafId;
448 + dbg?.("coordinator.persistCheckpoint.position", {
449 + sessionId,
450 + piLeafId,
451 + sdkSessionId: checkpoint.sdkSessionId,
452 + position: checkpoint.position,
453 + messageCount: checkpoint.messageCount,
454 + });
448 455 await saveCheckpoint(root, sessionId, checkpoint);
449 456 this.pendingCheckpoints.delete(sessionId);
450 457 dbg?.("coordinator.persistCheckpoint.end", { sessionId, piLeafId });
671 678 dbg?.("coordinator.start.completed", {
672 679 found: Boolean(completed),
673 680 messageCount: completed?.messageCount,
681 + sdkSessionId: completed?.sdkSessionId,
682 + position: completed?.position,
675 684 const offered =
676 685 reusable && !forceCold && reusable.handle?.isIdle() === true
743 752 thinkingBudget: request.thinkingBudget,
744 753 maxTokens: request.maxTokens,
745 754 cwd: request.cwd,
746 - resume: Boolean(request.resume),
747 - resumeAt: Boolean(request.resumeAt),
755 + resume: request.resume,
756 + resumeAt: request.resumeAt,
748 757 forkSession: request.forkSession,
750 759 const payloadRequest: KlausRequest = { ...request };
964 973 store: state.store,
975 + dbg?.("coordinator.checkpoint.published", {
976 + piSessionId: state.sessionId,
977 + sdkSessionId: completed.sdkSessionId,
978 + position: completed.position,
979 + messageCount: completed.messageCount,
980 + });
966 981 this.completed.set(state.sessionId, completed);
967 982 state.sdkSessionId = completed.sdkSessionId;
968 983 state.position = completed.position;
1350 1365 return (
1351 1366 error instanceof KlausCacheCorruptionError ||
1352 1367 /^Klaus cache corruption:/i.test(error.message) ||
1353 - /^Resume rejected by --resume-drops-turn:/i.test(error.message)
1368 + /^Resume rejected by --resume-drops-turn:/i.test(error.message) ||
1369 + /^No message found with message\.uuid of:/i.test(error.message)

extensions/klaus/src/debug.ts

Modified
1 -import { appendFileSync } from "node:fs";
1 +import { appendFileSync, mkdirSync } from "node:fs";
2 +import { homedir } from "node:os";
3 +import { dirname, join } from "node:path";
4 +import { SettingsManager } from "@earendil-works/pi-coding-agent";
3 6 type Debug = (event: string, details?: Record<string, unknown>) => void;
5 -const path = process.env.KLAUS_DEBUG_LOG;
8 +const unsafeFields = new Set([
9 + "content",
10 + "detail",
11 + "error",
12 + "failure",
13 + "message",
14 + "reason",
15 + "text",
16 +]);
7 -/** Temporary Klaus tracing. Delete this file, its imports, and all dbg?.(...) calls together. */
18 +function diagnostic(value: unknown): { kind: string; length: number } {
19 + const text = String(value);
20 + return {
21 + kind: /No message found with message\.uuid of:/i.test(text)
22 + ? "missing-resume-uuid"
23 + : /OAuth access token has been revoked/i.test(text)
24 + ? "revoked-oauth"
25 + : "redacted",
26 + length: text.length,
27 + };
30 +const settings = SettingsManager.create(
31 + process.cwd(),
32 +).getGlobalSettings() as Record<string, unknown>;
33 +const klaus = settings.klaus;
34 +const enabled =
35 + typeof klaus === "object" &&
36 + klaus !== null &&
37 + (klaus as { debugLog?: unknown }).debugLog === true;
38 +const path =
39 + process.env.KLAUS_DEBUG_LOG ??
40 + (enabled
41 + ? join(
42 + process.env.XDG_CACHE_HOME || join(homedir(), ".cache"),
43 + "pi-ext",
44 + "klaus",
45 + "debug.ndjson",
46 + )
47 + : undefined);
49 +/** Metadata-only Klaus tracing, enabled through global settings or KLAUS_DEBUG_LOG. */
50 +let directoryReady = false;
8 51 export const dbg: Debug | undefined = path
9 52 ? (event, details = {}) => {
10 53 try {
54 + if (!directoryReady) {
55 + mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
56 + directoryReady = true;
57 + }
11 58 appendFileSync(
12 59 path,
13 60 `${JSON.stringify({
14 61 timestamp: new Date().toISOString(),
15 62 pid: process.pid,
16 63 event,
17 - ...details,
64 + ...Object.fromEntries(
65 + Object.entries(details).map(([key, value]) => [
66 + key,
67 + unsafeFields.has(key) ? diagnostic(value) : value,
68 + ]),
69 + ),
18 70 })}\n`,
19 71 { encoding: "utf8", mode: 0o600 },