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.

Move grid assignment to models without delaying discovery or binding (#1076)

Dee67c2e52b7b40
diff --git a/cli/e2e/harness/daemon.ts b/cli/e2e/harness/daemon.ts
index 3bc9a332d..d799653a3 100644
--- a/cli/e2e/harness/daemon.ts
+++ b/cli/e2e/harness/daemon.ts
@@ -37,6 +37,8 @@ export interface EngineConfig {
/** Note every submitted prompt and hold a `!latestart` turn's start at a file gate (submission tests). */
submissionGate?: boolean
codexModel?: string
+ /** Keep the real interpreter/entrypoint argv, so macOS ps can also read the fixture environment. */
+ preserveProcessArgs?: boolean
/** The test's throwaway root: the engine runs no hooks from settings outside it. */
root: string
/** Where the engine notes each hook it ran. */
@@ -64,6 +66,8 @@ export interface DaemonOptions {
/** Note every submitted prompt and hold a `!latestart` turn's start at a file gate (submission tests). */
submissionGate?: boolean
codexModel?: string
+ /** Process-evidence tests need the real entrypoint; Node's process.title hides its env on macOS. */
+ preserveProcessArgs?: boolean
/** Boot the core on its own (`__run`) instead of under harnessd's master (`__harnessd`). */
noMaster?: boolean
/** Start as a supervisor does, `harness start -f`: the master in the foreground, the core its child. */
@@ -219,6 +223,7 @@ export class IsolatedDaemon {
const config: EngineConfig = {
port, dataDir: dirs.data, claudeProjectsDir: dirs.claudeProjects, codexHome: dirs.codexHome,
claudeModel: options.claudeModel, codexModel: options.codexModel, modelControlGate: options.modelControlGate,
+ ...(options.preserveProcessArgs ? { preserveProcessArgs: true } : {}),
...(options.submissionGate ? { submissionGate: true } : {}),
root, hookLog: join(own, 'fake-engine-hooks.log'),
...(options.trustPrompt ? { trustPrompt: true } : {}),
diff --git a/cli/e2e/harness/fakeEngine.mjs b/cli/e2e/harness/fakeEngine.mjs
index 1f7319245..e2cb31a96 100644
--- a/cli/e2e/harness/fakeEngine.mjs
+++ b/cli/e2e/harness/fakeEngine.mjs
@@ -168,7 +168,9 @@ export async function run(engine, config = {}, { native = false } = {}) {
// conversation on that command line). The title used to be the name alone, so no argument was ever on
// the command line discovery read. The name is padded to the 16 columns macOS's `ps` gives a name in a
// table, so the arguments are not read as part of it; a control character is shown as `ps` shows one.
- process.title = [engine.padEnd(16), ...args].join(' ').replace(/[\x00-\x1f\x7f]/g, '?')
+ // Node's title rewrite makes macOS ps omit the environment. Evidence tests keep the interpreter
+ // and its actual engine entrypoint, which discovery also recognizes, so endpoint markers are readable.
+ if (!config.preserveProcessArgs) process.title = [engine.padEnd(16), ...args].join(' ').replace(/[\x00-\x1f\x7f]/g, '?')
// Raw at once, as the real CLIs are (Ink and ratatui take the terminal before they draw anything): a
// terminal still in line mode keeps at most 1 KiB of a line, so a paste that arrived before the
// engine was ready lost the rest of itself (measured: 1,018 of 2,406 characters).
diff --git a/cli/e2e/serviceProcesses.e2e.ts b/cli/e2e/serviceProcesses.e2e.ts
index 6c2e71267..f515270f8 100644
--- a/cli/e2e/serviceProcesses.e2e.ts
+++ b/cli/e2e/serviceProcesses.e2e.ts
@@ -311,8 +311,8 @@ async function modelsAnswers(client: LocalClient): Promise<boolean> {
describe('models in its own process', () => {
let daemon: IsolatedDaemon | undefined
afterEach(async () => { await daemon?.close(); daemon = undefined })
- const fresh = async (env: Record<string, string> = {}) => {
- const d = await IsolatedDaemon.create({ env: {
+ const fresh = async (env: Record<string, string> = {}, preserveProcessArgs = false) => {
+ const d = await IsolatedDaemon.create({ preserveProcessArgs, env: {
HARNESSD_SERVICES: 'models',
HARNESSD_SERVICE_INITIAL_BACKOFF_MS: '200',
HARNESSD_SERVICE_MAX_BACKOFF_MS: '1000',
@@ -377,45 +377,102 @@ describe('models in its own process', () => {
client.close()
})
+ it('models killed during discovery: existing assignments stay, new marked processes bind without waiting, and later learn their grid', async () => {
+ const holdDir = mkdtempSync(join(tmpdir(), 'assignment-hold-'))
+ const hold = join(holdDir, 'hold')
+ try {
+ const d = await fresh({ HARNESSD_TEST_HOLD_CONNECT: `models:${hold}` }, true)
+ const client = await LocalClient.connect(d)
+ const grid = { networkId: 'assignment-e2e', networkName: 'Assignment', baseUrl: 'https://fixture.invalid/g/assignment/relay/v1', apiKey: 'fixture-key', model: 'Small-Q4' }
+ const known = await createOn(d, client, 'claude', 'assignment-known', grid)
+ const knownAssignment = { baseUrl: grid.baseUrl.replace(/\/v1$/, ''), model: grid.model }
+ await until('the existing Claude assignment to reflect its real endpoint', async () => {
+ const now = await row(client, known.id)
+ return now?.grid?.baseUrl === knownAssignment.baseUrl ? now : null
+ }, 15_000, 200)
+ writeFileSync(hold, '')
+ for (const pid of modelsPids(d)) process.kill(pid, 'SIGKILL')
+ await until('models disconnected', () => d.log().includes('[services] models disconnected') || null, 15_000, 100)
+ const discovered: Array<Record<string, any>> = []
+ for (const engine of ['claude', 'codex'] as const) {
+ const cwd = join(d.projectsDir, `assignment-external-${engine}`)
+ mkdirSync(cwd)
+ const environment = ['HOME', 'ZDOTDIR', 'PATH', 'CLAUDE_PATH', 'CODEX_PATH', 'CODEX_HOME', 'CLAUDE_PROJECTS_DIR', 'ADAPTER_DATA_DIR', 'PORT']
+ .flatMap(name => ['-e', `${name}=${d.env[name]}`])
+ if (engine === 'claude') environment.push('-e', `ANTHROPIC_BASE_URL=${grid.baseUrl}`, '-e', `ANTHROPIC_MODEL=${grid.model}`)
+ const args = engine === 'codex' ? ['-c', `model_providers.grid.base_url="${grid.baseUrl}"`, '-m', grid.model] : []
+ const asked = Date.now()
+ const tile = await client.request('agent_create', { engine: 'terminal', cwd }, 15_000)
+ expect(tile.error).toBeUndefined()
+ const pane = tile.agent.tmuxPane as string
+ // Start an engine in a Harness-owned terminal; unrelated user tmux sessions are intentionally ignored.
+ await d.tmux.run('respawn-pane', '-k', '-t', pane, '-c', cwd,
+ ...environment, d.env[engine === 'claude' ? 'CLAUDE_PATH' : 'CODEX_PATH']!, ...args)
+ const agent = await until(`${engine} discovered and bound while models is unavailable`, async () => {
+ const agents = (await client.request('agents_list', {}, 5_000)).agents as Array<Record<string, any>>
+ return agents.find(agent => agent.tmuxPane === pane && agent.sessionId && agent.status === 'active') ?? null
+ }, 15_000, 200)
+ expect(Date.now() - asked).toBeLessThan(15_000)
+ discovered.push(agent)
+ await turn(client, agent.id, `bound without models ${engine}`)
+ }
+ expect((await row(client, known.id))?.grid).toMatchObject(knownAssignment)
+ for (const agent of discovered) expect((await row(client, agent.id))?.grid ?? null).toBeNull()
+ rmSync(hold)
+ for (const agent of discovered) await until(`${agent.engine} classified after models returns`, async () => {
+ const now = await row(client, agent.id)
+ return now?.sessionId === agent.sessionId && now.grid?.baseUrl === grid.baseUrl && now.grid?.model === grid.model ? now : null
+ }, 45_000, 250)
+ expect(d.coresStarted()).toBe(1)
+ client.close()
+ } finally { rmSync(holdDir, { recursive: true, force: true }) }
+ })
+
it('down at launch time: Claude Code and Codex on their own login launch as ever, a launch on a grid or a saved API is refused at once, and builds again once models is back', async () => {
- // Slow to come back, so what is launched meanwhile finds it down.
- const d = await fresh({ HARNESSD_SERVICE_INITIAL_BACKOFF_MS: '8000', HARNESSD_SERVICE_MAX_BACKOFF_MS: '8000' })
- const client = await LocalClient.connect(d)
- // The launch the desktop sends for a grid it already resolved: models builds it (ModelsPort.gridLaunch).
- const grid = { networkId: 'net-e2e', networkName: 'e2e-grid', baseUrl: 'https://fixture.invalid/g/net-e2e/relay/v1', apiKey: 'fixture-key', model: 'Small-Q4' }
- const onGrid = await createOn(d, client, 'claude', 'launch-grid-claude', grid)
- expect(onGrid.grid).toMatchObject({ baseUrl: grid.baseUrl, model: 'Small-Q4' })
- const before = modelsPids(d)
- for (const pid of before) process.kill(pid, 'SIGKILL')
- await until('the core to see models gone', () => d.log().includes('[services] models disconnected') || null, 15_000, 100)
- // Their own login asks models nothing: both launch, and take a turn, while it is down.
- const plain = [await create(d, client, 'claude', 'launch-plain-claude'), await create(d, client, 'codex', 'launch-plain-codex')]
- for (const agent of plain) await turn(client, agent.id, `launched while models was down (${agent.engine})`)
- // A launch that needs it is refused at once, saying why, and nothing is started or stopped.
- const asked = Date.now()
- const down = (engine: string, name: string) => `The models service is not running, so ${engine} cannot be put on ${name}. Try again in a moment.`
- mkdirSync(join(d.projectsDir, 'launch-grid-refused'), { recursive: true })
- expect(await client.request('agent_create', { engine: 'codex', cwd: join(d.projectsDir, 'launch-grid-refused'), grid, bypassPermission: true }, 30_000))
- .toMatchObject({ error: 'GRID_UNAVAILABLE', detail: down('codex', 'e2e-grid') })
- expect(await client.request('agent_restart', { agentId: onGrid.id }, 30_000)).toMatchObject({ error: 'GRID_UNAVAILABLE', detail: down('claude', 'e2e-grid') })
- expect(await client.request('agent_retarget', { agentId: plain[0].id, grid }, 30_000)).toMatchObject({ error: 'GRID_UNAVAILABLE', detail: down('claude', 'e2e-grid') })
- expect(await client.request('agent_retarget', { agentId: plain[1].id, apiConnection: 'openrouter', apiModel: 'z-ai/glm-5' }, 30_000))
- .toMatchObject({ error: 'API_UNAVAILABLE', detail: 'The models service is not running, so this API cannot be used now. Try again in a moment.' })
- expect(Date.now() - asked).toBeLessThan(5_000)
- // The agent on the grid was left running as it was, and every agent goes on.
- await turn(client, onGrid.id, 'its restart was refused, and it is still here')
- for (const agent of plain) expect((await row(client, agent.id))?.grid ?? null).toBeNull()
- expect((await row(client, onGrid.id))?.grid).toMatchObject({ baseUrl: grid.baseUrl })
- // Back, it builds the launch again.
- await until('the master to restart models', () => restarts(d) >= 1 || null, 30_000, 200)
- await until('models to answer again', () => modelsAnswers(client).then((ok) => ok || null), 30_000, 500)
- expect(await client.request('agent_restart', { agentId: onGrid.id }, 90_000)).not.toHaveProperty('error')
- await until('the agent on the grid to come back', async () => {
- const agent = await row(client, onGrid.id)
- return agent?.status === 'active' && agent.grid?.baseUrl === grid.baseUrl ? agent : null
- }, 60_000, 500)
- expect(d.coresStarted()).toBe(1)
- client.close()
+ const holdDir = mkdtempSync(join(tmpdir(), 'models-launch-hold-'))
+ const hold = join(holdDir, 'hold')
+ try {
+ // Hold the replacement until every outage assertion has finished, regardless of host load.
+ const d = await fresh({ HARNESSD_TEST_HOLD_CONNECT: `models:${hold}` })
+ const client = await LocalClient.connect(d)
+ // The launch the desktop sends for a grid it already resolved: models builds it (ModelsPort.gridLaunch).
+ const grid = { networkId: 'net-e2e', networkName: 'e2e-grid', baseUrl: 'https://fixture.invalid/g/net-e2e/relay/v1', apiKey: 'fixture-key', model: 'Small-Q4' }
+ const onGrid = await createOn(d, client, 'claude', 'launch-grid-claude', grid)
+ expect(onGrid.grid).toMatchObject({ baseUrl: grid.baseUrl, model: 'Small-Q4' })
+ const before = modelsPids(d)
+ writeFileSync(hold, '')
+ for (const pid of before) process.kill(pid, 'SIGKILL')
+ await until('the core to see models gone', () => d.log().includes('[services] models disconnected') || null, 15_000, 100)
+ // Their own login asks models nothing: both launch, and take a turn, while it is down.
+ const plain = [await create(d, client, 'claude', 'launch-plain-claude'), await create(d, client, 'codex', 'launch-plain-codex')]
+ for (const agent of plain) await turn(client, agent.id, `launched while models was down (${agent.engine})`)
+ // A launch that needs it is refused at once, saying why, and nothing is started or stopped.
+ const asked = Date.now()
+ const down = (engine: string, name: string) => `The models service is not running, so ${engine} cannot be put on ${name}. Try again in a moment.`
+ mkdirSync(join(d.projectsDir, 'launch-grid-refused'), { recursive: true })
+ expect(await client.request('agent_create', { engine: 'codex', cwd: join(d.projectsDir, 'launch-grid-refused'), grid, bypassPermission: true }, 30_000))
+ .toMatchObject({ error: 'GRID_UNAVAILABLE', detail: down('codex', 'e2e-grid') })
+ expect(await client.request('agent_restart', { agentId: onGrid.id }, 30_000)).toMatchObject({ error: 'GRID_UNAVAILABLE', detail: down('claude', 'e2e-grid') })
+ expect(await client.request('agent_retarget', { agentId: plain[0].id, grid }, 30_000)).toMatchObject({ error: 'GRID_UNAVAILABLE', detail: down('claude', 'e2e-grid') })
+ expect(await client.request('agent_retarget', { agentId: plain[1].id, apiConnection: 'openrouter', apiModel: 'z-ai/glm-5' }, 30_000))
+ .toMatchObject({ error: 'API_UNAVAILABLE', detail: 'The models service is not running, so this API cannot be used now. Try again in a moment.' })
+ expect(Date.now() - asked).toBeLessThan(5_000)
+ // The agent on the grid was left running as it was, and every agent goes on.
+ await turn(client, onGrid.id, 'its restart was refused, and it is still here')
+ for (const agent of plain) expect((await row(client, agent.id))?.grid ?? null).toBeNull()
+ expect((await row(client, onGrid.id))?.grid).toMatchObject({ baseUrl: grid.baseUrl })
+ // Back, it builds the launch again.
+ rmSync(hold)
+ await until('the master to restart models', () => restarts(d) >= 1 || null, 30_000, 200)
+ await until('models to answer again', () => modelsAnswers(client).then((ok) => ok || null), 30_000, 500)
+ expect(await client.request('agent_restart', { agentId: onGrid.id }, 90_000)).not.toHaveProperty('error')
+ await until('the agent on the grid to come back', async () => {
+ const agent = await row(client, onGrid.id)
+ return agent?.status === 'active' && agent.grid?.baseUrl === grid.baseUrl ? agent : null
+ }, 60_000, 500)
+ expect(d.coresStarted()).toBe(1)
+ client.close()
+ } finally { rmSync(holdDir, { recursive: true, force: true }) }
})
/**
diff --git a/cli/scripts/handoff-2026-10-08/mutate-grid-assignment.py b/cli/scripts/handoff-2026-10-08/mutate-grid-assignment.py
new file mode 100644
index 000000000..b6123119c
--- /dev/null
+++ b/cli/scripts/handoff-2026-10-08/mutate-grid-assignment.py
@@ -0,0 +1,34 @@
+"""Break real L2 contributions; the unchanged former-code golden must reject each by assertion."""
+import os
+from pathlib import Path
+import subprocess
+import sys
+
+cli = Path(sys.argv[1]).resolve()
+mutations = [
+ ('endpoint marker', 'src/lib/gridAssignmentWire.ts', "claude: 'ANTHROPIC_BASE_URL'", "claude: 'ANTHROPIC_HOST'"),
+ ('model marker', 'src/lib/gridAssignmentWire.ts', "claude: 'ANTHROPIC_MODEL'", "claude: 'ANTHROPIC_OTHER_MODEL'"),
+ ('process argv at models boundary', 'src/services/modelsAssignments.ts', 'return gridAssignments(processes)', "return gridAssignments(processes.map(p => ({ ...p, args: '' })))"),
+ ('Pi config', 'src/lib/gridAssignment.ts', "join(dir, 'models.json')", "join(dir, 'not-models.json')"),
+ ('OpenCode router', 'src/lib/gridAssignment.ts', 'return { baseUrl, model: model.toLowerCase() === GRID_ROUTER_MODEL.toLowerCase() ? null : model }', 'return { baseUrl, model }'),
+ ('API endpoint form', 'src/lib/gridAssignment.ts', '[relayBaseUrl(baseUrl), anthropicBaseUrl(baseUrl)]', '[relayBaseUrl(baseUrl)]'),
+]
+env = {**os.environ, 'TZ': 'UTC', 'TMPDIR': '/tmp'}
+env.pop('RECORD_GRID_ASSIGNMENT_GOLDEN', None)
+env.pop('TMUX', None)
+env.pop('TMUX_PANE', None)
+for name, file, before, after in mutations:
+ path = cli / file
+ original = path.read_text()
+ assert original.count(before) == 1, name
+ path.write_text(original.replace(before, after))
+ try:
+ result = subprocess.run(['node', 'node_modules/vitest/vitest.mjs', 'run', 'src/lib/gridAssignmentShapes.golden.spec.ts', '--maxWorkers=1'],
+ cwd=cli, env=env, text=True, capture_output=True, timeout=90)
+ output = result.stdout + result.stderr
+ if result.returncode == 0 or 'AssertionError:' not in output or 'gridAssignmentShapes.golden.spec.ts:' not in output:
+ print(output[-6000:])
+ raise SystemExit(f'{name}: not rejected by the golden assertion')
+ print(f'{name}: caught by unchanged golden', flush=True)
+ finally:
+ path.write_text(original)
diff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.ts
index efd8a404d..a22917775 100644
--- a/cli/src/architecture.spec.ts
+++ b/cli/src/architecture.spec.ts
@@ -196,7 +196,7 @@ const EDGE: RegExp[] = [
// The grid and saved-API launch builders are models': the core asks it for a launch (ModelsPort.gridLaunch) and keeps
// only the wire it checks one with and the lists every launch reads (lib/gridLaunchWire.ts), so a launch on the
// engine's own login loads none of them (docs/design/2026-10-08-launch-port.md, (L1)).
- /^lib\/(gridLaunch|gridWebMcp|apiModels)\.ts$/,
+ /^lib\/(gridLaunch|gridWebMcp|apiModels|gridAssignment|apiConnections)\.ts$/,
// The change-agent handoff reads and redacts history and runs git: the edge host owns that work.
/^lib\/agentHandoff\.ts$/,
// The relay's own parts, the gateway's alone: the windows' sessions to other machines, P2P and STUN, the
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index 3a960bfbe..8c195f6e0 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -13,7 +13,6 @@ import { wholeHistoryPage } from './core/transcripts/history.js'
import { grokMessagesToEvents } from './engines/grok/normalizer.js'
import { bindAgentList, bindAgentUpdate, bindCancelRequest, bindLaunchRequests, bindCloseRequests, bindMessageRequest, bindPurgeRequest, bindQuestionResponse, bindStopRequest, bindTerminalRequests } from './testing/socketCore.js'
import { emptyPorts, MODELS_FALLBACKS, MODELS_OFF, MONITOR_FALLBACKS, type ModelsPort } from './core/api.js'
-import { classifyGridAssignment } from './lib/gridAssignment.js'
import { createServiceHost, ServiceUnavailableError } from './core/serviceHost.js'
import { MODELS_REQUESTS, startModels } from './services/models.js'
import { SHELL_REQUESTS, startShell } from './services/shell.js'
@@ -3377,13 +3376,10 @@ describe('a move onto a grid model asks models where it goes', () => {
it("a move onto a saved API's model: the launch models read, its endpoint recognised from then on, no grid started", async () => {
const apiTarget = vi.fn(async () => ({ target: API, apiBase: API.baseUrl }))
const d = daemon(vi.fn(), apiTarget)
- const env = { ANTHROPIC_BASE_URL: 'https://router.fixture.invalid', ANTHROPIC_MODEL: 'vendor/model-a' }
- expect(classifyGridAssignment('claude', env)).toBeNull()
expect(await d.ask('agent_retarget', { agentId: 'a1', apiConnection: 'router', apiModel: ' vendor/model-a ' })).toMatchObject({ retargeted: true })
expect(apiTarget).toHaveBeenCalledWith({ connectionId: 'router', model: 'vendor/model-a' })
expect(d.retargeted).toHaveBeenCalledWith({ agentId: 'a1', grid: API })
- // Read in models' process: only the answer's endpoint can teach the core's grid assignment.
- expect(classifyGridAssignment('claude', env)).toEqual({ baseUrl: 'https://router.fixture.invalid', model: 'vendor/model-a' })
+ // Target resolution and endpoint recognition belong to models; core forwards the launch.
expect(d.moved).not.toHaveBeenCalled()
await d.done()
})
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index aa1f8b153..9c9c4a597 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -26,7 +26,6 @@ import type { CloseAgentService } from './lib/closeAgentService.js'
import { ENGINES, type AgentEngine } from './engines/types.js'
import { gridCliPresence } from './lib/gridBinary.js'
import { GRID_FLEET_PROTOCOL, GRID_FLEET_MAX_TIMEOUT_MS } from './lib/gridFleetProtocol.js'
-import { rememberApiBase } from './lib/gridAssignment.js'
import { isApiLaunch, parseGridLaunchOverride, type GridLaunchOverride } from './lib/gridLaunchWire.js'
import type { ScmLaunchRecord } from './scm/types.js'
import { probeEngines } from './lib/engineProbe.js'
@@ -1021,7 +1020,6 @@ export class BackendSocket {
return
}
// An agent on it from now on reports that API's model, as when the socket read the store itself.
- rememberApiBase(resolved.apiBase)
payload.grid = resolved.target
}
if (picked && payload.grid === undefined && !clear) {
diff --git a/cli/src/core/agents/discovery.ts b/cli/src/core/agents/discovery.ts
index bd50f4a2d..ebc4ff8e0 100644
--- a/cli/src/core/agents/discovery.ts
+++ b/cli/src/core/agents/discovery.ts
@@ -10,7 +10,7 @@
import { isTerminalEngine } from '../../engines/types.js'
import type { AutonomousDeviceInput } from '../deviceInput.js'
import type { QuestionWatcher } from '../../lib/questionController.js'
-import { sameGridAssignment } from '../../lib/gridAssignment.js'
+import { sameGridAssignment } from '../../lib/gridAssignmentWire.js'
import { sid } from '../../lib/log.js'
import type { registry, RegisteredSession } from '../../lib/registry.js'
import type { SessionInputController } from '../../lib/sessionInput.js'
diff --git a/cli/src/core/agents/gridAssignments.spec.ts b/cli/src/core/agents/gridAssignments.spec.ts
new file mode 100644
index 000000000..1fed266b4
--- /dev/null
+++ b/cli/src/core/agents/gridAssignments.spec.ts
@@ -0,0 +1,162 @@
+import { afterEach, expect, it, vi } from 'vitest'
+import { readProcessEnv } from '../../lib/processEnv.js'
+import { processArgs } from '../../lib/tmux.js'
+import type { RegisteredSession } from '../../lib/registry.js'
+import type { DiscoveredTerminalAgent } from '../../lib/terminalAgentDiscovery.js'
+import { createGridAssignments } from './gridAssignments.js'
+
+vi.mock('../../lib/processEnv.js', () => ({ readProcessEnv: vi.fn(async () => ({ ANTHROPIC_BASE_URL: 'https://grid.example/relay' })) }))
+vi.mock('../../lib/tmux.js', () => ({ processArgs: vi.fn(async () => '') }))
+const assignment = { baseUrl: 'https://grid.example/relay', model: 'chosen' }
+const row = (id = 'a'): RegisteredSession => ({ agentId: id, engine: 'claude', sessionId: 'session', registeredAt: 1, boundAt: 2,
+ active: true, primaryRuntimeKey: 'tmux:%1', processIdentity: { pid: 123, startMarker: 'start', executable: 'claude' },
+ grid: assignment } as RegisteredSession)
+const observed = (session: RegisteredSession, marked = true): DiscoveredTerminalAgent => ({ engine: session.engine, processIdentity: session.processIdentity,
+ ...(marked ? { gridProcess: { key: 'old', engine: 'claude', env: { ANTHROPIC_BASE_URL: assignment.baseUrl }, args: '' } } : {}) } as DiscoveredTerminalAgent)
+const flush = async () => { for (let i = 0; i < 12; ++i) await Promise.resolve() }
+function setup() {
+ let rows = [row()]
+ let revision = 1
+ const pending: Array<{ processes: any[]; resolve: (value: any) => void; reject: (error: Error) => void }> = []
+ const models = { gridAssignments: vi.fn((processes) => new Promise<any[]>((resolve, reject) => pending.push({ processes, resolve, reject }))) }
+ const registry = { list: () => rows, byAgent: (id: string) => rows.find(row => row.agentId === id),
+ updateProcessIdentity: vi.fn((id, _identity, _gateway, grid) => { rows.find(row => row.agentId === id)!.grid = grid; return true }) }
+ const announce = vi.fn()
+ const service = createGridAssignments({ models: () => models, registry, revision: () => revision, announce, waitMs: 50 })
+ const answer = (index = 0, grid: typeof assignment | null = null) => pending[index].resolve(pending[index].processes.map(p => ({ key: p.key, assignment: grid })))
+ return { service, models, registry, announce, pending, answer, get rows() { return rows }, set rows(value) { rows = value }, bump: () => ++revision }
+}
+afterEach(() => { vi.clearAllMocks(); vi.useRealTimers() })
+
+it('batches fresh observations after binding, never blocks, and announces only changed assignments', async () => {
+ const s = setup()
+ s.rows.push({ ...row('b'), processIdentity: { pid: 124, startMarker: 'start', executable: 'claude' }, grid: undefined })
+ expect(s.service.observe(s.rows.map(row => observed(row)))).toBeUndefined()
+ await flush()
+ expect(s.models.gridAssignments).toHaveBeenCalledOnce()
+ expect(s.pending[0].processes).toHaveLength(2)
+ expect(s.announce).not.toHaveBeenCalled()
+ s.answer(0, assignment)
+ await flush()
+ expect(s.announce).toHaveBeenCalledExactlyOnceWith(s.rows[1])
+ s.service.observe(s.rows.map(row => observed(row)))
+ await flush()
+ s.answer()
+ s.answer(1)
+ await flush()
+ expect(s.rows.every(row => row.grid === null)).toBe(true)
+})
+
+it.each(['down', 'malformed', 'timeout', 'late-rejection'] as const)('keeps the last assignment when models is %s', async failure => {
+ vi.useFakeTimers()
+ const s = setup()
+ s.service.observe([observed(s.rows[0])])
+ await flush()
+ if (failure === 'down') s.pending[0].reject(new Error('down'))
+ else if (failure === 'malformed') s.pending[0].resolve([{ key: 'wrong', assignment: null }])
+ else {
+ await vi.advanceTimersByTimeAsync(51)
+ if (failure === 'late-rejection') s.pending[0].reject(new Error('late'))
+ else s.answer()
+ }
+ await flush()
+ expect(s.rows[0].grid).toEqual(assignment)
+ expect(s.registry.updateProcessIdentity).not.toHaveBeenCalled()
+})
+
+it('contains an unavailable port that throws synchronously', async () => {
+ const s = setup()
+ const service = createGridAssignments({ models: () => { throw new Error('off') }, registry: s.registry, revision: () => 0, announce: s.announce })
+ service.observe([observed(s.rows[0])])
+ await flush()
+ expect(s.announce).not.toHaveBeenCalled()
+})
+
+it.each(['removed', 'registration', 'engine', 'session', 'binding', 'route', 'active', 'process', 'revision', 'new-observation'] as const)(
+ 'rejects a late answer after %s changed', async change => {
+ const s = setup()
+ s.service.observe([observed(s.rows[0])])
+ await flush()
+ const current = s.rows[0]
+ if (change === 'removed') s.rows = []
+ if (change === 'registration') current.registeredAt++
+ if (change === 'engine') current.engine = 'codex'
+ if (change === 'session') current.sessionId = 'another'
+ if (change === 'binding') current.boundAt = 3
+ if (change === 'route') current.primaryRuntimeKey = 'tmux:%2'
+ if (change === 'active') current.active = false
+ if (change === 'process') current.processIdentity = { ...current.processIdentity!, startMarker: 'new' }
+ if (change === 'revision') s.bump()
+ if (change === 'new-observation') s.service.observe([observed(current, false)])
+ s.answer()
+ await flush()
+ expect(s.registry.updateProcessIdentity).not.toHaveBeenCalled()
+ })
+
+it('does not ask for missing rows, unknown process reads or absent markers, and forgets retired ordering tokens', async () => {
+ const s = setup()
+ s.service.observe([observed(s.rows[0], false)])
+ s.rows = [{ ...row('new'), processIdentity: null } as RegisteredSession]
+ s.service.observe([observed(row()), observed(s.rows[0], false)])
+ s.service.refresh(s.rows[0])
+ s.rows = [row('new')]
+ s.service.observe([observed(s.rows[0], false)])
+ await flush()
+ expect(s.models.gridAssignments).not.toHaveBeenCalled()
+})
+
+it('refreshes a committed swap in the background, with the same stale-answer guards', async () => {
+ const s = setup()
+ expect(s.service.refresh(s.rows[0])).toBeUndefined()
+ s.service.refresh(s.rows[0])
+ await flush()
+ expect(readProcessEnv).toHaveBeenCalledWith(s.rows[0].processIdentity)
+ expect(processArgs).toHaveBeenCalledWith(s.rows[0].processIdentity)
+ s.answer()
+ await flush()
+ expect(s.rows[0].grid).toBeNull()
+})
+
+it('coalesces only unfinished identical observations so a slower-than-discovery answer eventually lands', async () => {
+ const s = setup()
+ s.rows[0].grid = undefined
+ for (let pass = 0; pass < 5; ++pass) {
+ s.service.observe([observed(s.rows[0])])
+ await flush()
+ }
+ expect(s.models.gridAssignments).toHaveBeenCalledOnce()
+ s.answer(0, assignment)
+ await flush()
+ expect(s.rows[0].grid).toEqual(assignment)
+ // No completed answer is cached. The very next pass reads the process/config again.
+ s.service.observe([observed(s.rows[0])])
+ await flush()
+ expect(s.models.gridAssignments).toHaveBeenCalledTimes(2)
+ const changed = observed(s.rows[0])
+ changed.gridProcess!.env.ANTHROPIC_BASE_URL = 'https://other.example/relay'
+ s.service.observe([changed])
+ await flush()
+ s.answer(1)
+ await flush()
+ expect(s.rows[0].grid).toEqual(assignment)
+ s.answer(2)
+ await flush()
+ expect(s.rows[0].grid).toBeNull()
+})
+
+it('an unreadable or rejected process read keeps the assignment; a confirmed plain launch clears it', async () => {
+ const s = setup()
+ vi.mocked(readProcessEnv).mockResolvedValueOnce(null)
+ s.service.refresh(s.rows[0])
+ await flush()
+ expect(s.rows[0].grid).toEqual(assignment)
+ vi.mocked(processArgs).mockRejectedValueOnce(new Error('gone'))
+ s.service.refresh(s.rows[0])
+ await flush()
+ expect(s.rows[0].grid).toEqual(assignment)
+ vi.mocked(readProcessEnv).mockResolvedValueOnce({})
+ s.service.refresh(s.rows[0])
+ await flush()
+ expect(s.rows[0].grid).toBeNull()
+ expect(s.models.gridAssignments).not.toHaveBeenCalled()
+})
diff --git a/cli/src/core/agents/gridAssignments.ts b/cli/src/core/agents/gridAssignments.ts
new file mode 100644
index 000000000..c8ea86e52
--- /dev/null
+++ b/cli/src/core/agents/gridAssignments.ts
@@ -0,0 +1,93 @@
+/** Optional model metadata follows discovery; it never owns a binding or delays session control. */
+import type { ModelsPort } from '../api.js'
+import { gridAssignmentAnswersIn, gridAssignmentProcess, sameGridAssignment,
+ type GridAssignment, type GridAssignmentProcess } from '../../lib/gridAssignmentWire.js'
+import { readProcessEnv } from '../../lib/processEnv.js'
+import type { RegisteredSession, registry as Registry } from '../../lib/registry.js'
+import type { DiscoveredTerminalAgent } from '../../lib/terminalAgentDiscovery.js'
+import { sameProcessIdentity } from '../../lib/terminalRuntime.js'
+import { processArgs } from '../../lib/tmux.js'
+
+export interface GridAssignmentsDeps {
+ models: () => Pick<ModelsPort, 'gridAssignments'>
+ registry: Pick<typeof Registry, 'list' | 'byAgent' | 'updateProcessIdentity'>
+ revision: (agentId: string) => number
+ announce: (session: RegisteredSession) => void
+ /** The same bound as an ordinary port call; also bounds the explicit inline compatibility path. */
+ waitMs?: number
+}
+
+export function createGridAssignments({ models, registry, revision, announce, waitMs = 30_000 }: GridAssignmentsDeps) {
+ let sequence = 0
+ // Ordering tokens only. Every observation is classified again; no assignments are cached here.
+ const latest = new Map<string, { serial: number; signature: string; pending: boolean }>()
+ const ticket = (session: RegisteredSession, evidence: unknown) => {
+ for (const id of latest.keys()) if (!registry.byAgent(id)) latest.delete(id)
+ const snapshot = { ...session, revision: revision(session.agentId) }
+ const signature = JSON.stringify([snapshot.registeredAt, snapshot.engine, snapshot.sessionId, snapshot.boundAt,
+ snapshot.primaryRuntimeKey, snapshot.active, snapshot.processIdentity, snapshot.revision, evidence])
+ const prior = latest.get(session.agentId)
+ if (prior?.pending && prior.signature === signature) return null
+ const serial = ++sequence
+ const state = { serial, signature, pending: true }
+ latest.set(session.agentId, state)
+ return {
+ key: String(serial),
+ done: () => { state.pending = false },
+ apply(assignment: GridAssignment | null) {
+ const current = registry.byAgent(snapshot.agentId)
+ if (!current || latest.get(snapshot.agentId)?.serial !== serial || current.registeredAt !== snapshot.registeredAt
+ || current.engine !== snapshot.engine || current.sessionId !== snapshot.sessionId || current.boundAt !== snapshot.boundAt
+ || current.primaryRuntimeKey !== snapshot.primaryRuntimeKey || current.active !== snapshot.active
+ || !sameProcessIdentity(current.processIdentity, snapshot.processIdentity) || revision(current.agentId) !== snapshot.revision) return
+ if (sameGridAssignment(current.grid ?? null, assignment)) return
+ registry.updateProcessIdentity(current.agentId, current.processIdentity!, undefined, assignment)
+ announce(current)
+ },
+ }
+ }
+
+ const ask = (inputs: Array<{ process: GridAssignmentProcess; owner: NonNullable<ReturnType<typeof ticket>> }>) => {
+ if (!inputs.length) return
+ const processes = inputs.map(input => input.process)
+ let timer: NodeJS.Timeout
+ const deadline = new Promise<null>(resolve => { timer = setTimeout(() => resolve(null), waitMs); timer.unref?.() })
+ // Promise.resolve also contains a synchronous throw from an unavailable port.
+ void Promise.race([Promise.resolve().then(() => models().gridAssignments(processes)), deadline]).then(value => {
+ const answers = gridAssignmentAnswersIn(value, processes)
+ if (!answers) return
+ const owners = new Map(inputs.map(input => [input.process.key, input.owner]))
+ for (const answer of answers) owners.get(answer.key)!.apply(answer.assignment)
+ }).catch(() => {}).finally(() => { clearTimeout(timer); for (const input of inputs) input.owner.done() })
+ }
+
+ return {
+ /** One call after a completed discovery pass, including rows whose absent markers invalidate older reads. */
+ observe(observed: readonly DiscoveredTerminalAgent[]): void {
+ const rows = registry.list()
+ const inputs: Array<{ process: GridAssignmentProcess; owner: NonNullable<ReturnType<typeof ticket>> }> = []
+ for (const agent of observed) {
+ const session = rows.find(row => row.engine === agent.engine && sameProcessIdentity(row.processIdentity, agent.processIdentity))
+ if (!session) continue
+ const owner = ticket(session, agent.gridProcess ?? null)
+ if (!owner) continue
+ if (agent.gridProcess) inputs.push({ owner, process: { ...agent.gridProcess, key: owner.key } })
+ else owner.done()
+ }
+ ask(inputs)
+ },
+ /** A swap has already committed its process. Read metadata in the background, never under its route hold. */
+ refresh(session: RegisteredSession): void {
+ if (!session.processIdentity) return
+ const owner = ticket(session, 'refresh')
+ if (!owner) return
+ const identity = session.processIdentity
+ void Promise.all([readProcessEnv(identity), processArgs(identity)]).then(([env, args]) => {
+ if (!env) { owner.done(); return }
+ const process = gridAssignmentProcess(owner.key, session.engine, env, args)
+ if (process) ask([{ owner, process }])
+ else { owner.apply(null); owner.done() }
+ }).catch(() => { owner.done() })
+ },
+ }
+}
diff --git a/cli/src/core/agents/launch.spec.ts b/cli/src/core/agents/launch.spec.ts
index 9b28bcb60..49463090a 100644
--- a/cli/src/core/agents/launch.spec.ts
+++ b/cli/src/core/agents/launch.spec.ts
@@ -1,6 +1,5 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { prepareResume } from '../../engines/launchPrep.js'
-import { rememberApiBase } from '../../lib/gridAssignment.js'
import type { GridLaunchAnswer, GridLaunchOverride, GridLaunchRequest } from '../../lib/gridLaunchWire.js'
import { dropPermissionFlagIfUnsupported } from '../../lib/engineLaunch.js'
import { buildLaunchOverrides, type LaunchOverrides, type LaunchOverridesDeps } from '../../lib/launchOverrides.js'
@@ -10,7 +9,6 @@ import type { RegisteredSession } from '../../lib/registry.js'
import { createLaunchHelpers, gridLaunchThrough, type LaunchHelperDeps } from './launch.js'
vi.mock('../../engines/launchPrep.js', async (real) => ({ ...await real<object>(), prepareResume: vi.fn(() => ({ repairedItems: 0 })) }))
-vi.mock('../../lib/gridAssignment.js', async (real) => ({ ...await real<object>(), rememberApiBase: vi.fn() }))
vi.mock('../../lib/engineLaunch.js', async (real) => ({ ...await real<object>(), dropPermissionFlagIfUnsupported: vi.fn() }))
// OpenCode's version is its own code, loaded for an OpenCode relaunch alone; a test may say it could not be.
vi.mock('../../engines/inProcess.js', async (real) => {
@@ -118,13 +116,11 @@ describe('a grid launch, as the core asks the models service for it', () => {
const api: GridLaunchOverride = { networkId: 'api:openrouter', networkName: 'OpenRouter', baseUrl: 'https://openrouter.ai/api/v1', apiKey: 'k', model: 'q' }
const request = (override = grid): GridLaunchRequest => ({ engine: 'claude', override, machine: { hermesSystemManaged: false } })
- it("hands back models' answer as it is, and remembers a saved API's endpoint it read", async () => {
+ it("hands back models' answer as it is, including saved API details owned by models", async () => {
const built: GridLaunchAnswer = { ok: true, launch: { env: {}, args: [], webSearch: 'on' }, override: grid }
expect(await gridLaunchThrough(() => ({ gridLaunch: async () => built }))(request())).toBe(built)
- expect(rememberApiBase).not.toHaveBeenCalled()
const refused: GridLaunchAnswer = { ok: false, error: 'API_UNAVAILABLE', detail: 'OpenRouter was removed.', apiBase: 'https://openrouter.ai/api/v1' }
expect(await gridLaunchThrough(() => ({ gridLaunch: async () => refused }))(request(api))).toBe(refused)
- expect(rememberApiBase).toHaveBeenCalledWith('https://openrouter.ai/api/v1')
})
it('refuses at once, naming the grid or the API, when models is down or answers nothing usable', async () => {
@@ -137,6 +133,5 @@ describe('a grid launch, as the core asks the models service for it', () => {
expect(await down(request(api))).toMatchObject({ ok: false, error: 'API_UNAVAILABLE', detail: expect.stringContaining('on OpenRouter') })
// A port that is not there at all (models off) is the same refusal, not a throw out of the launch.
expect(await gridLaunchThrough(() => { throw new Error('no port') })(request())).toMatchObject({ error: 'GRID_UNAVAILABLE' })
- expect(rememberApiBase).not.toHaveBeenCalled()
})
})
diff --git a/cli/src/core/agents/launch.ts b/cli/src/core/agents/launch.ts
index 17da50286..9d49bb550 100644
--- a/cli/src/core/agents/launch.ts
+++ b/cli/src/core/agents/launch.ts
@@ -9,7 +9,6 @@
import { loadEngine } from '../../engines/inProcess.js'
import { prepareResume, repairedItemsName } from '../../engines/launchPrep.js'
import { dropPermissionFlagIfUnsupported } from '../../lib/engineLaunch.js'
-import { rememberApiBase } from '../../lib/gridAssignment.js'
import { gridUnavailable, type GridLaunchAnswer, type GridLaunchRequest } from '../../lib/gridLaunchWire.js'
import { buildLaunchOverrides, type LaunchOverrides, type LaunchOverridesDeps, type LaunchOverridesResult, type LaunchSource } from '../../lib/launchOverrides.js'
import type { ModelsPort } from '../api.js'
@@ -27,7 +26,6 @@ export function gridLaunchThrough(models: () => Pick<ModelsPort, 'gridLaunch'>)
return async (request: GridLaunchRequest): Promise<GridLaunchAnswer> => {
let answer: GridLaunchAnswer
try { answer = await models().gridLaunch(request) } catch { return gridUnavailable(request.engine, request.override) }
- if (answer.apiBase) rememberApiBase(answer.apiBase)
return answer
}
}
diff --git a/cli/src/core/agents/restart.spec.ts b/cli/src/core/agents/restart.spec.ts
index 568272eb9..02f0a9a98 100644
--- a/cli/src/core/agents/restart.spec.ts
+++ b/cli/src/core/agents/restart.spec.ts
@@ -4,7 +4,6 @@ import { engineBin, enginePathOverride } from '../../lib/engineBin.js'
import { engineInstallRecipe } from '../../lib/engineInstall.js'
import { buildEngineLaunchArgv, commandAvailableInInteractiveShell } from '../../lib/engineLaunch.js'
import { probeGatewayRuntime } from '../../lib/gatewayRuntime.js'
-import { probeGridAssignment } from '../../lib/gridAssignment.js'
import type { RegisteredSession } from '../../lib/registry.js'
import { AgentRestartCoordinator, bypassPermissionFor, restartAgent } from '../../lib/restartAgent.js'
import { terminalRouteKey } from '../../lib/terminalRuntime.js'
@@ -19,7 +18,6 @@ vi.mock('../../lib/engineLaunch.js', async (real) => ({
commandAvailableInInteractiveShell: vi.fn(async () => true),
}))
vi.mock('../../lib/gatewayRuntime.js', async (real) => ({ ...await real<object>(), probeGatewayRuntime: vi.fn(async () => ({ kind: 'none' })) }))
-vi.mock('../../lib/gridAssignment.js', async (real) => ({ ...await real<object>(), probeGridAssignment: vi.fn(async () => undefined) }))
vi.mock('../../lib/restartAgent.js', async (real) => ({
...await real<object>(),
bypassPermissionFor: vi.fn(async (_s: unknown, live: () => Promise<boolean>) => live()),
@@ -60,6 +58,7 @@ function setup(row: RegisteredSession | null = agent(), over: Partial<RestartDep
agentReconciler: { holdRoute: vi.fn(), releaseRoute: vi.fn() },
terminalHintMachineName: () => 'studio',
announceSession: vi.fn(),
+ refreshGridAssignment: vi.fn(),
relaunchOverrides: vi.fn(async () => ({ ok: true, overrides: { env: { GRID_KEY: 'k' } } })) as never,
downgradedPermission: vi.fn(async (_s, bypass: boolean) => ({ bypassPermission: bypass, permissionMode: 'auto' })) as never,
refreshGridWebSearch: vi.fn() as never,
@@ -248,12 +247,11 @@ describe('restarting an agent', () => {
expect(run.deps.refreshGridWebSearch).toHaveBeenCalledWith('a1', { env: { GRID_KEY: 'k' } })
expect(probeGatewayRuntime).toHaveBeenCalledWith(newProcess)
// Its command line, where a Codex or pi grid's address and model are: never its executable alone.
- expect(processArgs).toHaveBeenCalledWith(newProcess)
- expect(probeGridAssignment).toHaveBeenCalledWith(newProcess, 'claude', '/bin/claude --model opus -c model_provider=grid')
- expect(run.deps.registry.updateProcessIdentity).toHaveBeenCalledWith('a1', newProcess, 'none', undefined)
+ expect(run.deps.registry.updateProcessIdentity).toHaveBeenCalledWith('a1', newProcess, 'none')
expect(run.deps.registry.setActive).toHaveBeenCalledWith('a1', true)
expect(clearPaneRemainOnExit).toHaveBeenCalledWith('%4')
expect(run.deps.announceSession).toHaveBeenCalledWith(agent())
+ expect(run.deps.refreshGridAssignment).toHaveBeenCalledWith(agent())
expect(console.log).toHaveBeenCalledWith('[restart] a1 claude · resumed')
expect(run.deps.agentReconciler.holdRoute).toHaveBeenCalledWith(routeKey)
expect(run.deps.agentReconciler.releaseRoute).toHaveBeenCalledWith(routeKey)
diff --git a/cli/src/core/agents/restart.ts b/cli/src/core/agents/restart.ts
index 0b72780b0..4d9340bc5 100644
--- a/cli/src/core/agents/restart.ts
+++ b/cli/src/core/agents/restart.ts
@@ -9,14 +9,13 @@ import { engineBin, enginePathOverride } from '../../lib/engineBin.js'
import { engineInstallRecipe } from '../../lib/engineInstall.js'
import { buildEngineLaunchArgv, commandAvailableInInteractiveShell } from '../../lib/engineLaunch.js'
import { probeGatewayRuntime } from '../../lib/gatewayRuntime.js'
-import { probeGridAssignment } from '../../lib/gridAssignment.js'
import { sid } from '../../lib/log.js'
import type { registry, RegisteredSession } from '../../lib/registry.js'
import { bypassPermissionFor, restartAgent } from '../../lib/restartAgent.js'
import type { TerminalAgentReconciler } from '../../lib/terminalAgentReconciler.js'
import { terminalRouteKey } from '../../lib/terminalRuntime.js'
import type { TmuxRuntimeRef } from '../../lib/terminalTypes.js'
-import { clearPaneRemainOnExit, processArgs } from '../../lib/tmux.js'
+import { clearPaneRemainOnExit } from '../../lib/tmux.js'
import type { TmuxBackend } from '../../lib/tmuxBackend.js'
import type { HeldRestart } from './heldLaunches.js'
import { workspaceMissing } from '../../lib/workspaceCheck.js'
@@ -60,6 +59,7 @@ export interface RestartDeps {
agentReconciler: Pick<TerminalAgentReconciler, 'holdRoute' | 'releaseRoute'>
terminalHintMachineName: () => string
announceSession: (session: RegisteredSession) => void
+ refreshGridAssignment: (session: RegisteredSession) => void
relaunchOverrides: LaunchHelpers['relaunchOverrides']
downgradedPermission: LaunchHelpers['downgradedPermission']
refreshGridWebSearch: LaunchHelpers['refreshGridWebSearch']
@@ -72,7 +72,7 @@ export interface RestartDeps {
export function createAgentRestarter({
restartJobs, registry, purgeBusy, stopJobs, pinnedControls, tmuxBackend, sameRestartTarget, agentReconciler,
- terminalHintMachineName, announceSession, relaunchOverrides, downgradedPermission, refreshGridWebSearch,
+ terminalHintMachineName, announceSession, refreshGridAssignment, relaunchOverrides, downgradedPermission, refreshGridWebSearch,
liveBypassPermission, paneSwapDeps, restartHeld,
}: RestartDeps) {
/**
@@ -181,21 +181,18 @@ export function createAgentRestarter({
// Address the CANONICAL agentId from the resolved session, not the raw RPC input — `resolve()`
// accepts either an agentId or a bare sessionId, but `setActive`/`byAgent` only ever key on the
- // real agentId. Gateway and grid are re-read off the new pid now (one cached env read) rather
- // than left to the next scan, so the announce below already says where the engine came back.
- const [gateway, assignment] = await Promise.all([
- probeGatewayRuntime(outcome.processIdentity),
- // Its command line, which carries a Codex or pi grid's address and model: never its executable.
- processArgs(outcome.processIdentity).then((args) => probeGridAssignment(outcome.processIdentity, engine, args)),
- ])
+ // real agentId. Gateway is a core process fact; optional grid metadata follows the committed
+ // binding in the background, so an unavailable models service cannot hold this route.
+ const gateway = await probeGatewayRuntime(outcome.processIdentity)
if (!current()) return changed
- registry.updateProcessIdentity(session.agentId, outcome.processIdentity, gateway.kind, assignment)
+ registry.updateProcessIdentity(session.agentId, outcome.processIdentity, gateway.kind)
registry.setActive(session.agentId, true)
await clearPaneRemainOnExit(pane)
if (!current()) return changed
const refreshed = registry.byAgent(session.agentId)
if (!refreshed) return { ok: false, error: 'RESTART_FAILED', detail: 'agent vanished from the registry mid-restart' }
announceSession(refreshed)
+ refreshGridAssignment(refreshed)
console.log(`[restart] ${sid(session.agentId)} ${engine} · ${outcome.resumed ? 'resumed' : 'fresh session'}`
+ (session.gridLaunch ? ` · grid ${session.gridLaunch.networkName}` : ''))
return { ok: true, session: refreshed, resumed: outcome.resumed }
diff --git a/cli/src/core/agents/retarget.spec.ts b/cli/src/core/agents/retarget.spec.ts
index df7ccf13d..f08a3ae33 100644
--- a/cli/src/core/agents/retarget.spec.ts
+++ b/cli/src/core/agents/retarget.spec.ts
@@ -7,7 +7,6 @@ import type { RegisteredSession } from '../../lib/registry.js'
import { bypassPermissionFor, restartAgent } from '../../lib/restartAgent.js'
import { parseRuntimeProfile } from '../../lib/runtimeProfileWire.js'
import { inspectRuntimePane } from '../../lib/runtimeProfileController.js'
-import { probeGridAssignment } from '../../lib/gridAssignment.js'
import { clearPaneRemainOnExit } from '../../lib/tmux.js'
import { workspaceMissing } from '../../lib/workspaceCheck.js'
import { createAgentRetargeter, type RetargetDeps } from './retarget.js'
@@ -25,7 +24,6 @@ vi.mock('../../engines/inProcess.js', async (real) => {
vi.mock('../../engines/opencode/version.js', () => ({ isOpencodeV2: vi.fn(() => false), opencodeMajorVersion: vi.fn(() => 1) }))
vi.mock('../../lib/binaryOnPath.js', () => ({ binaryOnPath: vi.fn(() => true) }))
vi.mock('../../lib/gatewayRuntime.js', async (real) => ({ ...await real<object>(), probeGatewayRuntime: vi.fn(async () => ({ kind: 'none' })) }))
-vi.mock('../../lib/gridAssignment.js', async (real) => ({ ...await real<object>(), probeGridAssignment: vi.fn(async () => undefined) }))
vi.mock('../../lib/gridLaunchWire.js', async (real) => ({ ...await real<object>(), describeGridLaunch: vi.fn(() => 'claude on Home'), gridEnvVarNames: vi.fn(() => ['ANTHROPIC_BASE_URL']) }))
vi.mock('../../lib/launchOverrides.js', async (real) => ({ ...await real<object>(), validateLaunchOverrides: vi.fn(async () => ({ ok: true })) }))
vi.mock('../../lib/restartAgent.js', async (real) => ({
@@ -72,6 +70,7 @@ function setup(row: RegisteredSession | null = agent(), over: Partial<RetargetDe
paneSwapDeps: vi.fn(() => ({})) as never,
liveBypassPermission: vi.fn(async () => true),
announceSession: vi.fn(),
+ refreshGridAssignment: vi.fn(),
opencodeDb: '/db/opencode.db',
...over,
}
@@ -141,11 +140,11 @@ describe('retargeting an agent', () => {
expect(run.deps.agentReconciler.holdRoute).toHaveBeenCalled()
expect(restartAgent).toHaveBeenCalledWith({ engine: 'claude', sessionId: 's1' }, true, {})
// The grid is read off the new process's command line, never its executable alone.
- expect(probeGridAssignment).toHaveBeenCalledWith(expect.objectContaining({ pid: 2 }), 'claude', 'codex -c model_providers.grid.base_url=http://grid.local/v1')
- expect(run.deps.registry.updateProcessIdentity).toHaveBeenCalledWith('a1', expect.objectContaining({ pid: 2 }), 'none', undefined)
+ expect(run.deps.registry.updateProcessIdentity).toHaveBeenCalledWith('a1', expect.objectContaining({ pid: 2 }), 'none')
expect(run.deps.registry.setGridLaunch).toHaveBeenCalledWith('a1', { override: grid, webSearch: 'off' })
expect(run.deps.registry.setSubscriptionModel).toHaveBeenCalledWith('a1', 'opus')
expect(run.deps.registry.setActive).toHaveBeenCalledWith('a1', true)
+ expect(run.deps.refreshGridAssignment).toHaveBeenCalledWith(agent())
expect(clearPaneRemainOnExit).toHaveBeenCalledWith('%4')
expect(run.deps.announceSession).toHaveBeenCalled()
expect(run.release).toHaveBeenCalled()
diff --git a/cli/src/core/agents/retarget.ts b/cli/src/core/agents/retarget.ts
index 1d8f40eb2..5af053931 100644
--- a/cli/src/core/agents/retarget.ts
+++ b/cli/src/core/agents/retarget.ts
@@ -15,7 +15,6 @@ import type { BackendSocket } from '../../backendSocket.js'
import { loadEngine } from '../../engines/inProcess.js'
import { binaryOnPath } from '../../lib/binaryOnPath.js'
import { probeGatewayRuntime } from '../../lib/gatewayRuntime.js'
-import { probeGridAssignment } from '../../lib/gridAssignment.js'
import { describeGridLaunch, gridEnvVarNames } from '../../lib/gridLaunchWire.js'
import { validateLaunchOverrides, type LaunchOverridesDeps, type LaunchSource } from '../../lib/launchOverrides.js'
import { sid } from '../../lib/log.js'
@@ -27,7 +26,7 @@ import type { ScreenReader } from '../../lib/screenReader.js'
import type { TerminalAgentReconciler } from '../../lib/terminalAgentReconciler.js'
import { terminalRouteKey } from '../../lib/terminalRuntime.js'
import type { TmuxRuntimeRef } from '../../lib/terminalTypes.js'
-import { clearPaneRemainOnExit, processArgs } from '../../lib/tmux.js'
+import { clearPaneRemainOnExit } from '../../lib/tmux.js'
import type { TmuxBackend } from '../../lib/tmuxBackend.js'
import { workspaceMissing } from '../../lib/workspaceCheck.js'
import type { createLaunchHelpers } from './launch.js'
@@ -54,6 +53,7 @@ export interface RetargetDeps {
paneSwapDeps: PaneSwap['paneSwapDeps']
liveBypassPermission: PaneSwap['liveBypassPermission']
announceSession: (session: RegisteredSession) => void
+ refreshGridAssignment: (session: RegisteredSession) => void
/** OpenCode's store, whose rows a resumed session takes its model from. */
opencodeDb: string
}
@@ -61,7 +61,7 @@ export interface RetargetDeps {
export function createAgentRetargeter({
readScreen, purgeBusy, tmuxBackend, registry, runtimeProfiles, launchOverridesDeps, captureTerminal, acquireTerminalControl,
relaunchOverrides, downgradedPermission, agentReconciler, restartJobs, paneSwapDeps, liveBypassPermission,
- announceSession, opencodeDb,
+ announceSession, refreshGridAssignment, opencodeDb,
}: RetargetDeps) {
const retargetAgent: RetargetAgent = async ({ agentId, grid }) => {
if (purgeBusy(agentId)) return { ok: false, error: 'AGENT_BUSY' }
@@ -237,13 +237,9 @@ export function createAgentRetargeter({
console.warn(`[grid] retarget ${sid(session.agentId)} failed · ${outcome.detail}`)
return { ok: false, error: 'RESPAWN_FAILED', detail: outcome.detail }
}
- // Both are read off the new pid: its cached environment, and for the grid its command line too.
- const [gateway, assignment] = await Promise.all([
- probeGatewayRuntime(outcome.processIdentity),
- // Its command line, which carries a Codex or pi grid's address and model: never its executable.
- processArgs(outcome.processIdentity).then((args) => probeGridAssignment(outcome.processIdentity, session.engine, args)),
- ])
- registry.updateProcessIdentity(session.agentId, outcome.processIdentity, gateway.kind, assignment)
+ // Commit the new process now. Optional grid metadata follows outside the route hold.
+ const gateway = await probeGatewayRuntime(outcome.processIdentity)
+ registry.updateProcessIdentity(session.agentId, outcome.processIdentity, gateway.kind)
// The launch that just worked is the one a restart or a post-reboot restore must repeat — and
// what it decided about web search is what the app shows for this agent from now on. Null for
// a move home: the block, and the status with it, leave the frame together.
@@ -257,7 +253,7 @@ export function createAgentRetargeter({
const refreshed = registry.byAgent(session.agentId)
// The app decides whether to still offer a move from what it is told here, so a silent success
// would leave the banner up over an agent that had already been moved.
- if (refreshed) announceSession(refreshed)
+ if (refreshed) { announceSession(refreshed); refreshGridAssignment(refreshed) }
const how = outcome.resumed ? 'resumed' : 'fresh session'
const record = built.overrides.gridLaunchRecord
const where = record
diff --git a/cli/src/core/api.spec.ts b/cli/src/core/api.spec.ts
index 67fed8bc2..c93c8d987 100644
--- a/cli/src/core/api.spec.ts
+++ b/cli/src/core/api.spec.ts
@@ -266,6 +266,7 @@ describe('the core API services stand on', () => {
await expect(MODELS_OFF.launchTarget({ model: 'm', grid: 'mine' })).rejects.toThrow('the models service is unavailable')
await expect(MODELS_OFF.moveTarget({ gridName: null, model: 'm' })).rejects.toThrow('the models service is unavailable')
await expect(MODELS_OFF.lists()).rejects.toThrow('the models service is unavailable')
+ await expect(MODELS_OFF.gridAssignments([])).rejects.toThrow('the models service is unavailable')
// A launch on a grid or a saved API is refused while models is off (core/agents/launch.ts `gridLaunchThrough`).
await expect(MODELS_OFF.gridLaunch({ engine: 'claude', override: launch, machine: { hermesSystemManaged: false } })).rejects.toThrow('the models service is unavailable')
await expect(MODELS_OFF.apiTarget({ connectionId: 'openrouter', model: 'm' })).rejects.toThrow('the models service is unavailable')
diff --git a/cli/src/core/api.ts b/cli/src/core/api.ts
index 72f61f232..8d5b7aff6 100644
--- a/cli/src/core/api.ts
+++ b/cli/src/core/api.ts
@@ -1,3 +1,4 @@
+import type { GridAssignmentProcess, GridAssignmentAnswer } from '../lib/gridAssignmentWire.js'
/**
* The boundary the services stand on (docs/design/2026-10-03-harnessd.md, "The core boundary"):
* `CoreApi` is what a service may ask of the core, and `CorePorts` is what the core asks of services.
@@ -715,6 +716,8 @@ export interface ModelsPort {
* itself (docs/design/2026-10-08-launch-port.md).
*/
gridLaunch(request: GridLaunchRequest): Promise<GridLaunchAnswer>
+ /** Fresh process evidence, batched; core never waits for it to discover or bind a session. */
+ gridAssignments(processes: readonly GridAssignmentProcess[]): Promise<GridAssignmentAnswer[]>
/** Where an agent moved onto a saved API's model sends its inference: the key travels only into its launch. The
* sentence a person reads when the API cannot be used. */
apiTarget(request: { connectionId: string; model: string }): Promise<{ target: GridLaunchOverride; apiBase: string } | { detail: string }>
@@ -738,7 +741,7 @@ export interface ModelsPort {
*/
export const MODELS_FALLBACKS: PortFallbacks<ModelsPort> = {
ensure: later(FAIL), annotation: null, prewarm: undefined, launchTarget: later(FAIL), moveTarget: later(FAIL), moved: undefined,
- gridLaunch: later(FAIL), apiTarget: later(FAIL), privateGridName: later(null), lists: later(FAIL), machines: undefined, signedOut: undefined,
+ gridAssignments: later(FAIL), gridLaunch: later(FAIL), apiTarget: later(FAIL), privateGridName: later(null), lists: later(FAIL), machines: undefined, signedOut: undefined,
}
/** What the core calls while `ports.models` is null (models is off): its fallbacks' answers. */
@@ -749,6 +752,7 @@ export const MODELS_OFF: ModelsPort = {
launchTarget: () => Promise.reject(new ServiceUnavailableError('models')),
moveTarget: () => Promise.reject(new ServiceUnavailableError('models')),
moved: () => {},
+ gridAssignments: () => Promise.reject(new ServiceUnavailableError('models')),
gridLaunch: () => Promise.reject(new ServiceUnavailableError('models')),
apiTarget: () => Promise.reject(new ServiceUnavailableError('models')),
privateGridName: async () => null,
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index 28003a633..22541d7a4 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -1,3 +1,4 @@
+import { createGridAssignments } from './agents/gridAssignments.js'
import { createQuestionControls } from './engines/questionControls.js'
import { masterRunsEngineQuestionControl } from '../harnessd/services.js'
import { createModelControls } from './engines/modelControls.js'
@@ -76,8 +77,7 @@ import { buildHarnessSessionLabel } from '../lib/harnessSessionLabel.js'
import { adoptLegacyHarnessSessions, listTmuxPanes } from '../lib/tmuxAgentDiscovery.js'
import { installedDsh, invalidateInstalledDsh } from '../dsh/installed.js'
import { dshThrough } from './agents/dshThrough.js'
-import { ApiConnections } from '../lib/apiConnections.js'
-import { rememberSavedApis } from '../lib/gridAssignment.js'
+import { ApiConnectionMetadata } from '../lib/apiConnectionMetadata.js'
import { prepareApiInstructions } from '../lib/apiInstructions.js'
import type { AgentDshContext } from '../lib/agentFrame.js'
import type { AgentGridTarget, GridAnnotation } from '../lib/gridAnnotation.js'
@@ -458,9 +458,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// master's updater runs on, and a published fix still lands (`enterSafeMode`).
if (process.env.HARNESSD_SAFE_MODE) throw new SafeModeRequest(process.env.HARNESSD_SAFE_MODE)
- const savedApis = new ApiConnections(env.ADAPTER_DATA_DIR)
- // Before any agent is probed: one already running on a saved API's model reports that model.
- rememberSavedApis(savedApis)
+ const savedApis = new ApiConnectionMetadata(env.ADAPTER_DATA_DIR)
+ // Instructions read metadata locally; a models outage must not change a workspace's tool instructions.
const prepareApiTools = (cwd: string | null | undefined, engine: string): void => {
if (!cwd) return
try { prepareApiInstructions(savedApis, cwd, engine) }
@@ -471,6 +470,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// (engines/inProcess.ts).
registry.onEnter = preloadEngine
registry.load()
+ // Bindings can finish before full teardown exists, or during its awaits. Cover every owned exit,
+ // including a staged update received during startup, without touching a different daemon's table.
+ process.on('exit', () => registry.flush({ exiting: true }))
// Persisted locators are hints until this process has observed their terminal root and PID/start marker.
// Mark them dormant before the backend socket can publish anything; the first authoritative reconcile
// reactivates matching process agents without changing their public identity or session binding.
@@ -1546,6 +1548,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// applied: some scans land at once and some straddle an agent's start, as on a loaded machine. The
// end-to-end suite uses it to put a scan across an engine's start on purpose (e2e/core.e2e.ts).
const slowProbeMs = Number(process.env.HARNESSD_TEST_SLOW_PROBE_MS) || 0
+ const gridAssignments = createGridAssignments({ models: () => ports.models ?? MODELS_OFF, registry,
+ revision: (id) => restartJobs.revision(id), announce: announceSession })
const agentReconciler = new TerminalAgentReconciler({
// The hook server starts before restore. Its early SessionStart hints must not run a full
// discovery scan over rows whose panes have not been recreated yet (and archive those rows).
@@ -1562,6 +1566,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
},
} : {}),
...discovery,
+ onReconciled: gridAssignments.observe,
onProbeStatus: (status) => {
discoveryReady = status.ready
discoveryError = status.error
@@ -2303,6 +2308,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
restartJobs,
paneSwapDeps,
liveBypassPermission,
+ refreshGridAssignment: gridAssignments.refresh,
announceSession,
opencodeDb: OPENCODE_DB,
})
@@ -2372,6 +2378,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
sameRestartTarget,
agentReconciler,
terminalHintMachineName,
+ refreshGridAssignment: gridAssignments.refresh,
announceSession,
relaunchOverrides,
downgradedPermission,
@@ -2425,7 +2432,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// A straight-line assignment, never a wait: if the body never reaches this line the handler stays
// `bootHandoff`, and the fix still lands.
const updateTeardown = (): TeardownStep[] => [
- ['the registry', () => registry.flush()], ['the updater', () => daemonBoot.updaterBeside?.()],
+ ['the registry', () => registry.flush({ exiting: true })], ['the updater', () => daemonBoot.updaterBeside?.()],
['the reconciler', () => agentReconciler.stop()],
['the timers', () => { clearInterval(logTrimTimer); clearInterval(runtimeReconcileTimer); clearInterval(paneTitleSyncTimer) }],
['the question watchers', () => questionWatcher.stopAll()],
@@ -2460,6 +2467,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {
const forGood = (reason: string): boolean => reason === 'revoked' || reason === 'busy'
const shutdown = async (signal: string): Promise<void> => {
console.log(`\n[cli] ${signal} — shutting down`)
+ // A slow teardown may exhaust the master's grace. Persist already acknowledged bindings first.
+ registry.flush({ exiting: true })
// Mid-handoff everything below is already being torn down, and nothing has been started yet: leave
// — a second teardown of closed servers is noise.
if (updateHandoff.restarting()) {
diff --git a/cli/src/core/modelsLink.spec.ts b/cli/src/core/modelsLink.spec.ts
index 40e9d0894..9f65d414a 100644
--- a/cli/src/core/modelsLink.spec.ts
+++ b/cli/src/core/modelsLink.spec.ts
@@ -100,6 +100,15 @@ describe('models in its own process, as the core reaches it', () => {
await expect(setup().port.moveTarget({ gridName: null, model: 'm' })).rejects.toBeInstanceOf(ServiceUnavailableError)
})
+ it('checks the entire assignment batch before returning it', async () => {
+ const processes = [{ key: 'a', engine: 'claude' as const, env: { ANTHROPIC_BASE_URL: RELAY }, args: '' }]
+ const assignments = [{ key: 'a', assignment: { baseUrl: RELAY, model: null } }]
+ const { port, call } = setup({ gridAssignments: { assignments } })
+ expect(await port.gridAssignments(processes)).toEqual(assignments)
+ expect(call).toHaveBeenCalledWith('gridAssignments', { processes })
+ await expect(setup({ gridAssignments: {} }).port.gridAssignments(processes)).rejects.toBeInstanceOf(ServiceUnavailableError)
+ })
+
it("a grid or saved-API launch, as models built it and checked as far as the core hands it on; unavailable when it is not one", async () => {
const request = { engine: 'claude' as const, override: LAUNCH, machine: { hermesSystemManaged: false }, refresh: true }
const launch = { env: { ANTHROPIC_MODEL: 'Small-Q4' }, args: ['--x'], webSearch: 'on', sessionModel: 'grid/Small-Q4' }
diff --git a/cli/src/core/modelsLink.ts b/cli/src/core/modelsLink.ts
index 88fd28fc3..4047d7880 100644
--- a/cli/src/core/modelsLink.ts
+++ b/cli/src/core/modelsLink.ts
@@ -1,3 +1,4 @@
+import { gridAssignmentAnswersIn } from '../lib/gridAssignmentWire.js'
/**
* Models in its own process, as the core reaches it (`HARNESSD_SERVICES=models`; the process's side is
* services/modelsProcess.ts).
@@ -125,6 +126,11 @@ export function createModelsLink(core: Pick<CoreApi, 'agents' | 'account' | 'cli
return { detail: typeof answer.detail === 'string' && answer.detail ? answer.detail : 'Could not read this machine\'s grid endpoint.' }
},
moved: (launch) => tell({ kind: 'moved', launch }),
+ gridAssignments: async (processes) => {
+ const assignments = gridAssignmentAnswersIn((await ask('gridAssignments', { processes })).assignments, processes)
+ if (!assignments) throw new ServiceUnavailableError('models')
+ return assignments
+ },
gridLaunch: async (request) => {
const answer = gridLaunchAnswerIn(await ask('gridLaunch', { ...request }))
if (!answer) throw new ServiceUnavailableError('models')
diff --git a/cli/src/lib/__fixtures__/grid-assignment-shapes.golden.json b/cli/src/lib/__fixtures__/grid-assignment-shapes.golden.json
new file mode 100644
index 000000000..924bd2e94
--- /dev/null
+++ b/cli/src/lib/__fixtures__/grid-assignment-shapes.golden.json
@@ -0,0 +1,928 @@
+{
+ "darwin": {
+ "claude/plain": null,
+ "claude/provider-argument": null,
+ "codex/plain": null,
+ "codex/provider-argument": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "chosen"
+ },
+ "cursor/plain": null,
+ "cursor/provider-argument": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "opencode/plain": null,
+ "opencode/provider-argument": null,
+ "pi/plain": null,
+ "pi/provider-argument": null,
+ "hermes/plain": null,
+ "hermes/provider-argument": null,
+ "commandcode/plain": null,
+ "commandcode/provider-argument": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "devin/plain": null,
+ "devin/provider-argument": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "muse/plain": null,
+ "muse/provider-argument": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "amp/plain": null,
+ "amp/provider-argument": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "kilo/plain": null,
+ "kilo/provider-argument": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "grok/plain": null,
+ "grok/provider-argument": null,
+ "agy/plain": null,
+ "agy/provider-argument": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "copilot/plain": null,
+ "copilot/provider-argument": null,
+ "terminal/plain": null,
+ "terminal/provider-argument": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "claude/env//": null,
+ "claude/env//chosen": null,
+ "claude/env//Auto": null,
+ "claude/env//aUtO": null,
+ "claude/env/ /": null,
+ "claude/env/ /chosen": null,
+ "claude/env/ /Auto": null,
+ "claude/env/ /aUtO": null,
+ "claude/env/not-a-url/": null,
+ "claude/env/not-a-url/chosen": null,
+ "claude/env/not-a-url/Auto": null,
+ "claude/env/not-a-url/aUtO": null,
+ "claude/env/https://other.example/v1/": null,
+ "claude/env/https://other.example/v1/chosen": null,
+ "claude/env/https://other.example/v1/Auto": null,
+ "claude/env/https://other.example/v1/aUtO": null,
+ "claude/env/https://grid.example/relayish/v1/": null,
+ "claude/env/https://grid.example/relayish/v1/chosen": null,
+ "claude/env/https://grid.example/relayish/v1/Auto": null,
+ "claude/env/https://grid.example/relayish/v1/aUtO": null,
+ "claude/env/https://grid.example/g/home/relay/v1/": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "claude/env/https://grid.example/g/home/relay/v1/chosen": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "chosen"
+ },
+ "claude/env/https://grid.example/g/home/relay/v1/Auto": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "Auto"
+ },
+ "claude/env/https://grid.example/g/home/relay/v1/aUtO": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "aUtO"
+ },
+ "claude/env/ https://grid.example/g/home/relay/v1 /": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "claude/env/ https://grid.example/g/home/relay/v1 /chosen": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "chosen"
+ },
+ "claude/env/ https://grid.example/g/home/relay/v1 /Auto": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "Auto"
+ },
+ "claude/env/ https://grid.example/g/home/relay/v1 /aUtO": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "aUtO"
+ },
+ "hermes/env//": null,
+ "hermes/env//chosen": null,
+ "hermes/env//Auto": null,
+ "hermes/env//aUtO": null,
+ "hermes/env/ /": null,
+ "hermes/env/ /chosen": null,
+ "hermes/env/ /Auto": null,
+ "hermes/env/ /aUtO": null,
+ "hermes/env/not-a-url/": null,
+ "hermes/env/not-a-url/chosen": null,
+ "hermes/env/not-a-url/Auto": null,
+ "hermes/env/not-a-url/aUtO": null,
+ "hermes/env/https://other.example/v1/": null,
+ "hermes/env/https://other.example/v1/chosen": null,
+ "hermes/env/https://other.example/v1/Auto": null,
+ "hermes/env/https://other.example/v1/aUtO": null,
+ "hermes/env/https://grid.example/relayish/v1/": null,
+ "hermes/env/https://grid.example/relayish/v1/chosen": null,
+ "hermes/env/https://grid.example/relayish/v1/Auto": null,
+ "hermes/env/https://grid.example/relayish/v1/aUtO": null,
+ "hermes/env/https://grid.example/g/home/relay/v1/": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "hermes/env/https://grid.example/g/home/relay/v1/chosen": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "chosen"
+ },
+ "hermes/env/https://grid.example/g/home/relay/v1/Auto": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "Auto"
+ },
+ "hermes/env/https://grid.example/g/home/relay/v1/aUtO": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "aUtO"
+ },
+ "hermes/env/ https://grid.example/g/home/relay/v1 /": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "hermes/env/ https://grid.example/g/home/relay/v1 /chosen": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "chosen"
+ },
+ "hermes/env/ https://grid.example/g/home/relay/v1 /Auto": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "Auto"
+ },
+ "hermes/env/ https://grid.example/g/home/relay/v1 /aUtO": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "aUtO"
+ },
+ "grok/env//": null,
+ "grok/env//chosen": null,
+ "grok/env//Auto": null,
+ "grok/env//aUtO": null,
+ "grok/env/ /": null,
+ "grok/env/ /chosen": null,
+ "grok/env/ /Auto": null,
+ "grok/env/ /aUtO": null,
+ "grok/env/not-a-url/": null,
+ "grok/env/not-a-url/chosen": null,
+ "grok/env/not-a-url/Auto": null,
+ "grok/env/not-a-url/aUtO": null,
+ "grok/env/https://other.example/v1/": null,
+ "grok/env/https://other.example/v1/chosen": null,
+ "grok/env/https://other.example/v1/Auto": null,
+ "grok/env/https://other.example/v1/aUtO": null,
+ "grok/env/https://grid.example/relayish/v1/": null,
+ "grok/env/https://grid.example/relayish/v1/chosen": null,
+ "grok/env/https://grid.example/relayish/v1/Auto": null,
+ "grok/env/https://grid.example/relayish/v1/aUtO": null,
+ "grok/env/https://grid.example/g/home/relay/v1/": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "argv-model"
+ },
+ "grok/env/https://grid.example/g/home/relay/v1/chosen": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "chosen"
+ },
+ "grok/env/https://grid.example/g/home/relay/v1/Auto": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "grok/env/https://grid.example/g/home/relay/v1/aUtO": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "grok/env/ https://grid.example/g/home/relay/v1 /": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "argv-model"
+ },
+ "grok/env/ https://grid.example/g/home/relay/v1 /chosen": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "chosen"
+ },
+ "grok/env/ https://grid.example/g/home/relay/v1 /Auto": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "grok/env/ https://grid.example/g/home/relay/v1 /aUtO": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "copilot/env//": null,
+ "copilot/env//chosen": null,
+ "copilot/env//Auto": null,
+ "copilot/env//aUtO": null,
+ "copilot/env/ /": null,
+ "copilot/env/ /chosen": null,
+ "copilot/env/ /Auto": null,
+ "copilot/env/ /aUtO": null,
+ "copilot/env/not-a-url/": null,
+ "copilot/env/not-a-url/chosen": null,
+ "copilot/env/not-a-url/Auto": null,
+ "copilot/env/not-a-url/aUtO": null,
+ "copilot/env/https://other.example/v1/": null,
+ "copilot/env/https://other.example/v1/chosen": null,
+ "copilot/env/https://other.example/v1/Auto": null,
+ "copilot/env/https://other.example/v1/aUtO": null,
+ "copilot/env/https://grid.example/relayish/v1/": null,
+ "copilot/env/https://grid.example/relayish/v1/chosen": null,
+ "copilot/env/https://grid.example/relayish/v1/Auto": null,
+ "copilot/env/https://grid.example/relayish/v1/aUtO": null,
+ "copilot/env/https://grid.example/g/home/relay/v1/": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "copilot/env/https://grid.example/g/home/relay/v1/chosen": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "chosen"
+ },
+ "copilot/env/https://grid.example/g/home/relay/v1/Auto": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "Auto"
+ },
+ "copilot/env/https://grid.example/g/home/relay/v1/aUtO": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "aUtO"
+ },
+ "copilot/env/ https://grid.example/g/home/relay/v1 /": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "copilot/env/ https://grid.example/g/home/relay/v1 /chosen": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "chosen"
+ },
+ "copilot/env/ https://grid.example/g/home/relay/v1 /Auto": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "Auto"
+ },
+ "copilot/env/ https://grid.example/g/home/relay/v1 /aUtO": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "aUtO"
+ },
+ "codex/argv/": null,
+ "codex/argv/-c model_providers.other.base_url=https://grid.example/g/home/relay/v1": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "codex/argv/-c model_providers.other.base_url=\"https://grid.example/g/home/relay/v1\" -m chosen": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "chosen"
+ },
+ "codex/argv/-c model_providers.other.base_url=\"https://grid.example/g/home/relay/v1\" -m Auto": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "Auto"
+ },
+ "codex/argv/-c model_providers.grid.base_url=\"bad\" -m chosen": null,
+ "pi/broken/": null,
+ "pi/broken/--model grid/chosen": null,
+ "pi/broken/--model grid/Auto": null,
+ "pi/broken/--model other/chosen": null,
+ "pi/absent/": null,
+ "pi/absent/--model grid/chosen": null,
+ "pi/absent/--model grid/Auto": null,
+ "pi/absent/--model other/chosen": null,
+ "pi/wrong/": null,
+ "pi/wrong/--model grid/chosen": null,
+ "pi/wrong/--model grid/Auto": null,
+ "pi/wrong/--model other/chosen": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "chosen"
+ },
+ "pi/direct/": null,
+ "pi/direct/--model grid/chosen": null,
+ "pi/direct/--model grid/Auto": null,
+ "pi/direct/--model other/chosen": null,
+ "pi/valid/": null,
+ "pi/valid/--model grid/chosen": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "chosen"
+ },
+ "pi/valid/--model grid/Auto": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "Auto"
+ },
+ "pi/valid/--model other/chosen": null,
+ "pi/missing-file": null,
+ "opencode/broken": null,
+ "opencode/absent": null,
+ "opencode/many": null,
+ "opencode/noModel": null,
+ "opencode/manyModels": null,
+ "opencode/direct": null,
+ "opencode/model": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "chosen"
+ },
+ "opencode/router": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "opencode/missing-file": null,
+ "claude/launch-roundtrip/null": {
+ "baseUrl": "https://grid.example/g/home/relay",
+ "model": null
+ },
+ "claude/launch-roundtrip/chosen": {
+ "baseUrl": "https://grid.example/g/home/relay",
+ "model": "chosen"
+ },
+ "codex/launch-roundtrip/null": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "codex/launch-roundtrip/chosen": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "chosen"
+ },
+ "opencode/launch-roundtrip/null": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "opencode/launch-roundtrip/chosen": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "chosen"
+ },
+ "hermes/launch-roundtrip/null": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "hermes/launch-roundtrip/chosen": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "chosen"
+ },
+ "grok/launch-roundtrip/null": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "grok/launch-roundtrip/chosen": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "chosen"
+ },
+ "pi/launch-roundtrip/null": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "Auto"
+ },
+ "pi/launch-roundtrip/chosen": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "chosen"
+ },
+ "copilot/launch-roundtrip/null": {
+ "ok": false,
+ "error": "GRID_MODEL_REQUIRED",
+ "detail": "copilot will not start against a grid without a model. Pick one for Home and try again."
+ },
+ "copilot/launch-roundtrip/chosen": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "chosen"
+ },
+ "saved/before-save": null,
+ "saved/list": [
+ {
+ "id": "saved",
+ "provider": "custom",
+ "name": "Saved",
+ "baseUrl": "https://saved.example/inference/v1",
+ "keyEnv": "SAVED_API_KEY",
+ "authHeader": "Authorization",
+ "authPrefix": "Bearer"
+ }
+ ],
+ "saved/anthropic": {
+ "baseUrl": "https://saved.example/inference",
+ "model": "chosen"
+ },
+ "saved/openai": {
+ "baseUrl": "https://saved.example/inference/v1",
+ "model": "chosen"
+ },
+ "instructions/claude": {
+ "AGENTS.md": "# Existing rules\n",
+ "CLAUDE.md": "<!-- harness:apis -->\n## Saved APIs\n\nThe user can save API connections in Harness → Models → APIs on this computer.\nRun `harness api list --json` to discover the current connections; the list contains no keys.\nUse `harness api request <id> <path> --method POST --data @request.json` for JSON APIs,\nor `harness api run <id> -- <command> [args]` for a provider SDK/tool. The latter supplies\nthe connection's documented key variable and HARNESS_API_BASE_URL to that tool only.\nUse these APIs when needed for the user's task. Never print, paste, or save API keys in a project.\nAdding an API does not change this harness's model or subscription.\n"
+ },
+ "instructions/codex": {
+ "AGENTS.md": "# Existing rules\n\n<!-- harness:apis -->\n## Saved APIs\n\nThe user can save API connections in Harness → Models → APIs on this computer.\nRun `harness api list --json` to discover the current connections; the list contains no keys.\nUse `harness api request <id> <path> --method POST --data @request.json` for JSON APIs,\nor `harness api run <id> -- <command> [args]` for a provider SDK/tool. The latter supplies\nthe connection's documented key variable and HARNESS_API_BASE_URL to that tool only.\nUse these APIs when needed for the user's task. Never print, paste, or save API keys in a project.\nAdding an API does not change this harness's model or subscription.\n"
+ },
+ "instructions/cursor": {
+ "AGENTS.md": "# Existing rules\n\n<!-- harness:apis -->\n## Saved APIs\n\nThe user can save API connections in Harness → Models → APIs on this computer.\nRun `harness api list --json` to discover the current connections; the list contains no keys.\nUse `harness api request <id> <path> --method POST --data @request.json` for JSON APIs,\nor `harness api run <id> -- <command> [args]` for a provider SDK/tool. The latter supplies\nthe connection's documented key variable and HARNESS_API_BASE_URL to that tool only.\nUse these APIs when needed for the user's task. Never print, paste, or save API keys in a project.\nAdding an API does not change this harness's model or subscription.\n"
+ },
+ "instructions/opencode": {
+ "AGENTS.md": "# Existing rules\n\n<!-- harness:apis -->\n## Saved APIs\n\nThe user can save API connections in Harness → Models → APIs on this computer.\nRun `harness api list --json` to discover the current connections; the list contains no keys.\nUse `harness api request <id> <path> --method POST --data @request.json` for JSON APIs,\nor `harness api run <id> -- <command> [args]` for a provider SDK/tool. The latter supplies\nthe connection's documented key variable and HARNESS_API_BASE_URL to that tool only.\nUse these APIs when needed for the user's task. Never print, paste, or save API keys in a project.\nAdding an API does not change this harness's model or subscription.\n"
+ },
+ "instructions/pi": {
+ "AGENTS.md": "# Existing rules\n\n<!-- harness:apis -->\n## Saved APIs\n\nThe user can save API connections in Harness → Models → APIs on this computer.\nRun `harness api list --json` to discover the current connections; the list contains no keys.\nUse `harness api request <id> <path> --method POST --data @request.json` for JSON APIs,\nor `harness api run <id> -- <command> [args]` for a provider SDK/tool. The latter supplies\nthe connection's documented key variable and HARNESS_API_BASE_URL to that tool only.\nUse these APIs when needed for the user's task. Never print, paste, or save API keys in a project.\nAdding an API does not change this harness's model or subscription.\n"
+ },
+ "instructions/hermes": {
+ "AGENTS.md": "# Existing rules\n\n<!-- harness:apis -->\n## Saved APIs\n\nThe user can save API connections in Harness → Models → APIs on this computer.\nRun `harness api list --json` to discover the current connections; the list contains no keys.\nUse `harness api request <id> <path> --method POST --data @request.json` for JSON APIs,\nor `harness api run <id> -- <command> [args]` for a provider SDK/tool. The latter supplies\nthe connection's documented key variable and HARNESS_API_BASE_URL to that tool only.\nUse these APIs when needed for the user's task. Never print, paste, or save API keys in a project.\nAdding an API does not change this harness's model or subscription.\n"
+ },
+ "instructions/commandcode": {
+ "AGENTS.md": "# Existing rules\n\n<!-- harness:apis -->\n## Saved APIs\n\nThe user can save API connections in Harness → Models → APIs on this computer.\nRun `harness api list --json` to discover the current connections; the list contains no keys.\nUse `harness api request <id> <path> --method POST --data @request.json` for JSON APIs,\nor `harness api run <id> -- <command> [args]` for a provider SDK/tool. The latter supplies\nthe connection's documented key variable and HARNESS_API_BASE_URL to that tool only.\nUse these APIs when needed for the user's task. Never print, paste, or save API keys in a project.\nAdding an API does not change this harness's model or subscription.\n"
+ },
+ "instructions/devin": {
+ "AGENTS.md": "# Existing rules\n\n<!-- harness:apis -->\n## Saved APIs\n\nThe user can save API connections in Harness → Models → APIs on this computer.\nRun `harness api list --json` to discover the current connections; the list contains no keys.\nUse `harness api request <id> <path> --method POST --data @request.json` for JSON APIs,\nor `harness api run <id> -- <command> [args]` for a provider SDK/tool. The latter supplies\nthe connection's documented key variable and HARNESS_API_BASE_URL to that tool only.\nUse these APIs when needed for the user's task. Never print, paste, or save API keys in a project.\nAdding an API does not change this harness's model or subscription.\n"
+ },
+ "instructions/muse": {
+ "AGENTS.md": "# Existing rules\n\n<!-- harness:apis -->\n## Saved APIs\n\nThe user can save API connections in Harness → Models → APIs on this computer.\nRun `harness api list --json` to discover the current connections; the list contains no keys.\nUse `harness api request <id> <path> --method POST --data @request.json` for JSON APIs,\nor `harness api run <id> -- <command> [args]` for a provider SDK/tool. The latter supplies\nthe connection's documented key variable and HARNESS_API_BASE_URL to that tool only.\nUse these APIs when needed for the user's task. Never print, paste, or save API keys in a project.\nAdding an API does not change this harness's model or subscription.\n"
+ },
+ "instructions/amp": {
+ "AGENTS.md": "# Existing rules\n\n<!-- harness:apis -->\n## Saved APIs\n\nThe user can save API connections in Harness → Models → APIs on this computer.\nRun `harness api list --json` to discover the current connections; the list contains no keys.\nUse `harness api request <id> <path> --method POST --data @request.json` for JSON APIs,\nor `harness api run <id> -- <command> [args]` for a provider SDK/tool. The latter supplies\nthe connection's documented key variable and HARNESS_API_BASE_URL to that tool only.\nUse these APIs when needed for the user's task. Never print, paste, or save API keys in a project.\nAdding an API does not change this harness's model or subscription.\n"
+ },
+ "instructions/kilo": {
+ "AGENTS.md": "# Existing rules\n\n<!-- harness:apis -->\n## Saved APIs\n\nThe user can save API connections in Harness → Models → APIs on this computer.\nRun `harness api list --json` to discover the current connections; the list contains no keys.\nUse `harness api request <id> <path> --method POST --data @request.json` for JSON APIs,\nor `harness api run <id> -- <command> [args]` for a provider SDK/tool. The latter supplies\nthe connection's documented key variable and HARNESS_API_BASE_URL to that tool only.\nUse these APIs when needed for the user's task. Never print, paste, or save API keys in a project.\nAdding an API does not change this harness's model or subscription.\n"
+ },
+ "instructions/grok": {
+ "AGENTS.md": "# Existing rules\n\n<!-- harness:apis -->\n## Saved APIs\n\nThe user can save API connections in Harness → Models → APIs on this computer.\nRun `harness api list --json` to discover the current connections; the list contains no keys.\nUse `harness api request <id> <path> --method POST --data @request.json` for JSON APIs,\nor `harness api run <id> -- <command> [args]` for a provider SDK/tool. The latter supplies\nthe connection's documented key variable and HARNESS_API_BASE_URL to that tool only.\nUse these APIs when needed for the user's task. Never print, paste, or save API keys in a project.\nAdding an API does not change this harness's model or subscription.\n"
+ },
+ "instructions/agy": {
+ "AGENTS.md": "# Existing rules\n\n<!-- harness:apis -->\n## Saved APIs\n\nThe user can save API connections in Harness → Models → APIs on this computer.\nRun `harness api list --json` to discover the current connections; the list contains no keys.\nUse `harness api request <id> <path> --method POST --data @request.json` for JSON APIs,\nor `harness api run <id> -- <command> [args]` for a provider SDK/tool. The latter supplies\nthe connection's documented key variable and HARNESS_API_BASE_URL to that tool only.\nUse these APIs when needed for the user's task. Never print, paste, or save API keys in a project.\nAdding an API does not change this harness's model or subscription.\n"
+ },
+ "instructions/copilot": {
+ "AGENTS.md": "# Existing rules\n\n<!-- harness:apis -->\n## Saved APIs\n\nThe user can save API connections in Harness → Models → APIs on this computer.\nRun `harness api list --json` to discover the current connections; the list contains no keys.\nUse `harness api request <id> <path> --method POST --data @request.json` for JSON APIs,\nor `harness api run <id> -- <command> [args]` for a provider SDK/tool. The latter supplies\nthe connection's documented key variable and HARNESS_API_BASE_URL to that tool only.\nUse these APIs when needed for the user's task. Never print, paste, or save API keys in a project.\nAdding an API does not change this harness's model or subscription.\n"
+ },
+ "instructions/terminal": {
+ "AGENTS.md": "# Existing rules\n"
+ },
+ "instructions/gemini": {
+ "AGENTS.md": "# Existing rules\n",
+ "GEMINI.md": "<!-- harness:apis -->\n## Saved APIs\n\nThe user can save API connections in Harness → Models → APIs on this computer.\nRun `harness api list --json` to discover the current connections; the list contains no keys.\nUse `harness api request <id> <path> --method POST --data @request.json` for JSON APIs,\nor `harness api run <id> -- <command> [args]` for a provider SDK/tool. The latter supplies\nthe connection's documented key variable and HARNESS_API_BASE_URL to that tool only.\nUse these APIs when needed for the user's task. Never print, paste, or save API keys in a project.\nAdding an API does not change this harness's model or subscription.\n"
+ },
+ "saved/after-removal": {
+ "baseUrl": "https://saved.example/inference/v1",
+ "model": "chosen"
+ },
+ "instructions/no-saved-api": [],
+ "instructions/unreadable": "Saved APIs could not be read. Your keys have not been changed.",
+ "saved/unreadable": {
+ "baseUrl": "https://saved.example/inference/v1",
+ "model": "chosen"
+ }
+ },
+ "linux": {
+ "claude/plain": null,
+ "claude/provider-argument": null,
+ "codex/plain": null,
+ "codex/provider-argument": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "chosen"
+ },
+ "cursor/plain": null,
+ "cursor/provider-argument": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "opencode/plain": null,
+ "opencode/provider-argument": null,
+ "pi/plain": null,
+ "pi/provider-argument": null,
+ "hermes/plain": null,
+ "hermes/provider-argument": null,
+ "commandcode/plain": null,
+ "commandcode/provider-argument": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "devin/plain": null,
+ "devin/provider-argument": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "muse/plain": null,
+ "muse/provider-argument": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "amp/plain": null,
+ "amp/provider-argument": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "kilo/plain": null,
+ "kilo/provider-argument": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "grok/plain": null,
+ "grok/provider-argument": null,
+ "agy/plain": null,
+ "agy/provider-argument": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "copilot/plain": null,
+ "copilot/provider-argument": null,
+ "terminal/plain": null,
+ "terminal/provider-argument": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "claude/env//": null,
+ "claude/env//chosen": null,
+ "claude/env//Auto": null,
+ "claude/env//aUtO": null,
+ "claude/env/ /": null,
+ "claude/env/ /chosen": null,
+ "claude/env/ /Auto": null,
+ "claude/env/ /aUtO": null,
+ "claude/env/not-a-url/": null,
+ "claude/env/not-a-url/chosen": null,
+ "claude/env/not-a-url/Auto": null,
+ "claude/env/not-a-url/aUtO": null,
+ "claude/env/https://other.example/v1/": null,
+ "claude/env/https://other.example/v1/chosen": null,
+ "claude/env/https://other.example/v1/Auto": null,
+ "claude/env/https://other.example/v1/aUtO": null,
+ "claude/env/https://grid.example/relayish/v1/": null,
+ "claude/env/https://grid.example/relayish/v1/chosen": null,
+ "claude/env/https://grid.example/relayish/v1/Auto": null,
+ "claude/env/https://grid.example/relayish/v1/aUtO": null,
+ "claude/env/https://grid.example/g/home/relay/v1/": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "claude/env/https://grid.example/g/home/relay/v1/chosen": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "chosen"
+ },
+ "claude/env/https://grid.example/g/home/relay/v1/Auto": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "Auto"
+ },
+ "claude/env/https://grid.example/g/home/relay/v1/aUtO": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "aUtO"
+ },
+ "claude/env/ https://grid.example/g/home/relay/v1 /": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "claude/env/ https://grid.example/g/home/relay/v1 /chosen": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "chosen"
+ },
+ "claude/env/ https://grid.example/g/home/relay/v1 /Auto": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "Auto"
+ },
+ "claude/env/ https://grid.example/g/home/relay/v1 /aUtO": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "aUtO"
+ },
+ "hermes/env//": null,
+ "hermes/env//chosen": null,
+ "hermes/env//Auto": null,
+ "hermes/env//aUtO": null,
+ "hermes/env/ /": null,
+ "hermes/env/ /chosen": null,
+ "hermes/env/ /Auto": null,
+ "hermes/env/ /aUtO": null,
+ "hermes/env/not-a-url/": null,
+ "hermes/env/not-a-url/chosen": null,
+ "hermes/env/not-a-url/Auto": null,
+ "hermes/env/not-a-url/aUtO": null,
+ "hermes/env/https://other.example/v1/": null,
+ "hermes/env/https://other.example/v1/chosen": null,
+ "hermes/env/https://other.example/v1/Auto": null,
+ "hermes/env/https://other.example/v1/aUtO": null,
+ "hermes/env/https://grid.example/relayish/v1/": null,
+ "hermes/env/https://grid.example/relayish/v1/chosen": null,
+ "hermes/env/https://grid.example/relayish/v1/Auto": null,
+ "hermes/env/https://grid.example/relayish/v1/aUtO": null,
+ "hermes/env/https://grid.example/g/home/relay/v1/": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "hermes/env/https://grid.example/g/home/relay/v1/chosen": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "chosen"
+ },
+ "hermes/env/https://grid.example/g/home/relay/v1/Auto": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "Auto"
+ },
+ "hermes/env/https://grid.example/g/home/relay/v1/aUtO": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "aUtO"
+ },
+ "hermes/env/ https://grid.example/g/home/relay/v1 /": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "hermes/env/ https://grid.example/g/home/relay/v1 /chosen": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "chosen"
+ },
+ "hermes/env/ https://grid.example/g/home/relay/v1 /Auto": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "Auto"
+ },
+ "hermes/env/ https://grid.example/g/home/relay/v1 /aUtO": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "aUtO"
+ },
+ "grok/env//": null,
+ "grok/env//chosen": null,
+ "grok/env//Auto": null,
+ "grok/env//aUtO": null,
+ "grok/env/ /": null,
+ "grok/env/ /chosen": null,
+ "grok/env/ /Auto": null,
+ "grok/env/ /aUtO": null,
+ "grok/env/not-a-url/": null,
+ "grok/env/not-a-url/chosen": null,
+ "grok/env/not-a-url/Auto": null,
+ "grok/env/not-a-url/aUtO": null,
+ "grok/env/https://other.example/v1/": null,
+ "grok/env/https://other.example/v1/chosen": null,
+ "grok/env/https://other.example/v1/Auto": null,
+ "grok/env/https://other.example/v1/aUtO": null,
+ "grok/env/https://grid.example/relayish/v1/": null,
+ "grok/env/https://grid.example/relayish/v1/chosen": null,
+ "grok/env/https://grid.example/relayish/v1/Auto": null,
+ "grok/env/https://grid.example/relayish/v1/aUtO": null,
+ "grok/env/https://grid.example/g/home/relay/v1/": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "argv-model"
+ },
+ "grok/env/https://grid.example/g/home/relay/v1/chosen": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "chosen"
+ },
+ "grok/env/https://grid.example/g/home/relay/v1/Auto": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "grok/env/https://grid.example/g/home/relay/v1/aUtO": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "grok/env/ https://grid.example/g/home/relay/v1 /": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "argv-model"
+ },
+ "grok/env/ https://grid.example/g/home/relay/v1 /chosen": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "chosen"
+ },
+ "grok/env/ https://grid.example/g/home/relay/v1 /Auto": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "grok/env/ https://grid.example/g/home/relay/v1 /aUtO": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "copilot/env//": null,
+ "copilot/env//chosen": null,
+ "copilot/env//Auto": null,
+ "copilot/env//aUtO": null,
+ "copilot/env/ /": null,
+ "copilot/env/ /chosen": null,
+ "copilot/env/ /Auto": null,
+ "copilot/env/ /aUtO": null,
+ "copilot/env/not-a-url/": null,
+ "copilot/env/not-a-url/chosen": null,
+ "copilot/env/not-a-url/Auto": null,
+ "copilot/env/not-a-url/aUtO": null,
+ "copilot/env/https://other.example/v1/": null,
+ "copilot/env/https://other.example/v1/chosen": null,
+ "copilot/env/https://other.example/v1/Auto": null,
+ "copilot/env/https://other.example/v1/aUtO": null,
+ "copilot/env/https://grid.example/relayish/v1/": null,
+ "copilot/env/https://grid.example/relayish/v1/chosen": null,
+ "copilot/env/https://grid.example/relayish/v1/Auto": null,
+ "copilot/env/https://grid.example/relayish/v1/aUtO": null,
+ "copilot/env/https://grid.example/g/home/relay/v1/": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "copilot/env/https://grid.example/g/home/relay/v1/chosen": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "chosen"
+ },
+ "copilot/env/https://grid.example/g/home/relay/v1/Auto": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "Auto"
+ },
+ "copilot/env/https://grid.example/g/home/relay/v1/aUtO": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "aUtO"
+ },
+ "copilot/env/ https://grid.example/g/home/relay/v1 /": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "copilot/env/ https://grid.example/g/home/relay/v1 /chosen": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "chosen"
+ },
+ "copilot/env/ https://grid.example/g/home/relay/v1 /Auto": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "Auto"
+ },
+ "copilot/env/ https://grid.example/g/home/relay/v1 /aUtO": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "aUtO"
+ },
+ "codex/argv/": null,
+ "codex/argv/-c model_providers.other.base_url=https://grid.example/g/home/relay/v1": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "codex/argv/-c model_providers.other.base_url=\"https://grid.example/g/home/relay/v1\" -m chosen": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "chosen"
+ },
+ "codex/argv/-c model_providers.other.base_url=\"https://grid.example/g/home/relay/v1\" -m Auto": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "Auto"
+ },
+ "codex/argv/-c model_providers.grid.base_url=\"bad\" -m chosen": null,
+ "pi/broken/": null,
+ "pi/broken/--model grid/chosen": null,
+ "pi/broken/--model grid/Auto": null,
+ "pi/broken/--model other/chosen": null,
+ "pi/absent/": null,
+ "pi/absent/--model grid/chosen": null,
+ "pi/absent/--model grid/Auto": null,
+ "pi/absent/--model other/chosen": null,
+ "pi/wrong/": null,
+ "pi/wrong/--model grid/chosen": null,
+ "pi/wrong/--model grid/Auto": null,
+ "pi/wrong/--model other/chosen": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "chosen"
+ },
+ "pi/direct/": null,
+ "pi/direct/--model grid/chosen": null,
+ "pi/direct/--model grid/Auto": null,
+ "pi/direct/--model other/chosen": null,
+ "pi/valid/": null,
+ "pi/valid/--model grid/chosen": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "chosen"
+ },
+ "pi/valid/--model grid/Auto": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "Auto"
+ },
+ "pi/valid/--model other/chosen": null,
+ "pi/missing-file": null,
+ "opencode/broken": null,
+ "opencode/absent": null,
+ "opencode/many": null,
+ "opencode/noModel": null,
+ "opencode/manyModels": null,
+ "opencode/direct": null,
+ "opencode/model": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "chosen"
+ },
+ "opencode/router": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "opencode/missing-file": null,
+ "claude/launch-roundtrip/null": {
+ "baseUrl": "https://grid.example/g/home/relay",
+ "model": null
+ },
+ "claude/launch-roundtrip/chosen": {
+ "baseUrl": "https://grid.example/g/home/relay",
+ "model": "chosen"
+ },
+ "codex/launch-roundtrip/null": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "codex/launch-roundtrip/chosen": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "chosen"
+ },
+ "opencode/launch-roundtrip/null": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "opencode/launch-roundtrip/chosen": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "chosen"
+ },
+ "hermes/launch-roundtrip/null": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "hermes/launch-roundtrip/chosen": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "chosen"
+ },
+ "grok/launch-roundtrip/null": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": null
+ },
+ "grok/launch-roundtrip/chosen": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "chosen"
+ },
+ "pi/launch-roundtrip/null": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "Auto"
+ },
+ "pi/launch-roundtrip/chosen": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "chosen"
+ },
+ "copilot/launch-roundtrip/null": {
+ "ok": false,
+ "error": "GRID_MODEL_REQUIRED",
+ "detail": "copilot will not start against a grid without a model. Pick one for Home and try again."
+ },
+ "copilot/launch-roundtrip/chosen": {
+ "baseUrl": "https://grid.example/g/home/relay/v1",
+ "model": "chosen"
+ },
+ "saved/before-save": null,
+ "saved/list": [
+ {
+ "id": "saved",
+ "provider": "custom",
+ "name": "Saved",
+ "baseUrl": "https://saved.example/inference/v1",
+ "keyEnv": "SAVED_API_KEY",
+ "authHeader": "Authorization",
+ "authPrefix": "Bearer"
+ }
+ ],
+ "saved/anthropic": {
+ "baseUrl": "https://saved.example/inference",
+ "model": "chosen"
+ },
+ "saved/openai": {
+ "baseUrl": "https://saved.example/inference/v1",
+ "model": "chosen"
+ },
+ "instructions/claude": {
+ "AGENTS.md": "# Existing rules\n",
+ "CLAUDE.md": "<!-- harness:apis -->\n## Saved APIs\n\nThe user can save API connections in Harness → Models → APIs on this computer.\nRun `harness api list --json` to discover the current connections; the list contains no keys.\nUse `harness api request <id> <path> --method POST --data @request.json` for JSON APIs,\nor `harness api run <id> -- <command> [args]` for a provider SDK/tool. The latter supplies\nthe connection's documented key variable and HARNESS_API_BASE_URL to that tool only.\nUse these APIs when needed for the user's task. Never print, paste, or save API keys in a project.\nAdding an API does not change this harness's model or subscription.\n"
+ },
+ "instructions/codex": {
+ "AGENTS.md": "# Existing rules\n\n<!-- harness:apis -->\n## Saved APIs\n\nThe user can save API connections in Harness → Models → APIs on this computer.\nRun `harness api list --json` to discover the current connections; the list contains no keys.\nUse `harness api request <id> <path> --method POST --data @request.json` for JSON APIs,\nor `harness api run <id> -- <command> [args]` for a provider SDK/tool. The latter supplies\nthe connection's documented key variable and HARNESS_API_BASE_URL to that tool only.\nUse these APIs when needed for the user's task. Never print, paste, or save API keys in a project.\nAdding an API does not change this harness's model or subscription.\n"
+ },
+ "instructions/cursor": {
+ "AGENTS.md": "# Existing rules\n\n<!-- harness:apis -->\n## Saved APIs\n\nThe user can save API connections in Harness → Models → APIs on this computer.\nRun `harness api list --json` to discover the current connections; the list contains no keys.\nUse `harness api request <id> <path> --method POST --data @request.json` for JSON APIs,\nor `harness api run <id> -- <command> [args]` for a provider SDK/tool. The latter supplies\nthe connection's documented key variable and HARNESS_API_BASE_URL to that tool only.\nUse these APIs when needed for the user's task. Never print, paste, or save API keys in a project.\nAdding an API does not change this harness's model or subscription.\n"
+ },
+ "instructions/opencode": {
+ "AGENTS.md": "# Existing rules\n\n<!-- harness:apis -->\n## Saved APIs\n\nThe user can save API connections in Harness → Models → APIs on this computer.\nRun `harness api list --json` to discover the current connections; the list contains no keys.\nUse `harness api request <id> <path> --method POST --data @request.json` for JSON APIs,\nor `harness api run <id> -- <command> [args]` for a provider SDK/tool. The latter supplies\nthe connection's documented key variable and HARNESS_API_BASE_URL to that tool only.\nUse these APIs when needed for the user's task. Never print, paste, or save API keys in a project.\nAdding an API does not change this harness's model or subscription.\n"
+ },
+ "instructions/pi": {
+ "AGENTS.md": "# Existing rules\n\n<!-- harness:apis -->\n## Saved APIs\n\nThe user can save API connections in Harness → Models → APIs on this computer.\nRun `harness api list --json` to discover the current connections; the list contains no keys.\nUse `harness api request <id> <path> --method POST --data @request.json` for JSON APIs,\nor `harness api run <id> -- <command> [args]` for a provider SDK/tool. The latter supplies\nthe connection's documented key variable and HARNESS_API_BASE_URL to that tool only.\nUse these APIs when needed for the user's task. Never print, paste, or save API keys in a project.\nAdding an API does not change this harness's model or subscription.\n"
+ },
+ "instructions/hermes": {
+ "AGENTS.md": "# Existing rules\n\n<!-- harness:apis -->\n## Saved APIs\n\nThe user can save API connections in Harness → Models → APIs on this computer.\nRun `harness api list --json` to discover the current connections; the list contains no keys.\nUse `harness api request <id> <path> --method POST --data @request.json` for JSON APIs,\nor `harness api run <id> -- <command> [args]` for a provider SDK/tool. The latter supplies\nthe connection's documented key variable and HARNESS_API_BASE_URL to that tool only.\nUse these APIs when needed for the user's task. Never print, paste, or save API keys in a project.\nAdding an API does not change this harness's model or subscription.\n"
+ },
+ "instructions/commandcode": {
+ "AGENTS.md": "# Existing rules\n\n<!-- harness:apis -->\n## Saved APIs\n\nThe user can save API connections in Harness → Models → APIs on this computer.\nRun `harness api list --json` to discover the current connections; the list contains no keys.\nUse `harness api request <id> <path> --method POST --data @request.json` for JSON APIs,\nor `harness api run <id> -- <command> [args]` for a provider SDK/tool. The latter supplies\nthe connection's documented key variable and HARNESS_API_BASE_URL to that tool only.\nUse these APIs when needed for the user's task. Never print, paste, or save API keys in a project.\nAdding an API does not change this harness's model or subscription.\n"
+ },
+ "instructions/devin": {
+ "AGENTS.md": "# Existing rules\n\n<!-- harness:apis -->\n## Saved APIs\n\nThe user can save API connections in Harness → Models → APIs on this computer.\nRun `harness api list --json` to discover the current connections; the list contains no keys.\nUse `harness api request <id> <path> --method POST --data @request.json` for JSON APIs,\nor `harness api run <id> -- <command> [args]` for a provider SDK/tool. The latter supplies\nthe connection's documented key variable and HARNESS_API_BASE_URL to that tool only.\nUse these APIs when needed for the user's task. Never print, paste, or save API keys in a project.\nAdding an API does not change this harness's model or subscription.\n"
+ },
+ "instructions/muse": {
+ "AGENTS.md": "# Existing rules\n\n<!-- harness:apis -->\n## Saved APIs\n\nThe user can save API connections in Harness → Models → APIs on this computer.\nRun `harness api list --json` to discover the current connections; the list contains no keys.\nUse `harness api request <id> <path> --method POST --data @request.json` for JSON APIs,\nor `harness api run <id> -- <command> [args]` for a provider SDK/tool. The latter supplies\nthe connection's documented key variable and HARNESS_API_BASE_URL to that tool only.\nUse these APIs when needed for the user's task. Never print, paste, or save API keys in a project.\nAdding an API does not change this harness's model or subscription.\n"
+ },
+ "instructions/amp": {
+ "AGENTS.md": "# Existing rules\n\n<!-- harness:apis -->\n## Saved APIs\n\nThe user can save API connections in Harness → Models → APIs on this computer.\nRun `harness api list --json` to discover the current connections; the list contains no keys.\nUse `harness api request <id> <path> --method POST --data @request.json` for JSON APIs,\nor `harness api run <id> -- <command> [args]` for a provider SDK/tool. The latter supplies\nthe connection's documented key variable and HARNESS_API_BASE_URL to that tool only.\nUse these APIs when needed for the user's task. Never print, paste, or save API keys in a project.\nAdding an API does not change this harness's model or subscription.\n"
+ },
+ "instructions/kilo": {
+ "AGENTS.md": "# Existing rules\n\n<!-- harness:apis -->\n## Saved APIs\n\nThe user can save API connections in Harness → Models → APIs on this computer.\nRun `harness api list --json` to discover the current connections; the list contains no keys.\nUse `harness api request <id> <path> --method POST --data @request.json` for JSON APIs,\nor `harness api run <id> -- <command> [args]` for a provider SDK/tool. The latter supplies\nthe connection's documented key variable and HARNESS_API_BASE_URL to that tool only.\nUse these APIs when needed for the user's task. Never print, paste, or save API keys in a project.\nAdding an API does not change this harness's model or subscription.\n"
+ },
+ "instructions/grok": {
+ "AGENTS.md": "# Existing rules\n\n<!-- harness:apis -->\n## Saved APIs\n\nThe user can save API connections in Harness → Models → APIs on this computer.\nRun `harness api list --json` to discover the current connections; the list contains no keys.\nUse `harness api request <id> <path> --method POST --data @request.json` for JSON APIs,\nor `harness api run <id> -- <command> [args]` for a provider SDK/tool. The latter supplies\nthe connection's documented key variable and HARNESS_API_BASE_URL to that tool only.\nUse these APIs when needed for the user's task. Never print, paste, or save API keys in a project.\nAdding an API does not change this harness's model or subscription.\n"
+ },
+ "instructions/agy": {
+ "AGENTS.md": "# Existing rules\n\n<!-- harness:apis -->\n## Saved APIs\n\nThe user can save API connections in Harness → Models → APIs on this computer.\nRun `harness api list --json` to discover the current connections; the list contains no keys.\nUse `harness api request <id> <path> --method POST --data @request.json` for JSON APIs,\nor `harness api run <id> -- <command> [args]` for a provider SDK/tool. The latter supplies\nthe connection's documented key variable and HARNESS_API_BASE_URL to that tool only.\nUse these APIs when needed for the user's task. Never print, paste, or save API keys in a project.\nAdding an API does not change this harness's model or subscription.\n"
+ },
+ "instructions/copilot": {
+ "AGENTS.md": "# Existing rules\n\n<!-- harness:apis -->\n## Saved APIs\n\nThe user can save API connections in Harness → Models → APIs on this computer.\nRun `harness api list --json` to discover the current connections; the list contains no keys.\nUse `harness api request <id> <path> --method POST --data @request.json` for JSON APIs,\nor `harness api run <id> -- <command> [args]` for a provider SDK/tool. The latter supplies\nthe connection's documented key variable and HARNESS_API_BASE_URL to that tool only.\nUse these APIs when needed for the user's task. Never print, paste, or save API keys in a project.\nAdding an API does not change this harness's model or subscription.\n"
+ },
+ "instructions/terminal": {
+ "AGENTS.md": "# Existing rules\n"
+ },
+ "instructions/gemini": {
+ "AGENTS.md": "# Existing rules\n",
+ "GEMINI.md": "<!-- harness:apis -->\n## Saved APIs\n\nThe user can save API connections in Harness → Models → APIs on this computer.\nRun `harness api list --json` to discover the current connections; the list contains no keys.\nUse `harness api request <id> <path> --method POST --data @request.json` for JSON APIs,\nor `harness api run <id> -- <command> [args]` for a provider SDK/tool. The latter supplies\nthe connection's documented key variable and HARNESS_API_BASE_URL to that tool only.\nUse these APIs when needed for the user's task. Never print, paste, or save API keys in a project.\nAdding an API does not change this harness's model or subscription.\n"
+ },
+ "saved/after-removal": {
+ "baseUrl": "https://saved.example/inference/v1",
+ "model": "chosen"
+ },
+ "instructions/no-saved-api": [],
+ "instructions/unreadable": "Saved APIs could not be read. Your keys have not been changed.",
+ "saved/unreadable": {
+ "baseUrl": "https://saved.example/inference/v1",
+ "model": "chosen"
+ }
+ }
+}
diff --git a/cli/src/lib/apiConnectionMetadata.ts b/cli/src/lib/apiConnectionMetadata.ts
new file mode 100644
index 000000000..bcf23ee54
--- /dev/null
+++ b/cli/src/lib/apiConnectionMetadata.ts
@@ -0,0 +1,53 @@
+/** The synchronous, validated metadata read needed by every launch's saved-API instructions.
+ * There is one atomic file, no service dependency and no secondary metadata copy to fall out of step. */
+import { existsSync, lstatSync, readFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { z } from 'zod'
+
+const text = z.string().trim().min(1).max(120).regex(/^[^\x00-\x1f\x7f]+$/)
+export const id = z.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/)
+const environmentName = z.string().regex(/^[A-Z][A-Z0-9_]{0,79}$/).refine(
+ value => !/^(PATH|HOME|SHELL|ENV|BASH_ENV|ZDOTDIR|NODE_OPTIONS|LD_.+|DYLD_.+|HARNESS_.+)$/.test(value),
+)
+const baseUrl = z.string().max(2048).url().refine(value => {
+ const url = new URL(value)
+ return ['https:', 'http:'].includes(url.protocol) && !url.username && !url.password && !url.search && !url.hash
+})
+export const metadata = z.object({
+ id,
+ provider: id,
+ name: text,
+ baseUrl,
+ keyEnv: environmentName,
+ authHeader: z.string().regex(/^[A-Za-z][A-Za-z0-9-]{0,79}$/).refine(value =>
+ !['host', 'content-length', 'connection', 'transfer-encoding', 'cookie'].includes(value.toLowerCase())),
+ authPrefix: z.string().trim().max(40).regex(/^[A-Za-z0-9_-]*$/),
+})
+export const stored = metadata.extend({ apiKey: z.string().trim().min(1).max(8192).regex(/^[^\s\x00-\x1f\x7f]+$/) })
+const storeSchema = z.object({ version: z.literal(1), connections: z.array(stored).max(100), recognizedBases: z.array(baseUrl).optional() })
+export type ApiConnection = z.infer<typeof metadata>
+export type StoredConnection = z.infer<typeof stored>
+
+export class ApiConnectionError extends Error {}
+
+export function readApiConnectionStore(dataDir: string): z.infer<typeof storeSchema> {
+ const dir = join(dataDir, 'api-connections')
+ const file = join(dir, 'connections.json')
+ try {
+ if (!existsSync(dir)) return { version: 1, connections: [] }
+ if (!lstatSync(dir).isDirectory() || lstatSync(dir).isSymbolicLink()) throw new Error()
+ if (!existsSync(file)) return { version: 1, connections: [] }
+ const stat = lstatSync(file)
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 2 * 1024 * 1024) throw new Error()
+ const parsed = storeSchema.parse(JSON.parse(readFileSync(file, 'utf8')))
+ if (new Set(parsed.connections.map(row => row.id)).size !== parsed.connections.length) throw new Error()
+ return parsed
+ } catch { throw new ApiConnectionError('Saved APIs could not be read. Your keys have not been changed.') }
+}
+
+
+/** Its only capability is a list without keys. Parse the same store and report the same errors. */
+export class ApiConnectionMetadata {
+ constructor(private readonly dataDir: string) {}
+ list(): ApiConnection[] { return readApiConnectionStore(this.dataDir).connections.map(value => metadata.parse(value)) }
+}
diff --git a/cli/src/lib/apiConnections.spec.ts b/cli/src/lib/apiConnections.spec.ts
index 4676ced9f..eeef50789 100644
--- a/cli/src/lib/apiConnections.spec.ts
+++ b/cli/src/lib/apiConnections.spec.ts
@@ -23,6 +23,44 @@ beforeEach(() => { directory = mkdtempSync(join(tmpdir(), 'harness-api-store-'))
afterEach(() => { vi.restoreAllMocks(); rmSync(directory, { recursive: true, force: true }) })
describe('saved API connections', () => {
+ it('atomically retains edited and removed endpoint vocabulary for a restarted models process', () => {
+ const saved = store.save(custom)
+ store.save({ ...saved, baseUrl: 'https://edited.example.test/v1' })
+ store.remove(saved.id)
+ const restarted = new ApiConnections(directory)
+ expect(restarted.list()).toEqual([])
+ expect(restarted.recognizedBases()).toEqual([custom.baseUrl, 'https://edited.example.test/v1'])
+ const disk = JSON.parse(readFileSync(join(directory, 'api-connections/connections.json'), 'utf8'))
+ expect(disk).toEqual({ version: 1, connections: [], recognizedBases: [custom.baseUrl, 'https://edited.example.test/v1'] })
+ expect(JSON.stringify(disk)).not.toContain(secret)
+ })
+
+ it('upgrades a legacy file without forgetting its old endpoint and fails closed on corrupt vocabulary', () => {
+ const saved = store.save(custom)
+ const file = join(directory, 'api-connections/connections.json')
+ const disk = JSON.parse(readFileSync(file, 'utf8'))
+ delete disk.recognizedBases
+ writeFileSync(file, JSON.stringify(disk))
+ expect(store.recognizedBases()).toEqual([custom.baseUrl])
+ store.remove(saved.id)
+ expect(new ApiConnections(directory).recognizedBases()).toEqual([custom.baseUrl])
+ writeFileSync(file, JSON.stringify({ version: 1, connections: [], recognizedBases: ['https://user:[email protected]/v1'] }))
+ expect(() => store.recognizedBases()).toThrow('Saved APIs could not be read')
+ })
+
+ it('refuses an oversized vocabulary before replacing the saved connections and never prunes it', () => {
+ store.save(custom)
+ const file = join(directory, 'api-connections/connections.json')
+ const disk = JSON.parse(readFileSync(file, 'utf8'))
+ disk.recognizedBases = Array.from({ length: 1100 }, (_, i) => `https://example.test/${i}/${'x'.repeat(1980)}`)
+ // Valid read just below 2 MiB; a new maximum-length endpoint cannot fit.
+ while (Buffer.byteLength(JSON.stringify(disk)) > 2 * 1024 * 1024 - 1000) disk.recognizedBases.pop()
+ const before = JSON.stringify(disk)
+ writeFileSync(file, before)
+ expect(() => store.save({ ...custom, name: 'Another', baseUrl: `https://new.example.test/${'y'.repeat(1990)}` })).toThrow('could not be saved')
+ expect(readFileSync(file, 'utf8')).toBe(before)
+ })
+
it('lists empty storage and presets without creating a file or calling any API', () => {
expect(store.list()).toEqual([])
const result = apiConnectionsRequest(store, { action: 'list' })
diff --git a/cli/src/lib/apiConnections.ts b/cli/src/lib/apiConnections.ts
index f7d25fc03..977f982a5 100644
--- a/cli/src/lib/apiConnections.ts
+++ b/cli/src/lib/apiConnections.ts
@@ -1,33 +1,11 @@
/** Machine-local API connections. Only child tools receive credentials; model/subscription
* selection and the daemon's own environment are never changed by saving a key. */
-import { chmodSync, closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
+import { chmodSync, closeSync, fsyncSync, lstatSync, mkdirSync, openSync, renameSync, rmSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { randomUUID } from 'node:crypto'
-import { z } from 'zod'
-
-const text = z.string().trim().min(1).max(120).regex(/^[^\x00-\x1f\x7f]+$/)
-const id = z.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/)
-const environmentName = z.string().regex(/^[A-Z][A-Z0-9_]{0,79}$/).refine(
- value => !/^(PATH|HOME|SHELL|ENV|BASH_ENV|ZDOTDIR|NODE_OPTIONS|LD_.+|DYLD_.+|HARNESS_.+)$/.test(value),
-)
-const baseUrl = z.string().max(2048).url().refine(value => {
- const url = new URL(value)
- return ['https:', 'http:'].includes(url.protocol) && !url.username && !url.password && !url.search && !url.hash
-})
-const metadata = z.object({
- id,
- provider: id,
- name: text,
- baseUrl,
- keyEnv: environmentName,
- authHeader: z.string().regex(/^[A-Za-z][A-Za-z0-9-]{0,79}$/).refine(value =>
- !['host', 'content-length', 'connection', 'transfer-encoding', 'cookie'].includes(value.toLowerCase())),
- authPrefix: z.string().trim().max(40).regex(/^[A-Za-z0-9_-]*$/),
-})
-const stored = metadata.extend({ apiKey: z.string().trim().min(1).max(8192).regex(/^[^\s\x00-\x1f\x7f]+$/) })
-const storeSchema = z.object({ version: z.literal(1), connections: z.array(stored).max(100) })
-export type ApiConnection = z.infer<typeof metadata>
-type StoredConnection = z.infer<typeof stored>
+
+import { id, metadata, stored, readApiConnectionStore, ApiConnectionError, type ApiConnection, type StoredConnection } from './apiConnectionMetadata.js'
+export { ApiConnectionError, type ApiConnection } from './apiConnectionMetadata.js'
export type ApiPreset = Omit<ApiConnection, 'id'> & { keyUrl: string; docsUrl: string }
/** Defaults verified against each provider's public authentication docs. Custom APIs use the
@@ -41,7 +19,6 @@ export const API_PRESETS: ApiPreset[] = [
{ provider: 'replicate', name: 'Replicate', baseUrl: 'https://api.replicate.com/v1', keyEnv: 'REPLICATE_API_TOKEN', authHeader: 'Authorization', authPrefix: 'Bearer', keyUrl: 'https://replicate.com/account/api-tokens', docsUrl: 'https://replicate.com/docs/topics/security/api-tokens' },
]
-export class ApiConnectionError extends Error {}
const message = (value: string): never => { throw new ApiConnectionError(value) }
const publicConnection = (value: StoredConnection): ApiConnection => metadata.parse(value)
@@ -54,35 +31,31 @@ export function servesModels(connection: Pick<ApiConnection, 'authHeader' | 'aut
export class ApiConnections {
private readonly dir: string
private readonly file: string
- constructor(dataDir: string) {
+ constructor(private readonly dataDir: string) {
this.dir = join(dataDir, 'api-connections')
this.file = join(this.dir, 'connections.json')
}
- private read(): StoredConnection[] {
- try {
- if (!existsSync(this.dir)) return []
- if (!lstatSync(this.dir).isDirectory() || lstatSync(this.dir).isSymbolicLink()) throw new Error()
- if (!existsSync(this.file)) return []
- const stat = lstatSync(this.file)
- if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 2 * 1024 * 1024) throw new Error()
- const parsed = storeSchema.parse(JSON.parse(readFileSync(this.file, 'utf8'))).connections
- if (new Set(parsed.map(row => row.id)).size !== parsed.length) throw new Error()
- return parsed
- } catch { return message('Saved APIs could not be read. Your keys have not been changed.') }
- }
+ private read(): StoredConnection[] { return readApiConnectionStore(this.dataDir).connections }
private write(connections: StoredConnection[]): void {
const temporary = join(this.dir, `.connections-${randomUUID()}.tmp`)
let fd: number | undefined
let created = false
try {
+ const previous = readApiConnectionStore(this.dataDir)
+ // Endpoint recognition must survive a models restart, even before an organic agent's first scan.
+ // Keep it in this same atomic document so saving a key cannot half-write its endpoint vocabulary.
+ const recognizedBases = [...new Set([...(previous.recognizedBases ?? []),
+ ...previous.connections.map(row => row.baseUrl), ...connections.map(row => row.baseUrl)])]
+ const contents = JSON.stringify({ version: 1, connections, recognizedBases })
+ if (Buffer.byteLength(contents) > 2 * 1024 * 1024) throw new Error('API store is full')
mkdirSync(this.dir, { recursive: true, mode: 0o700 })
if (lstatSync(this.dir).isSymbolicLink()) throw new Error()
chmodSync(this.dir, 0o700)
fd = openSync(temporary, 'wx', 0o600)
created = true
- writeFileSync(fd, JSON.stringify({ version: 1, connections }))
+ writeFileSync(fd, contents)
fsyncSync(fd)
closeSync(fd)
fd = undefined
@@ -94,6 +67,11 @@ export class ApiConnections {
}
}
+ recognizedBases(): string[] {
+ const store = readApiConnectionStore(this.dataDir)
+ return [...new Set([...(store.recognizedBases ?? []), ...store.connections.map(row => row.baseUrl)])]
+ }
+
list(): ApiConnection[] { return this.read().map(publicConnection) }
save(input: Record<string, unknown>): ApiConnection {
diff --git a/cli/src/lib/apiInstructions.ts b/cli/src/lib/apiInstructions.ts
index 54fa3ea5e..0fb5f7db1 100644
--- a/cli/src/lib/apiInstructions.ts
+++ b/cli/src/lib/apiInstructions.ts
@@ -1,7 +1,7 @@
/** Discoverable tool access, without copying credentials or model settings into projects. */
import { existsSync, lstatSync, readFileSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
-import type { ApiConnections } from './apiConnections.js'
+import type { ApiConnectionMetadata } from './apiConnectionMetadata.js'
import { instructionFileOf } from '../engines/launches.js'
const marker = '<!-- harness:apis -->'
@@ -19,7 +19,7 @@ Adding an API does not change this harness's model or subscription.
/** Only Harness-created workspaces with saved APIs. Existing instructions are kept;
* no global agent settings or credentials are written into the project. */
-export function prepareApiInstructions(store: ApiConnections, workspace: string, engine: string): void {
+export function prepareApiInstructions(store: Pick<ApiConnectionMetadata, 'list'>, workspace: string, engine: string): void {
if (engine === 'terminal' || !store.list().length) return
const name = instructionFileOf(engine) ?? (engine === 'gemini' ? 'GEMINI.md' : 'AGENTS.md')
const file = join(workspace, name)
diff --git a/cli/src/lib/apiModels.spec.ts b/cli/src/lib/apiModels.spec.ts
index 81b6dcdd3..9a8e1a09f 100644
--- a/cli/src/lib/apiModels.spec.ts
+++ b/cli/src/lib/apiModels.spec.ts
@@ -253,8 +253,9 @@ describe('agent_retarget onto an API model', () => {
})
it("recognises an agent on the API's endpoint from then on, as when the socket read the store itself", async () => {
- // Read in another process: only the answer's endpoint can teach the core's grid assignment.
- const socket = socketWithModels(async () => ({ target: { networkId: 'api:far', networkName: 'Far', baseUrl: 'https://far.example.test/v1', apiKey: secret, model: 'm' }, apiBase: 'https://far.example.test/v1' }))
+ store.save({ provider: 'custom', name: 'Far', baseUrl: 'https://far.example.test/v1', apiKey: secret })
+ vi.spyOn(globalThis, 'fetch').mockImplementation(answering({ data: [{ id: 'm' }] }))
+ const socket = socketWithModels()
vi.spyOn(socket as any, 'emitReply').mockImplementation(() => {})
socket.onRetargetAgent = vi.fn(async () => ({ ok: true as const }))
const env = { ANTHROPIC_BASE_URL: 'https://far.example.test', ANTHROPIC_MODEL: 'm' }
diff --git a/cli/src/lib/gridAssignment.ts b/cli/src/lib/gridAssignment.ts
index 27674f653..bbf75525e 100644
--- a/cli/src/lib/gridAssignment.ts
+++ b/cli/src/lib/gridAssignment.ts
@@ -27,31 +27,11 @@ import { anthropicBaseUrl, GRID_ROUTER_MODEL, relayBaseUrl } from './gridLaunchW
import { readProcessEnv } from './processEnv.js'
import type { ProcessIdentity } from './registry.js'
-/** Where an agent's inference goes, as far as anyone outside the pane needs to know. */
-export interface GridAssignment {
- /** The relay root the engine was handed. The grid id is a path segment inside it. */
- baseUrl: string
- /** The model the launch pinned. Null = the engine's own choice. */
- model: string | null
-}
-
-/** The environment variable each engine's endpoint was written to, where it is one. */
-const BASE_URL_VAR: Partial<Record<AgentEngine, string>> = {
- claude: 'ANTHROPIC_BASE_URL',
- // opencode is deliberately absent: its endpoint moved into a config file (see
- // `readOpencodeGridAssignment`), and leaving it here would read a stray OPENAI_BASE_URL from the
- // user's own shell as proof this agent is on a grid.
- hermes: 'OPENAI_BASE_URL',
- grok: 'GROK_MODELS_BASE_URL',
- copilot: 'COPILOT_PROVIDER_BASE_URL',
-}
-
-/** The environment variable each engine's model was written to, where it is one. */
-const MODEL_VAR: Partial<Record<AgentEngine, string>> = {
- claude: 'ANTHROPIC_MODEL',
- hermes: 'HERMES_INFERENCE_MODEL',
- copilot: 'COPILOT_MODEL',
-}
+export type { GridAssignment } from './gridAssignmentWire.js'
+import { GRID_ENDPOINT_VARS as BASE_URL_VAR, GRID_MODEL_VARS as MODEL_VAR, GRID_CODEX_ENDPOINT as CODEX_BASE_URL,
+ GRID_ARGV_MODEL as ARGV_MODEL, GRID_PI_MODEL as PI_ARGV_MODEL, type GridAssignment, type GridAssignmentProcess,
+ type GridAssignmentAnswer } from './gridAssignmentWire.js'
+export { sameGridAssignment } from './gridAssignmentWire.js'
/**
* Engines whose model was written into argv as `-m <model>` rather than an environment variable: Codex's
@@ -70,11 +50,7 @@ const MODEL_IN_ARGV = new Set<AgentEngine>([...enginesDeclaring('modelInArgv'),
*/
const PI_CONFIG_DIR_VAR = 'PI_CODING_AGENT_DIR'
/** `--model grid/<model>` — how Pi is told which provider and model to use. */
-const PI_ARGV_MODEL = /(?:^|\s)--model\s+([A-Za-z0-9_-]+)\/(\S+)/
-/** `-c model_providers.<name>.base_url="…"` — how Codex's endpoint is written, so how it is read. */
-const CODEX_BASE_URL = /model_providers\.[A-Za-z0-9_-]+\.base_url=(?:"([^"]+)"|(\S+))/
-const ARGV_MODEL = /(?:^|\s)-m\s+(\S+)/
/**
* Endpoints of the APIs saved on this computer (`apiModels.ts`), in both forms an engine is handed
@@ -284,13 +260,8 @@ export async function gridAssignmentFromEnv(
return classifyGridAssignment(engine, env, args)
}
-/**
- * Do these two describe the same assignment?
- *
- * `undefined` is not compared here and must not reach this: it means the probe could not look, which
- * is never evidence that anything moved. Callers guard on it before asking.
- */
-export function sameGridAssignment(a: GridAssignment | null, b: GridAssignment | null): boolean {
- if (a === null || b === null) return a === b
- return a.baseUrl === b.baseUrl && (a.model ?? null) === (b.model ?? null)
+/** One fresh classification per process per pass; this is deliberately not an assignment cache. */
+export async function gridAssignments(processes: readonly GridAssignmentProcess[]): Promise<GridAssignmentAnswer[]> {
+ return Promise.all(processes.map(async process => ({ key: process.key,
+ assignment: await gridAssignmentFromEnv(process.engine, process.env, process.args) })))
}
diff --git a/cli/src/lib/gridAssignmentShapes.golden.spec.ts b/cli/src/lib/gridAssignmentShapes.golden.spec.ts
new file mode 100644
index 000000000..e3ab7da18
--- /dev/null
+++ b/cli/src/lib/gridAssignmentShapes.golden.spec.ts
@@ -0,0 +1,127 @@
+/** Former-code record for L2. Inputs, file bytes and expected answers stay fixed across the move. */
+import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { tmpdir } from 'node:os'
+import { fileURLToPath } from 'node:url'
+import { expect, it, vi } from 'vitest'
+import { ENGINES, type AgentEngine } from '../engines/types.js'
+
+process.env.TZ = 'UTC'
+const golden = fileURLToPath(new URL('./__fixtures__/grid-assignment-shapes.golden.json', import.meta.url))
+const relay = 'https://grid.example/g/home/relay/v1'
+const api = 'https://saved.example/inference/v1'
+const vars: Partial<Record<AgentEngine, [string, string]>> = {
+ claude: ['ANTHROPIC_BASE_URL', 'ANTHROPIC_MODEL'], hermes: ['OPENAI_BASE_URL', 'HERMES_INFERENCE_MODEL'],
+ grok: ['GROK_MODELS_BASE_URL', 'IGNORED_MODEL'], copilot: ['COPILOT_PROVIDER_BASE_URL', 'COPILOT_MODEL'],
+}
+
+it('keeps every assignment and saved-API instruction shape on both platforms', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'assignment-golden-'))
+ const platform = Object.getOwnPropertyDescriptor(process, 'platform')!
+ const result: Record<string, unknown> = {}
+ try {
+ for (const os of ['darwin', 'linux']) {
+ Object.defineProperty(process, 'platform', { value: os })
+ vi.resetModules()
+ const { gridAssignmentShapes } = await import('../testing/gridAssignmentShapes.js')
+ const { buildGridEngineLaunch, gridCapableEngines } = await import('./gridLaunch.js')
+ const dir = join(root, os)
+ const storeDir = join(dir, 'api-connections')
+ mkdirSync(storeDir, { recursive: true })
+ const shapes = gridAssignmentShapes(dir)
+ const out: Record<string, unknown> = {}
+ const assignment = async (name: string, engine: AgentEngine, env: Record<string, string>, args = '') => {
+ out[name] = await shapes.assignment(engine, { ...env, SECRET_API_KEY: 'never-forward-this-key' }, args)
+ }
+ for (const engine of ENGINES) {
+ await assignment(`${engine}/plain`, engine, {})
+ // The old classifier accepts a provider argument for any engine without its own URL variable.
+ await assignment(`${engine}/provider-argument`, engine, {}, `engine -c model_providers.grid.base_url="${relay}" -m chosen`)
+ }
+ for (const [engine, [urlVar, modelVar]] of Object.entries(vars) as Array<[AgentEngine, [string, string]]>) {
+ for (const url of ['', ' ', 'not-a-url', 'https://other.example/v1', 'https://grid.example/relayish/v1', relay, ` ${relay} `]) {
+ for (const model of ['', 'chosen', 'Auto', 'aUtO']) {
+ await assignment(`${engine}/env/${url}/${model}`, engine, { [urlVar]: url, [modelVar]: model }, `engine -m ${model || 'argv-model'}`)
+ }
+ }
+ }
+ for (const args of ['', `-c model_providers.other.base_url=${relay}`, `-c model_providers.other.base_url="${relay}" -m chosen`,
+ `-c model_providers.other.base_url="${relay}" -m Auto`, '-c model_providers.grid.base_url="bad" -m chosen']) {
+ await assignment(`codex/argv/${args}`, 'codex', { OPENAI_BASE_URL: relay }, args)
+ }
+ const piDir = join(dir, 'pi')
+ mkdirSync(piDir)
+ for (const [name, content] of Object.entries({ broken: '{', absent: '{}', wrong: '{"providers":{"other":{"baseUrl":"' + relay + '"}}}',
+ direct: JSON.stringify({ providers: { grid: { baseUrl: 'https://other.example/v1' } } }),
+ valid: JSON.stringify({ providers: { grid: { baseUrl: relay } } }) })) {
+ writeFileSync(join(piDir, 'models.json'), content)
+ for (const args of ['', '--model grid/chosen', '--model grid/Auto', '--model other/chosen']) {
+ await assignment(`pi/${name}/${args}`, 'pi', { PI_CODING_AGENT_DIR: piDir }, args)
+ }
+ }
+ await assignment('pi/missing-file', 'pi', { PI_CODING_AGENT_DIR: join(dir, 'missing') }, '--model grid/chosen')
+ const config = join(dir, 'opencode.json')
+ for (const [name, content] of Object.entries({ broken: '{', absent: '{}', many: JSON.stringify({ provider: { one: {}, two: {} } }),
+ noModel: JSON.stringify({ provider: { grid: { options: { baseURL: relay } } } }),
+ manyModels: JSON.stringify({ provider: { grid: { options: { baseURL: relay }, models: { one: {}, two: {} } } } }),
+ direct: JSON.stringify({ provider: { grid: { options: { baseURL: 'https://other.example/v1' }, models: { chosen: {} } } } }),
+ model: JSON.stringify({ provider: { grid: { options: { baseURL: relay }, models: { chosen: {} } } } }),
+ router: JSON.stringify({ provider: { grid: { options: { baseURL: relay }, models: { aUtO: {} } } } }) })) {
+ writeFileSync(config, content)
+ await assignment(`opencode/${name}`, 'opencode', { OPENCODE_CONFIG: config }, '-m ignored/wrong')
+ }
+ await assignment('opencode/missing-file', 'opencode', { OPENCODE_CONFIG: join(dir, 'missing.json') })
+ for (const engine of gridCapableEngines()) for (const model of [null, 'chosen']) {
+ const built = buildGridEngineLaunch(engine, { networkId: 'home', networkName: 'Home', baseUrl: relay, apiKey: 'fake-grid-key', ...(model === null ? {} : { model }) },
+ { hermesSystemManaged: false, opencodeMajor: 2 })
+ if (!built.ok) { out[`${engine}/launch-roundtrip/${model}`] = built; continue }
+ const env = { ...built.launch.env }
+ if (built.launch.configDir) {
+ const configs = built.launch.configDir
+ const path = join(dir, `config-${engine}-${model}`)
+ mkdirSync(path)
+ for (const file of configs.files) writeFileSync(join(path, file.name), file.content)
+ env[configs.envVar] = configs.pointAt ? join(path, configs.pointAt) : path
+ }
+ await assignment(`${engine}/launch-roundtrip/${model}`, engine, env, built.launch.args.join(' '))
+ }
+ const connection = { id: 'saved', provider: 'custom', name: 'Saved', baseUrl: api, keyEnv: 'SAVED_API_KEY', authHeader: 'Authorization', authPrefix: 'Bearer', apiKey: 'fake-saved-key' }
+ await assignment('saved/before-save', 'claude', { ANTHROPIC_BASE_URL: api, ANTHROPIC_MODEL: 'chosen' })
+ writeFileSync(join(storeDir, 'connections.json'), JSON.stringify({ version: 1, connections: [connection] }))
+ shapes.remember()
+ out['saved/list'] = shapes.list()
+ await assignment('saved/anthropic', 'claude', { ANTHROPIC_BASE_URL: api.replace(/\/v1$/, ''), ANTHROPIC_MODEL: 'chosen' })
+ await assignment('saved/openai', 'codex', {}, `-c model_providers.saved.base_url=${api} -m chosen`)
+ for (const engine of [...ENGINES, 'gemini']) {
+ const work = join(dir, `instructions-${engine}`)
+ mkdirSync(work)
+ writeFileSync(join(work, 'AGENTS.md'), '# Existing rules\n')
+ shapes.instructions(work, engine)
+ shapes.instructions(work, engine)
+ out[`instructions/${engine}`] = Object.fromEntries(readdirSync(work).sort().map(name => [name, readFileSync(join(work, name), 'utf8')]))
+ }
+ writeFileSync(join(storeDir, 'connections.json'), JSON.stringify({ version: 1, connections: [] }))
+ shapes.remember()
+ await assignment('saved/after-removal', 'codex', {}, `-c model_providers.saved.base_url=${api} -m chosen`)
+ const work = join(dir, 'instructions-empty')
+ mkdirSync(work)
+ shapes.instructions(work, 'claude')
+ out['instructions/no-saved-api'] = readdirSync(work)
+ writeFileSync(join(storeDir, 'connections.json'), '{')
+ try { shapes.instructions(work, 'claude') } catch (error) { out['instructions/unreadable'] = (error as Error).message }
+ shapes.remember() // Best effort recognition never erases remembered endpoints.
+ await assignment('saved/unreadable', 'codex', {}, `-c model_providers.saved.base_url=${api} -m chosen`)
+ result[os] = out
+ }
+ const text = JSON.stringify(result, null, 2) + '\n'
+ expect(text).not.toContain(root)
+ expect(text).not.toContain('fake-saved-key')
+ expect(text).not.toContain('never-forward-this-key')
+ if (process.env.RECORD_GRID_ASSIGNMENT_GOLDEN === '1') writeFileSync(golden, text)
+ expect(result).toEqual(JSON.parse(readFileSync(golden, 'utf8')))
+ } finally {
+ Object.defineProperty(process, 'platform', platform)
+ vi.resetModules()
+ rmSync(root, { recursive: true, force: true })
+ }
+})
diff --git a/cli/src/lib/gridAssignmentWire.spec.ts b/cli/src/lib/gridAssignmentWire.spec.ts
new file mode 100644
index 000000000..238f7fbd9
--- /dev/null
+++ b/cli/src/lib/gridAssignmentWire.spec.ts
@@ -0,0 +1,26 @@
+import { expect, it } from 'vitest'
+import { gridAssignmentProcess, gridAssignmentProcessesIn, gridAssignmentAnswersIn } from './gridAssignmentWire.js'
+
+it('forwards only the classifier variables and argument fragments, never unrelated keys or prompts', () => {
+ expect(gridAssignmentProcess('a', 'claude', { ANTHROPIC_BASE_URL: 'https://grid.example/relay', ANTHROPIC_MODEL: 'm',
+ ANTHROPIC_AUTH_TOKEN: 'secret', HOME: '/private-home' }, 'claude -m secret --prompt private')).toEqual({
+ key: 'a', engine: 'claude', env: { ANTHROPIC_BASE_URL: 'https://grid.example/relay', ANTHROPIC_MODEL: 'm' }, args: '',
+ })
+ const input = gridAssignmentProcess('a', 'codex', { GRID_API_KEY: 'secret' }, 'codex --prompt private -c model_providers.grid.base_url="https://grid.example/relay/v1" -m m')!
+ expect(input).toEqual({ key: 'a', engine: 'codex', env: {}, args: 'model_providers.grid.base_url="https://grid.example/relay/v1" -m m' })
+ expect(gridAssignmentProcessesIn([input])).toEqual([input])
+ expect(gridAssignmentProcess('a', 'pi', {}, '--model grid/m')).toBeNull()
+ expect(gridAssignmentProcess('a', 'opencode', { OPENAI_BASE_URL: 'https://grid.example/relay' }, '-m grid/m')).toBeNull()
+})
+
+it('rejects malformed, duplicate or mismatched batches instead of turning them into no assignment', () => {
+ const input = gridAssignmentProcess('a', 'claude', { ANTHROPIC_BASE_URL: 'https://grid.example/relay' }, '')!
+ for (const value of [null, {}, Array(4097).fill(input), [null], [{ ...input, engine: 'unknown' }],
+ [{ ...input, key: 1 }], [{ ...input, args: 1 }], [{ ...input, env: null }], [{ ...input, env: { ANTHROPIC_BASE_URL: 1 } }],
+ [{ ...input, env: {} }], [input, input]]) expect(gridAssignmentProcessesIn(value)).toBeNull()
+ for (const value of [null, [], [null], [{ key: 'wrong', assignment: null }], [{ key: 'a' }],
+ [{ key: 'a', assignment: { baseUrl: 1, model: null } }], [{ key: 'a', assignment: { baseUrl: 'url', model: 1 } }]]) {
+ expect(gridAssignmentAnswersIn(value, [input])).toBeNull()
+ }
+ expect(gridAssignmentAnswersIn([{ key: 'a', assignment: null }], [input])).toEqual([{ key: 'a', assignment: null }])
+})
diff --git a/cli/src/lib/gridAssignmentWire.ts b/cli/src/lib/gridAssignmentWire.ts
new file mode 100644
index 000000000..5afe6291a
--- /dev/null
+++ b/cli/src/lib/gridAssignmentWire.ts
@@ -0,0 +1,62 @@
+/** Core's declaration of the launch evidence models may classify. No keys cross this port. */
+import { ENGINES, type AgentEngine } from '../engines/types.js'
+
+export interface GridAssignment { baseUrl: string; model: string | null }
+export interface GridAssignmentProcess { key: string; engine: AgentEngine; env: Record<string, string>; args: string }
+export interface GridAssignmentAnswer { key: string; assignment: GridAssignment | null }
+
+export const GRID_ENDPOINT_VARS: Partial<Record<AgentEngine, string>> = {
+ claude: 'ANTHROPIC_BASE_URL', hermes: 'OPENAI_BASE_URL', grok: 'GROK_MODELS_BASE_URL', copilot: 'COPILOT_PROVIDER_BASE_URL',
+}
+export const GRID_MODEL_VARS: Partial<Record<AgentEngine, string>> = {
+ claude: 'ANTHROPIC_MODEL', hermes: 'HERMES_INFERENCE_MODEL', copilot: 'COPILOT_MODEL',
+}
+export const GRID_CODEX_ENDPOINT = /model_providers\.[A-Za-z0-9_-]+\.base_url=(?:"([^"]+)"|(\S+))/
+export const GRID_ARGV_MODEL = /(?:^|\s)-m\s+(\S+)/
+export const GRID_PI_MODEL = /(?:^|\s)--model\s+([A-Za-z0-9_-]+)\/(\S+)/
+
+/** Null is positive evidence of no launch markers. An unreadable environment is handled by the caller. */
+export function gridAssignmentProcess(key: string, engine: AgentEngine, env: Record<string, string>, args: string): GridAssignmentProcess | null {
+ const endpoint = GRID_ENDPOINT_VARS[engine]
+ const marker = engine === 'pi' ? 'PI_CODING_AGENT_DIR' : engine === 'opencode' ? 'OPENCODE_CONFIG' : endpoint
+ const provider = marker ? null : GRID_CODEX_ENDPOINT.exec(args)
+ if (!(marker ? env[marker]?.trim() : provider)) return null
+ const picked: Record<string, string> = {}
+ for (const name of [marker, GRID_MODEL_VARS[engine]]) if (name && env[name] !== undefined) picked[name] = env[name]
+ // Never forward the command line: it may carry a prompt, token or unrelated tool arguments.
+ const model = engine === 'pi' ? GRID_PI_MODEL.exec(args)?.[0]
+ : engine === 'codex' || engine === 'grok' ? GRID_ARGV_MODEL.exec(args)?.[0] : undefined
+ return { key, engine, env: picked, args: [provider?.[0], model].filter(Boolean).join(' ') }
+}
+
+const record = (value: unknown): value is Record<string, unknown> => !!value && typeof value === 'object' && !Array.isArray(value)
+export function gridAssignmentProcessesIn(value: unknown): GridAssignmentProcess[] | null {
+ if (!Array.isArray(value) || value.length > 4096) return null
+ const out: GridAssignmentProcess[] = []
+ for (const row of value) {
+ if (!record(row) || typeof row.key !== 'string' || typeof row.engine !== 'string' || !ENGINES.includes(row.engine as AgentEngine)
+ || typeof row.args !== 'string' || !record(row.env) || !Object.values(row.env).every(v => typeof v === 'string')) return null
+ const process = gridAssignmentProcess(row.key, row.engine as AgentEngine, row.env as Record<string, string>, row.args)
+ if (!process || out.some(previous => previous.key === row.key)) return null
+ out.push(process)
+ }
+ return out
+}
+
+export function gridAssignmentAnswersIn(value: unknown, processes: readonly GridAssignmentProcess[]): GridAssignmentAnswer[] | null {
+ if (!Array.isArray(value) || value.length !== processes.length) return null
+ const keys = new Set(processes.map(process => process.key))
+ const out: GridAssignmentAnswer[] = []
+ for (const row of value) {
+ if (!record(row) || typeof row.key !== 'string' || !keys.delete(row.key)) return null
+ const a = row.assignment
+ if (a !== null && (!record(a) || typeof a.baseUrl !== 'string' || !(a.model === null || typeof a.model === 'string'))) return null
+ out.push({ key: row.key, assignment: a === null ? null : { baseUrl: a.baseUrl as string, model: a.model as string | null } })
+ }
+ return out
+}
+
+export function sameGridAssignment(a: GridAssignment | null, b: GridAssignment | null): boolean {
+ if (a === null || b === null) return a === b
+ return a.baseUrl === b.baseUrl && (a.model ?? null) === (b.model ?? null)
+}
diff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.ts
index fd5c1399f..211f1a586 100644
--- a/cli/src/lib/registry.spec.ts
+++ b/cli/src/lib/registry.spec.ts
@@ -1946,6 +1946,43 @@ describe('registry across a reboot and pane loss', () => {
expect(saved.map((row) => row.agentId).sort()).toEqual([a, b].sort())
})
+ it('flushes an acknowledged binding at exit without waiting for a discovery transaction', async () => {
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ const transcriptPath = join(dataDir, 'just-bound.jsonl')
+ writeFileSync(transcriptPath, '{}\n')
+ const pending = registry.openProcessAgent({ engine: 'claude', tmuxPane: '%7', processIdentity: processIdentity(71) })!.entry
+ let finish!: () => void
+ const batch = registry.transaction(async () => {
+ registry.register({ engine: 'claude', sessionId: 'just-bound', transcriptPath, tmuxPane: '%7' })
+ await new Promise<void>(resolve => { finish = resolve })
+ })
+ try {
+ // Reflect keeps this regression runnable against the former flush(), which ignored this option.
+ Reflect.apply(registry.flush, registry, [{ exiting: true }])
+ const saved = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf8'))
+ expect(saved.find((row: any) => row.agentId === pending.agentId).sessionId).toBe('just-bound')
+ } finally { finish(); await batch }
+ })
+
+ it('never flushes an incomplete pane swap at exit or lets merge conflict resolution evict its other owner', async () => {
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ const a = registry.openProcessAgent({ engine: 'claude', tmuxPane: '%1', processIdentity: processIdentity(11) })!.entry.agentId
+ const b = registry.openProcessAgent({ engine: 'claude', tmuxPane: '%2', processIdentity: processIdentity(12) })!.entry.agentId
+ const file = join(dataDir, 'registry.json')
+ const before = readFileSync(file, 'utf8')
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})
+ await registry.transaction(async () => {
+ registry.updateRuntimes(a, [{ backend: 'tmux', paneId: '%2' }], 'tmux\u0000%2')
+ Reflect.apply(registry.flush, registry, [{ exiting: true }])
+ expect(readFileSync(file, 'utf8')).toBe(before)
+ registry.updateRuntimes(b, [{ backend: 'tmux', paneId: '%1' }], 'tmux\u0000%1')
+ })
+ expect(JSON.parse(readFileSync(file, 'utf8')).map((row: any) => row.agentId).sort()).toEqual([a, b].sort())
+ error.mockRestore()
+ })
+
it('stops holding saves back for a transaction that outlives its hold, and saves what it has changed', async () => {
// A reconcile pass stuck inside its transaction held every save back for as long as it ran.
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.ts
index 5b8eb0115..04388aa22 100644
--- a/cli/src/lib/registry.ts
+++ b/cli/src/lib/registry.ts
@@ -2327,13 +2327,13 @@ class Registry {
}
}
- flush(): void {
- this.save()
+ flush(options: { exiting?: boolean } = {}): void {
+ this.save(false, options.exiting === true)
this.saveNames()
}
- private save(strict = false): void {
- if (this.transactionDepth > 0) {
+ private save(strict = false, exiting = false): void {
+ if (this.transactionDepth > 0 && !exiting) {
if (strict) throw new Error('Cannot acknowledge a close intent inside an uncommitted registry transaction')
this.savePending = true
return
@@ -2350,6 +2350,10 @@ class Registry {
const row = persistedRow(entry) as unknown as Record<string, unknown>
return [entry.agentId, row] as const
}))
+ // A discovery batch may be awaiting a reader after acknowledging a complete binding. Exit cannot
+ // wait for it. Check BEFORE merge conflict resolution: an incomplete pane swap must never be
+ // made to look valid by evicting its other owner. Its last durable snapshot remains untouched.
+ if (exiting && !validatedRows([...currentRows.values()])) throw new Error('Cannot flush an incomplete registry transaction at exit')
// Discovery still calls save on an unchanged observation so a daemon-down hook's commit is
// noticed. If neither side changed, avoid the lock's process probe and all three fsyncs.
// Read through the normal ownership/mode/no-symlink checks; timestamps cannot prove equality.
diff --git a/cli/src/lib/terminalAgentDiscovery.grid.spec.ts b/cli/src/lib/terminalAgentDiscovery.grid.spec.ts
index f2e40a3f6..920e947c5 100644
--- a/cli/src/lib/terminalAgentDiscovery.grid.spec.ts
+++ b/cli/src/lib/terminalAgentDiscovery.grid.spec.ts
@@ -15,11 +15,11 @@ import type { TerminalRootObservation, TerminalRuntimeRef } from './terminalType
*/
const probeGatewayRuntime = vi.hoisted(() => vi.fn())
-const probeGridAssignment = vi.hoisted(() => vi.fn())
+const readProcessEnv = vi.hoisted(() => vi.fn())
const processRows = vi.hoisted(() => vi.fn())
vi.mock('./gatewayRuntime.js', () => ({ probeGatewayRuntime }))
-vi.mock('./gridAssignment.js', () => ({ probeGridAssignment }))
+vi.mock('./processEnv.js', () => ({ readProcessEnv }))
vi.mock('./tmux.js', async (importOriginal) => ({
...await importOriginal<typeof import('./tmux.js')>(),
processRows,
@@ -46,7 +46,7 @@ function backendWith(name: 'tmux', instanceId: string, roots: TerminalRootObserv
beforeEach(() => {
probeGatewayRuntime.mockReset()
probeGatewayRuntime.mockResolvedValue({ kind: null })
- probeGridAssignment.mockReset()
+ readProcessEnv.mockReset()
processRows.mockReset()
})
@@ -54,9 +54,9 @@ describe('grid assignment on the live terminal discovery path', () => {
it('reports the grid for every pane, from the process rather than the pane', async () => {
processRows.mockResolvedValue([
row(10, 1, 'bash'), row(30, 10, 'claude'),
- row(20, 1, 'bash'), row(40, 20, 'codex'),
+ row(20, 1, 'bash'), row(40, 20, 'codex', 'codex -c model_providers.grid.base_url="https://grid.example/relay/v1" -m chosen'),
])
- probeGridAssignment.mockResolvedValue(ASSIGNMENT)
+ readProcessEnv.mockResolvedValue({ ANTHROPIC_BASE_URL: ASSIGNMENT.baseUrl, ANTHROPIC_MODEL: ASSIGNMENT.model, API_KEY: 'secret' })
const probe = await probeTerminalAgents(
[
@@ -70,16 +70,17 @@ describe('grid assignment on the live terminal discovery path', () => {
)
expect(probe.agents).toHaveLength(2)
- expect(probe.agents.every((agent) => agent.grid === ASSIGNMENT)).toBe(true)
- expect(probeGridAssignment).toHaveBeenCalledTimes(2)
- for (const [identity] of probeGridAssignment.mock.calls) {
+ expect(probe.agents.every((agent) => agent.grid === undefined && agent.gridProcess)).toBe(true)
+ expect(JSON.stringify(probe.agents.map(a => a.gridProcess))).not.toContain('secret')
+ expect(readProcessEnv).toHaveBeenCalled()
+ for (const [identity] of readProcessEnv.mock.calls) {
expect(identity).toMatchObject({ startMarker: START })
}
})
it('reports null for an agent on its own login', async () => {
processRows.mockResolvedValue([row(10, 1, 'bash'), row(30, 10, 'claude')])
- probeGridAssignment.mockResolvedValue(null)
+ readProcessEnv.mockResolvedValue({})
const probe = await probeTerminalAgents(
[backendWith('tmux', 'tmux', [{ runtime: TMUX_RUNTIME, rootPid: 10, cwd: '/work' }])],
['tmux'],
@@ -96,6 +97,6 @@ describe('grid assignment on the live terminal discovery path', () => {
999,
)
expect(probe.processTableAvailable).toBe(false)
- expect(probeGridAssignment).not.toHaveBeenCalled()
+ expect(readProcessEnv).not.toHaveBeenCalled()
})
})
diff --git a/cli/src/lib/terminalAgentDiscovery.ts b/cli/src/lib/terminalAgentDiscovery.ts
index cc312cc65..f93faab66 100644
--- a/cli/src/lib/terminalAgentDiscovery.ts
+++ b/cli/src/lib/terminalAgentDiscovery.ts
@@ -6,7 +6,8 @@ import {
type AgentCommandOwnershipSnapshot,
} from './engineBin.js'
import { probeGatewayRuntime } from './gatewayRuntime.js'
-import { probeGridAssignment, type GridAssignment } from './gridAssignment.js'
+import { gridAssignmentProcess, type GridAssignment, type GridAssignmentProcess } from './gridAssignmentWire.js'
+import { readProcessEnv } from './processEnv.js'
import { probeProfileHome } from '../engines/discoveries.js'
import { loadEngine } from '../engines/inProcess.js'
import { probeDsh } from '../dsh/probe.js'
@@ -49,11 +50,13 @@ export interface DiscoveredTerminalAgent {
gateway?: 'ori' | null
/**
* The grid this engine process is pointed at, read from the same environment. null = a vendor login
- * or an unreadable probe — `gridAssignment.ts` explains why those share an answer.
+ * while undefined means the process or models could not be read and preserves the last assignment.
*
* Backend-agnostic for the same reason `gateway` is: it is a fact about the process, not the pane.
*/
grid?: GridAssignment | null
+ /** Sanitized launch markers; classified after the binding pass, never awaited by it. */
+ gridProcess?: GridAssignmentProcess
/**
* Codex only: the CODEX_HOME profile the process was launched under, when it is not this machine's
* default. null = the default profile (or not Codex); undefined = the probe could not read the
@@ -260,8 +263,13 @@ export async function probeTerminalAgents(
await Promise.all(discovered.agents.map(async (agent) => {
const runtime = await probeGatewayRuntime(agent.processIdentity, agent.args)
agent.gateway = runtime.kind
- // Same process, same cached read — the grid costs no extra `ps`.
- agent.grid = await probeGridAssignment(agent.processIdentity, agent.engine, agent.args)
+ // Only the marker read is core work. Models classifies it after reconciliation, without blocking binding.
+ const env = await readProcessEnv(agent.processIdentity)
+ if (env) {
+ const evidence = gridAssignmentProcess('', agent.engine, env, agent.args)
+ if (evidence) agent.gridProcess = evidence
+ else agent.grid = null
+ }
// And, for Codex, the profile it runs under — a fact about the process the row cannot otherwise learn.
agent.codexHome = await probeProfileHome(agent.processIdentity, agent.engine)
// …and, for Hermes, the home — same cached read, and it beats looking the session up in every store. Read by
diff --git a/cli/src/lib/terminalAgentReconciler.spec.ts b/cli/src/lib/terminalAgentReconciler.spec.ts
index 79229dc98..8a48614c7 100644
--- a/cli/src/lib/terminalAgentReconciler.spec.ts
+++ b/cli/src/lib/terminalAgentReconciler.spec.ts
@@ -285,11 +285,12 @@ describe('composite terminal reconciliation', () => {
// A stop retiring a starting agent's pane holds its route and lets it go; a probe taken before it
// still saw the engine there, and opened a second agent for a pane that no longer existed.
const onDiscovered = vi.fn()
+ const onReconciled = vi.fn()
const route = terminalRouteKey(tmux)
let whileProbing: (() => void) | null = null
const reconciler = new TerminalAgentReconciler({
current: () => [], backends: [], backendOrder: ['tmux'],
- onDiscovered, onObserved: vi.fn(), onDormant: vi.fn(), onRemoved: vi.fn(),
+ onDiscovered, onReconciled, onObserved: vi.fn(), onDormant: vi.fn(), onRemoved: vi.fn(),
probe: async () => {
whileProbing?.()
whileProbing = null
@@ -299,10 +300,12 @@ describe('composite terminal reconciliation', () => {
whileProbing = () => { reconciler.holdRoute(route); reconciler.releaseRoute(route) }
await reconciler.trigger()
expect(onDiscovered).not.toHaveBeenCalled()
+ expect(onReconciled).toHaveBeenLastCalledWith([])
// Releasing a route nobody held changes nothing, and a probe that began afterwards speaks for it.
reconciler.releaseRoute(route)
await reconciler.trigger()
expect(onDiscovered).toHaveBeenCalledTimes(1)
+ expect(onReconciled).toHaveBeenLastCalledWith([observed([tmux])])
})
it('does not count a miss for an agent whose route changed hands while the probe ran', async () => {
diff --git a/cli/src/lib/terminalAgentReconciler.ts b/cli/src/lib/terminalAgentReconciler.ts
index fbb4ad270..f675b0c9a 100644
--- a/cli/src/lib/terminalAgentReconciler.ts
+++ b/cli/src/lib/terminalAgentReconciler.ts
@@ -48,6 +48,7 @@ export interface TerminalAgentReconcilerDeps {
onDormant: (current: RegisteredSession, reason: string) => void | Promise<void>
onRemoved: (current: RegisteredSession, reason: string) => void | Promise<void>
onTerminalAvailability?: (current: RegisteredSession, available: boolean) => void | Promise<void>
+ onReconciled?: (agents: readonly DiscoveredTerminalAgent[]) => void
onProbeStatus?: (status: { ready: true; error: string | null }) => void
transaction?: <T>(apply: () => T | Promise<T>) => Promise<T>
probe?: (hints: ReadonlyMap<string, AgentEngine>) => Promise<TerminalAgentProbe>
@@ -462,5 +463,6 @@ export class TerminalAgentReconciler {
// Readiness is published last: clients must never observe ready=true between the inventory read and
// the authoritative availability/registry update.
this.deps.onProbeStatus?.({ ready: true, error: probeError })
+ this.deps.onReconciled?.(probe.agents.filter(agent => !this.routeHeld(agent.runtimes, probeSeq)))
}
}
diff --git a/cli/src/services/models.spec.ts b/cli/src/services/models.spec.ts
index ee9de545e..f64cce782 100644
--- a/cli/src/services/models.spec.ts
+++ b/cli/src/services/models.spec.ts
@@ -61,9 +61,9 @@ vi.mock('../lib/gridModels.js', () => ({
}))
vi.mock('../lib/runtimeInstall.js', () => ({ ensureManagedGrid: vi.fn(async () => {}), startGridPinRecheck: vi.fn(() => () => {}) }))
/** The saved APIs and the Codex profiles: their files and folders are the lib's, never this machine's here. */
-const apis = vi.hoisted(() => ({ stores: [] as string[] }))
+const apis = vi.hoisted(() => ({ stores: [] as string[], bases: vi.fn(() => [] as string[]) }))
vi.mock('../lib/apiConnections.js', () => ({
- ApiConnections: class { constructor(dataDir: string) { apis.stores.push(dataDir) } },
+ ApiConnections: class { constructor(dataDir: string) { apis.stores.push(dataDir) } recognizedBases = apis.bases },
apiConnectionsRequest: vi.fn((_store: unknown, payload: Record<string, unknown>) => ({ connections: [], presets: [], action: payload.action })),
}))
vi.mock('../lib/apiModels.js', () => ({
@@ -679,13 +679,26 @@ describe('the models service', () => {
it('api_connections: lists, saves (and recognises agents already on the saved endpoints), removes, and reads an API\'s models', async () => {
const { ask } = setup()
expect(await ask('api_connections', { action: 'list' })).toEqual({ connections: [], presets: [], action: 'list' })
- expect(rememberSavedApis).not.toHaveBeenCalled()
+ expect(rememberSavedApis).toHaveBeenCalledTimes(1)
expect(await ask('api_connections', { action: 'save', connection: { name: 'x' } })).toEqual({ connections: [], presets: [], action: 'save' })
- expect(rememberSavedApis).toHaveBeenCalledOnce()
+ expect(rememberSavedApis).toHaveBeenCalledTimes(2)
expect(await ask('api_connections', { action: 'remove', id: 'a' })).toEqual({ connections: [], presets: [], action: 'remove' })
expect(await ask('api_connections', { action: 'models', id: 'a' })).toEqual({ id: 'a', models: ['m1'] })
expect(apiModelsRequest).toHaveBeenCalledOnce()
- expect(rememberSavedApis).toHaveBeenCalledOnce()
+ expect(rememberSavedApis).toHaveBeenCalledTimes(2)
+ })
+
+ it('recognises persisted API endpoints after models restarts and refuses unreadable vocabulary', async () => {
+ const { port } = setup()
+ apis.bases.mockReturnValueOnce(['https://old-api.example/v1'])
+ const process = { key: 'organic', engine: 'claude' as const, env: { ANTHROPIC_BASE_URL: 'https://old-api.example', ANTHROPIC_MODEL: 'm' }, args: '' }
+ expect(await port.gridAssignments([process])).toEqual([{ key: 'organic', assignment: { baseUrl: 'https://old-api.example', model: 'm' } }])
+ apis.bases.mockImplementationOnce(() => { throw new Error('unreadable vocabulary') })
+ expect(await port.gridAssignments([process])).toMatchObject([{ assignment: { baseUrl: 'https://old-api.example' } }])
+ const restarted = setup().port
+ apis.bases.mockImplementationOnce(() => { throw new Error('unreadable vocabulary') })
+ await expect(restarted.gridAssignments([process])).rejects.toThrow('unreadable vocabulary')
+ expect(await restarted.gridAssignments([])).toEqual([])
})
it("builds the core's launches on a grid or a saved API, reading the saved APIs in the data folder as they are now", async () => {
diff --git a/cli/src/services/models.ts b/cli/src/services/models.ts
index 1c9f74cea..e50afff72 100644
--- a/cli/src/services/models.ts
+++ b/cli/src/services/models.ts
@@ -1,3 +1,4 @@
+import { modelsAssignments } from './modelsAssignments.js'
/**
* Models: grid, how Harness runs local AI models with Codex, Claude Code and the other engines
* (docs/design/2026-10-03-harnessd.md, "Models"). Grid access on first use, the managed grid's pin, the
@@ -140,6 +141,7 @@ export function startModels(core: CoreApi, ports: CorePorts): ServiceRequests {
// The saved APIs, a file in the data folder (lib/apiConnections.ts), read afresh by every launch on one.
const savedApis = new ApiConnections(core.dataDir)
+ rememberSavedApis(savedApis)
ports.models = {
ensure: grid.ensure,
annotation: (target) => gridAnnotation(target),
@@ -154,6 +156,7 @@ export function startModels(core: CoreApi, ports: CorePorts): ServiceRequests {
moved: (launch) => { void retargetPrewarm(launch).catch(() => {}) },
// The launch that points an engine at a grid or a saved API, built here for the core, which builds none
// (docs/design/2026-10-08-launch-port.md): a relaunch's saved API with its endpoint and key as saved now.
+ gridAssignments: modelsAssignments(savedApis),
gridLaunch: async (request) => answerGridLaunch(request, refreshApiFor(savedApis)),
apiTarget: (request) => apiTargetAnswer(savedApis, request.connectionId, request.model),
privateGridName,
diff --git a/cli/src/services/modelsAssignments.ts b/cli/src/services/modelsAssignments.ts
new file mode 100644
index 000000000..eb77a18d2
--- /dev/null
+++ b/cli/src/services/modelsAssignments.ts
@@ -0,0 +1,19 @@
+/** Endpoint vocabulary is models' state; each process/config classification is always fresh. */
+import type { ApiConnections } from '../lib/apiConnections.js'
+import { gridAssignments, rememberApiBase } from '../lib/gridAssignment.js'
+import type { ModelsPort } from '../core/api.js'
+
+export function modelsAssignments(store: Pick<ApiConnections, 'recognizedBases'>): ModelsPort['gridAssignments'] {
+ let vocabularyLoaded = false
+ return async processes => {
+ try {
+ for (const base of store.recognizedBases()) rememberApiBase(base)
+ vocabularyLoaded = true
+ } catch (error) {
+ // A restarted service with no validated vocabulary cannot claim a known API agent left it.
+ // Once read, retain that vocabulary through a transient file error, just as the former core did.
+ if (!vocabularyLoaded) throw error
+ }
+ return gridAssignments(processes)
+ }
+}
diff --git a/cli/src/services/modelsProcess.spec.ts b/cli/src/services/modelsProcess.spec.ts
index aa5428bb0..f3ea77397 100644
--- a/cli/src/services/modelsProcess.spec.ts
+++ b/cli/src/services/modelsProcess.spec.ts
@@ -24,6 +24,7 @@ function fakeModels() {
launchTarget: vi.fn(async () => LAUNCH),
moveTarget: vi.fn(async (): Promise<{ target: typeof LAUNCH } | { detail: string }> => ({ target: LAUNCH })),
moved: vi.fn(),
+ gridAssignments: vi.fn(async () => []),
gridLaunch: vi.fn(async (request: GridLaunchRequest): Promise<GridLaunchAnswer> => ({ ok: true, launch: BUILT, override: request.override })),
apiTarget: vi.fn(async (): Promise<{ target: typeof LAUNCH; apiBase: string } | { detail: string }> => ({ target: LAUNCH, apiBase: RELAY })),
privateGridName: vi.fn(async () => 'mine'),
@@ -69,7 +70,7 @@ describe('models in its own process', () => {
it('reaches the core as `models`, answering the apps\' requests and the core\'s port calls, and stops with its link', () => {
const { models, options, handle, service } = setup()
expect(options).toMatchObject({ name: 'models', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't' })
- expect(Object.keys(options.requests).sort()).toEqual(['apiTarget', 'ensure', 'gridLaunch', 'grid_models_list', 'launchTarget', 'lists', 'moveTarget', 'privateGridName'])
+ expect(Object.keys(options.requests).sort()).toEqual(['apiTarget', 'ensure', 'gridAssignments', 'gridLaunch', 'grid_models_list', 'launchTarget', 'lists', 'moveTarget', 'privateGridName'])
expect(options.requests.grid_models_list).toBe(models.requests.grid_models_list)
handle.stop()
expect(service.stop).toHaveBeenCalled()
@@ -107,6 +108,8 @@ describe('models in its own process', () => {
expect(await options.requests.gridLaunch!({ engine: 'claude', override: 'nope', machine }, asker))
.toEqual({ ok: false, error: 'INVALID_GRID', detail: 'This launch could not be read.' })
expect(models.port.gridLaunch).toHaveBeenCalledOnce()
+ expect(await options.requests.gridAssignments!({ processes: [] }, asker)).toEqual({ assignments: [] })
+ expect(await options.requests.gridAssignments!({ processes: 'invalid' }, asker)).toEqual({ error: 'INVALID_PROCESSES' })
expect(await options.requests.apiTarget!({ connectionId: 'openrouter', model: 'q' }, asker)).toEqual({ target: LAUNCH, apiBase: RELAY })
models.port.apiTarget.mockResolvedValueOnce({ detail: 'gone' })
expect(await options.requests.apiTarget!({ connectionId: 7 }, asker)).toEqual({ detail: 'gone' })
diff --git a/cli/src/services/modelsProcess.ts b/cli/src/services/modelsProcess.ts
index f749ca59f..63a1c368b 100644
--- a/cli/src/services/modelsProcess.ts
+++ b/cli/src/services/modelsProcess.ts
@@ -1,3 +1,4 @@
+import { gridAssignmentProcessesIn } from '../lib/gridAssignmentWire.js'
/**
* Models in its own process (`harness __service models`, with `HARNESSD_SERVICES=models`).
*
@@ -175,6 +176,10 @@ export function runModelsService(options: ModelsServiceOptions): ServiceProcess
ensure: async (payload) => ({ ...await models.ensure({ ownGrid: payload.ownGrid === true }) }),
launchTarget: async (payload) => ({ target: await models.launchTarget({ model: text(payload.model), grid: text(payload.grid) }) }),
moveTarget: async (payload) => ({ ...await models.moveTarget({ gridName: text(payload.gridName) || null, model: text(payload.model) }) }),
+ gridAssignments: async (payload) => {
+ const processes = gridAssignmentProcessesIn(payload.processes)
+ return processes ? { assignments: await models.gridAssignments(processes) } : { error: 'INVALID_PROCESSES' }
+ },
gridLaunch: async (payload) => {
const request = gridLaunchRequestIn(payload)
return request ? { ...await models.gridLaunch(request) } : { ok: false, error: 'INVALID_GRID', detail: 'This launch could not be read.' }
diff --git a/cli/src/startupOrder.spec.ts b/cli/src/startupOrder.spec.ts
index 6efb813c1..c8283b8c4 100644
--- a/cli/src/startupOrder.spec.ts
+++ b/cli/src/startupOrder.spec.ts
@@ -141,6 +141,18 @@ describe('the core\'s start-up order (core/main.ts)', () => {
.toEqual([])
})
+ it('protects acknowledged bindings on every exit after registry ownership, before startup can yield', () => {
+ const source = code(SOURCE)
+ const owned = source.indexOf('await refuseServedDataFolder(')
+ const loaded = source.indexOf('registry.load()')
+ const exiting = source.indexOf("process.on('exit', () => registry.flush({ exiting: true }))")
+ expect(loaded).toBeGreaterThan(owned)
+ expect(exiting).toBeGreaterThan(loaded)
+ // An update can exit before full teardown is constructed. Install the synchronous safeguard
+ // before the first yield after load, while a duplicate daemon still exits without touching disk.
+ expect(exiting).toBeLessThan(source.indexOf('\n await ', loaded))
+ })
+
it('only swaps in the full restart handler once everything it tears down exists', () => {
// `bootHandoff` hands the machine over without finishing start-up; the full handoff
// (core/updateHandoff.ts) tears down two dozen subsystems, handed to it here as its teardown, and may
diff --git a/cli/src/testing/gridAssignmentShapes.ts b/cli/src/testing/gridAssignmentShapes.ts
new file mode 100644
index 000000000..e71f4785a
--- /dev/null
+++ b/cli/src/testing/gridAssignmentShapes.ts
@@ -0,0 +1,28 @@
+/** Composition kept at the boundary while assignment classification moves to models. */
+import type { AgentEngine } from '../engines/types.js'
+import { ApiConnectionMetadata } from '../lib/apiConnectionMetadata.js'
+import { gridAssignmentProcess, gridAssignmentProcessesIn } from '../lib/gridAssignmentWire.js'
+import { createModelsLink } from '../core/modelsLink.js'
+import { rememberSavedApis } from '../lib/gridAssignment.js'
+import { ApiConnections } from '../lib/apiConnections.js'
+import { modelsAssignments } from '../services/modelsAssignments.js'
+import { prepareApiInstructions } from '../lib/apiInstructions.js'
+
+export function gridAssignmentShapes(dataDir: string) {
+ const store = new ApiConnectionMetadata(dataDir)
+ const classify = modelsAssignments(new ApiConnections(dataDir))
+ const port = createModelsLink({} as never, async (_type, payload) => {
+ const processes = gridAssignmentProcessesIn(JSON.parse(JSON.stringify(payload.processes)))
+ if (!processes) throw new Error('invalid assignment request')
+ return JSON.parse(JSON.stringify({ assignments: await classify(processes) }))
+ }, () => false).port
+ return {
+ remember: () => rememberSavedApis(store),
+ assignment: async (engine: AgentEngine, env: Record<string, string>, args = '') => {
+ const process = gridAssignmentProcess('golden', engine, env, args)
+ return process ? (await port.gridAssignments([process]))[0].assignment : null
+ },
+ list: () => store.list(),
+ instructions: (workspace: string, engine: string) => prepareApiInstructions(store, workspace, engine),
+ }
+}
diff --git a/docs/research/2026-10-09-daemon-separation-progress.md b/docs/research/2026-10-09-daemon-separation-progress.md
index 4966477c5..85615db2b 100644
--- a/docs/research/2026-10-09-daemon-separation-progress.md
+++ b/docs/research/2026-10-09-daemon-separation-progress.md
@@ -12,7 +12,7 @@ Time accounting (UTC): request first measured October 8 at 23:26:41; initial imp
## L3: Store launch preparation
-[PR #1073](https://github.com/autonomous-ai/openharness/pull/1073) is in progress. The 61-case DSH golden was re-recorded on `1987fa238` in its own commit before the move. Host tmux and Node paths are placeholders, both platforms are pinned, and execution uses `TZ=UTC TMPDIR=/tmp`. The fixture stays unchanged after moving requests and answers through JSON and the production validators.
+[PR #1073](https://github.com/autonomous-ai/openharness/pull/1073) merged as `0ed5636d4` at 01:22:56 UTC. The 61-case DSH golden was re-recorded on `1987fa238` in its own commit before the move. Host tmux and Node paths are placeholders, both platforms are pinned, and execution uses `TZ=UTC TMPDIR=/tmp`. The fixture stays unchanged after moving requests and answers through JSON and the production validators.
Core retains the installed index, compatibility checks, trust decisions, session state and pane ownership. Store owns workspace initialization and runtime preparation. Boot does not wait for Store. A grid package declares both dependencies; after a service cannot answer, later dependent agents in the same pass wait without repeating its deadline. Restore checks current held ownership after preparation and preserves the precise reason in the row and waiting pane.
@@ -33,3 +33,27 @@ A final fallback correction preserves `held` even when showing the waiting shell
L3 timing through the final local gates (UTC): implementation began after the crash fix merged at 00:00 and continued through 01:16; independent review ran alongside implementation and validation, with final approval at 01:14. Validation ran from the baseline measurement at 00:11 through final local checks after 01:16, including failed attempts above. The final six-file e2e run occupied 325 seconds; the successful type/core/recovery/resume/portability run occupied roughly four minutes with independent checks overlapped. Waiting for automatic CI and the merge are recorded separately in the PR body. Publication: zero. These phase intervals overlap and are not added to claim the total request duration.
The closure is 58,498 lines in 340 files versus 58,533 in 339 before L3. This is a reference; the added core recovery controls carry the safety guarantees above.
+
+
+L3 completion: [automatic CI](https://github.com/autonomous-ai/openharness/actions/runs/37869134630) passed all four Linux shards, typecheck, process checks and `ci/required`. The merge receipt verified both trees against reviewed head `8bd244a26` and base `db6eb769c`. Final CI waiting occupied 01:18–01:22:32; the merge helper occupied 01:22:43–01:22:56. Total request time through this merge was 1 hour 56 minutes 15 seconds, including implementation, review, diagnosis and waiting. Nothing was published.
+
+The final L3 measurement used Node 22.23.2, tmux 3.5a and the same Intel macOS machine with 16 logical CPUs and 64 GiB RAM. Four fake agents, two active agents, two windows and four streams ran ten-second empty/idle/active phases with two seconds of warmup and no history. Only the core PID was measured; workers, engines, tmux and USB were excluded. Baseline versus candidate CPU was 0.72/1.51/7.03% versus 0.80/1.70/6.96%; RSS was 80.2/102.3/99.5 MiB versus 81.3/96.4/99.4 MiB. Event-loop p95 stayed about 12.1 ms. Two turns completed in 6.37 versus 6.98 seconds; this sample is too small for a latency claim.
+
+## L2: assignment classification and saved APIs
+
+[PR #1076](https://github.com/autonomous-ai/openharness/pull/1076) is in progress. Commit `a05dc0060` recorded the former classifier, launch round trips, saved endpoint recognition and API instruction bytes before moving them. A separate type-only correction (`60d0cfd85`) left the fixture unchanged. Both platforms are pinned; execution uses UTC and `/tmp`. The golden now crosses the real models handler and both JSON validators. Six deliberately broken contributions are rejected by assertion failures: endpoint marker, model marker, provider argv, Pi config, OpenCode router and API endpoint normalization.
+
+Discovery collects only declared endpoint/model markers and relevant argv fragments, never API keys or the rest of a process environment. Core publishes readiness and bindings before sending classification requests to models. Every completed observation is classified afresh; there is no assignment cache. Identical pending observations share one bounded request so a slow answer cannot be starved by faster discovery passes. Answers are accepted only for the same process, session, lifecycle revision and newest evidence. Unknown reads, invalid replies and unavailable models preserve the last assignment. Reconciler route holds also reject metadata evidence from an obsolete probe. Restart and retarget commit their verified process before scheduling metadata.
+
+Saved API key access and writes remain with models. Core keeps a read-only metadata parser and the existing instruction preparation behavior. A validated endpoint vocabulary is persisted atomically beside the saved APIs, preserving recognition after an endpoint is edited or removed and the models process restarts. It intentionally survives a whole-daemon restart as well. Old version-one files remain readable; malformed or oversized updates leave the previous file intact. A new models process cannot clear assignments if it cannot read this vocabulary. An already initialized process keeps its validated vocabulary through a transient read failure.
+
+The new killed-models boot test exposed an existing shutdown race: an acknowledged binding could still be deferred by an unrelated discovery transaction when the process exited. Regression commit `ccc9fdc25` precedes the fix. Replaying it against the former registry under pinned Node and UTC fails because the saved session ID is empty instead of `just-bound`. Exit-only flushing now validates the entire live table before the existing locked, atomic merge, bypassing transaction batching only at exit. A half-finished pane swap is rejected without changing disk bytes. Core flushes before graceful shutdown work and at synchronous process exit. Ordinary and strict-close transaction behavior is unchanged.
+
+Validation plan: typecheck; architecture and unchanged golden; core and harnessd coverage; affected discovery, API, registry, models and backend specs; resume and portability coverage; real-tmux discovery; isolated machine, core, lifecycle and killed/hung-models e2e. Final gates follow integration with current main. Initial core and harnessd gates passed, but the combined affected receipt failed on an obsolete test stub and is not passing evidence. The first e2e receipt passed core/lifecycle and two models cases; it failed one fixture that used an intentionally ignored unowned tmux session and the genuine shutdown race above. The fixture now creates a registered terminal first. Final counts and review evidence are recorded when these gates complete.
+
+L2 timing: golden recording and implementation began after the L3 merge at 01:22:56 UTC. Independent review identified endpoint recognition after worker restart, slow-request starvation and held-route evidence races; all three were corrected before final validation. Implementation and review continued through 01:50. Publication remains zero.
+
+
+L2 integrated main `d364ca98e` before final gates; its CLI launch/account/retention changes were reviewed with the assignment move. Receipt `20261009T015141.373083Z-17943` passed typecheck, 1,704 core tests at per-file 100% coverage, 265 harnessd tests with one existing skip, and 477 affected tests in 17 files. Receipt `20261009T015303.584859Z-32741` passed 292 resume tests, 1,050 portability tests with nine skips at their 100% gates, and 57 real-tmux tests with 15 unavailable-engine skips. The e2e receipt passed all 16 core/lifecycle and six machine tests, plus three models cases, but failed the new assignment-recovery case and remains failed evidence.
+
+That remaining failure was traced to the fake engine's `process.title` rewrite: macOS `ps eww` returned its title with no environment, although the fixture inherited both endpoint and model. Core correctly treated that as unknown. The evidence test now opts into retaining the interpreter and real engine entrypoint, which discovery recognizes on both platforms. It does not weaken the production unknown-read rule. Independent review's final startup finding was also corrected: the exit listener is installed immediately after registry ownership/load, before startup yields, covering a staged update before full teardown exists. The new startup-order regression fails on the former placement and passes after the move. Final validation follows these narrow corrections; publication remains zero.