Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import {
3 ProviderReplayEntry,
4 ProviderInstanceId,
5 type ResolvedProviderInstanceEnvironment,
6 type ProviderReplayTranscript,
7 type ProviderReplayEntry as ProviderReplayEntryType,
8} from "@t3tools/contracts";
9import * as Cause from "effect/Cause";
10import * as Effect from "effect/Effect";
11import * as Layer from "effect/Layer";
12import * as Queue from "effect/Queue";
13import * as Schema from "effect/Schema";
14import * as Sink from "effect/Sink";
15import * as Stream from "effect/Stream";
16import { ChildProcess, ChildProcessSpawner } from "effect/process";
17
18import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
19import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
20import { ProviderAdapterDriverCreateError } from "@t3tools/provider-core/server/adapterDriver";
21import * as ProviderAdapterRegistry from "../ProviderAdapterRegistry.ts";
22import type { OrchestratorV2ProviderReplayHarness } from "../testkit/ProviderReplayHarness.ts";
23import { PI_PROVIDER, PiAdapterV2Driver } from "@t3tools/provider-pi/server";
24
25export const PI_RPC_REPLAY_PROTOCOL = "pi.rpc-jsonl";
26export const PI_REPLAY_ANY = "<any>";
27
28const PiRpcReplayTranscript = Schema.Struct({
29 provider: Schema.Literal(PI_PROVIDER),
30 protocol: Schema.Literal(PI_RPC_REPLAY_PROTOCOL),
31 version: Schema.String,
32 scenario: Schema.String,
33 metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
34 entries: Schema.Array(ProviderReplayEntry),
35});
36type PiRpcReplayTranscript = typeof PiRpcReplayTranscript.Type;
37const decodePiRpcReplayTranscript = Schema.decodeUnknownEffect(PiRpcReplayTranscript);
38
39class PiReplayTranscriptDecodeError extends Schema.TaggedError<PiReplayTranscriptDecodeError>()(
40 "PiReplayTranscriptDecodeError",
41 {
42 driver: Schema.optional(Schema.String),
43 protocol: Schema.optional(Schema.String),
44 scenario: Schema.optional(Schema.String),
45 cause: Schema.Defect(),
46 },
47) {
48 override get message(): string {
49 return `Failed to decode Pi RPC replay transcript for scenario ${this.scenario ?? "<unknown>"}.`;
50 }
51}
52
53class PiReplayMismatchError extends Schema.TaggedError<PiReplayMismatchError>()(
54 "PiReplayMismatchError",
55 {
56 scenario: Schema.String,
57 cursor: Schema.Number,
58 process: Schema.Number,
59 label: Schema.optional(Schema.String),
60 actualType: Schema.optional(Schema.String),
61 expected: Schema.Unknown,
62 actual: Schema.Unknown,
63 },
64) {
65 override get message(): string {
66 return `Pi replay frame mismatch at cursor ${this.cursor} (expected ${this.label ?? "<none>"}, received ${this.actualType ?? "<untyped>"} from process ${this.process}) in scenario ${this.scenario}.`;
67 }
68}
69
70class PiReplayIncompleteError extends Schema.TaggedError<PiReplayIncompleteError>()(
71 "PiReplayIncompleteError",
72 {
73 scenario: Schema.String,
74 cursor: Schema.Number,
75 remaining: Schema.Number,
76 nextLabel: Schema.optional(Schema.String),
77 },
78) {
79 override get message(): string {
80 return `Pi replay ended with ${this.remaining} unconsumed entries at cursor ${this.cursor} (next ${this.nextLabel ?? "<none>"}) in scenario ${this.scenario}.`;
81 }
82}
83
84function entryLabel(entry: ProviderReplayEntryType | undefined): string | undefined {
85 if (entry === undefined) return undefined;
86 return entry.type === "runtime_exit" ? "runtime_exit" : (entry.label ?? entry.type);
87}
88
89const PiOrchestratorReplayHarnessError = Schema.Union([
90 PiReplayTranscriptDecodeError,
91 ProviderAdapterDriverCreateError,
92]);
93type PiOrchestratorReplayHarnessError = typeof PiOrchestratorReplayHarnessError.Type;
94
95function isRecord(value: unknown): value is Record<string, unknown> {
96 return typeof value === "object" && value !== null && !Array.isArray(value);
97}
98
99function replayValueMatches(expected: unknown, actual: unknown): boolean {
100 if (expected === PI_REPLAY_ANY) return true;
101 if (Array.isArray(expected)) {
102 return (
103 Array.isArray(actual) &&
104 expected.length === actual.length &&
105 expected.every((entry, index) => replayValueMatches(entry, actual[index]))
106 );
107 }
108 if (isRecord(expected)) {
109 if (!isRecord(actual)) return false;
110 const keys = new Set([...Object.keys(expected), ...Object.keys(actual)]);
111 return [...keys].every((key) => replayValueMatches(expected[key], actual[key]));
112 }
113 return Object.is(expected, actual);
114}
115
116const ADAPTER_REQUEST_ID = /^t3-\d+$/u;
117
118function adapterRequestId(frame: unknown): string | undefined {
119 const id = isRecord(frame) ? frame.id : undefined;
120 return typeof id === "string" && ADAPTER_REQUEST_ID.test(id) ? id : undefined;
121}
122
123/** Rebind adapter request ids without pinning counters; provider ids that responses must echo stay exact. */
124function withRequestId(expected: unknown, actual: unknown): unknown {
125 const actualId = adapterRequestId(actual);
126 return isRecord(expected) && adapterRequestId(expected) !== undefined && actualId !== undefined
127 ? { ...expected, id: actualId }
128 : expected;
129}
130
131function startsTurn(entry: ProviderReplayEntryType): boolean {
132 if (entry.type !== "expect_outbound") return false;
133 const type = isRecord(entry.frame) ? entry.frame.type : undefined;
134 return type === "prompt" || type === "compact" || type === "process_start";
135}
136
137function processStartFrame(command: ChildProcess.Command) {
138 const args = ChildProcess.isStandardCommand(command) ? command.args : [];
139 return { type: "process_start", args: [...args] };
140}
141
142function entryProcess(entry: ProviderReplayEntryType): number {
143 const label = entry.type === "runtime_exit" ? undefined : entry.label;
144 const match = label === undefined ? null : /@p(\d+)$/u.exec(label);
145 return match === null ? 1 : Number(match[1]);
146}
147
148function recordLabel(frame: unknown, process: number): string | undefined {
149 const base = !isRecord(frame)
150 ? undefined
151 : frame.type === "response" && typeof frame.command === "string"
152 ? `response:${frame.command}`
153 : typeof frame.type === "string"
154 ? frame.type
155 : undefined;
156 if (base === undefined || process === 1) return base;
157 return `${base}@p${process}`;
158}
159
160const decodeJsonLine = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
161const encodeJsonLine = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
162
163function makeLineSplitter() {
164 let buffer = "";
165 const decoder = new TextDecoder();
166 return (chunk: Uint8Array): ReadonlyArray<string> => {
167 buffer += decoder.decode(chunk, { stream: true });
168 const lines = buffer.split("\n");
169 buffer = lines.pop() ?? "";
170 return lines.map((line) => line.replace(/\r$/u, "")).filter((line) => line.length > 0);
171 };
172}
173
174interface PiReplayProcess {
175 readonly ordinal: number;
176 readonly stdout: Queue.Queue<Uint8Array, Cause.Done>;
177 readonly ids: Map<string, string>;
178 open: boolean;
179}
180
181/** Adapter fibers can reorder stdin writes; hold matches within the turn until reached, and fail unmatched writes. */
182class PiReplayController {
183 private cursor = 0;
184 private failure: unknown = null;
185 private readonly consumed = new Set<number>();
186 private readonly held: Array<{ readonly process: PiReplayProcess; readonly actual: unknown }> =
187 [];
188 private readonly processes: Array<PiReplayProcess> = [];
189 private readonly transcript: PiRpcReplayTranscript;
190
191 constructor(transcript: PiRpcReplayTranscript) {
192 this.transcript = transcript;
193 }
194
195 spawn(
196 command: ChildProcess.Command,
197 stdout: Queue.Queue<Uint8Array, Cause.Done>,
198 ): PiReplayProcess {
199 const process: PiReplayProcess = {
200 ordinal: this.processes.length + 1,
201 stdout,
202 ids: new Map(),
203 open: true,
204 };
205 this.processes.push(process);
206 this.receive(process, processStartFrame(command));
207 return process;
208 }
209
210 receive(process: PiReplayProcess, actual: unknown): void {
211 if (this.failure !== null) return;
212 const entries = this.transcript.entries;
213 let possible = false;
214 for (let index = this.cursor; index < entries.length && !possible; index += 1) {
215 const entry = entries[index]!;
216 const pending = entry.type === "expect_outbound" && !this.consumed.has(index);
217 possible =
218 pending &&
219 entryProcess(entry) === process.ordinal &&
220 replayValueMatches(withRequestId(entry.frame, actual), actual);
221 if (!possible && pending && startsTurn(entry)) break;
222 }
223 if (!possible) {
224 const expected = entries[this.cursor];
225 const label = entryLabel(expected);
226 const actualType = isRecord(actual) ? actual.type : undefined;
227 this.fail(
228 new PiReplayMismatchError({
229 scenario: this.transcript.scenario,
230 cursor: this.cursor,
231 process: process.ordinal,
232 ...(label === undefined ? {} : { label }),
233 ...(typeof actualType === "string" ? { actualType } : {}),
234 expected: expected ?? null,
235 actual,
236 }),
237 );
238 return;
239 }
240 this.held.push({ process, actual });
241 this.advance();
242 }
243
244 close(process: PiReplayProcess): void {
245 process.open = false;
246 Queue.endUnsafe(process.stdout);
247 }
248
249 assertComplete(): void {
250 if (this.failure !== null) throw this.failure;
251 if (this.cursor !== this.transcript.entries.length || this.held.length > 0) {
252 const nextLabel = entryLabel(this.transcript.entries[this.cursor]);
253 throw new PiReplayIncompleteError({
254 scenario: this.transcript.scenario,
255 cursor: this.cursor,
256 remaining: this.transcript.entries.length - this.cursor,
257 ...(nextLabel === undefined ? {} : { nextLabel }),
258 });
259 }
260 }
261
262 private advance(): void {
263 let progressed = true;
264 while (progressed && this.failure === null) {
265 progressed = this.drainInbound();
266 for (const [heldIndex, write] of this.held.entries()) {
267 if (this.consumePending(write.process, write.actual)) {
268 this.held.splice(heldIndex, 1);
269 progressed = true;
270 break;
271 }
272 }
273 }
274 }
275
276 private consumePending(process: PiReplayProcess, actual: unknown): boolean {
277 const entries = this.transcript.entries;
278 for (let index = this.cursor; index < entries.length; index += 1) {
279 const entry = entries[index]!;
280 if (entry.type !== "expect_outbound") return false;
281 if (this.consumed.has(index) || entryProcess(entry) !== process.ordinal) continue;
282 if (!replayValueMatches(withRequestId(entry.frame, actual), actual)) continue;
283 const recordedId = adapterRequestId(entry.frame);
284 const actualId = adapterRequestId(actual);
285 if (recordedId !== undefined && actualId !== undefined) {
286 process.ids.set(recordedId, actualId);
287 }
288 this.consumed.add(index);
289 while (this.consumed.has(this.cursor)) this.cursor += 1;
290 return true;
291 }
292 return false;
293 }
294
295 private drainInbound(): boolean {
296 let emitted = false;
297 while (this.failure === null) {
298 const entry = this.transcript.entries[this.cursor];
299 if (entry?.type === "runtime_exit") {
300 this.cursor += 1;
301 emitted = true;
302 const process = this.processes.at(-1);
303 if (process !== undefined) this.close(process);
304 continue;
305 }
306 if (entry?.type !== "emit_inbound") return emitted;
307 const process = this.processes[entryProcess(entry) - 1];
308 if (process === undefined) return emitted;
309 this.cursor += 1;
310 emitted = true;
311 if (!process.open) continue;
312 const frame = entry.frame;
313 const recordedId = isRecord(frame) ? frame.id : undefined;
314 const reboundId = typeof recordedId === "string" ? process.ids.get(recordedId) : undefined;
315 const rebound =
316 isRecord(frame) && reboundId !== undefined ? { ...frame, id: reboundId } : frame;
317 Queue.offerUnsafe(process.stdout, new TextEncoder().encode(`${encodeJsonLine(rebound)}\n`));
318 }
319 return emitted;
320 }
321
322 private fail(cause: unknown): void {
323 if (this.failure !== null) return;
324 this.failure = cause;
325 for (const process of this.processes) Queue.endUnsafe(process.stdout);
326 }
327}
328
329/** Deliberately outside the valid pid range so PiRpc's group kill never lands. */
330const REPLAY_PID = 999_999_999;
331
332function makePiReplaySpawner(
333 controller: PiReplayController,
334): ChildProcessSpawner.ChildProcessSpawner["Service"] {
335 return ChildProcessSpawner.make((command) =>
336 Effect.gen(function* () {
337 const process = controller.spawn(command, yield* Queue.unbounded<Uint8Array, Cause.Done>());
338 yield* Effect.addFinalizer(() => Effect.sync(() => controller.close(process)));
339 const split = makeLineSplitter();
340 return ChildProcessSpawner.makeHandle({
341 pid: ChildProcessSpawner.ProcessId(REPLAY_PID),
342 exitCode: Effect.never,
343 isRunning: Effect.succeed(true),
344 kill: () => Effect.void,
345 unref: Effect.succeed(Effect.void),
346 stdin: Sink.forEach((chunk: Uint8Array) =>
347 Effect.sync(() => {
348 for (const line of split(chunk)) controller.receive(process, decodeJsonLine(line));
349 }),
350 ),
351 stdout: Stream.fromQueue(process.stdout),
352 stderr: Stream.empty,
353 all: Stream.empty,
354 getInputFd: () => Sink.drain,
355 getOutputFd: () => Stream.empty,
356 });
357 }),
358 );
359}
360
361export function layer<E, R>(input: {
362 readonly scenario: string;
363 readonly spawner: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner, E, R>;
364 readonly binaryPath: string;
365 readonly launchArgs: string;
366 readonly environment?: ResolvedProviderInstanceEnvironment;
367}) {
368 return ProviderAdapterRegistry.layerFromAdaptersEffect(
369 PiAdapterV2Driver.create({
370 instanceId: ProviderInstanceId.make(PI_PROVIDER),
371 environment: input.environment ?? [],
372 displayName: undefined,
373 enabled: true,
374 config: {
375 ...PiAdapterV2Driver.defaultConfig(),
376 binaryPath: input.binaryPath,
377 launchArgs: input.launchArgs,
378 },
379 }).pipe(Effect.map((adapter) => [adapter])),
380 ).pipe(
381 Layer.provide(input.spawner),
382 Layer.provide(
383 Layer.mergeAll(
384 TestProviderHost.layer().pipe(Layer.provide(NodeServices.layer)),
385 NodeServices.layer,
386 IdAllocator.layer,
387 ),
388 ),
389 );
390}
391
392function metadataString(transcript: PiRpcReplayTranscript, key: string): string {
393 const value = transcript.metadata?.[key];
394 return typeof value === "string" ? value : "";
395}
396
397export const PiOrchestratorReplayHarness: OrchestratorV2ProviderReplayHarness<
398 PiRpcReplayTranscript,
399 PiOrchestratorReplayHarnessError
400> = {
401 driver: PI_PROVIDER,
402 decodeTranscript: (transcript: ProviderReplayTranscript) =>
403 decodePiRpcReplayTranscript(transcript).pipe(
404 Effect.mapError(
405 (cause) =>
406 new PiReplayTranscriptDecodeError({
407 driver: transcript.provider,
408 protocol: transcript.protocol,
409 scenario: transcript.scenario,
410 cause,
411 }),
412 ),
413 ),
414 makeProviderAdapterRegistryLayer: (transcript) =>
415 layer({
416 scenario: transcript.scenario,
417 binaryPath: "pi",
418 launchArgs: metadataString(transcript, "launchArgs"),
419 spawner: Layer.effect(
420 ChildProcessSpawner.ChildProcessSpawner,
421 Effect.gen(function* () {
422 const controller = new PiReplayController(transcript);
423 yield* Effect.addFinalizer(() => Effect.sync(() => controller.assertComplete()));
424 return makePiReplaySpawner(controller);
425 }),
426 ),
427 }),
428};
429
430export function makePiRecordingSpawner(
431 live: ChildProcessSpawner.ChildProcessSpawner["Service"],
432 entries: Array<ProviderReplayEntryType>,
433): ChildProcessSpawner.ChildProcessSpawner["Service"] {
434 let spawned = 0;
435 return ChildProcessSpawner.make((command) =>
436 Effect.gen(function* () {
437 const handle = yield* live.spawn(command);
438 const process = ++spawned;
439 const record = (type: "expect_outbound" | "emit_inbound", frame: unknown) => {
440 const label = recordLabel(frame, process);
441 entries.push({ type, ...(label === undefined ? {} : { label }), frame });
442 };
443 const recordLines = (
444 type: "expect_outbound" | "emit_inbound",
445 lines: ReadonlyArray<string>,
446 ) => {
447 for (const line of lines) {
448 try {
449 record(type, decodeJsonLine(line));
450 } catch {
451 // PiRpc drops non-JSON stdout lines, so the transcript does too.
452 }
453 }
454 };
455 record("expect_outbound", processStartFrame(command));
456 const splitIn = makeLineSplitter();
457 const splitOut = makeLineSplitter();
458 return ChildProcessSpawner.makeHandle({
459 ...handle,
460 stdin: handle.stdin.pipe(
461 Sink.mapInput((chunk: Uint8Array) => {
462 recordLines("expect_outbound", splitIn(chunk));
463 return chunk;
464 }),
465 ),
466 stdout: handle.stdout.pipe(
467 Stream.tap((chunk) => Effect.sync(() => recordLines("emit_inbound", splitOut(chunk)))),
468 ),
469 });
470 }),
471 );
472}