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