@leitwerk-dev/test-support 0.1.8 → 0.2.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-QFCJV2VA.js → chunk-2IICIB6D.js} +187 -14
- package/dist/chunk-2IICIB6D.js.map +1 -0
- package/dist/{chunk-KIDBCGNW.js → chunk-7I4OCTF3.js} +21 -26
- package/dist/chunk-7I4OCTF3.js.map +1 -0
- package/dist/{chunk-EDIN4LC3.js → chunk-KPSK7EMY.js} +41 -10
- package/dist/chunk-KPSK7EMY.js.map +1 -0
- package/dist/{chunk-R4KVUGWR.js → chunk-MV4W6NOO.js} +25 -3
- package/dist/chunk-MV4W6NOO.js.map +1 -0
- package/dist/compact-process-detail-fixture.d.ts.map +1 -1
- package/dist/fakes/index.js +10 -2
- package/dist/fakes/index.js.map +1 -1
- package/dist/fixtures.js +35 -2
- package/dist/fixtures.js.map +1 -1
- package/dist/http-launch.d.ts +8 -0
- package/dist/http-launch.d.ts.map +1 -0
- package/dist/index.d.ts +4 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +156 -12
- package/dist/index.js.map +1 -1
- package/dist/integration.d.ts +1 -0
- package/dist/integration.d.ts.map +1 -1
- package/dist/integration.js +66 -4
- package/dist/integration.js.map +1 -1
- package/dist/local-git.d.ts +134 -0
- package/dist/local-git.d.ts.map +1 -0
- package/dist/local-git.js +297 -0
- package/dist/local-git.js.map +1 -0
- package/dist/model-provider-fixtures.d.ts +7 -0
- package/dist/model-provider-fixtures.d.ts.map +1 -0
- package/dist/polling.d.ts +1 -1
- package/dist/polling.d.ts.map +1 -1
- package/dist/process-driver.d.ts +10 -0
- package/dist/process-driver.d.ts.map +1 -0
- package/dist/server-extension-test-harness.d.ts +17 -2
- package/dist/server-extension-test-harness.d.ts.map +1 -1
- package/dist/stub-worker-entry.js +9 -5
- package/dist/stub-worker-entry.js.map +1 -1
- package/dist/worker-testing/in-process-worker-spawn.d.ts +5 -0
- package/dist/worker-testing/in-process-worker-spawn.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 +371 -7
- package/dist/worker-testing/index.js.map +1 -1
- package/dist/worker-testing/stub-pi-tree-handle.d.ts +19 -1
- package/dist/worker-testing/stub-pi-tree-handle.d.ts.map +1 -1
- package/dist/worker-testing/worker-runtime-harness.d.ts +2 -0
- package/dist/worker-testing/worker-runtime-harness.d.ts.map +1 -1
- package/dist/worker-testing/worker-start-payload.d.ts.map +1 -1
- package/package.json +14 -9
- package/src/compact-process-detail-fixture.ts +28 -2
- package/src/http-launch.ts +87 -0
- package/src/index.ts +9 -5
- package/src/integration.ts +1 -0
- package/src/local-git.ts +349 -0
- package/src/model-provider-fixtures.ts +23 -0
- package/src/polling.ts +2 -2
- package/src/process-driver.ts +57 -0
- package/src/server-extension-test-harness.ts +43 -5
- package/src/worker-testing/in-process-worker-spawn.ts +22 -2
- package/src/worker-testing/index.ts +5 -1
- package/src/worker-testing/stub-pi-tree-handle.ts +221 -20
- package/src/worker-testing/worker-runtime-harness.ts +24 -0
- package/src/worker-testing/worker-start-payload.ts +1 -0
- package/dist/chunk-EDIN4LC3.js.map +0 -1
- package/dist/chunk-KIDBCGNW.js.map +0 -1
- package/dist/chunk-QFCJV2VA.js.map +0 -1
- package/dist/chunk-R4KVUGWR.js.map +0 -1
- package/dist/compact-process-detail-fixture.js +0 -73
- package/dist/compact-process-detail-fixture.js.map +0 -1
- package/dist/fakes/fake-git-ops.js +0 -101
- package/dist/fakes/fake-git-ops.js.map +0 -1
- package/dist/fakes/fake-llm.js +0 -27
- package/dist/fakes/fake-llm.js.map +0 -1
- package/dist/in-process-worker.js +0 -2
- package/dist/in-process-worker.js.map +0 -1
- package/dist/integration-harness.js +0 -38
- package/dist/integration-harness.js.map +0 -1
- package/dist/polling.js +0 -14
- package/dist/polling.js.map +0 -1
- package/dist/question-fixtures.js +0 -26
- package/dist/question-fixtures.js.map +0 -1
- package/dist/server-extension-test-harness.js +0 -168
- package/dist/server-extension-test-harness.js.map +0 -1
- package/dist/test-app.js +0 -47
- package/dist/test-app.js.map +0 -1
- package/dist/worker-testing/in-process-worker-spawn.js +0 -61
- package/dist/worker-testing/in-process-worker-spawn.js.map +0 -1
- package/dist/worker-testing/ipc-harness.d.ts +0 -11
- package/dist/worker-testing/ipc-harness.d.ts.map +0 -1
- package/dist/worker-testing/ipc-harness.js +0 -17
- package/dist/worker-testing/ipc-harness.js.map +0 -1
- package/dist/worker-testing/schema-driven-stub-pi.js +0 -65
- package/dist/worker-testing/schema-driven-stub-pi.js.map +0 -1
- package/dist/worker-testing/stub-pi-controls.js +0 -10
- package/dist/worker-testing/stub-pi-controls.js.map +0 -1
- package/dist/worker-testing/stub-pi-tree-handle.js +0 -515
- package/dist/worker-testing/stub-pi-tree-handle.js.map +0 -1
- package/dist/worker-testing/worker-runtime-harness.js +0 -216
- package/dist/worker-testing/worker-runtime-harness.js.map +0 -1
- package/dist/worker-testing/worker-start-payload.js +0 -101
- package/dist/worker-testing/worker-start-payload.js.map +0 -1
- package/dist/workspace-source-aliases.d.ts +0 -6
- package/dist/workspace-source-aliases.d.ts.map +0 -1
- package/dist/workspace-source-aliases.js +0 -126
- package/dist/workspace-source-aliases.js.map +0 -1
- package/src/worker-testing/ipc-harness.ts +0 -19
- package/src/workspace-source-aliases.ts +0 -171
|
@@ -5,15 +5,44 @@ import {
|
|
|
5
5
|
coreHostCapabilities,
|
|
6
6
|
createCapabilityAccessor,
|
|
7
7
|
createEventBus,
|
|
8
|
+
type IntegrationToolDefinition,
|
|
8
9
|
type LeitwerkExtensionModule,
|
|
9
10
|
type ProvidedCapability,
|
|
11
|
+
type ServerExtensionAPI,
|
|
10
12
|
type ServerExtensionEventMap,
|
|
11
13
|
} from "@leitwerk-dev/process-sdk";
|
|
12
|
-
import { flushAsyncWork } from "
|
|
14
|
+
import { flushAsyncWork } from "@leitwerk-dev/worker-protocol";
|
|
13
15
|
|
|
14
16
|
export { flushAsyncWork };
|
|
15
17
|
|
|
18
|
+
/** Register a test provider and expose its poll result without erasing its type. */
|
|
19
|
+
export function createPollingTestExtension<T>(
|
|
20
|
+
manifest: LeitwerkExtensionModule["manifest"],
|
|
21
|
+
setup: (api: ServerExtensionAPI) => { poll(): Promise<T> } | undefined,
|
|
22
|
+
) {
|
|
23
|
+
let provider: ReturnType<typeof setup>;
|
|
24
|
+
return {
|
|
25
|
+
manifest,
|
|
26
|
+
setupServer(api: ServerExtensionAPI) {
|
|
27
|
+
provider = setup(api);
|
|
28
|
+
},
|
|
29
|
+
poll() {
|
|
30
|
+
if (!provider) throw new Error(`Test provider '${manifest.id}' has not been initialized`);
|
|
31
|
+
return provider.poll();
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function createToolCollector() {
|
|
37
|
+
const tools = new Map<string, IntegrationToolDefinition>();
|
|
38
|
+
const api = {
|
|
39
|
+
tool: (tool: IntegrationToolDefinition) => tools.set(tool.name, tool),
|
|
40
|
+
} as unknown as ServerExtensionAPI;
|
|
41
|
+
return { api, tools };
|
|
42
|
+
}
|
|
43
|
+
|
|
16
44
|
export interface InMemoryExternalWriteLog {
|
|
45
|
+
records: { dedupKey: string }[];
|
|
17
46
|
hasDedupKey(key: string): boolean;
|
|
18
47
|
record(input: { dedupKey: string }): { dedupKey: string };
|
|
19
48
|
getDedupKeys(): ReadonlySet<string>;
|
|
@@ -21,12 +50,15 @@ export interface InMemoryExternalWriteLog {
|
|
|
21
50
|
|
|
22
51
|
export function createInMemoryExternalWriteLog(): InMemoryExternalWriteLog {
|
|
23
52
|
const dedupKeys = new Set<string>();
|
|
53
|
+
const records: { dedupKey: string }[] = [];
|
|
24
54
|
return {
|
|
55
|
+
records,
|
|
25
56
|
hasDedupKey(key: string) {
|
|
26
57
|
return dedupKeys.has(key);
|
|
27
58
|
},
|
|
28
59
|
record(input: { dedupKey: string }) {
|
|
29
60
|
dedupKeys.add(input.dedupKey);
|
|
61
|
+
records.push(input);
|
|
30
62
|
return input;
|
|
31
63
|
},
|
|
32
64
|
getDedupKeys() {
|
|
@@ -40,6 +72,11 @@ function createDefaultServerSetupDeps(): CoreServerSetupDeps {
|
|
|
40
72
|
serverBaseUrl: "https://leitwerk.example",
|
|
41
73
|
components: {},
|
|
42
74
|
externalWrites: createInMemoryExternalWriteLog(),
|
|
75
|
+
polling: {
|
|
76
|
+
create(options) {
|
|
77
|
+
return { poll: options.pollOnce };
|
|
78
|
+
},
|
|
79
|
+
},
|
|
43
80
|
repositoryCredentials: { register: () => {} },
|
|
44
81
|
processes: {
|
|
45
82
|
create: () => {
|
|
@@ -47,6 +84,7 @@ function createDefaultServerSetupDeps(): CoreServerSetupDeps {
|
|
|
47
84
|
},
|
|
48
85
|
getById: () => null,
|
|
49
86
|
listAll: () => [],
|
|
87
|
+
update: () => null,
|
|
50
88
|
},
|
|
51
89
|
projects: {
|
|
52
90
|
create: () => {
|
|
@@ -110,11 +148,11 @@ function createDefaultServerSetupDeps(): CoreServerSetupDeps {
|
|
|
110
148
|
};
|
|
111
149
|
},
|
|
112
150
|
},
|
|
113
|
-
|
|
114
|
-
async
|
|
151
|
+
launchRuns: {
|
|
152
|
+
async startProgrammatic() {
|
|
115
153
|
throw new Error("not used");
|
|
116
154
|
},
|
|
117
|
-
async
|
|
155
|
+
async startWatcher() {
|
|
118
156
|
throw new Error("not used");
|
|
119
157
|
},
|
|
120
158
|
},
|
|
@@ -145,7 +183,7 @@ export function createTestServerSetupCapability(
|
|
|
145
183
|
...overrides.launcherModelConfigs,
|
|
146
184
|
},
|
|
147
185
|
launchPlans: { ...defaults.launchPlans, ...overrides.launchPlans },
|
|
148
|
-
|
|
186
|
+
launchRuns: { ...defaults.launchRuns, ...overrides.launchRuns },
|
|
149
187
|
};
|
|
150
188
|
}
|
|
151
189
|
|
|
@@ -2,6 +2,7 @@ import type { ChildProcess, spawn } from "node:child_process";
|
|
|
2
2
|
import { EventEmitter } from "node:events";
|
|
3
3
|
import { createRequire } from "node:module";
|
|
4
4
|
import { PassThrough } from "node:stream";
|
|
5
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
5
6
|
import type { ExtensionCatalog } from "@leitwerk-dev/extension-runtime";
|
|
6
7
|
import type { PiTreeHandleFactory } from "@leitwerk-dev/worker";
|
|
7
8
|
import { createWorkerEntryRuntime } from "@leitwerk-dev/worker";
|
|
@@ -18,6 +19,8 @@ export interface InProcessWorkerSpawnOptions {
|
|
|
18
19
|
extensionCatalog?: ExtensionCatalog | Promise<ExtensionCatalog>;
|
|
19
20
|
piFactory?: PiTreeHandleFactory;
|
|
20
21
|
toolCallScriptResolver?: StubToolCallScriptResolver;
|
|
22
|
+
/** Optional delays at real connection and managed-runtime preparation boundaries. */
|
|
23
|
+
startupDelays?: (instanceId: string) => { connectMs: number; prepareMs: number } | undefined;
|
|
21
24
|
}
|
|
22
25
|
|
|
23
26
|
/**
|
|
@@ -41,11 +44,15 @@ export function createInProcessWorkerSpawn(
|
|
|
41
44
|
const child = new EventEmitter() as unknown as ChildProcess;
|
|
42
45
|
const emitter = child as unknown as EventEmitter;
|
|
43
46
|
let exited = false;
|
|
47
|
+
const cancellation = new AbortController();
|
|
48
|
+
const timing = options.startupDelays?.(spawnOptions?.env?.LEITWERK_INSTANCE_ID ?? "");
|
|
49
|
+
const pause = (ms: number) => delay(ms, undefined, { signal: cancellation.signal });
|
|
44
50
|
|
|
45
51
|
let runtime: ReturnType<typeof createWorkerEntryRuntime> | null = null;
|
|
46
52
|
const finish = (code: number) => {
|
|
47
53
|
if (!exited) {
|
|
48
54
|
exited = true;
|
|
55
|
+
cancellation.abort();
|
|
49
56
|
emitter.emit("exit", code, null);
|
|
50
57
|
}
|
|
51
58
|
};
|
|
@@ -64,7 +71,16 @@ export function createInProcessWorkerSpawn(
|
|
|
64
71
|
|
|
65
72
|
runtime = createWorkerEntryRuntime({
|
|
66
73
|
extensionCatalog: options.extensionCatalog,
|
|
67
|
-
piFactory
|
|
74
|
+
piFactory: timing
|
|
75
|
+
? {
|
|
76
|
+
async prepareManagedBootstrap(input) {
|
|
77
|
+
await pause(timing.prepareMs);
|
|
78
|
+
return piFactory.prepareManagedBootstrap(input);
|
|
79
|
+
},
|
|
80
|
+
inspectPrimaryTree: (input) => piFactory.inspectPrimaryTree(input),
|
|
81
|
+
createPrimaryTreeHandle: (input) => piFactory.createPrimaryTreeHandle(input),
|
|
82
|
+
}
|
|
83
|
+
: piFactory,
|
|
68
84
|
stderr,
|
|
69
85
|
env: spawnOptions?.env ?? process.env,
|
|
70
86
|
exit: finish,
|
|
@@ -73,7 +89,11 @@ export function createInProcessWorkerSpawn(
|
|
|
73
89
|
setImmediate(() => {
|
|
74
90
|
if (exited) return;
|
|
75
91
|
(globalThis as unknown as { WebSocket?: unknown }).WebSocket = WebSocket;
|
|
76
|
-
void
|
|
92
|
+
void (async () => {
|
|
93
|
+
if (timing) await pause(timing.connectMs);
|
|
94
|
+
if (!exited) await runtime?.start();
|
|
95
|
+
})().catch((error: unknown) => {
|
|
96
|
+
if (exited) return;
|
|
77
97
|
stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
|
|
78
98
|
finish(1);
|
|
79
99
|
});
|
|
@@ -1,8 +1,12 @@
|
|
|
1
|
+
export {
|
|
2
|
+
createTestConfigSnapshot as testConfigSnapshot,
|
|
3
|
+
createTestIpcEnvelopeBase as baseEnvelope,
|
|
4
|
+
flushAsyncWork,
|
|
5
|
+
} from "@leitwerk-dev/worker-protocol";
|
|
1
6
|
export {
|
|
2
7
|
createInProcessWorkerSpawn,
|
|
3
8
|
type InProcessWorkerSpawnOptions,
|
|
4
9
|
} from "../in-process-worker.js";
|
|
5
|
-
export { baseEnvelope, flushAsyncWork, testConfigSnapshot } from "./ipc-harness.js";
|
|
6
10
|
export {
|
|
7
11
|
createSchemaDrivenStubPiFactory,
|
|
8
12
|
createSchemaDrivenToolCallScriptResolver,
|
|
@@ -1,5 +1,7 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
1
2
|
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
3
|
import path from "node:path";
|
|
4
|
+
import { CURRENT_SESSION_VERSION, type SessionHeader } from "@earendil-works/pi-coding-agent";
|
|
3
5
|
import type {
|
|
4
6
|
PiCustomMessageInput,
|
|
5
7
|
PiCustomTool,
|
|
@@ -14,6 +16,7 @@ import type {
|
|
|
14
16
|
PiTreeNode,
|
|
15
17
|
PiTurnExecutionResult,
|
|
16
18
|
} from "@leitwerk-dev/process-sdk";
|
|
19
|
+
import { isEnoent } from "@leitwerk-dev/process-sdk";
|
|
17
20
|
import type {
|
|
18
21
|
PiManagedBootstrapOptions,
|
|
19
22
|
PiManagedBootstrapResult,
|
|
@@ -33,16 +36,29 @@ export type StubToolCallScriptItem =
|
|
|
33
36
|
| StubToolCallScriptCall
|
|
34
37
|
| {
|
|
35
38
|
calls: readonly StubToolCallScriptCall[];
|
|
39
|
+
textChunks?: readonly string[];
|
|
40
|
+
thinkingChunks?: readonly string[];
|
|
41
|
+
chunkDelayMs?: number;
|
|
42
|
+
/** Optional scripted model reaction to a tool result, within the same turn. */
|
|
43
|
+
afterToolResult?: (
|
|
44
|
+
call: StubToolCallScriptCall,
|
|
45
|
+
result: unknown,
|
|
46
|
+
) => StubToolCallScriptCall | undefined;
|
|
36
47
|
};
|
|
37
48
|
|
|
38
49
|
export interface StubToolCallScriptResolverContext {
|
|
39
50
|
promptText: string;
|
|
40
51
|
tools: readonly PiCustomTool[];
|
|
52
|
+
instanceId?: string;
|
|
53
|
+
workspaceRoot?: string;
|
|
54
|
+
sessionCwd?: string;
|
|
55
|
+
treeFile: string;
|
|
56
|
+
turnSequence: number;
|
|
41
57
|
}
|
|
42
58
|
|
|
43
59
|
export type StubToolCallScriptResolver = (
|
|
44
60
|
context: StubToolCallScriptResolverContext,
|
|
45
|
-
) => StubToolCallScriptItem | undefined
|
|
61
|
+
) => StubToolCallScriptItem | undefined | Promise<StubToolCallScriptItem | undefined>;
|
|
46
62
|
|
|
47
63
|
function stringifyToolResult(result: unknown): string {
|
|
48
64
|
if (typeof result === "string") {
|
|
@@ -73,6 +89,7 @@ function stubToolCallId(turnSeq: number, totalCalls: number, index: number): str
|
|
|
73
89
|
}
|
|
74
90
|
|
|
75
91
|
interface StubPiTreeState {
|
|
92
|
+
header?: SessionHeader;
|
|
76
93
|
turnSeq: number;
|
|
77
94
|
currentLeafId: string | null;
|
|
78
95
|
entries: Map<string, PiTreeEntry>;
|
|
@@ -95,6 +112,13 @@ function createEmptyStubPiTreeState(): StubPiTreeState {
|
|
|
95
112
|
};
|
|
96
113
|
}
|
|
97
114
|
|
|
115
|
+
function indexStubEntry(state: StubPiTreeState, entry: PiTreeEntry): void {
|
|
116
|
+
state.entries.set(entry.id, entry);
|
|
117
|
+
const siblings = state.childIdsByParent.get(entry.parentId) ?? [];
|
|
118
|
+
siblings.push(entry.id);
|
|
119
|
+
state.childIdsByParent.set(entry.parentId, siblings);
|
|
120
|
+
}
|
|
121
|
+
|
|
98
122
|
function deriveStubLeafIdFromEntries(state: StubPiTreeState): string | null {
|
|
99
123
|
let leafId: string | null = null;
|
|
100
124
|
for (const entryId of state.entries.keys()) {
|
|
@@ -103,7 +127,16 @@ function deriveStubLeafIdFromEntries(state: StubPiTreeState): string | null {
|
|
|
103
127
|
return leafId;
|
|
104
128
|
}
|
|
105
129
|
|
|
106
|
-
function serializeStubPiTreeState(state: StubPiTreeState): string {
|
|
130
|
+
function serializeStubPiTreeState(state: StubPiTreeState, recordSessionTrace: boolean): string {
|
|
131
|
+
if (recordSessionTrace) {
|
|
132
|
+
return `${[
|
|
133
|
+
JSON.stringify({
|
|
134
|
+
...state.header,
|
|
135
|
+
stubState: { turnSeq: state.turnSeq, currentLeafId: state.currentLeafId },
|
|
136
|
+
}),
|
|
137
|
+
...[...state.entries.values()].map((entry) => JSON.stringify(entry)),
|
|
138
|
+
].join("\n")}\n`;
|
|
139
|
+
}
|
|
107
140
|
const persisted: PersistedStubPiTreeState = {
|
|
108
141
|
turnSeq: state.turnSeq,
|
|
109
142
|
currentLeafId: state.currentLeafId,
|
|
@@ -117,6 +150,22 @@ function serializeStubPiTreeState(state: StubPiTreeState): string {
|
|
|
117
150
|
}
|
|
118
151
|
|
|
119
152
|
function deserializeStubPiTreeState(value: string): StubPiTreeState {
|
|
153
|
+
const lines = value.trim().split("\n");
|
|
154
|
+
const header = JSON.parse(lines[0]) as SessionHeader & {
|
|
155
|
+
stubState?: { turnSeq: number; currentLeafId: string | null };
|
|
156
|
+
};
|
|
157
|
+
if (header.type === "session") {
|
|
158
|
+
const entries = lines
|
|
159
|
+
.slice(1)
|
|
160
|
+
.filter(Boolean)
|
|
161
|
+
.map((line) => JSON.parse(line) as PiTreeEntry);
|
|
162
|
+
const state = createEmptyStubPiTreeState();
|
|
163
|
+
state.header = header;
|
|
164
|
+
state.turnSeq = header.stubState?.turnSeq ?? 0;
|
|
165
|
+
state.currentLeafId = header.stubState?.currentLeafId ?? null;
|
|
166
|
+
for (const entry of entries) indexStubEntry(state, entry);
|
|
167
|
+
return state;
|
|
168
|
+
}
|
|
120
169
|
const parsed = JSON.parse(value) as PersistedStubPiTreeState;
|
|
121
170
|
return {
|
|
122
171
|
turnSeq: typeof parsed.turnSeq === "number" ? parsed.turnSeq : 0,
|
|
@@ -145,6 +194,7 @@ export class StubPiTreeHandle implements PiTreeHandle {
|
|
|
145
194
|
) => boolean | undefined | Promise<boolean | undefined>;
|
|
146
195
|
|
|
147
196
|
private _closed = false;
|
|
197
|
+
private turnAbort = new AbortController();
|
|
148
198
|
private branchDriftPending = false;
|
|
149
199
|
private readonly handlers = new Set<PiEventHandler>();
|
|
150
200
|
private readonly diagnosticHandlers = new Set<PiSessionDiagnosticHandler>();
|
|
@@ -152,6 +202,7 @@ export class StubPiTreeHandle implements PiTreeHandle {
|
|
|
152
202
|
private readonly state: StubPiTreeState;
|
|
153
203
|
private readonly runDetails: PiRunDetails;
|
|
154
204
|
private readonly persistState?: (() => Promise<void>) | undefined;
|
|
205
|
+
private readonly recordSessionTrace: boolean;
|
|
155
206
|
|
|
156
207
|
constructor(options: {
|
|
157
208
|
sessionId: string;
|
|
@@ -161,6 +212,7 @@ export class StubPiTreeHandle implements PiTreeHandle {
|
|
|
161
212
|
state?: StubPiTreeState;
|
|
162
213
|
runDetails?: Partial<PiRunDetails>;
|
|
163
214
|
persistState?: () => Promise<void>;
|
|
215
|
+
recordSessionTrace?: boolean;
|
|
164
216
|
}) {
|
|
165
217
|
this.sessionId = options.sessionId;
|
|
166
218
|
this.treeFile = options.treeFile;
|
|
@@ -168,6 +220,7 @@ export class StubPiTreeHandle implements PiTreeHandle {
|
|
|
168
220
|
this.toolCallScriptResolver = options.toolCallScriptResolver;
|
|
169
221
|
this.state = options.state ?? createEmptyStubPiTreeState();
|
|
170
222
|
this.persistState = options.persistState;
|
|
223
|
+
this.recordSessionTrace = options.recordSessionTrace ?? false;
|
|
171
224
|
this.runDetails = {
|
|
172
225
|
loadedAgentsFiles: options.runDetails?.loadedAgentsFiles?.map((file) => ({ ...file })) ?? [],
|
|
173
226
|
loadedSkills: options.runDetails?.loadedSkills?.map((skill) => ({ ...skill })) ?? [],
|
|
@@ -190,10 +243,7 @@ export class StubPiTreeHandle implements PiTreeHandle {
|
|
|
190
243
|
}
|
|
191
244
|
|
|
192
245
|
private addEntry(entry: PiTreeEntry): void {
|
|
193
|
-
this.state
|
|
194
|
-
const siblings = this.state.childIdsByParent.get(entry.parentId) ?? [];
|
|
195
|
-
siblings.push(entry.id);
|
|
196
|
-
this.state.childIdsByParent.set(entry.parentId, siblings);
|
|
246
|
+
indexStubEntry(this.state, entry);
|
|
197
247
|
this.state.currentLeafId = entry.id;
|
|
198
248
|
}
|
|
199
249
|
|
|
@@ -201,7 +251,7 @@ export class StubPiTreeHandle implements PiTreeHandle {
|
|
|
201
251
|
id: string,
|
|
202
252
|
parentId: string | null,
|
|
203
253
|
role: "user" | "assistant",
|
|
204
|
-
content:
|
|
254
|
+
content: unknown,
|
|
205
255
|
timestamp: string,
|
|
206
256
|
): PiTreeEntry {
|
|
207
257
|
return {
|
|
@@ -314,9 +364,12 @@ export class StubPiTreeHandle implements PiTreeHandle {
|
|
|
314
364
|
appendPromptUserMessage: boolean;
|
|
315
365
|
}): Promise<PiTurnExecutionResult> {
|
|
316
366
|
this.assertOpen();
|
|
367
|
+
this.turnAbort = new AbortController();
|
|
368
|
+
const signal = this.turnAbort.signal;
|
|
317
369
|
if ((await this.beforeTurn?.(input.kind, input.options, input.promptText)) === false) {
|
|
318
370
|
input.options = undefined;
|
|
319
371
|
}
|
|
372
|
+
signal.throwIfAborted();
|
|
320
373
|
if (this.branchDriftPending) {
|
|
321
374
|
this.branchDriftPending = false;
|
|
322
375
|
throw Object.assign(new Error("stubbed Pi branch drift"), {
|
|
@@ -350,18 +403,84 @@ export class StubPiTreeHandle implements PiTreeHandle {
|
|
|
350
403
|
);
|
|
351
404
|
createdEntryIds.push(userEntryId);
|
|
352
405
|
}
|
|
406
|
+
await this.persistState?.();
|
|
407
|
+
signal.throwIfAborted();
|
|
353
408
|
this.emitEvent({ type: "turn.start", turnId, data: {}, timestamp });
|
|
354
409
|
|
|
355
410
|
const tools = new Map((input.options?.tools ?? []).map((tool) => [tool.name, tool]));
|
|
356
411
|
let assistantContent = input.promptText ?? "Continued.";
|
|
357
412
|
let assistantContentFromScriptedMarkdown = false;
|
|
358
|
-
const scriptedItem = this.toolCallScriptResolver?.({
|
|
413
|
+
const scriptedItem = await this.toolCallScriptResolver?.({
|
|
414
|
+
treeFile: this.treeFile,
|
|
415
|
+
turnSequence: this.state.turnSeq,
|
|
359
416
|
promptText: input.promptText ?? "",
|
|
360
417
|
tools: input.options?.tools ?? [],
|
|
361
418
|
});
|
|
419
|
+
signal.throwIfAborted();
|
|
420
|
+
const hasScriptedChunks = Boolean(
|
|
421
|
+
scriptedItem &&
|
|
422
|
+
"calls" in scriptedItem &&
|
|
423
|
+
(scriptedItem.textChunks?.length ?? 0) + (scriptedItem.thinkingChunks?.length ?? 0),
|
|
424
|
+
);
|
|
425
|
+
if (hasScriptedChunks) assistantContent = "";
|
|
426
|
+
if (scriptedItem && "calls" in scriptedItem) {
|
|
427
|
+
const streamed = { thinking: "", text: "" };
|
|
428
|
+
const streamEntryId = `stream-${this.state.turnSeq}`;
|
|
429
|
+
const streamParentId = this.state.currentLeafId;
|
|
430
|
+
const chunks = [
|
|
431
|
+
...(scriptedItem.thinkingChunks ?? []).map((text) => ({
|
|
432
|
+
text,
|
|
433
|
+
streamType: "thinking" as const,
|
|
434
|
+
})),
|
|
435
|
+
...(scriptedItem.textChunks ?? []).map((text) => ({ text, streamType: "text" as const })),
|
|
436
|
+
];
|
|
437
|
+
for (const { text, streamType } of chunks) {
|
|
438
|
+
signal.throwIfAborted();
|
|
439
|
+
streamed[streamType] += text;
|
|
440
|
+
assistantContent = streamed.text;
|
|
441
|
+
if (this.recordSessionTrace) {
|
|
442
|
+
const entry = this.createMessageEntry(
|
|
443
|
+
streamEntryId,
|
|
444
|
+
streamParentId,
|
|
445
|
+
"assistant",
|
|
446
|
+
[
|
|
447
|
+
...(streamed.thinking ? [{ type: "thinking", thinking: streamed.thinking }] : []),
|
|
448
|
+
...(streamed.text ? [{ type: "text", text: streamed.text }] : []),
|
|
449
|
+
],
|
|
450
|
+
timestamp,
|
|
451
|
+
);
|
|
452
|
+
if (this.state.entries.has(streamEntryId)) this.state.entries.set(streamEntryId, entry);
|
|
453
|
+
else {
|
|
454
|
+
this.addEntry(entry);
|
|
455
|
+
createdEntryIds.push(streamEntryId);
|
|
456
|
+
}
|
|
457
|
+
await this.persistState?.();
|
|
458
|
+
}
|
|
459
|
+
this.emitEvent({
|
|
460
|
+
type: "stream.delta",
|
|
461
|
+
turnId,
|
|
462
|
+
data: { text, streamType },
|
|
463
|
+
timestamp: new Date().toISOString(),
|
|
464
|
+
});
|
|
465
|
+
signal.throwIfAborted();
|
|
466
|
+
if (scriptedItem.chunkDelayMs)
|
|
467
|
+
await new Promise<void>((resolve, reject) => {
|
|
468
|
+
const timer = setTimeout(() => {
|
|
469
|
+
signal.removeEventListener("abort", abort);
|
|
470
|
+
resolve();
|
|
471
|
+
}, scriptedItem.chunkDelayMs);
|
|
472
|
+
const abort = () => {
|
|
473
|
+
clearTimeout(timer);
|
|
474
|
+
reject(signal.reason);
|
|
475
|
+
};
|
|
476
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
477
|
+
});
|
|
478
|
+
}
|
|
479
|
+
}
|
|
362
480
|
const scriptedCalls = scriptedItem ? expandStubToolCallScriptItem(scriptedItem) : [];
|
|
363
481
|
if (scriptedCalls.length > 0) {
|
|
364
482
|
for (const [callIndex, scriptedCall] of scriptedCalls.entries()) {
|
|
483
|
+
signal.throwIfAborted();
|
|
365
484
|
const toolCallId = stubToolCallId(this.state.turnSeq, scriptedCalls.length, callIndex);
|
|
366
485
|
this.emitEvent({
|
|
367
486
|
type: "tool.call",
|
|
@@ -382,11 +501,66 @@ export class StubPiTreeHandle implements PiTreeHandle {
|
|
|
382
501
|
}
|
|
383
502
|
}
|
|
384
503
|
if (tool) {
|
|
504
|
+
if (this.recordSessionTrace) {
|
|
505
|
+
const entryId = `call-${toolCallId}`;
|
|
506
|
+
this.addEntry(
|
|
507
|
+
this.createMessageEntry(
|
|
508
|
+
entryId,
|
|
509
|
+
this.state.currentLeafId,
|
|
510
|
+
"assistant",
|
|
511
|
+
[
|
|
512
|
+
{
|
|
513
|
+
type: "toolCall",
|
|
514
|
+
id: toolCallId,
|
|
515
|
+
name: scriptedCall.toolName,
|
|
516
|
+
arguments: scriptedCall.args,
|
|
517
|
+
},
|
|
518
|
+
],
|
|
519
|
+
new Date().toISOString(),
|
|
520
|
+
),
|
|
521
|
+
);
|
|
522
|
+
createdEntryIds.push(entryId);
|
|
523
|
+
await this.persistState?.();
|
|
524
|
+
}
|
|
525
|
+
const recordToolResult = async (result: unknown, isError: boolean) => {
|
|
526
|
+
if (!this.recordSessionTrace) return;
|
|
527
|
+
const entryId = `result-${toolCallId}`;
|
|
528
|
+
const entry = {
|
|
529
|
+
id: entryId,
|
|
530
|
+
parentId: this.state.currentLeafId,
|
|
531
|
+
type: "message",
|
|
532
|
+
timestamp: new Date().toISOString(),
|
|
533
|
+
message: {
|
|
534
|
+
role: "toolResult",
|
|
535
|
+
toolCallId,
|
|
536
|
+
toolName: scriptedCall.toolName,
|
|
537
|
+
content: [{ type: "text", text: stringifyToolResult(result) }],
|
|
538
|
+
isError,
|
|
539
|
+
},
|
|
540
|
+
};
|
|
541
|
+
this.addEntry(entry);
|
|
542
|
+
createdEntryIds.push(entryId);
|
|
543
|
+
await this.persistState?.();
|
|
544
|
+
};
|
|
385
545
|
try {
|
|
386
|
-
|
|
546
|
+
signal.throwIfAborted();
|
|
547
|
+
const blocked = input.options?.shouldBlockToolCall?.(scriptedCall.toolName);
|
|
548
|
+
if (blocked) throw new Error(blocked);
|
|
549
|
+
const result = await tool.execute(scriptedCall.args, {
|
|
550
|
+
toolCallId,
|
|
551
|
+
signal,
|
|
552
|
+
suspendPromptGuards: input.options?.suspendPromptGuards,
|
|
553
|
+
});
|
|
554
|
+
signal.throwIfAborted();
|
|
387
555
|
if (!assistantContentFromScriptedMarkdown) {
|
|
388
556
|
assistantContent = stringifyToolResult(result);
|
|
389
557
|
}
|
|
558
|
+
await recordToolResult(result, false);
|
|
559
|
+
const followUp =
|
|
560
|
+
scriptedItem && "calls" in scriptedItem
|
|
561
|
+
? scriptedItem.afterToolResult?.(scriptedCall, result)
|
|
562
|
+
: undefined;
|
|
563
|
+
if (followUp) scriptedCalls.push(followUp);
|
|
390
564
|
this.emitEvent({
|
|
391
565
|
type: "tool.result",
|
|
392
566
|
turnId,
|
|
@@ -394,6 +568,7 @@ export class StubPiTreeHandle implements PiTreeHandle {
|
|
|
394
568
|
timestamp,
|
|
395
569
|
});
|
|
396
570
|
} catch (error) {
|
|
571
|
+
await recordToolResult(error instanceof Error ? error.message : String(error), true);
|
|
397
572
|
this.emitEvent({
|
|
398
573
|
type: "error",
|
|
399
574
|
turnId,
|
|
@@ -423,11 +598,11 @@ export class StubPiTreeHandle implements PiTreeHandle {
|
|
|
423
598
|
createdEntryIds.push(intermediateEntryId);
|
|
424
599
|
}
|
|
425
600
|
}
|
|
426
|
-
} else if (tools.size > 0) {
|
|
601
|
+
} else if (tools.size > 0 && !hasScriptedChunks) {
|
|
427
602
|
throw new Error(
|
|
428
603
|
`Stub Pi prompt requires a stub tool-call script when tools are provided (${[...tools.keys()].join(", ")})`,
|
|
429
604
|
);
|
|
430
|
-
} else if (input.promptText !== undefined) {
|
|
605
|
+
} else if (input.promptText !== undefined && !hasScriptedChunks) {
|
|
431
606
|
this.emitEvent({
|
|
432
607
|
type: "stream.delta",
|
|
433
608
|
turnId,
|
|
@@ -436,17 +611,22 @@ export class StubPiTreeHandle implements PiTreeHandle {
|
|
|
436
611
|
});
|
|
437
612
|
}
|
|
438
613
|
|
|
614
|
+
signal.throwIfAborted();
|
|
615
|
+
// Keep the result entry ID without repeating content already saved in the stream entry.
|
|
439
616
|
this.addEntry(
|
|
440
617
|
this.createMessageEntry(
|
|
441
618
|
turnId,
|
|
442
619
|
this.state.currentLeafId,
|
|
443
620
|
"assistant",
|
|
444
|
-
|
|
621
|
+
this.recordSessionTrace && hasScriptedChunks && scriptedCalls.length === 0
|
|
622
|
+
? []
|
|
623
|
+
: assistantContent,
|
|
445
624
|
timestamp,
|
|
446
625
|
),
|
|
447
626
|
);
|
|
448
627
|
createdEntryIds.push(turnId);
|
|
449
628
|
await this.persistState?.();
|
|
629
|
+
signal.throwIfAborted();
|
|
450
630
|
this.emitEvent({ type: "turn.end", turnId, data: {}, timestamp });
|
|
451
631
|
const resultEntryId = this.state.currentLeafId;
|
|
452
632
|
if (!resultEntryId) {
|
|
@@ -544,6 +724,7 @@ export class StubPiTreeHandle implements PiTreeHandle {
|
|
|
544
724
|
|
|
545
725
|
async abortTurn(): Promise<void> {
|
|
546
726
|
this.assertOpen();
|
|
727
|
+
this.turnAbort.abort(new Error("Scripted turn aborted"));
|
|
547
728
|
}
|
|
548
729
|
|
|
549
730
|
subscribe(handler: PiEventHandler): () => void {
|
|
@@ -565,6 +746,7 @@ export class StubPiTreeHandle implements PiTreeHandle {
|
|
|
565
746
|
}
|
|
566
747
|
|
|
567
748
|
async close(): Promise<void> {
|
|
749
|
+
this.turnAbort.abort(new Error("Scripted session closed"));
|
|
568
750
|
await this.persistState?.();
|
|
569
751
|
this._closed = true;
|
|
570
752
|
this.handlers.clear();
|
|
@@ -574,6 +756,8 @@ export class StubPiTreeHandle implements PiTreeHandle {
|
|
|
574
756
|
|
|
575
757
|
export interface StubPiTreeHandleFactoryOptions {
|
|
576
758
|
toolCallScriptResolver?: StubToolCallScriptResolver;
|
|
759
|
+
/** Persist SDK-readable JSONL with reasoning and tool messages for history/detail tests. */
|
|
760
|
+
recordSessionTrace?: boolean;
|
|
577
761
|
}
|
|
578
762
|
|
|
579
763
|
export class StubPiTreeHandleFactory implements PiTreeHandleFactory {
|
|
@@ -582,9 +766,11 @@ export class StubPiTreeHandleFactory implements PiTreeHandleFactory {
|
|
|
582
766
|
|
|
583
767
|
private seq = 0;
|
|
584
768
|
private readonly treeStateByFile = new Map<string, StubPiTreeState>();
|
|
769
|
+
private readonly recordSessionTrace: boolean;
|
|
585
770
|
|
|
586
771
|
constructor(options: StubPiTreeHandleFactoryOptions = {}) {
|
|
587
772
|
this.toolCallScriptResolver = options.toolCallScriptResolver;
|
|
773
|
+
this.recordSessionTrace = options.recordSessionTrace ?? false;
|
|
588
774
|
}
|
|
589
775
|
|
|
590
776
|
async prepareManagedBootstrap(
|
|
@@ -607,12 +793,7 @@ export class StubPiTreeHandleFactory implements PiTreeHandleFactory {
|
|
|
607
793
|
try {
|
|
608
794
|
treeState = deserializeStubPiTreeState(readFileSync(opts.treeFile, "utf8"));
|
|
609
795
|
} catch (error) {
|
|
610
|
-
if (
|
|
611
|
-
typeof error === "object" &&
|
|
612
|
-
error !== null &&
|
|
613
|
-
"code" in error &&
|
|
614
|
-
(error as { code?: unknown }).code === "ENOENT"
|
|
615
|
-
) {
|
|
796
|
+
if (isEnoent(error)) {
|
|
616
797
|
return { currentLeafId: null, entries: [] };
|
|
617
798
|
}
|
|
618
799
|
throw error;
|
|
@@ -632,7 +813,11 @@ export class StubPiTreeHandleFactory implements PiTreeHandleFactory {
|
|
|
632
813
|
this.treeStateByFile.set(opts.treeFile, state);
|
|
633
814
|
try {
|
|
634
815
|
mkdirSync(path.dirname(opts.treeFile), { recursive: true });
|
|
635
|
-
writeFileSync(
|
|
816
|
+
writeFileSync(
|
|
817
|
+
opts.treeFile,
|
|
818
|
+
serializeStubPiTreeState(state, this.recordSessionTrace),
|
|
819
|
+
"utf8",
|
|
820
|
+
);
|
|
636
821
|
} catch (error) {
|
|
637
822
|
if (
|
|
638
823
|
typeof error !== "object" ||
|
|
@@ -663,6 +848,13 @@ export class StubPiTreeHandleFactory implements PiTreeHandleFactory {
|
|
|
663
848
|
}
|
|
664
849
|
}
|
|
665
850
|
treeState ??= createEmptyStubPiTreeState();
|
|
851
|
+
treeState.header ??= {
|
|
852
|
+
type: "session",
|
|
853
|
+
version: CURRENT_SESSION_VERSION,
|
|
854
|
+
id: randomUUID(),
|
|
855
|
+
timestamp: new Date().toISOString(),
|
|
856
|
+
cwd: opts.sessionCwd ?? opts.workspaceRoot ?? path.dirname(opts.treeFile),
|
|
857
|
+
};
|
|
666
858
|
if (opts.resume) {
|
|
667
859
|
treeState.currentLeafId = deriveStubLeafIdFromEntries(treeState);
|
|
668
860
|
}
|
|
@@ -671,9 +863,18 @@ export class StubPiTreeHandleFactory implements PiTreeHandleFactory {
|
|
|
671
863
|
sessionId: `stub-${++this.seq}`,
|
|
672
864
|
treeFile: opts.treeFile,
|
|
673
865
|
isResumed: opts.resume,
|
|
674
|
-
toolCallScriptResolver: this.toolCallScriptResolver
|
|
866
|
+
toolCallScriptResolver: this.toolCallScriptResolver
|
|
867
|
+
? (context) =>
|
|
868
|
+
this.toolCallScriptResolver?.({
|
|
869
|
+
...context,
|
|
870
|
+
instanceId: opts.instanceId,
|
|
871
|
+
workspaceRoot: opts.workspaceRoot,
|
|
872
|
+
sessionCwd: opts.sessionCwd,
|
|
873
|
+
})
|
|
874
|
+
: undefined,
|
|
675
875
|
state: treeState,
|
|
676
876
|
persistState: () => persistState(treeState),
|
|
877
|
+
recordSessionTrace: this.recordSessionTrace,
|
|
677
878
|
runDetails: {
|
|
678
879
|
availableToolNames: opts.piConfig?.availableToolNames ?? [],
|
|
679
880
|
},
|
|
@@ -87,6 +87,8 @@ export interface WorkerRuntimeHarnessOptions {
|
|
|
87
87
|
config?: Partial<WorkerRuntimeConfig>;
|
|
88
88
|
/** Optional default used by start() and startLlmTo(). */
|
|
89
89
|
startPayload?: WorkerStartPayload;
|
|
90
|
+
/** Model the server's durable terminal acknowledgement. Defaults to true. */
|
|
91
|
+
autoAcknowledgeTerminals?: boolean;
|
|
90
92
|
adapters: Pick<WorkerRuntimeAdapters, "piFactory" | "gitOps"> &
|
|
91
93
|
Partial<
|
|
92
94
|
Pick<
|
|
@@ -151,6 +153,16 @@ export function createWorkerRuntimeHarness(options: WorkerRuntimeHarnessOptions)
|
|
|
151
153
|
outgoing.push(message);
|
|
152
154
|
observations.push({ kind: "ipc", type: message.type });
|
|
153
155
|
notifyWaiters();
|
|
156
|
+
if (
|
|
157
|
+
options.autoAcknowledgeTerminals !== false &&
|
|
158
|
+
(message.type === "worker.turn_outcome" || message.type === "worker.turn_failed")
|
|
159
|
+
) {
|
|
160
|
+
queueMicrotask(() =>
|
|
161
|
+
deliver("worker.turn_terminal_recorded", {
|
|
162
|
+
turnRecordId: message.payload.turnRecordId,
|
|
163
|
+
}),
|
|
164
|
+
);
|
|
165
|
+
}
|
|
154
166
|
},
|
|
155
167
|
onMessage(handler) {
|
|
156
168
|
messageHandler = handler;
|
|
@@ -235,6 +247,18 @@ export function createWorkerRuntimeHarness(options: WorkerRuntimeHarnessOptions)
|
|
|
235
247
|
await this.flush();
|
|
236
248
|
},
|
|
237
249
|
async stop(reason: string) {
|
|
250
|
+
const terminal = [...outgoing]
|
|
251
|
+
.reverse()
|
|
252
|
+
.find(
|
|
253
|
+
(message) =>
|
|
254
|
+
message.type === "worker.turn_outcome" || message.type === "worker.turn_failed",
|
|
255
|
+
);
|
|
256
|
+
if (terminal) {
|
|
257
|
+
deliver("worker.turn_terminal_recorded", {
|
|
258
|
+
turnRecordId: terminal.payload.turnRecordId,
|
|
259
|
+
});
|
|
260
|
+
await this.flush();
|
|
261
|
+
}
|
|
238
262
|
await runtime.stop(reason);
|
|
239
263
|
},
|
|
240
264
|
async acceptStart(acceptance: { startRecordId?: string; turnRecordId?: string } = {}) {
|
|
@@ -129,6 +129,7 @@ export function createTestLlmWorkerStartPayload(
|
|
|
129
129
|
treePaths: {
|
|
130
130
|
primaryTreeFile: path.join(options.root, "tree", "primary.jsonl"),
|
|
131
131
|
workspaceRoot: path.join(options.root, "workspace"),
|
|
132
|
+
piResourceBundlesDir: path.join(options.root, "pi-resource-bundles"),
|
|
132
133
|
},
|
|
133
134
|
resume: options.resume ?? false,
|
|
134
135
|
};
|