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