Open History to see the last commit
1// @effect-diagnostics globalTimers:off
2// The SDK owns process shutdown; native deadlines cover initialize before an Effect resource exists.
3import {
4 spawnMspConnection,
5 type Connection,
6 type ProcessExit,
7 type SpawnedMspConnection,
8} from "@muse-code/sdk";
9import type { RuntimeMode } from "@t3tools/contracts";
10import * as Effect from "effect/Effect";
11
12export interface MuseSdkHost {
13 readonly connection: Pick<
14 Connection,
15 | "command"
16 | "request"
17 | "mintCommandId"
18 | "onNotification"
19 | "onServerRequest"
20 | "onProtocolError"
21 | "closed"
22 >;
23 readonly initializeResult: Pick<SpawnedMspConnection["initializeResult"], "grantedCapabilities">;
24 readonly exited: Promise<ProcessExit>;
25 /** The last lines Muse wrote to stderr, for explaining an unexpected exit. */
26 readonly stderrTail?: () => ReadonlyArray<string>;
27 readonly close: () => Promise<void>;
28}
29
30export interface MuseSdkHostOptions {
31 readonly binaryPath: string;
32 /** Arguments before the serve arguments, for a launcher in front of the binary. */
33 readonly launchArgs?: ReadonlyArray<string>;
34 readonly cwd?: string;
35 readonly environment?: NodeJS.ProcessEnv;
36 readonly runtimeMode?: RuntimeMode;
37 /** Disables shell and filesystem writes and workspace trust. */
38 readonly readOnly?: boolean;
39 /** Read-only generation needs durable logging for turn/item notifications (verified through 1.1.1). */
40 readonly sessionLogging?: boolean;
41 readonly signal?: AbortSignal;
42 readonly startupTimeoutMs?: number;
43}
44
45/** Preserve the host's CLI login while excluding the API-key override before copying values. */
46export function makeMuseEnvironment(
47 environment: NodeJS.ProcessEnv = process.env,
48): NodeJS.ProcessEnv {
49 return {
50 ...Object.fromEntries(
51 Object.keys(environment)
52 .filter((key) => key.toUpperCase() !== "META_API_KEY")
53 .map((key) => [key, environment[key]]),
54 ),
55 MUSE_NO_AUTO_UPDATE: "1",
56 };
57}
58
59export function museApprovalMode(runtimeMode: RuntimeMode) {
60 return runtimeMode === "full-access" ? "allowAll" : "promptUnmatched";
61}
62
63/** The `muse serve` arguments for a host: read-only hosts get no shell, writes, or workspace trust. */
64export function museServeArgs(
65 options: Pick<MuseSdkHostOptions, "readOnly" | "sessionLogging" | "runtimeMode">,
66) {
67 const args = ["serve"];
68 if (options.readOnly) {
69 args.push("--disable-shell", "--disable-write");
70 if (options.sessionLogging !== true) args.push("--no-session-log");
71 } else {
72 args.push("--trust-workspace");
73 if (options.runtimeMode === "full-access") args.push("--disable-sandbox");
74 }
75 return args;
76}
77
78/** What T3 sends in MSP `initialize`; only full hosts ask for session MCP servers. */
79export function museInitializeParams(readOnly = false) {
80 return {
81 clientInfo: { name: "t3_code", title: "T3 Code", version: "1" },
82 capabilities: { requestedCapabilities: readOnly ? [] : ["sessionMcp"] },
83 };
84}
85
86/** One SDK-owned process. The pre-handshake handle owns cleanup even when initialize never replies. */
87export async function createMuseSdkHost(
88 options: MuseSdkHostOptions,
89 spawn: typeof spawnMspConnection = spawnMspConnection,
90): Promise<MuseSdkHost> {
91 options.signal?.throwIfAborted();
92 const handshake = spawn({
93 command: options.binaryPath,
94 args: [...(options.launchArgs ?? []), ...museServeArgs(options)],
95 ...(options.cwd ? { cwd: options.cwd } : {}),
96 // Callers pass an environment already built with makeMuseEnvironment.
97 env: options.environment ?? makeMuseEnvironment(),
98 // A healthy host exits at once; this only bounds a hung one on close.
99 shutdownTimeoutMs: 10_000,
100 });
101 let closePromise: Promise<void> | undefined;
102 const close = () => {
103 options.signal?.removeEventListener("abort", onAbort);
104 return (closePromise ??= handshake.close().then(() => undefined));
105 };
106 let rejectStartup: (reason: unknown) => void = () => {};
107 const onAbort = () => {
108 rejectStartup(options.signal?.reason ?? new Error("Muse SDK startup aborted."));
109 void close().catch(() => {});
110 };
111 const interrupted = new Promise<never>((_resolve, reject) => {
112 rejectStartup = reject;
113 });
114 options.signal?.addEventListener("abort", onAbort, { once: true });
115 if (options.signal?.aborted) onAbort();
116 const timer = setTimeout(
117 () => rejectStartup(new Error("Muse SDK initialization timed out.")),
118 options.startupTimeoutMs ?? 20_000,
119 );
120 timer.unref();
121 try {
122 const host = await Promise.race([
123 handshake.initialize(museInitializeParams(options.readOnly)),
124 interrupted,
125 ]);
126 if (host.initializeResult.schema?.version !== 1) {
127 throw new Error("Muse SDK returned an unsupported protocol envelope version.");
128 }
129 // The SDK's fingerprint warning permits additive optional schema changes.
130 // Successful initialization, not fingerprint identity, determines readiness.
131 return {
132 connection: host.connection,
133 initializeResult: host.initializeResult,
134 exited: host.exited,
135 stderrTail: () => handshake.child.stderrTail,
136 close,
137 };
138 } catch (error) {
139 await close();
140 throw error;
141 } finally {
142 clearTimeout(timer);
143 }
144}
145
146/** Cancellation waits for native shutdown before callers release startup resources. */
147export const createMuseSdkHostEffect = Effect.fn("createMuseSdkHostEffect")(function* (
148 options: Omit<MuseSdkHostOptions, "signal">,
149 createHost: typeof createMuseSdkHost = createMuseSdkHost,
150) {
151 let startup: Promise<MuseSdkHost> | undefined;
152 return yield* Effect.tryPromise((signal) => {
153 startup = createHost({ ...options, signal });
154 return startup;
155 }).pipe(
156 Effect.onInterrupt(() =>
157 Effect.promise(async () => {
158 await startup?.then(
159 (host) => host.close(),
160 () => {},
161 );
162 }),
163 ),
164 );
165});