The best way to control Claude Code, Codex and more from any computer or phone

main
ts 259 lines 9.43 KB
Raw
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.
4 import * as NodeFSP from "node:fs/promises";
5
6 import {
7 spawnMspConnection,
8 type Connection,
9 type ProcessExit,
10 type SpawnedMspConnection,
11 } from "@muse-code/sdk";
12 import type { RuntimeMode } from "@t3tools/contracts";
13 import { envTrampoline, supportsEnvChdir } from "@t3tools/shared/envTrampoline";
14 import * as HostProcess from "@t3tools/shared/HostProcess";
15 import { SpawnExecutableResolution } from "@t3tools/shared/shell";
16 import * as Effect from "effect/Effect";
17 import * as Schema from "effect/Schema";
18
19 export class MuseSdkError extends Schema.TaggedError<MuseSdkError>()("MuseSdkError", {
20 operation: Schema.String,
21 cause: Schema.Defect(),
22 }) {
23 override get message(): string {
24 return `Muse SDK ${this.operation} failed.`;
25 }
26 }
27
28 export interface MuseSdkHost {
29 readonly connection: Pick<
30 Connection,
31 | "command"
32 | "request"
33 | "mintCommandId"
34 | "onNotification"
35 | "onServerRequest"
36 | "onProtocolError"
37 | "closed"
38 >;
39 readonly initializeResult: Pick<SpawnedMspConnection["initializeResult"], "grantedCapabilities"> &
40 Partial<Pick<SpawnedMspConnection["initializeResult"], "museHome">>;
41 readonly exited: Promise<ProcessExit>;
42 readonly stderrTail?: () => ReadonlyArray<string>;
43 readonly close: () => Promise<void>;
44 }
45
46 export interface MuseLaunch {
47 readonly command: string;
48 readonly args: ReadonlyArray<string>;
49 }
50
51 export interface MuseSdkHostOptions {
52 readonly binaryPath: string;
53 readonly launchArgs?: ReadonlyArray<string>;
54 readonly launch?: MuseLaunch;
55 readonly cwd?: string;
56 readonly environment?: NodeJS.ProcessEnv;
57 readonly runtimeMode?: RuntimeMode;
58 readonly readOnly?: boolean;
59 /** Read-only generation needs session logging for turn/item notifications. */
60 readonly sessionLogging?: boolean;
61 readonly signal?: AbortSignal;
62 readonly startupTimeoutMs?: number;
63 readonly onProcessExit?: (exit: ProcessExit) => void;
64 }
65
66 export function makeMuseEnvironment(
67 environment: NodeJS.ProcessEnv = process.env,
68 ): NodeJS.ProcessEnv {
69 return {
70 ...Object.fromEntries(
71 Object.keys(environment)
72 .filter((key) => key.toUpperCase() !== "META_API_KEY")
73 .map((key) => [key, environment[key]]),
74 ),
75 MUSE_NO_AUTO_UPDATE: "1",
76 };
77 }
78
79 export function museVerbatimPath(path: string): string {
80 if (path.startsWith("\\\\?\\")) return path;
81 return path.startsWith("\\\\") ? `\\\\?\\UNC\\${path.slice(2)}` : `\\\\?\\${path}`;
82 }
83
84 // Native realpath corrects filesystem case as well as resolving symlinks.
85 export const museCanonicalPath = Effect.fn("museCanonicalPath")(function* (path: string) {
86 return yield* Effect.tryPromise({
87 try: () => NodeFSP.realpath(path),
88 catch: (cause) => new MuseSdkError({ operation: "realpath", cause }),
89 }).pipe(Effect.orElseSucceed(() => path));
90 });
91
92 // Windows turn roots need verbatim form; launch cmd.exe with the plain canonical path.
93 export const museWorkspaceRoot = Effect.fn("museWorkspaceRoot")(function* (path: string) {
94 if ((yield* HostProcess.Platform) !== "win32") return yield* museCanonicalPath(path);
95 const canonical = yield* Effect.tryPromise({
96 try: () => NodeFSP.realpath(path),
97 catch: (cause) => new MuseSdkError({ operation: "realpath", cause }),
98 }).pipe(
99 // A verbatim path takes `/` literally, so an unresolved root needs Windows separators.
100 Effect.orElseSucceed(() => path.replaceAll("/", "\\")),
101 );
102 return museVerbatimPath(canonical);
103 });
104
105 function windowsEnvironmentValue(environment: NodeJS.ProcessEnv, name: string) {
106 const key = Object.keys(environment).find(
107 (candidate) => candidate.toUpperCase() === name.toUpperCase(),
108 );
109 return key === undefined ? undefined : environment[key];
110 }
111
112 /** Resolve Windows launchers with PATHEXT and run .cmd/.bat under cmd.exe; SDK spawn has no shell. */
113 export const museLaunch = Effect.fn("museLaunch")(function* (
114 binaryPath: string,
115 environment?: NodeJS.ProcessEnv,
116 ): Effect.fn.Return<MuseLaunch> {
117 if ((yield* HostProcess.Platform) !== "win32") return { command: binaryPath, args: [] };
118 const env = environment ?? (yield* HostProcess.Environment);
119 const resolveExecutable = yield* SpawnExecutableResolution;
120 const resolved = resolveExecutable(binaryPath, "win32", env) ?? binaryPath;
121 if (!/\.(?:cmd|bat)$/i.test(resolved)) return { command: resolved, args: [] };
122 const systemRoot = windowsEnvironmentValue(env, "SystemRoot");
123 return {
124 command:
125 windowsEnvironmentValue(env, "ComSpec") ??
126 (systemRoot ? `${systemRoot}\\System32\\cmd.exe` : "cmd.exe"),
127 // /d prevents AutoRun stdout; bare @ preserves quoted paths that cmd /c would unquote.
128 args: [
129 "/d",
130 "/c",
131 ...(/\s/.test(resolved) ? ["@", resolved] : [resolved.replace(/[()&<>@^|]/g, "^$&")]),
132 ],
133 };
134 });
135
136 export function museApprovalMode(runtimeMode: RuntimeMode) {
137 return runtimeMode === "full-access" ? "allowAll" : "promptUnmatched";
138 }
139
140 // Select explicitly; Muse defaults may let an AI reviewer decide approvals.
141 export function musePermissionProfile(runtimeMode: RuntimeMode) {
142 return runtimeMode === "full-access" ? ":unrestricted" : ":ask-me";
143 }
144
145 export function museServeArgs(
146 options: Pick<MuseSdkHostOptions, "readOnly" | "sessionLogging" | "runtimeMode">,
147 ) {
148 const args = ["serve"];
149 if (options.readOnly) {
150 args.push("--disable-shell", "--disable-write");
151 if (options.sessionLogging !== true) args.push("--no-session-log");
152 } else {
153 args.push("--trust-workspace");
154 if (options.runtimeMode === "full-access") args.push("--disable-sandbox");
155 }
156 return args;
157 }
158
159 export function museInitializeParams(readOnly = false) {
160 return {
161 clientInfo: { name: "t3_code", title: "T3 Code", version: "1" },
162 capabilities: { requestedCapabilities: readOnly ? [] : ["sessionMcp"] },
163 };
164 }
165
166 /** Owns cleanup before the handshake, even if initialize never replies. */
167 export async function createMuseSdkHost(
168 options: MuseSdkHostOptions,
169 spawn: typeof spawnMspConnection = spawnMspConnection,
170 ): Promise<MuseSdkHost> {
171 options.signal?.throwIfAborted();
172 const launch = options.launch ?? { command: options.binaryPath, args: [] };
173 const handshake = spawn({
174 command: launch.command,
175 args: [...launch.args, ...(options.launchArgs ?? []), ...museServeArgs(options)],
176 ...(options.cwd ? { cwd: options.cwd } : {}),
177 env: options.environment ?? makeMuseEnvironment(),
178 shutdownTimeoutMs: 10_000,
179 ...(options.onProcessExit ? { onProcessExit: options.onProcessExit } : {}),
180 });
181 let closePromise: Promise<void> | undefined;
182 const close = () => {
183 options.signal?.removeEventListener("abort", onAbort);
184 return (closePromise ??= handshake.close().then(() => undefined));
185 };
186 let rejectStartup: (reason: unknown) => void = () => {};
187 const onAbort = () => {
188 rejectStartup(options.signal?.reason ?? new Error("Muse SDK startup aborted."));
189 void close().catch(() => {});
190 };
191 const interrupted = new Promise<never>((_resolve, reject) => {
192 rejectStartup = reject;
193 });
194 options.signal?.addEventListener("abort", onAbort, { once: true });
195 if (options.signal?.aborted) onAbort();
196 const timer = setTimeout(
197 () => rejectStartup(new Error("Muse SDK initialization timed out.")),
198 options.startupTimeoutMs ?? 20_000,
199 );
200 timer.unref();
201 try {
202 const host = await Promise.race([
203 handshake.initialize(museInitializeParams(options.readOnly)),
204 interrupted,
205 ]);
206 if (host.initializeResult.schema?.version !== 1) {
207 throw new Error("Muse SDK returned an unsupported protocol envelope version.");
208 }
209 // Fingerprint warnings permit additive schema changes; successful initialization proves readiness.
210 return {
211 connection: host.connection,
212 initializeResult: host.initializeResult,
213 exited: host.exited,
214 stderrTail: () => handshake.child.stderrTail,
215 close,
216 };
217 } catch (error) {
218 await close();
219 throw error;
220 } finally {
221 clearTimeout(timer);
222 }
223 }
224
225 /** Cancellation waits for native shutdown before callers release startup resources. */
226 export const createMuseSdkHostEffect = Effect.fn("createMuseSdkHostEffect")(function* (
227 options: Omit<MuseSdkHostOptions, "signal">,
228 createHost: typeof createMuseSdkHost = createMuseSdkHost,
229 ) {
230 const native = options.launch ?? (yield* museLaunch(options.binaryPath, options.environment));
231 // The Muse SDK hands libuv the cwd and the PATH search, which freeze the server while a
232 // mount under either hangs; `env` does both in the child.
233 const throughEnv =
234 (yield* HostProcess.Platform) === "linux" && (yield* Effect.promise(supportsEnvChdir))
235 ? envTrampoline(native.command, native.args, options.cwd)
236 : undefined;
237 const { cwd: _enteredByEnv, ...withoutCwd } = options;
238 const hostOptions =
239 throughEnv === undefined
240 ? { ...options, launch: native }
241 : { ...withoutCwd, launch: throughEnv };
242 let startup: Promise<MuseSdkHost> | undefined;
243 return yield* Effect.tryPromise({
244 try: (signal) => {
245 startup = createHost({ ...hostOptions, signal });
246 return startup;
247 },
248 catch: (cause) => new MuseSdkError({ operation: "start", cause }),
249 }).pipe(
250 Effect.onInterrupt(() =>
251 Effect.promise(async () => {
252 await startup?.then(
253 (host) => host.close(),
254 () => {},
255 );
256 }),
257 ),
258 );
259 });