@leitwerk-dev/test-support 0.1.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.
- package/dist/LICENSE +13 -0
- package/dist/chunk-22HCVJEE.js +294 -0
- package/dist/chunk-22HCVJEE.js.map +1 -0
- package/dist/chunk-3MQO3NCX.js +15 -0
- package/dist/chunk-3MQO3NCX.js.map +1 -0
- package/dist/chunk-7ZK5QRGP.js +98 -0
- package/dist/chunk-7ZK5QRGP.js.map +1 -0
- package/dist/chunk-JUH3LUYK.js +28 -0
- package/dist/chunk-JUH3LUYK.js.map +1 -0
- package/dist/chunk-KIDBCGNW.js +84 -0
- package/dist/chunk-KIDBCGNW.js.map +1 -0
- package/dist/chunk-QFCJV2VA.js +600 -0
- package/dist/chunk-QFCJV2VA.js.map +1 -0
- package/dist/chunk-R4KVUGWR.js +83 -0
- package/dist/chunk-R4KVUGWR.js.map +1 -0
- package/dist/compact-process-detail-fixture.d.ts +6 -0
- package/dist/compact-process-detail-fixture.d.ts.map +1 -0
- package/dist/compact-process-detail-fixture.js +73 -0
- package/dist/compact-process-detail-fixture.js.map +1 -0
- package/dist/fakes/fake-git-ops.d.ts +22 -0
- package/dist/fakes/fake-git-ops.d.ts.map +1 -0
- package/dist/fakes/fake-git-ops.js +101 -0
- package/dist/fakes/fake-git-ops.js.map +1 -0
- package/dist/fakes/fake-llm.d.ts +21 -0
- package/dist/fakes/fake-llm.d.ts.map +1 -0
- package/dist/fakes/fake-llm.js +27 -0
- package/dist/fakes/fake-llm.js.map +1 -0
- package/dist/fakes/index.d.ts +3 -0
- package/dist/fakes/index.d.ts.map +1 -0
- package/dist/fakes/index.js +3 -0
- package/dist/fakes/index.js.map +1 -0
- package/dist/fixtures.d.ts +3 -0
- package/dist/fixtures.d.ts.map +1 -0
- package/dist/fixtures.js +3 -0
- package/dist/fixtures.js.map +1 -0
- package/dist/in-process-worker.d.ts +2 -0
- package/dist/in-process-worker.d.ts.map +1 -0
- package/dist/in-process-worker.js +2 -0
- package/dist/in-process-worker.js.map +1 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +13 -0
- package/dist/index.js.map +1 -0
- package/dist/integration-harness.d.ts +21 -0
- package/dist/integration-harness.d.ts.map +1 -0
- package/dist/integration-harness.js +38 -0
- package/dist/integration-harness.js.map +1 -0
- package/dist/integration.d.ts +5 -0
- package/dist/integration.d.ts.map +1 -0
- package/dist/integration.js +5 -0
- package/dist/integration.js.map +1 -0
- package/dist/polling.d.ts +2 -0
- package/dist/polling.d.ts.map +1 -0
- package/dist/polling.js +14 -0
- package/dist/polling.js.map +1 -0
- package/dist/question-fixtures.d.ts +4 -0
- package/dist/question-fixtures.d.ts.map +1 -0
- package/dist/question-fixtures.js +26 -0
- package/dist/question-fixtures.js.map +1 -0
- package/dist/server-extension-test-harness.d.ts +31 -0
- package/dist/server-extension-test-harness.d.ts.map +1 -0
- package/dist/server-extension-test-harness.js +167 -0
- package/dist/server-extension-test-harness.js.map +1 -0
- package/dist/stub-worker-entry.d.ts +2 -0
- package/dist/stub-worker-entry.d.ts.map +1 -0
- package/dist/stub-worker-entry.js +10 -0
- package/dist/stub-worker-entry.js.map +1 -0
- package/dist/test-app.d.ts +23 -0
- package/dist/test-app.d.ts.map +1 -0
- package/dist/test-app.js +47 -0
- package/dist/test-app.js.map +1 -0
- package/dist/worker-testing/in-process-worker-spawn.d.ts +15 -0
- package/dist/worker-testing/in-process-worker-spawn.d.ts.map +1 -0
- package/dist/worker-testing/in-process-worker-spawn.js +61 -0
- package/dist/worker-testing/in-process-worker-spawn.js.map +1 -0
- package/dist/worker-testing/index.d.ts +8 -0
- package/dist/worker-testing/index.d.ts.map +1 -0
- package/dist/worker-testing/index.js +8 -0
- package/dist/worker-testing/index.js.map +1 -0
- package/dist/worker-testing/ipc-harness.d.ts +11 -0
- package/dist/worker-testing/ipc-harness.d.ts.map +1 -0
- package/dist/worker-testing/ipc-harness.js +17 -0
- package/dist/worker-testing/ipc-harness.js.map +1 -0
- package/dist/worker-testing/schema-driven-stub-pi.d.ts +8 -0
- package/dist/worker-testing/schema-driven-stub-pi.d.ts.map +1 -0
- package/dist/worker-testing/schema-driven-stub-pi.js +65 -0
- package/dist/worker-testing/schema-driven-stub-pi.js.map +1 -0
- package/dist/worker-testing/stub-pi-controls.d.ts +7 -0
- package/dist/worker-testing/stub-pi-controls.d.ts.map +1 -0
- package/dist/worker-testing/stub-pi-controls.js +10 -0
- package/dist/worker-testing/stub-pi-controls.js.map +1 -0
- package/dist/worker-testing/stub-pi-tree-handle.d.ts +92 -0
- package/dist/worker-testing/stub-pi-tree-handle.d.ts.map +1 -0
- package/dist/worker-testing/stub-pi-tree-handle.js +515 -0
- package/dist/worker-testing/stub-pi-tree-handle.js.map +1 -0
- package/dist/worker-testing/worker-runtime-harness.d.ts +53 -0
- package/dist/worker-testing/worker-runtime-harness.d.ts.map +1 -0
- package/dist/worker-testing/worker-runtime-harness.js +210 -0
- package/dist/worker-testing/worker-runtime-harness.js.map +1 -0
- package/dist/worker-testing/worker-start-payload.d.ts +25 -0
- package/dist/worker-testing/worker-start-payload.d.ts.map +1 -0
- package/dist/worker-testing/worker-start-payload.js +101 -0
- package/dist/worker-testing/worker-start-payload.js.map +1 -0
- package/dist/workspace-source-aliases.d.ts +6 -0
- package/dist/workspace-source-aliases.d.ts.map +1 -0
- package/dist/workspace-source-aliases.js +126 -0
- package/dist/workspace-source-aliases.js.map +1 -0
- package/package.json +66 -0
- package/src/compact-process-detail-fixture.ts +117 -0
- package/src/fakes/fake-git-ops.ts +109 -0
- package/src/fakes/fake-llm.ts +39 -0
- package/src/fakes/index.ts +2 -0
- package/src/fixtures.ts +2 -0
- package/src/in-process-worker.ts +4 -0
- package/src/index.ts +45 -0
- package/src/integration-harness.ts +75 -0
- package/src/integration.ts +14 -0
- package/src/polling.ts +17 -0
- package/src/question-fixtures.ts +32 -0
- package/src/server-extension-test-harness.ts +204 -0
- package/src/stub-worker-entry.ts +11 -0
- package/src/test-app.ts +82 -0
- package/src/worker-testing/in-process-worker-spawn.ts +84 -0
- package/src/worker-testing/index.ts +36 -0
- package/src/worker-testing/ipc-harness.ts +19 -0
- package/src/worker-testing/schema-driven-stub-pi.ts +83 -0
- package/src/worker-testing/stub-pi-controls.ts +16 -0
- package/src/worker-testing/stub-pi-tree-handle.ts +687 -0
- package/src/worker-testing/worker-runtime-harness.ts +280 -0
- package/src/worker-testing/worker-start-payload.ts +135 -0
- package/src/workspace-source-aliases.ts +171 -0
|
@@ -0,0 +1,687 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import type {
|
|
4
|
+
PiCustomMessageInput,
|
|
5
|
+
PiCustomTool,
|
|
6
|
+
PiEvent,
|
|
7
|
+
PiEventHandler,
|
|
8
|
+
PiPromptOptions,
|
|
9
|
+
PiRunDetails,
|
|
10
|
+
PiSessionDiagnostic,
|
|
11
|
+
PiSessionDiagnosticHandler,
|
|
12
|
+
PiTreeEntry,
|
|
13
|
+
PiTreeHandle,
|
|
14
|
+
PiTreeNode,
|
|
15
|
+
PiTurnExecutionResult,
|
|
16
|
+
} from "@leitwerk-dev/process-sdk";
|
|
17
|
+
import type {
|
|
18
|
+
PiManagedBootstrapOptions,
|
|
19
|
+
PiManagedBootstrapResult,
|
|
20
|
+
PiTreeHandleFactory,
|
|
21
|
+
PiTreeHandleOptions,
|
|
22
|
+
PiTreePlanningOptions,
|
|
23
|
+
PiTreePlanningSnapshot,
|
|
24
|
+
} from "@leitwerk-dev/worker";
|
|
25
|
+
|
|
26
|
+
export interface StubToolCallScriptCall {
|
|
27
|
+
toolName: string;
|
|
28
|
+
args: Record<string, unknown>;
|
|
29
|
+
intermediateEntryCount?: number;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export type StubToolCallScriptItem =
|
|
33
|
+
| StubToolCallScriptCall
|
|
34
|
+
| {
|
|
35
|
+
calls: readonly StubToolCallScriptCall[];
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
export interface StubToolCallScriptResolverContext {
|
|
39
|
+
promptText: string;
|
|
40
|
+
tools: readonly PiCustomTool[];
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export type StubToolCallScriptResolver = (
|
|
44
|
+
context: StubToolCallScriptResolverContext,
|
|
45
|
+
) => StubToolCallScriptItem | undefined;
|
|
46
|
+
|
|
47
|
+
function stringifyToolResult(result: unknown): string {
|
|
48
|
+
if (typeof result === "string") {
|
|
49
|
+
return result;
|
|
50
|
+
}
|
|
51
|
+
if (result === undefined) {
|
|
52
|
+
return "ok";
|
|
53
|
+
}
|
|
54
|
+
try {
|
|
55
|
+
return JSON.stringify(result, null, 2);
|
|
56
|
+
} catch {
|
|
57
|
+
return String(result);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function expandStubToolCallScriptItem(item: StubToolCallScriptItem): StubToolCallScriptCall[] {
|
|
62
|
+
if ("calls" in item) {
|
|
63
|
+
return [...item.calls];
|
|
64
|
+
}
|
|
65
|
+
return [item];
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function stubToolCallId(turnSeq: number, totalCalls: number, index: number): string {
|
|
69
|
+
if (totalCalls <= 1) {
|
|
70
|
+
return `tool-${turnSeq}`;
|
|
71
|
+
}
|
|
72
|
+
return `tool-${turnSeq}-${index + 1}`;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
interface StubPiTreeState {
|
|
76
|
+
turnSeq: number;
|
|
77
|
+
currentLeafId: string | null;
|
|
78
|
+
entries: Map<string, PiTreeEntry>;
|
|
79
|
+
childIdsByParent: Map<string | null, string[]>;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
interface PersistedStubPiTreeState {
|
|
83
|
+
turnSeq: number;
|
|
84
|
+
currentLeafId: string | null;
|
|
85
|
+
entries: PiTreeEntry[];
|
|
86
|
+
childIdsByParent: Array<{ parentId: string | null; childIds: string[] }>;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function createEmptyStubPiTreeState(): StubPiTreeState {
|
|
90
|
+
return {
|
|
91
|
+
turnSeq: 0,
|
|
92
|
+
currentLeafId: null,
|
|
93
|
+
entries: new Map<string, PiTreeEntry>(),
|
|
94
|
+
childIdsByParent: new Map<string | null, string[]>(),
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function deriveStubLeafIdFromEntries(state: StubPiTreeState): string | null {
|
|
99
|
+
let leafId: string | null = null;
|
|
100
|
+
for (const entryId of state.entries.keys()) {
|
|
101
|
+
leafId = entryId;
|
|
102
|
+
}
|
|
103
|
+
return leafId;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function serializeStubPiTreeState(state: StubPiTreeState): string {
|
|
107
|
+
const persisted: PersistedStubPiTreeState = {
|
|
108
|
+
turnSeq: state.turnSeq,
|
|
109
|
+
currentLeafId: state.currentLeafId,
|
|
110
|
+
entries: [...state.entries.values()],
|
|
111
|
+
childIdsByParent: [...state.childIdsByParent.entries()].map(([parentId, childIds]) => ({
|
|
112
|
+
parentId,
|
|
113
|
+
childIds: [...childIds],
|
|
114
|
+
})),
|
|
115
|
+
};
|
|
116
|
+
return JSON.stringify(persisted);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function deserializeStubPiTreeState(value: string): StubPiTreeState {
|
|
120
|
+
const parsed = JSON.parse(value) as PersistedStubPiTreeState;
|
|
121
|
+
return {
|
|
122
|
+
turnSeq: typeof parsed.turnSeq === "number" ? parsed.turnSeq : 0,
|
|
123
|
+
currentLeafId:
|
|
124
|
+
typeof parsed.currentLeafId === "string" || parsed.currentLeafId === null
|
|
125
|
+
? parsed.currentLeafId
|
|
126
|
+
: null,
|
|
127
|
+
entries: new Map((parsed.entries ?? []).map((entry) => [entry.id, entry])),
|
|
128
|
+
childIdsByParent: new Map(
|
|
129
|
+
(parsed.childIdsByParent ?? []).map((entry) => [entry.parentId, [...entry.childIds]]),
|
|
130
|
+
),
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export class StubPiTreeHandle implements PiTreeHandle {
|
|
135
|
+
readonly sessionId: string;
|
|
136
|
+
readonly treeFile: string;
|
|
137
|
+
readonly isResumed: boolean;
|
|
138
|
+
|
|
139
|
+
readonly prompts: string[] = [];
|
|
140
|
+
readonly steers: string[] = [];
|
|
141
|
+
beforeTurn?: (
|
|
142
|
+
kind: "prompt" | "literal" | "custom" | "continue",
|
|
143
|
+
options: PiPromptOptions | undefined,
|
|
144
|
+
promptText: string | undefined,
|
|
145
|
+
) => boolean | undefined | Promise<boolean | undefined>;
|
|
146
|
+
|
|
147
|
+
private _closed = false;
|
|
148
|
+
private branchDriftPending = false;
|
|
149
|
+
private readonly handlers = new Set<PiEventHandler>();
|
|
150
|
+
private readonly diagnosticHandlers = new Set<PiSessionDiagnosticHandler>();
|
|
151
|
+
private readonly toolCallScriptResolver?: StubToolCallScriptResolver;
|
|
152
|
+
private readonly state: StubPiTreeState;
|
|
153
|
+
private readonly runDetails: PiRunDetails;
|
|
154
|
+
private readonly persistState?: (() => Promise<void>) | undefined;
|
|
155
|
+
|
|
156
|
+
constructor(options: {
|
|
157
|
+
sessionId: string;
|
|
158
|
+
treeFile: string;
|
|
159
|
+
isResumed: boolean;
|
|
160
|
+
toolCallScriptResolver?: StubToolCallScriptResolver;
|
|
161
|
+
state?: StubPiTreeState;
|
|
162
|
+
runDetails?: Partial<PiRunDetails>;
|
|
163
|
+
persistState?: () => Promise<void>;
|
|
164
|
+
}) {
|
|
165
|
+
this.sessionId = options.sessionId;
|
|
166
|
+
this.treeFile = options.treeFile;
|
|
167
|
+
this.isResumed = options.isResumed;
|
|
168
|
+
this.toolCallScriptResolver = options.toolCallScriptResolver;
|
|
169
|
+
this.state = options.state ?? createEmptyStubPiTreeState();
|
|
170
|
+
this.persistState = options.persistState;
|
|
171
|
+
this.runDetails = {
|
|
172
|
+
loadedAgentsFiles: options.runDetails?.loadedAgentsFiles?.map((file) => ({ ...file })) ?? [],
|
|
173
|
+
loadedSkills: options.runDetails?.loadedSkills?.map((skill) => ({ ...skill })) ?? [],
|
|
174
|
+
availableToolNames: [...(options.runDetails?.availableToolNames ?? [])],
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
get closed(): boolean {
|
|
179
|
+
return this._closed;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
failNextTurnWithBranchDrift(): void {
|
|
183
|
+
this.branchDriftPending = true;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
private assertOpen(): void {
|
|
187
|
+
if (this._closed) {
|
|
188
|
+
throw new Error("Handle is closed");
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
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);
|
|
197
|
+
this.state.currentLeafId = entry.id;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
private createMessageEntry(
|
|
201
|
+
id: string,
|
|
202
|
+
parentId: string | null,
|
|
203
|
+
role: "user" | "assistant",
|
|
204
|
+
content: string,
|
|
205
|
+
timestamp: string,
|
|
206
|
+
): PiTreeEntry {
|
|
207
|
+
return {
|
|
208
|
+
id,
|
|
209
|
+
parentId,
|
|
210
|
+
type: "message",
|
|
211
|
+
timestamp,
|
|
212
|
+
message: {
|
|
213
|
+
role,
|
|
214
|
+
content,
|
|
215
|
+
},
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
private emitEvent(event: PiEvent): void {
|
|
220
|
+
for (const handler of this.handlers) {
|
|
221
|
+
handler(event);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
getRunDetails(): PiRunDetails {
|
|
226
|
+
return {
|
|
227
|
+
loadedAgentsFiles: this.runDetails.loadedAgentsFiles.map((file) => ({ ...file })),
|
|
228
|
+
loadedSkills: this.runDetails.loadedSkills.map((skill) => ({ ...skill })),
|
|
229
|
+
availableToolNames: [...this.runDetails.availableToolNames],
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
getLeafId(): string | null {
|
|
234
|
+
return this.state.currentLeafId;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
getEntry(id: string): PiTreeEntry | undefined {
|
|
238
|
+
return this.state.entries.get(id);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
getBranch(fromId: string | undefined = this.state.currentLeafId ?? undefined): PiTreeEntry[] {
|
|
242
|
+
if (!fromId) {
|
|
243
|
+
return [];
|
|
244
|
+
}
|
|
245
|
+
const branch: PiTreeEntry[] = [];
|
|
246
|
+
let currentId: string | null = fromId;
|
|
247
|
+
while (currentId) {
|
|
248
|
+
const entry = this.state.entries.get(currentId);
|
|
249
|
+
if (!entry) {
|
|
250
|
+
break;
|
|
251
|
+
}
|
|
252
|
+
branch.push(entry);
|
|
253
|
+
currentId = entry.parentId;
|
|
254
|
+
}
|
|
255
|
+
branch.reverse();
|
|
256
|
+
return branch;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
getChildren(parentId: string): PiTreeEntry[] {
|
|
260
|
+
return (this.state.childIdsByParent.get(parentId) ?? [])
|
|
261
|
+
.map((childId) => this.state.entries.get(childId))
|
|
262
|
+
.filter((entry): entry is PiTreeEntry => entry !== undefined);
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
getTree(): PiTreeNode[] {
|
|
266
|
+
const buildNode = (entry: PiTreeEntry): PiTreeNode => ({
|
|
267
|
+
entry,
|
|
268
|
+
children: this.getChildren(entry.id).map(buildNode),
|
|
269
|
+
});
|
|
270
|
+
return (this.state.childIdsByParent.get(null) ?? [])
|
|
271
|
+
.map((entryId) => this.state.entries.get(entryId))
|
|
272
|
+
.filter((entry): entry is PiTreeEntry => entry !== undefined)
|
|
273
|
+
.map(buildNode);
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
async branch(entryId: string): Promise<void> {
|
|
277
|
+
this.assertOpen();
|
|
278
|
+
if (!this.state.entries.has(entryId)) {
|
|
279
|
+
throw new Error(`Unknown Pi entry '${entryId}'`);
|
|
280
|
+
}
|
|
281
|
+
this.state.currentLeafId = entryId;
|
|
282
|
+
await this.persistState?.();
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
async branchFromRoot(): Promise<void> {
|
|
286
|
+
this.assertOpen();
|
|
287
|
+
this.state.currentLeafId = null;
|
|
288
|
+
await this.persistState?.();
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
async resetLeaf(): Promise<void> {
|
|
292
|
+
await this.branchFromRoot();
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
async compact(_customInstructions?: string, details?: unknown): Promise<{ summary: string }> {
|
|
296
|
+
this.assertOpen();
|
|
297
|
+
const timestamp = new Date().toISOString();
|
|
298
|
+
const compactionEntryId = `compaction-${++this.state.turnSeq}`;
|
|
299
|
+
this.addEntry({
|
|
300
|
+
id: compactionEntryId,
|
|
301
|
+
parentId: this.state.currentLeafId,
|
|
302
|
+
type: "compaction",
|
|
303
|
+
timestamp,
|
|
304
|
+
details,
|
|
305
|
+
});
|
|
306
|
+
await this.persistState?.();
|
|
307
|
+
return { summary: "Stub compaction" };
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
private async executeTurn(input: {
|
|
311
|
+
kind: "prompt" | "literal" | "custom" | "continue";
|
|
312
|
+
promptText?: string;
|
|
313
|
+
options?: PiPromptOptions;
|
|
314
|
+
appendPromptUserMessage: boolean;
|
|
315
|
+
}): Promise<PiTurnExecutionResult> {
|
|
316
|
+
this.assertOpen();
|
|
317
|
+
if ((await this.beforeTurn?.(input.kind, input.options, input.promptText)) === false) {
|
|
318
|
+
input.options = undefined;
|
|
319
|
+
}
|
|
320
|
+
if (this.branchDriftPending) {
|
|
321
|
+
this.branchDriftPending = false;
|
|
322
|
+
throw Object.assign(new Error("stubbed Pi branch drift"), {
|
|
323
|
+
name: "PiBranchDriftError",
|
|
324
|
+
failureCode: "branch_drift",
|
|
325
|
+
toTurnFailureOptions: () => ({
|
|
326
|
+
failureCode: "branch_drift",
|
|
327
|
+
failureDetails: { operation: input.kind },
|
|
328
|
+
recoveryContext: null,
|
|
329
|
+
restorePrimaryLeaf: false,
|
|
330
|
+
}),
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
if (input.promptText !== undefined) {
|
|
334
|
+
this.prompts.push(input.promptText);
|
|
335
|
+
}
|
|
336
|
+
const startLeafId = this.state.currentLeafId;
|
|
337
|
+
const turnId = `turn-${++this.state.turnSeq}`;
|
|
338
|
+
const timestamp = new Date().toISOString();
|
|
339
|
+
const createdEntryIds: string[] = [];
|
|
340
|
+
if (input.appendPromptUserMessage) {
|
|
341
|
+
const userEntryId = `user-${this.state.turnSeq}`;
|
|
342
|
+
this.addEntry(
|
|
343
|
+
this.createMessageEntry(
|
|
344
|
+
userEntryId,
|
|
345
|
+
this.state.currentLeafId,
|
|
346
|
+
"user",
|
|
347
|
+
input.promptText ?? "",
|
|
348
|
+
timestamp,
|
|
349
|
+
),
|
|
350
|
+
);
|
|
351
|
+
createdEntryIds.push(userEntryId);
|
|
352
|
+
}
|
|
353
|
+
this.emitEvent({ type: "turn.start", turnId, data: {}, timestamp });
|
|
354
|
+
|
|
355
|
+
const tools = new Map((input.options?.tools ?? []).map((tool) => [tool.name, tool]));
|
|
356
|
+
let assistantContent = input.promptText ?? "Continued.";
|
|
357
|
+
let assistantContentFromScriptedMarkdown = false;
|
|
358
|
+
const scriptedItem = this.toolCallScriptResolver?.({
|
|
359
|
+
promptText: input.promptText ?? "",
|
|
360
|
+
tools: input.options?.tools ?? [],
|
|
361
|
+
});
|
|
362
|
+
const scriptedCalls = scriptedItem ? expandStubToolCallScriptItem(scriptedItem) : [];
|
|
363
|
+
if (scriptedCalls.length > 0) {
|
|
364
|
+
for (const [callIndex, scriptedCall] of scriptedCalls.entries()) {
|
|
365
|
+
const toolCallId = stubToolCallId(this.state.turnSeq, scriptedCalls.length, callIndex);
|
|
366
|
+
this.emitEvent({
|
|
367
|
+
type: "tool.call",
|
|
368
|
+
turnId,
|
|
369
|
+
data: {
|
|
370
|
+
toolCallId,
|
|
371
|
+
name: scriptedCall.toolName,
|
|
372
|
+
arguments: scriptedCall.args,
|
|
373
|
+
},
|
|
374
|
+
timestamp,
|
|
375
|
+
});
|
|
376
|
+
const tool = tools.get(scriptedCall.toolName);
|
|
377
|
+
if (!tool && scriptedCall.toolName === "markdown_result") {
|
|
378
|
+
const markdown = (scriptedCall.args as { markdown?: unknown }).markdown;
|
|
379
|
+
if (typeof markdown === "string") {
|
|
380
|
+
assistantContent = markdown;
|
|
381
|
+
assistantContentFromScriptedMarkdown = true;
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
if (tool) {
|
|
385
|
+
try {
|
|
386
|
+
const result = await tool.execute(scriptedCall.args);
|
|
387
|
+
if (!assistantContentFromScriptedMarkdown) {
|
|
388
|
+
assistantContent = stringifyToolResult(result);
|
|
389
|
+
}
|
|
390
|
+
this.emitEvent({
|
|
391
|
+
type: "tool.result",
|
|
392
|
+
turnId,
|
|
393
|
+
data: { toolCallId, name: scriptedCall.toolName, result },
|
|
394
|
+
timestamp,
|
|
395
|
+
});
|
|
396
|
+
} catch (error) {
|
|
397
|
+
this.emitEvent({
|
|
398
|
+
type: "error",
|
|
399
|
+
turnId,
|
|
400
|
+
data: {
|
|
401
|
+
message: error instanceof Error ? error.message : String(error),
|
|
402
|
+
toolName: scriptedCall.toolName,
|
|
403
|
+
},
|
|
404
|
+
timestamp,
|
|
405
|
+
});
|
|
406
|
+
throw error;
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
for (let i = 0; i < (scriptedCall.intermediateEntryCount ?? 0); i++) {
|
|
410
|
+
const intermediateEntryId =
|
|
411
|
+
scriptedCalls.length === 1
|
|
412
|
+
? `intermediate-${this.state.turnSeq}-${i + 1}`
|
|
413
|
+
: `intermediate-${this.state.turnSeq}-${callIndex + 1}-${i + 1}`;
|
|
414
|
+
this.addEntry(
|
|
415
|
+
this.createMessageEntry(
|
|
416
|
+
intermediateEntryId,
|
|
417
|
+
this.state.currentLeafId,
|
|
418
|
+
"assistant",
|
|
419
|
+
`Intermediate entry ${i + 1}`,
|
|
420
|
+
timestamp,
|
|
421
|
+
),
|
|
422
|
+
);
|
|
423
|
+
createdEntryIds.push(intermediateEntryId);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
} else if (tools.size > 0) {
|
|
427
|
+
throw new Error(
|
|
428
|
+
`Stub Pi prompt requires a stub tool-call script when tools are provided (${[...tools.keys()].join(", ")})`,
|
|
429
|
+
);
|
|
430
|
+
} else if (input.promptText !== undefined) {
|
|
431
|
+
this.emitEvent({
|
|
432
|
+
type: "stream.delta",
|
|
433
|
+
turnId,
|
|
434
|
+
data: { text: input.promptText },
|
|
435
|
+
timestamp,
|
|
436
|
+
});
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
this.addEntry(
|
|
440
|
+
this.createMessageEntry(
|
|
441
|
+
turnId,
|
|
442
|
+
this.state.currentLeafId,
|
|
443
|
+
"assistant",
|
|
444
|
+
assistantContent,
|
|
445
|
+
timestamp,
|
|
446
|
+
),
|
|
447
|
+
);
|
|
448
|
+
createdEntryIds.push(turnId);
|
|
449
|
+
await this.persistState?.();
|
|
450
|
+
this.emitEvent({ type: "turn.end", turnId, data: {}, timestamp });
|
|
451
|
+
const resultEntryId = this.state.currentLeafId;
|
|
452
|
+
if (!resultEntryId) {
|
|
453
|
+
throw new Error(
|
|
454
|
+
input.appendPromptUserMessage
|
|
455
|
+
? "Stub Pi prompt completed without an active leaf"
|
|
456
|
+
: "Stub Pi continuation completed without an active leaf",
|
|
457
|
+
);
|
|
458
|
+
}
|
|
459
|
+
return {
|
|
460
|
+
startLeafId,
|
|
461
|
+
endLeafId: resultEntryId,
|
|
462
|
+
createdEntryIds,
|
|
463
|
+
resultEntryId,
|
|
464
|
+
assistantMarkdown: assistantContent,
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
async prompt(text: string, options: PiPromptOptions = {}): Promise<PiTurnExecutionResult> {
|
|
469
|
+
return await this.executeTurn({
|
|
470
|
+
kind: "prompt",
|
|
471
|
+
promptText: text,
|
|
472
|
+
options,
|
|
473
|
+
appendPromptUserMessage: true,
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
async promptLiteral(text: string, options: PiPromptOptions = {}): Promise<PiTurnExecutionResult> {
|
|
478
|
+
return await this.executeTurn({
|
|
479
|
+
kind: "literal",
|
|
480
|
+
promptText: text,
|
|
481
|
+
options,
|
|
482
|
+
appendPromptUserMessage: true,
|
|
483
|
+
});
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
async promptCustom(
|
|
487
|
+
input: PiCustomMessageInput,
|
|
488
|
+
options: PiPromptOptions = {},
|
|
489
|
+
): Promise<PiTurnExecutionResult> {
|
|
490
|
+
const startLeafId = this.getLeafId();
|
|
491
|
+
const promptEntryId = await this.appendCustomMessage(input);
|
|
492
|
+
const result = await this.executeTurn({
|
|
493
|
+
kind: "custom",
|
|
494
|
+
options,
|
|
495
|
+
appendPromptUserMessage: false,
|
|
496
|
+
});
|
|
497
|
+
return {
|
|
498
|
+
...result,
|
|
499
|
+
startLeafId,
|
|
500
|
+
createdEntryIds: [promptEntryId, ...result.createdEntryIds],
|
|
501
|
+
};
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
async continueTurn(options: PiPromptOptions = {}): Promise<PiTurnExecutionResult> {
|
|
505
|
+
return await this.executeTurn({
|
|
506
|
+
kind: "continue",
|
|
507
|
+
options,
|
|
508
|
+
appendPromptUserMessage: false,
|
|
509
|
+
});
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
async appendUserMessage(text: string): Promise<string> {
|
|
513
|
+
this.assertOpen();
|
|
514
|
+
const timestamp = new Date().toISOString();
|
|
515
|
+
const userEntryId = `user-${++this.state.turnSeq}`;
|
|
516
|
+
this.addEntry(
|
|
517
|
+
this.createMessageEntry(userEntryId, this.state.currentLeafId, "user", text, timestamp),
|
|
518
|
+
);
|
|
519
|
+
await this.persistState?.();
|
|
520
|
+
return userEntryId;
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
async appendCustomMessage(input: PiCustomMessageInput): Promise<string> {
|
|
524
|
+
this.assertOpen();
|
|
525
|
+
const timestamp = new Date().toISOString();
|
|
526
|
+
const entryId = `custom-${++this.state.turnSeq}`;
|
|
527
|
+
this.addEntry({
|
|
528
|
+
id: entryId,
|
|
529
|
+
parentId: this.state.currentLeafId,
|
|
530
|
+
type: "custom_message",
|
|
531
|
+
timestamp,
|
|
532
|
+
customType: "leitwerk",
|
|
533
|
+
content: input.content,
|
|
534
|
+
details: input.details,
|
|
535
|
+
});
|
|
536
|
+
await this.persistState?.();
|
|
537
|
+
return entryId;
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
async steer(text: string): Promise<void> {
|
|
541
|
+
this.assertOpen();
|
|
542
|
+
this.steers.push(text);
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
async abortTurn(): Promise<void> {
|
|
546
|
+
this.assertOpen();
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
subscribe(handler: PiEventHandler): () => void {
|
|
550
|
+
this.handlers.add(handler);
|
|
551
|
+
return () => {
|
|
552
|
+
this.handlers.delete(handler);
|
|
553
|
+
};
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
subscribeDiagnostics(handler: PiSessionDiagnosticHandler): () => void {
|
|
557
|
+
this.diagnosticHandlers.add(handler);
|
|
558
|
+
return () => {
|
|
559
|
+
this.diagnosticHandlers.delete(handler);
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
emitDiagnostic(diagnostic: PiSessionDiagnostic): void {
|
|
564
|
+
for (const handler of this.diagnosticHandlers) handler(diagnostic);
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
async close(): Promise<void> {
|
|
568
|
+
await this.persistState?.();
|
|
569
|
+
this._closed = true;
|
|
570
|
+
this.handlers.clear();
|
|
571
|
+
this.diagnosticHandlers.clear();
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
export interface StubPiTreeHandleFactoryOptions {
|
|
576
|
+
toolCallScriptResolver?: StubToolCallScriptResolver;
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
export class StubPiTreeHandleFactory implements PiTreeHandleFactory {
|
|
580
|
+
readonly sessions: StubPiTreeHandle[] = [];
|
|
581
|
+
toolCallScriptResolver?: StubToolCallScriptResolver;
|
|
582
|
+
|
|
583
|
+
private seq = 0;
|
|
584
|
+
private readonly treeStateByFile = new Map<string, StubPiTreeState>();
|
|
585
|
+
|
|
586
|
+
constructor(options: StubPiTreeHandleFactoryOptions = {}) {
|
|
587
|
+
this.toolCallScriptResolver = options.toolCallScriptResolver;
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
async prepareManagedBootstrap(
|
|
591
|
+
opts: PiManagedBootstrapOptions,
|
|
592
|
+
): Promise<PiManagedBootstrapResult> {
|
|
593
|
+
return {
|
|
594
|
+
loadedResourceIds: opts.manifest.provenance.map(
|
|
595
|
+
(resource: { snapshotPath: string }) => resource.snapshotPath,
|
|
596
|
+
),
|
|
597
|
+
loadedAgentsFiles: [],
|
|
598
|
+
loadedSkillFiles: [],
|
|
599
|
+
resolvedModel: { ...opts.expectedModel },
|
|
600
|
+
diagnostics: [],
|
|
601
|
+
};
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
async inspectPrimaryTree(opts: PiTreePlanningOptions): Promise<PiTreePlanningSnapshot> {
|
|
605
|
+
let treeState = this.treeStateByFile.get(opts.treeFile);
|
|
606
|
+
if (!treeState) {
|
|
607
|
+
try {
|
|
608
|
+
treeState = deserializeStubPiTreeState(readFileSync(opts.treeFile, "utf8"));
|
|
609
|
+
} catch (error) {
|
|
610
|
+
if (
|
|
611
|
+
typeof error === "object" &&
|
|
612
|
+
error !== null &&
|
|
613
|
+
"code" in error &&
|
|
614
|
+
(error as { code?: unknown }).code === "ENOENT"
|
|
615
|
+
) {
|
|
616
|
+
return { currentLeafId: null, entries: [] };
|
|
617
|
+
}
|
|
618
|
+
throw error;
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
return {
|
|
622
|
+
currentLeafId: treeState.currentLeafId ?? deriveStubLeafIdFromEntries(treeState),
|
|
623
|
+
entries: [...treeState.entries.values()].map((entry) => ({
|
|
624
|
+
id: entry.id,
|
|
625
|
+
parentId: entry.parentId,
|
|
626
|
+
})),
|
|
627
|
+
};
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
async createPrimaryTreeHandle(opts: PiTreeHandleOptions): Promise<PiTreeHandle> {
|
|
631
|
+
const persistState = async (state: StubPiTreeState): Promise<void> => {
|
|
632
|
+
this.treeStateByFile.set(opts.treeFile, state);
|
|
633
|
+
try {
|
|
634
|
+
mkdirSync(path.dirname(opts.treeFile), { recursive: true });
|
|
635
|
+
writeFileSync(opts.treeFile, serializeStubPiTreeState(state), "utf8");
|
|
636
|
+
} catch (error) {
|
|
637
|
+
if (
|
|
638
|
+
typeof error !== "object" ||
|
|
639
|
+
error === null ||
|
|
640
|
+
!("code" in error) ||
|
|
641
|
+
!["ENOENT", "EACCES", "EROFS", "EPERM"].includes(
|
|
642
|
+
String((error as { code?: unknown }).code),
|
|
643
|
+
)
|
|
644
|
+
) {
|
|
645
|
+
throw error;
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
};
|
|
649
|
+
let treeState = this.treeStateByFile.get(opts.treeFile);
|
|
650
|
+
if (!treeState && opts.resume) {
|
|
651
|
+
try {
|
|
652
|
+
const persisted = readFileSync(opts.treeFile, "utf8");
|
|
653
|
+
treeState = deserializeStubPiTreeState(persisted);
|
|
654
|
+
} catch (error) {
|
|
655
|
+
if (
|
|
656
|
+
typeof error === "object" &&
|
|
657
|
+
error !== null &&
|
|
658
|
+
"code" in error &&
|
|
659
|
+
(error as { code?: unknown }).code !== "ENOENT"
|
|
660
|
+
) {
|
|
661
|
+
throw error;
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
treeState ??= createEmptyStubPiTreeState();
|
|
666
|
+
if (opts.resume) {
|
|
667
|
+
treeState.currentLeafId = deriveStubLeafIdFromEntries(treeState);
|
|
668
|
+
}
|
|
669
|
+
this.treeStateByFile.set(opts.treeFile, treeState);
|
|
670
|
+
const piHandle = new StubPiTreeHandle({
|
|
671
|
+
sessionId: `stub-${++this.seq}`,
|
|
672
|
+
treeFile: opts.treeFile,
|
|
673
|
+
isResumed: opts.resume,
|
|
674
|
+
toolCallScriptResolver: this.toolCallScriptResolver,
|
|
675
|
+
state: treeState,
|
|
676
|
+
persistState: () => persistState(treeState),
|
|
677
|
+
runDetails: {
|
|
678
|
+
availableToolNames: opts.piConfig?.availableToolNames ?? [],
|
|
679
|
+
},
|
|
680
|
+
});
|
|
681
|
+
this.sessions.push(piHandle);
|
|
682
|
+
if (!opts.resume) {
|
|
683
|
+
await persistState(treeState);
|
|
684
|
+
}
|
|
685
|
+
return piHandle;
|
|
686
|
+
}
|
|
687
|
+
}
|