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

sdk.ts

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