Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

sdk.ts

260 lines9.5 KB

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 { envTrampoline, supportsEnvChdir } from "@t3tools/shared/envTrampoline";
14import * as HostProcess from "@t3tools/shared/HostProcess";
15import { SpawnExecutableResolution } from "@t3tools/shared/shell";
16import * as Effect from "effect/Effect";
17import * as Schema from "effect/Schema";
18​
19export 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 }
27​
28export 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>;
45​
46export interface MuseLaunch {
47 readonly command: string;
48 readonly args: ReadonlyArray<string>;
50​
51export 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;
65​
66export 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 };
78​
79export function museVerbatimPath(path: string): string {
80 if (path.startsWith("\\\\?\\")) return path;
81 return path.startsWith("\\\\") ? `\\\\?\\UNC\\${path.slice(2)}` : `\\\\?\\${path}`;
83​
84// Native realpath corrects filesystem case as well as resolving symlinks.
85export 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.
93export 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​
105function 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];
111​
112/** Resolve Windows launchers with PATHEXT and run .cmd/.bat under cmd.exe; SDK spawn has no shell. */
113export 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 =
121 (yield* Effect.promise(async () => resolveExecutable(binaryPath, "win32", env))) ?? binaryPath;
122 if (!/\.(?:cmd|bat)$/i.test(resolved)) return { command: resolved, args: [] };
123 const systemRoot = windowsEnvironmentValue(env, "SystemRoot");
124 return {
125 command:
126 windowsEnvironmentValue(env, "ComSpec") ??
127 (systemRoot ? `${systemRoot}\\System32\\cmd.exe` : "cmd.exe"),
128 // /d prevents AutoRun stdout; bare @ preserves quoted paths that cmd /c would unquote.
129 args: [
130 "/d",
131 "/c",
132 ...(/\s/.test(resolved) ? ["@", resolved] : [resolved.replace(/[()&<>@^|]/g, "^$&")]),
133 ],
134 };
135});
136​
137export function museApprovalMode(runtimeMode: RuntimeMode) {
138 return runtimeMode === "full-access" ? "allowAll" : "promptUnmatched";
140​
141// Select explicitly; Muse defaults may let an AI reviewer decide approvals.
142export function musePermissionProfile(runtimeMode: RuntimeMode) {
143 return runtimeMode === "full-access" ? ":unrestricted" : ":ask-me";
145​
146export function museServeArgs(
147 options: Pick<MuseSdkHostOptions, "readOnly" | "sessionLogging" | "runtimeMode">,
148) {
149 const args = ["serve"];
150 if (options.readOnly) {
151 args.push("--disable-shell", "--disable-write");
152 if (options.sessionLogging !== true) args.push("--no-session-log");
153 } else {
154 args.push("--trust-workspace");
155 if (options.runtimeMode === "full-access") args.push("--disable-sandbox");
156 }
157 return args;
159​
160export function museInitializeParams(readOnly = false) {
161 return {
162 clientInfo: { name: "t3_code", title: "T3 Code", version: "1" },
163 capabilities: { requestedCapabilities: readOnly ? [] : ["sessionMcp"] },
164 };
166​
167/** Owns cleanup before the handshake, even if initialize never replies. */
168export async function createMuseSdkHost(
169 options: MuseSdkHostOptions,
170 spawn: typeof spawnMspConnection = spawnMspConnection,
171): Promise<MuseSdkHost> {
172 options.signal?.throwIfAborted();
173 const launch = options.launch ?? { command: options.binaryPath, args: [] };
174 const handshake = spawn({
175 command: launch.command,
176 args: [...launch.args, ...(options.launchArgs ?? []), ...museServeArgs(options)],
177 ...(options.cwd ? { cwd: options.cwd } : {}),
178 env: options.environment ?? makeMuseEnvironment(),
179 shutdownTimeoutMs: 10_000,
180 ...(options.onProcessExit ? { onProcessExit: options.onProcessExit } : {}),
181 });
182 let closePromise: Promise<void> | undefined;
183 const close = () => {
184 options.signal?.removeEventListener("abort", onAbort);
185 return (closePromise ??= handshake.close().then(() => undefined));
186 };
187 let rejectStartup: (reason: unknown) => void = () => {};
188 const onAbort = () => {
189 rejectStartup(options.signal?.reason ?? new Error("Muse SDK startup aborted."));
190 void close().catch(() => {});
191 };
192 const interrupted = new Promise<never>((_resolve, reject) => {
193 rejectStartup = reject;
194 });
195 options.signal?.addEventListener("abort", onAbort, { once: true });
196 if (options.signal?.aborted) onAbort();
197 const timer = setTimeout(
198 () => rejectStartup(new Error("Muse SDK initialization timed out.")),
199 options.startupTimeoutMs ?? 20_000,
200 );
201 timer.unref();
202 try {
203 const host = await Promise.race([
204 handshake.initialize(museInitializeParams(options.readOnly)),
205 interrupted,
206 ]);
207 if (host.initializeResult.schema?.version !== 1) {
208 throw new Error("Muse SDK returned an unsupported protocol envelope version.");
209 }
210 // Fingerprint warnings permit additive schema changes; successful initialization proves readiness.
211 return {
212 connection: host.connection,
213 initializeResult: host.initializeResult,
214 exited: host.exited,
215 stderrTail: () => handshake.child.stderrTail,
216 close,
217 };
218 } catch (error) {
219 await close();
220 throw error;
221 } finally {
222 clearTimeout(timer);
223 }
225​
226/** Cancellation waits for native shutdown before callers release startup resources. */
227export const createMuseSdkHostEffect = Effect.fn("createMuseSdkHostEffect")(function* (
228 options: Omit<MuseSdkHostOptions, "signal">,
229 createHost: typeof createMuseSdkHost = createMuseSdkHost,
230) {
231 const native = options.launch ?? (yield* museLaunch(options.binaryPath, options.environment));
232 // The Muse SDK hands libuv the cwd and the PATH search, which freeze the server while a
233 // mount under either hangs; `env` does both in the child.
234 const throughEnv =
235 (yield* HostProcess.Platform) === "linux" && (yield* Effect.promise(supportsEnvChdir))
236 ? envTrampoline(native.command, native.args, options.cwd)
237 : undefined;
238 const { cwd: _enteredByEnv, ...withoutCwd } = options;
239 const hostOptions =
240 throughEnv === undefined
241 ? { ...options, launch: native }
242 : { ...withoutCwd, launch: throughEnv };
243 let startup: Promise<MuseSdkHost> | undefined;
244 return yield* Effect.tryPromise({
245 try: (signal) => {
246 startup = createHost({ ...hostOptions, signal });
247 return startup;
248 },
249 catch: (cause) => new MuseSdkError({ operation: "start", cause }),
250 }).pipe(
251 Effect.onInterrupt(() =>
252 Effect.promise(async () => {
253 await startup?.then(
254 (host) => host.close(),
255 () => {},
256 );
257 }),
258 ),
259 );
260});