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

sdk.ts

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