diff --git a/changelog.d/fix-acp-agent-path-gui-launch.md b/changelog.d/fix-acp-agent-path-gui-launch.md new file mode 100644 index 0000000000..b5486a4559 --- /dev/null +++ b/changelog.d/fix-acp-agent-path-gui-launch.md @@ -0,0 +1,5 @@ +### Fixed + +- Start custom agents that need Node or another tool from your shell when you open OpenBot from + Finder, the Dock, or a login item. Before, they stopped with exit code 127. Check agent now uses + the same `PATH`, and a `PATH` that you saved on the agent still wins. diff --git a/docs/architecture/providers.md b/docs/architecture/providers.md index 93f6cad279..3d0bafca36 100644 --- a/docs/architecture/providers.md +++ b/docs/architecture/providers.md @@ -478,7 +478,10 @@ next list starts another. values in one `safeStorage` ciphertext. `list()` returns summaries; only the backend gets the values. `customAgents.check` starts the program in a temporary folder, sends `initialize` only, and stops its process group. The scan (`src/backend/acp-agent-scan.ts`) looks up the preset names on the -login-shell `PATH` and in the user's folders, and never starts a file. The agents run confined with +login-shell `PATH` and in the user's folders, and never starts a file. An agent and its check start +with the `PATH` that its command was looked up in (`agentLaunchPath`): the absolute folders of the +login-shell `PATH`, then those of OpenBot's own, so an app that Finder starts can still run a +`#!/usr/bin/env node` agent. A `PATH` saved on the agent wins. The agents run confined with no state paths. Migration 23 adds `acp` to `projection_provider_sessions`. The host hides `acp` agents, models, status, and sign-in state from peers before protocol 5, and the `customAgents` IPC group is local only. diff --git a/package.json b/package.json index 1a6abae661..17cafdaf2b 100644 --- a/package.json +++ b/package.json @@ -192,6 +192,7 @@ "test:browser:framer-live": "bun scripts/browser-smoke.ts --framer-live", "test:codex": "bun scripts/codex-doctor.ts --strict", "test:custom-agents": "bun scripts/custom-acp-agent-e2e.ts", + "test:custom-agents:login-path": "bun scripts/custom-acp-agent-login-path-e2e.ts", "test:antigravity-start": "bun scripts/antigravity-start-e2e.ts", "test:filesystem": "bun scripts/filesystem-smoke.ts", "test:imagegen": "bun scripts/filesystem-smoke.ts --provider codex --imagegen", diff --git a/scripts/custom-acp-agent-login-path-e2e.ts b/scripts/custom-acp-agent-login-path-e2e.ts new file mode 100644 index 0000000000..193b82e58e --- /dev/null +++ b/scripts/custom-acp-agent-login-path-e2e.ts @@ -0,0 +1,131 @@ +// Adapted from the reproduction in nightly-labs/openbot#1824. +// A custom ACP agent whose interpreter is only on the user's login-shell PATH, with OpenBot started +// the way Finder, the Dock or a login item starts it: PATH=/usr/bin:/bin:/usr/sbin:/sbin. +// Most ACP adapters are `#!/usr/bin/env node` scripts and Node comes from Homebrew, nvm or mise, so +// this is the normal macOS setup. Both ways the agent starts must work: Check agent, and the `acp` +// provider driver that lists its models. `bun run test:custom-agents:login-path`; exit 0 = both +// worked. Writes .openbot-build/custom-acp-agent-login-path-e2e/report.json. +import assert from "node:assert/strict"; +import { chmod, mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { Effect } from "effect"; +import type { AgentClient } from "../src/backend/agent-client"; +import { runInLoginShell } from "../src/backend/cli"; +import { runCauseEffect } from "../src/backend/effect-boundary"; +import { requireProviderDriver } from "../src/backend/provider-drivers"; +import { createCustomAgentChanges } from "../src/main/custom-agent-changes"; +import { CustomAgentStore } from "../src/main/custom-agent-store"; +import type { CustomProviderCipher } from "../src/main/custom-provider-store"; + +// The interpreter has a name no system folder holds, so the result does not depend on whether this +// machine also has a `node` in /usr/bin. +const INTERPRETER = "openbot-login-path-node"; + +const FAKE_AGENT = `#!/usr/bin/env ${INTERPRETER} +const NL = String.fromCharCode(10); +let buffer = ""; +const write = (message) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + NL); +process.stdin.setEncoding("utf8"); +process.stdin.on("data", (chunk) => { + buffer += chunk; + let index; + while ((index = buffer.indexOf(NL)) >= 0) { + const line = buffer.slice(0, index); + buffer = buffer.slice(index + 1); + if (line.trim()) handle(JSON.parse(line)); + } +}); +function handle(message) { + if (message.id === undefined) return; + if (message.method === "initialize") { + write({ id: message.id, result: { protocolVersion: 1, agentInfo: { name: "fake", version: "1.0.0" }, agentCapabilities: {} } }); + return; + } + if (message.method === "session/new") { + write({ id: message.id, result: { sessionId: "s-1", models: { availableModels: [{ modelId: "fast", name: "Fast" }], currentModelId: "fast" } } }); + return; + } + write({ id: message.id, result: {} }); +} +setInterval(() => {}, 1000); +`; + +const cipher: CustomProviderCipher = { + canPersist: () => true, + encrypt: (value) => Buffer.from(Buffer.from(value, "utf8").map((byte) => byte ^ 0x5a)), + decrypt: (value) => Buffer.from(value.map((byte) => byte ^ 0x5a)).toString("utf8"), +}; + +const OUT = resolve(import.meta.dirname, "../.openbot-build/custom-acp-agent-login-path-e2e"); +const report: { passed: boolean; check?: unknown; models?: unknown; error?: string } = { passed: false }; + +const root = await mkdtemp(join(tmpdir(), "openbot-login-path-e2e-")); +const clients: AgentClient[] = []; +let passed = false; + +try { + // The user's login shell puts a tool folder on PATH, as Homebrew's `brew shellenv` or nvm does. + const home = join(root, "home"); + const tools = join(home, "tools"); + await mkdir(tools, { recursive: true }); + await symlink(process.execPath, join(tools, INTERPRETER)); + const profile = `export PATH="${tools}:$PATH"\n`; + for (const name of [".zprofile", ".zshrc", ".bash_profile", ".profile"]) await writeFile(join(home, name), profile); + process.env.HOME = home; + delete process.env.ZDOTDIR; + if (process.platform !== "darwin") process.env.SHELL = "/bin/bash"; + + // OpenBot started from Finder, the Dock or a login item. + process.env.PATH = "/usr/bin:/bin:/usr/sbin:/sbin"; + // Control run: the same agent with the tool folder on OpenBot's own PATH, as when started from a terminal. + if (process.env.LOGIN_PATH_CONTROL) process.env.PATH = `${tools}:${process.env.PATH}`; + + const found = await runCauseEffect(runInLoginShell(`command -v ${INTERPRETER}`)); + assert.ok(found.trim().endsWith(`/tools/${INTERPRETER}`), "Precondition: the login shell finds the interpreter."); + + const executable = join(root, "fake-acp-agent"); + await writeFile(executable, FAKE_AGENT); + await chmod(executable, 0o755); + const store = new CustomAgentStore({ path: join(root, "custom-agents.json"), cipher }); + await runCauseEffect(store.load()); + await runCauseEffect(store.save({ id: "alpha", name: "Alpha", command: executable, args: [], env: [] })); + + // Check agent, before the user saves an agent. Only the store's environment check is used. + const unused = () => Effect.die(new Error("Check agent changes no agent.")); + const changes = createCustomAgentChanges({ + service: { saveCustomAgent: unused, removeCustomAgent: unused, reloadCustomAgents: unused }, + customAgents: store, + }); + const check = await runCauseEffect(changes.check({ command: executable, args: [], env: [] })); + report.check = check; + assert.equal(check.agentName, "fake", "Check agent starts the agent."); + + const driver = requireProviderDriver("acp"); + const context = { + apiKey: () => null, + customProviders: () => [], + mcpServers: () => [], + customAgents: () => store.configs(), + }; + const cli = await runCauseEffect(driver.resolveCli()); + const client = driver.createClient(cli, 20_000, context, undefined); + clients.push(client); + client.start(); + const models = await runCauseEffect(client.request("model/list", {}, (value) => value)); + const text = JSON.stringify(models); + report.models = models; + assert.ok(text.includes('"alpha/fast"'), "The agent lists its model."); + passed = true; +} catch (error) { + report.error = error instanceof Error ? error.message : String(error); +} finally { + await Promise.all(clients.map((client) => runCauseEffect(client.stop()).catch(() => undefined))); + await rm(root, { recursive: true, force: true }); +} + +report.passed = passed; +await mkdir(OUT, { recursive: true }); +await writeFile(join(OUT, "report.json"), `${JSON.stringify(report, null, 2)}\n`); +process.stdout.write(`${JSON.stringify(report, null, 2)}\n`); +process.exit(passed ? 0 : 1); diff --git a/src/backend/acp-agent-check.ts b/src/backend/acp-agent-check.ts index cb5506921d..bde086662e 100644 --- a/src/backend/acp-agent-check.ts +++ b/src/backend/acp-agent-check.ts @@ -36,6 +36,11 @@ export interface AgentCheckTarget { executable: string; args: readonly string[]; env: Readonly>; + /** + * The `PATH` the agent starts with, from `agentLaunchPath`. Apart from `env`, because it is not a + * secret to mask. A `PATH` in `env`, which the user saved on the agent, wins over it. + */ + path?: string | null; timeoutMs?: number; } @@ -59,7 +64,7 @@ export const checkAcpAgent = Effect.fn("AcpAgent.check")((target: AgentCheckTarg spawn(spawnTarget.command, spawnTarget.args, { cwd: folder, stdio: ["pipe", "pipe", "pipe"], - env: { ...process.env, ...target.env }, + env: { ...process.env, ...(target.path ? { PATH: target.path } : {}), ...target.env }, detached: process.platform !== "win32", windowsVerbatimArguments: spawnTarget.windowsVerbatimArguments, windowsHide: true, diff --git a/src/backend/acp-agent-command.ts b/src/backend/acp-agent-command.ts index cfcbdbf568..3df90fcef1 100644 --- a/src/backend/acp-agent-command.ts +++ b/src/backend/acp-agent-command.ts @@ -127,6 +127,21 @@ const searchPath = Effect.fn("AcpAgentCommand.searchPath")(function* () { return yield* exit; }, Effect.uninterruptible); +/** + * The `PATH` that a custom agent's process starts with, or null where none is needed. It is the + * folders `resolveAgentCommand` looks in, so a command found there can find its own interpreter: an + * app that Finder, the Dock or a login item starts has a short `PATH`, and `#!/usr/bin/env node` + * fails with exit code 127 without the login shell's folders. Windows has no login shell. + */ +export const agentLaunchPath = Effect.fn("AcpAgentCommand.launchPath")(function* ( + platform: NodeJS.Platform = process.platform, +) { + if (platform === "win32") return null; + // A relative folder such as `.` would be read in the agent's working folder, which is a workspace. + const folders = (yield* searchPath()).filter((folder) => isAbsolute(folder)); + return folders.length > 0 ? folders.join(delimiter) : null; +}); + const whereExe = Effect.fn("AcpAgentCommand.whereExe")((command: string) => providerCall(() => execFileAsync("where.exe", [command], { timeout: 5_000, maxBuffer: 64 * 1024 })).pipe( Effect.map(({ stdout }) => pickWindowsExecutable(stdout, process.env.PATHEXT)), diff --git a/src/backend/custom-acp-agents-client.ts b/src/backend/custom-acp-agents-client.ts index d777086588..16c94c6d6e 100644 --- a/src/backend/custom-acp-agents-client.ts +++ b/src/backend/custom-acp-agents-client.ts @@ -22,7 +22,7 @@ import { type AgentSessionSettingsSnapshot, type AgentSessionSettingValue, isAge import type { DynamicRecord } from "@openbot/contracts/runtime-values"; import { sourceText } from "@openbot/i18n/source"; import { Deferred, Effect, Exit } from "effect"; -import { assertAgentArgs, assertWindowsScriptArgs, resolveAgentCommand } from "./acp-agent-command"; +import { agentLaunchPath, assertAgentArgs, assertWindowsScriptArgs, resolveAgentCommand } from "./acp-agent-command"; import type { AcpHistoryPersistence } from "./acp-client"; import type { AgentClient, DiagnosticOrigin } from "./agent-client"; import { causeHelpers } from "./effect-boundary"; @@ -58,13 +58,15 @@ export type CustomAgentSource = () => readonly CustomAgentConfig[]; /** * Builds the ACP client of one agent, on the file its command resolved to, for the sessions of one - * working folder. `null` is the process that lists the agent's models. + * working folder. `null` is the process that lists the agent's models. `launchPath` is the `PATH` + * the process starts with, or null to leave the `PATH` of OpenBot unchanged. */ export type CustomAgentChildFactory = ( config: CustomAgentConfig, executable: string, folder: string | null, history?: AcpHistoryPersistence, + launchPath?: string | null, ) => AgentClient; const MODEL_LIST_TIMEOUT_MS = 5_000; @@ -508,6 +510,7 @@ export class CustomAcpAgentsClient extends EventEmitter implements cause: new Error(sourceText("error.provider.customAgentNotFound", { command: config.command })), }); yield* customStep(() => assertWindowsScriptArgs(executable, config.args)); + const launchPath = yield* agentLaunchPath().pipe(toProviderClientOperationError); const prefix = folder === null ? agentId : `${agentId}:${folderTag(folder)}`; let child: AgentClient | null = null; const history = @@ -530,7 +533,7 @@ export class CustomAcpAgentsClient extends EventEmitter implements fragment, ) ?? Effect.void, }; - const created = yield* customStep(() => this.#createChild(config, executable, folder, history)); + const created = yield* customStep(() => this.#createChild(config, executable, folder, history, launchPath)); child = created; const route = (sessionId: string) => this.#routedSessionId(created, prefix, sessionId); created.on("notification", (notification) => { diff --git a/src/backend/provider-drivers.ts b/src/backend/provider-drivers.ts index f91d039b25..406f18728a 100644 --- a/src/backend/provider-drivers.ts +++ b/src/backend/provider-drivers.ts @@ -713,16 +713,16 @@ export const BUILT_IN_PROVIDER_DRIVERS: readonly BuiltInProviderDriver[] = [ createClient: (_cli, timeout, context, confinement) => new CustomAcpAgentsClient( () => savedCustomAgents(context), - (config, executable, folder, history) => - customAgentChild(config, executable, folder, timeout, context, confinement, false, history), + (config, executable, folder, history, launchPath) => + customAgentChild(config, executable, folder, timeout, context, confinement, false, history, launchPath), undefined, context.history?.("acp"), ), createProfileClient: (_cli, timeout, context) => new CustomAcpAgentsClient( () => savedCustomAgents(context), - (config, executable, folder, history) => - customAgentChild(config, executable, folder, timeout, context, undefined, true, history), + (config, executable, folder, history, launchPath) => + customAgentChild(config, executable, folder, timeout, context, undefined, true, history, launchPath), undefined, context.history?.("acp"), ), @@ -749,8 +749,13 @@ function customAgentChild( confinement: ProcessConfinement | undefined, profileGeneration: boolean, history?: AcpHistoryPersistence, + launchPath?: string | null, ): AgentClient { - const env = Object.fromEntries(config.env.map((entry) => [entry.name, entry.value])); + // A `PATH` the user saved on the agent wins over the login shell's. + const env = { + ...(launchPath ? { PATH: launchPath } : {}), + ...Object.fromEntries(config.env.map((entry) => [entry.name, entry.value])), + }; const values = config.env.map((entry) => entry.value); return new AcpAgentClient({ executable, version: "", source: "system" }, timeout, { provider: "acp", diff --git a/src/main/custom-agent-changes.ts b/src/main/custom-agent-changes.ts index 9a6949471a..6ba74c527e 100644 --- a/src/main/custom-agent-changes.ts +++ b/src/main/custom-agent-changes.ts @@ -16,7 +16,12 @@ import type { import { isNewCustomAgentId } from "@openbot/contracts/ipc"; import { sourceText } from "@openbot/i18n/source"; import { checkAcpAgent } from "../backend/acp-agent-check"; -import { assertAgentArgs, assertWindowsScriptArgs, resolveAgentCommand } from "../backend/acp-agent-command"; +import { + agentLaunchPath, + assertAgentArgs, + assertWindowsScriptArgs, + resolveAgentCommand, +} from "../backend/acp-agent-command"; import { AgentLifecycleFailed, type AgentService } from "../backend/agent-service"; import type { CustomAgentStore } from "./custom-agent-store"; @@ -141,7 +146,9 @@ export function createCustomAgentChanges({ cause: new Error(sourceText("error.provider.customAgentNotFound", { command: input.command })), }); yield* runtimeSync(() => assertWindowsScriptArgs(executable, input.args)); - return yield* check({ executable, args: input.args, env }).pipe(toProviderRuntimeFailure); + // The same `PATH` the agent starts with. + const path = yield* agentLaunchPath().pipe(toProviderRuntimeFailure); + return yield* check({ executable, args: input.args, env, path }).pipe(toProviderRuntimeFailure); })().pipe(Effect.uninterruptible), }; }