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.
3// @effect-diagnostics-next-line nodeBuiltinImport:off -- FileSystem.realPath is Node's JS realpath; museWorkspaceRoot needs the native one.
4import * as NodeFSP from "node:fs/promises";
5
6import {
7 spawnMspConnection,
8 type Connection,
9 type ProcessExit,
10 type SpawnedMspConnection,
11} from "@muse-code/sdk";
12import type { RuntimeMode } from "@t3tools/contracts";
13import * as HostProcess from "@t3tools/shared/HostProcess";
14import { SpawnExecutableResolution } from "@t3tools/shared/shell";
15import * as Effect from "effect/Effect";
16
17export interface MuseSdkHost {
18 readonly connection: Pick<
19 Connection,
20 | "command"
21 | "request"
22 | "mintCommandId"
23 | "onNotification"
24 | "onServerRequest"
25 | "onProtocolError"
26 | "closed"
27 >;
28 readonly initializeResult: Pick<SpawnedMspConnection["initializeResult"], "grantedCapabilities"> &
29 Partial<Pick<SpawnedMspConnection["initializeResult"], "museHome">>;
30 readonly exited: Promise<ProcessExit>;
31 readonly stderrTail?: () => ReadonlyArray<string>;
32 readonly close: () => Promise<void>;
33}
34
35export interface MuseLaunch {
36 readonly command: string;
37 readonly args: ReadonlyArray<string>;
38}
39
40export interface MuseSdkHostOptions {
41 readonly binaryPath: string;
42 readonly launchArgs?: ReadonlyArray<string>;
43 readonly launch?: MuseLaunch;
44 readonly cwd?: string;
45 readonly environment?: NodeJS.ProcessEnv;
46 readonly runtimeMode?: RuntimeMode;
47 readonly readOnly?: boolean;
48 /** Read-only generation needs durable logging for turn/item notifications (verified through 1.1.1). */
49 readonly sessionLogging?: boolean;
50 readonly signal?: AbortSignal;
51 readonly startupTimeoutMs?: number;
52 readonly onProcessExit?: (exit: ProcessExit) => void;
53}
54
55export function makeMuseEnvironment(
56 environment: NodeJS.ProcessEnv = process.env,
57): NodeJS.ProcessEnv {
58 return {
59 ...Object.fromEntries(
60 Object.keys(environment)
61 .filter((key) => key.toUpperCase() !== "META_API_KEY")
62 .map((key) => [key, environment[key]]),
63 ),
64 MUSE_NO_AUTO_UPDATE: "1",
65 };
66}
67
68export function museVerbatimPath(path: string): string {
69 if (path.startsWith("\\\\?\\")) return path;
70 return path.startsWith("\\\\") ? `\\\\?\\UNC\\${path.slice(2)}` : `\\\\?\\${path}`;
71}
72
73/**
74 * On Windows Muse rejects anything but the verbatim canonical path, true case
75 * and long names included, so resolve with the native realpath, which unlike
76 * FileSystem.realPath fixes case and expands 8.3 names. Muse itself still
77 * starts in the plain path: the `muse.cmd` launcher runs under cmd.exe, which
78 * cannot use a verbatim directory.
79 */
80export const museWorkspaceRoot = Effect.fn("museWorkspaceRoot")(function* (path: string) {
81 if ((yield* HostProcess.Platform) !== "win32") return path;
82 const canonical = yield* Effect.tryPromise(() => NodeFSP.realpath(path)).pipe(
83 // A verbatim path takes `/` literally, so an unresolved root needs Windows separators.
84 Effect.orElseSucceed(() => path.replaceAll("/", "\\")),
85 );
86 return museVerbatimPath(canonical);
87});
88
89function windowsEnvironmentValue(environment: NodeJS.ProcessEnv, name: string) {
90 const key = Object.keys(environment).find(
91 (candidate) => candidate.toUpperCase() === name.toUpperCase(),
92 );
93 return key === undefined ? undefined : environment[key];
94}
95
96/**
97 * The SDK spawns without a shell, which finds the `muse` launcher on PATH
98 * everywhere but Windows. There Node neither looks a bare `muse` up with
99 * PATHEXT (ENOENT) nor runs a `.cmd` file such as Muse's own launcher (EINVAL)
100 * without a shell, so resolve the binary like any other command and run a
101 * `.cmd` or `.bat` under cmd.exe.
102 */
103export const museLaunch = Effect.fn("museLaunch")(function* (
104 binaryPath: string,
105 environment?: NodeJS.ProcessEnv,
106): Effect.fn.Return<MuseLaunch> {
107 if ((yield* HostProcess.Platform) !== "win32") return { command: binaryPath, args: [] };
108 const env = environment ?? (yield* HostProcess.Environment);
109 const resolveExecutable = yield* SpawnExecutableResolution;
110 const resolved = resolveExecutable(binaryPath, "win32", env) ?? binaryPath;
111 if (!/\.(?:cmd|bat)$/i.test(resolved)) return { command: resolved, args: [] };
112 const systemRoot = windowsEnvironmentValue(env, "SystemRoot");
113 return {
114 command:
115 windowsEnvironmentValue(env, "ComSpec") ??
116 (systemRoot ? `${systemRoot}\\System32\\cmd.exe` : "cmd.exe"),
117 // /d skips cmd's AutoRun commands, which could write into Muse's stdout. cmd /c drops
118 // the quotes from a command that starts with one and holds `&`, `@`, `^` or a
119 // parenthesis, so a quoted path follows a bare `@` (echo off), which keeps them.
120 args: [
121 "/d",
122 "/c",
123 ...(/\s/.test(resolved) ? ["@", resolved] : [resolved.replace(/[()&<>@^|]/g, "^$&")]),
124 ],
125 };
126});
127
128export function museApprovalMode(runtimeMode: RuntimeMode) {
129 return runtimeMode === "full-access" ? "allowAll" : "promptUnmatched";
130}
131
132/**
133 * The permission profile `session/start` and `session/resume` select. Without
134 * one Muse applies its own default, which can be `:auto-review`, where an AI
135 * reviewer decides eligible approvals instead of the user.
136 */
137export function musePermissionProfile(runtimeMode: RuntimeMode) {
138 return runtimeMode === "full-access" ? ":unrestricted" : ":ask-me";
139}
140
141export function museServeArgs(
142 options: Pick<MuseSdkHostOptions, "readOnly" | "sessionLogging" | "runtimeMode">,
143) {
144 const args = ["serve"];
145 if (options.readOnly) {
146 args.push("--disable-shell", "--disable-write");
147 if (options.sessionLogging !== true) args.push("--no-session-log");
148 } else {
149 args.push("--trust-workspace");
150 if (options.runtimeMode === "full-access") args.push("--disable-sandbox");
151 }
152 return args;
153}
154
155export function museInitializeParams(readOnly = false) {
156 return {
157 clientInfo: { name: "t3_code", title: "T3 Code", version: "1" },
158 capabilities: { requestedCapabilities: readOnly ? [] : ["sessionMcp"] },
159 };
160}
161
162/**
163 * The pre-handshake handle owns cleanup even when initialize never replies.
164 */
165export async function createMuseSdkHost(
166 options: MuseSdkHostOptions,
167 spawn: typeof spawnMspConnection = spawnMspConnection,
168): Promise<MuseSdkHost> {
169 options.signal?.throwIfAborted();
170 const launch = options.launch ?? { command: options.binaryPath, args: [] };
171 const handshake = spawn({
172 command: launch.command,
173 args: [...launch.args, ...(options.launchArgs ?? []), ...museServeArgs(options)],
174 ...(options.cwd ? { cwd: options.cwd } : {}),
175 env: options.environment ?? makeMuseEnvironment(),
176 shutdownTimeoutMs: 10_000,
177 ...(options.onProcessExit ? { onProcessExit: options.onProcessExit } : {}),
178 });
179 let closePromise: Promise<void> | undefined;
180 const close = () => {
181 options.signal?.removeEventListener("abort", onAbort);
182 return (closePromise ??= handshake.close().then(() => undefined));
183 };
184 let rejectStartup: (reason: unknown) => void = () => {};
185 const onAbort = () => {
186 rejectStartup(options.signal?.reason ?? new Error("Muse SDK startup aborted."));
187 void close().catch(() => {});
188 };
189 const interrupted = new Promise<never>((_resolve, reject) => {
190 rejectStartup = reject;
191 });
192 options.signal?.addEventListener("abort", onAbort, { once: true });
193 if (options.signal?.aborted) onAbort();
194 const timer = setTimeout(
195 () => rejectStartup(new Error("Muse SDK initialization timed out.")),
196 options.startupTimeoutMs ?? 20_000,
197 );
198 timer.unref();
199 try {
200 const host = await Promise.race([
201 handshake.initialize(museInitializeParams(options.readOnly)),
202 interrupted,
203 ]);
204 if (host.initializeResult.schema?.version !== 1) {
205 throw new Error("Muse SDK returned an unsupported protocol envelope version.");
206 }
207 // The SDK's fingerprint warning permits additive optional schema changes.
208 // Successful initialization, not fingerprint identity, determines readiness.
209 return {
210 connection: host.connection,
211 initializeResult: host.initializeResult,
212 exited: host.exited,
213 stderrTail: () => handshake.child.stderrTail,
214 close,
215 };
216 } catch (error) {
217 await close();
218 throw error;
219 } finally {
220 clearTimeout(timer);
221 }
222}
223
224/** Cancellation waits for native shutdown before callers release startup resources. */
225export const createMuseSdkHostEffect = Effect.fn("createMuseSdkHostEffect")(function* (
226 options: Omit<MuseSdkHostOptions, "signal">,
227 createHost: typeof createMuseSdkHost = createMuseSdkHost,
228) {
229 const launch = options.launch ?? (yield* museLaunch(options.binaryPath, options.environment));
230 let startup: Promise<MuseSdkHost> | undefined;
231 return yield* Effect.tryPromise((signal) => {
232 startup = createHost({ ...options, launch, signal });
233 return startup;
234 }).pipe(
235 Effect.onInterrupt(() =>
236 Effect.promise(async () => {
237 await startup?.then(
238 (host) => host.close(),
239 () => {},
240 );
241 }),
242 ),
243 );
244});