diff --git a/plugins/pstack/skills/poteto-mode/references/model-catalog.md b/plugins/pstack/skills/poteto-mode/references/model-catalog.md index 5857bcaf..0ac83350 100644 --- a/plugins/pstack/skills/poteto-mode/references/model-catalog.md +++ b/plugins/pstack/skills/poteto-mode/references/model-catalog.md @@ -86,6 +86,9 @@ The runner refuses an access mode outside a provider's Access modes cell before - Host prerequisites: none. - State paths: the Claude config home (`CLAUDE_CONFIG_DIR`, else `~/.claude`). - Child environment: read-only: inherited; isolated-write: inherited without `GIT_*`. +- `--verbose` makes Claude emit its event array, so the runner reports `child-failed` when every Bash call fails to start its sandbox (`apply-seccomp:` or `bwrap:`). +- The runner passes `ANTHROPIC_BASE_URL` and `ANTHROPIC_AUTH_TOKEN` from the `env` of `settings.json` in the Claude config home only when the shell sets none of `ANTHROPIC_BASE_URL`, `ANTHROPIC_AUTH_TOKEN`, or `ANTHROPIC_API_KEY`. +- When the runner uses those settings, it also forwards `apiKeyHelper` if the settings `env` supplies neither `ANTHROPIC_API_KEY` nor `ANTHROPIC_AUTH_TOKEN`. ### codex: Codex CLI diff --git a/plugins/pstack/skills/poteto-mode/scripts/runner/providers/claude.test.ts b/plugins/pstack/skills/poteto-mode/scripts/runner/providers/claude.test.ts index eb4333a2..4a6b3478 100644 --- a/plugins/pstack/skills/poteto-mode/scripts/runner/providers/claude.test.ts +++ b/plugins/pstack/skills/poteto-mode/scripts/runner/providers/claude.test.ts @@ -1,4 +1,7 @@ -import { describe, expect, it } from "bun:test"; +import { afterEach, beforeEach, describe, expect, it } from "bun:test"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { access } from "../registry/contract.ts"; import type { LaneRequest } from "../registry/index.ts"; import { adapterSuite, testLane } from "./adapter-suite.ts"; @@ -9,9 +12,29 @@ adapterSuite(claude); const lane = (request: Partial = {}) => testLane({ provider: "claude", model: "fable", ...request }); -const argv = (request: Partial = {}, sharedGitDir: string | null = null) => - claude.launch.argv(lane(request), { sharedGitDir, providerSidecar: null }); -const parse = (stdout: string) => claude.parse({ exitCode: 0, stdout, stderr: "", sidecar: null }, lane()); +const argv = ( + request: Partial = {}, + sharedGitDir: string | null = null, + sourceEnv?: NodeJS.ProcessEnv +) => claude.launch.argv(lane(request), { + sharedGitDir, + providerSidecar: null, + hostConfig: sourceEnv === undefined ? undefined : claude.hostConfig?.(sourceEnv), +}); +const launchSettings = (args: readonly string[]): unknown => + JSON.parse(args[args.indexOf("--settings") + 1] ?? ""); +const parse = (stdout: string, request: Partial = {}) => + claude.parse({ exitCode: 0, stdout, stderr: "", sidecar: null }, lane(request)); + +const seccomp = "apply-seccomp: failed to apply seccomp filter: Operation not permitted"; +const toolUse = (id: string, name = "Bash") => + ({ type: "assistant", message: { content: [{ type: "tool_use", id, name, input: {} }] } }); +const toolResult = (id: string, content: unknown, isError = true) => + ({ type: "user", message: { content: [{ type: "tool_result", tool_use_id: id, content, is_error: isError }] } }); +const terminal = { + type: "result", is_error: false, result: "I could not run commands.", + session_id: "s1", modelUsage: { "claude-fable-9-9": {} }, +}; describe("claude launch", () => { it("passes Claude model, effort, permissions, and no-recursion controls", () => { @@ -37,6 +60,7 @@ describe("claude launch", () => { "Agent,Task,WebSearch,WebFetch,Edit,Write,NotebookEdit", "--output-format", "json", + "--verbose", ]); expect(args).not.toContain("bypassPermissions"); }); @@ -60,14 +84,11 @@ describe("claude launch", () => { allowUnsandboxedCommands: false, failIfUnavailable: true, }; - const settings = (args: readonly string[]): unknown => - JSON.parse(args[args.indexOf("--settings") + 1] ?? ""); - - expect(settings(argv(writer))).toEqual({ sandbox }); - expect(settings(argv(writer, "/repo/.git"))).toEqual({ + expect(launchSettings(argv(writer))).toEqual({ sandbox }); + expect(launchSettings(argv(writer, "/repo/.git"))).toEqual({ sandbox: { ...sandbox, filesystem: { denyWrite: ["/repo/.git"] } }, }); - expect(settings(argv(writer, "/srv/my repo/.git"))).toEqual({ + expect(launchSettings(argv(writer, "/srv/my repo/.git"))).toEqual({ sandbox: { ...sandbox, filesystem: { denyWrite: ["/srv/my repo/.git"] } }, }); @@ -88,6 +109,75 @@ describe("claude launch", () => { }); }); +describe("claude launch authentication", () => { + const apiKeyHelper = "/example/claude-auth"; + let configDir: string; + let sourceEnv: NodeJS.ProcessEnv; + + beforeEach(() => { + configDir = mkdtempSync(join(tmpdir(), "pstack-claude-settings-")); + sourceEnv = { CLAUDE_CONFIG_DIR: configDir }; + }); + afterEach(() => rmSync(configDir, { recursive: true })); + + function writeSettings(settings: object): void { + writeFileSync(join(configDir, "settings.json"), JSON.stringify(settings)); + } + + it("passes the settings gateway and helper when the source has no connection or auth values", () => { + const env = { ANTHROPIC_BASE_URL: "https://gateway.example" }; + writeSettings({ apiKeyHelper, env }); + expect(claude.hostConfig?.(sourceEnv)?.environmentDefaults).toEqual(env); + expect(launchSettings(argv({}, null, sourceEnv))).toEqual({ apiKeyHelper }); + }); + + it("leaves the settings gateway, token, and helper out when the source has an API key", () => { + writeSettings({ + apiKeyHelper, + env: { ANTHROPIC_BASE_URL: "https://gateway.example", ANTHROPIC_AUTH_TOKEN: "settings-token" }, + }); + const source = { ...sourceEnv, ANTHROPIC_API_KEY: "source-key" }; + expect(claude.hostConfig?.(source)).toEqual({ environmentDefaults: {}, settings: {} }); + expect(argv({}, null, source)).not.toContain("--settings"); + }); + + it("merges helper and sandbox into one inline settings object for a writer", () => { + writeSettings({ apiKeyHelper }); + const writer = { mode: "isolated-write" }; + const args = argv(writer, "/repo/.git", sourceEnv); + expect(args.filter((arg) => arg === "--settings")).toHaveLength(1); + expect(launchSettings(args)).toEqual({ + apiKeyHelper, + sandbox: { + enabled: true, + autoAllowBashIfSandboxed: true, + allowUnsandboxedCommands: false, + failIfUnavailable: true, + filesystem: { denyWrite: ["/repo/.git"] }, + }, + }); + }); + + for (const key of ["ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY"]) { + it(`omits the helper when ${key} is set in the source or settings env`, () => { + writeSettings({ apiKeyHelper }); + expect(argv({}, null, { ...sourceEnv, [key]: "source-auth" })).toEqual(argv()); + writeSettings({ apiKeyHelper, env: { [key]: "settings-auth" } }); + expect(argv({}, null, sourceEnv)).toEqual(argv()); + }); + } + + it("keeps the existing argv without a settings file or a non-empty string helper", () => { + const writer = { mode: "isolated-write" }; + expect(argv({}, null, sourceEnv)).toEqual(argv()); + for (const apiKeyHelper of [undefined, "", 42]) { + writeSettings({ apiKeyHelper }); + expect(argv({}, null, sourceEnv)).toEqual(argv()); + expect(argv(writer, null, sourceEnv)).toEqual(argv(writer)); + } + }); +}); + describe("claude parse", () => { it("extracts Claude text, model, usage, cost, and session", () => { expect(parse(JSON.stringify({ @@ -176,6 +266,69 @@ describe("claude parse", () => { }); }); +describe("claude Bash sandbox startup failure", () => { + const sandboxFailed = (line: string) => ({ + kind: "provider-failure", + status: "child-failed", + message: `claude could not start its Bash sandbox: ${line}`, + metadata: { reportedModel: "claude-fable-9-9", sessionId: "s1" }, + }); + const bwrap = "bwrap: No permissions to create new namespace"; + + for (const { name, events, mode, expected } of [ + { + name: "apply-seccomp string content", + events: [toolUse("b1"), toolResult("b1", `Exit code 1\n${seccomp}`)], + expected: sandboxFailed(seccomp), + }, + { + name: "bwrap text-block content", + events: [toolUse("b1"), toolResult("b1", [{ type: "text", text: ` ${bwrap}\nmore` }])], + expected: sandboxFailed(bwrap), + }, + { + name: "read-only lane", + events: [toolUse("b1"), toolResult("b1", seccomp)], + mode: "read-only" as const, + expected: sandboxFailed(seccomp), + }, + { + name: "mixed success and failure", + events: [toolUse("b1"), toolResult("b1", seccomp), toolUse("b2"), toolResult("b2", "ok", false)], + expected: { kind: "complete" }, + }, + { + name: "mixed sandbox startup failure and ordinary Bash error", + events: [ + toolUse("b1"), toolResult("b1", seccomp), + toolUse("b2"), toolResult("b2", "Exit code 1\nno matches"), + ], + expected: { kind: "complete", text: terminal.result }, + }, + { + name: "two sandbox startup failures", + events: [toolUse("b1"), toolResult("b1", seccomp), toolUse("b2"), toolResult("b2", bwrap)], + expected: sandboxFailed(seccomp), + }, + { + name: "ordinary Bash error", + events: [toolUse("b1"), toolResult("b1", "Exit code 2\nls: missing: No such file or directory")], + expected: { kind: "complete" }, + }, + { name: "no tool calls", events: [], expected: { kind: "complete" } }, + { + name: "non-Bash tool error", + events: [toolUse("r1", "Read"), toolResult("r1", bwrap)], + expected: { kind: "complete" }, + }, + ]) { + it(`classifies ${name}`, () => { + expect(parse(JSON.stringify([...events, terminal]), { mode: mode ?? "isolated-write" })) + .toMatchObject(expected); + }); + } +}); + describe("claude model proof", () => { it("matches only concrete Claude revisions from the requested rolling family", () => { const fable = lane(); diff --git a/plugins/pstack/skills/poteto-mode/scripts/runner/providers/claude.ts b/plugins/pstack/skills/poteto-mode/scripts/runner/providers/claude.ts index 973ed423..baf475fe 100644 --- a/plugins/pstack/skills/poteto-mode/scripts/runner/providers/claude.ts +++ b/plugins/pstack/skills/poteto-mode/scripts/runner/providers/claude.ts @@ -1,5 +1,7 @@ -import { adapter, isRevision, type Lane, type ParseResult } from "../registry/contract.ts"; -import type { AccessMode } from "../types.ts"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { adapter, isRevision, type Lane, type LaunchHostConfig, type ParseResult } from "../registry/contract.ts"; +import { type AccessMode, evidence } from "../types.ts"; import { effortArgs, exactOrSuffixed, @@ -25,19 +27,39 @@ function tools(mode: AccessMode): string { } // Writers run Bash without prompts inside the OS sandbox, which confines writes to the cwd and a -// per-user temp directory. The model cannot opt a command out, and Claude refuses to start when -// the sandbox is unavailable. A linked worktree's shared git directory is otherwise writable, so -// run.ts passes its literal path, which discoverSharedGitDir checked for glob characters. -function permissions(mode: AccessMode, sharedGitDir: string | null): string[] { - if (mode === "read-only") return ["--permission-mode", "plan"]; - const sandbox = { +// per-user temp directory. The model cannot opt a command out. When the sandbox is unavailable, +// Claude still exits 0 but every Bash call fails with an `apply-seccomp:` or `bwrap:` line, which +// only the verbose event array exposes; parse reports that as child-failed. A linked worktree's +// shared git directory is otherwise writable, so run.ts passes its literal path, which +// discoverSharedGitDir checked for glob characters. +function permissions( + mode: AccessMode, + sharedGitDir: string | null, + settings: LaunchHostConfig["settings"] = {} +): string[] { + const sandbox = mode === "read-only" ? undefined : { enabled: true, autoAllowBashIfSandboxed: true, allowUnsandboxedCommands: false, failIfUnavailable: true, ...(sharedGitDir === null ? {} : { filesystem: { denyWrite: [sharedGitDir] } }), }; - return ["--permission-mode", "acceptEdits", "--settings", JSON.stringify({ sandbox })]; + const args = ["--permission-mode", mode === "read-only" ? "plan" : "acceptEdits"]; + if (sandbox !== undefined || Object.keys(settings).length > 0) { + args.push("--settings", JSON.stringify({ sandbox, ...settings })); + } + return args; +} + +function receiptArgv(argv: readonly string[]): readonly string[] { + const settingsIndex = argv.indexOf("--settings", argv.indexOf("--model") + 2) + 1; + const raw = argv[settingsIndex]; + if (settingsIndex === 0 || raw === undefined) return argv; + const settings = object(JSON.parse(raw)); + if (settings?.apiKeyHelper === undefined) return argv; + return argv.map((arg, index) => index === settingsIndex + ? JSON.stringify({ ...settings, apiKeyHelper: "[redacted]" }) + : arg); } function loggedIn(stdout: string): boolean { @@ -53,6 +75,44 @@ function matches(lane: Lane, reported: string): boolean { return rolling === null ? exactOrSuffixed(lane, reported) : isRevision(rolling, reported); } +function blocks(event: JsonObject | null, type: string): JsonObject[] { + const content = object(event?.message)?.content; + if (!Array.isArray(content)) return []; + return content.map(object).filter((block): block is JsonObject => block?.type === type); +} + +function resultText(content: unknown): string { + if (typeof content === "string") return content; + if (!Array.isArray(content)) return ""; + return content + .map(object) + .map((block) => block?.type === "text" && typeof block.text === "string" ? block.text : "") + .join("\n"); +} + +const SANDBOX_START_FAILURE = /(?:^|\n)\s*((?:apply-seccomp|bwrap): [^\n]*)/; + +function sandboxStartFailure(events: readonly unknown[]): string | null { + const bashIds = new Set( + events + .map(object) + .filter((event) => event?.type === "assistant") + .flatMap((event) => blocks(event, "tool_use")) + .filter((block) => block.name === "Bash") + .map((block) => block.id) + ); + const bashResults = events + .map(object) + .filter((event) => event?.type === "user") + .flatMap((event) => blocks(event, "tool_result")) + .filter((block) => bashIds.has(block.tool_use_id)); + const [firstLine, ...remainingLines] = bashResults.map((block) => + block.is_error === true ? SANDBOX_START_FAILURE.exec(resultText(block.content))?.[1] : undefined + ); + if (firstLine === undefined || remainingLines.some((line) => line === undefined)) return null; + return evidence(firstLine); +} + function parse(stdout: string, lane: Lane): ParseResult { const malformed = (message: string): ParseResult => ({ kind: "malformed", message }); let raw: unknown; @@ -77,15 +137,71 @@ function parse(stdout: string, lane: Lane): ParseResult { const text = nullableString(value.result); if (text === null) return malformed("claude result did not contain final text"); + const metadata = { + reportedModel: modelFromUsage(value.modelUsage, lane, matches), + sessionId: nullableString(value.session_id ?? value.sessionId), + usage: normalizedUsage(value.usage), + costUsd: finiteNumber(value.total_cost_usd) ?? null, + }; + const sandboxFailure = Array.isArray(raw) ? sandboxStartFailure(raw) : null; + if (sandboxFailure !== null) { + return { + kind: "provider-failure", + status: "child-failed", + message: `claude could not start its Bash sandbox: ${sandboxFailure}`, + metadata, + }; + } + return { kind: "complete", text, metadata }; +} + +const CONNECTION_KEYS = ["ANTHROPIC_BASE_URL", "ANTHROPIC_AUTH_TOKEN"] as const; +const AUTH_KEYS = ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN"] as const; + +function configHome(source: NodeJS.ProcessEnv): string | null { + if (source.CLAUDE_CONFIG_DIR) return source.CLAUDE_CONFIG_DIR; + return source.HOME ? join(source.HOME, ".claude") : null; +} + +function readClaudeSettings(source: NodeJS.ProcessEnv): JsonObject | null { + const home = configHome(source); + if (home === null) return null; + const path = join(home, "settings.json"); + let text: string; + try { + text = readFileSync(path, "utf8"); + } catch (error) { + const code = error instanceof Error && "code" in error ? error.code : undefined; + if (code === "ENOENT") return null; + throw new Error(`could not read Claude settings ${path}: ${code}`); + } + try { + return object(JSON.parse(text)); + } catch { + throw new Error(`Claude settings ${path} are not valid JSON`); + } +} + +function connectionDefaults(env: JsonObject | null): Record { + return Object.fromEntries( + CONNECTION_KEYS.flatMap((key) => { + const value = nullableString(env?.[key]); + return value === null ? [] : [[key, value]]; + }) + ); +} + +// `--setting-sources project` excludes the user settings, including gateway configuration. +function hostConfig(source: NodeJS.ProcessEnv): LaunchHostConfig { + const hasSourceAuth = AUTH_KEYS.some((key) => source[key] !== undefined); + const useSettings = !hasSourceAuth && !CONNECTION_KEYS.some((key) => source[key] !== undefined); + const config = useSettings ? readClaudeSettings(source) : null; + const env = object(config?.env); + const hasSettingsAuth = AUTH_KEYS.some((key) => nullableString(env?.[key]) !== null); + const apiKeyHelper = hasSettingsAuth ? null : nullableString(config?.apiKeyHelper); return { - kind: "complete", - text, - metadata: { - reportedModel: modelFromUsage(value.modelUsage, lane, matches), - sessionId: nullableString(value.session_id ?? value.sessionId), - usage: normalizedUsage(value.usage), - costUsd: finiteNumber(value.total_cost_usd) ?? null, - }, + environmentDefaults: connectionDefaults(env), + settings: apiKeyHelper === null ? {} : { apiKeyHelper }, }; } @@ -110,7 +226,7 @@ export const claude = adapter({ "--model", lane.model, ...effortArgs(lane, ["--effort", lane.effort]), - ...permissions(lane.access.mode, facts.sharedGitDir), + ...permissions(lane.access.mode, facts.sharedGitDir, facts.hostConfig?.settings), "--setting-sources", "project", "--strict-mcp-config", @@ -122,7 +238,9 @@ export const claude = adapter({ deniedTools(lane.access.mode), "--output-format", "json", + "--verbose", ], + receiptArgv, }, parse: (run, lane) => parse(run.stdout, lane), proof: { report: "required", matches }, @@ -130,10 +248,15 @@ export const claude = adapter({ kind: "inherit", dropPrefixes: access.mode === "isolated-write" ? ["GIT_"] : [], }), + hostConfig, docs: { name: "Claude Code CLI", hostPrerequisites: [], statePaths: ["the Claude config home (`CLAUDE_CONFIG_DIR`, else `~/.claude`)"], - notes: [], + notes: [ + "`--verbose` makes Claude emit its event array, so the runner reports `child-failed` when every Bash call fails to start its sandbox (`apply-seccomp:` or `bwrap:`).", + "The runner passes `ANTHROPIC_BASE_URL` and `ANTHROPIC_AUTH_TOKEN` from the `env` of `settings.json` in the Claude config home only when the shell sets none of `ANTHROPIC_BASE_URL`, `ANTHROPIC_AUTH_TOKEN`, or `ANTHROPIC_API_KEY`.", + "When the runner uses those settings, it also forwards `apiKeyHelper` if the settings `env` supplies neither `ANTHROPIC_API_KEY` nor `ANTHROPIC_AUTH_TOKEN`.", + ], }, }); diff --git a/plugins/pstack/skills/poteto-mode/scripts/runner/registry/contract.ts b/plugins/pstack/skills/poteto-mode/scripts/runner/registry/contract.ts index bba1d21e..1e0f6497 100644 --- a/plugins/pstack/skills/poteto-mode/scripts/runner/registry/contract.ts +++ b/plugins/pstack/skills/poteto-mode/scripts/runner/registry/contract.ts @@ -100,8 +100,14 @@ export type EnvPolicy = } | { readonly kind: "inherit"; readonly dropPrefixes: readonly string[] }; +export interface LaunchHostConfig { + readonly environmentDefaults: Readonly>; + readonly settings: Readonly>; +} + export interface LaunchFacts { readonly sharedGitDir: string | null; + readonly hostConfig?: LaunchHostConfig; readonly providerSidecar: { readonly directory: string; readonly output: string | null; @@ -134,6 +140,7 @@ export interface ProviderAdapter { stdinEnvelope?(prompt: string): string; needsSharedGitDir(access: Access): boolean; argv(lane: Lane, facts: LaunchFacts): readonly string[]; + receiptArgv?(argv: readonly string[]): readonly string[]; }; parse(run: ModelRun, lane: Lane): ParseResult; readonly proof: { @@ -141,6 +148,8 @@ export interface ProviderAdapter { matches(lane: Lane, reported: string): boolean; }; environment(access: Access, sidecarDir: string | null): EnvPolicy; + /** Read host settings once per launch. Inherited and policy-set variables override the defaults. */ + hostConfig?(source: NodeJS.ProcessEnv): LaunchHostConfig; readonly docs: { readonly name: string; readonly hostPrerequisites: readonly string[]; diff --git a/plugins/pstack/skills/poteto-mode/scripts/runner/run.test.ts b/plugins/pstack/skills/poteto-mode/scripts/runner/run.test.ts index 0cf0b7a1..69690331 100644 --- a/plugins/pstack/skills/poteto-mode/scripts/runner/run.test.ts +++ b/plugins/pstack/skills/poteto-mode/scripts/runner/run.test.ts @@ -28,6 +28,7 @@ import type { AccessKind, RunnerReceipt } from "./types.ts"; let scratch = ""; let bin = ""; let previousPath: string | undefined; +let previousClaudeConfigDir: string | undefined; function streamPath(path: string | null): string { if (path === null) throw new Error("expected a reserved stream artifact path"); @@ -270,6 +271,8 @@ beforeEach(() => { for (const name of ["claude", "codex", "grok"]) makeExecutable(name); previousPath = process.env.PATH; process.env.PATH = `${bin}:${dirname(process.execPath)}:${previousPath ?? ""}`; + previousClaudeConfigDir = process.env.CLAUDE_CONFIG_DIR; + process.env.CLAUDE_CONFIG_DIR = join(scratch, "claude-config"); delete process.env.GROK_FAKE_TIMEOUT; delete process.env.GROK_FAKE_INVALID_MODEL; delete process.env.GROK_FAKE_CANCEL; @@ -297,6 +300,11 @@ beforeEach(() => { afterEach(() => { process.env.PATH = previousPath; + if (previousClaudeConfigDir === undefined) { + delete process.env.CLAUDE_CONFIG_DIR; + } else { + process.env.CLAUDE_CONFIG_DIR = previousClaudeConfigDir; + } delete process.env.GROK_FAKE_TIMEOUT; delete process.env.GROK_FAKE_INVALID_MODEL; delete process.env.GROK_FAKE_CANCEL; @@ -325,13 +333,21 @@ afterEach(() => { describe("Codex parent sandbox diagnostics", () => { let previousNetworkDisabled: string | undefined; + let previousForceColor: string | undefined; beforeEach(() => { previousNetworkDisabled = process.env.CODEX_SANDBOX_NETWORK_DISABLED; delete process.env.CODEX_SANDBOX_NETWORK_DISABLED; + previousForceColor = process.env.FORCE_COLOR; + process.env.FORCE_COLOR = "1"; }); afterEach(() => { + if (previousForceColor === undefined) { + delete process.env.FORCE_COLOR; + } else { + process.env.FORCE_COLOR = previousForceColor; + } if (previousNetworkDisabled === undefined) { delete process.env.CODEX_SANDBOX_NETWORK_DISABLED; } else { @@ -352,7 +368,7 @@ writeFileSync(${JSON.stringify(invoked)}, JSON.stringify({ argv: process.argv.slice(2), networkDisabled: process.env.CODEX_SANDBOX_NETWORK_DISABLED ?? null, })); -console.error("ENOTFOUND api.anthropic.com"); +process.stderr.write("ENOTFOUND api.anthropic.com\\n"); process.exit(1); `); const input = options("claude"); @@ -386,7 +402,7 @@ if (process.argv[2] === "auth") { console.log(JSON.stringify({ loggedIn: true })); process.exit(0); } -console.error("ENOTFOUND api.anthropic.com; EACCES local-state"); +process.stderr.write("ENOTFOUND api.anthropic.com; EACCES local-state\\n"); process.exit(1); `); const result = await runLane(laneOf(options("claude"))); @@ -1669,6 +1685,35 @@ const startedPath =`)); expect(existsSync(input.outputPath)).toBe(false); }); + it("fails a Claude writer whose every Bash call could not start the sandbox", async () => { + const shared = join(scratch, "repo"); + const lane = join(scratch, "lane"); + gitRepository(gitEnv(), shared); + git(gitEnv(), "-C", shared, "worktree", "add", "-q", "-b", "lane", lane); + const seccomp = "apply-seccomp: failed to apply seccomp filter: Operation not permitted"; + const events = [ + { type: "assistant", message: { content: [{ type: "tool_use", id: "b1", name: "Bash", input: {} }] } }, + { type: "user", message: { content: [{ type: "tool_result", tool_use_id: "b1", content: seccomp, is_error: true }] } }, + { type: "result", is_error: false, result: "Done.", session_id: "c1", modelUsage: { "claude-fable-9-9": {} } }, + ]; + writeFileSync(join(bin, "claude"), `#!/usr/bin/env bun +if (process.argv[2] === "auth") { + console.log(JSON.stringify({ loggedIn: true })); + process.exit(0); +} +process.stdout.write(${JSON.stringify(JSON.stringify(events))}); +process.exit(0); +`); + const input = { ...options("claude"), mode: "isolated-write" as const, cwd: lane }; + const result = await runLane(laneOf(input)); + expect(result.exitCode).toBe(70); + expect(result.receipt.status).toBe("child-failed"); + expect(result.receipt.error?.evidence).toStartWith(`claude could not start its Bash sandbox: ${seccomp}`); + expect(result.receipt.error?.evidence?.length).toBeLessThanOrEqual(4_000); + expect(result.receipt.reportedModel).toBe("claude-fable-9-9"); + expect(existsSync(input.outputPath)).toBe(false); + }); + it("rejects same-provider recursion", () => { const input = { ...options("claude"), parent: "claude" as const }; expect(() => laneOf(input)).toThrow("native to parent"); @@ -2105,6 +2150,182 @@ describe("childEnvironment", () => { }); }); +describe("Claude settings fallback", () => { + const BASE_URL = "https://gateway.example"; + const TOKEN = "sk-settings-token-123"; + const claudeLane = () => laneOf({ ...options("claude"), mode: "read-only" }); + const writeSettings = (home: string, content: string): void => { + mkdirSync(home, { recursive: true }); + writeFileSync(join(home, "settings.json"), content); + }; + const settings = (env: Record): string => JSON.stringify({ env }); + let saved: Record = {}; + + beforeEach(() => { + saved = { + ANTHROPIC_BASE_URL: process.env.ANTHROPIC_BASE_URL, + ANTHROPIC_AUTH_TOKEN: process.env.ANTHROPIC_AUTH_TOKEN, + ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY, + }; + delete process.env.ANTHROPIC_BASE_URL; + delete process.env.ANTHROPIC_AUTH_TOKEN; + delete process.env.ANTHROPIC_API_KEY; + }); + + afterEach(() => { + for (const [key, value] of Object.entries(saved)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + }); + + it("copies only the connection pair from settings env", () => { + const home = join(scratch, "config"); + writeSettings(home, settings({ + ANTHROPIC_BASE_URL: BASE_URL, + ANTHROPIC_AUTH_TOKEN: TOKEN, + ANTHROPIC_API_KEY: "api-key", + OTHER: "other", + })); + expect(childEnvironment(claudeLane(), { PATH: "/bin", CLAUDE_CONFIG_DIR: home })).toEqual({ + PATH: "/bin", + CLAUDE_CONFIG_DIR: home, + ANTHROPIC_BASE_URL: BASE_URL, + ANTHROPIC_AUTH_TOKEN: TOKEN, + }); + }); + + it("prefers CLAUDE_CONFIG_DIR over HOME/.claude", () => { + const home = join(scratch, "home"); + const config = join(scratch, "config"); + writeSettings(join(home, ".claude"), settings({ ANTHROPIC_BASE_URL: "https://home.example" })); + writeSettings(config, settings({ ANTHROPIC_BASE_URL: BASE_URL })); + expect(childEnvironment(claudeLane(), { HOME: home, CLAUDE_CONFIG_DIR: config }).ANTHROPIC_BASE_URL) + .toBe(BASE_URL); + expect(childEnvironment(claudeLane(), { HOME: home }).ANTHROPIC_BASE_URL) + .toBe("https://home.example"); + }); + + it("uses no settings value when the source sets either connection key", () => { + const home = join(scratch, "config"); + writeSettings(home, settings({ ANTHROPIC_BASE_URL: BASE_URL, ANTHROPIC_AUTH_TOKEN: TOKEN })); + expect(childEnvironment(claudeLane(), { CLAUDE_CONFIG_DIR: home, ANTHROPIC_BASE_URL: "https://shell.example" })) + .toEqual({ CLAUDE_CONFIG_DIR: home, ANTHROPIC_BASE_URL: "https://shell.example" }); + expect(childEnvironment(claudeLane(), { CLAUDE_CONFIG_DIR: home, ANTHROPIC_AUTH_TOKEN: "shell-token" })) + .toEqual({ CLAUDE_CONFIG_DIR: home, ANTHROPIC_AUTH_TOKEN: "shell-token" }); + }); + + it("keeps the environment unchanged without a settings file or HOME", () => { + const missing = { PATH: "/bin", CLAUDE_CONFIG_DIR: join(scratch, "absent") }; + expect(childEnvironment(claudeLane(), missing)).toEqual(missing); + expect(childEnvironment(claudeLane(), { PATH: "/bin" })).toEqual({ PATH: "/bin" }); + }); + + it("refuses invalid settings JSON without echoing its bytes", () => { + const home = join(scratch, "config"); + writeSettings(home, `{"env":{"ANTHROPIC_AUTH_TOKEN":"sk-secret-123"`); + let message = ""; + try { + childEnvironment(claudeLane(), { CLAUDE_CONFIG_DIR: home }); + } catch (error) { + message = (error as Error).message; + } + expect(message).toBe(`Claude settings ${join(home, "settings.json")} are not valid JSON`); + expect(message).not.toContain("sk-secret"); + }); + + it("ignores non-string and empty settings values", () => { + const home = join(scratch, "config"); + writeSettings(home, settings({ ANTHROPIC_BASE_URL: 42, ANTHROPIC_AUTH_TOKEN: "" })); + expect(childEnvironment(claudeLane(), { CLAUDE_CONFIG_DIR: home })).toEqual({ CLAUDE_CONFIG_DIR: home }); + writeSettings(home, JSON.stringify({ env: [BASE_URL] })); + expect(childEnvironment(claudeLane(), { CLAUDE_CONFIG_DIR: home })).toEqual({ CLAUDE_CONFIG_DIR: home }); + }); + + it("leaves Codex and Grok lanes unaffected and still strips parent identity", () => { + const home = join(scratch, "config"); + writeSettings(home, settings({ ANTHROPIC_BASE_URL: BASE_URL, ANTHROPIC_AUTH_TOKEN: TOKEN })); + const source = { PATH: "/bin", CLAUDE_CONFIG_DIR: home }; + expect(childEnvironment(laneOf({ ...options("codex"), mode: "read-only" }), source)).toEqual(source); + expect(childEnvironment(laneOf({ ...options("grok"), mode: "read-only" }), source)).toEqual({ PATH: "/bin" }); + expect(childEnvironment(claudeLane(), { ...source, CODEX_THREAD_ID: "parent" })).toEqual({ + ...source, + ANTHROPIC_BASE_URL: BASE_URL, + ANTHROPIC_AUTH_TOKEN: TOKEN, + }); + }); + + it("gives preflight and the model call the settings pair without recording the token", async () => { + const seen = join(scratch, "seen.jsonl"); + writeSettings(process.env.CLAUDE_CONFIG_DIR!, settings({ ANTHROPIC_BASE_URL: BASE_URL, ANTHROPIC_AUTH_TOKEN: TOKEN })); + writeFileSync(join(bin, "claude"), `#!/usr/bin/env bun +import { appendFileSync } from "node:fs"; +appendFileSync(${JSON.stringify(seen)}, JSON.stringify({ + stage: process.argv[2] === "auth" ? "preflight" : "model", + baseUrl: process.env.ANTHROPIC_BASE_URL ?? null, + token: process.env.ANTHROPIC_AUTH_TOKEN ?? null, +}) + "\\n"); +if (process.argv[2] === "auth") { + console.log(JSON.stringify({ loggedIn: true })); + process.exit(0); +} +console.log(JSON.stringify({ result: "CLAUDE_OK", modelUsage: { "claude-fable-9-9": {} } })); +`); + const input = options("claude"); + const result = await runLane(laneOf(input)); + expect(result.receipt.status).toBe("complete"); + const calls = readFileSync(seen, "utf8").trim().split("\n").map((line) => JSON.parse(line)); + expect(calls).toEqual([ + { stage: "preflight", baseUrl: BASE_URL, token: TOKEN }, + { stage: "model", baseUrl: BASE_URL, token: TOKEN }, + ]); + expect(readFileSync(input.receiptPath, "utf8")).not.toContain(TOKEN); + expect(readFileSync(streamPath(result.receipt.stdoutPath), "utf8")).not.toContain(TOKEN); + expect(readFileSync(streamPath(result.receipt.stderrPath), "utf8")).not.toContain(TOKEN); + }); + + it("fails the lane before preflight when settings JSON is invalid", async () => { + writeSettings(process.env.CLAUDE_CONFIG_DIR!, `{"env":{"ANTHROPIC_AUTH_TOKEN":"${TOKEN}"`); + const preflightStarted = join(scratch, "preflight.started"); + process.env.GROK_FAKE_PREFLIGHT_STARTED_PATH = preflightStarted; + const input = options("claude"); + const result = await runLane(laneOf(input)); + expect(result.exitCode).toBe(70); + expect(result.receipt.status).toBe("child-failed"); + expect(result.receipt.preflight.status).toBe("not-run"); + expect(result.receipt.error?.evidence) + .toBe(`Claude settings ${join(process.env.CLAUDE_CONFIG_DIR!, "settings.json")} are not valid JSON`); + expect(readFileSync(input.receiptPath, "utf8")).not.toContain(TOKEN); + expect(existsSync(preflightStarted)).toBe(false); + expect(existsSync(input.outputPath)).toBe(false); + }); + + it("launches a Claude model with the settings helper and omits its command from the receipt", async () => { + const apiKeyHelper = "/example/claude-auth"; + writeSettings(process.env.CLAUDE_CONFIG_DIR!, JSON.stringify({ + apiKeyHelper, env: { ANTHROPIC_BASE_URL: BASE_URL }, + })); + const executable = join(bin, "claude"); + writeFileSync(executable, `#!/usr/bin/env bun +const args = process.argv.slice(2); +if (args[0] === "auth") { + console.log(JSON.stringify({ loggedIn: true })); + process.exit(0); +} +const settings = JSON.parse(args[args.indexOf("--settings") + 1] ?? "{}"); +if (settings.apiKeyHelper !== ${JSON.stringify(apiKeyHelper)} || + process.env.ANTHROPIC_BASE_URL !== ${JSON.stringify(BASE_URL)}) process.exit(1); +console.log(JSON.stringify([{ type: "result", result: "CLAUDE_OK", modelUsage: { "claude-fable-9-9": {} } }])); +`); + const input = options("claude"); + const result = await runLane(laneOf(input)); + expect(result.exitCode).toBe(0); + expect(result.receipt).toMatchObject({ status: "complete", modelVerified: true }); + expect(result.receipt.argv).toContain(JSON.stringify({ apiKeyHelper: "[redacted]" })); + expect(readFileSync(input.receiptPath, "utf8")).not.toContain(apiKeyHelper); + }); +}); + describe("discoverSharedGitDir", () => { const cancellation = { promise: new Promise(() => {}), signal: null, dispose() {} }; diff --git a/plugins/pstack/skills/poteto-mode/scripts/runner/run.ts b/plugins/pstack/skills/poteto-mode/scripts/runner/run.ts index b6c22987..7c8172a7 100644 --- a/plugins/pstack/skills/poteto-mode/scripts/runner/run.ts +++ b/plugins/pstack/skills/poteto-mode/scripts/runner/run.ts @@ -171,13 +171,15 @@ function installRunCancellation(): RunCancellation { export function childEnvironment( lane: Lane, - source: NodeJS.ProcessEnv = process.env + source: NodeJS.ProcessEnv = process.env, + hostConfig: LaunchFacts["hostConfig"] = lane.adapter.hostConfig?.(source) ): NodeJS.ProcessEnv { const policy = lane.adapter.environment(lane.access, providerSidecar(lane)?.facts.directory ?? null); const keep = policy.kind === "allowlist" ? (key: string) => policy.names.includes(key) || policy.prefixes.some((prefix) => key.startsWith(prefix)) : (key: string) => !policy.dropPrefixes.some((prefix) => key.startsWith(prefix)); const result = { + ...hostConfig?.environmentDefaults, ...Object.fromEntries(Object.entries(source).filter(([key]) => keep(key))), ...(policy.kind === "allowlist" ? policy.set : undefined), }; @@ -586,6 +588,7 @@ function completeReceipt( outputPath: lane.outputPath, ...modelStreamPaths(lane.receiptPath), ...partial, + argv: lane.adapter.launch.receiptArgv?.(partial.argv) ?? partial.argv, }; } @@ -630,7 +633,11 @@ async function executeLane( const prompt = readFileSync(lane.promptPath, "utf8"); const parentNetworkDisabled = lane.parent === "codex" && process.env.CODEX_SANDBOX_NETWORK_DISABLED === "1"; - const env = childEnvironment(lane); + const source = process.env; + const hostConfig = adapter.hostConfig?.(source); + const env = childEnvironment(lane, source, hostConfig); + const facts = { sharedGitDir: null, providerSidecar: providerSidecar(lane)?.facts ?? null, hostConfig }; + if (hostConfig !== undefined) launchArgs = adapter.launch.argv(lane, facts); const executable = Bun.which(adapter.executable, { PATH: env.PATH, cwd: lane.cwd, @@ -741,8 +748,7 @@ async function executeLane( writeReceipt(lane.receiptPath, receipt); return { exitCode: statusExitCode(discovery.status), receipt }; } - const facts: LaunchFacts = { sharedGitDir: discovery.sharedGitDir, providerSidecar: providerSidecar(lane)?.facts ?? null }; - launchArgs = adapter.launch.argv(lane, facts); + launchArgs = adapter.launch.argv(lane, { ...facts, sharedGitDir: discovery.sharedGitDir }); progress.argv = [executable, ...launchArgs]; }