mirror of
https://github.com/nightly-labs/openbot.git
synced 2026-11-26 02:29:31 +08:00
Start custom agents with the login shell PATH (#2158)
* Start custom agents with the login shell PATH An app that Finder, the Dock, or a login item starts has a short PATH. The login shell PATH found the agent command, but the agent process got the short PATH, so "#!/usr/bin/env node" agents stopped with exit code 127. Give the process, and Check agent, the PATH that the command was looked up in. A PATH saved on the agent still wins. Fixes #1824 Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * Do not mask the launch PATH in Check agent, and test Check agent Check agent masks each value in its environment as a secret. Give the launch PATH to Check agent as a separate field, so that only the saved values are masked. A PATH that the user saved on the agent still wins. Remove the launchPath injection parameters, because no test uses them. Add the test:custom-agents:login-path script, and make the E2E script also start the agent through Check agent. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Give agents only absolute PATH folders, and stop E2E agents A relative PATH folder such as "." would be read in the agent's working folder, which is a workspace. The launch PATH now holds only absolute folders, as the command lookup does. The E2E script now runs the stop Effect of each client, so no agent process stays after the script. Document the launch PATH in the provider architecture notes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: batool-fariha <farihabatool2023@gmail.com> Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
batool-fariha
parent
ba40805f6b
commit
b10aa58161
@@ -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.
|
||||
@@ -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.
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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);
|
||||
@@ -36,6 +36,11 @@ export interface AgentCheckTarget {
|
||||
executable: string;
|
||||
args: readonly string[];
|
||||
env: Readonly<Record<string, string>>;
|
||||
/**
|
||||
* 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,
|
||||
|
||||
@@ -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)),
|
||||
|
||||
@@ -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<ClientEvents> 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<ClientEvents> 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) => {
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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),
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user