Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

feat(example-provider): run against a custom LLM configured in `.env`

0xken1549ef7d684d6e
diff --git a/.gitignore b/.gitignore
index b06b66722..8802b232b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -5,6 +5,10 @@ dist/
# Per-deployment state, never source:
# agents.json names real directories on the machine it runs on
-# sessions.json maps A2A contextIds to Claude session ids
+# sessions.json maps agent ids to Claude session ids
+# .env HOLDS A CREDENTIAL — the provider's ANTHROPIC_AUTH_TOKEN
provider/example-provider/agents.json
provider/example-provider/sessions.json
+.env
+.env.*
+!.env.example
diff --git a/provider/README.md b/provider/README.md
index 053e0d757..0a2e069ce 100644
--- a/provider/README.md
+++ b/provider/README.md
@@ -69,7 +69,9 @@ reference-provider/ zero runtime dependencies — readable end to end
example-provider/ a real agent; runs Claude with permissions skipped ⚠ read its README first
```
-Both packages are plain TypeScript on Node ≥ 20 with **no runtime dependencies**. That is on purpose:
+Both packages are plain TypeScript with **no runtime dependencies** — Node ≥ 20, or ≥ 20.12 for
+`example-provider`, which reads its `.env` with the platform's own `process.loadEnvFile` rather than
+take a dependency on one. That is on purpose:
you should be able to read `reference-provider/src/server.ts` and know exactly what your own endpoint
has to do.
diff --git a/provider/example-provider/.env.example b/provider/example-provider/.env.example
new file mode 100644
index 000000000..48baf795e
--- /dev/null
+++ b/provider/example-provider/.env.example
@@ -0,0 +1,27 @@
+# Copy to .env and fill in. `.env` is gitignored — it holds a real credential.
+#
+# These are the `claude` CLI's own environment variables, so any Anthropic-compatible endpoint works:
+# a gateway in front of another model, a proxy, or the Anthropic API itself.
+#
+# ALL THREE OR NONE. Set none of them and the CLI uses whatever `claude` is logged into locally.
+# Set some but not all and the provider refuses to start — a base URL without a model would otherwise
+# send `claude-sonnet-5` to a gateway that has never heard of it, and you would find out mid-turn,
+# with a user watching, instead of at boot.
+
+ANTHROPIC_BASE_URL=https://my-gateway.example.com
+ANTHROPIC_AUTH_TOKEN=sk-...
+# ANTHROPIC_API_KEY works too — use whichever name your endpoint hands out.
+
+# Must be a model the endpoint above actually serves. It is also what goes to `--model`, so there is
+# only ever one model name in play.
+ANTHROPIC_MODEL=my-custom-model
+
+# Optional. The CLI's small-model slot, used for the per-turn recap one-shot — a headline is not the
+# work, so it does not need the big model. Falls back to CLAUDE_RECAP_MODEL, then the built-in default.
+# ANTHROPIC_SMALL_FAST_MODEL=my-small-model
+
+# Everything below is unrelated to credentials and already had a default; override only if you need to.
+# PORT=4502
+# AGENTS_FILE=./agents.json
+# WORKSPACE_ROOT=/tmp/example-provider-scratch
+# RECAP_DISABLED=1
diff --git a/provider/example-provider/README.md b/provider/example-provider/README.md
index 558e834ad..5495fdf75 100644
--- a/provider/example-provider/README.md
+++ b/provider/example-provider/README.md
@@ -26,6 +26,7 @@ format.
```bash
npm install
cp agents.example.json agents.json # then edit cwd
+cp .env.example .env # optional — see "Which LLM answers" below
mkdir -p /tmp/example-provider-scratch
npm run dev # http://127.0.0.1:4502
```
@@ -38,16 +39,45 @@ curl -N localhost:4502 \
"message":{"text":"what files are here?"}}}'
```
+## Which LLM answers
+
+By default the `claude` CLI uses whatever it is logged into locally, so this example runs with no
+credential setup at all — and two machines running the same code can quietly answer with two different
+models.
+
+To pin it to a specific endpoint, put the CLI's own variables in `.env` (gitignored; copy
+`.env.example`). Any Anthropic-compatible endpoint works — a gateway in front of another model, a
+proxy, or the Anthropic API itself:
+
+```sh
+ANTHROPIC_BASE_URL=https://my-gateway.example.com
+ANTHROPIC_AUTH_TOKEN=sk-... # ANTHROPIC_API_KEY works too
+ANTHROPIC_MODEL=my-custom-model # must be a model that endpoint serves
+```
+
+**All three or none.** Set none and you get the local login. Set some but not all and the provider
+**refuses to start**, naming what is missing — because a base URL without a model would otherwise send
+the default `claude-sonnet-5` to a gateway that has never heard of it, and you would find out during a
+turn with a user watching rather than at boot.
+
+`ANTHROPIC_MODEL` is also what goes to `--model`, so there is only ever one model name in play. A real
+environment variable beats the file, so a one-off run can override `.env` without editing it.
+
| Env | Default |
|---|---|
+| `ANTHROPIC_BASE_URL` | unset — the CLI uses its local login. Set it with a token and a model to pin the endpoint |
+| `ANTHROPIC_AUTH_TOKEN` | unset. `ANTHROPIC_API_KEY` is accepted as an alias |
+| `ANTHROPIC_MODEL` | unset. When set it wins over `CLAUDE_MODEL` and is passed as `--model` |
+| `ANTHROPIC_SMALL_FAST_MODEL` | unset. The CLI's small-model slot; when set it wins over `CLAUDE_RECAP_MODEL` for the recap one-shot |
+| `ENV_FILE` | `./.env` |
| `AGENTS_FILE` | `./agents.json` |
| `CLAUDE_PATH` | resolved via `which claude`, then the usual install locations |
-| `CLAUDE_MODEL` | `claude-sonnet-5`. Pinned, not left to the CLI default: a provider owns its model choice, and Autonomous never sends one |
+| `CLAUDE_MODEL` | `claude-sonnet-5`. Pinned, not left to the CLI default: a provider owns its model choice, and Autonomous never sends one. Overridden by `ANTHROPIC_MODEL` |
| `PORT` | `4502` |
| `STATE_FILE` | `./sessions.json` |
| `WORKSPACE_ROOT` | `/tmp/example-provider-scratch` — where `agent.create` puts a new agent's directory |
| `CLAUDE_PROJECTS_DIR` | `~/.claude/projects` |
-| `CLAUDE_RECAP_MODEL` | `claude-haiku-4-5-20251001` — the per-turn recap is a one-line headline, not the work, so it gets a small model |
+| `CLAUDE_RECAP_MODEL` | `claude-haiku-4-5-20251001` — the per-turn recap is a one-line headline, not the work, so it gets a small model. Overridden by `ANTHROPIC_SMALL_FAST_MODEL` |
| `RECAP_DISABLED` | unset. `1` skips the recap model entirely and excerpts the turn instead |
## How it works
diff --git a/provider/example-provider/package.json b/provider/example-provider/package.json
index b595ea537..104bd73bf 100644
--- a/provider/example-provider/package.json
+++ b/provider/example-provider/package.json
@@ -11,6 +11,9 @@
"homepage": "https://github.com/autonomous-ai/autonomous-harness#readme",
"bugs": "https://github.com/autonomous-ai/autonomous-harness/issues",
"type": "module",
+ "engines": {
+ "node": ">=20.12"
+ },
"scripts": {
"dev": "tsx src/server.ts",
"start": "node dist/server.js",
diff --git a/provider/example-provider/src/claude.ts b/provider/example-provider/src/claude.ts
index 51ade789d..d3bf5bb08 100644
--- a/provider/example-provider/src/claude.ts
+++ b/provider/example-provider/src/claude.ts
@@ -11,6 +11,7 @@
*/
import { spawn, type ChildProcess } from 'node:child_process'
import { createInterface } from 'node:readline'
+import { anthropicSpawnEnv, type AnthropicEnv } from './config.js'
import type { StreamLine } from './mapper.js'
export interface TurnOptions {
@@ -21,6 +22,8 @@ export interface TurnOptions {
/** Present on every turn after the first in a session. */
resumeSessionId?: string
model?: string
+ /** The endpoint and credential to run against. Absent ⇒ the CLI uses its own local login. */
+ anthropic?: AnthropicEnv
signal?: AbortSignal
}
@@ -54,7 +57,9 @@ export function runTurn(opts: TurnOptions, onLine: (line: StreamLine) => void, o
// leaves those orphaned — the same reason brain uses kill(-pid) in oneshot.ts.
detached: true,
stdio: ['pipe', 'pipe', 'pipe'],
- env: { ...process.env },
+ // Credentials LAST, so a configured endpoint wins over whatever the parent shell happens to
+ // export. Absent, this spreads to nothing and the CLI authenticates exactly as it did before.
+ env: { ...process.env, ...anthropicSpawnEnv(opts.anthropic) },
})
let killed = false
diff --git a/provider/example-provider/src/config.spec.ts b/provider/example-provider/src/config.spec.ts
new file mode 100644
index 000000000..925451ba0
--- /dev/null
+++ b/provider/example-provider/src/config.spec.ts
@@ -0,0 +1,90 @@
+// The credential resolver is where a misconfiguration is supposed to become a startup error rather
+// than a failed turn, so these tests are mostly about the REFUSALS, not the happy path.
+import { describe, expect, it } from 'vitest'
+
+const { anthropicSpawnEnv, resolveAnthropicEnv } = await import('./config.js')
+
+const FULL = {
+ ANTHROPIC_BASE_URL: 'https://gateway.example.com',
+ ANTHROPIC_AUTH_TOKEN: 'sk-secret',
+ ANTHROPIC_MODEL: 'my-custom-model',
+}
+
+describe('resolveAnthropicEnv', () => {
+ it('returns nothing when nothing is configured — the local login is a valid setup', () => {
+ // The zero-config path this example shipped with. It must stay reachable, or every reader who
+ // just wants to try the thing has to go find a gateway first.
+ expect(resolveAnthropicEnv({})).toBeUndefined()
+ })
+
+ it('resolves a complete set', () => {
+ expect(resolveAnthropicEnv(FULL)).toEqual({
+ baseUrl: 'https://gateway.example.com',
+ authToken: 'sk-secret',
+ model: 'my-custom-model',
+ })
+ })
+
+ it('accepts ANTHROPIC_API_KEY as the token', () => {
+ // Which of the two names an endpoint hands out is its own business; both authenticate the CLI.
+ const { ANTHROPIC_AUTH_TOKEN, ...rest } = FULL
+ expect(resolveAnthropicEnv({ ...rest, ANTHROPIC_API_KEY: 'sk-other' })?.authToken).toBe('sk-other')
+ })
+
+ it('carries the small-model slot when given, and omits it otherwise', () => {
+ expect(resolveAnthropicEnv({ ...FULL, ANTHROPIC_SMALL_FAST_MODEL: 'tiny' })?.smallFastModel).toBe('tiny')
+ expect('smallFastModel' in resolveAnthropicEnv(FULL)!).toBe(false)
+ })
+
+ it('REFUSES a base URL with no token, and names what is missing', () => {
+ const { ANTHROPIC_AUTH_TOKEN, ...partial } = FULL
+ expect(() => resolveAnthropicEnv(partial)).toThrow(/ANTHROPIC_AUTH_TOKEN/)
+ })
+
+ it('REFUSES a base URL with no model', () => {
+ // The case this rule exists for. Without it the provider starts happily and sends the default
+ // `claude-sonnet-5` to a gateway that does not serve it — a failure that surfaces mid-turn, in
+ // front of a user, instead of at boot in front of whoever is configuring it.
+ const { ANTHROPIC_MODEL, ...partial } = FULL
+ expect(() => resolveAnthropicEnv(partial)).toThrow(/ANTHROPIC_MODEL/)
+ })
+
+ it('REFUSES a token with no endpoint to send it to', () => {
+ expect(() => resolveAnthropicEnv({ ANTHROPIC_AUTH_TOKEN: 'sk-secret' })).toThrow(/ANTHROPIC_BASE_URL/)
+ })
+
+ it('lists EVERY missing variable at once, not just the first', () => {
+ // Reporting them one per restart turns configuration into a guessing game.
+ try {
+ resolveAnthropicEnv({ ANTHROPIC_BASE_URL: 'https://gateway.example.com' })
+ throw new Error('expected a refusal')
+ } catch (err) {
+ const message = (err as Error).message
+ expect(message).toContain('ANTHROPIC_AUTH_TOKEN')
+ expect(message).toContain('ANTHROPIC_MODEL')
+ // …and it says how to get out of the state, not just what is wrong with it.
+ expect(message).toMatch(/\.env|local .?claude.? login/)
+ }
+ })
+
+ it('treats whitespace-only values as absent rather than as configuration', () => {
+ // A trailing-space edit in a .env is not a credential, and quietly accepting one would send an
+ // empty Authorization header to the gateway.
+ expect(() => resolveAnthropicEnv({ ...FULL, ANTHROPIC_AUTH_TOKEN: ' ' })).toThrow(/ANTHROPIC_AUTH_TOKEN/)
+ })
+})
+
+describe('anthropicSpawnEnv', () => {
+ it('spreads to nothing when unconfigured, leaving the CLI exactly as it was', () => {
+ expect(anthropicSpawnEnv(undefined)).toEqual({})
+ })
+
+ it('maps to the CLI’s own variable names', () => {
+ // The one place this mapping lives — both spawn sites call it, so they cannot drift apart.
+ expect(anthropicSpawnEnv(resolveAnthropicEnv(FULL))).toEqual({
+ ANTHROPIC_BASE_URL: 'https://gateway.example.com',
+ ANTHROPIC_AUTH_TOKEN: 'sk-secret',
+ ANTHROPIC_MODEL: 'my-custom-model',
+ })
+ })
+})
diff --git a/provider/example-provider/src/config.ts b/provider/example-provider/src/config.ts
index ff71e57ef..b2c9db4fe 100644
--- a/provider/example-provider/src/config.ts
+++ b/provider/example-provider/src/config.ts
@@ -1,8 +1,8 @@
/**
- * Configuration: the agent list, and how to reach the `claude` binary.
+ * Configuration: the agent list, which LLM to talk to, and how to reach the `claude` binary.
*
- * The agent list is the ONLY per-deployment state. Each entry becomes an `agent.list` entry
- * and carries the working directory `claude` is spawned in.
+ * Two kinds of per-deployment state, both kept out of source: `agents.json` (which directories the
+ * agents own) and `.env` (which model answers, and with whose credential).
*/
import { execFileSync } from 'node:child_process'
import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs'
@@ -18,6 +18,21 @@ export interface AgentEntry {
cwd: string
}
+/**
+ * Credentials for the endpoint `claude` talks to, when one is configured.
+ *
+ * These are the CLI's own environment variables, so pointing it at a different LLM needs no code: any
+ * Anthropic-compatible gateway works. `machine-manager` does exactly this to route managed nodes
+ * through CCR (`resolveManagedAnthropicEnv` in its `lib/docker.ts`).
+ */
+export interface AnthropicEnv {
+ baseUrl: string
+ authToken: string
+ model: string
+ /** The CLI's own small-model slot; used for the recap one-shot. */
+ smallFastModel?: string
+}
+
export interface Config {
agents: AgentEntry[]
/**
@@ -30,7 +45,15 @@ export interface Config {
/** Path to agents.json, so a created agent survives a restart. */
agentsFile: string
claudeBin: string
- /** Passed to `--model`. Never taken from the wire: model selection is out of scope (spec §9). */
+ /**
+ * The endpoint and credential `claude` runs against, or undefined to use its own local login.
+ *
+ * Merged into the environment at BOTH spawn sites (`claude.ts`, `recap.ts`) rather than left in
+ * this process's env, so the credential path is visible from the spawn and a test that builds a
+ * Config without one genuinely gets none instead of inheriting the developer's shell.
+ */
+ anthropic?: AnthropicEnv
+ /** Passed to `--model`. Never taken from the wire: model selection is out of scope. */
model: string
port: number
/** Where sessions.json lives. */
@@ -52,6 +75,70 @@ export interface Config {
*/
export const DEFAULT_MODEL = 'claude-sonnet-5'
+/**
+ * Credentials from the environment, or undefined when none are configured.
+ *
+ * ALL-OR-NOTHING, and it throws rather than shipping a half-configured provider. `machine-manager`
+ * learned this the same way ("partial config ⇒ treated as unset, so we never ship a half-configured
+ * node that fails auth"), and the model is part of the set for a reason specific to this case: a
+ * custom gateway does not serve `claude-sonnet-5`, so a base URL carrying the default model is a
+ * guaranteed failure on the first turn — which is far worse than a failure at startup, because by
+ * then a user is watching.
+ */
+export function resolveAnthropicEnv(source: NodeJS.ProcessEnv = process.env): AnthropicEnv | undefined {
+ const baseUrl = source.ANTHROPIC_BASE_URL?.trim()
+ // Either name works: the CLI accepts both, and which one a gateway hands out is its own business.
+ const authToken = (source.ANTHROPIC_AUTH_TOKEN || source.ANTHROPIC_API_KEY)?.trim()
+ const model = source.ANTHROPIC_MODEL?.trim()
+ const smallFastModel = source.ANTHROPIC_SMALL_FAST_MODEL?.trim()
+
+ // Nothing set at all is a legitimate configuration — the CLI then uses whatever it is logged into.
+ if (!baseUrl && !authToken && !model) return undefined
+
+ const missing = [
+ baseUrl ? '' : 'ANTHROPIC_BASE_URL',
+ authToken ? '' : 'ANTHROPIC_AUTH_TOKEN (or ANTHROPIC_API_KEY)',
+ model ? '' : 'ANTHROPIC_MODEL',
+ ].filter(Boolean)
+ if (missing.length) {
+ throw new Error(
+ `incomplete Anthropic configuration — missing ${missing.join(', ')}.\n` +
+ `Set all three in .env (see .env.example), or none of them to use the local \`claude\` login.`,
+ )
+ }
+
+ return { baseUrl: baseUrl!, authToken: authToken!, model: model!, ...(smallFastModel ? { smallFastModel } : {}) }
+}
+
+/**
+ * The credential set as the CLI's own environment variables.
+ *
+ * The one place the mapping from our config shape to the CLI's variable names lives — both spawn
+ * sites call this, so neither can drift from the other.
+ */
+export function anthropicSpawnEnv(anthropic?: AnthropicEnv): Record<string, string> {
+ if (!anthropic) return {}
+ return {
+ ANTHROPIC_BASE_URL: anthropic.baseUrl,
+ ANTHROPIC_AUTH_TOKEN: anthropic.authToken,
+ ANTHROPIC_MODEL: anthropic.model,
+ ...(anthropic.smallFastModel ? { ANTHROPIC_SMALL_FAST_MODEL: anthropic.smallFastModel } : {}),
+ }
+}
+
+/**
+ * Read `.env` into `process.env`, if there is one.
+ *
+ * `process.loadEnvFile` rather than a dependency: it is the platform's own parser, so this package
+ * keeps its zero-runtime-dependency property and inherits correct handling of quoting and comments.
+ * A variable already set in the real environment WINS over the file — which is the precedence you
+ * want, since it lets one-off runs override the checked-in defaults without editing anything.
+ */
+export function loadEnvFile(file: string): void {
+ if (!existsSync(file)) return
+ process.loadEnvFile(file)
+}
+
/** Agent ids are interpolated into paths and compared against wire input — keep them boring. */
const ID_RE = /^[a-z0-9][a-z0-9-]{0,63}$/
@@ -121,18 +208,25 @@ export function resolveClaudeBin(explicit?: string): string {
}
export function loadConfig(): Config {
+ // Before anything reads process.env — every setting below may come from the file.
+ loadEnvFile(process.env.ENV_FILE ?? resolve(process.cwd(), '.env'))
+
const agentsFile = process.env.AGENTS_FILE ?? resolve(process.cwd(), 'agents.json')
const workspaceRoot = realpathSync(resolve(process.env.WORKSPACE_ROOT ?? '/tmp/example-provider-scratch'))
+ const anthropic = resolveAnthropicEnv()
return {
agents: loadAgents(agentsFile),
workspaceRoot,
agentsFile,
claudeBin: resolveClaudeBin(process.env.CLAUDE_PATH),
- model: process.env.CLAUDE_MODEL || DEFAULT_MODEL,
+ ...(anthropic ? { anthropic } : {}),
+ // ONE source for the model, so the `--model` flag and the CLI's own ANTHROPIC_MODEL can never
+ // name two different models — a disagreement that would be invisible until a turn failed.
+ model: anthropic?.model || process.env.CLAUDE_MODEL || DEFAULT_MODEL,
port: Number(process.env.PORT ?? 4502),
stateFile: process.env.STATE_FILE ?? resolve(process.cwd(), 'sessions.json'),
claudeProjectsDir: process.env.CLAUDE_PROJECTS_DIR ?? `${homedir()}/.claude/projects`,
- recapModel: process.env.CLAUDE_RECAP_MODEL || DEFAULT_RECAP_MODEL,
+ recapModel: anthropic?.smallFastModel || process.env.CLAUDE_RECAP_MODEL || DEFAULT_RECAP_MODEL,
recapDisabled: process.env.RECAP_DISABLED === '1',
}
}
diff --git a/provider/example-provider/src/recap.ts b/provider/example-provider/src/recap.ts
index 4e2b8d621..2b48c39e2 100644
--- a/provider/example-provider/src/recap.ts
+++ b/provider/example-provider/src/recap.ts
@@ -19,6 +19,7 @@
* A recap is a nicety: it must never be able to fail a turn that already succeeded.
*/
import { spawn } from 'node:child_process'
+import { anthropicSpawnEnv, type AnthropicEnv } from './config.js'
/** `recapEntry.recap` is capped at 200 by the schema; the device renders it on one line. */
export const RECAP_MAX_CHARS = 200
@@ -60,6 +61,8 @@ export interface SummariseOptions {
/** The assistant's output for this turn. */
turnText: string
model?: string
+ /** The endpoint and credential to run against. Absent ⇒ the CLI uses its own local login. */
+ anthropic?: AnthropicEnv
/** Skip the model entirely and go straight to the excerpt. */
disabled?: boolean
}
@@ -111,7 +114,9 @@ function oneShot(opts: SummariseOptions): Promise<string> {
opts.claudeBin,
// No --resume, no tools, no permissions flag: this reads text and writes text.
['--model', opts.model ?? DEFAULT_RECAP_MODEL, '--print'],
- { cwd: opts.cwd, stdio: ['pipe', 'pipe', 'ignore'], env: { ...process.env } },
+ // Same endpoint as the turn it summarises — a recap answered by a different model than the
+ // work would be a confusing thing to debug.
+ { cwd: opts.cwd, stdio: ['pipe', 'pipe', 'ignore'], env: { ...process.env, ...anthropicSpawnEnv(opts.anthropic) } },
)
let out = ''
const timer = setTimeout(() => { child.kill('SIGKILL'); reject(new Error('recap timed out')) }, SUMMARY_TIMEOUT_MS)
diff --git a/provider/example-provider/src/server.spec.ts b/provider/example-provider/src/server.spec.ts
index a6030b463..7c2aaee0f 100644
--- a/provider/example-provider/src/server.spec.ts
+++ b/provider/example-provider/src/server.spec.ts
@@ -11,7 +11,7 @@
* implement as something that never terminates.
*/
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
-import { chmodSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'
+import { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import type { AddressInfo } from 'node:net'
@@ -40,6 +40,24 @@ function fakeClaude(name: string, lines: unknown[]): string {
return path
}
+/**
+ * A `claude` that records the environment it was spawned with, then answers normally.
+ *
+ * Asserting on the config object would only prove we stored the credential; the thing that matters is
+ * that the CHILD received it, because that is the whole mechanism — the CLI reads these variables
+ * itself and we never see the request it makes.
+ */
+function envRecordingClaude(name: string, envDump: string, lines: unknown[]): string {
+ const path = join(ROOT, name)
+ const body = lines.map((l) => `echo '${JSON.stringify(l)}'`).join('\n')
+ writeFileSync(
+ path,
+ `#!/bin/sh\ncat > /dev/null\nprintf '%s\\n%s\\n%s\\n' "$ANTHROPIC_BASE_URL" "$ANTHROPIC_AUTH_TOKEN" "$ANTHROPIC_MODEL" > ${envDump}\n${body}\n`,
+ )
+ chmodSync(path, 0o755)
+ return path
+}
+
const textLine = (text: string): unknown => ({
type: 'stream_event',
session_id: CLAUDE_SESSION,
@@ -51,7 +69,7 @@ const resultLine = (failed = false): unknown => ({
...(failed ? { is_error: true, result: 'boom' } : { subtype: 'success', result: 'ok' }),
})
-function config(claudeBin: string): Config {
+function config(claudeBin: string, anthropic?: Config['anthropic']): Config {
return {
agents: [
{ id: 'scratch', name: 'Scratch', description: 'test agent', cwd: AGENT_CWD },
@@ -60,6 +78,7 @@ function config(claudeBin: string): Config {
workspaceRoot: ROOT,
agentsFile: join(ROOT, 'agents.json'),
claudeBin,
+ ...(anthropic ? { anthropic } : {}),
model: 'test-model',
port: 0,
stateFile: join(ROOT, `state-${Math.random().toString(36).slice(2)}.json`),
@@ -75,8 +94,9 @@ function config(claudeBin: string): Config {
async function withServer<T>(
claudeBin: string,
fn: (port: number, deps: ReturnType<typeof createProviderServer>['deps']) => Promise<T>,
+ anthropic?: Config['anthropic'],
): Promise<T> {
- const { server, deps } = createProviderServer(config(claudeBin))
+ const { server, deps } = createProviderServer(config(claudeBin, anthropic))
await new Promise<void>((r) => server.listen(0, '127.0.0.1', r))
const { port } = server.address() as AddressInfo
try {
@@ -179,6 +199,39 @@ describe('agents', () => {
})
})
+describe('the endpoint the CLI runs against', () => {
+ it('hands the configured credentials to the spawned claude', async () => {
+ const envDump = join(ROOT, 'env-dump.txt')
+ const bin = envRecordingClaude('claude-env.sh', envDump, [resultLine()])
+ const anthropic = {
+ baseUrl: 'https://gateway.example.com',
+ authToken: 'sk-from-config',
+ model: 'my-custom-model',
+ }
+ await withServer(bin, async (port) => {
+ await runTurn(port, 'hello')
+ }, anthropic)
+
+ expect(readFileSync(envDump, 'utf8').split('\n').slice(0, 3)).toEqual([
+ 'https://gateway.example.com',
+ 'sk-from-config',
+ 'my-custom-model',
+ ])
+ })
+
+ it('leaves the environment alone when nothing is configured', async () => {
+ // The local-login path. If this ever started injecting an empty ANTHROPIC_BASE_URL, the CLI would
+ // try to reach "" instead of falling back to whatever it is logged into.
+ const envDump = join(ROOT, 'env-dump-bare.txt')
+ const bin = envRecordingClaude('claude-env-bare.sh', envDump, [resultLine()])
+ await withServer(bin, async (port) => {
+ await runTurn(port, 'hello')
+ })
+
+ expect(readFileSync(envDump, 'utf8').split('\n').slice(0, 3)).toEqual(['', '', ''])
+ })
+})
+
describe('a turn on the wire', () => {
it('opens with turn_started and closes with exactly one terminal frame', async () => {
const bin = fakeClaude('claude-basic.sh', [textLine('hello there'), resultLine()])
diff --git a/provider/example-provider/src/server.ts b/provider/example-provider/src/server.ts
index e2475042d..f533942f0 100644
--- a/provider/example-provider/src/server.ts
+++ b/provider/example-provider/src/server.ts
@@ -173,6 +173,7 @@ async function agentSend(res: ServerResponse, deps: Deps, params: Record<string,
text,
resumeSessionId: record.claudeSessionId,
model: deps.config.model,
+ anthropic: deps.config.anthropic,
signal: controller.signal,
},
(line) => {
@@ -258,6 +259,7 @@ async function recapTurn(
cwd: agent.cwd,
turnText,
model: deps.config.recapModel,
+ anthropic: deps.config.anthropic,
disabled: deps.config.recapDisabled,
})
if (recap) deps.store.setRecap(turnId, recap.recap, recap.body)