pi-render-btw 0.6.10 → 0.6.12

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.
@@ -0,0 +1,616 @@
1
+ import { createHash } from "node:crypto";
2
+ import {
3
+ appendFileSync,
4
+ closeSync,
5
+ existsSync,
6
+ fstatSync,
7
+ mkdirSync,
8
+ openSync,
9
+ readFileSync,
10
+ readSync,
11
+ renameSync,
12
+ unlinkSync,
13
+ writeFileSync,
14
+ writeSync,
15
+ } from "node:fs";
16
+ import path from "node:path";
17
+
18
+ /** The on-disk format is deliberately independent from the Pi core session schema. */
19
+ export const BTW_TRANSCRIPT_SCHEMA_VERSION = 1 as const;
20
+
21
+ export type DurableTranscriptEntry = {
22
+ id: number;
23
+ turnId: number;
24
+ type:
25
+ | "turn-boundary"
26
+ | "user-message"
27
+ | "thinking"
28
+ | "assistant-text"
29
+ | "tool-call"
30
+ | "tool-result";
31
+ phase?: "start" | "end";
32
+ text?: string;
33
+ toolCallId?: string;
34
+ toolName?: string;
35
+ args?: string;
36
+ content?: string;
37
+ fullContent?: string;
38
+ truncated?: boolean;
39
+ isError?: boolean;
40
+ streaming?: boolean;
41
+ };
42
+
43
+ export type DurableTranscriptSnapshot = {
44
+ schemaVersion: typeof BTW_TRANSCRIPT_SCHEMA_VERSION;
45
+ recordId: string;
46
+ threadId: string;
47
+ timestamp: number;
48
+ mode: "contextual" | "tangent";
49
+ entries: DurableTranscriptEntry[];
50
+ nextEntryId: number;
51
+ nextTurnId: number;
52
+ currentTurnId: number | null;
53
+ lastTurnId: number | null;
54
+ };
55
+
56
+ export type ToolArtifactPhase = "start" | "update" | "end";
57
+
58
+ export type ToolArtifactWrite = {
59
+ toolCallId: string;
60
+ toolName: string;
61
+ phase: ToolArtifactPhase;
62
+ input?: unknown;
63
+ output?: unknown;
64
+ isError?: boolean;
65
+ };
66
+
67
+ export type ToolArtifact = {
68
+ toolCallId: string;
69
+ toolName: string;
70
+ phase: ToolArtifactPhase;
71
+ isError: boolean;
72
+ input?: unknown;
73
+ output?: unknown;
74
+ details?: unknown;
75
+ diff?: string;
76
+ };
77
+
78
+ export type RestoredTranscript = {
79
+ snapshot: DurableTranscriptSnapshot;
80
+ /** Rebuilt from the persisted entries; maps are intentionally not serialized. */
81
+ toolCalls: Map<string, { turnId: number; callEntryId: number; resultEntryId?: number }>;
82
+ };
83
+
84
+ function safeSegment(value: string, fallback: string): string {
85
+ const normalized = value.replace(/[^a-zA-Z0-9._-]+/g, "-").replace(/^-+|-+$/g, "");
86
+ if (normalized === "." || normalized === "..") return fallback;
87
+ return normalized.slice(0, 96) || fallback;
88
+ }
89
+
90
+ function stableId(value: string): string {
91
+ return createHash("sha256").update(value).digest("hex").slice(0, 16);
92
+ }
93
+
94
+ function jsonReplacer(_key: string, value: unknown): unknown {
95
+ if (typeof value === "bigint") return `${value}n`;
96
+ if (value instanceof Error) {
97
+ return { name: value.name, message: value.message, stack: value.stack };
98
+ }
99
+ return value;
100
+ }
101
+
102
+ function stringifyJson(value: unknown): string {
103
+ try {
104
+ const serialized = JSON.stringify(value, jsonReplacer, 2);
105
+ return serialized === undefined ? "null" : serialized;
106
+ } catch {
107
+ return JSON.stringify(String(value), null, 2);
108
+ }
109
+ }
110
+
111
+ /**
112
+ * Append one JSONL record without assuming the previous process reached EOF.
113
+ * A killed append can leave a valid record without its trailing newline; add
114
+ * the separator before the next record so that readSnapshot can still recover
115
+ * every later complete record.
116
+ */
117
+ function appendJsonLine(filePath: string, value: unknown): void {
118
+ const fd = openSync(filePath, "a+");
119
+ try {
120
+ const size = fstatSync(fd).size;
121
+ if (size > 0) {
122
+ const lastByte = Buffer.allocUnsafe(1);
123
+ readSync(fd, lastByte, 0, 1, size - 1);
124
+ if (lastByte[0] !== 0x0a) {
125
+ writeSync(fd, "\n", undefined, "utf8");
126
+ }
127
+ }
128
+ writeSync(fd, `${JSON.stringify(value, jsonReplacer)}\n`, undefined, "utf8");
129
+ } finally {
130
+ closeSync(fd);
131
+ }
132
+ }
133
+
134
+ function writeJsonAtomic(filePath: string, value: unknown): void {
135
+ const temporaryPath = `${filePath}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
136
+ try {
137
+ writeFileSync(temporaryPath, `${stringifyJson(value)}\n`, "utf8");
138
+ renameSync(temporaryPath, filePath);
139
+ } catch {
140
+ // A best-effort fallback is preferable to losing the last tool result, but
141
+ // never leave a half-written temporary file to be mistaken for an artifact.
142
+ try {
143
+ writeFileSync(filePath, `${stringifyJson(value)}\n`, "utf8");
144
+ } finally {
145
+ try {
146
+ unlinkSync(temporaryPath);
147
+ } catch {
148
+ // Best effort cleanup only.
149
+ }
150
+ }
151
+ }
152
+ }
153
+
154
+ function writeTextAtomic(filePath: string, value: string): void {
155
+ const temporaryPath = `${filePath}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
156
+ try {
157
+ writeFileSync(temporaryPath, value, "utf8");
158
+ renameSync(temporaryPath, filePath);
159
+ } catch {
160
+ try {
161
+ writeFileSync(filePath, value, "utf8");
162
+ } finally {
163
+ try {
164
+ unlinkSync(temporaryPath);
165
+ } catch {
166
+ // Best effort cleanup only.
167
+ }
168
+ }
169
+ }
170
+ }
171
+
172
+ function ensureProjectIgnore(projectDir: string): void {
173
+ const ignoreDir = path.join(projectDir, ".pi-subagents");
174
+ mkdirSync(ignoreDir, { recursive: true });
175
+ const ignorePath = path.join(ignoreDir, ".gitignore");
176
+ const existing = existsSync(ignorePath) ? readFileSync(ignorePath, "utf8") : "";
177
+ const rules = existing.split(/\r?\n/).map((line) => line.trim());
178
+ if (!rules.includes("*")) {
179
+ const prefix = existing.length > 0 && !existing.endsWith("\n") ? "\n" : "";
180
+ appendFileSync(ignorePath, `${prefix}*\n`, "utf8");
181
+ }
182
+ }
183
+
184
+ function isRecord(value: unknown): value is Record<string, unknown> {
185
+ return !!value && typeof value === "object" && !Array.isArray(value);
186
+ }
187
+
188
+ function isFiniteInteger(value: unknown): value is number {
189
+ return typeof value === "number" && Number.isSafeInteger(value);
190
+ }
191
+
192
+ function validateEntry(value: unknown): DurableTranscriptEntry | null {
193
+ if (!isRecord(value) || !isFiniteInteger(value.id) || !isFiniteInteger(value.turnId)) return null;
194
+ const allowed = new Set([
195
+ "turn-boundary",
196
+ "user-message",
197
+ "thinking",
198
+ "assistant-text",
199
+ "tool-call",
200
+ "tool-result",
201
+ ]);
202
+ if (typeof value.type !== "string" || !allowed.has(value.type)) return null;
203
+ if (value.type === "turn-boundary" && value.phase !== "start" && value.phase !== "end") return null;
204
+ const stringFields = ["text", "toolCallId", "toolName", "args", "content", "fullContent"];
205
+ for (const field of stringFields) {
206
+ if (value[field] !== undefined && typeof value[field] !== "string") return null;
207
+ }
208
+ if (value.truncated !== undefined && typeof value.truncated !== "boolean") return null;
209
+ if (value.isError !== undefined && typeof value.isError !== "boolean") return null;
210
+ if (value.streaming !== undefined && typeof value.streaming !== "boolean") return null;
211
+
212
+ // A current-schema snapshot is only useful when its entry can be rendered
213
+ // without inventing missing tool output. Reject the complete snapshot rather
214
+ // than manufacturing placeholders from corrupt persisted data.
215
+ if ((value.type === "user-message" || value.type === "thinking" || value.type === "assistant-text") && typeof value.text !== "string") return null;
216
+ if (value.type === "thinking" || value.type === "assistant-text") {
217
+ if (typeof value.streaming !== "boolean") return null;
218
+ }
219
+ if (value.type === "tool-call" &&
220
+ (typeof value.toolCallId !== "string" || typeof value.toolName !== "string" || typeof value.args !== "string")) return null;
221
+ if (value.type === "tool-result" &&
222
+ (typeof value.toolCallId !== "string" || typeof value.toolName !== "string" ||
223
+ typeof value.content !== "string" || typeof value.truncated !== "boolean" ||
224
+ typeof value.isError !== "boolean" || typeof value.streaming !== "boolean")) return null;
225
+ return value as unknown as DurableTranscriptEntry;
226
+ }
227
+
228
+ function validateSnapshot(value: unknown, expectedThreadId: string): DurableTranscriptSnapshot | null {
229
+ if (!isRecord(value)) return null;
230
+ if (value.schemaVersion !== BTW_TRANSCRIPT_SCHEMA_VERSION) return null;
231
+ if (value.threadId !== expectedThreadId || typeof value.recordId !== "string") return null;
232
+ if (!isFiniteInteger(value.timestamp) || (value.mode !== "contextual" && value.mode !== "tangent")) return null;
233
+ if (!Array.isArray(value.entries)) return null;
234
+ const entries = value.entries.map(validateEntry);
235
+ if (entries.some((entry) => entry === null)) return null;
236
+ const ids = new Set<number>();
237
+ for (const entry of entries) {
238
+ if (!entry || ids.has(entry.id)) return null;
239
+ ids.add(entry.id);
240
+ }
241
+ if (!isFiniteInteger(value.nextEntryId) || !isFiniteInteger(value.nextTurnId) ||
242
+ value.nextEntryId < 1 || value.nextTurnId < 1) return null;
243
+ if (ids.size > 0 && value.nextEntryId <= Math.max(...ids)) return null;
244
+ if (value.currentTurnId !== null && !isFiniteInteger(value.currentTurnId)) return null;
245
+ if (value.lastTurnId !== null && !isFiniteInteger(value.lastTurnId)) return null;
246
+ return {
247
+ schemaVersion: BTW_TRANSCRIPT_SCHEMA_VERSION,
248
+ recordId: value.recordId,
249
+ threadId: expectedThreadId,
250
+ timestamp: value.timestamp,
251
+ mode: value.mode,
252
+ entries: entries as DurableTranscriptEntry[],
253
+ nextEntryId: value.nextEntryId,
254
+ nextTurnId: value.nextTurnId,
255
+ currentTurnId: value.currentTurnId as number | null,
256
+ lastTurnId: value.lastTurnId as number | null,
257
+ };
258
+ }
259
+
260
+ function rebuildToolCalls(entries: DurableTranscriptEntry[]): Map<string, { turnId: number; callEntryId: number; resultEntryId?: number }> {
261
+ const toolCalls = new Map<string, { turnId: number; callEntryId: number; resultEntryId?: number }>();
262
+ for (const entry of entries) {
263
+ if (entry.type === "tool-call" && entry.toolCallId) {
264
+ toolCalls.set(entry.toolCallId, { turnId: entry.turnId, callEntryId: entry.id });
265
+ } else if (entry.type === "tool-result" && entry.toolCallId) {
266
+ const current = toolCalls.get(entry.toolCallId) ?? {
267
+ turnId: entry.turnId,
268
+ callEntryId: entry.id,
269
+ };
270
+ current.resultEntryId = entry.id;
271
+ toolCalls.set(entry.toolCallId, current);
272
+ }
273
+ }
274
+ return toolCalls;
275
+ }
276
+
277
+ function mergeToolArtifact(previous: ToolArtifactWrite | undefined, next: ToolArtifactWrite): ToolArtifactWrite {
278
+ if (!previous) return { ...next };
279
+ return {
280
+ ...previous,
281
+ ...next,
282
+ // A start event owns input and update/end events own output. Keep both
283
+ // when several events are collapsed into one durable write.
284
+ input: next.input !== undefined ? next.input : previous.input,
285
+ output: next.output !== undefined ? next.output : previous.output,
286
+ isError: next.isError ?? previous.isError,
287
+ };
288
+ }
289
+
290
+ const DURABLE_WRITE_DEBOUNCE_MS = 16;
291
+
292
+ type FlushWaiter = {
293
+ resolve: () => void;
294
+ reject: (error: unknown) => void;
295
+ };
296
+
297
+ /**
298
+ * Project-local durable BTW store. The Pi session only stores small immutable
299
+ * locators; all potentially large tool payloads stay under .pi-subagents/btw.
300
+ */
301
+ export class BtwTranscriptStore {
302
+ readonly threadId: string;
303
+ readonly threadDir: string;
304
+ readonly transcriptPath: string;
305
+ readonly toolsDir: string;
306
+ /** At most one transcript snapshot is needed between durable boundaries. */
307
+ private pendingSnapshot: DurableTranscriptSnapshot | null = null;
308
+ /** Tool updates are coalesced by call id; end always supersedes update. */
309
+ private readonly pendingToolArtifacts = new Map<string, ToolArtifactWrite>();
310
+ private drainTimer: ReturnType<typeof setTimeout> | null = null;
311
+ private draining = false;
312
+ private readonly flushWaiters: FlushWaiter[] = [];
313
+ private lastWriteError: unknown = null;
314
+
315
+ constructor(projectDir: string, sessionId: string) {
316
+ const normalizedProjectDir = path.resolve(projectDir || process.cwd());
317
+ ensureProjectIgnore(normalizedProjectDir);
318
+ this.threadId = safeSegment(sessionId, `session-${stableId(normalizedProjectDir)}`);
319
+ this.threadDir = path.join(normalizedProjectDir, ".pi-subagents", "btw", "threads", this.threadId);
320
+ this.transcriptPath = path.join(this.threadDir, "transcript.jsonl");
321
+ this.toolsDir = path.join(this.threadDir, "tools");
322
+ mkdirSync(this.toolsDir, { recursive: true });
323
+ }
324
+
325
+ private makeSnapshot(
326
+ snapshot: Omit<DurableTranscriptSnapshot, "schemaVersion" | "recordId" | "threadId" | "timestamp">,
327
+ ): DurableTranscriptSnapshot {
328
+ const now = Date.now();
329
+ const recordId = `${now.toString(36)}-${stableId(`${this.threadId}:${now}:${Math.random()}`)}`;
330
+ return {
331
+ schemaVersion: BTW_TRANSCRIPT_SCHEMA_VERSION,
332
+ recordId,
333
+ threadId: this.threadId,
334
+ timestamp: now,
335
+ ...snapshot,
336
+ };
337
+ }
338
+
339
+ private appendSnapshotRecord(snapshot: DurableTranscriptSnapshot): void {
340
+ mkdirSync(this.threadDir, { recursive: true });
341
+ // transcript.jsonl is line-delimited: keep each immutable snapshot on one
342
+ // physical line so a partial/corrupt record cannot hide later records.
343
+ appendJsonLine(this.transcriptPath, snapshot);
344
+ }
345
+
346
+ /**
347
+ * Synchronous escape hatch retained for callers that explicitly need a
348
+ * record before returning. Normal event handling uses enqueueSnapshot and
349
+ * flushes at request/shutdown boundaries instead.
350
+ */
351
+ appendSnapshot(snapshot: Omit<DurableTranscriptSnapshot, "schemaVersion" | "recordId" | "threadId" | "timestamp">): DurableTranscriptSnapshot {
352
+ const persisted = this.makeSnapshot(snapshot);
353
+ this.appendSnapshotRecord(persisted);
354
+ return persisted;
355
+ }
356
+
357
+ /** Queue the newest immutable snapshot and schedule a debounced drain. */
358
+ enqueueSnapshot(
359
+ snapshot: Omit<DurableTranscriptSnapshot, "schemaVersion" | "recordId" | "threadId" | "timestamp">,
360
+ ): DurableTranscriptSnapshot {
361
+ const persisted = this.makeSnapshot(snapshot);
362
+ this.pendingSnapshot = persisted;
363
+ this.scheduleDrain();
364
+ return persisted;
365
+ }
366
+
367
+ /** Alias for callers that use queue terminology. */
368
+ queueSnapshot(
369
+ snapshot: Omit<DurableTranscriptSnapshot, "schemaVersion" | "recordId" | "threadId" | "timestamp">,
370
+ ): DurableTranscriptSnapshot {
371
+ return this.enqueueSnapshot(snapshot);
372
+ }
373
+
374
+ /** Queue a tool event; repeated partial updates collapse to one write. */
375
+ enqueueToolArtifact(artifact: ToolArtifactWrite): void {
376
+ const current = this.pendingToolArtifacts.get(artifact.toolCallId);
377
+ this.pendingToolArtifacts.set(artifact.toolCallId, mergeToolArtifact(current, artifact));
378
+ this.scheduleDrain();
379
+ }
380
+
381
+ /** Alias for callers that use queue terminology. */
382
+ queueToolArtifact(artifact: ToolArtifactWrite): void {
383
+ this.enqueueToolArtifact(artifact);
384
+ }
385
+
386
+ private scheduleDrain(): void {
387
+ if (this.drainTimer !== null || this.draining) return;
388
+ this.drainTimer = setTimeout(() => {
389
+ this.drainTimer = null;
390
+ this.drainQueue();
391
+ }, DURABLE_WRITE_DEBOUNCE_MS);
392
+ // Pending writes are flushed explicitly by request/shutdown paths. They
393
+ // must not keep a non-interactive process alive on their own.
394
+ this.drainTimer.unref?.();
395
+ }
396
+
397
+ private settleFlushWaiters(error?: unknown): void {
398
+ if (this.flushWaiters.length === 0) return;
399
+ const waiters = this.flushWaiters.splice(0);
400
+ for (const waiter of waiters) {
401
+ if (error === undefined) waiter.resolve();
402
+ else waiter.reject(error);
403
+ }
404
+ }
405
+
406
+ private drainQueue(): void {
407
+ if (this.draining) return;
408
+ if (this.pendingSnapshot === null && this.pendingToolArtifacts.size === 0) {
409
+ this.settleFlushWaiters();
410
+ return;
411
+ }
412
+
413
+ this.draining = true;
414
+ const snapshot = this.pendingSnapshot;
415
+ this.pendingSnapshot = null;
416
+ const artifacts = [...this.pendingToolArtifacts.values()];
417
+ this.pendingToolArtifacts.clear();
418
+ let snapshotCommitted = false;
419
+ let artifactIndex = 0;
420
+
421
+ try {
422
+ if (snapshot) {
423
+ this.appendSnapshotRecord(snapshot);
424
+ snapshotCommitted = true;
425
+ }
426
+ for (; artifactIndex < artifacts.length; artifactIndex++) {
427
+ this.writeToolArtifact(artifacts[artifactIndex]!);
428
+ }
429
+ this.lastWriteError = null;
430
+ this.settleFlushWaiters();
431
+ } catch (error) {
432
+ // Keep failed work available for an explicit retry. If the append threw
433
+ // after writing its bytes, the duplicate is harmless and the locator
434
+ // still resolves to a valid latest record after the retry.
435
+ if (snapshot && !snapshotCommitted && this.pendingSnapshot === null) {
436
+ this.pendingSnapshot = snapshot;
437
+ }
438
+ for (let i = artifactIndex; i < artifacts.length; i++) {
439
+ const artifact = artifacts[i]!;
440
+ this.pendingToolArtifacts.set(
441
+ artifact.toolCallId,
442
+ mergeToolArtifact(this.pendingToolArtifacts.get(artifact.toolCallId), artifact),
443
+ );
444
+ }
445
+ this.lastWriteError = error;
446
+ this.settleFlushWaiters(error);
447
+ } finally {
448
+ this.draining = false;
449
+ if (this.pendingSnapshot !== null || this.pendingToolArtifacts.size > 0) {
450
+ this.scheduleDrain();
451
+ }
452
+ }
453
+ }
454
+
455
+ /** Drain all queued snapshot/artifact writes before a durable boundary. */
456
+ flush(): Promise<void> {
457
+ if (this.drainTimer !== null) {
458
+ clearTimeout(this.drainTimer);
459
+ this.drainTimer = null;
460
+ }
461
+
462
+ if (this.pendingSnapshot === null && this.pendingToolArtifacts.size === 0 && !this.draining) {
463
+ if (this.lastWriteError !== null) {
464
+ const error = this.lastWriteError;
465
+ this.lastWriteError = null;
466
+ return Promise.reject(error);
467
+ }
468
+ return Promise.resolve();
469
+ }
470
+
471
+ const result = new Promise<void>((resolve, reject) => {
472
+ this.flushWaiters.push({ resolve, reject });
473
+ });
474
+ this.drainQueue();
475
+ return result;
476
+ }
477
+
478
+ readSnapshot(recordId?: string): RestoredTranscript | null {
479
+ if (!existsSync(this.transcriptPath)) return null;
480
+ let latest: DurableTranscriptSnapshot | null = null;
481
+ let content = "";
482
+ try {
483
+ content = readFileSync(this.transcriptPath, "utf8");
484
+ } catch {
485
+ return null;
486
+ }
487
+ for (const line of content.split(/\r?\n/)) {
488
+ if (!line.trim()) continue;
489
+ try {
490
+ const candidate = validateSnapshot(JSON.parse(line), this.threadId);
491
+ if (!candidate || (recordId && candidate.recordId !== recordId)) continue;
492
+ latest = candidate;
493
+ } catch {
494
+ // A corrupt line must not hide earlier valid snapshots.
495
+ }
496
+ }
497
+ return latest ? { snapshot: latest, toolCalls: rebuildToolCalls(latest.entries) } : null;
498
+ }
499
+
500
+ writeToolArtifact(artifact: ToolArtifactWrite): void {
501
+ const toolDir = path.join(
502
+ this.toolsDir,
503
+ `${safeSegment(artifact.toolCallId, "tool")}-${stableId(artifact.toolCallId)}`,
504
+ );
505
+ mkdirSync(toolDir, { recursive: true });
506
+ const now = Date.now();
507
+ writeJsonAtomic(path.join(toolDir, "meta.json"), {
508
+ schemaVersion: BTW_TRANSCRIPT_SCHEMA_VERSION,
509
+ toolCallId: artifact.toolCallId,
510
+ toolName: artifact.toolName,
511
+ phase: artifact.phase,
512
+ isError: artifact.isError ?? false,
513
+ updatedAt: now,
514
+ });
515
+ if (artifact.input !== undefined) writeJsonAtomic(path.join(toolDir, "input.json"), artifact.input);
516
+ if (artifact.output !== undefined) {
517
+ writeJsonAtomic(path.join(toolDir, "output.json"), artifact.output);
518
+ const details = isRecord(artifact.output) && artifact.output.details !== undefined
519
+ ? artifact.output.details
520
+ : artifact.output;
521
+ writeJsonAtomic(path.join(toolDir, "details.json"), details);
522
+ const diff = findDiff(artifact.output);
523
+ const diffPath = path.join(toolDir, "diff.patch");
524
+ if (diff) {
525
+ writeTextAtomic(diffPath, `${diff.endsWith("\n") ? diff : `${diff}\n`}`);
526
+ } else if (existsSync(diffPath)) {
527
+ try {
528
+ unlinkSync(diffPath);
529
+ } catch {
530
+ // Best effort cleanup. A stale diff is never read as transcript data.
531
+ }
532
+ }
533
+ }
534
+ }
535
+
536
+ readToolArtifact(toolCallId: string): ToolArtifact | null {
537
+ const toolDir = path.join(
538
+ this.toolsDir,
539
+ `${safeSegment(toolCallId, "tool")}-${stableId(toolCallId)}`,
540
+ );
541
+ const metaPath = path.join(toolDir, "meta.json");
542
+ if (!existsSync(metaPath)) return null;
543
+
544
+ const readJson = (fileName: string): unknown | undefined => {
545
+ try {
546
+ return JSON.parse(readFileSync(path.join(toolDir, fileName), "utf8"));
547
+ } catch {
548
+ return undefined;
549
+ }
550
+ };
551
+ const meta = readJson("meta.json");
552
+ if (!isRecord(meta) || meta.schemaVersion !== BTW_TRANSCRIPT_SCHEMA_VERSION ||
553
+ meta.toolCallId !== toolCallId || typeof meta.toolName !== "string" ||
554
+ (meta.phase !== "start" && meta.phase !== "update" && meta.phase !== "end")) {
555
+ return null;
556
+ }
557
+
558
+ const artifact: ToolArtifact = {
559
+ toolCallId,
560
+ toolName: meta.toolName,
561
+ phase: meta.phase,
562
+ isError: meta.isError === true,
563
+ };
564
+ const input = readJson("input.json");
565
+ const output = readJson("output.json");
566
+ if (input !== undefined) artifact.input = input;
567
+ if (output !== undefined) {
568
+ artifact.output = output;
569
+ artifact.details = readJson("details.json");
570
+ }
571
+ try {
572
+ const diff = readFileSync(path.join(toolDir, "diff.patch"), "utf8");
573
+ if (diff) artifact.diff = diff;
574
+ } catch {
575
+ // Diff is optional; absence is distinct from an empty diff.
576
+ }
577
+ return artifact;
578
+ }
579
+ }
580
+
581
+ function findDiff(value: unknown): string | null {
582
+ if (typeof value === "string") return null;
583
+ if (!isRecord(value)) return null;
584
+ for (const key of ["diff", "patch", "unifiedDiff", "diffPatch"]) {
585
+ if (typeof value[key] === "string") return value[key] as string;
586
+ }
587
+ if (value.details !== undefined) {
588
+ const nested = findDiff(value.details);
589
+ if (nested) return nested;
590
+ }
591
+ if (value.result !== undefined) return findDiff(value.result);
592
+ return null;
593
+ }
594
+
595
+ export function makeTranscriptLocator(store: BtwTranscriptStore, snapshot: DurableTranscriptSnapshot): {
596
+ schemaVersion: typeof BTW_TRANSCRIPT_SCHEMA_VERSION;
597
+ threadId: string;
598
+ recordId: string;
599
+ } {
600
+ return {
601
+ schemaVersion: BTW_TRANSCRIPT_SCHEMA_VERSION,
602
+ threadId: store.threadId,
603
+ recordId: snapshot.recordId,
604
+ };
605
+ }
606
+
607
+ export function isTranscriptLocator(value: unknown): value is {
608
+ schemaVersion: typeof BTW_TRANSCRIPT_SCHEMA_VERSION;
609
+ threadId: string;
610
+ recordId: string;
611
+ } {
612
+ return isRecord(value) &&
613
+ value.schemaVersion === BTW_TRANSCRIPT_SCHEMA_VERSION &&
614
+ typeof value.threadId === "string" &&
615
+ typeof value.recordId === "string";
616
+ }