diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 63e9324d983bb..2702d08df3be5 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -122,6 +122,7 @@ import { resolveCodexComputerUse, type CodexComputerUseAvailability, } from "../../provider/CodexComputerUse.ts"; +import { configureProviderComputerUse } from "../../provider/CodexComputerUseSetup.ts"; import { buildCodexAdditionalContext, buildCodexComputerUseInstructions, @@ -2329,6 +2330,16 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( }); if (refused) return yield* refused; yield* client.notify("initialized", undefined); + if (adapterOptions.enableComputerUse) { + yield* configureProviderComputerUse( + (resolvedRuntime?.config ?? adapterOptions.settings).homePath || + environment.CODEX_HOME, + ).pipe( + Effect.provideService(CodexClient.CodexAppServerClient, client), + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, pathService), + ); + } yield* Ref.set(initialized, true); }), ); diff --git a/apps/server/src/provider/CodexComputerUse.test.ts b/apps/server/src/provider/CodexComputerUse.test.ts index 11f5695819dc3..660e1bf579634 100644 --- a/apps/server/src/provider/CodexComputerUse.test.ts +++ b/apps/server/src/provider/CodexComputerUse.test.ts @@ -11,8 +11,10 @@ import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as Stream from "effect/Stream"; import { TestClock } from "effect/testing"; +import { stringify } from "smol-toml"; import { resolveCodexComputerUse } from "./CodexComputerUse.ts"; +import { configureProviderComputerUse, prepareComputerUseEdits } from "./CodexComputerUseSetup.ts"; const resources = "/custom/Acme.app/Contents/Resources"; const command = `${resources}/cua_node/bin/node_repl`; @@ -41,6 +43,56 @@ const rpcError = new CodexErrors.CodexAppServerTransportError({ cause: "fixture", }); +it("prepares only the native Mac tool for a separate Codex home without replacing its settings", () => { + const source = configured(); + const node = source.mcp_servers.node_repl; + const config = { + ...source, + mcp_servers: { + node_repl: { + ...node, + args: [], + environment_id: "local", + tool_timeout_sec: null, + env: { + ...node.env, + CODEX_HOME: "/personal", + TOKEN: "private", + NODE_REPL_TRUSTED_SERVICES: JSON.stringify({ sky: "@oai/sky/service", browser: "other" }), + }, + }, + }, + }; + const target = { model_provider: "custom", mcp_servers: { unrelated: {} } }; + const edits = prepareComputerUseEdits(config, target); + assert.deepEqual( + edits.map((edit) => edit.keyPath), + ["plugins.computer-use@openai-bundled.enabled", "mcp_servers.node_repl"], + ); + assert.deepEqual(edits[1]?.value, { + command, + enabled_tools: ["js"], + env: { + ...node.env, + NODE_REPL_NODE_PATH: `${resources}/cua_node/bin/node`, + NODE_REPL_TRUSTED_CODE_PATHS: modules, + }, + }); + for (const conflict of [ + { features: { plugins: false } }, + { plugins: { "computer-use@openai-bundled": { enabled: false } } }, + { mcp_servers: { node_repl: {} } }, + ]) { + assert.throws(() => prepareComputerUseEdits(config, conflict)); + } + assert.throws(() => + prepareComputerUseEdits( + { ...config, mcp_servers: { node_repl: { ...node, disabled_tools: ["js"] } } }, + target, + ), + ); +}); + const fixture = ( options: { config?: unknown; @@ -51,6 +103,8 @@ const fixture = ( missing?: string; fail?: string; platform?: NodeJS.Platform; + homePath?: string; + nativeConfig?: string; request?: CodexClient.CodexAppServerClient["Service"]["raw"]["request"]; } = {}, ) => { @@ -63,6 +117,7 @@ const fixture = ( calls.push({ method, params }); if (options.request) return options.request(method, params); if (options.fail === method) return Effect.fail(rpcError); + if (method === "config/batchWrite") return Effect.succeed({ status: "ok" }); if (method === "config/read") return Effect.succeed({ config: options.config ?? configured(), @@ -76,7 +131,11 @@ const fixture = ( if (method === "skills/list") return Effect.succeed({ data: [ - { cwd: "/project", skills: options.skills ?? [], errors: options.skillErrors ?? [] }, + { + cwd: options.homePath ? "/" : "/project", + skills: options.skills ?? [], + errors: options.skillErrors ?? [], + }, ], }); return Effect.die(`Unexpected RPC ${method}`); @@ -100,6 +159,7 @@ const fixture = ( }); const absent = FileSystem.makeNoop({}); const fileSystem = FileSystem.makeNoop({ + realPath: (path) => Effect.succeed(path), access: (path) => Effect.sync(() => { reads.push(path); @@ -107,6 +167,7 @@ const fixture = ( readFileString: (path) => { reads.push(path); if (path === options.missing) return absent.readFileString(path); + if (path === "/mac/.codex/config.toml") return Effect.succeed(options.nativeConfig ?? ""); if (path.endsWith("package.json")) return Effect.succeed( JSON.stringify({ name: "@oai/sky", exports: { "./service": "./service.js" } }), @@ -116,15 +177,76 @@ const fixture = ( ); }, }); - const resolve = resolveCodexComputerUse({ cwd: "/project" }).pipe( - Effect.provideService(CodexClient.CodexAppServerClient, client), - Effect.provideService(FileSystem.FileSystem, fileSystem), - Effect.provide(Path.layer), - Effect.provideService(HostProcess.Platform, options.platform ?? "darwin"), - ); - return { resolve, calls, reads }; + const provide = ( + effect: Effect.Effect< + A, + E, + CodexClient.CodexAppServerClient | FileSystem.FileSystem | Path.Path + >, + ) => + effect.pipe( + Effect.provideService(CodexClient.CodexAppServerClient, client), + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provide(Path.layer), + Effect.provideService(HostProcess.HomeDirectory, "/mac"), + Effect.provideService(HostProcess.Platform, options.platform ?? "darwin"), + ); + return { + resolve: provide(resolveCodexComputerUse({ cwd: "/project" })), + configure: provide(configureProviderComputerUse(options.homePath)), + calls, + reads, + }; }; +it.effect( + "provisions an isolated provider home globally without replacing overrides or writing from a project layer", + () => + Effect.gen(function* () { + const file = "/providers/custom/config.toml"; + const user = { name: { type: "user", file }, config: {}, version: "original" }; + const custom = { + homePath: "/providers/custom", + config: {}, + layers: [user], + nativeConfig: stringify(configured()), + }; + const fresh = fixture(custom); + yield* fresh.configure; + assert.deepEqual( + fresh.calls + .filter((call) => call.method === "config/batchWrite") + .map((call) => call.params), + [ + { + filePath: file, + expectedVersion: "original", + reloadUserConfig: true, + edits: prepareComputerUseEdits(configured(), {}), + }, + ], + ); + for (const overrides of [ + { config: configured() }, + { config: { features: { plugins: false } } }, + { config: { mcp_servers: { node_repl: { enabled: false } } } }, + { requirements: { allowBrowserAndComputerUse: false } }, + { + layers: [ + user, + { name: { type: "project", dotCodexFolder: "/.codex" }, config: {}, version: "other" }, + ], + }, + { nativeConfig: "invalid TOML" }, + { platform: "linux" as const }, + ]) { + const blocked = fixture({ ...custom, ...overrides }); + yield* blocked.configure; + assert.isFalse(blocked.calls.some((call) => call.method === "config/batchWrite")); + } + }), +); + it.effect("locates configured native files from the selected effective home and cwd", () => Effect.gen(function* () { const f = fixture(); diff --git a/apps/server/src/provider/CodexComputerUse.ts b/apps/server/src/provider/CodexComputerUse.ts index 48a6bb2c35d9c..ea802bc052fab 100644 --- a/apps/server/src/provider/CodexComputerUse.ts +++ b/apps/server/src/provider/CodexComputerUse.ts @@ -47,8 +47,17 @@ const relevantSkill = (value: { name?: unknown; path?: unknown }) => (typeof value.name === "string" && skillNames.has(value.name)) || (typeof value.path === "string" && /(?:^|[/\\])computer-use[/\\]SKILL\.md$/.test(value.path)); +export function computerUseSkillDisabled(config: Record) { + const rules = record(config.skills).config; + return ( + Array.isArray(rules) && + rules.some((rule) => record(rule).enabled === false && relevantSkill(record(rule))) + ); +} + export const resolveCodexComputerUse = Effect.fn("CodexComputerUse.resolve")(function* (input: { readonly cwd: string | null; + readonly candidateConfig?: Readonly>; }): Effect.fn.Return< CodexComputerUseAvailability, never, @@ -61,9 +70,11 @@ export const resolveCodexComputerUse = Effect.fn("CodexComputerUse.resolve")(fun const cwd = input.cwd ?? (yield* HostProcess.WorkingDirectory); return yield* Effect.gen(function* () { - const { config } = yield* client.raw - .request("config/read", { cwd, includeLayers: false }) - .pipe(Effect.flatMap(decodeConfig)); + const config = + input.candidateConfig ?? + (yield* client.raw + .request("config/read", { cwd, includeLayers: false }) + .pipe(Effect.flatMap(decodeConfig))).config; if ( record(config.features).plugins === false || record(record(config.plugins)[pluginId]).enabled !== true @@ -109,12 +120,7 @@ export const resolveCodexComputerUse = Effect.fn("CodexComputerUse.resolve")(fun !env.SKY_CUA_SERVICE_PATH.endsWith(".app") ) return unavailable; - const rules = record(config.skills).config; - if ( - Array.isArray(rules) && - rules.some((rule) => record(rule).enabled === false && relevantSkill(record(rule))) - ) - return unavailable; + if (computerUseSkillDisabled(config)) return unavailable; const catalog = yield* client.raw .request("skills/list", { cwds: [cwd] }) diff --git a/apps/server/src/provider/CodexComputerUseSetup.ts b/apps/server/src/provider/CodexComputerUseSetup.ts new file mode 100644 index 0000000000000..b19778563669f --- /dev/null +++ b/apps/server/src/provider/CodexComputerUseSetup.ts @@ -0,0 +1,158 @@ +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as CodexClient from "effect-codex-app-server/client"; +import * as CodexSchema from "effect-codex-app-server/schema"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; +import { parse } from "smol-toml"; +import { computerUseSkillDisabled, resolveCodexComputerUse } from "./CodexComputerUse.ts"; + +const plugin = "computer-use@openai-bundled"; +const isTable = Schema.is(Schema.Record(Schema.String, Schema.Unknown)); +const table = (value: unknown) => (isTable(value) ? value : {}); + +const hasProviderChoice = (config: Record) => + Object.hasOwn(table(config.plugins), plugin) || + Object.hasOwn(table(config.mcp_servers), "node_repl") || + table(config.features).plugins === false || + computerUseSkillDisabled(config); + +export function prepareComputerUseEdits( + source: Record, + target: Record, +) { + if (hasProviderChoice(target)) { + throw new Error( + "The destination already configures the Computer Use plugin or node_repl, or disables plugins. No settings were replaced.", + ); + } + const node = table(table(source.mcp_servers).node_repl); + const env = table(node.env); + if ( + table(source.features).plugins === false || + source.profile != null || + computerUseSkillDisabled(source) || + table(table(source.plugins)[plugin]).enabled !== true || + node.enabled === false || + (node.args != null && !(Array.isArray(node.args) && node.args.length === 0)) || + (node.environment_id != null && node.environment_id !== "local") || + (node.enabled_tools !== undefined && + !(Array.isArray(node.enabled_tools) && node.enabled_tools.includes("js"))) || + (node.disabled_tools !== undefined && + !(Array.isArray(node.disabled_tools) && !node.disabled_tools.includes("js"))) || + Object.keys(node).some( + (key) => + ![ + "command", + "args", + "environment_id", + "tool_timeout_sec", + "env", + "env_vars", + "startup_timeout_sec", + "enabled", + "enabled_tools", + "disabled_tools", + ].includes(key), + ) || + Object.keys(table(source.computer_use)).length > 0 || + typeof node.command !== "string" || + !node.command.startsWith("/") || + !node.command.endsWith("/Contents/Resources/cua_node/bin/node_repl") || + typeof env.SKY_CUA_SERVICE_PATH !== "string" || + typeof env.NODE_REPL_NODE_MODULE_DIRS !== "string" || + typeof env.NODE_REPL_TRUSTED_SERVICES !== "string" || + table(JSON.parse(env.NODE_REPL_TRUSTED_SERVICES)).sky !== "@oai/sky/service" + ) { + throw new Error( + "The source is not a supported native Computer Use configuration. No settings were copied.", + ); + } + const server = { + command: node.command, + enabled_tools: ["js"], + ...(typeof node.tool_timeout_sec === "number" + ? { tool_timeout_sec: node.tool_timeout_sec } + : {}), + ...(typeof node.startup_timeout_sec === "number" + ? { startup_timeout_sec: node.startup_timeout_sec } + : {}), + env: { + NODE_REPL_NODE_PATH: node.command.slice(0, -"node_repl".length) + "node", + NODE_REPL_NODE_MODULE_DIRS: env.NODE_REPL_NODE_MODULE_DIRS, + NODE_REPL_TRUSTED_CODE_PATHS: env.NODE_REPL_NODE_MODULE_DIRS, + NODE_REPL_TRUSTED_SERVICES: JSON.stringify({ sky: "@oai/sky/service" }), + SKY_CUA_SERVICE_PATH: env.SKY_CUA_SERVICE_PATH, + ...(typeof env.NODE_REPL_INSTRUCTIONS_USE_CASE_COMPUTER_USE === "string" + ? { + NODE_REPL_INSTRUCTIONS_USE_CASE_COMPUTER_USE: + env.NODE_REPL_INSTRUCTIONS_USE_CASE_COMPUTER_USE, + } + : {}), + }, + }; + return [ + { keyPath: `plugins.${plugin}.enabled`, mergeStrategy: "replace", value: true }, + { keyPath: "mcp_servers.node_repl", mergeStrategy: "replace", value: server }, + ] as const; +} + +export const configureProviderComputerUse = Effect.fn("CodexComputerUse.configureProvider")( + function* (homePath: string | undefined) { + if (!homePath || (yield* HostProcess.Platform) !== "darwin") return; + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const nativeHome = path.join(yield* HostProcess.HomeDirectory, ".codex"); + if (path.resolve(homePath) === nativeHome) return; + const target = yield* fs.realPath(homePath); + if (target === (yield* fs.realPath(nativeHome))) return; + const configPath = path.join(target, "config.toml"); + const entry = yield* fs + .lstat(configPath) + .pipe(Effect.catchReason("PlatformError", "NotFound", () => Effect.undefined)); + if (entry && entry.type !== "File") return; + const client = yield* CodexClient.CodexAppServerClient; + const { config, layers } = yield* client.raw + .request("config/read", { cwd: "/", includeLayers: true }) + .pipe(Effect.flatMap(Schema.decodeUnknownEffect(CodexSchema.V2ConfigReadResponse))); + if ( + hasProviderChoice(config) || + layers?.some((layer) => layer.name.type === "project" && !layer.disabledReason) + ) + return; + const user = layers?.find( + (layer) => + layer.name.type === "user" && + !layer.name.profile && + layer.name.file === configPath && + !layer.disabledReason, + ); + if (!user || hasProviderChoice(table(user.config))) return; + const source = yield* fs.readFileString(path.join(nativeHome, "config.toml")); + const edits = yield* Effect.try({ + try: () => prepareComputerUseEdits(parse(source), config), + catch: () => "UnsupportedNativeComputerUseConfig" as const, + }); + const candidateConfig = { + ...config, + plugins: { ...table(config.plugins), [plugin]: { enabled: true } }, + mcp_servers: { ...table(config.mcp_servers), node_repl: edits[1].value }, + }; + const checked = yield* resolveCodexComputerUse({ cwd: "/", candidateConfig }); + if (checked.status !== "available") return; + yield* client.raw.request("config/batchWrite", { + filePath: configPath, + expectedVersion: user.version, + reloadUserConfig: true, + edits, + }); + yield* Effect.logDebug("Applied native Computer Use settings to the Codex provider home."); + }, + Effect.timeout("3 seconds"), + Effect.catch((reason) => + Effect.logDebug("Native Computer Use setup was unavailable.", { + reason: typeof reason === "string" ? reason : reason._tag, + }), + ), +); diff --git a/apps/server/src/provider/Drivers/CodexManagedProvider.ts b/apps/server/src/provider/Drivers/CodexManagedProvider.ts index 08eeb1499bc62..7fdb5ab83553d 100644 --- a/apps/server/src/provider/Drivers/CodexManagedProvider.ts +++ b/apps/server/src/provider/Drivers/CodexManagedProvider.ts @@ -251,6 +251,7 @@ export const makeManagedCodexProvider = Effect.fn("makeManagedCodexProvider")(fu // already wraps openSession in withAccess, so resolve without re-entering it. const models = snapshot.getSnapshot.pipe(Effect.map((value) => value.models)); const orchestrationAdapter = yield* createCodexAdapterV2(input, { + enableComputerUse: true, onUsageLimits: (update) => snapshot.applyUsageLimits(update), models, resolveRuntime: runtime.resolve, diff --git a/docs/user/providers-codex.md b/docs/user/providers-codex.md index f67296e8ab8b7..e1c467fbdd432 100644 --- a/docs/user/providers-codex.md +++ b/docs/user/providers-codex.md @@ -87,10 +87,9 @@ supports async questions. ## Use Mac apps -If your Codex instance already has native Computer Use configured and enabled, -ask it to work in a Mac app, such as Calculator. Computer Use controls the server -environment's Mac, even when you connect from another computer or your phone. -Native permissions and confirmation requests still apply. +If native Computer Use is configured in `~/.codex` on the server Mac, ask Codex to work in a Mac app such as Calculator. When a provider starts with its own Codex home, T3 adds the native tool to that home’s `config.toml` if it is not already configured. No setup command is needed. T3 leaves existing plugin and `node_repl` settings alone and does not copy account credentials. + +Computer Use controls the server Mac, even from a remote client. macOS permissions, project restrictions and confirmations still apply. To opt a provider out, set `enabled = false` in its `[plugins."computer-use@openai-bundled"]` and `[mcp_servers.node_repl]` tables. ## Approve app access