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; museCanonicalPath 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 session logging for turn/item notifications. */
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// Native realpath corrects filesystem case as well as resolving symlinks.
74export const museCanonicalPath = Effect.fn("museCanonicalPath")(function* (path: string) {
75 return yield* Effect.tryPromise(() => NodeFSP.realpath(path)).pipe(
76 Effect.orElseSucceed(() => path),
77 );
78});
79
80// Windows turn roots need verbatim form; launch cmd.exe with the plain canonical path.
81export const museWorkspaceRoot = Effect.fn("museWorkspaceRoot")(function* (path: string) {
82 if ((yield* HostProcess.Platform) !== "win32") return yield* museCanonicalPath(path);
83 const canonical = yield* Effect.tryPromise(() => NodeFSP.realpath(path)).pipe(
84 // A verbatim path takes `/` literally, so an unresolved root needs Windows separators.
85 Effect.orElseSucceed(() => path.replaceAll("/", "\\")),
86 );
87 return museVerbatimPath(canonical);
88});
89
90function windowsEnvironmentValue(environment: NodeJS.ProcessEnv, name: string) {
91 const key = Object.keys(environment).find(
92 (candidate) => candidate.toUpperCase() === name.toUpperCase(),
93 );
94 return key === undefined ? undefined : environment[key];
95}
96
97/** Resolve Windows launchers with PATHEXT and run .cmd/.bat under cmd.exe; SDK spawn has no shell. */
98export const museLaunch = Effect.fn("museLaunch")(function* (
99 binaryPath: string,
100 environment?: NodeJS.ProcessEnv,
101): Effect.fn.Return<MuseLaunch> {
102 if ((yield* HostProcess.Platform) !== "win32") return { command: binaryPath, args: [] };
103 const env = environment ?? (yield* HostProcess.Environment);
104 const resolveExecutable = yield* SpawnExecutableResolution;
105 const resolved = resolveExecutable(binaryPath, "win32", env) ?? binaryPath;
106 if (!/\.(?:cmd|bat)$/i.test(resolved)) return { command: resolved, args: [] };
107 const systemRoot = windowsEnvironmentValue(env, "SystemRoot");
108 return {
109 command:
110 windowsEnvironmentValue(env, "ComSpec") ??
111 (systemRoot ? `${systemRoot}\\System32\\cmd.exe` : "cmd.exe"),
112 // /d prevents AutoRun stdout; bare @ preserves quoted paths that cmd /c would unquote.
113 args: [
114 "/d",
115 "/c",
116 ...(/\s/.test(resolved) ? ["@", resolved] : [resolved.replace(/[()&<>@^|]/g, "^$&")]),
117 ],
118 };
119});
120
121export function museApprovalMode(runtimeMode: RuntimeMode) {
122 return runtimeMode === "full-access" ? "allowAll" : "promptUnmatched";
123}
124
125// Select explicitly; Muse defaults may let an AI reviewer decide approvals.
126export function musePermissionProfile(runtimeMode: RuntimeMode) {
127 return runtimeMode === "full-access" ? ":unrestricted" : ":ask-me";
128}
129
130export function museServeArgs(
131 options: Pick<MuseSdkHostOptions, "readOnly" | "sessionLogging" | "runtimeMode">,
132) {
133 const args = ["serve"];
134 if (options.readOnly) {
135 args.push("--disable-shell", "--disable-write");
136 if (options.sessionLogging !== true) args.push("--no-session-log");
137 } else {
138 args.push("--trust-workspace");
139 if (options.runtimeMode === "full-access") args.push("--disable-sandbox");
140 }
141 return args;
142}
143
144export function museInitializeParams(readOnly = false) {
145 return {
146 clientInfo: { name: "t3_code", title: "T3 Code", version: "1" },
147 capabilities: { requestedCapabilities: readOnly ? [] : ["sessionMcp"] },
148 };
149}
150
151/** Owns cleanup before the handshake, even if initialize never replies. */
152export async function createMuseSdkHost(
153 options: MuseSdkHostOptions,
154 spawn: typeof spawnMspConnection = spawnMspConnection,
155): Promise<MuseSdkHost> {
156 options.signal?.throwIfAborted();
157 const launch = options.launch ?? { command: options.binaryPath, args: [] };
158 const handshake = spawn({
159 command: launch.command,
160 args: [...launch.args, ...(options.launchArgs ?? []), ...museServeArgs(options)],
161 ...(options.cwd ? { cwd: options.cwd } : {}),
162 env: options.environment ?? makeMuseEnvironment(),
163 shutdownTimeoutMs: 10_000,
164 ...(options.onProcessExit ? { onProcessExit: options.onProcessExit } : {}),
165 });
166 let closePromise: Promise<void> | undefined;
167 const close = () => {
168 options.signal?.removeEventListener("abort", onAbort);
169 return (closePromise ??= handshake.close().then(() => undefined));
170 };
171 let rejectStartup: (reason: unknown) => void = () => {};
172 const onAbort = () => {
173 rejectStartup(options.signal?.reason ?? new Error("Muse SDK startup aborted."));
174 void close().catch(() => {});
175 };
176 const interrupted = new Promise<never>((_resolve, reject) => {
177 rejectStartup = reject;
178 });
179 options.signal?.addEventListener("abort", onAbort, { once: true });
180 if (options.signal?.aborted) onAbort();
181 const timer = setTimeout(
182 () => rejectStartup(new Error("Muse SDK initialization timed out.")),
183 options.startupTimeoutMs ?? 20_000,
184 );
185 timer.unref();
186 try {
187 const host = await Promise.race([
188 handshake.initialize(museInitializeParams(options.readOnly)),
189 interrupted,
190 ]);
191 if (host.initializeResult.schema?.version !== 1) {
192 throw new Error("Muse SDK returned an unsupported protocol envelope version.");
193 }
194 // Fingerprint warnings permit additive schema changes; successful initialization proves readiness.
195 return {
196 connection: host.connection,
197 initializeResult: host.initializeResult,
198 exited: host.exited,
199 stderrTail: () => handshake.child.stderrTail,
200 close,
201 };
202 } catch (error) {
203 await close();
204 throw error;
205 } finally {
206 clearTimeout(timer);
207 }
208}
209
210/** Cancellation waits for native shutdown before callers release startup resources. */
211export const createMuseSdkHostEffect = Effect.fn("createMuseSdkHostEffect")(function* (
212 options: Omit<MuseSdkHostOptions, "signal">,
213 createHost: typeof createMuseSdkHost = createMuseSdkHost,
214) {
215 const launch = options.launch ?? (yield* museLaunch(options.binaryPath, options.environment));
216 let startup: Promise<MuseSdkHost> | undefined;
217 return yield* Effect.tryPromise((signal) => {
218 startup = createHost({ ...options, launch, signal });
219 return startup;
220 }).pipe(
221 Effect.onInterrupt(() =>
222 Effect.promise(async () => {
223 await startup?.then(
224 (host) => host.close(),
225 () => {},
226 );
227 }),
228 ),
229 );
230});