@leitwerk-dev/test-support 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/LICENSE +13 -0
- package/dist/chunk-22HCVJEE.js +294 -0
- package/dist/chunk-22HCVJEE.js.map +1 -0
- package/dist/chunk-3MQO3NCX.js +15 -0
- package/dist/chunk-3MQO3NCX.js.map +1 -0
- package/dist/chunk-7ZK5QRGP.js +98 -0
- package/dist/chunk-7ZK5QRGP.js.map +1 -0
- package/dist/chunk-JUH3LUYK.js +28 -0
- package/dist/chunk-JUH3LUYK.js.map +1 -0
- package/dist/chunk-KIDBCGNW.js +84 -0
- package/dist/chunk-KIDBCGNW.js.map +1 -0
- package/dist/chunk-QFCJV2VA.js +600 -0
- package/dist/chunk-QFCJV2VA.js.map +1 -0
- package/dist/chunk-R4KVUGWR.js +83 -0
- package/dist/chunk-R4KVUGWR.js.map +1 -0
- package/dist/compact-process-detail-fixture.d.ts +6 -0
- package/dist/compact-process-detail-fixture.d.ts.map +1 -0
- package/dist/compact-process-detail-fixture.js +73 -0
- package/dist/compact-process-detail-fixture.js.map +1 -0
- package/dist/fakes/fake-git-ops.d.ts +22 -0
- package/dist/fakes/fake-git-ops.d.ts.map +1 -0
- package/dist/fakes/fake-git-ops.js +101 -0
- package/dist/fakes/fake-git-ops.js.map +1 -0
- package/dist/fakes/fake-llm.d.ts +21 -0
- package/dist/fakes/fake-llm.d.ts.map +1 -0
- package/dist/fakes/fake-llm.js +27 -0
- package/dist/fakes/fake-llm.js.map +1 -0
- package/dist/fakes/index.d.ts +3 -0
- package/dist/fakes/index.d.ts.map +1 -0
- package/dist/fakes/index.js +3 -0
- package/dist/fakes/index.js.map +1 -0
- package/dist/fixtures.d.ts +3 -0
- package/dist/fixtures.d.ts.map +1 -0
- package/dist/fixtures.js +3 -0
- package/dist/fixtures.js.map +1 -0
- package/dist/in-process-worker.d.ts +2 -0
- package/dist/in-process-worker.d.ts.map +1 -0
- package/dist/in-process-worker.js +2 -0
- package/dist/in-process-worker.js.map +1 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +13 -0
- package/dist/index.js.map +1 -0
- package/dist/integration-harness.d.ts +21 -0
- package/dist/integration-harness.d.ts.map +1 -0
- package/dist/integration-harness.js +38 -0
- package/dist/integration-harness.js.map +1 -0
- package/dist/integration.d.ts +5 -0
- package/dist/integration.d.ts.map +1 -0
- package/dist/integration.js +5 -0
- package/dist/integration.js.map +1 -0
- package/dist/polling.d.ts +2 -0
- package/dist/polling.d.ts.map +1 -0
- package/dist/polling.js +14 -0
- package/dist/polling.js.map +1 -0
- package/dist/question-fixtures.d.ts +4 -0
- package/dist/question-fixtures.d.ts.map +1 -0
- package/dist/question-fixtures.js +26 -0
- package/dist/question-fixtures.js.map +1 -0
- package/dist/server-extension-test-harness.d.ts +31 -0
- package/dist/server-extension-test-harness.d.ts.map +1 -0
- package/dist/server-extension-test-harness.js +167 -0
- package/dist/server-extension-test-harness.js.map +1 -0
- package/dist/stub-worker-entry.d.ts +2 -0
- package/dist/stub-worker-entry.d.ts.map +1 -0
- package/dist/stub-worker-entry.js +10 -0
- package/dist/stub-worker-entry.js.map +1 -0
- package/dist/test-app.d.ts +23 -0
- package/dist/test-app.d.ts.map +1 -0
- package/dist/test-app.js +47 -0
- package/dist/test-app.js.map +1 -0
- package/dist/worker-testing/in-process-worker-spawn.d.ts +15 -0
- package/dist/worker-testing/in-process-worker-spawn.d.ts.map +1 -0
- package/dist/worker-testing/in-process-worker-spawn.js +61 -0
- package/dist/worker-testing/in-process-worker-spawn.js.map +1 -0
- package/dist/worker-testing/index.d.ts +8 -0
- package/dist/worker-testing/index.d.ts.map +1 -0
- package/dist/worker-testing/index.js +8 -0
- package/dist/worker-testing/index.js.map +1 -0
- package/dist/worker-testing/ipc-harness.d.ts +11 -0
- package/dist/worker-testing/ipc-harness.d.ts.map +1 -0
- package/dist/worker-testing/ipc-harness.js +17 -0
- package/dist/worker-testing/ipc-harness.js.map +1 -0
- package/dist/worker-testing/schema-driven-stub-pi.d.ts +8 -0
- package/dist/worker-testing/schema-driven-stub-pi.d.ts.map +1 -0
- package/dist/worker-testing/schema-driven-stub-pi.js +65 -0
- package/dist/worker-testing/schema-driven-stub-pi.js.map +1 -0
- package/dist/worker-testing/stub-pi-controls.d.ts +7 -0
- package/dist/worker-testing/stub-pi-controls.d.ts.map +1 -0
- package/dist/worker-testing/stub-pi-controls.js +10 -0
- package/dist/worker-testing/stub-pi-controls.js.map +1 -0
- package/dist/worker-testing/stub-pi-tree-handle.d.ts +92 -0
- package/dist/worker-testing/stub-pi-tree-handle.d.ts.map +1 -0
- package/dist/worker-testing/stub-pi-tree-handle.js +515 -0
- package/dist/worker-testing/stub-pi-tree-handle.js.map +1 -0
- package/dist/worker-testing/worker-runtime-harness.d.ts +53 -0
- package/dist/worker-testing/worker-runtime-harness.d.ts.map +1 -0
- package/dist/worker-testing/worker-runtime-harness.js +210 -0
- package/dist/worker-testing/worker-runtime-harness.js.map +1 -0
- package/dist/worker-testing/worker-start-payload.d.ts +25 -0
- package/dist/worker-testing/worker-start-payload.d.ts.map +1 -0
- package/dist/worker-testing/worker-start-payload.js +101 -0
- package/dist/worker-testing/worker-start-payload.js.map +1 -0
- package/dist/workspace-source-aliases.d.ts +6 -0
- package/dist/workspace-source-aliases.d.ts.map +1 -0
- package/dist/workspace-source-aliases.js +126 -0
- package/dist/workspace-source-aliases.js.map +1 -0
- package/package.json +66 -0
- package/src/compact-process-detail-fixture.ts +117 -0
- package/src/fakes/fake-git-ops.ts +109 -0
- package/src/fakes/fake-llm.ts +39 -0
- package/src/fakes/index.ts +2 -0
- package/src/fixtures.ts +2 -0
- package/src/in-process-worker.ts +4 -0
- package/src/index.ts +45 -0
- package/src/integration-harness.ts +75 -0
- package/src/integration.ts +14 -0
- package/src/polling.ts +17 -0
- package/src/question-fixtures.ts +32 -0
- package/src/server-extension-test-harness.ts +204 -0
- package/src/stub-worker-entry.ts +11 -0
- package/src/test-app.ts +82 -0
- package/src/worker-testing/in-process-worker-spawn.ts +84 -0
- package/src/worker-testing/index.ts +36 -0
- package/src/worker-testing/ipc-harness.ts +19 -0
- package/src/worker-testing/schema-driven-stub-pi.ts +83 -0
- package/src/worker-testing/stub-pi-controls.ts +16 -0
- package/src/worker-testing/stub-pi-tree-handle.ts +687 -0
- package/src/worker-testing/worker-runtime-harness.ts +280 -0
- package/src/worker-testing/worker-start-payload.ts +135 -0
- package/src/workspace-source-aliases.ts +171 -0
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
import { createEventBus } from "@leitwerk-dev/process-sdk";
|
|
2
|
+
import {
|
|
3
|
+
createWorkerRuntime,
|
|
4
|
+
type WorkerRuntimeAdapters,
|
|
5
|
+
type WorkerRuntimeConfig,
|
|
6
|
+
type WorkerRuntimeScheduler,
|
|
7
|
+
} from "@leitwerk-dev/worker";
|
|
8
|
+
import {
|
|
9
|
+
createIpcMessage,
|
|
10
|
+
type ServerToWorkerMessage,
|
|
11
|
+
type WorkerStartPayload,
|
|
12
|
+
type WorkerToServerMessage,
|
|
13
|
+
} from "@leitwerk-dev/worker-protocol";
|
|
14
|
+
|
|
15
|
+
type Timer = ReturnType<typeof setTimeout>;
|
|
16
|
+
type ServerMessageType = ServerToWorkerMessage["type"];
|
|
17
|
+
type ServerMessagePayloadByType = {
|
|
18
|
+
[T in ServerMessageType]: Extract<ServerToWorkerMessage, { type: T }>["payload"];
|
|
19
|
+
};
|
|
20
|
+
type WorkerMessageType = WorkerToServerMessage["type"];
|
|
21
|
+
type WorkerMessageByType<T extends WorkerMessageType> = Extract<WorkerToServerMessage, { type: T }>;
|
|
22
|
+
type MessageWaiter = {
|
|
23
|
+
type: WorkerMessageType;
|
|
24
|
+
count: number;
|
|
25
|
+
resolve(message: WorkerToServerMessage): void;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
type Scheduled = {
|
|
29
|
+
id: number;
|
|
30
|
+
dueAt: number;
|
|
31
|
+
handler(): void;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
export interface ManualWorkerRuntimeScheduler extends WorkerRuntimeScheduler {
|
|
35
|
+
advanceBy(delayMs: number): Promise<void>;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function createManualWorkerRuntimeScheduler(
|
|
39
|
+
initialNow = new Date("2025-01-01T00:00:00.000Z"),
|
|
40
|
+
): ManualWorkerRuntimeScheduler {
|
|
41
|
+
let nowMs = initialNow.getTime();
|
|
42
|
+
let nextId = 1;
|
|
43
|
+
const scheduled = new Map<number, Scheduled>();
|
|
44
|
+
const asTimer = (id: number) => id as unknown as Timer;
|
|
45
|
+
const fromTimer = (timer: Timer) => timer as unknown as number;
|
|
46
|
+
|
|
47
|
+
const schedule = (handler: () => void, delayMs: number): number => {
|
|
48
|
+
const id = nextId++;
|
|
49
|
+
scheduled.set(id, { id, dueAt: nowMs + delayMs, handler });
|
|
50
|
+
return id;
|
|
51
|
+
};
|
|
52
|
+
const clearTimer = (timer: Timer): void => {
|
|
53
|
+
scheduled.delete(fromTimer(timer));
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
return {
|
|
57
|
+
setTimeout: (handler, delayMs) => asTimer(schedule(handler, delayMs)),
|
|
58
|
+
clearTimeout: clearTimer,
|
|
59
|
+
sleep: (delayMs) => new Promise((resolve) => schedule(resolve, delayMs)),
|
|
60
|
+
now() {
|
|
61
|
+
return new Date(nowMs);
|
|
62
|
+
},
|
|
63
|
+
async advanceBy(delayMs) {
|
|
64
|
+
const target = nowMs + delayMs;
|
|
65
|
+
while (true) {
|
|
66
|
+
const next = [...scheduled.values()]
|
|
67
|
+
.filter((item) => item.dueAt <= target)
|
|
68
|
+
.sort((left, right) => left.dueAt - right.dueAt || left.id - right.id)[0];
|
|
69
|
+
if (!next) break;
|
|
70
|
+
nowMs = next.dueAt;
|
|
71
|
+
scheduled.delete(next.id);
|
|
72
|
+
next.handler();
|
|
73
|
+
await Promise.resolve();
|
|
74
|
+
}
|
|
75
|
+
nowMs = target;
|
|
76
|
+
},
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export interface WorkerRuntimeHarnessOptions {
|
|
81
|
+
config?: Partial<WorkerRuntimeConfig>;
|
|
82
|
+
/** Optional default used by start() and startLlmTo(). */
|
|
83
|
+
startPayload?: WorkerStartPayload;
|
|
84
|
+
adapters: Pick<WorkerRuntimeAdapters, "piFactory" | "gitOps"> &
|
|
85
|
+
Partial<
|
|
86
|
+
Pick<
|
|
87
|
+
WorkerRuntimeAdapters,
|
|
88
|
+
| "sessionSnapshots"
|
|
89
|
+
| "resultImageTools"
|
|
90
|
+
| "resolveWorkerProcess"
|
|
91
|
+
| "stderr"
|
|
92
|
+
| "extensionEvents"
|
|
93
|
+
>
|
|
94
|
+
>;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export type WorkerRuntimeObservation =
|
|
98
|
+
| { kind: "ipc"; type: WorkerToServerMessage["type"] }
|
|
99
|
+
| { kind: "extension"; event: string };
|
|
100
|
+
|
|
101
|
+
export function createWorkerRuntimeHarness(options: WorkerRuntimeHarnessOptions) {
|
|
102
|
+
let messageHandler: ((message: ServerToWorkerMessage) => void) | undefined;
|
|
103
|
+
let errorHandler: ((error: Error) => void) | undefined;
|
|
104
|
+
let connectHandler: (() => void) | undefined;
|
|
105
|
+
const outgoing: WorkerToServerMessage[] = [];
|
|
106
|
+
const waiters = new Set<MessageWaiter>();
|
|
107
|
+
const messagesOfType = <T extends WorkerMessageType>(type: T): WorkerMessageByType<T>[] =>
|
|
108
|
+
outgoing.filter((message) => message.type === type) as WorkerMessageByType<T>[];
|
|
109
|
+
const notifyWaiters = (): void => {
|
|
110
|
+
for (const waiter of waiters) {
|
|
111
|
+
const matches = messagesOfType(waiter.type);
|
|
112
|
+
const message = matches[waiter.count - 1];
|
|
113
|
+
if (!message) continue;
|
|
114
|
+
waiters.delete(waiter);
|
|
115
|
+
waiter.resolve(message);
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
const observations: WorkerRuntimeObservation[] = [];
|
|
119
|
+
const exitCodes: number[] = [];
|
|
120
|
+
let transportStartCount = 0;
|
|
121
|
+
let transportStopCount = 0;
|
|
122
|
+
let nextMessageId = 1;
|
|
123
|
+
let latestStart: WorkerStartPayload | undefined;
|
|
124
|
+
const instanceId = options.config?.instanceId ?? "proc_test";
|
|
125
|
+
const workerId = options.config?.workerId ?? "worker_test";
|
|
126
|
+
const deliver = <T extends ServerMessageType>(
|
|
127
|
+
type: T,
|
|
128
|
+
payload: ServerMessagePayloadByType[T],
|
|
129
|
+
): void => {
|
|
130
|
+
if (type === "worker.start") latestStart = payload as WorkerStartPayload;
|
|
131
|
+
messageHandler?.(
|
|
132
|
+
createIpcMessage({
|
|
133
|
+
type,
|
|
134
|
+
payload,
|
|
135
|
+
messageId: `harness_${nextMessageId++}`,
|
|
136
|
+
instanceId,
|
|
137
|
+
workerId,
|
|
138
|
+
} as never) as ServerToWorkerMessage,
|
|
139
|
+
);
|
|
140
|
+
};
|
|
141
|
+
const scheduler = createManualWorkerRuntimeScheduler();
|
|
142
|
+
const transport: WorkerRuntimeAdapters["transport"] = {
|
|
143
|
+
send(message) {
|
|
144
|
+
outgoing.push(message);
|
|
145
|
+
observations.push({ kind: "ipc", type: message.type });
|
|
146
|
+
notifyWaiters();
|
|
147
|
+
},
|
|
148
|
+
onMessage(handler) {
|
|
149
|
+
messageHandler = handler;
|
|
150
|
+
},
|
|
151
|
+
onError(handler) {
|
|
152
|
+
errorHandler = handler;
|
|
153
|
+
},
|
|
154
|
+
onConnect(handler) {
|
|
155
|
+
connectHandler = handler;
|
|
156
|
+
},
|
|
157
|
+
start() {
|
|
158
|
+
transportStartCount++;
|
|
159
|
+
},
|
|
160
|
+
stop() {
|
|
161
|
+
transportStopCount++;
|
|
162
|
+
},
|
|
163
|
+
};
|
|
164
|
+
const delegatedExtensionEvents = options.adapters.extensionEvents ?? createEventBus();
|
|
165
|
+
const extensionEvents: NonNullable<WorkerRuntimeAdapters["extensionEvents"]> = {
|
|
166
|
+
emit(event, payload) {
|
|
167
|
+
observations.push({ kind: "extension", event });
|
|
168
|
+
delegatedExtensionEvents.emit(event, payload);
|
|
169
|
+
},
|
|
170
|
+
on(event, handler) {
|
|
171
|
+
delegatedExtensionEvents.on(event, handler);
|
|
172
|
+
},
|
|
173
|
+
off(event, handler) {
|
|
174
|
+
delegatedExtensionEvents.off(event, handler);
|
|
175
|
+
},
|
|
176
|
+
};
|
|
177
|
+
const runtime = createWorkerRuntime({
|
|
178
|
+
config: {
|
|
179
|
+
instanceId,
|
|
180
|
+
workerId,
|
|
181
|
+
heartbeatIntervalMs: options.config?.heartbeatIntervalMs,
|
|
182
|
+
turnMaxDurationMs: options.config?.turnMaxDurationMs,
|
|
183
|
+
turnInactivityTimeoutMs: options.config?.turnInactivityTimeoutMs,
|
|
184
|
+
turnAbortGracePeriodMs: options.config?.turnAbortGracePeriodMs,
|
|
185
|
+
},
|
|
186
|
+
adapters: {
|
|
187
|
+
transport,
|
|
188
|
+
scheduler,
|
|
189
|
+
resultImageTools: options.adapters.resultImageTools ?? { create: () => null },
|
|
190
|
+
piFactory: options.adapters.piFactory,
|
|
191
|
+
gitOps: options.adapters.gitOps,
|
|
192
|
+
resolveWorkerProcess: options.adapters.resolveWorkerProcess,
|
|
193
|
+
stderr: options.adapters.stderr,
|
|
194
|
+
extensionEvents,
|
|
195
|
+
sessionSnapshots:
|
|
196
|
+
options.adapters.sessionSnapshots ??
|
|
197
|
+
({
|
|
198
|
+
async uploadSnapshot() {
|
|
199
|
+
return { kind: "uploaded", bytes: 0 } as const;
|
|
200
|
+
},
|
|
201
|
+
} satisfies WorkerRuntimeAdapters["sessionSnapshots"]),
|
|
202
|
+
exit(code) {
|
|
203
|
+
exitCodes.push(code);
|
|
204
|
+
},
|
|
205
|
+
},
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
return {
|
|
209
|
+
scheduler,
|
|
210
|
+
outgoing,
|
|
211
|
+
observations,
|
|
212
|
+
exitCodes,
|
|
213
|
+
get transportStartCount() {
|
|
214
|
+
return transportStartCount;
|
|
215
|
+
},
|
|
216
|
+
get transportStopCount() {
|
|
217
|
+
return transportStopCount;
|
|
218
|
+
},
|
|
219
|
+
deliver,
|
|
220
|
+
async connect() {
|
|
221
|
+
await runtime.start();
|
|
222
|
+
},
|
|
223
|
+
async start(payload = options.startPayload) {
|
|
224
|
+
if (!payload) throw new Error("WorkerRuntimeHarness.start requires a start payload");
|
|
225
|
+
await this.connect();
|
|
226
|
+
deliver("worker.start", payload);
|
|
227
|
+
await this.flush();
|
|
228
|
+
},
|
|
229
|
+
async stop(reason: string) {
|
|
230
|
+
await runtime.stop(reason);
|
|
231
|
+
},
|
|
232
|
+
async acceptStart(acceptance: { startRecordId?: string; turnRecordId?: string } = {}) {
|
|
233
|
+
if (!latestStart) throw new Error("Cannot accept a turn before worker.start");
|
|
234
|
+
deliver("worker.turn_start_accepted", {
|
|
235
|
+
startRecordId: acceptance.startRecordId ?? latestStart.turnStart.id,
|
|
236
|
+
turnRecordId: acceptance.turnRecordId ?? latestStart.turnStart.proposedTurnRecordId,
|
|
237
|
+
});
|
|
238
|
+
await this.flush();
|
|
239
|
+
},
|
|
240
|
+
async startLlmTo<T extends WorkerMessageType>(
|
|
241
|
+
type: T,
|
|
242
|
+
payload = options.startPayload,
|
|
243
|
+
): Promise<WorkerMessageByType<T>> {
|
|
244
|
+
if (!payload) throw new Error("WorkerRuntimeHarness.startLlmTo requires a start payload");
|
|
245
|
+
if (payload.bootstrap.kind !== "llm") {
|
|
246
|
+
throw new Error("WorkerRuntimeHarness.startLlmTo requires an LLM start payload");
|
|
247
|
+
}
|
|
248
|
+
await this.start(payload);
|
|
249
|
+
await this.waitForMessage("worker.ready");
|
|
250
|
+
await this.acceptStart();
|
|
251
|
+
return this.waitForMessage(type);
|
|
252
|
+
},
|
|
253
|
+
reconnect() {
|
|
254
|
+
connectHandler?.();
|
|
255
|
+
},
|
|
256
|
+
failTransport(error: Error) {
|
|
257
|
+
errorHandler?.(error);
|
|
258
|
+
},
|
|
259
|
+
async waitForMessage<T extends WorkerMessageType>(
|
|
260
|
+
type: T,
|
|
261
|
+
count = 1,
|
|
262
|
+
): Promise<WorkerMessageByType<T>> {
|
|
263
|
+
const matches = messagesOfType(type);
|
|
264
|
+
if (matches.length >= count) return matches[count - 1] as (typeof matches)[number];
|
|
265
|
+
return new Promise<(typeof matches)[number]>((resolve) =>
|
|
266
|
+
waiters.add({
|
|
267
|
+
type,
|
|
268
|
+
count,
|
|
269
|
+
resolve: (message) => resolve(message as (typeof matches)[number]),
|
|
270
|
+
}),
|
|
271
|
+
);
|
|
272
|
+
},
|
|
273
|
+
async flush() {
|
|
274
|
+
for (let index = 0; index < 100; index++)
|
|
275
|
+
await new Promise<void>((resolve) => setImmediate(resolve));
|
|
276
|
+
},
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
export type WorkerRuntimeHarness = ReturnType<typeof createWorkerRuntimeHarness>;
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { VERSION as PI_VERSION } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import type { ResolvedTurnStart } from "@leitwerk-dev/domain";
|
|
4
|
+
import {
|
|
5
|
+
createCanonicalPiResourceBundle,
|
|
6
|
+
createTestConfigSnapshot,
|
|
7
|
+
type InputDelivery,
|
|
8
|
+
type ProcessInstanceSnapshot,
|
|
9
|
+
type ProcessProjectSnapshot,
|
|
10
|
+
sha256Digest,
|
|
11
|
+
WORKER_API_VERSION,
|
|
12
|
+
type WorkerCredentialMaterial,
|
|
13
|
+
type WorkerStartPayload,
|
|
14
|
+
} from "@leitwerk-dev/worker-protocol";
|
|
15
|
+
|
|
16
|
+
type LlmStart = Extract<ResolvedTurnStart, { kind: "llm" }>;
|
|
17
|
+
type LlmModel = LlmStart["model"];
|
|
18
|
+
|
|
19
|
+
export interface TestLlmWorkerStartPayloadOptions {
|
|
20
|
+
root: string;
|
|
21
|
+
processSnapshot: ProcessInstanceSnapshot;
|
|
22
|
+
projectSnapshots?: ProcessProjectSnapshot[];
|
|
23
|
+
turnResultMarkdownBySemanticRef?: WorkerStartPayload["turnResultMarkdownBySemanticRef"];
|
|
24
|
+
turnResultMarkdownByProduct?: WorkerStartPayload["turnResultMarkdownByProduct"];
|
|
25
|
+
pendingInputs?: InputDelivery[];
|
|
26
|
+
workerLeaseId?: string;
|
|
27
|
+
startRecordId?: string;
|
|
28
|
+
turnRecordId?: string;
|
|
29
|
+
model?: LlmModel;
|
|
30
|
+
credential?: WorkerCredentialMaterial | null;
|
|
31
|
+
resume?: boolean;
|
|
32
|
+
now?: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Builds a valid public LLM worker.start payload with canonical Pi resources. */
|
|
36
|
+
export function createTestLlmWorkerStartPayload(
|
|
37
|
+
options: TestLlmWorkerStartPayloadOptions,
|
|
38
|
+
): WorkerStartPayload {
|
|
39
|
+
const instanceId = options.processSnapshot.id ?? "proc_test";
|
|
40
|
+
const model =
|
|
41
|
+
options.model ??
|
|
42
|
+
({
|
|
43
|
+
profileId: "test",
|
|
44
|
+
providerId: "openai",
|
|
45
|
+
modelId: "test-model",
|
|
46
|
+
thinkingLevel: "low",
|
|
47
|
+
} satisfies LlmModel);
|
|
48
|
+
const immutableFiles = [
|
|
49
|
+
{
|
|
50
|
+
path: "settings.json",
|
|
51
|
+
content: Buffer.from('{"defaultProjectTrust":"never","packages":[]}\n'),
|
|
52
|
+
},
|
|
53
|
+
{ path: "models.json", content: Buffer.from('{"providers":{}}\n') },
|
|
54
|
+
];
|
|
55
|
+
const generated = {
|
|
56
|
+
schemaVersion: 1,
|
|
57
|
+
model,
|
|
58
|
+
providerOptions: {},
|
|
59
|
+
providerWorkerConfig: null,
|
|
60
|
+
declaredCredentialPaths: ["auth.json"],
|
|
61
|
+
compatibility: { workerApiVersion: WORKER_API_VERSION, piVersion: PI_VERSION },
|
|
62
|
+
provenance: immutableFiles.map((file) => ({
|
|
63
|
+
kind: "generated" as const,
|
|
64
|
+
ownerExtensionId: null,
|
|
65
|
+
packageName: null,
|
|
66
|
+
snapshotPath: file.path,
|
|
67
|
+
sha256: sha256Digest(file.content),
|
|
68
|
+
size: file.content.byteLength,
|
|
69
|
+
})),
|
|
70
|
+
};
|
|
71
|
+
const bundle = createCanonicalPiResourceBundle([
|
|
72
|
+
...immutableFiles,
|
|
73
|
+
{ path: "generated.json", content: Buffer.from(`${JSON.stringify(generated)}\n`) },
|
|
74
|
+
]);
|
|
75
|
+
const configSnapshot = createTestConfigSnapshot();
|
|
76
|
+
configSnapshot.pi.agent_dir = path.join(options.root, "agent");
|
|
77
|
+
configSnapshot.pi.model_profiles = [
|
|
78
|
+
{
|
|
79
|
+
id: model.profileId,
|
|
80
|
+
provider: model.providerId,
|
|
81
|
+
model_id: model.modelId,
|
|
82
|
+
thinking_level: model.thinkingLevel,
|
|
83
|
+
},
|
|
84
|
+
];
|
|
85
|
+
const now = options.now ?? "2025-01-01T00:00:00.000Z";
|
|
86
|
+
return {
|
|
87
|
+
processSnapshot: options.processSnapshot,
|
|
88
|
+
projectSnapshots: options.projectSnapshots ?? [],
|
|
89
|
+
turnResultMarkdownBySemanticRef: options.turnResultMarkdownBySemanticRef,
|
|
90
|
+
turnResultMarkdownByProduct: options.turnResultMarkdownByProduct,
|
|
91
|
+
workerLeaseId: options.workerLeaseId ?? "lease_1",
|
|
92
|
+
turnStart: {
|
|
93
|
+
id: options.startRecordId ?? "start_1",
|
|
94
|
+
instanceId,
|
|
95
|
+
turnId: options.processSnapshot.selectedTurnId ?? "run",
|
|
96
|
+
turnType: "llm",
|
|
97
|
+
proposedTurnRecordId: options.turnRecordId ?? "trn_1",
|
|
98
|
+
startKind: "selected_turn",
|
|
99
|
+
recoveryTurnRecordId: null,
|
|
100
|
+
continuation: null,
|
|
101
|
+
state: {
|
|
102
|
+
kind: "starting",
|
|
103
|
+
start: {
|
|
104
|
+
kind: "llm",
|
|
105
|
+
model,
|
|
106
|
+
providerOptions: {},
|
|
107
|
+
providerWorkerConfig: null,
|
|
108
|
+
piResourceSnapshotDigest: bundle.digest,
|
|
109
|
+
workerRuntimeProfileId: "default",
|
|
110
|
+
piSettings: {},
|
|
111
|
+
},
|
|
112
|
+
},
|
|
113
|
+
createdAt: now,
|
|
114
|
+
updatedAt: now,
|
|
115
|
+
},
|
|
116
|
+
pendingInputs: options.pendingInputs ?? [],
|
|
117
|
+
bootstrap: {
|
|
118
|
+
kind: "llm",
|
|
119
|
+
resourceBundle: {
|
|
120
|
+
digest: bundle.digest,
|
|
121
|
+
archiveBase64: Buffer.from(bundle.bytes).toString("base64"),
|
|
122
|
+
},
|
|
123
|
+
credential:
|
|
124
|
+
options.credential === undefined
|
|
125
|
+
? { providerId: model.providerId, revision: 1, values: { apiKey: "test-secret" } }
|
|
126
|
+
: options.credential,
|
|
127
|
+
},
|
|
128
|
+
configSnapshot,
|
|
129
|
+
treePaths: {
|
|
130
|
+
primaryTreeFile: path.join(options.root, "tree", "primary.jsonl"),
|
|
131
|
+
workspaceRoot: path.join(options.root, "workspace"),
|
|
132
|
+
},
|
|
133
|
+
resume: options.resume ?? false,
|
|
134
|
+
};
|
|
135
|
+
}
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
|
|
4
|
+
interface RootPackageJson {
|
|
5
|
+
workspaces?: string[] | { packages?: string[] };
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
interface WorkspacePackageJson {
|
|
9
|
+
name?: string;
|
|
10
|
+
exports?: unknown;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
interface JsonRecord {
|
|
14
|
+
[key: string]: unknown;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface WorkspaceSourceAlias {
|
|
18
|
+
find: RegExp;
|
|
19
|
+
replacement: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function buildWorkspaceSourceAliases(
|
|
23
|
+
rootDir: string,
|
|
24
|
+
additionalPackageDirs: readonly string[] = [],
|
|
25
|
+
): WorkspaceSourceAlias[] {
|
|
26
|
+
const packageDirs = [
|
|
27
|
+
...new Set([...listWorkspacePackageDirs(rootDir), ...additionalPackageDirs]),
|
|
28
|
+
];
|
|
29
|
+
const aliases = packageDirs.flatMap((packageDir) => buildAliasesForPackage(packageDir));
|
|
30
|
+
|
|
31
|
+
return aliases.sort((left, right) => {
|
|
32
|
+
const lengthDelta = right.find.source.length - left.find.source.length;
|
|
33
|
+
if (lengthDelta !== 0) {
|
|
34
|
+
return lengthDelta;
|
|
35
|
+
}
|
|
36
|
+
return left.find.source.localeCompare(right.find.source);
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function buildAliasesForPackage(packageDir: string): WorkspaceSourceAlias[] {
|
|
41
|
+
const packageJson = readJson<WorkspacePackageJson>(path.join(packageDir, "package.json"));
|
|
42
|
+
if (!packageJson.name) {
|
|
43
|
+
return [];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
return listPackageExportTargets(packageJson.name, packageJson.exports).flatMap(
|
|
47
|
+
({ specifier, importTarget }) => {
|
|
48
|
+
const replacement = resolveSourceFile(packageDir, importTarget);
|
|
49
|
+
if (!replacement) {
|
|
50
|
+
return [];
|
|
51
|
+
}
|
|
52
|
+
return [{ find: createExactSpecifierPattern(specifier), replacement }];
|
|
53
|
+
},
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function listWorkspacePackageDirs(rootDir: string): string[] {
|
|
58
|
+
const rootPackageJson = readJson<RootPackageJson>(path.join(rootDir, "package.json"));
|
|
59
|
+
const workspacePatterns = Array.isArray(rootPackageJson.workspaces)
|
|
60
|
+
? rootPackageJson.workspaces
|
|
61
|
+
: (rootPackageJson.workspaces?.packages ?? []);
|
|
62
|
+
|
|
63
|
+
return workspacePatterns
|
|
64
|
+
.flatMap((pattern) => expandWorkspacePattern(rootDir, pattern))
|
|
65
|
+
.filter((packageDir, index, dirs) => dirs.indexOf(packageDir) === index)
|
|
66
|
+
.sort((left, right) => left.localeCompare(right));
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function expandWorkspacePattern(rootDir: string, pattern: string): string[] {
|
|
70
|
+
if (pattern.endsWith("/*")) {
|
|
71
|
+
const baseDir = path.join(rootDir, pattern.slice(0, -2));
|
|
72
|
+
if (!existsSync(baseDir)) {
|
|
73
|
+
return [];
|
|
74
|
+
}
|
|
75
|
+
return readdirSync(baseDir, { withFileTypes: true })
|
|
76
|
+
.filter((entry) => entry.isDirectory())
|
|
77
|
+
.map((entry) => path.join(baseDir, entry.name))
|
|
78
|
+
.filter((packageDir) => existsSync(path.join(packageDir, "package.json")));
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const packageDir = path.join(rootDir, pattern);
|
|
82
|
+
return existsSync(path.join(packageDir, "package.json")) ? [packageDir] : [];
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function listPackageExportTargets(
|
|
86
|
+
packageName: string,
|
|
87
|
+
exportsField: unknown,
|
|
88
|
+
): Array<{ specifier: string; importTarget: string }> {
|
|
89
|
+
if (!exportsField) {
|
|
90
|
+
return [];
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
if (isPackageSubpathExportMap(exportsField)) {
|
|
94
|
+
return Object.entries(exportsField).flatMap(([subpath, exportValue]) => {
|
|
95
|
+
const importTarget = resolveImportTarget(exportValue);
|
|
96
|
+
if (!importTarget) {
|
|
97
|
+
return [];
|
|
98
|
+
}
|
|
99
|
+
const specifier = subpath === "." ? packageName : `${packageName}/${subpath.slice(2)}`;
|
|
100
|
+
return [{ specifier, importTarget }];
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const importTarget = resolveImportTarget(exportsField);
|
|
105
|
+
return importTarget ? [{ specifier: packageName, importTarget }] : [];
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function isPackageSubpathExportMap(value: unknown): value is JsonRecord {
|
|
109
|
+
if (!isJsonRecord(value)) {
|
|
110
|
+
return false;
|
|
111
|
+
}
|
|
112
|
+
return Object.keys(value).some((key) => key === "." || key.startsWith("./"));
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function resolveImportTarget(exportValue: unknown): string | null {
|
|
116
|
+
if (typeof exportValue === "string") {
|
|
117
|
+
return exportValue;
|
|
118
|
+
}
|
|
119
|
+
if (!isJsonRecord(exportValue)) {
|
|
120
|
+
return null;
|
|
121
|
+
}
|
|
122
|
+
if (typeof exportValue.import === "string") {
|
|
123
|
+
return exportValue.import;
|
|
124
|
+
}
|
|
125
|
+
if (typeof exportValue.default === "string") {
|
|
126
|
+
return exportValue.default;
|
|
127
|
+
}
|
|
128
|
+
return null;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function resolveSourceFile(packageDir: string, importTarget: string): string | null {
|
|
132
|
+
const normalizedTarget = importTarget.startsWith("./") ? importTarget.slice(2) : importTarget;
|
|
133
|
+
for (const candidate of buildSourceCandidates(normalizedTarget)) {
|
|
134
|
+
const absoluteCandidate = path.join(packageDir, candidate);
|
|
135
|
+
if (existsSync(absoluteCandidate)) {
|
|
136
|
+
return absoluteCandidate;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return null;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function buildSourceCandidates(importTarget: string): string[] {
|
|
143
|
+
const srcTarget = importTarget.startsWith("dist/")
|
|
144
|
+
? `src/${importTarget.slice("dist/".length)}`
|
|
145
|
+
: importTarget;
|
|
146
|
+
const extensionlessTarget = srcTarget.replace(/\.(?:[cm]?js)$/, "");
|
|
147
|
+
|
|
148
|
+
return [
|
|
149
|
+
`${extensionlessTarget}.ts`,
|
|
150
|
+
`${extensionlessTarget}.tsx`,
|
|
151
|
+
`${extensionlessTarget}.mts`,
|
|
152
|
+
`${extensionlessTarget}.cts`,
|
|
153
|
+
srcTarget,
|
|
154
|
+
];
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function createExactSpecifierPattern(specifier: string): RegExp {
|
|
158
|
+
return new RegExp(`^${escapeRegExp(specifier)}$`);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function escapeRegExp(value: string): string {
|
|
162
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function isJsonRecord(value: unknown): value is JsonRecord {
|
|
166
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function readJson<T>(filePath: string): T {
|
|
170
|
+
return JSON.parse(readFileSync(filePath, "utf8")) as T;
|
|
171
|
+
}
|