@leitwerk-dev/test-support 0.1.9 → 0.2.1

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 (143) hide show
  1. package/dist/{chunk-KIDBCGNW.js → chunk-2PCDTYVH.js} +26 -26
  2. package/dist/chunk-2PCDTYVH.js.map +1 -0
  3. package/dist/chunk-5BZSJ4OO.js +192 -0
  4. package/dist/chunk-5BZSJ4OO.js.map +1 -0
  5. package/dist/{chunk-QFCJV2VA.js → chunk-ECAWLVYB.js} +224 -17
  6. package/dist/chunk-ECAWLVYB.js.map +1 -0
  7. package/dist/{chunk-JUH3LUYK.js → chunk-EXHTWQAE.js} +5 -1
  8. package/dist/chunk-EXHTWQAE.js.map +1 -0
  9. package/dist/compact-process-detail-fixture.d.ts +3 -0
  10. package/dist/compact-process-detail-fixture.d.ts.map +1 -1
  11. package/dist/fakes/fake-git-ops.d.ts +12 -0
  12. package/dist/fakes/fake-git-ops.d.ts.map +1 -1
  13. package/dist/fakes/fake-llm.d.ts +11 -0
  14. package/dist/fakes/fake-llm.d.ts.map +1 -1
  15. package/dist/fakes/index.d.ts +1 -1
  16. package/dist/fakes/index.d.ts.map +1 -1
  17. package/dist/fakes/index.js +111 -2
  18. package/dist/fakes/index.js.map +1 -1
  19. package/dist/fixtures.js +137 -2
  20. package/dist/fixtures.js.map +1 -1
  21. package/dist/http-launch.d.ts +9 -0
  22. package/dist/http-launch.d.ts.map +1 -0
  23. package/dist/index.d.ts +24 -12
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +113 -12
  26. package/dist/index.js.map +1 -1
  27. package/dist/integration-harness.d.ts +36 -1
  28. package/dist/integration-harness.d.ts.map +1 -1
  29. package/dist/integration.d.ts +3 -3
  30. package/dist/integration.d.ts.map +1 -1
  31. package/dist/integration.js +184 -4
  32. package/dist/integration.js.map +1 -1
  33. package/dist/local-git.d.ts +231 -0
  34. package/dist/local-git.d.ts.map +1 -0
  35. package/dist/local-git.js +428 -0
  36. package/dist/local-git.js.map +1 -0
  37. package/dist/model-provider-fixtures.d.ts +15 -0
  38. package/dist/model-provider-fixtures.d.ts.map +1 -0
  39. package/dist/polling.d.ts +2 -1
  40. package/dist/polling.d.ts.map +1 -1
  41. package/dist/process-driver.d.ts +14 -0
  42. package/dist/process-driver.d.ts.map +1 -0
  43. package/dist/question-fixtures.d.ts +2 -0
  44. package/dist/question-fixtures.d.ts.map +1 -1
  45. package/dist/server-extension-test-harness.d.ts +57 -2
  46. package/dist/server-extension-test-harness.d.ts.map +1 -1
  47. package/dist/stub-worker-entry.js +9 -5
  48. package/dist/stub-worker-entry.js.map +1 -1
  49. package/dist/test-diagnostics.d.ts +14 -0
  50. package/dist/test-diagnostics.d.ts.map +1 -0
  51. package/dist/worker-testing/in-process-worker-spawn.d.ts +21 -0
  52. package/dist/worker-testing/in-process-worker-spawn.d.ts.map +1 -1
  53. package/dist/worker-testing/index.d.ts +6 -7
  54. package/dist/worker-testing/index.d.ts.map +1 -1
  55. package/dist/worker-testing/index.js +381 -7
  56. package/dist/worker-testing/index.js.map +1 -1
  57. package/dist/worker-testing/schema-driven-stub-pi.d.ts +5 -0
  58. package/dist/worker-testing/schema-driven-stub-pi.d.ts.map +1 -1
  59. package/dist/worker-testing/stub-pi-controls.d.ts +4 -0
  60. package/dist/worker-testing/stub-pi-controls.d.ts.map +1 -1
  61. package/dist/worker-testing/stub-pi-tree-handle.d.ts +93 -1
  62. package/dist/worker-testing/stub-pi-tree-handle.d.ts.map +1 -1
  63. package/dist/worker-testing/worker-runtime-harness.d.ts +37 -2
  64. package/dist/worker-testing/worker-runtime-harness.d.ts.map +1 -1
  65. package/dist/worker-testing/worker-start-payload.d.ts +17 -1
  66. package/dist/worker-testing/worker-start-payload.d.ts.map +1 -1
  67. package/package.json +15 -9
  68. package/src/compact-process-detail-fixture.ts +37 -3
  69. package/src/fakes/fake-git-ops.ts +12 -0
  70. package/src/fakes/fake-llm.ts +11 -0
  71. package/src/fakes/index.ts +1 -1
  72. package/src/http-launch.ts +88 -0
  73. package/src/index.ts +31 -41
  74. package/src/integration-harness.ts +100 -9
  75. package/src/integration.ts +3 -9
  76. package/src/local-git.ts +499 -0
  77. package/src/model-provider-fixtures.ts +36 -0
  78. package/src/polling.ts +3 -2
  79. package/src/process-driver.ts +63 -0
  80. package/src/question-fixtures.ts +2 -0
  81. package/src/server-extension-test-harness.ts +100 -6
  82. package/src/test-diagnostics.ts +69 -0
  83. package/src/worker-testing/in-process-worker-spawn.ts +49 -2
  84. package/src/worker-testing/index.ts +4 -26
  85. package/src/worker-testing/schema-driven-stub-pi.ts +8 -1
  86. package/src/worker-testing/stub-pi-controls.ts +4 -0
  87. package/src/worker-testing/stub-pi-tree-handle.ts +301 -21
  88. package/src/worker-testing/worker-runtime-harness.ts +57 -6
  89. package/src/worker-testing/worker-start-payload.ts +18 -1
  90. package/dist/chunk-3MQO3NCX.js +0 -15
  91. package/dist/chunk-3MQO3NCX.js.map +0 -1
  92. package/dist/chunk-7ZK5QRGP.js +0 -98
  93. package/dist/chunk-7ZK5QRGP.js.map +0 -1
  94. package/dist/chunk-JUH3LUYK.js.map +0 -1
  95. package/dist/chunk-KIDBCGNW.js.map +0 -1
  96. package/dist/chunk-QFCJV2VA.js.map +0 -1
  97. package/dist/chunk-R4KVUGWR.js +0 -83
  98. package/dist/chunk-R4KVUGWR.js.map +0 -1
  99. package/dist/chunk-ST2C4VKX.js +0 -297
  100. package/dist/chunk-ST2C4VKX.js.map +0 -1
  101. package/dist/compact-process-detail-fixture.js +0 -73
  102. package/dist/compact-process-detail-fixture.js.map +0 -1
  103. package/dist/fakes/fake-git-ops.js +0 -101
  104. package/dist/fakes/fake-git-ops.js.map +0 -1
  105. package/dist/fakes/fake-llm.js +0 -27
  106. package/dist/fakes/fake-llm.js.map +0 -1
  107. package/dist/in-process-worker.js +0 -2
  108. package/dist/in-process-worker.js.map +0 -1
  109. package/dist/integration-harness.js +0 -38
  110. package/dist/integration-harness.js.map +0 -1
  111. package/dist/polling.js +0 -14
  112. package/dist/polling.js.map +0 -1
  113. package/dist/question-fixtures.js +0 -26
  114. package/dist/question-fixtures.js.map +0 -1
  115. package/dist/server-extension-test-harness.js +0 -169
  116. package/dist/server-extension-test-harness.js.map +0 -1
  117. package/dist/test-app.d.ts +0 -23
  118. package/dist/test-app.d.ts.map +0 -1
  119. package/dist/test-app.js +0 -47
  120. package/dist/test-app.js.map +0 -1
  121. package/dist/worker-testing/in-process-worker-spawn.js +0 -61
  122. package/dist/worker-testing/in-process-worker-spawn.js.map +0 -1
  123. package/dist/worker-testing/ipc-harness.d.ts +0 -11
  124. package/dist/worker-testing/ipc-harness.d.ts.map +0 -1
  125. package/dist/worker-testing/ipc-harness.js +0 -17
  126. package/dist/worker-testing/ipc-harness.js.map +0 -1
  127. package/dist/worker-testing/schema-driven-stub-pi.js +0 -65
  128. package/dist/worker-testing/schema-driven-stub-pi.js.map +0 -1
  129. package/dist/worker-testing/stub-pi-controls.js +0 -10
  130. package/dist/worker-testing/stub-pi-controls.js.map +0 -1
  131. package/dist/worker-testing/stub-pi-tree-handle.js +0 -515
  132. package/dist/worker-testing/stub-pi-tree-handle.js.map +0 -1
  133. package/dist/worker-testing/worker-runtime-harness.js +0 -231
  134. package/dist/worker-testing/worker-runtime-harness.js.map +0 -1
  135. package/dist/worker-testing/worker-start-payload.js +0 -101
  136. package/dist/worker-testing/worker-start-payload.js.map +0 -1
  137. package/dist/workspace-source-aliases.d.ts +0 -6
  138. package/dist/workspace-source-aliases.d.ts.map +0 -1
  139. package/dist/workspace-source-aliases.js +0 -126
  140. package/dist/workspace-source-aliases.js.map +0 -1
  141. package/src/test-app.ts +0 -82
  142. package/src/worker-testing/ipc-harness.ts +0 -19
  143. package/src/workspace-source-aliases.ts +0 -171
@@ -1,5 +1,7 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
3
  import path from "node:path";
4
+ import { CURRENT_SESSION_VERSION, type SessionHeader } from "@earendil-works/pi-coding-agent";
3
5
  import type {
4
6
  PiCustomMessageInput,
5
7
  PiCustomTool,
@@ -14,6 +16,7 @@ import type {
14
16
  PiTreeNode,
15
17
  PiTurnExecutionResult,
16
18
  } from "@leitwerk-dev/process-sdk";
19
+ import { isEnoent } from "@leitwerk-dev/process-sdk";
17
20
  import type {
18
21
  PiManagedBootstrapOptions,
19
22
  PiManagedBootstrapResult,
@@ -23,26 +26,57 @@ import type {
23
26
  PiTreePlanningSnapshot,
24
27
  } from "@leitwerk-dev/worker";
25
28
 
29
+ /** @public */
26
30
  export interface StubToolCallScriptCall {
31
+ /** @public */
27
32
  toolName: string;
33
+ /** @public */
28
34
  args: Record<string, unknown>;
35
+ /** @internal */
29
36
  intermediateEntryCount?: number;
30
37
  }
31
38
 
39
+ /** @public */
32
40
  export type StubToolCallScriptItem =
33
41
  | StubToolCallScriptCall
34
42
  | {
43
+ /** @public */
35
44
  calls: readonly StubToolCallScriptCall[];
45
+ /** @public */
46
+ textChunks?: readonly string[];
47
+ /** @public */
48
+ thinkingChunks?: readonly string[];
49
+ /** @public */
50
+ chunkDelayMs?: number;
51
+ /** Optional scripted model reaction to a tool result, within the same turn. @internal */
52
+ afterToolResult?: (
53
+ call: StubToolCallScriptCall,
54
+ result: unknown,
55
+ ) => StubToolCallScriptCall | undefined;
36
56
  };
37
57
 
58
+ /** @public */
38
59
  export interface StubToolCallScriptResolverContext {
60
+ /** @public */
39
61
  promptText: string;
62
+ /** @public */
40
63
  tools: readonly PiCustomTool[];
64
+ /** @public */
65
+ instanceId?: string;
66
+ /** @public */
67
+ workspaceRoot?: string;
68
+ /** @public */
69
+ sessionCwd?: string;
70
+ /** @public */
71
+ treeFile: string;
72
+ /** @internal */
73
+ turnSequence: number;
41
74
  }
42
75
 
76
+ /** @public */
43
77
  export type StubToolCallScriptResolver = (
44
78
  context: StubToolCallScriptResolverContext,
45
- ) => StubToolCallScriptItem | undefined;
79
+ ) => StubToolCallScriptItem | undefined | Promise<StubToolCallScriptItem | undefined>;
46
80
 
47
81
  function stringifyToolResult(result: unknown): string {
48
82
  if (typeof result === "string") {
@@ -72,10 +106,17 @@ function stubToolCallId(turnSeq: number, totalCalls: number, index: number): str
72
106
  return `tool-${turnSeq}-${index + 1}`;
73
107
  }
74
108
 
109
+ /** @internal */
75
110
  interface StubPiTreeState {
111
+ /** @internal */
112
+ header?: SessionHeader;
113
+ /** @internal */
76
114
  turnSeq: number;
115
+ /** @internal */
77
116
  currentLeafId: string | null;
117
+ /** @internal */
78
118
  entries: Map<string, PiTreeEntry>;
119
+ /** @internal */
79
120
  childIdsByParent: Map<string | null, string[]>;
80
121
  }
81
122
 
@@ -95,6 +136,13 @@ function createEmptyStubPiTreeState(): StubPiTreeState {
95
136
  };
96
137
  }
97
138
 
139
+ function indexStubEntry(state: StubPiTreeState, entry: PiTreeEntry): void {
140
+ state.entries.set(entry.id, entry);
141
+ const siblings = state.childIdsByParent.get(entry.parentId) ?? [];
142
+ siblings.push(entry.id);
143
+ state.childIdsByParent.set(entry.parentId, siblings);
144
+ }
145
+
98
146
  function deriveStubLeafIdFromEntries(state: StubPiTreeState): string | null {
99
147
  let leafId: string | null = null;
100
148
  for (const entryId of state.entries.keys()) {
@@ -103,7 +151,16 @@ function deriveStubLeafIdFromEntries(state: StubPiTreeState): string | null {
103
151
  return leafId;
104
152
  }
105
153
 
106
- function serializeStubPiTreeState(state: StubPiTreeState): string {
154
+ function serializeStubPiTreeState(state: StubPiTreeState, recordSessionTrace: boolean): string {
155
+ if (recordSessionTrace) {
156
+ return `${[
157
+ JSON.stringify({
158
+ ...state.header,
159
+ stubState: { turnSeq: state.turnSeq, currentLeafId: state.currentLeafId },
160
+ }),
161
+ ...[...state.entries.values()].map((entry) => JSON.stringify(entry)),
162
+ ].join("\n")}\n`;
163
+ }
107
164
  const persisted: PersistedStubPiTreeState = {
108
165
  turnSeq: state.turnSeq,
109
166
  currentLeafId: state.currentLeafId,
@@ -117,6 +174,22 @@ function serializeStubPiTreeState(state: StubPiTreeState): string {
117
174
  }
118
175
 
119
176
  function deserializeStubPiTreeState(value: string): StubPiTreeState {
177
+ const lines = value.trim().split("\n");
178
+ const header = JSON.parse(lines[0]) as SessionHeader & {
179
+ stubState?: { turnSeq: number; currentLeafId: string | null };
180
+ };
181
+ if (header.type === "session") {
182
+ const entries = lines
183
+ .slice(1)
184
+ .filter(Boolean)
185
+ .map((line) => JSON.parse(line) as PiTreeEntry);
186
+ const state = createEmptyStubPiTreeState();
187
+ state.header = header;
188
+ state.turnSeq = header.stubState?.turnSeq ?? 0;
189
+ state.currentLeafId = header.stubState?.currentLeafId ?? null;
190
+ for (const entry of entries) indexStubEntry(state, entry);
191
+ return state;
192
+ }
120
193
  const parsed = JSON.parse(value) as PersistedStubPiTreeState;
121
194
  return {
122
195
  turnSeq: typeof parsed.turnSeq === "number" ? parsed.turnSeq : 0,
@@ -131,13 +204,20 @@ function deserializeStubPiTreeState(value: string): StubPiTreeState {
131
204
  };
132
205
  }
133
206
 
207
+ /** @public */
134
208
  export class StubPiTreeHandle implements PiTreeHandle {
209
+ /** @public */
135
210
  readonly sessionId: string;
211
+ /** @internal */
136
212
  readonly treeFile: string;
213
+ /** @internal */
137
214
  readonly isResumed: boolean;
138
215
 
216
+ /** @internal */
139
217
  readonly prompts: string[] = [];
218
+ /** @internal */
140
219
  readonly steers: string[] = [];
220
+ /** @internal */
141
221
  beforeTurn?: (
142
222
  kind: "prompt" | "literal" | "custom" | "continue",
143
223
  options: PiPromptOptions | undefined,
@@ -145,6 +225,7 @@ export class StubPiTreeHandle implements PiTreeHandle {
145
225
  ) => boolean | undefined | Promise<boolean | undefined>;
146
226
 
147
227
  private _closed = false;
228
+ private turnAbort = new AbortController();
148
229
  private branchDriftPending = false;
149
230
  private readonly handlers = new Set<PiEventHandler>();
150
231
  private readonly diagnosticHandlers = new Set<PiSessionDiagnosticHandler>();
@@ -152,15 +233,26 @@ export class StubPiTreeHandle implements PiTreeHandle {
152
233
  private readonly state: StubPiTreeState;
153
234
  private readonly runDetails: PiRunDetails;
154
235
  private readonly persistState?: (() => Promise<void>) | undefined;
236
+ private readonly recordSessionTrace: boolean;
155
237
 
238
+ /** @internal */
156
239
  constructor(options: {
240
+ /** @internal */
157
241
  sessionId: string;
242
+ /** @internal */
158
243
  treeFile: string;
244
+ /** @internal */
159
245
  isResumed: boolean;
246
+ /** @internal */
160
247
  toolCallScriptResolver?: StubToolCallScriptResolver;
248
+ /** @internal */
161
249
  state?: StubPiTreeState;
250
+ /** @internal */
162
251
  runDetails?: Partial<PiRunDetails>;
252
+ /** @internal */
163
253
  persistState?: () => Promise<void>;
254
+ /** @internal */
255
+ recordSessionTrace?: boolean;
164
256
  }) {
165
257
  this.sessionId = options.sessionId;
166
258
  this.treeFile = options.treeFile;
@@ -168,6 +260,7 @@ export class StubPiTreeHandle implements PiTreeHandle {
168
260
  this.toolCallScriptResolver = options.toolCallScriptResolver;
169
261
  this.state = options.state ?? createEmptyStubPiTreeState();
170
262
  this.persistState = options.persistState;
263
+ this.recordSessionTrace = options.recordSessionTrace ?? false;
171
264
  this.runDetails = {
172
265
  loadedAgentsFiles: options.runDetails?.loadedAgentsFiles?.map((file) => ({ ...file })) ?? [],
173
266
  loadedSkills: options.runDetails?.loadedSkills?.map((skill) => ({ ...skill })) ?? [],
@@ -175,10 +268,12 @@ export class StubPiTreeHandle implements PiTreeHandle {
175
268
  };
176
269
  }
177
270
 
271
+ /** @internal */
178
272
  get closed(): boolean {
179
273
  return this._closed;
180
274
  }
181
275
 
276
+ /** @internal */
182
277
  failNextTurnWithBranchDrift(): void {
183
278
  this.branchDriftPending = true;
184
279
  }
@@ -190,10 +285,7 @@ export class StubPiTreeHandle implements PiTreeHandle {
190
285
  }
191
286
 
192
287
  private addEntry(entry: PiTreeEntry): void {
193
- this.state.entries.set(entry.id, entry);
194
- const siblings = this.state.childIdsByParent.get(entry.parentId) ?? [];
195
- siblings.push(entry.id);
196
- this.state.childIdsByParent.set(entry.parentId, siblings);
288
+ indexStubEntry(this.state, entry);
197
289
  this.state.currentLeafId = entry.id;
198
290
  }
199
291
 
@@ -201,7 +293,7 @@ export class StubPiTreeHandle implements PiTreeHandle {
201
293
  id: string,
202
294
  parentId: string | null,
203
295
  role: "user" | "assistant",
204
- content: string,
296
+ content: unknown,
205
297
  timestamp: string,
206
298
  ): PiTreeEntry {
207
299
  return {
@@ -222,6 +314,7 @@ export class StubPiTreeHandle implements PiTreeHandle {
222
314
  }
223
315
  }
224
316
 
317
+ /** @internal */
225
318
  getRunDetails(): PiRunDetails {
226
319
  return {
227
320
  loadedAgentsFiles: this.runDetails.loadedAgentsFiles.map((file) => ({ ...file })),
@@ -230,14 +323,17 @@ export class StubPiTreeHandle implements PiTreeHandle {
230
323
  };
231
324
  }
232
325
 
326
+ /** @internal */
233
327
  getLeafId(): string | null {
234
328
  return this.state.currentLeafId;
235
329
  }
236
330
 
331
+ /** @internal */
237
332
  getEntry(id: string): PiTreeEntry | undefined {
238
333
  return this.state.entries.get(id);
239
334
  }
240
335
 
336
+ /** @public */
241
337
  getBranch(fromId: string | undefined = this.state.currentLeafId ?? undefined): PiTreeEntry[] {
242
338
  if (!fromId) {
243
339
  return [];
@@ -256,12 +352,14 @@ export class StubPiTreeHandle implements PiTreeHandle {
256
352
  return branch;
257
353
  }
258
354
 
355
+ /** @internal */
259
356
  getChildren(parentId: string): PiTreeEntry[] {
260
357
  return (this.state.childIdsByParent.get(parentId) ?? [])
261
358
  .map((childId) => this.state.entries.get(childId))
262
359
  .filter((entry): entry is PiTreeEntry => entry !== undefined);
263
360
  }
264
361
 
362
+ /** @internal */
265
363
  getTree(): PiTreeNode[] {
266
364
  const buildNode = (entry: PiTreeEntry): PiTreeNode => ({
267
365
  entry,
@@ -273,6 +371,7 @@ export class StubPiTreeHandle implements PiTreeHandle {
273
371
  .map(buildNode);
274
372
  }
275
373
 
374
+ /** @internal */
276
375
  async branch(entryId: string): Promise<void> {
277
376
  this.assertOpen();
278
377
  if (!this.state.entries.has(entryId)) {
@@ -282,17 +381,26 @@ export class StubPiTreeHandle implements PiTreeHandle {
282
381
  await this.persistState?.();
283
382
  }
284
383
 
384
+ /** @internal */
285
385
  async branchFromRoot(): Promise<void> {
286
386
  this.assertOpen();
287
387
  this.state.currentLeafId = null;
288
388
  await this.persistState?.();
289
389
  }
290
390
 
391
+ /** @internal */
291
392
  async resetLeaf(): Promise<void> {
292
393
  await this.branchFromRoot();
293
394
  }
294
395
 
295
- async compact(_customInstructions?: string, details?: unknown): Promise<{ summary: string }> {
396
+ /** @internal */
397
+ async compact(
398
+ _customInstructions?: string,
399
+ details?: unknown,
400
+ ): Promise<{
401
+ /** @internal */
402
+ summary: string;
403
+ }> {
296
404
  this.assertOpen();
297
405
  const timestamp = new Date().toISOString();
298
406
  const compactionEntryId = `compaction-${++this.state.turnSeq}`;
@@ -314,9 +422,12 @@ export class StubPiTreeHandle implements PiTreeHandle {
314
422
  appendPromptUserMessage: boolean;
315
423
  }): Promise<PiTurnExecutionResult> {
316
424
  this.assertOpen();
425
+ this.turnAbort = new AbortController();
426
+ const signal = this.turnAbort.signal;
317
427
  if ((await this.beforeTurn?.(input.kind, input.options, input.promptText)) === false) {
318
428
  input.options = undefined;
319
429
  }
430
+ signal.throwIfAborted();
320
431
  if (this.branchDriftPending) {
321
432
  this.branchDriftPending = false;
322
433
  throw Object.assign(new Error("stubbed Pi branch drift"), {
@@ -350,18 +461,84 @@ export class StubPiTreeHandle implements PiTreeHandle {
350
461
  );
351
462
  createdEntryIds.push(userEntryId);
352
463
  }
464
+ await this.persistState?.();
465
+ signal.throwIfAborted();
353
466
  this.emitEvent({ type: "turn.start", turnId, data: {}, timestamp });
354
467
 
355
468
  const tools = new Map((input.options?.tools ?? []).map((tool) => [tool.name, tool]));
356
469
  let assistantContent = input.promptText ?? "Continued.";
357
470
  let assistantContentFromScriptedMarkdown = false;
358
- const scriptedItem = this.toolCallScriptResolver?.({
471
+ const scriptedItem = await this.toolCallScriptResolver?.({
472
+ treeFile: this.treeFile,
473
+ turnSequence: this.state.turnSeq,
359
474
  promptText: input.promptText ?? "",
360
475
  tools: input.options?.tools ?? [],
361
476
  });
477
+ signal.throwIfAborted();
478
+ const hasScriptedChunks = Boolean(
479
+ scriptedItem &&
480
+ "calls" in scriptedItem &&
481
+ (scriptedItem.textChunks?.length ?? 0) + (scriptedItem.thinkingChunks?.length ?? 0),
482
+ );
483
+ if (hasScriptedChunks) assistantContent = "";
484
+ if (scriptedItem && "calls" in scriptedItem) {
485
+ const streamed = { thinking: "", text: "" };
486
+ const streamEntryId = `stream-${this.state.turnSeq}`;
487
+ const streamParentId = this.state.currentLeafId;
488
+ const chunks = [
489
+ ...(scriptedItem.thinkingChunks ?? []).map((text) => ({
490
+ text,
491
+ streamType: "thinking" as const,
492
+ })),
493
+ ...(scriptedItem.textChunks ?? []).map((text) => ({ text, streamType: "text" as const })),
494
+ ];
495
+ for (const { text, streamType } of chunks) {
496
+ signal.throwIfAborted();
497
+ streamed[streamType] += text;
498
+ assistantContent = streamed.text;
499
+ if (this.recordSessionTrace) {
500
+ const entry = this.createMessageEntry(
501
+ streamEntryId,
502
+ streamParentId,
503
+ "assistant",
504
+ [
505
+ ...(streamed.thinking ? [{ type: "thinking", thinking: streamed.thinking }] : []),
506
+ ...(streamed.text ? [{ type: "text", text: streamed.text }] : []),
507
+ ],
508
+ timestamp,
509
+ );
510
+ if (this.state.entries.has(streamEntryId)) this.state.entries.set(streamEntryId, entry);
511
+ else {
512
+ this.addEntry(entry);
513
+ createdEntryIds.push(streamEntryId);
514
+ }
515
+ await this.persistState?.();
516
+ }
517
+ this.emitEvent({
518
+ type: "stream.delta",
519
+ turnId,
520
+ data: { text, streamType },
521
+ timestamp: new Date().toISOString(),
522
+ });
523
+ signal.throwIfAborted();
524
+ if (scriptedItem.chunkDelayMs)
525
+ await new Promise<void>((resolve, reject) => {
526
+ const timer = setTimeout(() => {
527
+ signal.removeEventListener("abort", abort);
528
+ resolve();
529
+ }, scriptedItem.chunkDelayMs);
530
+ const abort = () => {
531
+ clearTimeout(timer);
532
+ reject(signal.reason);
533
+ };
534
+ signal.addEventListener("abort", abort, { once: true });
535
+ });
536
+ }
537
+ }
362
538
  const scriptedCalls = scriptedItem ? expandStubToolCallScriptItem(scriptedItem) : [];
363
539
  if (scriptedCalls.length > 0) {
364
540
  for (const [callIndex, scriptedCall] of scriptedCalls.entries()) {
541
+ signal.throwIfAborted();
365
542
  const toolCallId = stubToolCallId(this.state.turnSeq, scriptedCalls.length, callIndex);
366
543
  this.emitEvent({
367
544
  type: "tool.call",
@@ -382,11 +559,66 @@ export class StubPiTreeHandle implements PiTreeHandle {
382
559
  }
383
560
  }
384
561
  if (tool) {
562
+ if (this.recordSessionTrace) {
563
+ const entryId = `call-${toolCallId}`;
564
+ this.addEntry(
565
+ this.createMessageEntry(
566
+ entryId,
567
+ this.state.currentLeafId,
568
+ "assistant",
569
+ [
570
+ {
571
+ type: "toolCall",
572
+ id: toolCallId,
573
+ name: scriptedCall.toolName,
574
+ arguments: scriptedCall.args,
575
+ },
576
+ ],
577
+ new Date().toISOString(),
578
+ ),
579
+ );
580
+ createdEntryIds.push(entryId);
581
+ await this.persistState?.();
582
+ }
583
+ const recordToolResult = async (result: unknown, isError: boolean) => {
584
+ if (!this.recordSessionTrace) return;
585
+ const entryId = `result-${toolCallId}`;
586
+ const entry = {
587
+ id: entryId,
588
+ parentId: this.state.currentLeafId,
589
+ type: "message",
590
+ timestamp: new Date().toISOString(),
591
+ message: {
592
+ role: "toolResult",
593
+ toolCallId,
594
+ toolName: scriptedCall.toolName,
595
+ content: [{ type: "text", text: stringifyToolResult(result) }],
596
+ isError,
597
+ },
598
+ };
599
+ this.addEntry(entry);
600
+ createdEntryIds.push(entryId);
601
+ await this.persistState?.();
602
+ };
385
603
  try {
386
- const result = await tool.execute(scriptedCall.args);
604
+ signal.throwIfAborted();
605
+ const blocked = input.options?.shouldBlockToolCall?.(scriptedCall.toolName);
606
+ if (blocked) throw new Error(blocked);
607
+ const result = await tool.execute(scriptedCall.args, {
608
+ toolCallId,
609
+ signal,
610
+ suspendPromptGuards: input.options?.suspendPromptGuards,
611
+ });
612
+ signal.throwIfAborted();
387
613
  if (!assistantContentFromScriptedMarkdown) {
388
614
  assistantContent = stringifyToolResult(result);
389
615
  }
616
+ await recordToolResult(result, false);
617
+ const followUp =
618
+ scriptedItem && "calls" in scriptedItem
619
+ ? scriptedItem.afterToolResult?.(scriptedCall, result)
620
+ : undefined;
621
+ if (followUp) scriptedCalls.push(followUp);
390
622
  this.emitEvent({
391
623
  type: "tool.result",
392
624
  turnId,
@@ -394,6 +626,7 @@ export class StubPiTreeHandle implements PiTreeHandle {
394
626
  timestamp,
395
627
  });
396
628
  } catch (error) {
629
+ await recordToolResult(error instanceof Error ? error.message : String(error), true);
397
630
  this.emitEvent({
398
631
  type: "error",
399
632
  turnId,
@@ -423,11 +656,11 @@ export class StubPiTreeHandle implements PiTreeHandle {
423
656
  createdEntryIds.push(intermediateEntryId);
424
657
  }
425
658
  }
426
- } else if (tools.size > 0) {
659
+ } else if (tools.size > 0 && !hasScriptedChunks) {
427
660
  throw new Error(
428
661
  `Stub Pi prompt requires a stub tool-call script when tools are provided (${[...tools.keys()].join(", ")})`,
429
662
  );
430
- } else if (input.promptText !== undefined) {
663
+ } else if (input.promptText !== undefined && !hasScriptedChunks) {
431
664
  this.emitEvent({
432
665
  type: "stream.delta",
433
666
  turnId,
@@ -436,17 +669,22 @@ export class StubPiTreeHandle implements PiTreeHandle {
436
669
  });
437
670
  }
438
671
 
672
+ signal.throwIfAborted();
673
+ // Keep the result entry ID without repeating content already saved in the stream entry.
439
674
  this.addEntry(
440
675
  this.createMessageEntry(
441
676
  turnId,
442
677
  this.state.currentLeafId,
443
678
  "assistant",
444
- assistantContent,
679
+ this.recordSessionTrace && hasScriptedChunks && scriptedCalls.length === 0
680
+ ? []
681
+ : assistantContent,
445
682
  timestamp,
446
683
  ),
447
684
  );
448
685
  createdEntryIds.push(turnId);
449
686
  await this.persistState?.();
687
+ signal.throwIfAborted();
450
688
  this.emitEvent({ type: "turn.end", turnId, data: {}, timestamp });
451
689
  const resultEntryId = this.state.currentLeafId;
452
690
  if (!resultEntryId) {
@@ -465,6 +703,7 @@ export class StubPiTreeHandle implements PiTreeHandle {
465
703
  };
466
704
  }
467
705
 
706
+ /** @internal */
468
707
  async prompt(text: string, options: PiPromptOptions = {}): Promise<PiTurnExecutionResult> {
469
708
  return await this.executeTurn({
470
709
  kind: "prompt",
@@ -474,6 +713,7 @@ export class StubPiTreeHandle implements PiTreeHandle {
474
713
  });
475
714
  }
476
715
 
716
+ /** @internal */
477
717
  async promptLiteral(text: string, options: PiPromptOptions = {}): Promise<PiTurnExecutionResult> {
478
718
  return await this.executeTurn({
479
719
  kind: "literal",
@@ -483,6 +723,7 @@ export class StubPiTreeHandle implements PiTreeHandle {
483
723
  });
484
724
  }
485
725
 
726
+ /** @internal */
486
727
  async promptCustom(
487
728
  input: PiCustomMessageInput,
488
729
  options: PiPromptOptions = {},
@@ -501,6 +742,7 @@ export class StubPiTreeHandle implements PiTreeHandle {
501
742
  };
502
743
  }
503
744
 
745
+ /** @internal */
504
746
  async continueTurn(options: PiPromptOptions = {}): Promise<PiTurnExecutionResult> {
505
747
  return await this.executeTurn({
506
748
  kind: "continue",
@@ -509,6 +751,7 @@ export class StubPiTreeHandle implements PiTreeHandle {
509
751
  });
510
752
  }
511
753
 
754
+ /** @internal */
512
755
  async appendUserMessage(text: string): Promise<string> {
513
756
  this.assertOpen();
514
757
  const timestamp = new Date().toISOString();
@@ -520,6 +763,7 @@ export class StubPiTreeHandle implements PiTreeHandle {
520
763
  return userEntryId;
521
764
  }
522
765
 
766
+ /** @internal */
523
767
  async appendCustomMessage(input: PiCustomMessageInput): Promise<string> {
524
768
  this.assertOpen();
525
769
  const timestamp = new Date().toISOString();
@@ -537,15 +781,19 @@ export class StubPiTreeHandle implements PiTreeHandle {
537
781
  return entryId;
538
782
  }
539
783
 
784
+ /** @internal */
540
785
  async steer(text: string): Promise<void> {
541
786
  this.assertOpen();
542
787
  this.steers.push(text);
543
788
  }
544
789
 
790
+ /** @internal */
545
791
  async abortTurn(): Promise<void> {
546
792
  this.assertOpen();
793
+ this.turnAbort.abort(new Error("Scripted turn aborted"));
547
794
  }
548
795
 
796
+ /** @internal */
549
797
  subscribe(handler: PiEventHandler): () => void {
550
798
  this.handlers.add(handler);
551
799
  return () => {
@@ -553,6 +801,7 @@ export class StubPiTreeHandle implements PiTreeHandle {
553
801
  };
554
802
  }
555
803
 
804
+ /** @internal */
556
805
  subscribeDiagnostics(handler: PiSessionDiagnosticHandler): () => void {
557
806
  this.diagnosticHandlers.add(handler);
558
807
  return () => {
@@ -560,11 +809,14 @@ export class StubPiTreeHandle implements PiTreeHandle {
560
809
  };
561
810
  }
562
811
 
812
+ /** @internal */
563
813
  emitDiagnostic(diagnostic: PiSessionDiagnostic): void {
564
814
  for (const handler of this.diagnosticHandlers) handler(diagnostic);
565
815
  }
566
816
 
817
+ /** @internal */
567
818
  async close(): Promise<void> {
819
+ this.turnAbort.abort(new Error("Scripted session closed"));
568
820
  await this.persistState?.();
569
821
  this._closed = true;
570
822
  this.handlers.clear();
@@ -572,21 +824,32 @@ export class StubPiTreeHandle implements PiTreeHandle {
572
824
  }
573
825
  }
574
826
 
827
+ /** @public */
575
828
  export interface StubPiTreeHandleFactoryOptions {
829
+ /** @public */
576
830
  toolCallScriptResolver?: StubToolCallScriptResolver;
831
+ /** Persist SDK-readable JSONL with reasoning and tool messages for history/detail tests. @public */
832
+ recordSessionTrace?: boolean;
577
833
  }
578
834
 
835
+ /** @public */
579
836
  export class StubPiTreeHandleFactory implements PiTreeHandleFactory {
837
+ /** @public */
580
838
  readonly sessions: StubPiTreeHandle[] = [];
839
+ /** @internal */
581
840
  toolCallScriptResolver?: StubToolCallScriptResolver;
582
841
 
583
842
  private seq = 0;
584
843
  private readonly treeStateByFile = new Map<string, StubPiTreeState>();
844
+ private readonly recordSessionTrace: boolean;
585
845
 
846
+ /** @public */
586
847
  constructor(options: StubPiTreeHandleFactoryOptions = {}) {
587
848
  this.toolCallScriptResolver = options.toolCallScriptResolver;
849
+ this.recordSessionTrace = options.recordSessionTrace ?? false;
588
850
  }
589
851
 
852
+ /** @internal */
590
853
  async prepareManagedBootstrap(
591
854
  opts: PiManagedBootstrapOptions,
592
855
  ): Promise<PiManagedBootstrapResult> {
@@ -601,18 +864,14 @@ export class StubPiTreeHandleFactory implements PiTreeHandleFactory {
601
864
  };
602
865
  }
603
866
 
867
+ /** @internal */
604
868
  async inspectPrimaryTree(opts: PiTreePlanningOptions): Promise<PiTreePlanningSnapshot> {
605
869
  let treeState = this.treeStateByFile.get(opts.treeFile);
606
870
  if (!treeState) {
607
871
  try {
608
872
  treeState = deserializeStubPiTreeState(readFileSync(opts.treeFile, "utf8"));
609
873
  } catch (error) {
610
- if (
611
- typeof error === "object" &&
612
- error !== null &&
613
- "code" in error &&
614
- (error as { code?: unknown }).code === "ENOENT"
615
- ) {
874
+ if (isEnoent(error)) {
616
875
  return { currentLeafId: null, entries: [] };
617
876
  }
618
877
  throw error;
@@ -627,12 +886,17 @@ export class StubPiTreeHandleFactory implements PiTreeHandleFactory {
627
886
  };
628
887
  }
629
888
 
889
+ /** @public */
630
890
  async createPrimaryTreeHandle(opts: PiTreeHandleOptions): Promise<PiTreeHandle> {
631
891
  const persistState = async (state: StubPiTreeState): Promise<void> => {
632
892
  this.treeStateByFile.set(opts.treeFile, state);
633
893
  try {
634
894
  mkdirSync(path.dirname(opts.treeFile), { recursive: true });
635
- writeFileSync(opts.treeFile, serializeStubPiTreeState(state), "utf8");
895
+ writeFileSync(
896
+ opts.treeFile,
897
+ serializeStubPiTreeState(state, this.recordSessionTrace),
898
+ "utf8",
899
+ );
636
900
  } catch (error) {
637
901
  if (
638
902
  typeof error !== "object" ||
@@ -663,6 +927,13 @@ export class StubPiTreeHandleFactory implements PiTreeHandleFactory {
663
927
  }
664
928
  }
665
929
  treeState ??= createEmptyStubPiTreeState();
930
+ treeState.header ??= {
931
+ type: "session",
932
+ version: CURRENT_SESSION_VERSION,
933
+ id: randomUUID(),
934
+ timestamp: new Date().toISOString(),
935
+ cwd: opts.sessionCwd ?? opts.workspaceRoot ?? path.dirname(opts.treeFile),
936
+ };
666
937
  if (opts.resume) {
667
938
  treeState.currentLeafId = deriveStubLeafIdFromEntries(treeState);
668
939
  }
@@ -671,9 +942,18 @@ export class StubPiTreeHandleFactory implements PiTreeHandleFactory {
671
942
  sessionId: `stub-${++this.seq}`,
672
943
  treeFile: opts.treeFile,
673
944
  isResumed: opts.resume,
674
- toolCallScriptResolver: this.toolCallScriptResolver,
945
+ toolCallScriptResolver: this.toolCallScriptResolver
946
+ ? (context) =>
947
+ this.toolCallScriptResolver?.({
948
+ ...context,
949
+ instanceId: opts.instanceId,
950
+ workspaceRoot: opts.workspaceRoot,
951
+ sessionCwd: opts.sessionCwd,
952
+ })
953
+ : undefined,
675
954
  state: treeState,
676
955
  persistState: () => persistState(treeState),
956
+ recordSessionTrace: this.recordSessionTrace,
677
957
  runDetails: {
678
958
  availableToolNames: opts.piConfig?.availableToolNames ?? [],
679
959
  },