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

sdk.ts

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