Open History to see the last commit
1/**
2 * Muse MSP replay: swaps the host factory `MuseAdapterV2` uses to launch
3 * `muse serve` for one that answers from a recorded transcript. The real
4 * adapter and the real `@muse-code/sdk` `Connection` run unchanged; only the
5 * stdio pipe underneath is replayed.
6 *
7 * Transcript entries are MSP JSON-RPC lines. `expect_outbound` is one line T3
8 * wrote to Muse's stdin and `emit_inbound` is one line Muse wrote to stdout.
9 * Every host begins with a synthetic `host_start` outbound record carrying its
10 * `muse serve` arguments; records of the Nth host (N > 1) carry an `@hN` label
11 * suffix. The SDK numbers its requests, so a recorded request id is rebound to
12 * the id the replaying connection sent. Command and session ids come from the
13 * SDK's minter, so replay mints the ids the recording minted, in order.
14 * `<any>` in an outbound frame matches any value.
15 */
16import * as NodeServices from "@effect/platform-node/NodeServices";
17import { Connection, type DuplexTransport } from "@muse-code/sdk";
18import {
19 ProviderDriverKind,
20 ProviderInstanceId,
21 ProviderReplayEntry,
22 type ProviderReplayEntry as ProviderReplayEntryType,
23 type ProviderReplayTranscript,
24} from "@t3tools/contracts";
25import { MuseSettings } from "@t3tools/provider-muse/settings";
26import * as Effect from "effect/Effect";
27import * as Layer from "effect/Layer";
28import * as Schema from "effect/Schema";
29
30import { layerTestProviderHost } from "@t3tools/provider-testing/host";
31import {
32 museInitializeParams,
33 museServeArgs,
34 type MuseSdkHost,
35 type MuseSdkHostOptions,
36} from "@t3tools/provider-muse/testing";
37import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
38import * as ProviderAdapterRegistry from "../ProviderAdapterRegistry.ts";
39import * as ProviderContinuationRequests from "@t3tools/provider-core/server/continuationRequests";
40import type { OrchestratorV2ProviderReplayHarness } from "../testkit/ProviderReplayHarness.ts";
41import { makeMuseAdapterV2 } from "@t3tools/provider-muse/server";
42
43export const MUSE_PROVIDER_KIND = "muse";
44export const MUSE_MSP_REPLAY_PROTOCOL = "muse.msp-jsonl";
45const MUSE_REPLAY_ANY = "<any>";
46
47const MuseReplayTranscript = Schema.Struct({
48 provider: Schema.Literal(MUSE_PROVIDER_KIND),
49 protocol: Schema.Literal(MUSE_MSP_REPLAY_PROTOCOL),
50 version: Schema.String,
51 scenario: Schema.String,
52 metadata: Schema.Struct({
53 /** Ids each host's SDK minted, in order: session ids, then one per command. */
54 commandIds: Schema.Array(Schema.Array(Schema.String)),
55 }),
56 entries: Schema.Array(ProviderReplayEntry),
57});
58type MuseReplayTranscript = typeof MuseReplayTranscript.Type;
59const decodeMuseReplayTranscript = Schema.decodeUnknownEffect(MuseReplayTranscript);
60
61class MuseReplayTranscriptDecodeError extends Schema.TaggedError<MuseReplayTranscriptDecodeError>()(
62 "MuseReplayTranscriptDecodeError",
63 { scenario: Schema.optional(Schema.String), cause: Schema.Defect() },
64) {
65 override get message(): string {
66 return `Failed to decode Muse MSP replay transcript for scenario ${this.scenario ?? "<unknown>"}.`;
67 }
68}
69
70class MuseReplayMismatchError extends Schema.TaggedError<MuseReplayMismatchError>()(
71 "MuseReplayMismatchError",
72 {
73 scenario: Schema.String,
74 cursor: Schema.Number,
75 host: Schema.Number,
76 expected: Schema.Unknown,
77 actual: Schema.Unknown,
78 },
79) {
80 override get message(): string {
81 return `Muse replay frame mismatch at cursor ${this.cursor} from host ${this.host} in scenario ${this.scenario}.`;
82 }
83}
84
85class MuseReplayIncompleteError extends Schema.TaggedError<MuseReplayIncompleteError>()(
86 "MuseReplayIncompleteError",
87 {
88 scenario: Schema.String,
89 cursor: Schema.Number,
90 remaining: Schema.Number,
91 nextLabel: Schema.optional(Schema.String),
92 },
93) {
94 override get message(): string {
95 return `Muse replay ended with ${this.remaining} unconsumed entries at cursor ${this.cursor} (next ${this.nextLabel ?? "<none>"}) in scenario ${this.scenario}.`;
96 }
97}
98
99function isRecord(value: unknown): value is Record<string, unknown> {
100 return typeof value === "object" && value !== null && !Array.isArray(value);
101}
102
103function replayValueMatches(expected: unknown, actual: unknown): boolean {
104 if (expected === MUSE_REPLAY_ANY) return true;
105 if (Array.isArray(expected)) {
106 return (
107 Array.isArray(actual) &&
108 expected.length === actual.length &&
109 expected.every((entry, index) => replayValueMatches(entry, actual[index]))
110 );
111 }
112 if (isRecord(expected)) {
113 if (!isRecord(actual)) return false;
114 const keys = new Set([...Object.keys(expected), ...Object.keys(actual)]);
115 return [...keys].every((key) => replayValueMatches(expected[key], actual[key]));
116 }
117 return Object.is(expected, actual);
118}
119
120/** A client request: the SDK's own numbered id plus a method. */
121function clientRequestId(frame: unknown): number | undefined {
122 return isRecord(frame) && typeof frame.method === "string" && typeof frame.id === "number"
123 ? frame.id
124 : undefined;
125}
126
127function withRequestId(expected: unknown, actual: unknown): unknown {
128 const actualId = clientRequestId(actual);
129 return isRecord(expected) && clientRequestId(expected) !== undefined && actualId !== undefined
130 ? { ...expected, id: actualId }
131 : expected;
132}
133
134/** A write may not match past one of these: it would be a turn early. */
135function startsTurn(entry: ProviderReplayEntryType): boolean {
136 if (entry.type !== "expect_outbound" || !isRecord(entry.frame)) return false;
137 const method = entry.frame.method ?? entry.frame.type;
138 return method === "turn/start" || method === "session/compact" || method === "host_start";
139}
140
141function entryHost(entry: ProviderReplayEntryType): number {
142 const label = entry.type === "runtime_exit" ? undefined : entry.label;
143 const match = label === undefined ? null : /@h(\d+)$/u.exec(label);
144 return match === null ? 1 : Number(match[1]);
145}
146
147function entryLabel(entry: ProviderReplayEntryType | undefined): string | undefined {
148 if (entry === undefined) return undefined;
149 return entry.type === "runtime_exit" ? "runtime_exit" : (entry.label ?? entry.type);
150}
151
152/** `turn/start`, `response:turn/start`, `request:approval/request`, or `reply:approval/request`. */
153export function museRecordLabel(
154 frame: unknown,
155 direction: "expect_outbound" | "emit_inbound",
156 requestMethods: ReadonlyMap<unknown, string>,
157 host: number,
158): string | undefined {
159 if (!isRecord(frame)) return undefined;
160 const method = typeof frame.method === "string" ? frame.method : undefined;
161 const base =
162 frame.type === "host_start"
163 ? "host_start"
164 : method !== undefined
165 ? direction === "emit_inbound" && "id" in frame
166 ? `request:${method}`
167 : method
168 : requestMethods.has(frame.id)
169 ? `${direction === "emit_inbound" ? "response" : "reply"}:${requestMethods.get(frame.id)}`
170 : undefined;
171 return base === undefined || host === 1 ? base : `${base}@h${host}`;
172}
173
174/** Async line source the SDK `Connection` reads, fed by the replay controller. */
175class LineQueue implements AsyncIterable<string> {
176 private readonly lines: Array<string> = [];
177 private waiting: ((result: IteratorResult<string>) => void) | undefined;
178 private ended = false;
179
180 push(line: string): void {
181 if (this.ended) return;
182 const waiting = this.waiting;
183 if (waiting) {
184 this.waiting = undefined;
185 waiting({ value: line, done: false });
186 } else this.lines.push(line);
187 }
188
189 end(): void {
190 this.ended = true;
191 this.waiting?.({ value: undefined, done: true });
192 this.waiting = undefined;
193 }
194
195 [Symbol.asyncIterator](): AsyncIterator<string> {
196 return {
197 next: () => {
198 const line = this.lines.shift();
199 if (line !== undefined) return Promise.resolve({ value: line, done: false });
200 if (this.ended) return Promise.resolve({ value: undefined, done: true });
201 return new Promise((resolve) => {
202 this.waiting = resolve;
203 });
204 },
205 };
206 }
207}
208
209interface MuseReplayHost {
210 readonly ordinal: number;
211 readonly incoming: LineQueue;
212 /** Recorded request id -> id the replaying connection sent in its place. */
213 readonly ids: Map<number, number>;
214 readonly minted: Array<string>;
215 readonly exited: Promise<{ readonly code: number | null; readonly signal: null }>;
216 readonly exit: () => void;
217 open: boolean;
218}
219
220/**
221 * Drives every Muse host of one scenario from a single ordered transcript.
222 * Outbound lines must match the recording; the inbound lines that follow them
223 * go to the host that produced them. A write that matches a later outbound
224 * record of the same turn is held until the transcript reaches it, because
225 * independent adapter fibers can reach stdin in a different order than
226 * recorded. A write that matches nothing before the next turn fails at once.
227 */
228class MuseReplayController {
229 private cursor = 0;
230 private failure: unknown = null;
231 private readonly consumed = new Set<number>();
232 private readonly held: Array<{ readonly host: MuseReplayHost; readonly actual: unknown }> = [];
233 private readonly hosts: Array<MuseReplayHost> = [];
234 private readonly transcript: MuseReplayTranscript;
235
236 constructor(transcript: MuseReplayTranscript) {
237 this.transcript = transcript;
238 }
239
240 spawn(args: ReadonlyArray<string>): MuseReplayHost {
241 let exit = () => {};
242 const exited = new Promise<{ readonly code: number | null; readonly signal: null }>(
243 (resolve) => {
244 exit = () => resolve({ code: 0, signal: null });
245 },
246 );
247 const host: MuseReplayHost = {
248 ordinal: this.hosts.length + 1,
249 incoming: new LineQueue(),
250 ids: new Map(),
251 minted: [...(this.transcript.metadata.commandIds[this.hosts.length] ?? [])],
252 exited,
253 exit,
254 open: true,
255 };
256 this.hosts.push(host);
257 this.receive(host, { type: "host_start", args: [...args] });
258 return host;
259 }
260
261 mint(host: MuseReplayHost): string {
262 const id = host.minted.shift();
263 if (id === undefined) {
264 throw new Error(`Muse replay host ${host.ordinal} minted more ids than were recorded.`);
265 }
266 return id;
267 }
268
269 receive(host: MuseReplayHost, actual: unknown): void {
270 if (this.failure !== null) return;
271 const entries = this.transcript.entries;
272 let possible = false;
273 for (let index = this.cursor; index < entries.length && !possible; index += 1) {
274 const entry = entries[index]!;
275 const pending = entry.type === "expect_outbound" && !this.consumed.has(index);
276 possible =
277 pending &&
278 entryHost(entry) === host.ordinal &&
279 replayValueMatches(withRequestId(entry.frame, actual), actual);
280 if (!possible && pending && startsTurn(entry)) break;
281 }
282 if (!possible) {
283 this.fail(
284 new MuseReplayMismatchError({
285 scenario: this.transcript.scenario,
286 cursor: this.cursor,
287 host: host.ordinal,
288 expected: entries[this.cursor] ?? null,
289 actual,
290 }),
291 );
292 return;
293 }
294 this.held.push({ host, actual });
295 this.advance();
296 }
297
298 close(host: MuseReplayHost): void {
299 host.open = false;
300 host.incoming.end();
301 host.exit();
302 }
303
304 assertComplete(): void {
305 if (this.failure !== null) throw this.failure;
306 if (this.cursor !== this.transcript.entries.length || this.held.length > 0) {
307 const nextLabel = entryLabel(this.transcript.entries[this.cursor]);
308 throw new MuseReplayIncompleteError({
309 scenario: this.transcript.scenario,
310 cursor: this.cursor,
311 remaining: this.transcript.entries.length - this.cursor,
312 ...(nextLabel === undefined ? {} : { nextLabel }),
313 });
314 }
315 }
316
317 private advance(): void {
318 let progressed = true;
319 while (progressed && this.failure === null) {
320 progressed = this.drainInbound();
321 for (const [heldIndex, write] of this.held.entries()) {
322 if (this.consumePending(write.host, write.actual)) {
323 this.held.splice(heldIndex, 1);
324 progressed = true;
325 break;
326 }
327 }
328 }
329 }
330
331 private consumePending(host: MuseReplayHost, actual: unknown): boolean {
332 const entries = this.transcript.entries;
333 for (let index = this.cursor; index < entries.length; index += 1) {
334 const entry = entries[index]!;
335 if (entry.type !== "expect_outbound") return false;
336 if (this.consumed.has(index) || entryHost(entry) !== host.ordinal) continue;
337 if (!replayValueMatches(withRequestId(entry.frame, actual), actual)) continue;
338 const recordedId = clientRequestId(entry.frame);
339 const actualId = clientRequestId(actual);
340 if (recordedId !== undefined && actualId !== undefined) host.ids.set(recordedId, actualId);
341 this.consumed.add(index);
342 while (this.consumed.has(this.cursor)) this.cursor += 1;
343 return true;
344 }
345 return false;
346 }
347
348 private drainInbound(): boolean {
349 let emitted = false;
350 while (this.failure === null) {
351 const entry = this.transcript.entries[this.cursor];
352 if (entry?.type === "runtime_exit") {
353 // Muse exited on its own in the recording: end the newest host.
354 this.cursor += 1;
355 emitted = true;
356 const host = this.hosts.at(-1);
357 if (host !== undefined) this.close(host);
358 continue;
359 }
360 if (entry?.type !== "emit_inbound") return emitted;
361 const host = this.hosts[entryHost(entry) - 1];
362 if (host === undefined) return emitted;
363 this.cursor += 1;
364 emitted = true;
365 // Output a host wrote after T3 released it was never observed.
366 if (!host.open) continue;
367 const frame = entry.frame;
368 // Responses carry the client's request id; server requests carry their own.
369 const reboundId =
370 isRecord(frame) && frame.method === undefined && typeof frame.id === "number"
371 ? host.ids.get(frame.id)
372 : undefined;
373 const rebound =
374 isRecord(frame) && reboundId !== undefined ? { ...frame, id: reboundId } : frame;
375 host.incoming.push(`${JSON.stringify(rebound)}\n`);
376 }
377 return emitted;
378 }
379
380 private fail(cause: unknown): void {
381 if (this.failure !== null) return;
382 this.failure = cause;
383 for (const host of this.hosts) host.incoming.end();
384 }
385}
386
387/**
388 * Builds a `MuseSdkHost` over any line transport, doing the same `initialize`
389 * handshake the SDK's spawn path does. Replay and recording both use it.
390 */
391export async function connectMuseTransport(input: {
392 readonly transport: DuplexTransport;
393 readonly readOnly: boolean | undefined;
394 readonly mintCommandId?: () => string;
395 readonly exited: MuseSdkHost["exited"];
396 readonly close: () => Promise<void>;
397}): Promise<MuseSdkHost> {
398 const connection = new Connection(
399 input.transport,
400 input.mintCommandId ? { mintCommandId: input.mintCommandId } : {},
401 );
402 const result = await connection.request("initialize", museInitializeParams(input.readOnly));
403 connection.notify("initialized");
404 const granted = result.grantedCapabilities;
405 return {
406 connection,
407 initializeResult: {
408 grantedCapabilities: Array.isArray(granted)
409 ? granted.filter((capability) => typeof capability === "string")
410 : [],
411 },
412 exited: input.exited,
413 close: input.close,
414 };
415}
416
417function makeReplayCreateHost(controller: MuseReplayController) {
418 return async (options: MuseSdkHostOptions): Promise<MuseSdkHost> => {
419 const host = controller.spawn(museServeArgs(options));
420 return connectMuseTransport({
421 transport: {
422 incoming: host.incoming,
423 write: async (line) => {
424 for (const part of line.split("\n")) {
425 if (part.trim()) controller.receive(host, JSON.parse(part));
426 }
427 },
428 close: () => controller.close(host),
429 },
430 readOnly: options.readOnly,
431 mintCommandId: () => controller.mint(host),
432 exited: host.exited,
433 close: async () => controller.close(host),
434 });
435 };
436}
437
438const DEFAULT_MUSE_SETTINGS = Schema.decodeUnknownSync(MuseSettings)({ enabled: true });
439
440/** Registry with the real Muse adapter on the given host factory. */
441export function layer(input: {
442 readonly scenario: string;
443 readonly createHost: NonNullable<Parameters<typeof makeMuseAdapterV2>[0]["createHost"]>;
444 /** Replay needs none; a live recording passes the host environment. */
445 readonly environment?: NodeJS.ProcessEnv;
446}) {
447 return ProviderAdapterRegistry.layerFromAdaptersEffect(
448 Effect.gen(function* () {
449 return [
450 yield* makeMuseAdapterV2({
451 instanceId: ProviderInstanceId.make(MUSE_PROVIDER_KIND),
452 settings: DEFAULT_MUSE_SETTINGS,
453 environment: input.environment ?? {},
454 createHost: input.createHost,
455 // Same queue the continuation worker drains when the fixture runs it.
456 continuationRequests: yield* ProviderContinuationRequests.ProviderContinuationRequests,
457 }),
458 ];
459 }),
460 ).pipe(
461 Layer.provide(
462 Layer.mergeAll(
463 layerTestProviderHost().pipe(Layer.provide(NodeServices.layer)),
464 NodeServices.layer,
465 IdAllocator.layer,
466 ),
467 ),
468 );
469}
470
471export const MuseOrchestratorReplayHarness: OrchestratorV2ProviderReplayHarness<
472 MuseReplayTranscript,
473 MuseReplayTranscriptDecodeError
474> = {
475 driver: ProviderDriverKind.make(MUSE_PROVIDER_KIND),
476 decodeTranscript: (transcript: ProviderReplayTranscript) =>
477 decodeMuseReplayTranscript(transcript).pipe(
478 Effect.mapError(
479 (cause) => new MuseReplayTranscriptDecodeError({ scenario: transcript.scenario, cause }),
480 ),
481 ),
482 makeProviderAdapterRegistryLayer: (transcript) =>
483 Layer.unwrap(
484 Effect.gen(function* () {
485 const controller = new MuseReplayController(transcript);
486 yield* Effect.addFinalizer(() => Effect.sync(() => controller.assertComplete()));
487 return layer({
488 scenario: transcript.scenario,
489 createHost: makeReplayCreateHost(controller),
490 });
491 }),
492 ),
493};