@mrclrchtr/supi-review 7.3.0 → 7.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +4 -0
  2. package/node_modules/@mrclrchtr/supi-agent-runtime/README.md +10 -0
  3. package/node_modules/@mrclrchtr/supi-agent-runtime/node_modules/@mrclrchtr/supi-core/package.json +1 -1
  4. package/node_modules/@mrclrchtr/supi-agent-runtime/package.json +7 -3
  5. package/node_modules/@mrclrchtr/supi-agent-runtime/src/api.ts +37 -1
  6. package/node_modules/@mrclrchtr/supi-agent-runtime/src/run.ts +151 -21
  7. package/node_modules/@mrclrchtr/supi-agent-runtime/src/session/agent-run-registry-types.ts +95 -0
  8. package/node_modules/@mrclrchtr/supi-agent-runtime/src/session/agent-run-registry.ts +372 -0
  9. package/node_modules/@mrclrchtr/supi-agent-runtime/src/session/transcript-format.ts +184 -0
  10. package/node_modules/@mrclrchtr/supi-agent-runtime/src/session/transcript-store.ts +284 -0
  11. package/node_modules/@mrclrchtr/supi-agent-runtime/src/types.ts +22 -0
  12. package/node_modules/@mrclrchtr/supi-agent-runtime/src/ui/agents-command.ts +206 -0
  13. package/node_modules/@mrclrchtr/supi-agent-runtime/src/ui/agents-overlay-data.ts +78 -0
  14. package/node_modules/@mrclrchtr/supi-agent-runtime/src/ui/agents-overlay-render.ts +167 -0
  15. package/node_modules/@mrclrchtr/supi-agent-runtime/src/ui/agents-overlay.ts +400 -0
  16. package/node_modules/@mrclrchtr/supi-agent-runtime/src/ui/agents-run-list.ts +95 -0
  17. package/node_modules/@mrclrchtr/supi-agent-runtime/src/ui/agents-run-switcher.ts +29 -0
  18. package/node_modules/@mrclrchtr/supi-agent-runtime/src/ui/agents-run-viewer-input.ts +69 -0
  19. package/node_modules/@mrclrchtr/supi-agent-runtime/src/ui/agents-run-viewer-render.ts +246 -0
  20. package/node_modules/@mrclrchtr/supi-agent-runtime/src/ui/agents-run-viewer.ts +400 -0
  21. package/node_modules/@mrclrchtr/supi-agent-runtime/src/ui/agents-run-viewport.ts +112 -0
  22. package/node_modules/@mrclrchtr/supi-agent-runtime/src/ui/agents-steering-input.ts +50 -0
  23. package/node_modules/@mrclrchtr/supi-agent-runtime/src/ui/agents-transcript-context.ts +56 -0
  24. package/node_modules/@mrclrchtr/supi-agent-runtime/src/ui/agents-transcript-pane.ts +386 -0
  25. package/node_modules/@mrclrchtr/supi-agent-runtime/src/ui/agents-transcript-payload.ts +66 -0
  26. package/node_modules/@mrclrchtr/supi-agent-runtime/src/ui/agents-transcript.ts +380 -0
  27. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-code-runtime/package.json +1 -1
  28. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-core/package.json +1 -1
  29. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-lsp/node_modules/@mrclrchtr/supi-code-runtime/package.json +1 -1
  30. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-lsp/node_modules/@mrclrchtr/supi-core/package.json +1 -1
  31. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-lsp/node_modules/ignore/index.js +25 -6
  32. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-lsp/node_modules/ignore/legacy.js +22 -6
  33. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-lsp/node_modules/ignore/package.json +1 -1
  34. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-jsonrpc/lib/common/connection.js +2 -2
  35. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-jsonrpc/lib/node/main.d.ts +1 -0
  36. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-jsonrpc/lib/node/main.js +7 -0
  37. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-jsonrpc/package.json +2 -2
  38. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-languageserver-protocol/lib/common/protocol.inlayHint.d.ts +2 -2
  39. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-languageserver-protocol/lib/common/protocol.inlineCompletion.d.ts +2 -2
  40. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-languageserver-protocol/lib/common/protocol.inlineValue.d.ts +2 -2
  41. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-languageserver-protocol/package.json +4 -4
  42. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-languageserver-types/package.json +2 -2
  43. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-lsp/package.json +3 -3
  44. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-tree-sitter/node_modules/@mrclrchtr/supi-code-runtime/package.json +1 -1
  45. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-tree-sitter/node_modules/@mrclrchtr/supi-core/package.json +1 -1
  46. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-tree-sitter/package.json +3 -3
  47. package/node_modules/@mrclrchtr/supi-code-intelligence/package.json +5 -5
  48. package/node_modules/@mrclrchtr/supi-core/package.json +1 -1
  49. package/package.json +4 -4
  50. package/src/review.ts +5 -2
  51. package/src/tool/review_run/child-session.ts +29 -7
  52. package/src/tool/review_run/execute.ts +6 -1
  53. package/src/tool/review_run/execution.ts +6 -0
  54. package/src/tool/review_run/register.ts +3 -1
  55. package/src/tool/review_run/runner.ts +40 -0
  56. package/src/tool/review_run/workflow.ts +7 -1
  57. package/src/tui/review-command.ts +74 -3
  58. package/src/types.ts +5 -0
@@ -0,0 +1,372 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import type { AgentRunHandle, AgentRunSessionView } from "../types.ts";
3
+ import type {
4
+ AgentRunDisplayConversation,
5
+ AgentRunDisplayMetadata,
6
+ AgentRunDisplayResult,
7
+ AgentRunRegistration,
8
+ AgentRunRegistryRun,
9
+ AgentRunRegistrySnapshot,
10
+ AgentRunStopResult,
11
+ } from "./agent-run-registry-types.ts";
12
+ import {
13
+ AgentRunTranscriptCapture,
14
+ type AgentRunTranscriptMetadata,
15
+ AgentRunTranscriptStore,
16
+ } from "./transcript-store.ts";
17
+
18
+ interface LiveRun {
19
+ readonly handle: AgentRunHandle<unknown>;
20
+ readonly getConversation?: AgentRunRegistration["getConversation"];
21
+ readonly getRecentActivity?: AgentRunRegistration["getRecentActivity"];
22
+ unsubscribeProgress?: () => void;
23
+ unsubscribeSession?: () => void;
24
+ }
25
+
26
+ interface RegisteredRun {
27
+ readonly runKey: string;
28
+ readonly batchId: string;
29
+ readonly generation: number;
30
+ readonly metadata: AgentRunDisplayMetadata;
31
+ readonly transcript?: AgentRunTranscriptCapture;
32
+ readonly acceptedSteering: string[];
33
+ live?: LiveRun;
34
+ status: AgentRunRegistryRun["status"];
35
+ finishedAt?: number;
36
+ turns: number;
37
+ toolUses: number;
38
+ usage?: AgentRunRegistryRun["usage"];
39
+ conversation?: AgentRunDisplayConversation;
40
+ recentActivity?: readonly string[];
41
+ result?: AgentRunDisplayResult;
42
+ }
43
+
44
+ type RegistryListener = (snapshot: AgentRunRegistrySnapshot) => void;
45
+
46
+ /** Session-local registry and transcript owner for all managed Agent Runs. */
47
+ export class AgentRunRegistry {
48
+ readonly #runs = new Map<string, RegisteredRun>();
49
+ readonly #listeners = new Set<RegistryListener>();
50
+ #sessionGeneration = 0;
51
+ #sessionOpen = true;
52
+ #transcriptStore = new AgentRunTranscriptStore();
53
+
54
+ /** Open registry writes for a new containing session. */
55
+ openSession(): void {
56
+ this.#sessionOpen = true;
57
+ }
58
+
59
+ /** Start one temporary transcript without affecting Agent Run execution. */
60
+ createTranscriptCapture(
61
+ metadata: AgentRunTranscriptMetadata,
62
+ systemPrompt = "",
63
+ toolRenderers: AgentRunTranscriptCapture["toolRenderers"] = [],
64
+ ): AgentRunTranscriptCapture {
65
+ if (!this.#sessionOpen) {
66
+ return new AgentRunTranscriptCapture({
67
+ metadata,
68
+ systemPrompt,
69
+ toolRenderers,
70
+ getDirectory: async () => {
71
+ throw new Error("The containing session is closed.");
72
+ },
73
+ });
74
+ }
75
+ return this.#transcriptStore.createCapture(metadata, systemPrompt, toolRenderers, () =>
76
+ this.#publish(),
77
+ );
78
+ }
79
+
80
+ /** Register one run before its initial prompt starts. */
81
+ register(registration: AgentRunRegistration): string {
82
+ const runKey = registration.metadata.runKey ?? randomUUID();
83
+ const batchId = registration.metadata.batchId ?? "default";
84
+ if (!this.#sessionOpen) {
85
+ void registration.handle.stop().catch(() => undefined);
86
+ return runKey;
87
+ }
88
+ this.#remove(runKey);
89
+ const live: LiveRun = {
90
+ handle: registration.handle,
91
+ ...(registration.getConversation ? { getConversation: registration.getConversation } : {}),
92
+ ...(registration.getRecentActivity
93
+ ? { getRecentActivity: registration.getRecentActivity }
94
+ : {}),
95
+ };
96
+ const run: RegisteredRun = {
97
+ runKey,
98
+ batchId,
99
+ generation: this.#sessionGeneration,
100
+ metadata: {
101
+ ...registration.metadata,
102
+ runKey,
103
+ batchId,
104
+ tools: [...registration.metadata.tools],
105
+ },
106
+ ...(registration.transcript ? { transcript: registration.transcript } : {}),
107
+ acceptedSteering: [],
108
+ live,
109
+ status: "starting",
110
+ turns: 0,
111
+ toolUses: 0,
112
+ };
113
+ this.#runs.set(runKey, run);
114
+ live.unsubscribeProgress = registration.handle.subscribe((progress) => {
115
+ if (!this.#isCurrent(run)) return;
116
+ run.status = progress.status;
117
+ run.turns = progress.turns;
118
+ run.toolUses = progress.toolUses;
119
+ run.usage = progress.usage;
120
+ this.#publish();
121
+ });
122
+ void registration.handle.result.then(
123
+ (outcome) => {
124
+ if (!this.#isCurrent(run)) return;
125
+ this.#finishRun(
126
+ run,
127
+ outcome.kind === "success" ? "completed" : outcome.kind,
128
+ outcome.usage,
129
+ outcome.kind === "failed" ? outcome.failureCode : undefined,
130
+ );
131
+ },
132
+ () => {
133
+ if (!this.#isCurrent(run)) return;
134
+ this.#finishRun(run, "failed", undefined, "unexpected-runner-failure");
135
+ },
136
+ );
137
+ this.#publish();
138
+ return runKey;
139
+ }
140
+
141
+ /** Attach full transcript capture to a read-only child-session view. */
142
+ attachSession(runKey: string, session: AgentRunSessionView): () => void {
143
+ const run = this.#runs.get(runKey);
144
+ if (!run || !this.#isCurrent(run)) return () => undefined;
145
+ const live = run.live;
146
+ if (!live) return () => undefined;
147
+ const transcript = run.transcript;
148
+ transcript?.updateSession(session.systemPrompt, session.getToolRenderers());
149
+ const unsubscribe = session.subscribe((event) => {
150
+ if (!this.#isCurrent(run)) return;
151
+ transcript?.observe(event, session.systemPrompt, session.getToolRenderers());
152
+ this.#publish();
153
+ });
154
+ live.unsubscribeSession?.();
155
+ live.unsubscribeSession = unsubscribe;
156
+ this.#publish();
157
+ return () => {
158
+ if (live.unsubscribeSession !== unsubscribe) return;
159
+ live.unsubscribeSession = undefined;
160
+ unsubscribe();
161
+ };
162
+ }
163
+
164
+ /** Set caller-owned, human-only display details after the run settles. */
165
+ setDisplayResult(runKey: string, result: AgentRunDisplayResult): void {
166
+ const run = this.#runs.get(runKey);
167
+ if (!run || !this.#isCurrent(run)) return;
168
+ run.result = { ...run.result, ...result };
169
+ this.#publish();
170
+ }
171
+
172
+ /** Notify the viewer after caller-owned live metadata changes. */
173
+ refresh(): void {
174
+ this.#publish();
175
+ }
176
+
177
+ /** Return the current session-local run list. */
178
+ snapshot(): AgentRunRegistrySnapshot {
179
+ return { runs: [...this.#runs.values()].map((run) => this.#snapshotRun(run)) };
180
+ }
181
+
182
+ /** Observe run changes; deliver the current snapshot at once. */
183
+ subscribe(listener: RegistryListener): () => void {
184
+ this.#listeners.add(listener);
185
+ try {
186
+ listener(this.snapshot());
187
+ } catch {
188
+ // Viewer failures must not change Agent Run lifecycle semantics.
189
+ }
190
+ return () => this.#listeners.delete(listener);
191
+ }
192
+
193
+ /** Queue steering only for the selected run during its initial active prompt. */
194
+ async steer(runKey: string, message: string): Promise<"accepted" | "not-running"> {
195
+ const run = this.#runs.get(runKey);
196
+ const handle = run?.live?.handle;
197
+ if (run?.status !== "running" || !handle?.steeringAvailable) {
198
+ return "not-running";
199
+ }
200
+ const result = await handle.steer(message);
201
+ if (
202
+ result === "accepted" &&
203
+ this.#isCurrent(run) &&
204
+ run.status === "running" &&
205
+ run.live?.handle === handle
206
+ ) {
207
+ run.acceptedSteering.push(message);
208
+ this.#publish();
209
+ }
210
+ return result;
211
+ }
212
+
213
+ /** Return the steering messages accepted through the viewer. */
214
+ acceptedSteering(runKey: string): readonly string[] {
215
+ return [...(this.#runs.get(runKey)?.acceptedSteering ?? [])];
216
+ }
217
+
218
+ /** Stop only the selected active run. */
219
+ async stop(runKey: string): Promise<AgentRunStopResult> {
220
+ const run = this.#runs.get(runKey);
221
+ const handle = run?.live?.handle;
222
+ if (
223
+ !run ||
224
+ !handle ||
225
+ (run.status !== "starting" && run.status !== "running") ||
226
+ !this.#isCurrent(run)
227
+ ) {
228
+ return "not-running";
229
+ }
230
+ run.status = "stopping";
231
+ this.#publish();
232
+ await handle.stop();
233
+ return "accepted";
234
+ }
235
+
236
+ /** Whether any registered run is still active. */
237
+ hasActive(): boolean {
238
+ return [...this.#runs.values()].some((run) => isActive(run.status));
239
+ }
240
+
241
+ /** Stop all active runs and wait for their bounded disposal. */
242
+ async cancelAll(): Promise<void> {
243
+ await Promise.allSettled(
244
+ [...this.#runs.values()]
245
+ .filter((run) => isActive(run.status))
246
+ .flatMap((run) => (run.live ? [run.live.handle.stop()] : [])),
247
+ );
248
+ }
249
+
250
+ /** Clear session state and remove all temporary transcript files. */
251
+ async clear(): Promise<void> {
252
+ this.#sessionOpen = false;
253
+ this.#sessionGeneration++;
254
+ const runs = [...this.#runs.values()];
255
+ const activeHandles = runs.flatMap((run) =>
256
+ isActive(run.status) && run.live ? [run.live.handle] : [],
257
+ );
258
+ this.#runs.clear();
259
+ for (const run of runs) this.#releaseLive(run);
260
+ await Promise.allSettled(activeHandles.map((handle) => handle.stop()));
261
+ const store = this.#transcriptStore;
262
+ this.#transcriptStore = new AgentRunTranscriptStore();
263
+ await store.dispose();
264
+ this.#publish();
265
+ }
266
+
267
+ #snapshotRun(run: RegisteredRun): AgentRunRegistryRun {
268
+ const live = run.live;
269
+ const conversation = live ? this.#readConversation(run) : run.conversation;
270
+ const recentActivity = live ? this.#readRecentActivity(live) : run.recentActivity;
271
+ return {
272
+ ...run.metadata,
273
+ runKey: run.runKey,
274
+ batchId: run.batchId,
275
+ active: isActive(run.status),
276
+ status: run.status,
277
+ ...(run.finishedAt === undefined ? {} : { finishedAt: run.finishedAt }),
278
+ steeringAvailable: run.status === "running" && (live?.handle.steeringAvailable ?? false),
279
+ turns: run.turns,
280
+ toolUses: run.toolUses,
281
+ ...(run.usage ? { usage: run.usage } : {}),
282
+ ...(recentActivity ? { recentActivity } : {}),
283
+ ...(run.transcript ? { transcriptSource: run.transcript } : {}),
284
+ ...(conversation ? { conversation } : {}),
285
+ ...(run.result ? { result: run.result } : {}),
286
+ };
287
+ }
288
+
289
+ #publish(): void {
290
+ if (this.#listeners.size === 0) return;
291
+ const snapshot = this.snapshot();
292
+ for (const listener of this.#listeners) {
293
+ try {
294
+ listener(snapshot);
295
+ } catch {
296
+ // Viewer failures must not change Agent Run lifecycle semantics.
297
+ }
298
+ }
299
+ }
300
+
301
+ #isCurrent(run: RegisteredRun): boolean {
302
+ return (
303
+ this.#sessionOpen &&
304
+ run.generation === this.#sessionGeneration &&
305
+ this.#runs.get(run.runKey) === run
306
+ );
307
+ }
308
+
309
+ #finishRun(
310
+ run: RegisteredRun,
311
+ status: AgentRunRegistryRun["status"],
312
+ usage: AgentRunRegistryRun["usage"],
313
+ failureCode?: string,
314
+ ): void {
315
+ run.status = status;
316
+ run.finishedAt = Date.now();
317
+ run.usage = usage ?? run.usage;
318
+ if (failureCode) run.result = { ...run.result, failureCode };
319
+ if (run.live) {
320
+ run.conversation = this.#readConversation(run);
321
+ run.recentActivity = this.#readRecentActivity(run.live);
322
+ this.#releaseLive(run);
323
+ }
324
+ this.#publish();
325
+ }
326
+
327
+ #readConversation(run: RegisteredRun): AgentRunDisplayConversation | undefined {
328
+ try {
329
+ const conversation = run.live?.getConversation?.([...run.acceptedSteering]);
330
+ return conversation ? copyConversation(conversation) : undefined;
331
+ } catch {
332
+ return undefined;
333
+ }
334
+ }
335
+
336
+ #readRecentActivity(live: LiveRun): readonly string[] | undefined {
337
+ try {
338
+ const activity = live.getRecentActivity?.();
339
+ return activity ? [...activity] : undefined;
340
+ } catch {
341
+ return undefined;
342
+ }
343
+ }
344
+
345
+ #releaseLive(run: RegisteredRun): void {
346
+ run.acceptedSteering.length = 0;
347
+ const live = run.live;
348
+ if (!live) return;
349
+ live.unsubscribeProgress?.();
350
+ live.unsubscribeSession?.();
351
+ run.live = undefined;
352
+ }
353
+
354
+ #remove(runKey: string): void {
355
+ const previous = this.#runs.get(runKey);
356
+ if (previous) this.#releaseLive(previous);
357
+ this.#runs.delete(runKey);
358
+ }
359
+ }
360
+
361
+ function isActive(status: AgentRunRegistryRun["status"]): boolean {
362
+ return status === "starting" || status === "running" || status === "stopping";
363
+ }
364
+
365
+ function copyConversation(conversation: AgentRunDisplayConversation): AgentRunDisplayConversation {
366
+ return {
367
+ entries: conversation.entries.map((entry) => ({ ...entry })),
368
+ omittedEntryCount: conversation.omittedEntryCount,
369
+ omittedCharacterCount: conversation.omittedCharacterCount,
370
+ textTruncated: conversation.textTruncated,
371
+ };
372
+ }
@@ -0,0 +1,184 @@
1
+ import type { AgentSessionEvent } from "@earendil-works/pi-coding-agent";
2
+ import type { AgentRunMessage } from "../types.ts";
3
+ import type {
4
+ AgentRunTranscriptDocument,
5
+ AgentRunTranscriptMetadata,
6
+ AgentRunTranscriptOperation,
7
+ AgentRunTranscriptStatus,
8
+ } from "./transcript-store.ts";
9
+
10
+ interface HeaderRecord {
11
+ readonly kind: "header";
12
+ readonly metadata: AgentRunTranscriptMetadata;
13
+ readonly systemPrompt: string;
14
+ readonly occurredAt: number;
15
+ }
16
+
17
+ interface MessageRecord {
18
+ readonly kind: "message";
19
+ readonly message: AgentRunMessage;
20
+ }
21
+
22
+ interface PromptRecord {
23
+ readonly kind: "system-prompt";
24
+ readonly text: string;
25
+ readonly occurredAt: number;
26
+ }
27
+
28
+ interface OperationRecord {
29
+ readonly kind: "operation";
30
+ readonly operation: AgentRunTranscriptOperation;
31
+ }
32
+
33
+ interface StatusRecord {
34
+ readonly kind: "status";
35
+ readonly status: AgentRunTranscriptStatus;
36
+ }
37
+
38
+ export type TranscriptRecord =
39
+ | HeaderRecord
40
+ | MessageRecord
41
+ | PromptRecord
42
+ | OperationRecord
43
+ | StatusRecord;
44
+
45
+ const excludedField =
46
+ /^(?:.*api[_-]?(?:key|token|secret|credentials?)|token|bearer|authorization|auth.*|access[_-]?token|refresh[_-]?token|session[_-]?token|bearer[_-]?token|client[_-]?secret|provider[_-]?(?:auth|token|secret|credentials?)|secret|credentials?|password|cookie|set-cookie|.*headers?|providerMetadata|providerResponse|.*debug.*|transport.*)$/i;
47
+
48
+ /** Remove credentials and provider debug data from a transcript message. */
49
+ export function sanitizeMessage(message: unknown): AgentRunMessage {
50
+ return sanitizeValue(message) as AgentRunMessage;
51
+ }
52
+
53
+ function sanitizeValue(value: unknown): unknown {
54
+ if (Array.isArray(value)) return value.map(sanitizeValue);
55
+ if (!value || typeof value !== "object") return value;
56
+ const output: Record<string, unknown> = {};
57
+ for (const [key, child] of Object.entries(value)) {
58
+ if (excludedField.test(key)) continue;
59
+ output[key] = sanitizeValue(child);
60
+ }
61
+ return output;
62
+ }
63
+
64
+ /** Read transcript records and flag malformed storage as incomplete. */
65
+ export function parseTranscript(
66
+ content: string,
67
+ fallback: AgentRunTranscriptDocument,
68
+ ): AgentRunTranscriptDocument {
69
+ let metadata = fallback.metadata;
70
+ let systemPrompt = fallback.systemPrompt;
71
+ let systemPromptHistory = [...fallback.systemPromptHistory];
72
+ const messages: AgentRunMessage[] = [];
73
+ const operations: AgentRunTranscriptOperation[] = [];
74
+ let status = fallback.status;
75
+ for (const line of content.split("\n")) {
76
+ if (!line) continue;
77
+ let record: TranscriptRecord;
78
+ try {
79
+ record = JSON.parse(line) as TranscriptRecord;
80
+ } catch {
81
+ status = "incomplete";
82
+ break;
83
+ }
84
+ switch (record.kind) {
85
+ case "header":
86
+ metadata = record.metadata;
87
+ systemPrompt = record.systemPrompt;
88
+ systemPromptHistory = [{ occurredAt: record.occurredAt, text: record.systemPrompt }];
89
+ break;
90
+ case "message":
91
+ messages.push(record.message);
92
+ break;
93
+ case "system-prompt":
94
+ systemPrompt = record.text;
95
+ systemPromptHistory.push({ occurredAt: record.occurredAt, text: record.text });
96
+ break;
97
+ case "operation":
98
+ operations.push(record.operation);
99
+ break;
100
+ case "status":
101
+ status = record.status;
102
+ break;
103
+ }
104
+ }
105
+ return {
106
+ metadata,
107
+ systemPrompt,
108
+ systemPromptHistory,
109
+ messages,
110
+ operations,
111
+ status,
112
+ messageCount: messages.length,
113
+ };
114
+ }
115
+
116
+ /** Project only safe lifecycle fields from Pi's session events. */
117
+ export function projectOperation(
118
+ event: AgentSessionEvent,
119
+ ): AgentRunTranscriptOperation | undefined {
120
+ const occurredAt = Date.now();
121
+ switch (event.type) {
122
+ case "agent_start":
123
+ case "agent_settled":
124
+ case "turn_start":
125
+ return { type: event.type, occurredAt };
126
+ case "agent_end":
127
+ return { type: event.type, occurredAt, willRetry: event.willRetry };
128
+ case "turn_end":
129
+ return { type: event.type, occurredAt };
130
+ case "tool_execution_start":
131
+ return {
132
+ type: event.type,
133
+ occurredAt,
134
+ toolName: event.toolName,
135
+ toolCallId: event.toolCallId,
136
+ };
137
+ case "tool_execution_end":
138
+ return {
139
+ type: event.type,
140
+ occurredAt,
141
+ toolName: event.toolName,
142
+ toolCallId: event.toolCallId,
143
+ isError: event.isError,
144
+ };
145
+ case "compaction_start":
146
+ return { type: event.type, occurredAt, reason: event.reason };
147
+ case "compaction_end": {
148
+ const result = event.result;
149
+ return {
150
+ type: event.type,
151
+ occurredAt,
152
+ reason: event.reason,
153
+ aborted: event.aborted,
154
+ willRetry: event.willRetry,
155
+ ...(result
156
+ ? {
157
+ summary: result.summary,
158
+ firstKeptEntryId: result.firstKeptEntryId,
159
+ tokensBefore: result.tokensBefore,
160
+ ...(result.estimatedTokensAfter === undefined
161
+ ? {}
162
+ : { estimatedTokensAfter: result.estimatedTokensAfter }),
163
+ ...(result.usage === undefined ? {} : { usage: sanitizeValue(result.usage) }),
164
+ ...(result.details === undefined ? {} : { details: sanitizeValue(result.details) }),
165
+ }
166
+ : {}),
167
+ };
168
+ }
169
+ case "auto_retry_start":
170
+ return {
171
+ type: event.type,
172
+ occurredAt,
173
+ attempt: event.attempt,
174
+ maxAttempts: event.maxAttempts,
175
+ delayMs: event.delayMs,
176
+ };
177
+ case "auto_retry_end":
178
+ return { type: event.type, occurredAt, success: event.success, attempt: event.attempt };
179
+ case "thinking_level_changed":
180
+ return { type: event.type, occurredAt, level: event.level };
181
+ default:
182
+ return undefined;
183
+ }
184
+ }