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