A pane listing this session's subagents (Agent tool and workflow agents) with their status; select one to see its prompt, text, tool calls and results.

ushironoko's dotfiles management system.
# Initial setup
git clone https://github.com/ushironoko/dotfiles.git
cd dotfiles
./init.sh
# After setup, the dotfiles command is available:
dotfiles install # Install symlinks
dotfiles list # List managed files
dotfiles restore # Restore from backup
dotfiles doctor # Check environment
# Future updates with ghq (after initial setup):
ghq get ushironoko/dotfiles
cd $(ghq root)/github.com/ushironoko/dotfiles
dotfiles installCreates symbolic links from repository to system locations.
-d, --dryRun: Preview changes-f, --force: Force overwrite-s, --select: Interactive selection-v, --verbose: Detailed outputdotfiles listShows all managed dotfiles and their status.
-v, --verbose: Detailed informationdotfiles restoreRestores files from backup.
-b, --backup <timestamp>: Specific backup-l, --list: List available backups-v, --verbose: Detailed outputdotfiles doctorDiagnoses environment issues.
-c, --check <categories>: Check specific areas (environment,conflicts,ghq,config,mcp)-v, --verbose: Detailed diagnosticsIf you're having issues with the initial setup, run the diagnostic tool:
./init.sh --check
This will show:
Run dotfiles doctor to diagnose issues. Common fixes:
# If mise commands are not found after installation
# Make sure ~/.local/bin is in your PATH and restart shell
export PATH="$HOME/.local/bin:$PATH"
exec $SHELL
# Remove conflicting Bun installation
rm -rf ~/.bun
# Fix PATH permanently
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(mise activate bash)"' >> ~/.bashrc
exec $SHELL
# Migrate old repos to ghq
./scripts/migrate-to-ghq.sh --dry-run
./scripts/migrate-to-ghq.sh --symlink
Edit dotfiles.config.ts to manage your files:
The versioned Codex harness installs global instructions, native custom agents, lifecycle hooks, command restrictions, and the shared Claude skills alongside ~/.codex/config.toml. Each component is linked selectively so Codex runtime state and bundled skills remain intact. After hook changes, review and trust them with /hooks in Codex.
~/.codex/config.toml)~/.codex/config.toml is symlinked to codex/config.toml, but codex rewrites that file at runtime, filling it with machine-local state — [projects."<path>"] trust levels (absolute paths, including private/client repo names), [mcp_servers.*] tables wired to Codex.app paths, [marketplaces.*] sources, the notify helper path, per-repo [desktop...perPath] prefs, and [hooks.state] approval hashes. A git clean filter (codex-scrub, codex/scrub-config.awk) drops anything carrying a quoted absolute path, every [projects.*]/[mcp_servers.*] table, and the complete [hooks.state] tree at git add time. The path rule remains content-based so unknown machine state is scrubbed by default; URLs and relative paths are kept. The working tree keeps the live file untouched, so codex keeps functioning.
The filter driver lives in .git/config (never committed), so it must be registered once per clone:
bun run setup:git-filters # also run automatically by init.sh and run-all
init.sh runs it on initial setup and bun run run-all runs it before every pre-commit check, so under normal use no manual step is needed. If you commit codex/config.toml on a fresh clone without it, trust state would leak — the filter is set to required = true to fail loudly if the scrubber ever errors.
hooks/register.tsx 1142 lines1import type { On } from "claude-code";
2import {
3 colorOf,
4 type Detail,
5 detailView,
6 type Entry,
7 glyphOf,
8 harnessFrameOf,
9 type Kit,
10 promptTextOf,
11 type Summary,
12 tidyOf,
13} from "./detail";
14import {
15 SUMMARY_ARGV,
16 SUMMARY_TIMEOUT_MS,
17 summaryInputOf,
18 summaryTextOf,
19} from "./summary";
20import {
21 agentMetaOf,
22 recentRunsOf,
23 runNamesOf,
24 runScansOf,
25 sessionPathsOf,
26 transcriptOf,
27 transcriptPathOf,
28 type Disk,
29 type RunAgent,
30 type SessionPaths,
31} from "./disk";
32
33const PANE_ID = "agents-view";
34const PANE_TITLE = "Agents";
35const COMMAND = "subagents";
36const TICK_MS = 500;
37const SYNC_MS = 3000;
38const PATHS_RETRY_MS = 30_000;
39const NAMES_RETRY_MS = 15_000;
40const MAX_LOOKUPS = 5;
41const MAX_BACKFILLS = 3;
42const PLAIN_TYPES = new Set(["agent", "workflow-subagent"]);
43const MAX_AGENTS = 300;
44const MAX_ENTRIES = 300;
45const MAX_TEXT_CHARS = 2000;
46const MAX_PROMPT_CHARS = 8000;
47const MAX_LINE_CHARS = 200;
48const MAX_DEPTH = 6;
49const SUMMARY_FIELDS = [
50 "file_path",
51 "notebook_path",
52 "command",
53 "pattern",
54 "url",
55 "query",
56 "description",
57 "prompt",
58] as const;
59
60interface Tokens {
61 input: number;
62 output: number;
63}
64
65interface Tracked {
66 id: string;
67 label: string;
68 type: string;
69 status: string;
70 isListed: boolean;
71 isBackground: boolean;
72 seq: number;
73 entries: readonly Entry[];
74 parentId?: string;
75 workflowRun?: string;
76 workflowIndex?: number;
77 phase?: string;
78 isResolved: boolean;
79 isBackfilled: boolean;
80 lookups: number;
81 model?: string;
82 effort?: string;
83 startedAt: number;
84 endedAt?: number;
85 steps: number;
86 toolCalls: number;
87 tokens: Tokens;
88}
89
90type Runs = ReadonlyMap<string, string>;
91
92interface Placed {
93 agent: Tracked;
94 depth: number;
95}
96
97interface Group {
98 key: string;
99 title: string;
100 note: string;
101 members: readonly Placed[];
102}
103
104interface Listed {
105 id: string;
106 description: string;
107 type: string;
108 status: string;
109 parentId?: string;
110}
111
112interface Host {
113 list: () => Promise<readonly Listed[]>;
114 now: () => Promise<number>;
115 disk: Disk;
116 summarize: (input: string) => Promise<string>;
117 open: () => Promise<unknown>;
118 redraw: () => void;
119}
120
121interface Row {
122 type: string;
123 role?: string;
124 isMeta?: true;
125 content: readonly { type: string; [field: string]: unknown }[];
126}
127
128const isDrawable = (char: string): boolean => {
129 const code = char.codePointAt(0) ?? 0;
130
131 return code === 9 || code === 10 || (code >= 32 && code !== 127);
132};
133
134const drawableOf = (text: string, limit: number): string => {
135 const cleaned = [...text.slice(0, limit * 2).replaceAll("\r\n", "\n")]
136 .filter(isDrawable)
137 .join("");
138
139 return cleaned.length > limit ? `${cleaned.slice(0, limit - 1)}…` : cleaned;
140};
141
142const lineOf = (text: string): string =>
143 drawableOf(text.replaceAll(/\s+/g, " ").trim(), MAX_LINE_CHARS);
144
145const summaryOf = (input: unknown): string => {
146 if (typeof input !== "object" || input === null) {
147 return "";
148 }
149
150 const record = input as Record<string, unknown>;
151 const found = SUMMARY_FIELDS.map((field) => record[field]).find(
152 (value): value is string => typeof value === "string" && value !== "",
153 );
154
155 return found === undefined ? "" : lineOf(tidyOf(found));
156};
157
158const resultTextOf = (content: unknown): string => {
159 if (typeof content === "string") {
160 return content;
161 }
162
163 if (!Array.isArray(content)) {
164 return "";
165 }
166
167 return content
168 .map((part: unknown) =>
169 typeof part === "object" &&
170 part !== null &&
171 (part as Record<string, unknown>).type === "text"
172 ? String((part as Record<string, unknown>).text ?? "")
173 : "",
174 )
175 .join("\n");
176};
177
178const resultEntryOf = (content: unknown, isError: boolean): Entry => {
179 const text = tidyOf(resultTextOf(content));
180 const lines = text === "" ? 0 : text.split("\n").length;
181 const head = lineOf(
182 text.split("\n").find((line) => line.trim() !== "") ?? "",
183 );
184
185 return {
186 kind: "result",
187 isError,
188 text: lines > 1 ? `${head} (+${lines - 1} lines)` : head,
189 };
190};
191
192const entriesOf = (row: Row, hasPrompt: boolean): Entry[] =>
193 row.content.flatMap((block): Entry[] => {
194 if (block.type === "text" && typeof block.text === "string") {
195 const frame =
196 row.role === "user" ? harnessFrameOf(block.text) : undefined;
197
198 if (frame === "user request") {
199 return [];
200 }
201
202 const isPrompt =
203 row.role === "user" &&
204 (frame === "computed task" || (!hasPrompt && frame === undefined));
205 const text = isPrompt
206 ? drawableOf(tidyOf(promptTextOf(block.text)), MAX_PROMPT_CHARS)
207 : drawableOf(tidyOf(block.text.trim()), MAX_TEXT_CHARS);
208
209 if (text.trim() === "") {
210 return [];
211 }
212
213 return [isPrompt ? { kind: "prompt", text } : { kind: "text", text }];
214 }
215
216 if (block.type === "tool_use") {
217 return [
218 {
219 kind: "tool",
220 name: typeof block.name === "string" ? block.name : "tool",
221 summary: summaryOf(block.input),
222 },
223 ];
224 }
225
226 if (block.type === "tool_result") {
227 return [resultEntryOf(block.content, block.is_error === true)];
228 }
229
230 return [];
231 });
232
233const statusOfReason = (reason: string): string => {
234 switch (reason) {
235 case "answer": {
236 return "completed";
237 }
238 case "aborted": {
239 return "killed";
240 }
241 default: {
242 return "failed";
243 }
244 }
245};
246
247const isLive = (status: string): boolean =>
248 status === "running" || status === "idle";
249
250const seededStatusOf = (one: Tracked, member: RunAgent): string => {
251 if (!member.isDone || one.isListed || !isLive(one.status)) {
252 return one.status;
253 }
254
255 return member.isRetried ? "retried" : "completed";
256};
257
258const modelOf = (model: string): string =>
259 model
260 .replace(/^.*?claude-/, "")
261 .replace(/-\d{8}(?=$|\[|-v)/, "")
262 .replace(/-(\d+)-(\d+)(?=$|\[)/, "-$1.$2");
263
264const effortOf = (effort: string | number | undefined): string | undefined => {
265 if (effort === undefined) {
266 return undefined;
267 }
268
269 return typeof effort === "number" ? `budget ${effort}` : effort;
270};
271
272const countOf = (value: number): string => {
273 if (value < 1000) {
274 return String(value);
275 }
276
277 if (value < 1_000_000) {
278 return `${(value / 1000).toFixed(1)}k`;
279 }
280
281 return `${(value / 1_000_000).toFixed(1)}M`;
282};
283
284const durationOf = (ms: number): string => {
285 const seconds = Math.max(0, Math.floor(ms / 1000));
286
287 if (seconds < 60) {
288 return `${seconds}s`;
289 }
290
291 const minutes = Math.floor(seconds / 60);
292
293 if (minutes < 60) {
294 return `${minutes}m${String(seconds % 60).padStart(2, "0")}s`;
295 }
296
297 return `${Math.floor(minutes / 60)}h${String(minutes % 60).padStart(2, "0")}m`;
298};
299
300const elapsedOf = (agent: Tracked, now: number): string =>
301 durationOf((agent.endedAt ?? now) - agent.startedAt);
302
303const runnerOf = (agent: Tracked): string =>
304 [agent.model === undefined ? undefined : modelOf(agent.model), agent.effort]
305 .filter((part) => part !== undefined)
306 .join(" · ");
307
308const chipOf = (agent: Tracked): string =>
309 [PLAIN_TYPES.has(agent.type) ? undefined : `[${agent.type}]`, agent.phase]
310 .filter((part) => part !== undefined)
311 .join(" ");
312
313const countedOf = (value: number, noun: string): string =>
314 `${value} ${noun}${value === 1 ? "" : "s"}`;
315
316const definedOf = (parts: readonly (string | undefined)[]): string[] =>
317 parts.filter((part): part is string => part !== undefined && part !== "");
318
319const detailOf = (
320 agent: Tracked,
321 runs: Runs,
322 now: number,
323 summary?: Summary,
324): Detail => {
325 const workflow =
326 agent.workflowRun === undefined
327 ? undefined
328 : definedOf([
329 runs.get(agent.workflowRun) ?? "workflow",
330 agent.workflowIndex === undefined
331 ? undefined
332 : `#${agent.workflowIndex}`,
333 ]).join(" ");
334
335 return {
336 id: agent.id,
337 summary,
338 label: agent.label,
339 status: agent.status,
340 elapsed: elapsedOf(agent, now),
341 context: definedOf([
342 agent.type,
343 agent.phase,
344 workflow,
345 agent.isBackground ? "background" : undefined,
346 ]),
347 model: agent.model === undefined ? undefined : modelOf(agent.model),
348 effort: agent.effort,
349 stats: definedOf([
350 countedOf(agent.steps, "step"),
351 countedOf(agent.toolCalls, "tool"),
352 `in ${countOf(agent.tokens.input)}`,
353 `out ${countOf(agent.tokens.output)}`,
354 ]).join(" · "),
355 origin: definedOf([
356 agent.id,
357 agent.parentId === undefined ? undefined : `parent ${agent.parentId}`,
358 agent.workflowRun,
359 ]).join(" · "),
360 entries: agent.entries,
361 };
362};
363
364const freshOf = (id: string, seq: number, now: number): Tracked => ({
365 id,
366 label: id,
367 type: "agent",
368 status: "running",
369 isListed: false,
370 isBackground: false,
371 isResolved: false,
372 isBackfilled: false,
373 lookups: 0,
374 seq,
375 entries: [],
376 startedAt: now,
377 steps: 0,
378 toolCalls: 0,
379 tokens: { input: 0, output: 0 },
380});
381
382const orderOf = (agents: ReadonlyMap<string, Tracked>): Tracked[] =>
383 [...agents.values()].toSorted((a, b) => {
384 const running = Number(isLive(b.status)) - Number(isLive(a.status));
385
386 return running === 0 ? b.seq - a.seq : running;
387 });
388
389const placedOf = (agents: ReadonlyMap<string, Tracked>): Placed[] => {
390 const ordered = orderOf(agents);
391 const rootOf = (agent: Tracked): string | undefined =>
392 agent.parentId !== undefined && agents.has(agent.parentId)
393 ? agent.parentId
394 : undefined;
395 const walk = (parentId: string | undefined, depth: number): Placed[] =>
396 ordered
397 .filter((one) => rootOf(one) === parentId)
398 .flatMap((one) => [
399 { agent: one, depth },
400 ...(depth < MAX_DEPTH ? walk(one.id, depth + 1) : []),
401 ]);
402
403 return walk(undefined, 0);
404};
405
406const noteOf = (members: readonly Placed[], suffix?: string): string =>
407 [
408 `${members.filter(({ agent }) => isLive(agent.status)).length} running / ${members.length}`,
409 suffix,
410 ]
411 .filter((part) => part !== undefined)
412 .join(" · ");
413
414const rankOf = (group: Group): readonly [number, number] => [
415 Number(group.members.some(({ agent }) => isLive(agent.status))),
416 Math.max(...group.members.map(({ agent }) => agent.seq)),
417];
418
419const groupsOf = (
420 agents: ReadonlyMap<string, Tracked>,
421 runs: Runs,
422): Group[] => {
423 const ordered = orderOf(agents);
424 const runIds = [
425 ...new Set(
426 ordered.flatMap((one) =>
427 one.workflowRun === undefined ? [] : [one.workflowRun],
428 ),
429 ),
430 ];
431 const loose = placedOf(
432 new Map([...agents].filter(([, one]) => one.workflowRun === undefined)),
433 );
434 const workflows = runIds.map((run): Group => {
435 const members = ordered
436 .filter((one) => one.workflowRun === run)
437 .map((agent) => ({ agent, depth: 0 }));
438 const name = runs.get(run);
439
440 return {
441 key: run,
442 title: name ?? run,
443 note: noteOf(members, name === undefined ? undefined : run),
444 members,
445 };
446 });
447 const groups =
448 loose.length === 0
449 ? workflows
450 : [
451 ...workflows,
452 {
453 key: "subagents",
454 title: "subagents",
455 note: noteOf(loose),
456 members: loose,
457 },
458 ];
459
460 return groups.toSorted((a, b) => {
461 const [liveA, seqA] = rankOf(a);
462 const [liveB, seqB] = rankOf(b);
463
464 return liveA === liveB ? seqB - seqA : liveB - liveA;
465 });
466};
467
468const prunedOf = (
469 agents: ReadonlyMap<string, Tracked>,
470): ReadonlyMap<string, Tracked> =>
471 agents.size <= MAX_AGENTS
472 ? agents
473 : new Map(
474 orderOf(agents)
475 .slice(0, MAX_AGENTS)
476 .map((one) => [one.id, one]),
477 );
478
479const trackedSignatureOf = (one: Tracked, now: number): string =>
480 [
481 one.id,
482 one.status,
483 one.entries.length,
484 one.label,
485 one.type,
486 one.phase,
487 one.workflowRun,
488 one.model,
489 one.effort,
490 one.steps,
491 one.tokens.output,
492 one.endedAt === undefined ? Math.floor(now / 1000) : one.endedAt,
493 ].join(":");
494
495const signatureOf = (
496 agents: ReadonlyMap<string, Tracked>,
497 runs: Runs,
498 now: number,
499): string =>
500 [
501 ...runs.values(),
502 ...[...agents.values()].map((one) => trackedSignatureOf(one, now)),
503 ].join("|");
504
505export const register = (on: On) => {
506 let agents: ReadonlyMap<string, Tracked> = new Map();
507 let runs: Runs = new Map();
508 let selectedId: string | null = null;
509 let expandedIds: ReadonlySet<string> = new Set();
510 let summaries: ReadonlyMap<string, Summary & { seq: number }> = new Map();
511 let summarySeq = 0;
512 let host: Host | null = null;
513 let isOpen = false;
514 let hasAutoOpened = false;
515 let drawnSignature = "";
516 let seq = 0;
517 let paths: SessionPaths | undefined;
518 let pathsCheckedAt = Number.NEGATIVE_INFINITY;
519 let syncedAt = Number.NEGATIVE_INFINITY;
520 let namedAt = Number.NEGATIVE_INFINITY;
521 let soughtRuns: ReadonlySet<string> = new Set();
522 let endedRuns: ReadonlySet<string> = new Set();
523 let syncNote: string | undefined;
524
525 const upsert = (
526 id: string,
527 now: number,
528 change: (current: Tracked) => Tracked,
529 ) => {
530 const current = agents.get(id) ?? freshOf(id, (seq += 1), now);
531 agents = prunedOf(new Map([...agents, [id, change(current)]]));
532 };
533
534 const openPane = async (current: Host) => {
535 isOpen = true;
536 await current.open();
537 current.redraw();
538 };
539
540 const resolvePaths = async (disk: Disk, now: number) => {
541 if (paths === undefined && now - pathsCheckedAt >= PATHS_RETRY_MS) {
542 pathsCheckedAt = now;
543 paths = await sessionPathsOf(disk).catch(() => undefined);
544 }
545
546 return paths;
547 };
548
549 const seedRuns = async (
550 disk: Disk,
551 found: SessionPaths,
552 recent: readonly string[],
553 now: number,
554 ) => {
555 const scan = await runScansOf(
556 disk,
557 found,
558 recent.filter((run) => !endedRuns.has(run)),
559 );
560 endedRuns = new Set([...endedRuns, ...scan.ended]);
561
562 scan.active.forEach(({ run, agents: members }) =>
563 members.forEach((member) =>
564 upsert(member.id, member.startedAt ?? now, (one) => ({
565 ...one,
566 label:
567 one.label === one.id && member.label !== undefined
568 ? lineOf(member.label)
569 : one.label,
570 type: one.type === "agent" ? "workflow-subagent" : one.type,
571 phase: one.phase ?? member.phase,
572 workflowRun: one.workflowRun ?? run,
573 isResolved: one.isResolved || member.label !== undefined,
574 status: seededStatusOf(one, member),
575 endedAt:
576 member.isDone && one.endedAt === undefined
577 ? (member.endedAt ?? now)
578 : one.endedAt,
579 })),
580 ),
581 );
582 };
583
584 const resolveAgents = async (
585 disk: Disk,
586 found: SessionPaths,
587 recent: readonly string[],
588 now: number,
589 ) => {
590 const pending = [...agents.values()].filter(
591 (one) => !one.isResolved && one.lookups < MAX_LOOKUPS,
592 );
593
594 if (pending.length === 0) {
595 return;
596 }
597
598 const metas = await Promise.all(
599 pending.map(
600 async (one) =>
601 [
602 one.id,
603 await agentMetaOf(
604 disk,
605 found,
606 one.workflowRun === undefined ? recent : [one.workflowRun],
607 one.id,
608 ).catch(() => undefined),
609 ] as const,
610 ),
611 );
612
613 metas.forEach(([id, meta]) =>
614 upsert(id, now, (one) =>
615 meta === undefined
616 ? { ...one, lookups: one.lookups + 1 }
617 : {
618 ...one,
619 label:
620 !one.isListed && meta.label !== undefined
621 ? lineOf(meta.label)
622 : one.label,
623 type: one.isListed ? one.type : (meta.type ?? one.type),
624 phase: meta.phase ?? one.phase,
625 model: one.model ?? meta.model,
626 workflowRun: one.workflowRun ?? meta.run,
627 isResolved: true,
628 lookups: one.lookups + 1,
629 },
630 ),
631 );
632 };
633
634 const backfillAgents = async (
635 disk: Disk,
636 found: SessionPaths,
637 now: number,
638 ) => {
639 const pending = [...agents.values()]
640 .filter(
641 (one) =>
642 !one.isBackfilled &&
643 one.entries.length === 0 &&
644 one.steps === 0 &&
645 (one.workflowRun !== undefined || one.isResolved) &&
646 (isLive(one.status) || one.id === selectedId),
647 )
648 .slice(0, MAX_BACKFILLS);
649 const loaded = await Promise.all(
650 pending.map(
651 async (one) =>
652 [
653 one.id,
654 await transcriptOf(
655 disk,
656 transcriptPathOf(found, one.id, one.workflowRun),
657 ).catch(() => undefined),
658 ] as const,
659 ),
660 );
661
662 loaded.forEach(([id, transcript]) =>
663 upsert(id, now, (one) => {
664 if (transcript === undefined || one.entries.length > 0) {
665 return { ...one, isBackfilled: true };
666 }
667
668 return {
669 ...one,
670 isBackfilled: true,
671 entries: transcript.rows
672 .reduce<Entry[]>(
673 (collected, row) => [
674 ...collected,
675 ...entriesOf(
676 row,
677 collected.some((entry) => entry.kind === "prompt"),
678 ),
679 ],
680 [],
681 )
682 .slice(-MAX_ENTRIES),
683 model: one.model ?? transcript.model,
684 effort: one.effort ?? transcript.effort,
685 steps: one.steps + transcript.steps,
686 toolCalls: one.toolCalls + transcript.toolCalls,
687 tokens: {
688 input: one.tokens.input + transcript.input,
689 output: one.tokens.output + transcript.output,
690 },
691 };
692 }),
693 );
694 };
695
696 const requestSummary = async (current: Host, id: string) => {
697 const seq = (summarySeq += 1);
698 const settle = (summary: Summary) => {
699 if (summaries.get(id)?.seq === seq) {
700 summaries = new Map([...summaries, [id, { ...summary, seq }]]);
701 current.redraw();
702 }
703 };
704
705 summaries = new Map([
706 ...summaries,
707 [id, { state: "loading", text: "", seq }],
708 ]);
709 current.redraw();
710
711 const now = await current.now();
712
713 if (paths !== undefined) {
714 await backfillAgents(current.disk, paths, now).catch(() => undefined);
715 }
716
717 const agent = agents.get(id);
718
719 if (agent === undefined) {
720 settle({ state: "error", text: "agent is no longer tracked" });
721
722 return;
723 }
724
725 await current.summarize(summaryInputOf(detailOf(agent, runs, now))).then(
726 (text) => settle({ state: "done", text }),
727 (error: unknown) =>
728 settle({ state: "error", text: lineOf(String(error)) }),
729 );
730 };
731
732 const resolveNames = async (disk: Disk, found: SessionPaths, now: number) => {
733 const unnamed = [...agents.values()].flatMap((one) =>
734 one.workflowRun === undefined ||
735 runs.has(one.workflowRun) ||
736 soughtRuns.has(one.workflowRun)
737 ? []
738 : [one.workflowRun],
739 );
740
741 if (unnamed.length === 0 || now - namedAt < NAMES_RETRY_MS) {
742 return;
743 }
744
745 namedAt = now;
746 soughtRuns = new Set([...soughtRuns, ...unnamed]);
747 const named = await runNamesOf(disk, found).catch(() => new Map());
748 runs = new Map([...named, ...runs]);
749 };
750
751 const sync = async (disk: Disk, now: number) => {
752 if (now - syncedAt < SYNC_MS) {
753 return;
754 }
755
756 syncedAt = now;
757 const found = await resolvePaths(disk, now);
758
759 if (found === undefined) {
760 syncNote =
761 "session records not found; workflow agents appear as they run";
762
763 return;
764 }
765
766 const recent = await recentRunsOf(disk, found, now);
767 const open = recent.filter((one) => !one.isEnded).map((one) => one.run);
768
769 await seedRuns(disk, found, open, now);
770 await resolveAgents(
771 disk,
772 found,
773 recent.map((one) => one.run),
774 now,
775 );
776 await backfillAgents(disk, found, now);
777 await resolveNames(disk, found, now);
778 syncNote = undefined;
779 };
780
781 const tick = async (current: Host) => {
782 const listed = await current.list().catch(() => []);
783 const now = await current.now();
784
785 await sync(current.disk, now).catch((error: unknown) => {
786 syncNote = `reading session records failed: ${lineOf(String(error))}`;
787 });
788
789 listed.forEach((info) =>
790 upsert(info.id, now, (one) => ({
791 ...one,
792 label: lineOf(info.description) || one.label,
793 type: info.type,
794 status: info.status,
795 parentId: info.parentId ?? one.parentId,
796 isListed: true,
797 endedAt: isLive(info.status) ? undefined : (one.endedAt ?? now),
798 })),
799 );
800
801 if (!hasAutoOpened && agents.size > 0) {
802 hasAutoOpened = true;
803
804 if (!isOpen) {
805 await openPane(current);
806 }
807 }
808
809 const signature = [
810 syncNote ?? "",
811 [...summaries].map(([id, one]) => `${id}:${one.seq}:${one.state}`),
812 signatureOf(agents, runs, now),
813 ].join("|");
814
815 if (signature !== drawnSignature) {
816 drawnSignature = signature;
817 current.redraw();
818 }
819 };
820
821 on("session.start", async ($, e, next) => {
822 if ((await $.env.get("AGENTS_VIEW_CHILD")) === "1") {
823 return next(e);
824 }
825
826 const current: Host = {
827 list: () => $.agent.list(),
828 now: () => $.clock.now(),
829 disk: {
830 read: (path) => $.fs.read(path),
831 list: (path) => $.fs.list(path),
832 exists: (path) => $.fs.exists(path),
833 stat: (path) => $.fs.stat(path),
834 run: (argv) => $.process.run(argv),
835 configured: () => $.env.get("CLAUDE_CONFIG_DIR"),
836 home: () => $.env.get("HOME"),
837 sessionId: () => $.session.id(),
838 roots: async () => [await $.session.root(), await $.session.cwd()],
839 },
840 summarize: async (input) => {
841 const { exitCode, stdout, stderr } = await $.process.run(SUMMARY_ARGV, {
842 stdin: input,
843 env: { AGENTS_VIEW_CHILD: "1" },
844 timeoutMs: SUMMARY_TIMEOUT_MS,
845 });
846
847 if (exitCode !== 0) {
848 throw new Error(
849 lineOf(stderr) || lineOf(stdout) || `claude exited ${exitCode}`,
850 );
851 }
852
853 return summaryTextOf(stdout);
854 },
855 open: () => $.ui.open({ id: PANE_ID, title: PANE_TITLE }),
856 redraw: () => $.ui.invalidate("ui.render"),
857 };
858 host = current;
859
860 await $.command.register({
861 name: COMMAND,
862 description: "Toggle the pane listing this session's subagents",
863 });
864 const loop = () =>
865 $.clock.after(
866 TICK_MS,
867 () =>
868 void tick(current)
869 .catch(() => undefined)
870 .finally(loop),
871 );
872 loop();
873
874 return next(e);
875 });
876
877 on("command.run", { command: COMMAND }, async ($) => {
878 if (host === null) {
879 return { text: "agents-view is not ready yet." };
880 }
881
882 if (isOpen) {
883 isOpen = false;
884 await $.ui.close({ id: PANE_ID });
885
886 return { text: "Agents pane hidden." };
887 }
888
889 hasAutoOpened = true;
890 await openPane(host);
891
892 return { text: "Agents pane shown." };
893 });
894
895 on("agent.spawn", async ($, e, next) => {
896 const result = await next(e);
897 const { agentId } = result;
898
899 if (agentId !== undefined) {
900 const now = await $.clock.now();
901 const description = lineOf(e.description);
902
903 upsert(agentId, now, (one) => ({
904 ...one,
905 label: !one.isListed && description !== "" ? description : one.label,
906 type: one.isListed ? one.type : e.subagentType,
907 model: one.model ?? result.model,
908 parentId: one.parentId ?? e.parentAgentId,
909 workflowRun: e.workflow?.runId || one.workflowRun,
910 workflowIndex: e.workflow?.agentIndex ?? one.workflowIndex,
911 isBackground: e.background,
912 status: one.isListed ? one.status : "running",
913 endedAt: undefined,
914 }));
915 }
916
917 return result;
918 });
919
920 on("turn.start", async ($, e, next) => {
921 const { agentId } = e;
922
923 if (agentId !== undefined) {
924 const now = await $.clock.now();
925 const prompt = lineOf(e.text);
926
927 upsert(agentId, now, (one) => ({
928 ...one,
929 label: one.label === one.id && prompt !== "" ? prompt : one.label,
930 status: one.isListed ? one.status : "running",
931 endedAt: undefined,
932 }));
933 }
934
935 return next(e);
936 });
937
938 on("tool.call", { tool: "Workflow" }, async (_, e, next) => {
939 const ran = await next(e);
940
941 if (ran.deny === undefined && ran.isError !== true) {
942 const { runId, workflowName } = ran.result;
943 const name = workflowName ?? e.name;
944
945 if (runId !== undefined && name !== undefined && name !== "") {
946 runs = new Map([...runs, [runId, lineOf(name)]]);
947 }
948 }
949
950 return ran;
951 });
952
953 on("turn.step", async function* observeStep($, e, next) {
954 const { agentId } = e;
955
956 if (agentId === undefined) {
957 return yield* next(e);
958 }
959
960 upsert(agentId, await $.clock.now(), (one) => ({
961 ...one,
962 model: e.model,
963 effort: effortOf(e.effort),
964 }));
965
966 const result = yield* next(e);
967 const { usage } = result;
968
969 upsert(agentId, await $.clock.now(), (one) => ({
970 ...one,
971 model: usage?.model ?? one.model,
972 steps: one.steps + 1,
973 toolCalls: one.toolCalls + result.toolUses.length,
974 tokens:
975 usage === null
976 ? one.tokens
977 : {
978 input:
979 one.tokens.input +
980 usage.input_tokens +
981 usage.cache_read_input_tokens +
982 usage.cache_creation_input_tokens,
983 output: one.tokens.output + usage.output_tokens,
984 },
985 }));
986
987 return result;
988 });
989
990 on("session.append", async ($, e, next) => {
991 const { agentId, message } = e;
992
993 if (
994 agentId !== undefined &&
995 (message.type === "user" || message.type === "assistant") &&
996 message.isMeta !== true
997 ) {
998 upsert(agentId, await $.clock.now(), (one) => {
999 const added = entriesOf(
1000 message,
1001 one.entries.some((entry) => entry.kind === "prompt"),
1002 );
1003 const opening = added.find((entry) => entry.kind === "prompt");
1004
1005 return {
1006 ...one,
1007 label:
1008 !one.isListed && one.label === one.id && opening !== undefined
1009 ? lineOf(opening.text)
1010 : one.label,
1011 entries: [...one.entries, ...added].slice(-MAX_ENTRIES),
1012 };
1013 });
1014 }
1015
1016 return next(e);
1017 });
1018
1019 on("turn.complete", async ($, e, next) => {
1020 const { agentId } = e;
1021
1022 if (agentId !== undefined && agents.has(agentId)) {
1023 const now = await $.clock.now();
1024
1025 upsert(agentId, now, (one) => ({
1026 ...one,
1027 status: one.isListed ? one.status : statusOfReason(e.reason),
1028 endedAt: now,
1029 }));
1030 }
1031
1032 return next(e);
1033 });
1034
1035 on("ui.render", { component: "Pane" }, async ($, e, next) => {
1036 if (e.requestId !== PANE_ID || e.surface !== "terminal") {
1037 return next(e);
1038 }
1039
1040 const { Box, Text, Button } = $.ui.resolve(e);
1041 const kit: Kit = { Box, Text, Button };
1042 const now = await $.clock.now();
1043 const groups = groupsOf(agents, runs);
1044 const ordered = groups.flatMap(({ members }) =>
1045 members.map(({ agent }) => agent),
1046 );
1047 const selected =
1048 agents.get(selectedId ?? "") ??
1049 ordered.find((one) => isLive(one.status)) ??
1050 ordered[0];
1051 const running = ordered.filter((one) => isLive(one.status)).length;
1052
1053 return (
1054 <Box flexDirection="column" paddingRight={1}>
1055 <Text bold>
1056 Agents <Text color="yellow">{running} running</Text>
1057 <Text dimColor> / {ordered.length} total</Text>
1058 </Text>
1059 {syncNote === undefined ? undefined : (
1060 <Text color="yellow" wrap="truncate-end">
1061 {syncNote}
1062 </Text>
1063 )}
1064 {ordered.length === 0 ? (
1065 <Text dimColor>No subagents in this session yet.</Text>
1066 ) : (
1067 <Box flexDirection="column">
1068 {groups.map((group) => (
1069 <Box key={`group:${group.key}`} flexDirection="column">
1070 <Text wrap="truncate-end">
1071 <Text bold color="cyan">
1072 {group.title}
1073 </Text>
1074 <Text dimColor> {group.note}</Text>
1075 </Text>
1076 {group.members.map(({ agent: one, depth }) => {
1077 const isSelected = one.id === selected?.id;
1078 const meta = [chipOf(one), runnerOf(one), elapsedOf(one, now)]
1079 .filter((part) => part !== "")
1080 .join(" · ");
1081
1082 return (
1083 <Button
1084 key={`agent:${one.id}`}
1085 plain
1086 dimColor={!isSelected}
1087 onPress={() => {
1088 selectedId = one.id;
1089 syncedAt = Number.NEGATIVE_INFINITY;
1090
1091 if (host !== null) {
1092 void requestSummary(host, one.id);
1093 }
1094 host?.redraw();
1095 }}
1096 >
1097 {isSelected ? "❯ " : " "}
1098 {" ".repeat(depth)}
1099 {depth > 0 ? "└ " : ""}
1100 <Text color={colorOf(one.status)}>
1101 {glyphOf(one.status)}
1102 </Text>{" "}
1103 {one.label}
1104 <Text dimColor> {meta}</Text>
1105 </Button>
1106 );
1107 })}
1108 </Box>
1109 ))}
1110 </Box>
1111 )}
1112 <Text dimColor>{"─".repeat(Math.max(1, e.props.bodyColumns - 1))}</Text>
1113 {detailView(
1114 kit,
1115 selected === undefined
1116 ? undefined
1117 : detailOf(selected, runs, now, summaries.get(selected.id)),
1118 {
1119 isExpanded: selected !== undefined && expandedIds.has(selected.id),
1120 onToggle: () => {
1121 if (selected === undefined) {
1122 return;
1123 }
1124
1125 expandedIds = expandedIds.has(selected.id)
1126 ? new Set([...expandedIds].filter((id) => id !== selected.id))
1127 : new Set([...expandedIds, selected.id]);
1128 host?.redraw();
1129 },
1130 },
1131 )}
1132 </Box>
1133 );
1134 });
1135
1136 on("ui.close", { id: PANE_ID }, (_, e, next) => {
1137 isOpen = false;
1138
1139 return next(e);
1140 });
1141};
1142hooks/detail.tsx 351 lines1import type { ElementTable } from "claude-code";
2
3const PROMPT_LINES = 3;
4const TEXT_LINES = 4;
5const MAX_ACTIVITY = 40;
6const MIN_NAME_WIDTH = 6;
7const MAX_NAME_WIDTH = 16;
8const HARNESS_PREAMBLE =
9 /^\s*\[Workflow harness[^\]]*\][\s\S]*?\bfollows:[^\S\n]*\n/;
10const HARNESS_FRAME = /^\s*\[Workflow harness\s*\W\s*([a-z ]+?)\s*\]/i;
11const TIDY_RULES: readonly (readonly [RegExp, string])[] = [
12 [/<\/?(?:tool_use_error|system-reminder)>/g, ""],
13 [/\/(?:private\/)?var\/folders\/[^/\s]+\/[^/\s]+\/T\//g, "$$TMPDIR/"],
14 [/\/(?:private\/)?tmp\/claude-\d+\/[^/\s]+\/[^/\s]+\//g, "$$TMPDIR/"],
15 [/\/(?:Users|home)\/[^/\s]+\//g, "~/"],
16];
17
18export type Entry =
19 | { kind: "prompt"; text: string }
20 | { kind: "text"; text: string }
21 | { kind: "tool"; name: string; summary: string }
22 | { kind: "result"; text: string; isError: boolean };
23
24export type Kit = Pick<ElementTable<"terminal">, "Box" | "Text" | "Button">;
25
26export interface Summary {
27 state: "loading" | "done" | "error";
28 text: string;
29}
30
31export interface Detail {
32 id: string;
33 summary?: Summary;
34 label: string;
35 status: string;
36 elapsed: string;
37 context: readonly string[];
38 model?: string;
39 effort?: string;
40 stats: string;
41 origin: string;
42 entries: readonly Entry[];
43}
44
45export interface DetailView {
46 isExpanded: boolean;
47 onToggle: () => void;
48}
49
50export const tidyOf = (text: string): string =>
51 TIDY_RULES.reduce(
52 (current, [pattern, replacement]) =>
53 current.replaceAll(pattern, replacement),
54 text,
55 );
56
57const dedentOf = (text: string): string => {
58 const lines = text.split("\n");
59 const indents = lines
60 .filter((line) => line.trim() !== "")
61 .map((line) => line.length - line.trimStart().length);
62 const indent = indents.length === 0 ? 0 : Math.min(...indents);
63
64 return lines.map((line) => line.slice(indent)).join("\n");
65};
66
67export const harnessFrameOf = (text: string): string | undefined =>
68 HARNESS_FRAME.exec(text)?.[1]?.toLowerCase();
69
70export const promptTextOf = (text: string): string =>
71 dedentOf(text.replace(HARNESS_PREAMBLE, ""))
72 .replaceAll(/\n{3,}/g, "\n\n")
73 .trim();
74
75export const glyphOf = (status: string): string => {
76 switch (status) {
77 case "running": {
78 return "●";
79 }
80 case "completed": {
81 return "✓";
82 }
83 case "failed": {
84 return "✗";
85 }
86 case "killed": {
87 return "■";
88 }
89 default: {
90 return "○";
91 }
92 }
93};
94
95export const colorOf = (status: string): string => {
96 switch (status) {
97 case "running": {
98 return "warning";
99 }
100 case "completed": {
101 return "success";
102 }
103 case "failed": {
104 return "error";
105 }
106 default: {
107 return "inactive";
108 }
109 }
110};
111
112const toolNameOf = (name: string): string =>
113 name.startsWith("mcp__") ? (name.split("__").at(-1) ?? name) : name;
114
115const sectionView = ({ Text }: Kit, title: string, note?: string) => (
116 <Text>
117 <Text bold dimColor>
118 {title}
119 </Text>
120 {note === undefined ? "" : <Text dimColor> · {note}</Text>}
121 </Text>
122);
123
124const summaryBodyOf = ({ Text }: Kit, summary: Summary) => {
125 switch (summary.state) {
126 case "loading": {
127 return <Text dimColor>✻ Summarizing with haiku-5.5 · xhigh…</Text>;
128 }
129 case "done": {
130 return <Text>{summary.text}</Text>;
131 }
132 case "error": {
133 return (
134 <Text color="error" wrap="truncate-end">
135 Summary failed: {summary.text}
136 </Text>
137 );
138 }
139 }
140};
141
142const summaryView = (kit: Kit, summary: Summary | undefined) => {
143 const { Box } = kit;
144
145 if (summary === undefined) {
146 return undefined;
147 }
148
149 return (
150 <Box
151 flexDirection="column"
152 borderStyle="round"
153 borderColor={summary.state === "error" ? "error" : "inactive"}
154 paddingX={1}
155 marginBottom={1}
156 >
157 {summaryBodyOf(kit, summary)}
158 </Box>
159 );
160};
161
162const headerView = ({ Box, Text }: Kit, detail: Detail) => (
163 <Box flexDirection="column">
164 <Box columnGap={2}>
165 <Box flexShrink={1}>
166 <Text bold wrap="truncate-end">
167 {detail.label}
168 </Text>
169 </Box>
170 <Box flexShrink={0}>
171 <Text color={colorOf(detail.status)}>
172 {glyphOf(detail.status)} {detail.status}
173 </Text>
174 <Text dimColor> {detail.elapsed}</Text>
175 </Box>
176 </Box>
177 {detail.context.length === 0 ? undefined : (
178 <Text dimColor wrap="truncate-end">
179 {detail.context.join(" · ")}
180 </Text>
181 )}
182 <Text wrap="truncate-end">
183 <Text color="claude">{detail.model ?? "model ?"}</Text>
184 {detail.effort === undefined ? "" : <Text bold> {detail.effort}</Text>}
185 <Text dimColor>
186 {" "}
187 {detail.stats}
188 </Text>
189 </Text>
190 </Box>
191);
192
193const promptView = (
194 kit: Kit,
195 text: string | undefined,
196 { isExpanded, onToggle }: DetailView,
197) => {
198 const { Box, Text, Button } = kit;
199
200 if (text === undefined) {
201 return undefined;
202 }
203
204 const lines = text.split("\n");
205 const hidden = lines.length - PROMPT_LINES;
206 const shown =
207 isExpanded || hidden <= 0 ? lines : lines.slice(0, PROMPT_LINES);
208
209 return (
210 <Box flexDirection="column" marginTop={1}>
211 {sectionView(kit, "PROMPT")}
212 <Box flexDirection="column" paddingLeft={2}>
213 {shown.map((line, index) => (
214 <Text
215 key={`prompt:${index}`}
216 color="suggestion"
217 wrap={isExpanded ? "wrap" : "truncate-end"}
218 >
219 {line === "" ? " " : line}
220 </Text>
221 ))}
222 {hidden <= 0 ? undefined : (
223 <Button
224 key="prompt:toggle"
225 plain
226 dimColor
227 label={isExpanded ? "▾ collapse" : `▸ show ${hidden} more lines`}
228 onPress={onToggle}
229 />
230 )}
231 </Box>
232 </Box>
233 );
234};
235
236const nameWidthOf = (entries: readonly Entry[]): number =>
237 Math.min(
238 MAX_NAME_WIDTH,
239 Math.max(
240 MIN_NAME_WIDTH,
241 ...entries.map((entry) =>
242 entry.kind === "tool" ? toolNameOf(entry.name).length : 0,
243 ),
244 ) + 2,
245 );
246
247const activityView = (
248 { Box, Text }: Kit,
249 entry: Entry,
250 index: number,
251 nameWidth: number,
252) => {
253 switch (entry.kind) {
254 case "tool": {
255 return (
256 <Box key={`activity:${index}`}>
257 <Box width={nameWidth} flexShrink={0}>
258 <Text bold color="permission" wrap="truncate-end">
259 {toolNameOf(entry.name)}
260 </Text>
261 </Box>
262 <Text wrap="truncate-end">{entry.summary}</Text>
263 </Box>
264 );
265 }
266 case "result": {
267 return (
268 <Box key={`activity:${index}`} paddingLeft={nameWidth}>
269 {entry.isError ? (
270 <Text color="error" wrap="truncate-end">
271 ✗ {entry.text}
272 </Text>
273 ) : (
274 <Text dimColor wrap="truncate-end">
275 ↳ {entry.text}
276 </Text>
277 )}
278 </Box>
279 );
280 }
281 case "text": {
282 const lines = entry.text.split("\n");
283 const hidden = lines.length - TEXT_LINES;
284
285 return (
286 <Box key={`activity:${index}`} flexDirection="column" marginTop={1}>
287 {lines.slice(0, TEXT_LINES).map((line, row) => (
288 <Text key={`text:${index}:${row}`} wrap="truncate-end">
289 {line === "" ? " " : line}
290 </Text>
291 ))}
292 {hidden <= 0 ? undefined : <Text dimColor>(+{hidden} lines)</Text>}
293 </Box>
294 );
295 }
296 case "prompt": {
297 return undefined;
298 }
299 }
300};
301
302export const detailView = (
303 kit: Kit,
304 detail: Detail | undefined,
305 view: DetailView,
306) => {
307 const { Box, Text } = kit;
308
309 if (detail === undefined) {
310 return <Text dimColor>Select an agent above.</Text>;
311 }
312
313 const prompt = detail.entries.find((entry) => entry.kind === "prompt");
314 const activity = detail.entries.filter((entry) => entry.kind !== "prompt");
315 const hidden = Math.max(0, activity.length - MAX_ACTIVITY);
316 const calls = activity.filter((entry) => entry.kind === "tool").length;
317 const shown = activity.slice(hidden);
318 const nameWidth = nameWidthOf(shown);
319
320 return (
321 <Box flexDirection="column">
322 {summaryView(kit, detail.summary)}
323 {headerView(kit, detail)}
324 {promptView(kit, prompt?.text, view)}
325 <Box flexDirection="column" marginTop={1}>
326 {sectionView(
327 kit,
328 "ACTIVITY",
329 calls === 0 ? undefined : `${calls} call${calls === 1 ? "" : "s"}`,
330 )}
331 <Box flexDirection="column" paddingLeft={2}>
332 {activity.length === 0 ? (
333 <Text dimColor>No output recorded yet.</Text>
334 ) : undefined}
335 {hidden === 0 ? undefined : (
336 <Text dimColor>… {hidden} earlier entries</Text>
337 )}
338 {shown.map((entry, index) =>
339 activityView(kit, entry, hidden + index, nameWidth),
340 )}
341 </Box>
342 </Box>
343 <Box marginTop={1}>
344 <Text dimColor wrap="truncate-end">
345 {detail.origin}
346 </Text>
347 </Box>
348 </Box>
349 );
350};
351hooks/summary.ts 78 lines1import type { Detail, Entry } from "./detail";
2
3const SUMMARY_LIMIT = 200;
4const PROMPT_CHARS = 3000;
5const ACTIVITY_ENTRIES = 40;
6const LINE_CHARS = 300;
7const SYSTEM_PROMPT =
8 "Summarize the state of a Claude Code subagent from the record given on stdin: what it is for, its progress and current state, and its latest output or result. Answer in Japanese plain text within 200 characters. No preamble, headings, lists or Markdown.";
9
10export const SUMMARY_TIMEOUT_MS = 120_000;
11
12export const SUMMARY_ARGV: readonly string[] = [
13 "claude",
14 "-p",
15 "--model",
16 "claude-haiku-5-5",
17 "--effort",
18 "xhigh",
19 "--no-session-persistence",
20 "--tools",
21 "",
22 "--disable-slash-commands",
23 "--strict-mcp-config",
24 "--system-prompt",
25 SYSTEM_PROMPT,
26];
27
28const clipOf = (text: string, limit: number): string => {
29 const chars = [...text.replaceAll(/\s+/g, " ").trim()];
30
31 return chars.length > limit
32 ? `${chars.slice(0, limit - 1).join("")}…`
33 : chars.join("");
34};
35
36const activityLineOf = (entry: Entry): string | undefined => {
37 switch (entry.kind) {
38 case "tool": {
39 return `- ${entry.name}: ${clipOf(entry.summary, LINE_CHARS)}`;
40 }
41 case "result": {
42 return ` ${entry.isError ? "error" : "result"}: ${clipOf(entry.text, LINE_CHARS)}`;
43 }
44 case "text": {
45 return `- said: ${clipOf(entry.text, LINE_CHARS)}`;
46 }
47 case "prompt": {
48 return undefined;
49 }
50 }
51};
52
53export const summaryInputOf = (detail: Detail): string => {
54 const prompt = detail.entries.find((entry) => entry.kind === "prompt");
55 const activity = detail.entries
56 .filter((entry) => entry.kind !== "prompt")
57 .slice(-ACTIVITY_ENTRIES)
58 .flatMap((entry) => activityLineOf(entry) ?? []);
59
60 return [
61 `Agent: ${detail.label}`,
62 `Kind: ${detail.context.join(", ")}`,
63 `Status: ${detail.status}, elapsed ${detail.elapsed}`,
64 `Model: ${[detail.model, detail.effort].filter(Boolean).join(" ")}; ${detail.stats}`,
65 "",
66 "Task prompt:",
67 prompt === undefined
68 ? "(not recorded)"
69 : [...prompt.text].slice(0, PROMPT_CHARS).join(""),
70 "",
71 "Recent activity (oldest first):",
72 ...(activity.length === 0 ? ["(none recorded)"] : activity),
73 ].join("\n");
74};
75
76export const summaryTextOf = (stdout: string): string =>
77 clipOf(stdout, SUMMARY_LIMIT);
78hooks/disk.ts 502 lines1const RECENT_RUN_MS = 24 * 60 * 60 * 1000;
2const READ_LIMIT = 3_500_000;
3const HEAD_BYTES = 262_144;
4const TAIL_BYTES = 3_000_000;
5const MAX_RECENT_RUNS = 40;
6const RUN_NAME =
7 /"workflowName":"((?:[^"\\]|\\.){1,200})","runId":"(wf_[0-9a-f-]+)"/g;
8
9export interface DiskEntry {
10 name: string;
11 kind: string;
12 mtimeMs: number;
13}
14
15export interface Disk {
16 read: (path: string) => Promise<string>;
17 list: (path: string) => Promise<readonly DiskEntry[]>;
18 exists: (path: string) => Promise<boolean>;
19 stat: (path: string) => Promise<{ mtimeMs: number; size: number }>;
20 run: (
21 argv: readonly string[],
22 ) => Promise<{ exitCode: number; stdout: string }>;
23 configured: () => Promise<string | undefined>;
24 home: () => Promise<string | undefined>;
25 sessionId: () => Promise<string>;
26 roots: () => Promise<readonly string[]>;
27}
28
29export interface SessionPaths {
30 transcript: string;
31 dir: string;
32}
33
34export interface RecentRun {
35 run: string;
36 isEnded: boolean;
37}
38
39export interface RunAgent {
40 id: string;
41 label?: string;
42 phase?: string;
43 isDone: boolean;
44 isRetried: boolean;
45 startedAt?: number;
46 endedAt?: number;
47}
48
49export interface RunScan {
50 active: readonly { run: string; agents: readonly RunAgent[] }[];
51 ended: readonly string[];
52}
53
54export interface TranscriptRow {
55 type: string;
56 role: string;
57 content: readonly { type: string; [field: string]: unknown }[];
58}
59
60export interface Transcript {
61 rows: readonly TranscriptRow[];
62 model?: string;
63 effort?: string;
64 steps: number;
65 toolCalls: number;
66 input: number;
67 output: number;
68}
69
70export interface AgentMeta {
71 label?: string;
72 type?: string;
73 phase?: string;
74 model?: string;
75 run?: string;
76}
77
78const findFirst = async <T>(
79 items: readonly T[],
80 predicate: (item: T) => Promise<boolean>,
81): Promise<T | undefined> => {
82 const [head, ...rest] = items;
83
84 if (head === undefined) {
85 return undefined;
86 }
87
88 return (await predicate(head).catch(() => false))
89 ? head
90 : findFirst(rest, predicate);
91};
92
93const projectDirOf = (root: string): string =>
94 root.replaceAll(/[^a-zA-Z0-9]/g, "-");
95
96const configDirOf = async (disk: Disk): Promise<string | undefined> => {
97 const configured = await disk.configured();
98
99 if (configured !== undefined && configured !== "") {
100 return configured;
101 }
102
103 const home = await disk.home();
104
105 return home === undefined || home === "" ? undefined : `${home}/.claude`;
106};
107
108export const sessionPathsOf = async (
109 disk: Disk,
110): Promise<SessionPaths | undefined> => {
111 const configDir = await configDirOf(disk);
112
113 if (configDir === undefined) {
114 return undefined;
115 }
116
117 const projects = `${configDir}/projects`;
118 const id = await disk.sessionId();
119 const roots = await disk.roots();
120 const entries = await disk.list(projects).catch(() => []);
121 const named = roots.map((root) => `${projects}/${projectDirOf(root)}`);
122 const listed = entries
123 .filter((entry) => entry.kind === "dir")
124 .map((entry) => `${projects}/${entry.name}`);
125 const found = await findFirst([...new Set([...named, ...listed])], (base) =>
126 disk.exists(`${base}/${id}.jsonl`),
127 );
128
129 return found === undefined
130 ? undefined
131 : { transcript: `${found}/${id}.jsonl`, dir: `${found}/${id}` };
132};
133
134export const recentRunsOf = async (
135 disk: Disk,
136 paths: SessionPaths,
137 now: number,
138): Promise<readonly RecentRun[]> => {
139 const [folders, records] = await Promise.all([
140 disk.list(`${paths.dir}/subagents/workflows`).catch(() => []),
141 disk.list(`${paths.dir}/workflows`).catch(() => []),
142 ]);
143 const ended = new Map(
144 records
145 .filter(
146 (entry) =>
147 entry.kind === "file" &&
148 entry.name.startsWith("wf_") &&
149 entry.name.endsWith(".json"),
150 )
151 .map((entry) => [entry.name.slice(0, -".json".length), entry.mtimeMs]),
152 );
153 const open = await Promise.all(
154 folders
155 .filter(
156 (entry) =>
157 entry.kind === "dir" &&
158 entry.name.startsWith("wf_") &&
159 !ended.has(entry.name),
160 )
161 .map(async (entry) => {
162 const journal = await disk
163 .stat(`${paths.dir}/subagents/workflows/${entry.name}/journal.jsonl`)
164 .catch(() => undefined);
165
166 return {
167 run: entry.name,
168 isEnded: false,
169 mtimeMs: journal?.mtimeMs ?? 0,
170 };
171 }),
172 );
173 const closed = [...ended].map(([run, mtimeMs]) => ({
174 run,
175 isEnded: true,
176 mtimeMs,
177 }));
178
179 return [...open, ...closed]
180 .filter((one) => now - one.mtimeMs < RECENT_RUN_MS)
181 .toSorted((a, b) => b.mtimeMs - a.mtimeMs)
182 .slice(0, MAX_RECENT_RUNS)
183 .map(({ run, isEnded }) => ({ run, isEnded }));
184};
185
186const stringOf = (value: unknown): string | undefined =>
187 typeof value === "string" && value !== "" ? value : undefined;
188
189const recordOf = (line: string): Record<string, unknown> | undefined => {
190 try {
191 const parsed: unknown = JSON.parse(line);
192
193 return typeof parsed === "object" && parsed !== null
194 ? (parsed as Record<string, unknown>)
195 : undefined;
196 } catch {
197 return undefined;
198 }
199};
200
201const runAgentsOf = (
202 journal: string,
203 mtimes: ReadonlyMap<string, number>,
204): RunAgent[] => {
205 const events = journal.split("\n").flatMap((line) => {
206 const event = recordOf(line);
207 const agentId = stringOf(event?.agentId);
208
209 return event === undefined || agentId === undefined
210 ? []
211 : [
212 {
213 type: stringOf(event.type),
214 agentId,
215 label: stringOf(event.label),
216 phase: stringOf(event.phase),
217 },
218 ];
219 });
220 const done = new Set(
221 events
222 .filter((event) => event.type === "result")
223 .map((event) => event.agentId),
224 );
225 const started = new Map(
226 events
227 .filter((event) => event.type === "started")
228 .map((event) => [event.agentId, event] as const),
229 );
230
231 const latest = new Map(
232 [...started.values()].map((event) => [event.label, event.agentId] as const),
233 );
234
235 return [...started.values()].map((event) => {
236 const isRetried =
237 !done.has(event.agentId) &&
238 event.label !== undefined &&
239 latest.get(event.label) !== event.agentId;
240 const isDone = done.has(event.agentId) || isRetried;
241
242 return {
243 id: event.agentId,
244 label: event.label,
245 phase: event.phase,
246 isDone,
247 isRetried,
248 startedAt: mtimes.get(`agent-${event.agentId}.meta.json`),
249 endedAt: isDone ? mtimes.get(`agent-${event.agentId}.jsonl`) : undefined,
250 };
251 });
252};
253
254const runScanOf = async (
255 disk: Disk,
256 paths: SessionPaths,
257 run: string,
258): Promise<RunScan> => {
259 if (await disk.exists(`${paths.dir}/workflows/${run}.json`)) {
260 return { active: [], ended: [run] };
261 }
262
263 const base = `${paths.dir}/subagents/workflows/${run}`;
264 const [entries, journal] = await Promise.all([
265 disk.list(base),
266 disk.read(`${base}/journal.jsonl`),
267 ]);
268 const mtimes = new Map(
269 entries
270 .filter((entry) => entry.mtimeMs > 0)
271 .map((entry) => [entry.name, entry.mtimeMs]),
272 );
273
274 return {
275 active: [{ run, agents: runAgentsOf(journal, mtimes) }],
276 ended: [],
277 };
278};
279
280export const runScansOf = async (
281 disk: Disk,
282 paths: SessionPaths,
283 runs: readonly string[],
284): Promise<RunScan> => {
285 const scans = await Promise.all(
286 runs.map((run) =>
287 runScanOf(disk, paths, run).catch(
288 (): RunScan => ({ active: [], ended: [] }),
289 ),
290 ),
291 );
292
293 return {
294 active: scans.flatMap((scan) => scan.active),
295 ended: scans.flatMap((scan) => scan.ended),
296 };
297};
298
299export const transcriptPathOf = (
300 paths: SessionPaths,
301 agentId: string,
302 run?: string,
303): string =>
304 run === undefined
305 ? `${paths.dir}/subagents/agent-${agentId}.jsonl`
306 : `${paths.dir}/subagents/workflows/${run}/agent-${agentId}.jsonl`;
307
308const numberOf = (value: unknown): number =>
309 typeof value === "number" && Number.isFinite(value) ? value : 0;
310
311const blocksOf = (content: unknown): TranscriptRow["content"] => {
312 if (typeof content === "string") {
313 return [{ type: "text", text: content }];
314 }
315
316 return Array.isArray(content)
317 ? content.filter(
318 (block): block is { type: string } =>
319 typeof block === "object" &&
320 block !== null &&
321 typeof (block as Record<string, unknown>).type === "string",
322 )
323 : [];
324};
325
326const rowOf = (record: Record<string, unknown>): TranscriptRow | undefined => {
327 const message = record.message as Record<string, unknown> | undefined;
328 const role = stringOf(message?.role);
329
330 if (
331 (record.type !== "user" && record.type !== "assistant") ||
332 record.isMeta === true ||
333 role === undefined
334 ) {
335 return undefined;
336 }
337
338 return { type: role, role, content: blocksOf(message?.content) };
339};
340
341const transcriptFrom = (
342 records: readonly Record<string, unknown>[],
343 opening: readonly TranscriptRow[],
344): Transcript => {
345 const requests = records.filter((record) => record.type === "api-request");
346 const params = requests.at(-1)?.params as Record<string, unknown> | undefined;
347 const config = params?.output_config as Record<string, unknown> | undefined;
348 const replies = records
349 .filter((record) => record.type === "assistant")
350 .map((record) => record.message as Record<string, unknown> | undefined);
351 const usages = new Map(
352 replies.flatMap((message) => {
353 const id = stringOf(message?.id);
354
355 return id === undefined
356 ? []
357 : [[id, message?.usage as Record<string, unknown> | undefined]];
358 }),
359 );
360 const rows = records.flatMap((record) => rowOf(record) ?? []);
361
362 return {
363 rows: [...opening, ...rows],
364 model: stringOf(params?.model) ?? stringOf(replies.at(-1)?.model),
365 effort: stringOf(config?.effort),
366 steps: usages.size,
367 toolCalls: replies.reduce(
368 (count, message) =>
369 count +
370 blocksOf(message?.content).filter((block) => block.type === "tool_use")
371 .length,
372 0,
373 ),
374 input: [...usages.values()].reduce(
375 (total, usage) =>
376 total +
377 numberOf(usage?.input_tokens) +
378 numberOf(usage?.cache_read_input_tokens) +
379 numberOf(usage?.cache_creation_input_tokens),
380 0,
381 ),
382 output: [...usages.values()].reduce(
383 (total, usage) => total + numberOf(usage?.output_tokens),
384 0,
385 ),
386 };
387};
388
389const recordsOf = (text: string, isCut: boolean): Record<string, unknown>[] =>
390 (isCut ? text.split("\n").slice(1) : text.split("\n")).flatMap((line) => {
391 const record = recordOf(line);
392
393 return record === undefined ? [] : [record];
394 });
395
396export const transcriptOf = async (
397 disk: Disk,
398 path: string,
399): Promise<Transcript> => {
400 const { size } = await disk.stat(path);
401
402 if (size <= READ_LIMIT) {
403 return transcriptFrom(recordsOf(await disk.read(path), false), []);
404 }
405
406 const [head, tail] = await Promise.all([
407 disk.run(["head", "-c", String(HEAD_BYTES), path]),
408 disk.run(["tail", "-c", String(TAIL_BYTES), path]),
409 ]);
410 const opening = recordsOf(head.stdout, false)
411 .flatMap((record) => rowOf(record) ?? [])
412 .filter((row) => row.role === "user")
413 .slice(0, 1);
414
415 return transcriptFrom(recordsOf(tail.stdout, true), opening);
416};
417
418const parsedMetaOf = (text: string, run?: string): AgentMeta | undefined => {
419 const parsed: unknown = JSON.parse(text);
420
421 if (typeof parsed !== "object" || parsed === null) {
422 return undefined;
423 }
424
425 const record = parsed as Record<string, unknown>;
426
427 return {
428 label: stringOf(record.description),
429 type: stringOf(record.agentType),
430 phase: stringOf(record.workflowPhase),
431 model: stringOf(record.model),
432 run,
433 };
434};
435
436export const agentMetaOf = async (
437 disk: Disk,
438 paths: SessionPaths,
439 runs: readonly string[],
440 agentId: string,
441): Promise<AgentMeta | undefined> => {
442 const candidates: readonly { path: string; run?: string }[] = [
443 { path: `${paths.dir}/subagents/agent-${agentId}.meta.json` },
444 ...runs.map((run) => ({
445 path: `${paths.dir}/subagents/workflows/${run}/agent-${agentId}.meta.json`,
446 run,
447 })),
448 ];
449 const found = await findFirst(candidates, (candidate) =>
450 disk.exists(candidate.path),
451 );
452
453 if (found === undefined) {
454 return undefined;
455 }
456
457 return parsedMetaOf(await disk.read(found.path), found.run);
458};
459
460const unescapedOf = (text: string): string => {
461 try {
462 const parsed: unknown = JSON.parse(`"${text}"`);
463
464 return typeof parsed === "string" ? parsed : text;
465 } catch {
466 return text;
467 }
468};
469
470export const runNamesOf = async (
471 disk: Disk,
472 paths: SessionPaths,
473): Promise<ReadonlyMap<string, string>> => {
474 const scanned = await disk
475 .run([
476 "perl",
477 "-ne",
478 String.raw`next unless index($_, q("workflowName":")) >= 0; print "$&\n" while /"workflowName":"[^"]{1,200}","runId":"wf_[0-9a-f-]+"/g`,
479 paths.transcript,
480 ])
481 .catch(() => ({ exitCode: 2, stdout: "" }));
482 const { exitCode, stdout } =
483 scanned.exitCode === 0
484 ? scanned
485 : await disk.run([
486 "grep",
487 "-o",
488 '"workflowName":"[^"]*","runId":"wf_[0-9a-f-]*"',
489 paths.transcript,
490 ]);
491
492 if (exitCode > 1) {
493 return new Map();
494 }
495
496 return new Map(
497 [...stdout.matchAll(RUN_NAME)].map(
498 ([, name = "", runId = ""]) => [runId, unescapedOf(name)] as const,
499 ),
500 );
501};
502