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

sdk.ts

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