@leitwerk-dev/test-support 0.3.0 → 0.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.
- package/dist/{chunk-OE4NHDVS.js → chunk-3RWI5WJK.js} +2 -2
- package/dist/{chunk-5BZSJ4OO.js → chunk-DNUGHAYN.js} +37 -4
- package/dist/chunk-DNUGHAYN.js.map +1 -0
- package/dist/{chunk-P2FF4AP7.js → chunk-FDXRT6UZ.js} +57 -2
- package/dist/chunk-FDXRT6UZ.js.map +1 -0
- package/dist/{chunk-E4Y7XND5.js → chunk-WRAVDPEM.js} +16 -27
- package/dist/chunk-WRAVDPEM.js.map +1 -0
- package/dist/extension-integration-harness.d.ts +2 -2
- package/dist/extension-integration-harness.d.ts.map +1 -1
- package/dist/fixtures.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +9 -26
- package/dist/index.js.map +1 -1
- package/dist/integration-harness.d.ts +2 -0
- package/dist/integration-harness.d.ts.map +1 -1
- package/dist/integration.d.ts +1 -1
- package/dist/integration.d.ts.map +1 -1
- package/dist/integration.js +54 -101
- package/dist/integration.js.map +1 -1
- package/dist/local-git.d.ts +9 -0
- package/dist/local-git.d.ts.map +1 -1
- package/dist/local-git.js +31 -0
- package/dist/local-git.js.map +1 -1
- package/dist/model-provider-fixtures.d.ts +7 -0
- package/dist/model-provider-fixtures.d.ts.map +1 -1
- package/dist/process.d.ts +32 -2
- package/dist/process.d.ts.map +1 -1
- package/dist/process.js +24 -15
- package/dist/process.js.map +1 -1
- package/dist/server-extension-test-harness.d.ts +3 -1
- package/dist/server-extension-test-harness.d.ts.map +1 -1
- package/dist/stub-worker-entry.js +1 -1
- package/dist/supported-question-fixtures.d.ts.map +1 -1
- package/dist/worker-testing/index.d.ts +1 -1
- package/dist/worker-testing/index.d.ts.map +1 -1
- package/dist/worker-testing/index.js +7 -4
- package/dist/worker-testing/index.js.map +1 -1
- package/dist/worker-testing/schema-driven-stub-pi.d.ts.map +1 -1
- package/dist/worker-testing/stub-pi-tree-handle.d.ts +15 -0
- package/dist/worker-testing/stub-pi-tree-handle.d.ts.map +1 -1
- package/dist/worker-testing/worker-start-payload.d.ts.map +1 -1
- package/package.json +10 -10
- package/src/extension-integration-harness.ts +44 -139
- package/src/index.ts +2 -0
- package/src/integration-harness.ts +17 -1
- package/src/integration.ts +1 -0
- package/src/local-git.ts +34 -0
- package/src/model-provider-fixtures.ts +40 -0
- package/src/process.ts +22 -12
- package/src/server-extension-test-harness.ts +40 -1
- package/src/supported-question-fixtures.ts +0 -20
- package/src/worker-testing/index.ts +1 -0
- package/src/worker-testing/schema-driven-stub-pi.ts +11 -23
- package/src/worker-testing/stub-pi-tree-handle.ts +34 -1
- package/src/worker-testing/worker-start-payload.ts +1 -0
- package/dist/chunk-5BZSJ4OO.js.map +0 -1
- package/dist/chunk-E4Y7XND5.js.map +0 -1
- package/dist/chunk-P2FF4AP7.js.map +0 -1
- /package/dist/{chunk-OE4NHDVS.js.map → chunk-3RWI5WJK.js.map} +0 -0
package/src/process.ts
CHANGED
|
@@ -383,6 +383,8 @@ export async function createExtensionTestHarness(options: ExtensionTestHarnessOp
|
|
|
383
383
|
name: string,
|
|
384
384
|
args: Record<string, unknown>,
|
|
385
385
|
fixture: ExtensionToolFixture = {},
|
|
386
|
+
/** @internal */
|
|
387
|
+
reportProgress: (report: TurnProgressReport) => void = () => {},
|
|
386
388
|
) {
|
|
387
389
|
assertOpen();
|
|
388
390
|
const tool = tools.get(name);
|
|
@@ -415,6 +417,7 @@ export async function createExtensionTestHarness(options: ExtensionTestHarnessOp
|
|
|
415
417
|
process,
|
|
416
418
|
projects,
|
|
417
419
|
turn,
|
|
420
|
+
reportProgress,
|
|
418
421
|
project:
|
|
419
422
|
projects.find((project) => project.key === args.projectKey) ??
|
|
420
423
|
(projects.length === 1 ? (projects[0] ?? null) : null),
|
|
@@ -647,6 +650,9 @@ export async function createExtensionTestHarness(options: ExtensionTestHarnessOp
|
|
|
647
650
|
const prompts: string[] = [];
|
|
648
651
|
const tools: { name: string; arguments: Record<string, unknown> }[] = [];
|
|
649
652
|
const progress: TurnProgressReport[] = [];
|
|
653
|
+
const reportProgress = (report: TurnProgressReport) => {
|
|
654
|
+
progress.push(structuredClone(report));
|
|
655
|
+
};
|
|
650
656
|
const completed: ExtensionTurnResponse[] = [];
|
|
651
657
|
const requestedTools = new Set<string>();
|
|
652
658
|
const parked: (string | undefined)[] = [];
|
|
@@ -664,18 +670,21 @@ export async function createExtensionTestHarness(options: ExtensionTestHarnessOp
|
|
|
664
670
|
if (!allowed?.includes(name))
|
|
665
671
|
throw new Error(`Integration tool '${name}' is not declared for '${id}'`);
|
|
666
672
|
tools.push({ name, arguments: structuredClone(args) });
|
|
667
|
-
return callTool(
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
673
|
+
return callTool(
|
|
674
|
+
name,
|
|
675
|
+
args,
|
|
676
|
+
{
|
|
677
|
+
...defaults,
|
|
678
|
+
...options.fixture,
|
|
679
|
+
processId: definition.id,
|
|
680
|
+
params: base.params,
|
|
681
|
+
state: base.state,
|
|
682
|
+
position: { selectedTurnId: id, lifecycleStatus: "active" },
|
|
683
|
+
},
|
|
684
|
+
reportProgress,
|
|
685
|
+
);
|
|
678
686
|
},
|
|
687
|
+
reportProgress,
|
|
679
688
|
};
|
|
680
689
|
await handler({
|
|
681
690
|
ctx,
|
|
@@ -686,7 +695,6 @@ export async function createExtensionTestHarness(options: ExtensionTestHarnessOp
|
|
|
686
695
|
...(def.resolveIntegrationTools?.(base.params, base.state) ??
|
|
687
696
|
def.integrationTools ??
|
|
688
697
|
[]),
|
|
689
|
-
...(def.askQuestions ? ["ask_questions"] : []),
|
|
690
698
|
])
|
|
691
699
|
requestedTools.add(name);
|
|
692
700
|
const prepared = await def.prepare?.({
|
|
@@ -694,6 +702,8 @@ export async function createExtensionTestHarness(options: ExtensionTestHarnessOp
|
|
|
694
702
|
callIntegrationTool: ctx.callIntegrationTool,
|
|
695
703
|
reportProgress: ctx.reportProgress,
|
|
696
704
|
});
|
|
705
|
+
if (def.askQuestions && (def.resolveAskQuestions?.({ ...ctx, prepared }) ?? true))
|
|
706
|
+
requestedTools.add("ask_questions");
|
|
697
707
|
prompts.push(await def.prompt({ ...ctx, prepared }));
|
|
698
708
|
const response = responses.shift();
|
|
699
709
|
if (!response)
|
|
@@ -28,6 +28,8 @@ export function createPollingTestExtension<T>(
|
|
|
28
28
|
poll(): Promise<T>;
|
|
29
29
|
}
|
|
30
30
|
| undefined,
|
|
31
|
+
/** Disable scheduled polling so tests control every observation. @internal */
|
|
32
|
+
manual = false,
|
|
31
33
|
) {
|
|
32
34
|
let provider: ReturnType<typeof setup>;
|
|
33
35
|
return {
|
|
@@ -35,7 +37,26 @@ export function createPollingTestExtension<T>(
|
|
|
35
37
|
manifest,
|
|
36
38
|
/** @internal */
|
|
37
39
|
setupServer(api: ServerExtensionAPI) {
|
|
38
|
-
provider = setup(
|
|
40
|
+
provider = setup(
|
|
41
|
+
manual
|
|
42
|
+
? {
|
|
43
|
+
...api,
|
|
44
|
+
get<T>(token: import("@leitwerk-dev/process-sdk").CapabilityToken<T>) {
|
|
45
|
+
const value = api.get(token);
|
|
46
|
+
return token === coreHostCapabilities.serverSetup && value && !Array.isArray(value)
|
|
47
|
+
? ({
|
|
48
|
+
...value,
|
|
49
|
+
polling: {
|
|
50
|
+
create: ({ pollOnce }: { pollOnce: () => Promise<unknown> }) => ({
|
|
51
|
+
poll: pollOnce,
|
|
52
|
+
}),
|
|
53
|
+
},
|
|
54
|
+
} as T)
|
|
55
|
+
: value;
|
|
56
|
+
},
|
|
57
|
+
}
|
|
58
|
+
: api,
|
|
59
|
+
);
|
|
39
60
|
},
|
|
40
61
|
/** @public */
|
|
41
62
|
poll() {
|
|
@@ -115,6 +136,22 @@ function createDefaultServerSetupDeps(): CoreServerSetupDeps {
|
|
|
115
136
|
serverBaseUrl: "https://leitwerk.example",
|
|
116
137
|
components: {},
|
|
117
138
|
externalWrites: createInMemoryExternalWriteLog(),
|
|
139
|
+
publications: {
|
|
140
|
+
publication: () => null,
|
|
141
|
+
publicationByExternalId: () => null,
|
|
142
|
+
reservePublication() {
|
|
143
|
+
throw new Error("Configure publication storage for this test");
|
|
144
|
+
},
|
|
145
|
+
finishPublication() {
|
|
146
|
+
throw new Error("Configure publication storage for this test");
|
|
147
|
+
},
|
|
148
|
+
releaseRejectedPublication() {
|
|
149
|
+
throw new Error("Configure publication storage for this test");
|
|
150
|
+
},
|
|
151
|
+
markPublicationTriggered() {
|
|
152
|
+
throw new Error("Configure publication storage for this test");
|
|
153
|
+
},
|
|
154
|
+
},
|
|
118
155
|
polling: {
|
|
119
156
|
create(options) {
|
|
120
157
|
return { poll: options.pollOnce };
|
|
@@ -140,6 +177,7 @@ function createDefaultServerSetupDeps(): CoreServerSetupDeps {
|
|
|
140
177
|
events: { create: () => {}, listByInstance: () => [] },
|
|
141
178
|
broadcaster: { sendDurable: () => {} },
|
|
142
179
|
commands: {
|
|
180
|
+
applyProcessObservation: async () => ({ ok: true, process: null }),
|
|
143
181
|
getDeferredProcessActivationSnapshots: () => ({ outcome: "process_not_found" }),
|
|
144
182
|
activateDeferredProcess: async () => ({
|
|
145
183
|
ok: true,
|
|
@@ -172,6 +210,7 @@ function createDefaultServerSetupDeps(): CoreServerSetupDeps {
|
|
|
172
210
|
resolveUiOptions: async () => ({}),
|
|
173
211
|
resolveUiRelaunchInput: async (_launcherId, previousInput) => ({ ...previousInput }),
|
|
174
212
|
resolveUiLauncher: async () => ({ ok: false as const, errors: [] }),
|
|
213
|
+
resolveUiLauncherPreview: async () => ({ ok: false as const, errors: [] }),
|
|
175
214
|
},
|
|
176
215
|
launcherRecentValues: {
|
|
177
216
|
list: () => ({}),
|
|
@@ -48,19 +48,13 @@ export interface QuestionRequestFixture {
|
|
|
48
48
|
/** Question content with generated stable option identities. @public */
|
|
49
49
|
export interface QuestionFixtureOptions {
|
|
50
50
|
/** @public */
|
|
51
|
-
|
|
52
51
|
question?: string;
|
|
53
|
-
|
|
54
52
|
/** @public */
|
|
55
|
-
|
|
56
53
|
selection?: "single" | "multiple";
|
|
57
|
-
|
|
58
54
|
/** @public */
|
|
59
|
-
|
|
60
55
|
options?: readonly {
|
|
61
56
|
/** @public */
|
|
62
57
|
label: string;
|
|
63
|
-
|
|
64
58
|
/** @public */
|
|
65
59
|
details?: string | null;
|
|
66
60
|
}[];
|
|
@@ -86,13 +80,9 @@ export type QuestionFixtureResolution =
|
|
|
86
80
|
| {
|
|
87
81
|
/** @public */
|
|
88
82
|
status: "answered";
|
|
89
|
-
|
|
90
83
|
/** @public */
|
|
91
|
-
|
|
92
84
|
answers: readonly string[];
|
|
93
|
-
|
|
94
85
|
/** @public */
|
|
95
|
-
|
|
96
86
|
actor?: Actor;
|
|
97
87
|
}
|
|
98
88
|
| {
|
|
@@ -103,32 +93,22 @@ export type QuestionFixtureResolution =
|
|
|
103
93
|
/** Reference inputs and question content, without durable status overrides. @public */
|
|
104
94
|
export interface QuestionRequestFixtureOptions {
|
|
105
95
|
/** @public */
|
|
106
|
-
|
|
107
96
|
id?: string;
|
|
108
|
-
|
|
109
97
|
/** @public */
|
|
110
|
-
|
|
111
98
|
process?: {
|
|
112
99
|
/** @public */
|
|
113
100
|
id: string;
|
|
114
101
|
};
|
|
115
|
-
|
|
116
102
|
/** @public */
|
|
117
|
-
|
|
118
103
|
turn?: {
|
|
119
104
|
/** @public */
|
|
120
105
|
id: string;
|
|
121
|
-
|
|
122
106
|
/** @public */
|
|
123
107
|
instanceId: string;
|
|
124
108
|
};
|
|
125
|
-
|
|
126
109
|
/** @public */
|
|
127
|
-
|
|
128
110
|
questions?: readonly QuestionFixtureOptions[];
|
|
129
|
-
|
|
130
111
|
/** @public */
|
|
131
|
-
|
|
132
112
|
resolution?: QuestionFixtureResolution;
|
|
133
113
|
}
|
|
134
114
|
|
|
@@ -2,6 +2,7 @@ export { flushAsyncWork } from "@leitwerk-dev/worker-protocol";
|
|
|
2
2
|
export { createInProcessWorkerSpawn } from "../in-process-worker.js";
|
|
3
3
|
export { createStubToolScriptController } from "./stub-pi-controls.js";
|
|
4
4
|
export {
|
|
5
|
+
formatBranchText,
|
|
5
6
|
StubPiTreeHandle,
|
|
6
7
|
StubPiTreeHandleFactory,
|
|
7
8
|
type StubToolCallScriptCall,
|
|
@@ -46,33 +46,21 @@ export function synthesizeStubToolArgs(
|
|
|
46
46
|
|
|
47
47
|
/** @internal */
|
|
48
48
|
export function createSchemaDrivenToolCallScriptResolver(): StubToolCallScriptResolver {
|
|
49
|
-
return ({ tools }: StubToolCallScriptResolverContext) => {
|
|
49
|
+
return ({ tools: availableTools }: StubToolCallScriptResolverContext) => {
|
|
50
|
+
// Failure requires an explicit script; the default stub completes successful turns.
|
|
51
|
+
const tools = availableTools.filter((tool) => tool.name !== "abort_turn");
|
|
50
52
|
const markdownTool = tools.find((tool) => tool.name === "markdown_result");
|
|
51
53
|
const completionTool = tools.find(
|
|
52
54
|
(tool) => tool.name !== "markdown_result" && tool.name !== "upload_result_images",
|
|
53
55
|
);
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
toolName: completionTool.name,
|
|
63
|
-
args: synthesizeStubToolArgs(completionTool.parameters),
|
|
64
|
-
},
|
|
65
|
-
],
|
|
66
|
-
};
|
|
67
|
-
}
|
|
68
|
-
const tool = markdownTool ?? completionTool ?? tools[0];
|
|
69
|
-
if (!tool) {
|
|
70
|
-
return undefined;
|
|
71
|
-
}
|
|
72
|
-
return {
|
|
73
|
-
toolName: tool.name,
|
|
74
|
-
args: synthesizeStubToolArgs(tool.parameters),
|
|
75
|
-
};
|
|
56
|
+
const selectedTools =
|
|
57
|
+
markdownTool && completionTool
|
|
58
|
+
? [markdownTool, completionTool]
|
|
59
|
+
: [markdownTool ?? completionTool ?? tools[0]];
|
|
60
|
+
const calls = selectedTools
|
|
61
|
+
.filter((tool) => tool !== undefined)
|
|
62
|
+
.map((tool) => ({ toolName: tool.name, args: synthesizeStubToolArgs(tool.parameters) }));
|
|
63
|
+
return calls.length > 1 ? { calls } : calls[0];
|
|
76
64
|
};
|
|
77
65
|
}
|
|
78
66
|
|
|
@@ -65,6 +65,19 @@ export interface StubToolCallScriptResolverContext {
|
|
|
65
65
|
tools: readonly PiCustomTool[];
|
|
66
66
|
/** @public */
|
|
67
67
|
instanceId?: string;
|
|
68
|
+
/** Active frozen item when the turn is one item of a mapped LLM turn. @public */
|
|
69
|
+
iteration?: {
|
|
70
|
+
/** @public */
|
|
71
|
+
itemKey: string;
|
|
72
|
+
/** @public */
|
|
73
|
+
itemLabel: string;
|
|
74
|
+
/** @public */
|
|
75
|
+
itemIndex: number;
|
|
76
|
+
/** @public */
|
|
77
|
+
itemCount: number;
|
|
78
|
+
/** @public */
|
|
79
|
+
item: unknown;
|
|
80
|
+
};
|
|
68
81
|
/** @public */
|
|
69
82
|
workspaceRoot?: string;
|
|
70
83
|
/** @public */
|
|
@@ -80,6 +93,25 @@ export type StubToolCallScriptResolver = (
|
|
|
80
93
|
context: StubToolCallScriptResolverContext,
|
|
81
94
|
) => StubToolCallScriptItem | undefined | Promise<StubToolCallScriptItem | undefined>;
|
|
82
95
|
|
|
96
|
+
/** Formats textual branch entries without choosing a session. @internal */
|
|
97
|
+
export function formatBranchText(
|
|
98
|
+
entries: readonly PiTreeEntry[] = [],
|
|
99
|
+
missingMessageText?: string,
|
|
100
|
+
): string {
|
|
101
|
+
return entries
|
|
102
|
+
.map((entry) =>
|
|
103
|
+
entry.type === "custom_message"
|
|
104
|
+
? entry.content
|
|
105
|
+
: entry.type === "message"
|
|
106
|
+
? entry.message
|
|
107
|
+
? entry.message.content
|
|
108
|
+
: missingMessageText
|
|
109
|
+
: "",
|
|
110
|
+
)
|
|
111
|
+
.filter((value): value is string => typeof value === "string")
|
|
112
|
+
.join("\n\n");
|
|
113
|
+
}
|
|
114
|
+
|
|
83
115
|
function stringifyToolResult(result: unknown): string {
|
|
84
116
|
if (typeof result === "string") {
|
|
85
117
|
return result;
|
|
@@ -660,7 +692,7 @@ export class StubPiTreeHandle implements PiTreeHandle {
|
|
|
660
692
|
createdEntryIds.push(intermediateEntryId);
|
|
661
693
|
}
|
|
662
694
|
}
|
|
663
|
-
} else if (tools.
|
|
695
|
+
} else if ([...tools.keys()].some((name) => name !== "abort_turn") && !hasScriptedChunks) {
|
|
664
696
|
throw new Error(
|
|
665
697
|
`Stub Pi prompt requires a stub tool-call script when tools are provided (${[...tools.keys()].join(", ")})`,
|
|
666
698
|
);
|
|
@@ -952,6 +984,7 @@ export class StubPiTreeHandleFactory implements PiTreeHandleFactory {
|
|
|
952
984
|
this.toolCallScriptResolver?.({
|
|
953
985
|
...context,
|
|
954
986
|
instanceId: opts.instanceId,
|
|
987
|
+
...(opts.iteration ? { iteration: opts.iteration } : {}),
|
|
955
988
|
workspaceRoot: opts.workspaceRoot,
|
|
956
989
|
sessionCwd: opts.sessionCwd,
|
|
957
990
|
})
|
|
@@ -90,6 +90,7 @@ export function createTestLlmWorkerStartPayload(
|
|
|
90
90
|
]);
|
|
91
91
|
const configSnapshot = createTestConfigSnapshot();
|
|
92
92
|
configSnapshot.pi.agent_dir = path.join(options.root, "agent");
|
|
93
|
+
configSnapshot.pi.default_model_profile = model.profileId;
|
|
93
94
|
configSnapshot.pi.model_profiles = [
|
|
94
95
|
{
|
|
95
96
|
id: model.profileId,
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server-extension-test-harness.ts"],"sourcesContent":["import { type ExtensionCatalog, setupServerExtensions } from \"@leitwerk-dev/extension-runtime\";\nimport { buildExtensionCatalogFromModules } from \"@leitwerk-dev/extension-runtime/testing\";\nimport {\n\tbindExternalWrites,\n\ttype ExternalWriteLogRepoLike,\n} from \"@leitwerk-dev/external-writes/internal\";\nimport {\n\ttype CoreServerSetupDeps,\n\tcoreHostCapabilities,\n\tcreateCapabilityAccessor,\n\tcreateEventBus,\n\ttype IntegrationToolDefinition,\n\ttype LeitwerkExtensionModule,\n\ttype ProvidedCapability,\n\ttype ServerExtensionAPI,\n\ttype ServerExtensionEventMap,\n} from \"@leitwerk-dev/process-sdk\";\nimport { flushAsyncWork } from \"@leitwerk-dev/worker-protocol\";\n\nexport { flushAsyncWork };\n\n/** Register a test provider and expose its poll result without erasing its type. @public */\nexport function createPollingTestExtension<T>(\n\tmanifest: LeitwerkExtensionModule[\"manifest\"],\n\tsetup: (api: ServerExtensionAPI) =>\n\t\t| {\n\t\t\t\t/** @internal */\n\t\t\t\tpoll(): Promise<T>;\n\t\t }\n\t\t| undefined,\n) {\n\tlet provider: ReturnType<typeof setup>;\n\treturn {\n\t\t/** @internal */\n\t\tmanifest,\n\t\t/** @internal */\n\t\tsetupServer(api: ServerExtensionAPI) {\n\t\t\tprovider = setup(api);\n\t\t},\n\t\t/** @public */\n\t\tpoll() {\n\t\t\tif (!provider) throw new Error(`Test provider '${manifest.id}' has not been initialized`);\n\t\t\treturn provider.poll();\n\t\t},\n\t};\n}\n\n/** @internal */\nexport function createToolCollector(\n\twrites: ExternalWriteLogRepoLike = createInMemoryExternalWriteLog(),\n) {\n\tconst tools = new Map<string, IntegrationToolDefinition>();\n\tconst api = {\n\t\ttool: (tool: IntegrationToolDefinition) =>\n\t\t\ttools.set(tool.name, {\n\t\t\t\t...tool,\n\t\t\t\texecute: (ctx, args) =>\n\t\t\t\t\ttool.execute(\n\t\t\t\t\t\t{ ...ctx, externalWrites: bindExternalWrites(writes, ctx.process.id) },\n\t\t\t\t\t\targs,\n\t\t\t\t\t),\n\t\t\t}),\n\t} as unknown as ServerExtensionAPI;\n\treturn {\n\t\t/** @internal */\n\t\tapi,\n\t\t/** @internal */\n\t\ttools,\n\t};\n}\n\n/** @internal */\nexport interface InMemoryExternalWriteLog {\n\t/** @internal */\n\trecords: {\n\t\t/** @internal */\n\t\tdedupKey: string;\n\t}[];\n\t/** @internal */\n\thasDedupKey(key: string): boolean;\n\t/** @internal */\n\trecord(input: {\n\t\t/** @internal */\n\t\tdedupKey: string;\n\t}): {\n\t\t/** @internal */\n\t\tdedupKey: string;\n\t};\n\t/** @internal */\n\tgetDedupKeys(): ReadonlySet<string>;\n}\n\n/** @internal */\nexport function createInMemoryExternalWriteLog(): InMemoryExternalWriteLog {\n\tconst dedupKeys = new Set<string>();\n\tconst records: { dedupKey: string }[] = [];\n\treturn {\n\t\trecords,\n\t\thasDedupKey(key: string) {\n\t\t\treturn dedupKeys.has(key);\n\t\t},\n\t\trecord(input: { dedupKey: string }) {\n\t\t\tdedupKeys.add(input.dedupKey);\n\t\t\trecords.push(input);\n\t\t\treturn input;\n\t\t},\n\t\tgetDedupKeys() {\n\t\t\treturn dedupKeys;\n\t\t},\n\t};\n}\n\nfunction createDefaultServerSetupDeps(): CoreServerSetupDeps {\n\treturn {\n\t\tserverBaseUrl: \"https://leitwerk.example\",\n\t\tcomponents: {},\n\t\texternalWrites: createInMemoryExternalWriteLog(),\n\t\tpolling: {\n\t\t\tcreate(options) {\n\t\t\t\treturn { poll: options.pollOnce };\n\t\t\t},\n\t\t},\n\t\trepositoryCredentials: { register: () => {} },\n\t\tprocesses: {\n\t\t\tcreate: () => {\n\t\t\t\tthrow new Error(\"not used\");\n\t\t\t},\n\t\t\tgetById: () => null,\n\t\t\tlistAll: () => [],\n\t\t\tupdate: () => null,\n\t\t},\n\t\tprojects: {\n\t\t\tcreate: () => {\n\t\t\t\tthrow new Error(\"not used\");\n\t\t\t},\n\t\t\tgetByInstanceAndKey: () => null,\n\t\t\tupdate: () => null,\n\t\t\tlistByInstance: () => [],\n\t\t},\n\t\tevents: { create: () => {}, listByInstance: () => [] },\n\t\tbroadcaster: { sendDurable: () => {} },\n\t\tcommands: {\n\t\t\tgetDeferredProcessActivationSnapshots: () => ({ outcome: \"process_not_found\" }),\n\t\t\tactivateDeferredProcess: async () => ({\n\t\t\t\tok: true,\n\t\t\t\tprocess: null,\n\t\t\t\tdata: { outcome: \"not_applicable\" },\n\t\t\t}),\n\t\t\tparkDeferredProcessActivationFailure: async () => ({\n\t\t\t\tok: true,\n\t\t\t\tprocess: null,\n\t\t\t\tdata: { outcome: \"parked\" },\n\t\t\t}),\n\t\t\tstartProcess: async () => ({ ok: true, process: null }),\n\t\t\tabortProcess: async () => ({ ok: true, process: null }),\n\t\t\tretryProcess: async () => ({ ok: true, process: null }),\n\t\t\tcontinueFailedTurn: async () => ({ ok: true, process: null }),\n\t\t\tqueueInputs: async () => ({ ok: true, process: null }),\n\t\t},\n\t\tprocessActions: {\n\t\t\tlistVisibleActions: () => [],\n\t\t\texecuteAction: async () => ({ ok: true, process: null }),\n\t\t},\n\t\texternalSources: {\n\t\t\tlistArmed: () => [],\n\t\t\tfire: async () => ({ ok: true, process: null }),\n\t\t},\n\t\tgetSupervisor: () => undefined,\n\t\tlauncherService: {\n\t\t\tlistUiLaunchers: () => [],\n\t\t\tresolveUiDefaults: async () => ({}),\n\t\t\tresolveUiOptions: async () => ({}),\n\t\t\tresolveUiRelaunchInput: async (_launcherId, previousInput) => ({ ...previousInput }),\n\t\t\tresolveUiLauncher: async () => ({ ok: false as const, errors: [] }),\n\t\t},\n\t\tlauncherRecentValues: {\n\t\t\tlist: () => ({}),\n\t\t\trecord: () => {},\n\t\t},\n\t\tlauncherModelConfigs: {\n\t\t\tgetSchema: async () => null,\n\t\t\tpreview: async () => null,\n\t\t},\n\t\tlaunchPlans: {\n\t\t\tasync prepare(launchPlan, opts) {\n\t\t\t\treturn {\n\t\t\t\t\tok: true as const,\n\t\t\t\t\tlaunchPlan,\n\t\t\t\t\tmodelConfig: opts?.modelConfig ?? {},\n\t\t\t\t\twarnings: [],\n\t\t\t\t};\n\t\t\t},\n\t\t},\n\t\tlaunchRuns: {\n\t\t\tasync startProgrammatic() {\n\t\t\t\tthrow new Error(\"not used\");\n\t\t\t},\n\t\t\tasync startWatcher() {\n\t\t\t\tthrow new Error(\"not used\");\n\t\t\t},\n\t\t},\n\t};\n}\n\n/** @public */\nexport function createTestServerSetupCapability(\n\toverrides: Partial<CoreServerSetupDeps> = {},\n): CoreServerSetupDeps {\n\tconst defaults = createDefaultServerSetupDeps();\n\treturn {\n\t\t...defaults,\n\t\t...overrides,\n\t\tprocesses: { ...defaults.processes, ...overrides.processes },\n\t\tprojects: { ...defaults.projects, ...overrides.projects },\n\t\tevents: { ...defaults.events, ...overrides.events },\n\t\tbroadcaster: { ...defaults.broadcaster, ...overrides.broadcaster },\n\t\tcommands: { ...defaults.commands, ...overrides.commands },\n\t\tprocessActions: { ...defaults.processActions, ...overrides.processActions },\n\t\texternalSources: { ...defaults.externalSources, ...overrides.externalSources },\n\t\tlauncherService: { ...defaults.launcherService, ...overrides.launcherService },\n\t\tlauncherRecentValues: {\n\t\t\t...defaults.launcherRecentValues,\n\t\t\t...overrides.launcherRecentValues,\n\t\t},\n\t\tlauncherModelConfigs: {\n\t\t\t...defaults.launcherModelConfigs,\n\t\t\t...overrides.launcherModelConfigs,\n\t\t},\n\t\tlaunchPlans: { ...defaults.launchPlans, ...overrides.launchPlans },\n\t\tlaunchRuns: { ...defaults.launchRuns, ...overrides.launchRuns },\n\t};\n}\n\n/** @internal */\nexport interface ServerExtensionTestHarness {\n\t/** @internal */\n\tcatalog: ExtensionCatalog;\n\t/** @internal */\n\tevents: ReturnType<typeof createEventBus>;\n\t/** @internal */\n\tserverSetup: CoreServerSetupDeps;\n\t/** @internal */\n\tstartHooks: Array<() => void | Promise<void>>;\n\t/** @internal */\n\tstopHooks: Array<() => void | Promise<void>>;\n\t/** @internal */\n\tflushAsyncWork: typeof flushAsyncWork;\n}\n\n/** @internal */\nexport async function setupServerExtensionTest(input: {\n\t/** @internal */\n\tmodules: readonly LeitwerkExtensionModule[];\n\t/** @internal */\n\tprovidedCapabilities?: readonly ProvidedCapability[];\n\t/** @internal */\n\tserverSetup?: Partial<CoreServerSetupDeps>;\n\t/** @internal */\n\tonStart?: (handler: () => void | Promise<void>) => void;\n\t/** @internal */\n\tonStop?: (handler: () => void | Promise<void>) => void;\n}): Promise<ServerExtensionTestHarness> {\n\tconst catalog = await buildExtensionCatalogFromModules(input.modules);\n\tconst events = createEventBus<ServerExtensionEventMap>();\n\tconst serverSetup = createTestServerSetupCapability(input.serverSetup);\n\tconst capabilities = createCapabilityAccessor([\n\t\t{\n\t\t\ttoken: coreHostCapabilities.serverSetup,\n\t\t\tvalue: serverSetup,\n\t\t},\n\t\t...(input.providedCapabilities ?? []),\n\t]);\n\tconst startHooks: Array<() => void | Promise<void>> = [];\n\tconst stopHooks: Array<() => void | Promise<void>> = [];\n\n\tawait setupServerExtensions(catalog, {\n\t\tevents,\n\t\tprovide: capabilities.provide.bind(capabilities),\n\t\tget: capabilities.get.bind(capabilities),\n\t\trequire: capabilities.require.bind(capabilities),\n\t\ttool() {},\n\t\tonStart(handler) {\n\t\t\tstartHooks.push(handler);\n\t\t\tinput.onStart?.(handler);\n\t\t},\n\t\tonStop(handler) {\n\t\t\tstopHooks.push(handler);\n\t\t\tinput.onStop?.(handler);\n\t\t},\n\t});\n\n\treturn {\n\t\tcatalog,\n\t\tevents,\n\t\tserverSetup,\n\t\tstartHooks,\n\t\tstopHooks,\n\t\tflushAsyncWork,\n\t};\n}\n"],"mappings":";AAAA,SAAgC,6BAA6B;AAC7D,SAAS,wCAAwC;AACjD;AAAA,EACC;AAAA,OAEM;AACP;AAAA,EAEC;AAAA,EACA;AAAA,EACA;AAAA,OAMM;AACP,SAAS,sBAAsB;AAKxB,SAAS,2BACf,UACA,OAMC;AACD,MAAI;AACJ,SAAO;AAAA;AAAA,IAEN;AAAA;AAAA,IAEA,YAAY,KAAyB;AACpC,iBAAW,MAAM,GAAG;AAAA,IACrB;AAAA;AAAA,IAEA,OAAO;AACN,UAAI,CAAC,SAAU,OAAM,IAAI,MAAM,kBAAkB,SAAS,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gBAAgB;AAAA,IAC7E,iBAAiB,EAAE,GAAG,SAAS,iBAAiB,GAAG,UAAU,gBAAgB;AAAA,IAC7E,sBAAsB;AAAA,MACrB,GAAG,SAAS;AAAA,MACZ,GAAG,UAAU;AAAA,IACd;AAAA,IACA,sBAAsB;AAAA,MACrB,GAAG,SAAS;AAAA,MACZ,GAAG,UAAU;AAAA,IACd;AAAA,IACA,aAAa,EAAE,GAAG,SAAS,aAAa,GAAG,UAAU,YAAY;AAAA,IACjE,YAAY,EAAE,GAAG,SAAS,YAAY,GAAG,UAAU,WAAW;AAAA,EAC/D;AACD;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/worker-testing/stub-pi-tree-handle.ts","../src/worker-testing/schema-driven-stub-pi.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { CURRENT_SESSION_VERSION, type SessionHeader } from \"@earendil-works/pi-coding-agent\";\nimport type {\n\tPiCustomMessageInput,\n\tPiCustomTool,\n\tPiEvent,\n\tPiEventHandler,\n\tPiPromptOptions,\n\tPiRunDetails,\n\tPiSessionDiagnostic,\n\tPiSessionDiagnosticHandler,\n\tPiTreeEntry,\n\tPiTreeHandle,\n\tPiTreeNode,\n\tPiTurnExecutionResult,\n} from \"@leitwerk-dev/process-sdk\";\nimport { isEnoent } from \"@leitwerk-dev/process-sdk\";\nimport type {\n\tPiManagedBootstrapOptions,\n\tPiManagedBootstrapResult,\n\tPiTreeHandleFactory,\n\tPiTreeHandleOptions,\n\tPiTreePlanningOptions,\n\tPiTreePlanningSnapshot,\n} from \"@leitwerk-dev/worker\";\n\n/** @public */\nexport interface StubToolCallScriptCall {\n\t/** @public */\n\ttoolName: string;\n\t/** @public */\n\targs: Record<string, unknown>;\n\t/** @internal */\n\tintermediateEntryCount?: number;\n}\n\n/** @public */\nexport type StubToolCallScriptItem =\n\t| StubToolCallScriptCall\n\t| {\n\t\t\t/** @public */\n\t\t\tcalls: readonly StubToolCallScriptCall[];\n\t\t\t/** @public */\n\t\t\ttextChunks?: readonly string[];\n\t\t\t/** @public */\n\t\t\tthinkingChunks?: readonly string[];\n\t\t\t/** @public */\n\t\t\tchunkDelayMs?: number;\n\t\t\t/** Optional scripted model reaction to a tool result, within the same turn. @internal */\n\t\t\tafterToolResult?: (\n\t\t\t\tcall: StubToolCallScriptCall,\n\t\t\t\tresult: unknown,\n\t\t\t) => StubToolCallScriptCall | undefined;\n\t };\n\n/** @public */\nexport interface StubToolCallScriptResolverContext {\n\t/** @public */\n\tpromptText: string;\n\t/** Identified turn prompt, when the SDK prompt uses a custom message. @internal */\n\tidentifiedPromptText?: string;\n\t/** @public */\n\ttools: readonly PiCustomTool[];\n\t/** @public */\n\tinstanceId?: string;\n\t/** @public */\n\tworkspaceRoot?: string;\n\t/** @public */\n\tsessionCwd?: string;\n\t/** @public */\n\ttreeFile: string;\n\t/** @internal */\n\tturnSequence: number;\n}\n\n/** @public */\nexport type StubToolCallScriptResolver = (\n\tcontext: StubToolCallScriptResolverContext,\n) => StubToolCallScriptItem | undefined | Promise<StubToolCallScriptItem | undefined>;\n\nfunction stringifyToolResult(result: unknown): string {\n\tif (typeof result === \"string\") {\n\t\treturn result;\n\t}\n\tif (result === undefined) {\n\t\treturn \"ok\";\n\t}\n\ttry {\n\t\treturn JSON.stringify(result, null, 2);\n\t} catch {\n\t\treturn String(result);\n\t}\n}\n\nfunction expandStubToolCallScriptItem(item: StubToolCallScriptItem): StubToolCallScriptCall[] {\n\tif (\"calls\" in item) {\n\t\treturn [...item.calls];\n\t}\n\treturn [item];\n}\n\nfunction stubToolCallId(turnSeq: number, totalCalls: number, index: number): string {\n\tif (totalCalls <= 1) {\n\t\treturn `tool-${turnSeq}`;\n\t}\n\treturn `tool-${turnSeq}-${index + 1}`;\n}\n\n/** @internal */\ninterface StubPiTreeState {\n\t/** @internal */\n\theader?: SessionHeader;\n\t/** @internal */\n\tturnSeq: number;\n\t/** @internal */\n\tcurrentLeafId: string | null;\n\t/** @internal */\n\tentries: Map<string, PiTreeEntry>;\n\t/** @internal */\n\tchildIdsByParent: Map<string | null, string[]>;\n}\n\ninterface PersistedStubPiTreeState {\n\tturnSeq: number;\n\tcurrentLeafId: string | null;\n\tentries: PiTreeEntry[];\n\tchildIdsByParent: Array<{ parentId: string | null; childIds: string[] }>;\n}\n\nfunction createEmptyStubPiTreeState(): StubPiTreeState {\n\treturn {\n\t\tturnSeq: 0,\n\t\tcurrentLeafId: null,\n\t\tentries: new Map<string, PiTreeEntry>(),\n\t\tchildIdsByParent: new Map<string | null, string[]>(),\n\t};\n}\n\nfunction indexStubEntry(state: StubPiTreeState, entry: PiTreeEntry): void {\n\tstate.entries.set(entry.id, entry);\n\tconst siblings = state.childIdsByParent.get(entry.parentId) ?? [];\n\tsiblings.push(entry.id);\n\tstate.childIdsByParent.set(entry.parentId, siblings);\n}\n\nfunction deriveStubLeafIdFromEntries(state: StubPiTreeState): string | null {\n\tlet leafId: string | null = null;\n\tfor (const entryId of state.entries.keys()) {\n\t\tleafId = entryId;\n\t}\n\treturn leafId;\n}\n\nfunction serializeStubPiTreeState(state: StubPiTreeState, recordSessionTrace: boolean): string {\n\tif (recordSessionTrace) {\n\t\treturn `${[\n\t\t\tJSON.stringify({\n\t\t\t\t...state.header,\n\t\t\t\tstubState: { turnSeq: state.turnSeq, currentLeafId: state.currentLeafId },\n\t\t\t}),\n\t\t\t...[...state.entries.values()].map((entry) => JSON.stringify(entry)),\n\t\t].join(\"\\n\")}\\n`;\n\t}\n\tconst persisted: PersistedStubPiTreeState = {\n\t\tturnSeq: state.turnSeq,\n\t\tcurrentLeafId: state.currentLeafId,\n\t\tentries: [...state.entries.values()],\n\t\tchildIdsByParent: [...state.childIdsByParent.entries()].map(([parentId, childIds]) => ({\n\t\t\tparentId,\n\t\t\tchildIds: [...childIds],\n\t\t})),\n\t};\n\treturn JSON.stringify(persisted);\n}\n\nfunction deserializeStubPiTreeState(value: string): StubPiTreeState {\n\tconst lines = value.trim().split(\"\\n\");\n\tconst header = JSON.parse(lines[0]) as SessionHeader & {\n\t\tstubState?: { turnSeq: number; currentLeafId: string | null };\n\t};\n\tif (header.type === \"session\") {\n\t\tconst entries = lines\n\t\t\t.slice(1)\n\t\t\t.filter(Boolean)\n\t\t\t.map((line) => JSON.parse(line) as PiTreeEntry);\n\t\tconst state = createEmptyStubPiTreeState();\n\t\tstate.header = header;\n\t\tstate.turnSeq = header.stubState?.turnSeq ?? 0;\n\t\tstate.currentLeafId = header.stubState?.currentLeafId ?? null;\n\t\tfor (const entry of entries) indexStubEntry(state, entry);\n\t\treturn state;\n\t}\n\tconst parsed = JSON.parse(value) as PersistedStubPiTreeState;\n\treturn {\n\t\tturnSeq: typeof parsed.turnSeq === \"number\" ? parsed.turnSeq : 0,\n\t\tcurrentLeafId:\n\t\t\ttypeof parsed.currentLeafId === \"string\" || parsed.currentLeafId === null\n\t\t\t\t? parsed.currentLeafId\n\t\t\t\t: null,\n\t\tentries: new Map((parsed.entries ?? []).map((entry) => [entry.id, entry])),\n\t\tchildIdsByParent: new Map(\n\t\t\t(parsed.childIdsByParent ?? []).map((entry) => [entry.parentId, [...entry.childIds]]),\n\t\t),\n\t};\n}\n\n/** @public */\nexport class StubPiTreeHandle implements PiTreeHandle {\n\t/** @public */\n\treadonly sessionId: string;\n\t/** @internal */\n\treadonly treeFile: string;\n\t/** @internal */\n\treadonly isResumed: boolean;\n\n\t/** @internal */\n\treadonly prompts: string[] = [];\n\t/** @internal */\n\treadonly steers: string[] = [];\n\t/** @internal */\n\tbeforeTurn?: (\n\t\tkind: \"prompt\" | \"literal\" | \"custom\" | \"continue\",\n\t\toptions: PiPromptOptions | undefined,\n\t\tpromptText: string | undefined,\n\t) => boolean | undefined | Promise<boolean | undefined>;\n\n\tprivate _closed = false;\n\tprivate turnAbort = new AbortController();\n\tprivate branchDriftPending = false;\n\tprivate readonly handlers = new Set<PiEventHandler>();\n\tprivate readonly diagnosticHandlers = new Set<PiSessionDiagnosticHandler>();\n\tprivate readonly toolCallScriptResolver?: StubToolCallScriptResolver;\n\tprivate readonly state: StubPiTreeState;\n\tprivate readonly runDetails: PiRunDetails;\n\tprivate readonly persistState?: (() => Promise<void>) | undefined;\n\tprivate readonly recordSessionTrace: boolean;\n\n\t/** @internal */\n\tconstructor(options: {\n\t\t/** @internal */\n\t\tsessionId: string;\n\t\t/** @internal */\n\t\ttreeFile: string;\n\t\t/** @internal */\n\t\tisResumed: boolean;\n\t\t/** @internal */\n\t\ttoolCallScriptResolver?: StubToolCallScriptResolver;\n\t\t/** @internal */\n\t\tstate?: StubPiTreeState;\n\t\t/** @internal */\n\t\trunDetails?: Partial<PiRunDetails>;\n\t\t/** @internal */\n\t\tpersistState?: () => Promise<void>;\n\t\t/** @internal */\n\t\trecordSessionTrace?: boolean;\n\t}) {\n\t\tthis.sessionId = options.sessionId;\n\t\tthis.treeFile = options.treeFile;\n\t\tthis.isResumed = options.isResumed;\n\t\tthis.toolCallScriptResolver = options.toolCallScriptResolver;\n\t\tthis.state = options.state ?? createEmptyStubPiTreeState();\n\t\tthis.persistState = options.persistState;\n\t\tthis.recordSessionTrace = options.recordSessionTrace ?? false;\n\t\tthis.runDetails = {\n\t\t\tloadedAgentsFiles: options.runDetails?.loadedAgentsFiles?.map((file) => ({ ...file })) ?? [],\n\t\t\tloadedSkills: options.runDetails?.loadedSkills?.map((skill) => ({ ...skill })) ?? [],\n\t\t\tavailableToolNames: [...(options.runDetails?.availableToolNames ?? [])],\n\t\t};\n\t}\n\n\t/** @internal */\n\tget closed(): boolean {\n\t\treturn this._closed;\n\t}\n\n\t/** @internal */\n\tfailNextTurnWithBranchDrift(): void {\n\t\tthis.branchDriftPending = true;\n\t}\n\n\tprivate assertOpen(): void {\n\t\tif (this._closed) {\n\t\t\tthrow new Error(\"Handle is closed\");\n\t\t}\n\t}\n\n\tprivate addEntry(entry: PiTreeEntry): void {\n\t\tindexStubEntry(this.state, entry);\n\t\tthis.state.currentLeafId = entry.id;\n\t}\n\n\tprivate createMessageEntry(\n\t\tid: string,\n\t\tparentId: string | null,\n\t\trole: \"user\" | \"assistant\",\n\t\tcontent: unknown,\n\t\ttimestamp: string,\n\t): PiTreeEntry {\n\t\treturn {\n\t\t\tid,\n\t\t\tparentId,\n\t\t\ttype: \"message\",\n\t\t\ttimestamp,\n\t\t\tmessage: {\n\t\t\t\trole,\n\t\t\t\tcontent,\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate emitEvent(event: PiEvent): void {\n\t\tfor (const handler of this.handlers) {\n\t\t\thandler(event);\n\t\t}\n\t}\n\n\t/** @internal */\n\tgetRunDetails(): PiRunDetails {\n\t\treturn {\n\t\t\tloadedAgentsFiles: this.runDetails.loadedAgentsFiles.map((file) => ({ ...file })),\n\t\t\tloadedSkills: this.runDetails.loadedSkills.map((skill) => ({ ...skill })),\n\t\t\tavailableToolNames: [...this.runDetails.availableToolNames],\n\t\t};\n\t}\n\n\t/** @internal */\n\tgetLeafId(): string | null {\n\t\treturn this.state.currentLeafId;\n\t}\n\n\t/** @internal */\n\tgetEntry(id: string): PiTreeEntry | undefined {\n\t\treturn this.state.entries.get(id);\n\t}\n\n\t/** @public */\n\tgetBranch(fromId: string | undefined = this.state.currentLeafId ?? undefined): PiTreeEntry[] {\n\t\tif (!fromId) {\n\t\t\treturn [];\n\t\t}\n\t\tconst branch: PiTreeEntry[] = [];\n\t\tlet currentId: string | null = fromId;\n\t\twhile (currentId) {\n\t\t\tconst entry = this.state.entries.get(currentId);\n\t\t\tif (!entry) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbranch.push(entry);\n\t\t\tcurrentId = entry.parentId;\n\t\t}\n\t\tbranch.reverse();\n\t\treturn branch;\n\t}\n\n\t/** @internal */\n\tgetChildren(parentId: string): PiTreeEntry[] {\n\t\treturn (this.state.childIdsByParent.get(parentId) ?? [])\n\t\t\t.map((childId) => this.state.entries.get(childId))\n\t\t\t.filter((entry): entry is PiTreeEntry => entry !== undefined);\n\t}\n\n\t/** @internal */\n\tgetTree(): PiTreeNode[] {\n\t\tconst buildNode = (entry: PiTreeEntry): PiTreeNode => ({\n\t\t\tentry,\n\t\t\tchildren: this.getChildren(entry.id).map(buildNode),\n\t\t});\n\t\treturn (this.state.childIdsByParent.get(null) ?? [])\n\t\t\t.map((entryId) => this.state.entries.get(entryId))\n\t\t\t.filter((entry): entry is PiTreeEntry => entry !== undefined)\n\t\t\t.map(buildNode);\n\t}\n\n\t/** @internal */\n\tasync branch(entryId: string): Promise<void> {\n\t\tthis.assertOpen();\n\t\tif (!this.state.entries.has(entryId)) {\n\t\t\tthrow new Error(`Unknown Pi entry '${entryId}'`);\n\t\t}\n\t\tthis.state.currentLeafId = entryId;\n\t\tawait this.persistState?.();\n\t}\n\n\t/** @internal */\n\tasync branchFromRoot(): Promise<void> {\n\t\tthis.assertOpen();\n\t\tthis.state.currentLeafId = null;\n\t\tawait this.persistState?.();\n\t}\n\n\t/** @internal */\n\tasync resetLeaf(): Promise<void> {\n\t\tawait this.branchFromRoot();\n\t}\n\n\t/** @internal */\n\tasync compact(\n\t\t_customInstructions?: string,\n\t\tdetails?: unknown,\n\t): Promise<{\n\t\t/** @internal */\n\t\tsummary: string;\n\t}> {\n\t\tthis.assertOpen();\n\t\tconst timestamp = new Date().toISOString();\n\t\tconst compactionEntryId = `compaction-${++this.state.turnSeq}`;\n\t\tthis.addEntry({\n\t\t\tid: compactionEntryId,\n\t\t\tparentId: this.state.currentLeafId,\n\t\t\ttype: \"compaction\",\n\t\t\ttimestamp,\n\t\t\tdetails,\n\t\t});\n\t\tawait this.persistState?.();\n\t\treturn { summary: \"Stub compaction\" };\n\t}\n\n\tprivate async executeTurn(input: {\n\t\tkind: \"prompt\" | \"literal\" | \"custom\" | \"continue\";\n\t\tpromptText?: string;\n\t\tscriptPromptText?: string;\n\t\toptions?: PiPromptOptions;\n\t\tappendPromptUserMessage: boolean;\n\t}): Promise<PiTurnExecutionResult> {\n\t\tthis.assertOpen();\n\t\tthis.turnAbort = new AbortController();\n\t\tconst signal = this.turnAbort.signal;\n\t\tif ((await this.beforeTurn?.(input.kind, input.options, input.promptText)) === false) {\n\t\t\tinput.options = undefined;\n\t\t}\n\t\tsignal.throwIfAborted();\n\t\tif (this.branchDriftPending) {\n\t\t\tthis.branchDriftPending = false;\n\t\t\tthrow Object.assign(new Error(\"stubbed Pi branch drift\"), {\n\t\t\t\tname: \"PiBranchDriftError\",\n\t\t\t\tfailureCode: \"branch_drift\",\n\t\t\t\ttoTurnFailureOptions: () => ({\n\t\t\t\t\tfailureCode: \"branch_drift\",\n\t\t\t\t\tfailureDetails: { operation: input.kind },\n\t\t\t\t\trecoveryContext: null,\n\t\t\t\t\trestorePrimaryLeaf: false,\n\t\t\t\t}),\n\t\t\t});\n\t\t}\n\t\tif (input.promptText !== undefined) {\n\t\t\tthis.prompts.push(input.promptText);\n\t\t}\n\t\tconst startLeafId = this.state.currentLeafId;\n\t\tconst turnId = `turn-${++this.state.turnSeq}`;\n\t\tconst timestamp = new Date().toISOString();\n\t\tconst createdEntryIds: string[] = [];\n\t\tif (input.appendPromptUserMessage) {\n\t\t\tconst userEntryId = `user-${this.state.turnSeq}`;\n\t\t\tthis.addEntry(\n\t\t\t\tthis.createMessageEntry(\n\t\t\t\t\tuserEntryId,\n\t\t\t\t\tthis.state.currentLeafId,\n\t\t\t\t\t\"user\",\n\t\t\t\t\tinput.promptText ?? \"\",\n\t\t\t\t\ttimestamp,\n\t\t\t\t),\n\t\t\t);\n\t\t\tcreatedEntryIds.push(userEntryId);\n\t\t}\n\t\tawait this.persistState?.();\n\t\tsignal.throwIfAborted();\n\t\tthis.emitEvent({ type: \"turn.start\", turnId, data: {}, timestamp });\n\n\t\tconst tools = new Map((input.options?.tools ?? []).map((tool) => [tool.name, tool]));\n\t\tlet assistantContent = input.promptText ?? \"Continued.\";\n\t\tlet assistantContentFromScriptedMarkdown = false;\n\t\tconst scriptedItem = await this.toolCallScriptResolver?.({\n\t\t\ttreeFile: this.treeFile,\n\t\t\tturnSequence: this.state.turnSeq,\n\t\t\tpromptText: input.promptText ?? \"\",\n\t\t\tidentifiedPromptText: input.scriptPromptText,\n\t\t\ttools: input.options?.tools ?? [],\n\t\t});\n\t\tsignal.throwIfAborted();\n\t\tconst hasScriptedChunks = Boolean(\n\t\t\tscriptedItem &&\n\t\t\t\t\"calls\" in scriptedItem &&\n\t\t\t\t(scriptedItem.textChunks?.length ?? 0) + (scriptedItem.thinkingChunks?.length ?? 0),\n\t\t);\n\t\tif (hasScriptedChunks) assistantContent = \"\";\n\t\tif (scriptedItem && \"calls\" in scriptedItem) {\n\t\t\tconst streamed = { thinking: \"\", text: \"\" };\n\t\t\tconst streamEntryId = `stream-${this.state.turnSeq}`;\n\t\t\tconst streamParentId = this.state.currentLeafId;\n\t\t\tconst chunks = [\n\t\t\t\t...(scriptedItem.thinkingChunks ?? []).map((text) => ({\n\t\t\t\t\ttext,\n\t\t\t\t\tstreamType: \"thinking\" as const,\n\t\t\t\t})),\n\t\t\t\t...(scriptedItem.textChunks ?? []).map((text) => ({ text, streamType: \"text\" as const })),\n\t\t\t];\n\t\t\tfor (const { text, streamType } of chunks) {\n\t\t\t\tsignal.throwIfAborted();\n\t\t\t\tstreamed[streamType] += text;\n\t\t\t\tassistantContent = streamed.text;\n\t\t\t\tif (this.recordSessionTrace) {\n\t\t\t\t\tconst entry = this.createMessageEntry(\n\t\t\t\t\t\tstreamEntryId,\n\t\t\t\t\t\tstreamParentId,\n\t\t\t\t\t\t\"assistant\",\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t...(streamed.thinking ? [{ type: \"thinking\", thinking: streamed.thinking }] : []),\n\t\t\t\t\t\t\t...(streamed.text ? [{ type: \"text\", text: streamed.text }] : []),\n\t\t\t\t\t\t],\n\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t);\n\t\t\t\t\tif (this.state.entries.has(streamEntryId)) this.state.entries.set(streamEntryId, entry);\n\t\t\t\t\telse {\n\t\t\t\t\t\tthis.addEntry(entry);\n\t\t\t\t\t\tcreatedEntryIds.push(streamEntryId);\n\t\t\t\t\t}\n\t\t\t\t\tawait this.persistState?.();\n\t\t\t\t}\n\t\t\t\tthis.emitEvent({\n\t\t\t\t\ttype: \"stream.delta\",\n\t\t\t\t\tturnId,\n\t\t\t\t\tdata: { text, streamType },\n\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t});\n\t\t\t\tsignal.throwIfAborted();\n\t\t\t\tif (scriptedItem.chunkDelayMs)\n\t\t\t\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\t\t\t\tconst timer = setTimeout(() => {\n\t\t\t\t\t\t\tsignal.removeEventListener(\"abort\", abort);\n\t\t\t\t\t\t\tresolve();\n\t\t\t\t\t\t}, scriptedItem.chunkDelayMs);\n\t\t\t\t\t\tconst abort = () => {\n\t\t\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\t\t\treject(signal.reason);\n\t\t\t\t\t\t};\n\t\t\t\t\t\tsignal.addEventListener(\"abort\", abort, { once: true });\n\t\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tconst scriptedCalls = scriptedItem ? expandStubToolCallScriptItem(scriptedItem) : [];\n\t\tif (scriptedCalls.length > 0) {\n\t\t\tfor (const [callIndex, scriptedCall] of scriptedCalls.entries()) {\n\t\t\t\tsignal.throwIfAborted();\n\t\t\t\tconst toolCallId = stubToolCallId(this.state.turnSeq, scriptedCalls.length, callIndex);\n\t\t\t\tthis.emitEvent({\n\t\t\t\t\ttype: \"tool.call\",\n\t\t\t\t\tturnId,\n\t\t\t\t\tdata: {\n\t\t\t\t\t\ttoolCallId,\n\t\t\t\t\t\tname: scriptedCall.toolName,\n\t\t\t\t\t\targuments: scriptedCall.args,\n\t\t\t\t\t},\n\t\t\t\t\ttimestamp,\n\t\t\t\t});\n\t\t\t\tconst tool = tools.get(scriptedCall.toolName);\n\t\t\t\tif (!tool && scriptedCall.toolName === \"markdown_result\") {\n\t\t\t\t\tconst markdown = (scriptedCall.args as { markdown?: unknown }).markdown;\n\t\t\t\t\tif (typeof markdown === \"string\") {\n\t\t\t\t\t\tassistantContent = markdown;\n\t\t\t\t\t\tassistantContentFromScriptedMarkdown = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (tool) {\n\t\t\t\t\tif (this.recordSessionTrace) {\n\t\t\t\t\t\tconst entryId = `call-${toolCallId}`;\n\t\t\t\t\t\tthis.addEntry(\n\t\t\t\t\t\t\tthis.createMessageEntry(\n\t\t\t\t\t\t\t\tentryId,\n\t\t\t\t\t\t\t\tthis.state.currentLeafId,\n\t\t\t\t\t\t\t\t\"assistant\",\n\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\ttype: \"toolCall\",\n\t\t\t\t\t\t\t\t\t\tid: toolCallId,\n\t\t\t\t\t\t\t\t\t\tname: scriptedCall.toolName,\n\t\t\t\t\t\t\t\t\t\targuments: scriptedCall.args,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\tnew Date().toISOString(),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tcreatedEntryIds.push(entryId);\n\t\t\t\t\t\tawait this.persistState?.();\n\t\t\t\t\t}\n\t\t\t\t\tconst recordToolResult = async (result: unknown, isError: boolean) => {\n\t\t\t\t\t\tif (!this.recordSessionTrace) return;\n\t\t\t\t\t\tconst entryId = `result-${toolCallId}`;\n\t\t\t\t\t\tconst entry = {\n\t\t\t\t\t\t\tid: entryId,\n\t\t\t\t\t\t\tparentId: this.state.currentLeafId,\n\t\t\t\t\t\t\ttype: \"message\",\n\t\t\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\t\t\tmessage: {\n\t\t\t\t\t\t\t\trole: \"toolResult\",\n\t\t\t\t\t\t\t\ttoolCallId,\n\t\t\t\t\t\t\t\ttoolName: scriptedCall.toolName,\n\t\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: stringifyToolResult(result) }],\n\t\t\t\t\t\t\t\tisError,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t};\n\t\t\t\t\t\tthis.addEntry(entry);\n\t\t\t\t\t\tcreatedEntryIds.push(entryId);\n\t\t\t\t\t\tawait this.persistState?.();\n\t\t\t\t\t};\n\t\t\t\t\ttry {\n\t\t\t\t\t\tsignal.throwIfAborted();\n\t\t\t\t\t\tconst blocked = input.options?.shouldBlockToolCall?.(scriptedCall.toolName);\n\t\t\t\t\t\tif (blocked) throw new Error(blocked);\n\t\t\t\t\t\tconst result = await tool.execute(scriptedCall.args, {\n\t\t\t\t\t\t\ttoolCallId,\n\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t\tsuspendPromptGuards: input.options?.suspendPromptGuards,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tsignal.throwIfAborted();\n\t\t\t\t\t\tif (!assistantContentFromScriptedMarkdown) {\n\t\t\t\t\t\t\tassistantContent = stringifyToolResult(result);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tawait recordToolResult(result, false);\n\t\t\t\t\t\tconst followUp =\n\t\t\t\t\t\t\tscriptedItem && \"calls\" in scriptedItem\n\t\t\t\t\t\t\t\t? scriptedItem.afterToolResult?.(scriptedCall, result)\n\t\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t\tif (followUp) scriptedCalls.push(followUp);\n\t\t\t\t\t\tthis.emitEvent({\n\t\t\t\t\t\t\ttype: \"tool.result\",\n\t\t\t\t\t\t\tturnId,\n\t\t\t\t\t\t\tdata: { toolCallId, name: scriptedCall.toolName, result },\n\t\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tawait recordToolResult(error instanceof Error ? error.message : String(error), true);\n\t\t\t\t\t\tthis.emitEvent({\n\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\tturnId,\n\t\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\tmessage: error instanceof Error ? error.message : String(error),\n\t\t\t\t\t\t\t\ttoolName: scriptedCall.toolName,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (let i = 0; i < (scriptedCall.intermediateEntryCount ?? 0); i++) {\n\t\t\t\t\tconst intermediateEntryId =\n\t\t\t\t\t\tscriptedCalls.length === 1\n\t\t\t\t\t\t\t? `intermediate-${this.state.turnSeq}-${i + 1}`\n\t\t\t\t\t\t\t: `intermediate-${this.state.turnSeq}-${callIndex + 1}-${i + 1}`;\n\t\t\t\t\tthis.addEntry(\n\t\t\t\t\t\tthis.createMessageEntry(\n\t\t\t\t\t\t\tintermediateEntryId,\n\t\t\t\t\t\t\tthis.state.currentLeafId,\n\t\t\t\t\t\t\t\"assistant\",\n\t\t\t\t\t\t\t`Intermediate entry ${i + 1}`,\n\t\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tcreatedEntryIds.push(intermediateEntryId);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (tools.size > 0 && !hasScriptedChunks) {\n\t\t\tthrow new Error(\n\t\t\t\t`Stub Pi prompt requires a stub tool-call script when tools are provided (${[...tools.keys()].join(\", \")})`,\n\t\t\t);\n\t\t} else if (input.promptText !== undefined && !hasScriptedChunks) {\n\t\t\tthis.emitEvent({\n\t\t\t\ttype: \"stream.delta\",\n\t\t\t\tturnId,\n\t\t\t\tdata: { text: input.promptText },\n\t\t\t\ttimestamp,\n\t\t\t});\n\t\t}\n\n\t\tsignal.throwIfAborted();\n\t\t// Keep the result entry ID without repeating content already saved in the stream entry.\n\t\tthis.addEntry(\n\t\t\tthis.createMessageEntry(\n\t\t\t\tturnId,\n\t\t\t\tthis.state.currentLeafId,\n\t\t\t\t\"assistant\",\n\t\t\t\tthis.recordSessionTrace && hasScriptedChunks && scriptedCalls.length === 0\n\t\t\t\t\t? []\n\t\t\t\t\t: assistantContent,\n\t\t\t\ttimestamp,\n\t\t\t),\n\t\t);\n\t\tcreatedEntryIds.push(turnId);\n\t\tawait this.persistState?.();\n\t\tsignal.throwIfAborted();\n\t\tthis.emitEvent({ type: \"turn.end\", turnId, data: {}, timestamp });\n\t\tconst resultEntryId = this.state.currentLeafId;\n\t\tif (!resultEntryId) {\n\t\t\tthrow new Error(\n\t\t\t\tinput.appendPromptUserMessage\n\t\t\t\t\t? \"Stub Pi prompt completed without an active leaf\"\n\t\t\t\t\t: \"Stub Pi continuation completed without an active leaf\",\n\t\t\t);\n\t\t}\n\t\treturn {\n\t\t\tstartLeafId,\n\t\t\tendLeafId: resultEntryId,\n\t\t\tcreatedEntryIds,\n\t\t\tresultEntryId,\n\t\t\tassistantMarkdown: assistantContent,\n\t\t};\n\t}\n\n\t/** @internal */\n\tasync prompt(text: string, options: PiPromptOptions = {}): Promise<PiTurnExecutionResult> {\n\t\treturn await this.executeTurn({\n\t\t\tkind: \"prompt\",\n\t\t\tpromptText: text,\n\t\t\toptions,\n\t\t\tappendPromptUserMessage: true,\n\t\t});\n\t}\n\n\t/** @internal */\n\tasync promptLiteral(text: string, options: PiPromptOptions = {}): Promise<PiTurnExecutionResult> {\n\t\treturn await this.executeTurn({\n\t\t\tkind: \"literal\",\n\t\t\tpromptText: text,\n\t\t\toptions,\n\t\t\tappendPromptUserMessage: true,\n\t\t});\n\t}\n\n\t/** @internal */\n\tasync promptCustom(\n\t\tinput: PiCustomMessageInput,\n\t\toptions: PiPromptOptions = {},\n\t): Promise<PiTurnExecutionResult> {\n\t\tconst startLeafId = this.getLeafId();\n\t\tconst promptEntryId = await this.appendCustomMessage(input);\n\t\tconst result = await this.executeTurn({\n\t\t\tkind: \"custom\",\n\t\t\tscriptPromptText: input.content,\n\t\t\toptions,\n\t\t\tappendPromptUserMessage: false,\n\t\t});\n\t\treturn {\n\t\t\t...result,\n\t\t\tstartLeafId,\n\t\t\tcreatedEntryIds: [promptEntryId, ...result.createdEntryIds],\n\t\t};\n\t}\n\n\t/** @internal */\n\tasync continueTurn(options: PiPromptOptions = {}): Promise<PiTurnExecutionResult> {\n\t\treturn await this.executeTurn({\n\t\t\tkind: \"continue\",\n\t\t\toptions,\n\t\t\tappendPromptUserMessage: false,\n\t\t});\n\t}\n\n\t/** @internal */\n\tasync appendUserMessage(text: string): Promise<string> {\n\t\tthis.assertOpen();\n\t\tconst timestamp = new Date().toISOString();\n\t\tconst userEntryId = `user-${++this.state.turnSeq}`;\n\t\tthis.addEntry(\n\t\t\tthis.createMessageEntry(userEntryId, this.state.currentLeafId, \"user\", text, timestamp),\n\t\t);\n\t\tawait this.persistState?.();\n\t\treturn userEntryId;\n\t}\n\n\t/** @internal */\n\tasync appendCustomMessage(input: PiCustomMessageInput): Promise<string> {\n\t\tthis.assertOpen();\n\t\tconst timestamp = new Date().toISOString();\n\t\tconst entryId = `custom-${++this.state.turnSeq}`;\n\t\tthis.addEntry({\n\t\t\tid: entryId,\n\t\t\tparentId: this.state.currentLeafId,\n\t\t\ttype: \"custom_message\",\n\t\t\ttimestamp,\n\t\t\tcustomType: \"leitwerk\",\n\t\t\tcontent: input.content,\n\t\t\tdetails: input.details,\n\t\t});\n\t\tawait this.persistState?.();\n\t\treturn entryId;\n\t}\n\n\t/** @internal */\n\tasync steer(text: string): Promise<void> {\n\t\tthis.assertOpen();\n\t\tthis.steers.push(text);\n\t}\n\n\t/** @internal */\n\tasync abortTurn(): Promise<void> {\n\t\tthis.assertOpen();\n\t\tthis.turnAbort.abort(new Error(\"Scripted turn aborted\"));\n\t}\n\n\t/** @internal */\n\tsubscribe(handler: PiEventHandler): () => void {\n\t\tthis.handlers.add(handler);\n\t\treturn () => {\n\t\t\tthis.handlers.delete(handler);\n\t\t};\n\t}\n\n\t/** @internal */\n\tsubscribeDiagnostics(handler: PiSessionDiagnosticHandler): () => void {\n\t\tthis.diagnosticHandlers.add(handler);\n\t\treturn () => {\n\t\t\tthis.diagnosticHandlers.delete(handler);\n\t\t};\n\t}\n\n\t/** @internal */\n\temitDiagnostic(diagnostic: PiSessionDiagnostic): void {\n\t\tfor (const handler of this.diagnosticHandlers) handler(diagnostic);\n\t}\n\n\t/** @internal */\n\tasync close(): Promise<void> {\n\t\tthis.turnAbort.abort(new Error(\"Scripted session closed\"));\n\t\tawait this.persistState?.();\n\t\tthis._closed = true;\n\t\tthis.handlers.clear();\n\t\tthis.diagnosticHandlers.clear();\n\t}\n}\n\n/** @public */\nexport interface StubPiTreeHandleFactoryOptions {\n\t/** @public */\n\ttoolCallScriptResolver?: StubToolCallScriptResolver;\n\t/** Persist SDK-readable JSONL with reasoning and tool messages for history/detail tests. @public */\n\trecordSessionTrace?: boolean;\n}\n\n/** @public */\nexport class StubPiTreeHandleFactory implements PiTreeHandleFactory {\n\t/** @public */\n\treadonly sessions: StubPiTreeHandle[] = [];\n\t/** @internal */\n\ttoolCallScriptResolver?: StubToolCallScriptResolver;\n\n\tprivate seq = 0;\n\tprivate readonly treeStateByFile = new Map<string, StubPiTreeState>();\n\tprivate readonly recordSessionTrace: boolean;\n\n\t/** @public */\n\tconstructor(options: StubPiTreeHandleFactoryOptions = {}) {\n\t\tthis.toolCallScriptResolver = options.toolCallScriptResolver;\n\t\tthis.recordSessionTrace = options.recordSessionTrace ?? false;\n\t}\n\n\t/** @internal */\n\tasync prepareManagedBootstrap(\n\t\topts: PiManagedBootstrapOptions,\n\t): Promise<PiManagedBootstrapResult> {\n\t\treturn {\n\t\t\tloadedResourceIds: opts.manifest.provenance.map(\n\t\t\t\t(resource: { snapshotPath: string }) => resource.snapshotPath,\n\t\t\t),\n\t\t\tloadedAgentsFiles: [],\n\t\t\tloadedSkillFiles: [],\n\t\t\tresolvedModel: { ...opts.expectedModel },\n\t\t\tdiagnostics: [],\n\t\t};\n\t}\n\n\t/** @internal */\n\tasync inspectPrimaryTree(opts: PiTreePlanningOptions): Promise<PiTreePlanningSnapshot> {\n\t\tlet treeState = this.treeStateByFile.get(opts.treeFile);\n\t\tif (!treeState) {\n\t\t\ttry {\n\t\t\t\ttreeState = deserializeStubPiTreeState(readFileSync(opts.treeFile, \"utf8\"));\n\t\t\t} catch (error) {\n\t\t\t\tif (isEnoent(error)) {\n\t\t\t\t\treturn { currentLeafId: null, entries: [] };\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tcurrentLeafId: treeState.currentLeafId ?? deriveStubLeafIdFromEntries(treeState),\n\t\t\tentries: [...treeState.entries.values()].map((entry) => ({\n\t\t\t\tid: entry.id,\n\t\t\t\tparentId: entry.parentId,\n\t\t\t})),\n\t\t};\n\t}\n\n\t/** @public */\n\tasync createPrimaryTreeHandle(opts: PiTreeHandleOptions): Promise<PiTreeHandle> {\n\t\tconst persistState = async (state: StubPiTreeState): Promise<void> => {\n\t\t\tthis.treeStateByFile.set(opts.treeFile, state);\n\t\t\ttry {\n\t\t\t\tmkdirSync(path.dirname(opts.treeFile), { recursive: true });\n\t\t\t\twriteFileSync(\n\t\t\t\t\topts.treeFile,\n\t\t\t\t\tserializeStubPiTreeState(state, this.recordSessionTrace),\n\t\t\t\t\t\"utf8\",\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\tif (\n\t\t\t\t\ttypeof error !== \"object\" ||\n\t\t\t\t\terror === null ||\n\t\t\t\t\t!(\"code\" in error) ||\n\t\t\t\t\t![\"ENOENT\", \"EACCES\", \"EROFS\", \"EPERM\"].includes(\n\t\t\t\t\t\tString((error as { code?: unknown }).code),\n\t\t\t\t\t)\n\t\t\t\t) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\tlet treeState = this.treeStateByFile.get(opts.treeFile);\n\t\tif (!treeState && opts.resume) {\n\t\t\ttry {\n\t\t\t\tconst persisted = readFileSync(opts.treeFile, \"utf8\");\n\t\t\t\ttreeState = deserializeStubPiTreeState(persisted);\n\t\t\t} catch (error) {\n\t\t\t\tif (\n\t\t\t\t\ttypeof error === \"object\" &&\n\t\t\t\t\terror !== null &&\n\t\t\t\t\t\"code\" in error &&\n\t\t\t\t\t(error as { code?: unknown }).code !== \"ENOENT\"\n\t\t\t\t) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ttreeState ??= createEmptyStubPiTreeState();\n\t\ttreeState.header ??= {\n\t\t\ttype: \"session\",\n\t\t\tversion: CURRENT_SESSION_VERSION,\n\t\t\tid: randomUUID(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tcwd: opts.sessionCwd ?? opts.workspaceRoot ?? path.dirname(opts.treeFile),\n\t\t};\n\t\tif (opts.resume) {\n\t\t\ttreeState.currentLeafId = deriveStubLeafIdFromEntries(treeState);\n\t\t}\n\t\tthis.treeStateByFile.set(opts.treeFile, treeState);\n\t\tconst piHandle = new StubPiTreeHandle({\n\t\t\tsessionId: `stub-${++this.seq}`,\n\t\t\ttreeFile: opts.treeFile,\n\t\t\tisResumed: opts.resume,\n\t\t\ttoolCallScriptResolver: this.toolCallScriptResolver\n\t\t\t\t? (context) =>\n\t\t\t\t\t\tthis.toolCallScriptResolver?.({\n\t\t\t\t\t\t\t...context,\n\t\t\t\t\t\t\tinstanceId: opts.instanceId,\n\t\t\t\t\t\t\tworkspaceRoot: opts.workspaceRoot,\n\t\t\t\t\t\t\tsessionCwd: opts.sessionCwd,\n\t\t\t\t\t\t})\n\t\t\t\t: undefined,\n\t\t\tstate: treeState,\n\t\t\tpersistState: () => persistState(treeState),\n\t\t\trecordSessionTrace: this.recordSessionTrace,\n\t\t\trunDetails: {\n\t\t\t\tavailableToolNames: opts.piConfig?.availableToolNames ?? [],\n\t\t\t},\n\t\t});\n\t\tthis.sessions.push(piHandle);\n\t\tif (!opts.resume) {\n\t\t\tawait persistState(treeState);\n\t\t}\n\t\treturn piHandle;\n\t}\n}\n","import {\n\tStubPiTreeHandleFactory,\n\ttype StubToolCallScriptResolver,\n\ttype StubToolCallScriptResolverContext,\n} from \"./stub-pi-tree-handle.js\";\n\nfunction isObjectLike(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null;\n}\n\n/** @internal */\nexport function synthesizeStubArgValue(key: string, spec: unknown): unknown {\n\tif (key === \"changedProjects\") {\n\t\treturn undefined;\n\t}\n\tconst type = isObjectLike(spec) && typeof spec.type === \"string\" ? spec.type : \"string\";\n\tswitch (type) {\n\t\tcase \"number\":\n\t\tcase \"integer\":\n\t\t\treturn 1;\n\t\tcase \"boolean\":\n\t\t\treturn true;\n\t\tcase \"array\": {\n\t\t\tconst itemSpec = isObjectLike(spec) ? spec.items : undefined;\n\t\t\treturn [synthesizeStubArgValue(`${key}_item`, itemSpec)];\n\t\t}\n\t\tcase \"object\":\n\t\t\treturn {};\n\t\tdefault:\n\t\t\treturn `${key} value`;\n\t}\n}\n\n/** @internal */\nexport function synthesizeStubToolArgs(\n\tparameters: Record<string, unknown>,\n): Record<string, unknown> {\n\tconst parameterEntries =\n\t\tisObjectLike(parameters) && parameters.type === \"object\" && isObjectLike(parameters.properties)\n\t\t\t? Object.entries(parameters.properties)\n\t\t\t: Object.entries(parameters);\n\treturn Object.fromEntries(\n\t\tparameterEntries.map(([key, spec]) => [key, synthesizeStubArgValue(key, spec)]),\n\t);\n}\n\n/** @internal */\nexport function createSchemaDrivenToolCallScriptResolver(): StubToolCallScriptResolver {\n\treturn ({ tools }: StubToolCallScriptResolverContext) => {\n\t\tconst markdownTool = tools.find((tool) => tool.name === \"markdown_result\");\n\t\tconst completionTool = tools.find(\n\t\t\t(tool) => tool.name !== \"markdown_result\" && tool.name !== \"upload_result_images\",\n\t\t);\n\t\tif (markdownTool && completionTool) {\n\t\t\treturn {\n\t\t\t\tcalls: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttoolName: markdownTool.name,\n\t\t\t\t\t\targs: synthesizeStubToolArgs(markdownTool.parameters),\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\ttoolName: completionTool.name,\n\t\t\t\t\t\targs: synthesizeStubToolArgs(completionTool.parameters),\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t}\n\t\tconst tool = markdownTool ?? completionTool ?? tools[0];\n\t\tif (!tool) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn {\n\t\t\ttoolName: tool.name,\n\t\t\targs: synthesizeStubToolArgs(tool.parameters),\n\t\t};\n\t};\n}\n\n/** @internal */\nexport function createSchemaDrivenStubPiFactory(\n\toptions: {\n\t\t/** @internal */\n\t\ttoolCallScriptResolver?: StubToolCallScriptResolver;\n\t} = {},\n): StubPiTreeHandleFactory {\n\treturn new StubPiTreeHandleFactory({\n\t\ttoolCallScriptResolver:\n\t\t\toptions.toolCallScriptResolver ?? createSchemaDrivenToolCallScriptResolver(),\n\t});\n}\n"],"mappings":";AAAA,SAAS,kBAAkB;AAC3B,SAAS,WAAW,cAAc,qBAAqB;AACvD,OAAO,UAAU;AACjB,SAAS,+BAAmD;AAe5D,SAAS,gBAAgB;AAgEzB,SAAS,oBAAoB,QAAyB;AACrD,MAAI,OAAO,WAAW,UAAU;AAC/B,WAAO;AAAA,EACR;AACA,MAAI,WAAW,QAAW;AACzB,WAAO;AAAA,EACR;AACA,MAAI;AACH,WAAO,KAAK,UAAU,QAAQ,MAAM,CAAC;AAAA,EACtC,QAAQ;AACP,WAAO,OAAO,MAAM;AAAA,EACrB;AACD;AAEA,SAAS,6BAA6B,MAAwD;AAC7F,MAAI,WAAW,MAAM;AACpB,WAAO,CAAC,GAAG,KAAK,KAAK;AAAA,EACtB;AACA,SAAO,CAAC,IAAI;AACb;AAEA,SAAS,eAAe,SAAiB,YAAoB,OAAuB;AACnF,MAAI,cAAc,GAAG;AACpB,WAAO,QAAQ,OAAO;AAAA,EACvB;AACA,SAAO,QAAQ,OAAO,IAAI,QAAQ,CAAC;AACpC;AAuBA,SAAS,6BAA8C;AACtD,SAAO;AAA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K,uBAAuB,KAAK,IAAI,CAAC,CAAC;AAAA,EAC/E;AACD;AAGO,SAAS,2CAAuE;AACtF,SAAO,CAAC,EAAE,MAAM,MAAyC;AACxD,UAAM,eAAe,MAAM,KAAK,CAACA,UAASA,MAAK,SAAS,iBAAiB;AACzE,UAAM,iBAAiB,MAAM;AAAA,MAC5B,CAACA,UAASA,MAAK,SAAS,qBAAqBA,MAAK,SAAS;AAAA,IAC5D;AACA,QAAI,gBAAgB,gBAAgB;AACnC,aAAO;AAAA,QACN,OAAO;AAAA,UACN;AAAA,YACC,UAAU,aAAa;AAAA,YACvB,MAAM,uBAAuB,aAAa,UAAU;AAAA,UACrD;AAAA,UACA;AAAA,YACC,UAAU,eAAe;AAAA,YACzB,MAAM,uBAAuB,eAAe,UAAU;AAAA,UACvD;AAAA,QACD;AAAA,MACD;AAAA,IACD;AACA,UAAM,OAAO,gBAAgB,kBAAkB,MAAM,CAAC;AACtD,QAAI,CAAC,MAAM;AACV,aAAO;AAAA,IACR;AACA,WAAO;AAAA,MACN,UAAU,KAAK;AAAA,MACf,MAAM,uBAAuB,KAAK,UAAU;AAAA,IAC7C;AAAA,EACD;AACD;AAGO,SAAS,gCACf,UAGI,CAAC,GACqB;AAC1B,SAAO,IAAI,wBAAwB;AAAA,IAClC,wBACC,QAAQ,0BAA0B,yCAAyC;AAAA,EAC7E,CAAC;AACF;","names":["tool"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/http-launch.ts"],"sourcesContent":["import type { LaunchRun } from \"@leitwerk-dev/domain\";\n\n/** Accepts a launch-run request shape and waits for its admitted process commit. @internal */\nexport async function postImmediateLaunchRequest(\n\tinput: string | URL | Request,\n\tinit?: RequestInit,\n): Promise<Response> {\n\tconst url = new URL(String(input));\n\tconst match = /^\\/api\\/launchers\\/([^/]+)\\/launch-runs$/.exec(url.pathname);\n\tif (!match?.[1]) throw new Error(`Expected an immediate launch-run URL, received '${url}'`);\n\tconst body = init?.body ? (JSON.parse(String(init.body)) as Record<string, unknown>) : {};\n\treturn postImmediateLaunch(url.origin, decodeURIComponent(match[1]), body);\n}\n\n/**\n * Admits an immediate launch through the public asynchronous HTTP contract and waits until the\n * process commit or a pre-commit failure is observable. Intended for integration-test setup.\n */\n/** @public */\nexport async function postImmediateLaunch(\n\tserverBaseUrl: string,\n\tlauncherId: string,\n\tbody: Record<string, unknown>,\n): Promise<Response> {\n\tconst admitted = await fetch(\n\t\t`${serverBaseUrl.replace(/\\/$/, \"\")}/api/launchers/${encodeURIComponent(launcherId)}/launch-runs`,\n\t\t{\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { \"content-type\": \"application/json\", \"idempotency-key\": crypto.randomUUID() },\n\t\t\tbody: JSON.stringify({ ...body, schedule: { mode: \"now\" } }),\n\t\t},\n\t);\n\tconst admittedBody = (await admitted.json()) as { launchRunId?: string };\n\tif (admitted.status !== 202 || !admittedBody.launchRunId) {\n\t\treturn new Response(JSON.stringify(admittedBody), {\n\t\t\tstatus: admitted.status,\n\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t});\n\t}\n\n\tlet launchRun: LaunchRun;\n\tconst deadline = Date.now() + 10_000;\n\tfor (;;) {\n\t\tconst response = await fetch(\n\t\t\t`${serverBaseUrl.replace(/\\/$/, \"\")}/api/launch-runs/${admittedBody.launchRunId}`,\n\t\t);\n\t\tconst responseBody = (await response.json()) as { launchRun: LaunchRun };\n\t\tif (\n\t\t\tresponseBody.launchRun.instanceId ||\n\t\t\t[\"failed\", \"cancelled\"].includes(responseBody.launchRun.status)\n\t\t) {\n\t\t\tlaunchRun = responseBody.launchRun;\n\t\t\tbreak;\n\t\t}\n\t\tif (Date.now() >= deadline) throw new Error(\"Timed out waiting for immediate launch admission\");\n\t\tawait new Promise((resolve) => setTimeout(resolve, 10));\n\t}\n\n\tif (!launchRun.instanceId) {\n\t\tconst failure = launchRun.steps.find((step) => step.status === \"failed\");\n\t\treturn new Response(\n\t\t\tJSON.stringify({\n\t\t\t\terror: failure?.safeSummary ?? \"Launch failed\",\n\t\t\t\tlaunchRunId: launchRun.id,\n\t\t\t}),\n\t\t\t{ status: 400, headers: { \"content-type\": \"application/json\" } },\n\t\t);\n\t}\n\tconst detailResponse = await fetch(\n\t\t`${serverBaseUrl.replace(/\\/$/, \"\")}/api/processes/${encodeURIComponent(launchRun.instanceId)}`,\n\t);\n\tconst detail = (await detailResponse.json()) as { process: unknown; projects?: unknown[] };\n\tconst failure = launchRun.steps.find((step) => step.status === \"failed\");\n\treturn new Response(\n\t\tJSON.stringify({\n\t\t\tprocess: detail.process,\n\t\t\tprojects: detail.projects ?? [],\n\t\t\tlaunchRunId: launchRun.id,\n\t\t\t...(launchRun.status === \"failed\"\n\t\t\t\t? { error: failure?.safeSummary ?? \"Process was created, but startup failed\" }\n\t\t\t\t: {}),\n\t\t}),\n\t\t{\n\t\t\tstatus: launchRun.status === \"failed\" ? 200 : 201,\n\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t},\n\t);\n}\n"],"mappings":";AAGA,eAAsB,2BACrB,OACA,MACoB;AACpB,QAAM,MAAM,IAAI,IAAI,OAAO,KAAK,CAAC;AACjC,QAAM,QAAQ,2CAA2C,KAAK,IAAI,QAAQ;AAC1E,MAAI,CAAC,QAAQ,CAAC,EAAG,OAAM,IAAI,MAAM,mDAAmD,GAAG,GAAG;AAC1F,QAAM,OAAO,MAAM,OAAQ,KAAK,MAAM,OAAO,KAAK,IAAI,CAAC,IAAgC,CAAC;AACxF,SAAO,oBAAoB,IAAI,QAAQ,mBAAmB,MAAM,CAAC,CAAC,GAAG,IAAI;AAC1E;AAOA,eAAsB,oBACrB,eACA,YACA,MACoB;AACpB,QAAM,WAAW,MAAM;AAAA,IACtB,GAAG,cAAc,QAAQ,OAAO,EAAE,CAAC,kBAAkB,mBAAmB,UAAU,CAAC;AAAA,IACnF;AAAA,MACC,QAAQ;AAAA,MACR,SAAS,EAAE,gBAAgB,oBAAoB,mBAAmB,OAAO,WAAW,EAAE;AA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