Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PiAdapterV2.testkit.ts

479 lines16.9 KB

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