Open History to see the last commit
1import * as Effect from "effect/Effect";
2import * as Schema from "effect/Schema";
3
4import type { EmbeddedDriverExit } from "@trycua/cua-driver/embedded";
5import type { CuaDriverMcpConfiguration } from "@t3tools/contracts";
6
7import { T3CODE_CODEX_CUA_LAUNCH_ARGS_ENV } from "../provider/Layers/codexLaunchArgs.ts";
8
9export const T3CODE_CUA_DRIVER_PATH_ENV = "T3CODE_CUA_DRIVER_PATH";
10export const T3CODE_CUA_DRIVER_HOST_BUNDLE_ID_ENV = "T3CODE_CUA_DRIVER_HOST_BUNDLE_ID";
11export const T3CODE_CUA_DRIVER_MODULE_URL_ENV = "T3CODE_CUA_DRIVER_MODULE_URL";
12
13export class CuaDriverStartError extends Schema.TaggedErrorClass<CuaDriverStartError>()(
14 "CuaDriverStartError",
15 {
16 binaryPath: Schema.String,
17 cause: Schema.Defect(),
18 },
19) {
20 override get message(): string {
21 return `Could not start embedded cua-driver at '${this.binaryPath}'.`;
22 }
23}
24
25export class CuaDriverModuleLoadError extends Schema.TaggedErrorClass<CuaDriverModuleLoadError>()(
26 "CuaDriverModuleLoadError",
27 {
28 modulePath: Schema.String,
29 cause: Schema.Defect(),
30 },
31) {
32 override get message(): string {
33 return `Could not load embedded cua-driver module at '${this.modulePath}'.`;
34 }
35}
36
37const tomlString = (value: string): string => JSON.stringify(value);
38
39export const buildCodexLaunchArgs = (connection: {
40 readonly mcp: CuaDriverMcpConfiguration;
41}): string => {
42 const proxyArgs = connection.mcp.args.map(tomlString).join(",");
43 const proxyEnv = connection.mcp.environment
44 .map(({ name, value }) => `${name}=${tomlString(value)}`)
45 .join(",");
46 return [
47 "-c",
48 tomlString(`mcp_servers.cua-driver.command=${tomlString(connection.mcp.command)}`),
49 "-c",
50 tomlString(`mcp_servers.cua-driver.args=[${proxyArgs}]`),
51 "-c",
52 tomlString(`mcp_servers.cua-driver.env={${proxyEnv}}`),
53 ].join(" ");
54};
55
56const importEmbeddedCuaDriver = (
57 moduleUrl?: string,
58): Promise<typeof import("@trycua/cua-driver/embedded")> =>
59 moduleUrl === undefined ? import("@trycua/cua-driver/embedded") : import(moduleUrl);
60
61export const monitorEmbeddedCuaDriverExit = Effect.fn("server.monitorEmbeddedCuaDriverExit")(
62 function* (
63 waitForExit: () => Promise<EmbeddedDriverExit>,
64 onUnexpectedExit: (exit: EmbeddedDriverExit) => Effect.Effect<void>,
65 ) {
66 const exit = yield* Effect.tryPromise(waitForExit);
67 yield* onUnexpectedExit(exit);
68 },
69);
70
71export const installCodexLaunchArgs = Effect.fn("server.installCodexLaunchArgs")(function* (
72 launchArgs: string,
73) {
74 const previous = process.env[T3CODE_CODEX_CUA_LAUNCH_ARGS_ENV];
75 let active = true;
76 const deactivate = Effect.sync(() => {
77 if (!active) return false;
78 active = false;
79 if (previous === undefined) delete process.env[T3CODE_CODEX_CUA_LAUNCH_ARGS_ENV];
80 else process.env[T3CODE_CODEX_CUA_LAUNCH_ARGS_ENV] = previous;
81 return true;
82 });
83 yield* Effect.addFinalizer(() => deactivate.pipe(Effect.asVoid));
84 process.env[T3CODE_CODEX_CUA_LAUNCH_ARGS_ENV] = launchArgs;
85 return () => deactivate;
86});
87
88/**
89 * Uses the descriptor supplied by the permission-owning desktop host. The
90 * server launches only the stdio proxy; it does not own or restart the daemon.
91 */
92export const installDesktopCuaDriver = Effect.fn("server.installDesktopCuaDriver")(function* (
93 mcp: CuaDriverMcpConfiguration,
94) {
95 yield* installCodexLaunchArgs(buildCodexLaunchArgs({ mcp }));
96 yield* Effect.logInfo("desktop-hosted cua-driver ready", {
97 component: "embedded-cua-driver",
98 command: mcp.command,
99 });
100});
101
102/**
103 * Starts a server-private driver when T3CODE_CUA_DRIVER_PATH is configured.
104 * The scoped finalizer owns both the native host and its child process.
105 */
106export const startEmbeddedCuaDriver = Effect.fn("server.startEmbeddedCuaDriver")(function* () {
107 const binaryPath = process.env[T3CODE_CUA_DRIVER_PATH_ENV]?.trim();
108 if (!binaryPath) return;
109
110 const hostBundleId = process.env[T3CODE_CUA_DRIVER_HOST_BUNDLE_ID_ENV]?.trim() || "t3-server";
111 const moduleUrl = process.env[T3CODE_CUA_DRIVER_MODULE_URL_ENV]?.trim() || undefined;
112 const { EmbeddedCuaDriverHost } = yield* Effect.tryPromise({
113 try: () => importEmbeddedCuaDriver(moduleUrl),
114 catch: (cause) =>
115 new CuaDriverModuleLoadError({
116 modulePath: moduleUrl ?? "@trycua/cua-driver/embedded",
117 cause,
118 }),
119 });
120 const driver = yield* Effect.try({
121 try: () => new EmbeddedCuaDriverHost(binaryPath, hostBundleId),
122 catch: (cause) => new CuaDriverStartError({ binaryPath, cause }),
123 });
124 yield* Effect.addFinalizer(() =>
125 Effect.tryPromise(() => driver.stop()).pipe(
126 Effect.ignore,
127 Effect.ensuring(
128 Effect.sync(() => driver.uniffiDestroy()).pipe(Effect.catchCause(() => Effect.void)),
129 ),
130 ),
131 );
132
133 const connection = yield* Effect.tryPromise({
134 try: () => driver.start(),
135 catch: (cause) => new CuaDriverStartError({ binaryPath, cause }),
136 });
137
138 const disableCua = yield* installCodexLaunchArgs(buildCodexLaunchArgs(connection));
139 yield* monitorEmbeddedCuaDriverExit(
140 () => driver.waitForExit(connection.generation),
141 (exit) =>
142 disableCua().pipe(
143 Effect.flatMap((disabled) =>
144 disabled
145 ? Effect.logWarning("embedded cua-driver exited; computer use is unavailable", {
146 component: "embedded-cua-driver",
147 generation: exit.generation,
148 code: exit.code,
149 success: exit.success,
150 })
151 : Effect.void,
152 ),
153 ),
154 ).pipe(
155 Effect.catch((cause) =>
156 disableCua().pipe(
157 Effect.flatMap((disabled) =>
158 disabled
159 ? Effect.logWarning(
160 "embedded cua-driver exit monitor failed; computer use is unavailable",
161 {
162 component: "embedded-cua-driver",
163 cause,
164 },
165 )
166 : Effect.void,
167 ),
168 ),
169 ),
170 Effect.forkScoped,
171 );
172
173 yield* Effect.logInfo("embedded cua-driver ready", {
174 component: "embedded-cua-driver",
175 pid: connection.pid,
176 socketPath: connection.socketPath,
177 });
178});