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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Models runs in a process of its own: the core reaches grid only through its port (#896)
Dee99036bc49d3f
diff --git a/cli/e2e/compat.e2e.ts b/cli/e2e/compat.e2e.tsindex 67e5f4605..9e591a749 100644--- a/cli/e2e/compat.e2e.ts+++ b/cli/e2e/compat.e2e.ts@@ -26,6 +26,9 @@ import { LocalClient, type Frame } from './harness/client.js'import { CLI_ROOT, IsolatedDaemon, until } from './harness/daemon.js'const FROM = process.env.COMPAT_FROM+/** No `grid` on either side's machine as far as the daemons can tell: never the developer's own, and the+ * same answer from both. */+const NO_GRID = '/nonexistent/harness-compat/grid'/*** Differences on purpose, by the path that differs (a prefix covers everything under it), each with@@ -233,6 +236,16 @@ async function scenario(d: IsolatedDaemon): Promise<Answers> {await ask('agents_cleanup_preview', 'agents_cleanup_preview')await ask('harness_devices_list', 'harness_devices_list')await ask('theme_set', 'theme_set', { background: '#000000', foreground: '#ffffff' })+ // Models, in its own process from step 7 (docs/design/2026-10-06-core-boundary-next.md): the pickers, the+ // Model Manager and its grid commands, a create on a grid model. Nothing that sets grid up is asked: a+ // Set up, a Get or a Use would install it.+ await ask('grid_models_list', 'grid_models_list')+ await ask('grid_models_list with row state', 'grid_models_list', { rowState: true })+ await ask('grid_fleet_models_list', 'grid_fleet_models_list')+ await ask('grid_fleet_capabilities', 'grid_fleet_capabilities')+ await ask('grid_fleet_run', 'grid_fleet_run', { args: ['--remote', 'ls', '--json'], timeoutMs: 5_000 })+ await ask('grid_fleet_cancel', 'grid_fleet_cancel', { commandId: 'compat-not-running' })+ await ask('agent_create on a grid model', 'agent_create', { engine: 'codex', cwd: cwd('codex'), gridModel: 'Qwen3-Coder-30B', gridName: 'mine', bypassPermission: true })await ask('a request nobody answers', 'compat_unknown_request')await ask('agent_create_status for no such creation', 'agent_create_status', { creationId: 'compat-no-such-creation' })@@ -243,7 +256,9 @@ async function scenario(d: IsolatedDaemon): Promise<Answers> {'git_project_info', 'fs_list_dir', 'project_preview', 'session_tail', 'dsh_remove', 'dsh_install', 'dsh_update', 'theme_set','agent_create', 'agent_create_status', 'agent_handoff_prepare', 'agent_worktree_delete', 'message',// Moved out of the socket's switch into services (docs/design/2026-10-06-core-boundary-next.md, step 4).- 'git_pull_request', 'codex_profile_link', 'api_connections']+ 'git_pull_request', 'codex_profile_link', 'api_connections',+ // Into models' own process (step 7). A Get and a Use are left out: they set grid up.+ 'grid_fleet_run', 'grid_fleet_cancel', 'grid_fleet_model_stop']for (const type of malformed) {// `cancel` and `message` are fire-and-forget: no build answers them, so waiting a minute shows nothing more.const ms = type === 'cancel' || type === 'message' ? 5_000 : 60_000@@ -303,8 +318,8 @@ describe.skipIf(!FROM)('what the apps see, compared with the released build', ()for (const dir of [build, released]) writeFileSync(join(dir, 'package.json'), '{"type":"module"}\n')for (const [side, options] of [- ['released', { scriptPath: join(released, 'cli.js'), env: { ADAPTER_CLI_DIR: released } }],- ['this', { scriptPath: join(build, 'cli.js'), env: { ADAPTER_CLI_DIR: build } }],+ ['released', { scriptPath: join(released, 'cli.js'), env: { ADAPTER_CLI_DIR: released, HARNESS_GRID_BIN: NO_GRID } }],+ ['this', { scriptPath: join(build, 'cli.js'), env: { ADAPTER_CLI_DIR: build, HARNESS_GRID_BIN: NO_GRID } }],] as const) {const d = await IsolatedDaemon.create(options)// tmux titles each new pane with the machine's name as it is then, and a daemon refuses that titlediff --git a/cli/e2e/lean.e2e.ts b/cli/e2e/lean.e2e.tsindex e2a56e0b6..d422de569 100644--- a/cli/e2e/lean.e2e.ts+++ b/cli/e2e/lean.e2e.ts@@ -20,8 +20,8 @@ import { readLeanBundle } from '../src/harnessd/leanBundle.js'type Engine = 'claude' | 'codex'/** The processes the master runs the services in, and the services, each on its own link to the core. */-const PROCESSES = ['search', 'viewers', 'edge', 'teams']-const SERVICES = ['search', 'viewers', 'store', 'workspaces', 'usage', 'monitor', 'projects', 'teams']+const PROCESSES = ['search', 'viewers', 'edge', 'teams', 'models']+const SERVICES = ['search', 'viewers', 'store', 'workspaces', 'usage', 'monitor', 'projects', 'teams', 'models']const commandOf = (pid: number): string => execFileSync('ps', ['-o', 'command=', '-p', String(pid)], { encoding: 'utf8' }).trim()const rssMiB = (pid: number): number => Number(execFileSync('ps', ['-o', 'rss=', '-p', String(pid)], { encoding: 'utf8' }).trim()) / 1024diff --git a/cli/e2e/models.e2e.ts b/cli/e2e/models.e2e.tsindex 3e0d0a27c..8831cc7db 100644--- a/cli/e2e/models.e2e.ts+++ b/cli/e2e/models.e2e.ts@@ -140,6 +140,33 @@ describe('switching a Codex agent model and effort', () => {client.close()})+ it('lists the choices from models\' own process, and switches with models killed: the switch is the core\'s', async () => {+ const d = await fresh({ codexModel: 'gpt-5.5', env: { HARNESSD_SERVICE_INITIAL_BACKOFF_MS: '8000', HARNESSD_SERVICE_MAX_BACKOFF_MS: '8000' } })+ await until('models to connect to the core', () => d.log().includes('[services] models connected') || null, 30_000, 200)+ const client = await LocalClient.connect(d)+ const agent = await create(d, client, 'apart')+ await turn(client, agent.id, 'hello')+ await runningOn(client, agent.id, 'gpt-5.5', 'high')+ // The picker's choices come from models, in its own process (harnessd/services.ts), which asks the core+ // for the agent's catalog.+ const xhigh = profile(agent.id, 'gpt-6-luna', 'xhigh')+ const offered = (await client.request<{ models: Array<{ id: string }> }>('models_list', { agentId: agent.id }, 30_000)).models+ expect(offered.map((option) => option.id)).toContain(xhigh)++ const pids = [...d.log().matchAll(/\[harnessd\] service models started \(pid (\d+)\)/g)].map((match) => Number(match[1]))+ for (const pid of pids) { try { process.kill(pid, 'SIGKILL') } catch { /* already gone */ } }+ await until('the core to see models gone', () => d.log().includes('[services] models disconnected') || null, 15_000, 100)+ expect(await client.request('models_list', { agentId: agent.id }, 10_000)).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'models', retryable: true })+ // A switch the picker already offered is the core's to make, and the agent goes on on it.+ const switched = await client.request('agent_update', { agentId: agent.id, selectedModel: xhigh }, 60_000)+ expect(switched.error, JSON.stringify(switched)).toBeUndefined()+ expect(applied(d, agent.sessionId)).toEqual([{ model: 'gpt-6-luna', effort: 'xhigh' }])+ await turn(client, agent.id, 'while models was gone')+ await runningOn(client, agent.id, 'gpt-6-luna', 'xhigh')+ expect(d.coresStarted()).toBe(1)+ client.close()+ })+it('offers an account held to the reserve model no other model, and changes the reserve effort', async () => {const d = await fresh({ codexModel: 'gpt-reserve' })const client = await LocalClient.connect(d)diff --git a/cli/e2e/serviceProcesses.e2e.ts b/cli/e2e/serviceProcesses.e2e.tsindex 3216b3745..9b2a6dda1 100644--- a/cli/e2e/serviceProcesses.e2e.ts+++ b/cli/e2e/serviceProcesses.e2e.ts@@ -1,11 +1,12 @@/*** Services in their own processes, for Claude Code and Codex, on the real daemon: harnessd's master runs- * search beside the core (`HARNESSD_SERVICES=search`), and the edge host, one process for several light- * services (`HARNESSD_SERVICES=edge`: workspaces, usage, the monitor and the project readers). Whatever- * happens to either process — killed outright, hung, leaking memory, crashing on every start — costs that- * process alone. The core never restarts, every agent keeps working, a request asked while it is down is- * answered SERVICE_UNAVAILABLE at once, and the master brings it back (or parks it, when it keeps- * crashing), every service in it connected again.+ * search beside the core (`HARNESSD_SERVICES=search`), the edge host, one process for several light+ * services (`HARNESSD_SERVICES=edge`: workspaces, usage, the monitor and the project readers), and models+ * (`HARNESSD_SERVICES=models`: grid, the Model Manager, the pickers). Whatever happens to any of them —+ * killed outright, hung, leaking memory, crashing on every start — costs that process alone. The core+ * never restarts, every agent keeps working, a request asked while it is down is answered+ * SERVICE_UNAVAILABLE at once (a create on a grid model, GRID_UNAVAILABLE), and the master brings it back+ * (or parks it, when it keeps crashing), every service in it connected again.*/import { execFileSync } from 'node:child_process'import { mkdirSync } from 'node:fs'@@ -278,3 +279,141 @@ describe('the edge host: several services in one process of their own', () => {client.close()})})++/** This daemon's models process: titled `harnessd-models` AND started by its own master, by the pid it logged. */+function modelsPids(d: IsolatedDaemon): number[] {+ const ours = new Set([...d.log().matchAll(/\[harnessd\] service models started \(pid (\d+)\)/g)].map((match) => Number(match[1])))+ const table = execFileSync('ps', ['-A', '-o', 'pid=,command=']).toString().trim().split('\n')+ return table.map((line) => line.trim().match(/^(\d+)\s+(.*)$/)).filter((match): match is RegExpMatchArray => !!match)+ .filter(([, pid, command]) => command.trim() === 'harnessd-models' && ours.has(Number(pid))).map(([, pid]) => Number(pid))+}+/** A create on a grid model: what the models picker sends, a model and the grid serving it. */+const createOnGrid = (client: LocalClient, d: IsolatedDaemon): Promise<Record<string, any>> =>+ client.request('agent_create', { engine: 'codex', cwd: join(d.projectsDir, 'on-a-grid'), gridModel: 'Qwen3-Coder-30B', gridName: 'mine', bypassPermission: true }, 30_000)+/** Models answers, through the core: the Model Manager's list, signed out, says to sign in. */+async function modelsAnswers(client: LocalClient): Promise<boolean> {+ const manager = await client.request('grid_fleet_models_list', {}, 30_000)+ return manager.error === undefined && Array.isArray(manager.models)+}++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: {+ HARNESSD_SERVICES: 'models',+ HARNESSD_SERVICE_INITIAL_BACKOFF_MS: '200',+ HARNESSD_SERVICE_MAX_BACKOFF_MS: '1000',+ // No `grid` on this machine as far as the daemon can tell: never the developer's own.+ HARNESS_GRID_BIN: '/nonexistent/harness-e2e/grid',+ ...env,+ } })+ daemon = d+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`) })+ await d.start()+ await until('models to connect to the core', () => d.log().includes('[services] models connected') || null, 30_000, 200)+ return d+ }+ const restarts = (d: IsolatedDaemon) => d.log().split('\n').filter((line) => /\[harnessd\] service models started .* restart \d+/.test(line)).length++ it('answers the pickers, the Model Manager and its grid commands through the core, and each agent\'s Model/Effort choices, for both engines', async () => {+ const d = await fresh()+ const client = await LocalClient.connect(d)+ expect(modelsPids(d)).toHaveLength(1)+ expect(await client.request('grid_models_list', {}, 30_000)).toMatchObject({ gridName: null, models: [], grids: [], gridCli: 'missing' })+ expect(await client.request('grid_fleet_models_list', {}, 30_000)).toMatchObject({ models: [], notice: 'Sign in to find models for this computer.' })+ // The commands' handshake is the core's own; the command runs in models' process, as this connection's job.+ expect(await client.request('grid_fleet_capabilities', {})).toMatchObject({ protocol: 1, gridCli: 'missing' })+ expect(await client.request('grid_fleet_run', { args: ['--remote', 'ls', '--json'], timeoutMs: 5_000 }, 30_000))+ .toMatchObject({ ok: false, code: 127, error: 'Grid could not start on this machine. Check its Grid installation.' })+ expect(await client.request('grid_fleet_run', { args: [] }, 30_000)).toMatchObject({ error: 'INVALID_GRID_COMMAND' })+ expect(await client.request('grid_fleet_cancel', { commandId: 'not-running' }, 30_000)).toMatchObject({ cancelled: false })+ for (const engine of ['claude', 'codex'] as const) {+ const agent = await create(d, client, engine, `models-${engine}`)+ await turn(client, agent.id, `with models apart (${engine})`)+ const offered = await client.request('models_list', { agentId: agent.id }, 30_000)+ expect(offered.error, JSON.stringify(offered)).toBeUndefined()+ expect(Array.isArray(offered.models)).toBe(true)+ }+ // A create on a grid model that this machine's grid does not serve is refused, as in the core's process.+ expect(await createOnGrid(client, d)).toMatchObject({ error: 'GRID_UNAVAILABLE' })+ expect(d.coresStarted()).toBe(1)+ client.close()+ })++ it('killed outright: the Model Manager says so at once, a create on a grid model answers GRID_UNAVAILABLE, every agent goes on, and the master brings it back', async () => {+ // Slow to come back, so what is asked 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)+ const agents = [await create(d, client, 'claude', 'models-killed-claude'), await create(d, client, 'codex', 'models-killed-codex')]+ const before = modelsPids(d)+ expect(before).toHaveLength(1)+ 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)+ const asked = Date.now()+ expect(await client.request('grid_fleet_models_list', {}, 10_000)).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'models', retryable: true })+ expect(await client.request('grid_models_list', {}, 10_000)).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'models', retryable: true })+ expect(await createOnGrid(client, d)).toMatchObject({ error: 'GRID_UNAVAILABLE' })+ expect(Date.now() - asked).toBeLessThan(5_000)+ // The agents never noticed, and their rows are as they were.+ for (const agent of agents) await turn(client, agent.id, `while models was gone (${agent.engine})`)+ expect((await client.request('agents_list', {}, 30_000)).agents.map((one: Record<string, any>) => one.id).sort()).toEqual(agents.map((one) => one.id).sort())+ 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(modelsPids(d).some((pid) => !before.includes(pid))).toBe(true)+ expect(d.coresStarted()).toBe(1)+ client.close()+ })++ it('hung, it is killed by the master\'s heartbeat watch and started again; the core never waits on it', async () => {+ const d = await fresh({ HARNESSD_SERVICE_HEARTBEAT_TIMEOUT_MS: '2000' })+ const client = await LocalClient.connect(d)+ const agent = await create(d, client, 'codex', 'models-hung')+ for (const pid of modelsPids(d)) process.kill(pid, 'SIGSTOP')+ // Frames read what models last said, and turns never ask it: neither waits.+ const listed = Date.now()+ expect((await client.request('agents_list', {}, 30_000)).agents.some((one: Record<string, any>) => one.id === agent.id)).toBe(true)+ expect(Date.now() - listed).toBeLessThan(5_000)+ await turn(client, agent.id, 'the core never waited on models')+ // Asked while it is stopped: answered when the master kills it and the link lets go, never a hang.+ const answer = await client.request('grid_fleet_models_list', {}, 40_000)+ if (answer.error) expect(answer).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'models' })+ await until('the master to find models hung', () => d.log().includes('[harnessd] service models sent no heartbeat') || null, 30_000, 200)+ await until('models to be started again', () => restarts(d) >= 1 || null, 30_000, 200)+ await until('models to answer again', () => modelsAnswers(client).then((ok) => ok || null), 30_000, 500)+ expect(d.coresStarted()).toBe(1)+ client.close()+ })++ it('leaking, it is restarted at its memory budget, before it can hurt anything else', async () => {+ const d = await fresh({ HARNESSD_TEST_FAULTS: 'models.leak', HARNESSD_SERVICE_HEAP_LIMIT_MIB: '128' })+ const client = await LocalClient.connect(d)+ const agent = await create(d, client, 'claude', 'models-leaking')+ await until('the master to restart models for memory', () => /\[harnessd\] service models: (its heap is at|it is using)/.test(d.log()) || null, 60_000, 250)+ await until('models to be started again', () => restarts(d) >= 1 || null, 30_000, 200)+ await turn(client, agent.id, 'the leak was models\' alone')+ expect(d.coresStarted()).toBe(1)+ client.close()+ })++ it('crashing on every start, it is parked, and asked meanwhile says so; a create on a grid model is refused, and agents go on', async () => {+ const d = await IsolatedDaemon.create({ env: {+ HARNESSD_SERVICES: 'models', HARNESSD_TEST_FAULTS: 'models.crash', HARNESSD_SERVICE_PARK_CRASHES: '3',+ HARNESSD_SERVICE_INITIAL_BACKOFF_MS: '200', HARNESSD_SERVICE_MAX_BACKOFF_MS: '1000', HARNESS_GRID_BIN: '/nonexistent/harness-e2e/grid',+ } })+ daemon = d+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`) })+ await d.start()+ const client = await LocalClient.connect(d)+ const agent = await create(d, client, 'codex', 'models-crash-loop')+ await until('the master to park models', () => d.log().includes('[harnessd] service models ended 3 times') || null, 60_000, 250)+ expect(await client.request('grid_fleet_models_list', {}, 10_000)).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'models', retryable: true })+ expect(await client.request('models_list', { agentId: agent.id }, 10_000)).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'models', retryable: true })+ expect(await createOnGrid(client, d)).toMatchObject({ error: 'GRID_UNAVAILABLE' })+ // The handshake is the core's: the Grid harness is told its command was refused, not to update Harness.+ expect(await client.request('grid_fleet_capabilities', {})).toMatchObject({ protocol: 1 })+ await turn(client, agent.id, 'models is parked and nothing else cares')+ expect(d.coresStarted()).toBe(1)+ client.close()+ })+})diff --git a/cli/e2e/services.e2e.ts b/cli/e2e/services.e2e.tsindex 89065f2ed..2a42d6020 100644--- a/cli/e2e/services.e2e.ts+++ b/cli/e2e/services.e2e.ts@@ -2,10 +2,10 @@* A failing service never takes the core down, proven on the real daemon: every service made to fail as* it starts, and services made to fail on every call, while a client starts an agent, the agent binds,* messages become turns that start and end, and the daemon restarts. Both ways a service runs: in a- * process of its own (the default for search, the viewers, the teams and the edge host's workspaces,- * usage, monitor and project readers, harnessd/services.ts), and inside the core's process- * (`HARNESSD_SERVICES=none`, and always for models, the Store and the fleet), where the core's host- * guards it (core/serviceHost.ts).+ * process of its own (the default for search, the viewers with the Store, the teams, models and the edge+ * host's workspaces, usage, monitor and project readers, harnessd/services.ts), and inside the core's+ * process (`HARNESSD_SERVICES=none`, and always for the fleet), where the core's host guards it+ * (core/serviceHost.ts).*/import { randomUUID } from 'node:crypto'import { mkdirSync } from 'node:fs'@@ -52,15 +52,15 @@ const IN_THE_CORE = { HARNESSD_SERVICES: 'none' }/** A master quick to give up on a service that keeps failing as it starts. */const QUICK_TO_PARK = { HARNESSD_SERVICE_PARK_CRASHES: '3', HARNESSD_SERVICE_INITIAL_BACKOFF_MS: '200', HARNESSD_SERVICE_MAX_BACKOFF_MS: '1000' }/** The processes the services run in by default, and what makes every one of them fail as it starts. */-const SERVICE_PROCESSES = ['search', 'viewers', 'edge', 'teams'] as const-const EVERY_PROCESS_FAILING = 'search,viewers,store,workspaces,usage,monitor,projects,teams'+const SERVICE_PROCESSES = ['search', 'viewers', 'edge', 'teams', 'models'] as const+const EVERY_PROCESS_FAILING = 'search,viewers,store,workspaces,usage,monitor,projects,teams,models'describe('a failing service never takes the core down', () => {let daemon: IsolatedDaemon | undefinedafterEach(async () => { await daemon?.close(); daemon = undefined })it('with every service failing to start, in its own process or in the core, the core starts, runs an agent through turns and a restart, and says each one is unavailable', async () => {- daemon = await IsolatedDaemon.create({ env: { HARNESSD_TEST_FAULTS: `${EVERY_PROCESS_FAILING},models`, ...QUICK_TO_PARK } })+ daemon = await IsolatedDaemon.create({ env: { HARNESSD_TEST_FAULTS: EVERY_PROCESS_FAILING, ...QUICK_TO_PARK } })const d = daemononTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-120).join('\n')}`) })await d.start()@@ -68,7 +68,6 @@ describe('a failing service never takes the core down', () => {for (const service of SERVICE_PROCESSES) {await until(`the master to park ${service}`, () => d.log().includes(`[harnessd] service ${service} ended 3 times`) || null, 60_000, 250)}- expect(d.log()).toContain('[services] models did not start · injected fault: models · the core runs without it')const client = await LocalClient.connect(d)const agentId = await boundAgent(d, client, 'no-service-processes')await turn(client, agentId, 'first, with every service down')@@ -76,6 +75,10 @@ describe('a failing service never takes the core down', () => {expect(await client.request('dsh_list', {})).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'store', retryable: true })expect(await client.request('fs_list_dir', { path: d.projectsDir })).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'projects', retryable: true })expect(await client.request('machine_resources', {})).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'monitor', retryable: true })+ expect(await client.request('grid_fleet_models_list', {})).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'models', retryable: true })+ // A create on a grid model, with models parked, is refused as the grid being unavailable, at once.+ const onGrid = await client.request('agent_create', { engine: 'codex', cwd: d.projectsDir, gridModel: 'Qwen-35B', gridName: 'mine', bypassPermission: true }, 30_000)+ expect(onGrid).toMatchObject({ error: 'GRID_UNAVAILABLE' })// With the monitor's process parked, the Monitor's list is still the list: its rows, without readings.const monitored = (await client.request('agents_list', { monitor: true })).agents.find((agent: Record<string, any>) => agent.id === agentId)expect(monitored.monitor).toMatchObject({ rssBytes: null, cpu: null, processes: [], sampledAt: null })@@ -144,7 +147,7 @@ describe('a failing service never takes the core down', () => {expect(await client.request(type, { id: 'acme/thing' }), type).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'store', retryable: false })}for (const type of ['grid_models_list', 'models_list', 'grid_fleet_models_list', 'grid_fleet_model_download', 'grid_fleet_model_start', 'grid_fleet_model_stop',- 'api_connections', 'codex_profiles_list', 'codex_profile_link']) {+ 'grid_fleet_run', 'grid_fleet_cancel', 'api_connections', 'codex_profiles_list', 'codex_profile_link']) {expect(await client.request(type, { modelId: 'org/Model-GGUF' }), type).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'models', retryable: false })}// The services that came out of the socket's switch (docs/design/2026-10-06-core-boundary-next.md, step 4).@@ -157,8 +160,8 @@ describe('a failing service never takes the core down', () => {// With the monitor off, the Monitor's list is still the list: its rows, without readings.const monitored = (await client.request('agents_list', { monitor: true })).agents.find((agent: Record<string, any>) => agent.id === agentId)expect(monitored.monitor).toMatchObject({ rssBytes: null, cpu: null, processes: [] })- // The Model Manager's grid commands are still the socket's, and so is their handshake: models being- // off does not tell the Grid harness to update Harness.+ // The Model Manager's grid commands' handshake is still the socket's: models being off does not tell+ // the Grid harness to update Harness.expect(await client.request('grid_fleet_capabilities', {})).toMatchObject({ protocol: 1, thinkingControl: true })await daemon.restart()@@ -297,11 +300,14 @@ describe('a failing service never takes the core down', () => {it('models answers from its own service; one of its requests failing leaves its others and the core alone', async () => {daemon = await IsolatedDaemon.create({ env: { HARNESSD_TEST_FAULTS: 'models.grid_models_list' } })- onTestFailed(() => { console.log(`---- daemon log\n${daemon?.log().split('\n').slice(-80).join('\n')}`) })- await daemon.start()+ const d = daemon+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-80).join('\n')}`) })+ await d.start()+ // In its own process: asked before it has connected, it is answered SERVICE_UNAVAILABLE, retryable.+ await until('models to connect', () => d.log().includes('[services] models connected') || null, 30_000, 200)const client = await LocalClient.connect(daemon)expect(await client.request('grid_models_list', {})).toMatchObject({ error: 'SERVICE_FAILED', service: 'models' })- expect(daemon.log()).toContain('[services] models.grid_models_list failed · injected fault: models.grid_models_list')+ expect(daemon.log()).toContain('[service models] grid_models_list failed · injected fault: models.grid_models_list')// Its other requests are still its own answers: with no agent here, no Model/Effort choices.expect(await client.request('models_list', {})).toMatchObject({ models: [] })expect(await client.request('grid_fleet_capabilities', {})).toMatchObject({ protocol: 1 })diff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.tsindex c5a233aa0..861e3c7e3 100644--- a/cli/src/architecture.spec.ts+++ b/cli/src/architecture.spec.ts@@ -143,12 +143,16 @@ const WALK_TIMEOUT_MS = 60_000* modules: binding each of them is the wiring this function is for. backendSocket.ts lost 615 lines in* those moves, and runForeground gained 28. Down to 2,380 on 6 October (step 11), at 2,346: a core on its* own hands an update to a master, which judges it, and no longer spawns, judges and rolls back a core.+ *+ * BACKEND_SOCKET_BUDGET came down again on 6 October (step 7): the Model Manager's grid commands, the grid+ * name it worked out and the model lists it built moved to the models service, 1,457 → 1,391 lines.*/const RUN_FOREGROUND_BUDGET = 2_380/** Lowered from 2,180 when the relay and its E2EE left the socket for the gateway (step 10, R1: 1,440).* The Wi-Fi device's relay came back to it in R2, beside the device service it answers for, over the- * gateway's sessions (lib/autonomous-device/overGateway.ts): 1,460. */-const BACKEND_SOCKET_BUDGET = 1_460+ * gateway's sessions (lib/autonomous-device/overGateway.ts): 1,460. Models' grid commands, grid name and+ * lists left it for the models service (step 7): 1,391. */+const BACKEND_SOCKET_BUDGET = 1_400/** Exceptions, each with its reason. Keep this short. */const SERVICE_MAY_IMPORT: Record<string, string> = {@@ -176,9 +180,6 @@ const SERVICE_MAY_IMPORT: Record<string, string> = {* Grew by 58 for the turn a blocking Stop hook continues (a Claude /goal loop): it is the turn lifecycle,* which only the core's transcript normalizer and Stop-hook fallback can keep.*- * Grew by 97 for the Jev catalog (#888, lib/localModels.ts and appModels.ts): the models service's own- * code, in the core's process only until step 7 runs models in a process of its own and takes it out.- ** Then at 102,019 in 430 with #893's shell launch (step 5), from 106,006 in 451: search, the viewers, workspaces, usage, the* monitor and the project readers run in processes of their own, and their code is loaded into the* core's only when they run there instead (services/inline.ts). Then at 101,896 in 430 (step 6): the@@ -216,7 +217,12 @@ const SERVICE_MAY_IMPORT: Record<string, string> = {// Then at 95,374 in 417 (step 11), from 95,380: a core on its own hands an update to a master on the new// build, which judges it, instead of spawning a core and judging it itself. Not the 180 lines the plan// counted on: a core still runs without a master when an older release's own handoff started it.-const CORE_CLOSURE_BUDGET = 95_420+//+// Then at 89,632 in 401 (step 7), from 95,374 in 417: models runs in a process of its own, the Jev catalog's+// 97 lines (#888) with it, and the core reaches grid only through its port (core/modelsLink.ts), keeping+// which `grid` a pane runs (lib/gridBinary.ts), how a frame reads a grid's note (lib/gridAnnotation.ts) and+// the launchers (lib/launchers.ts).+const CORE_CLOSURE_BUDGET = 89_730/** What is not the core's, by path: each goes to a service or its own process, in the plan's order. */const EDGE: RegExp[] = [@@ -291,23 +297,6 @@ const CORE_MAY_REACH: Record<string, string> = {'lib/e2ee/machinePeers.ts': 'step 9: the fleet reads which machines are linked (their public keys, no credential), beside the dial','lib/e2ee/passwordPake.ts': 'with lib/e2ee/store.ts','lib/e2ee/store.ts': 'step 8: this machine\'s identity, for Share\'s owner',- 'lib/gridAttach.ts': 'step 7: models, in its own process',- 'lib/gridCredentials.ts': 'step 7: models, in its own process',- 'lib/gridDerive.ts': 'step 7: models, in its own process',- 'lib/gridEnsure.ts': 'step 7: models, in its own process',- 'lib/gridExec.ts': 'step 7: models, in its own process',- 'lib/gridFleetRpc.ts': 'step 7: models, in its own process',- 'lib/gridHandoff.ts': 'step 7: models, in its own process',- 'lib/gridInstall.ts': 'step 7: models, in its own process',- 'lib/gridMcpUrl.ts': 'step 7: models, in its own process',- 'lib/gridModels.ts': 'step 7: models, in its own process',- 'lib/gridModelsPayload.ts': 'step 7: models, in its own process',- 'lib/gridPicture.ts': 'step 7: models, in its own process',- 'lib/gridPresence.ts': 'step 7: models, in its own process',- 'lib/gridReader.ts': 'step 7: models, in its own process',- 'lib/gridTarget.ts': 'step 7: models, in its own process',- 'lib/gridWake.ts': 'step 7: models, in its own process',- 'lib/localModels.ts': 'step 7: models, in its own process','lib/sessionSearch/sessionTurns.ts': 'the handoff (lib/agentHandoff.ts), in the edge host once CoreApi gives it the stopped agents, recaps and discovery it reads','lib/sessionSearch/transcript.ts': 'the readers of other engines\' sessions keep this helper: it moves beside them, out of search\'s folder','lib/sessionSearch/turns.ts': 'the handoff (lib/agentHandoff.ts), in the edge host once CoreApi gives it the stopped agents, recaps and discovery it reads',@@ -318,9 +307,7 @@ const CORE_MAY_REACH: Record<string, string> = {'orchestrator/wire.ts': 'step 8: the experimental host','services/fleet.ts': 'step 9: the fleet, beside the dial','services/fleetRouter.ts': 'step 9: the fleet, beside the dial',- 'services/models.ts': 'step 7: models, in its own process','services/shell.ts': 'shell setup and launch receipts, in the edge host; only the argv launch stays in the core (#893)',- 'services/requestErrors.ts': 'step 7: with the last service that uses it, models, out of the core\'s process','sharing/collaboration.ts': 'step 8: the experimental host','sharing/crypto.ts': 'step 8: the experimental host','sharing/grants.ts': 'step 8: the experimental host',diff --git a/cli/src/backendSocket.gridReads.spec.ts b/cli/src/backendSocket.gridReads.spec.tsindex 35facdff6..a986a12cb 100644--- a/cli/src/backendSocket.gridReads.spec.ts+++ b/cli/src/backendSocket.gridReads.spec.ts@@ -14,7 +14,7 @@ import { join } from 'node:path'import { BackendSocket } from './backendSocket.js'import { relaySocket } from './testing/relaySocket.js'import { env } from './config/env.js'-import { emptyPorts, MODELS_FALLBACKS } from './core/api.js'+import { emptyPorts, MODELS_FALLBACKS, MODELS_OFF } from './core/api.js'import { createServiceHost } from './core/serviceHost.js'import { fakeGridAnswers, installFakeGrid, type FakeGrid, type FakeGridPlan } from './lib/__fixtures__/fakeGrid.js'import { clearGridMcpUrlCache } from './lib/gridMcpUrl.js'@@ -23,6 +23,13 @@ import { MODELS_REQUESTS, startModels } from './services/models.js'import { fakeCore } from './testing/fakeCore.js'const OWN = 'mine', OWN_ID = 'net-own'++// Grid's set-up, which a move onto a grid model asks the models service for first: the fake grid here is+// set up already, as on a machine that has used it before.+vi.mock('./lib/gridAttach.js', async (real) => ({+ ...await real<object>(),+ createGridAccess: () => ({ ensure: async () => ({ status: 'converged', name: 'mine', detail: 'set up already' }) }),+}))const OVERVIEW = '/relay/v1/grid/overview'let server: Server, base: string, seen: Array<{ path: string; headers: IncomingHttpHeaders }>@@ -95,13 +102,17 @@ beforeEach(async () => {grid = installFakeGrid(plan())socket = relaySocket('token')socket.setHarnessGridName(OWN)- const models = createServiceHost(emptyPorts(), { log: () => {} })+ const ports = emptyPorts()+ const models = createServiceHost(ports, { log: () => {} })+ // This test's socket, not the variable's: a change an earlier test's pictures say late must not push here.+ const here = socketmodels.start('models', startModels, fakeCore({dataDir: join(root, 'data'),- account: { privateGridName: () => socket.privateGridName(), machineName: () => socket.machineName() },- clients: { gridModelsChanged: () => { void socket.pushGridModels() } },+ account: { privateGridName: async () => here.gridName(), machineName: () => here.machineName() },+ clients: { gridModelsChanged: () => { void here.pushGridModels() } },}), MODELS_FALLBACKS, MODELS_REQUESTS)socket.serviceRouter = (type, payload, asker, reply) => models.route(type, payload, asker, reply)+ socket.models = () => ports.models ?? MODELS_OFFframes = []socket.registerLocalClient('local:grid-reads', { sendFrame: (frame) => { frames.push(frame as typeof frames[number]); return true }, sendBinary: () => true })})diff --git a/cli/src/backendSocket.models.spec.ts b/cli/src/backendSocket.models.spec.tsindex 9c82c69e0..d50ae1374 100644--- a/cli/src/backendSocket.models.spec.ts+++ b/cli/src/backendSocket.models.spec.ts@@ -6,9 +6,9 @@ import { BackendSocket } from './backendSocket.js'import { relaySocket } from './testing/relaySocket.js'import { bindLaunchRequests } from './testing/socketCore.js'import { env } from './config/env.js'-import { resolveNewAgentModel } from './lib/newAgentModel.js'-vi.mock('./lib/newAgentModel.js', async (original) => ({ ...await original<typeof import('./lib/newAgentModel.js')>(), resolveNewAgentModel: vi.fn() }))+/** Where the models service resolves a new agent's grid model (core/api.ts `ModelsPort.launchTarget`). */+const resolveNewAgentModel = vi.fn()let socket: BackendSocket, root: string, previous: stringlet frames: Array<{ type: string; payload: Record<string, unknown> }>const target = { networkId: 'fixture-grid', networkName: 'my-grid', baseUrl: 'https://fixture.invalid/relay/v1', apiKey: 'fixture-secret', model: 'Qwen-35B' }@@ -19,7 +19,7 @@ beforeEach(() => {previous = env.ADAPTER_DATA_DIRenv.ADAPTER_DATA_DIR = rootsocket = relaySocket('token')- bindLaunchRequests(socket)+ bindLaunchRequests(socket, { modelTarget: resolveNewAgentModel })frames = []socket.registerLocalClient('local:models', { sendFrame: frame => { frames.push(frame as typeof frames[number]); return true }, sendBinary: () => true })socket.onCreateAgent = vi.fn(async () => ({ ok: false as const, error: 'TEST_STOP' }))@@ -37,7 +37,7 @@ async function ask(extra: Record<string, unknown>) {await vi.waitFor(() => expect(frames.some(f => f.type === 'agent_create_result' && f.payload.requestId === requestId)).toBe(true))return frames.find(f => f.type === 'agent_create_result' && f.payload.requestId === requestId)!.payload}-it('resolves a cross-machine choice on the daemon, including clients without receipts', async () => {+it('resolves a cross-machine choice on the daemon, through the models service, including clients without receipts', async () => {await ask({})expect(socket.onCreateAgent).toHaveBeenCalledWith(expect.objectContaining({ engine: 'codex', grid: target, cwd: '/tmp' }))expect(resolveNewAgentModel).toHaveBeenCalledWith({ model: 'Qwen-35B', grid: 'my-grid' })@@ -49,6 +49,12 @@ it.each([null, new Error('private error')])('refuses resolution failure before aexpect(await ask({})).toMatchObject({ error: 'GRID_UNAVAILABLE' })expect(socket.onCreateAgent).not.toHaveBeenCalled()})+it('refuses the create while models is off, as GRID_UNAVAILABLE', async () => {+ bindLaunchRequests(socket, { modelTarget: null })+ expect(await ask({})).toMatchObject({ error: 'GRID_UNAVAILABLE' })+ expect(await ask({ creationId: 'model-launch-00000003' })).toMatchObject({ state: 'failed', failure: { code: 'GRID_UNAVAILABLE' } })+ expect(socket.onCreateAgent).not.toHaveBeenCalled()+})it('refuses malformed model selections before creating a receipt', async () => {expect(await ask({ gridName: '' })).toMatchObject({ error: 'INVALID_GRID' })expect(socket.onCreateAgent).not.toHaveBeenCalled()diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.tsindex 93f592d4c..2fa2c6e57 100644--- a/cli/src/backendSocket.spec.ts+++ b/cli/src/backendSocket.spec.ts@@ -11,7 +11,7 @@ import { AGENT_OPENED_THROTTLE_MS } from './core/agents/update.js'import { deviceAgentListItem, deviceAgentRow } from './core/agents/list.js'import { grokHistoryPage } from './core/transcripts/history.js'import { bindAgentList, bindAgentUpdate, bindCancelRequest, bindLaunchRequests, bindCloseRequests, bindMessageRequest, bindPurgeRequest, bindQuestionResponse, bindStopRequest, bindTerminalRequests } from './testing/socketCore.js'-import { emptyPorts, MODELS_FALLBACKS, MONITOR_FALLBACKS } from './core/api.js'+import { emptyPorts, MODELS_FALLBACKS, MODELS_OFF, MONITOR_FALLBACKS, type ModelsPort } from './core/api.js'import { createServiceHost, ServiceUnavailableError } from './core/serviceHost.js'import { MODELS_REQUESTS, startModels } from './services/models.js'import { SHELL_REQUESTS, startShell } from './services/shell.js'@@ -41,7 +41,6 @@ import { randomUUID } from 'node:crypto'import { fakeGridAnswers, installFakeGrid, type FakeGrid } from './lib/__fixtures__/fakeGrid.js'import { clearGridMcpUrlCache } from './lib/gridMcpUrl.js'import { LocalModels } from './lib/localModels.js'-import type { GridAttachResult } from './lib/gridAttach.js'import { STRICT_DOWN_TYPES, encryptDownFrame, encryptDownFrameFor, encryptRpcResult } from './lib/e2ee/applicationFrames.js'import { CloseAgentService } from './lib/closeAgentService.js'import { env } from './config/env.js'@@ -567,6 +566,12 @@ const wsMock = vi.hoisted(() => {})vi.mock('ws', () => ({ WebSocket: wsMock.MockWebSocket }))+// Grid's set-up, which the models service asks for before a move onto a grid model: set up already here,+// as on a machine that has used grid before. Never a real install or sign-in from a spec.+vi.mock('./lib/gridAttach.js', async (real) => ({+ ...await real<object>(),+ createGridAccess: () => ({ ensure: async () => ({ status: 'converged', name: null, detail: 'set up already' }) }),+}))// Never the person's real ~/.claude.json or ~/.codex/config.toml: creating an agent records folder trust,// and an unmocked run of these specs used to write test paths into the developer's own config.vi.mock('./lib/claudeTrust.js', () => ({@@ -591,15 +596,17 @@ function sealedDown(socket: BackendSocket, connId: string, type: string, payload/** The models service (services/models.ts) answering the socket's models requests through a service host,* as the daemon runs it: its core reads the grid name and this machine's name off the socket. */function serveModels(socket: BackendSocket, over: Parameters<typeof fakeCore>[0] = {}) {- const host = createServiceHost(emptyPorts(), { log: () => {} })+ const ports = emptyPorts()+ const host = createServiceHost(ports, { log: () => {} })const core = fakeCore({dataDir: process.env.ADAPTER_DATA_DIR,...over,- account: { privateGridName: () => socket.privateGridName(), machineName: () => socket.machineName(), ...over.account },+ account: { privateGridName: async () => socket.gridName(), machineName: () => socket.machineName(), ...over.account },clients: { gridModelsChanged: () => { void socket.pushGridModels() }, ...over.clients },})host.start('models', startModels, core, MODELS_FALLBACKS, MODELS_REQUESTS)socket.serviceRouter = (type, payload, asker, reply) => host.route(type, payload, asker, reply)+ socket.models = () => ports.models ?? MODELS_OFFreturn host}@@ -1012,13 +1019,13 @@ describe('BackendSocket outbound queue', () => {await vi.waitFor(() => {expect(wrapReply).toHaveBeenCalledWith('web-1', 'session_search_result', 's-1', { hits: [], indexed: 3, pending: 0, ready: true, tookMs: 1 })})- expect(routed[0]).toEqual({ type: 'session_search', payload: { requestId: 's-1', query: 'dial scroll', limit: 12 }, asker: { local: false, owner: true } })+ expect(routed[0]).toEqual({ type: 'session_search', payload: { requestId: 's-1', query: 'dial scroll', limit: 12 }, asker: { local: false, owner: true, connection: 'web-1', requestId: 's-1' } })// A device's session may not act as the owner, and the service is told so.role.mockReturnValue('device')ask('session_search', { requestId: 's-2', query: 'dial' })await vi.waitFor(() => expect(routed).toHaveLength(2))- expect(routed[1].asker).toEqual({ local: false, owner: false })+ expect(routed[1].asker).toEqual({ local: false, owner: false, connection: 'web-1', requestId: 's-2' })// A type no service declared is the socket's own: an unknown one is refused at once, in the clear,// as a reply that carries nothing is.@@ -1032,7 +1039,7 @@ describe('BackendSocket outbound queue', () => {socket.registerLocalClient('local:app', { sendFrame: (frame) => { frames.push(frame as Record<string, unknown>); return true }, sendBinary: () => true })socket.handleLocalFrame('local:app', { type: 'session_search', payload: { requestId: 'l-1', query: 'dial' } })await vi.waitFor(() => expect(frames).toContainEqual(expect.objectContaining({ type: 'session_search_result' })))- expect(routed.at(-1)?.asker).toEqual({ local: true, owner: true })+ expect(routed.at(-1)?.asker).toEqual({ local: true, owner: true, connection: 'local:app', requestId: 'l-1' })await socket.stop()})@@ -2966,6 +2973,8 @@ describe('agent_retarget onto a Local model resolves web tools', () => {const seen: Array<{ agentId: string; grid: unknown }> = []const socket = relaySocket('token')socket.onRetargetAgent = async (input) => { seen.push(input); return { ok: true } }+ // Where the move goes is the models service's: it resolves the target from this machine's own grid.+ serveModels(socket)socket.connect()const ws = wsMock.instances[0]ws.open()@@ -3157,20 +3166,15 @@ describe('grid_models_list says whether this machine has a grid CLI', () => {})})-describe('grid is set up on demand — by an act, never by a read', () => {- afterEach(() => { vi.restoreAllMocks() })-- const READY: GridAttachResult = { status: 'signed-in', name: 'kelvin-1a2b3c4d', detail: '', ownGrid: 'created' }-- /** A daemon whose grid set-up is a stub, asked over a local frame. The models picker's Set up and a- * local model's Get and Use are the models service's (services/models.spec.ts); a Grid harness command- * and a move onto a grid model are the socket's. */- function daemon(ready: GridAttachResult = READY) {+describe('a move onto a grid model asks models where it goes', () => {+ /** A daemon whose models is a stub, asked over a local frame. Where the move goes, grid's set-up before+ * it and the prewarm after it are the models service's (services/models.spec.ts). */+ function daemon(moveTarget: ModelsPort['moveTarget'] | null) {const socket = relaySocket('token')- socket.deriveGridName = async () => 'kelvin-1a2b3c4d'- const ensureGrid = vi.fn(async (_request?: { ownGrid?: boolean }) => ready)- socket.ensureGrid = ensureGrid- socket.onRetargetAgent = async () => ({ ok: true })+ const moved = vi.fn()+ if (moveTarget) socket.models = () => ({ annotation: () => null, lists: () => Promise.reject(new Error('no lists')), moveTarget, moved })+ const retargeted = vi.fn(async (_request: { agentId: string; grid: unknown }) => ({ ok: true as const }))+ socket.onRetargetAgent = retargetedconst frames: Array<Record<string, unknown>> = []socket.registerLocalClient('local:grid', { sendFrame: (frame) => { frames.push(frame); return true }, sendBinary: () => true })let asked = 0@@ -3183,31 +3187,103 @@ describe('grid is set up on demand — by an act, never by a read', () => {await vi.waitFor(() => expect(answer()).toBeDefined())return answer()!}- return { socket, ensureGrid, ask, done: async () => { await socket.unregisterLocalClient('local:grid'); await socket.stop() } }+ return { socket, moved, retargeted, ask, done: async () => { await socket.unregisterLocalClient('local:grid'); await socket.stop() } }}-- it('a Grid harness command runs against grid as it stands — its viewer asks on its own, so it never sets grid up', async () => {- const d = daemon()- const run = vi.fn(async () => ({ ok: true, code: 0, stdout: '[]', stderr: '', error: null }))- Object.assign(d.socket as unknown as Record<string, unknown>, { gridFleet: { run, cancel: () => false } })- await d.ask('grid_fleet_run', { args: ['--remote', 'ls', '--json'], timeoutMs: 5_000 })- expect(run).toHaveBeenCalledTimes(1)- expect(d.ensureGrid).not.toHaveBeenCalled()+ const TARGET = { networkId: 'net-1', networkName: 'team-grid-0000aaaa', baseUrl: 'https://fixture.invalid/g/net-1/relay/v1', apiKey: 'fixture-key', model: 'Shared-Model' }++ it('moves onto what models resolved, from the grid the model was picked from, and has models start it', async () => {+ const moveTarget = vi.fn(async () => ({ target: TARGET }))+ const d = daemon(moveTarget)+ expect(await d.ask('agent_retarget', { agentId: 'a1', gridModel: 'Shared-Model', gridName: ' team-grid-0000aaaa ' })).toEqual({ requestId: 'agent_retarget-1', retargeted: true })+ expect(moveTarget).toHaveBeenCalledWith({ gridName: 'team-grid-0000aaaa', model: 'Shared-Model' })+ expect(d.retargeted).toHaveBeenCalledWith({ agentId: 'a1', grid: TARGET })+ expect(d.moved).toHaveBeenCalledWith(TARGET)+ // The account's own grid when the picker names none.+ await d.ask('agent_retarget', { agentId: 'a1', gridModel: 'Own-Model' })+ expect(moveTarget).toHaveBeenLastCalledWith({ gridName: null, model: 'Own-Model' })await d.done()})- it("a move onto a grid model signs grid in first — with the account's own grid only when the model is on it", async () => {- // Refused, so the move stops at the set-up and no grid is read: what is pinned is what was asked.- const d = daemon({ status: 'handoff-failed', name: null, detail: 'no grid on this computer' })+ it('says why it cannot move, in models\' words, and moves nothing', async () => {+ const d = daemon(async () => ({ detail: 'no grid on this computer' }))expect(await d.ask('agent_retarget', { agentId: 'a1', gridModel: 'Shared-Model', gridName: 'team-grid-0000aaaa' })).toMatchObject({ error: 'GRID_UNAVAILABLE', detail: 'no grid on this computer' })- expect(await d.ask('agent_retarget', { agentId: 'a1', gridModel: 'Own-Model' }))- .toMatchObject({ error: 'GRID_UNAVAILABLE' })- expect(d.ensureGrid.mock.calls).toEqual([[{ ownGrid: false }], [{ ownGrid: true }]])+ expect(d.retargeted).not.toHaveBeenCalled()+ expect(d.moved).not.toHaveBeenCalled()+ await d.done()+ })++ it('with models down or off, the move answers GRID_UNAVAILABLE at once', async () => {+ for (const down of [async () => { throw new Error('models is down') }, null]) {+ const d = daemon(down)+ expect(await d.ask('agent_retarget', { agentId: 'a1', gridModel: 'Own-Model' }))+ .toMatchObject({ error: 'GRID_UNAVAILABLE', detail: 'Models are unavailable. Try again.' })+ expect(d.retargeted).not.toHaveBeenCalled()+ await d.done()+ }+ })++ it('a move onto an API, or back onto the own login, asks models nothing', async () => {+ const moveTarget = vi.fn()+ const d = daemon(moveTarget)+ expect(await d.ask('agent_retarget', { agentId: 'a1', clearGrid: true })).toMatchObject({ retargeted: true })+ expect(moveTarget).not.toHaveBeenCalled()+ expect(d.moved).not.toHaveBeenCalled()await d.done()})})+describe('the models lists pushed to the windows', () => {+ it('pushes each window the list in the form it asked for, as models built it; nothing while models is off or failing', async () => {+ const socket = relaySocket('token')+ const rows: Array<Record<string, unknown>> = []+ const plain: Array<Record<string, unknown>> = []+ socket.registerLocalClient('local:rows', { sendFrame: (frame) => { rows.push(frame); return true }, sendBinary: () => true })+ socket.registerLocalClient('local:plain', { sendFrame: (frame) => { plain.push(frame); return true }, sendBinary: () => true })+ // A window that draws row state says so when it asks for the list.+ socket.handleLocalFrame('local:rows', { type: 'grid_models_list', payload: { requestId: 'r1', rowState: true } })+ await vi.waitFor(() => expect(rows.some((frame) => frame.type === 'grid_models_list_result')).toBe(true))+ rows.length = 0+ plain.length = 0++ await socket.pushGridModels()+ socket.models = () => ({ ...MODELS_OFF, lists: async () => ({ plain: { form: 'plain' }, rowState: { form: 'rows' } }) })+ await socket.pushGridModels()+ expect(rows).toEqual([{ type: 'grid_models_changed', payload: { form: 'rows' } }])+ expect(plain).toEqual([{ type: 'grid_models_changed', payload: { form: 'plain' } }])+ socket.models = () => MODELS_OFF+ await socket.pushGridModels()+ expect(rows).toHaveLength(1)+ await socket.unregisterLocalClient('local:rows')+ await socket.unregisterLocalClient('local:plain')+ await socket.stop()+ })++ it('carries models\' note on the grid an agent is on in every frame it builds, and none while models is off', async () => {+ const socket = relaySocket('token')+ const grid = { baseUrl: 'https://fixture.invalid/g/n1/relay/v1', model: 'm' }+ const agent = { agentId: 'a-note', sessionId: 's-note', engine: 'claude', cwd: '/tmp', runtimes: [], registeredAt: 1, active: true, grid } as unknown as RegisteredSession+ expect((await socket.toProject(agent)).grid).toEqual(grid)+ socket.models = () => ({ ...MODELS_OFF, annotation: () => ({ state: 'asleep' as const }) })+ expect((await socket.toProject(agent)).grid).toEqual({ ...grid, state: 'asleep' })+ expect((await socket.toStoppedProject(agent)).grid).toEqual({ ...grid, state: 'asleep' })+ await socket.stop()+ })++ it('answers the grid commands\' handshake itself, so a Grid harness never reads models being down as "update Harness"', async () => {+ const socket = relaySocket('token')+ socket.models = () => MODELS_OFF+ const frames: Array<Record<string, unknown>> = []+ socket.registerLocalClient('local:grid', { sendFrame: (frame) => { frames.push(frame); return true }, sendBinary: () => true })+ socket.handleLocalFrame('local:grid', { type: 'grid_fleet_capabilities', payload: { requestId: 'c1' } })+ await vi.waitFor(() => expect(frames.some((frame) => frame.type === 'grid_fleet_capabilities_result')).toBe(true))+ expect(frames.find((frame) => frame.type === 'grid_fleet_capabilities_result')!.payload)+ .toMatchObject({ requestId: 'c1', protocol: 1, maxTimeoutMs: 30 * 60_000, thinkingControl: true, gridCli: expect.any(String) })+ await socket.unregisterLocalClient('local:grid')+ await socket.stop()+ })+})+describe('the connect burst with no network', () => {afterEach(() => { wsMock.instances.length = 0 })@@ -3220,9 +3296,9 @@ describe('the connect burst with no network', () => {// "offline" the whole time.const socket = relaySocket('token')bindAgentList(socket)- socket.deriveGridName = () => new Promise<null>(() => {}) // a grid read that never lands- // A vendor that never answers, asked of the usage service beside models.- serveModels(socket).serve('usage', (core) => startUsage(core, { read: () => new Promise(() => {}) }), fakeCore(), USAGE_REQUESTS)+ // A grid name that never comes, as a grid read that never lands; and a vendor that never answers, asked+ // of the usage service beside models.+ serveModels(socket, { account: { privateGridName: () => new Promise<null>(() => {}) } }).serve('usage', (core) => startUsage(core, { read: () => new Promise(() => {}) }), fakeCore(), USAGE_REQUESTS)const frames: Array<Record<string, unknown>> = []socket.registerLocalClient('local:burst', { sendFrame: (frame) => { frames.push(frame); return true }, sendBinary: () => true })@@ -3718,7 +3794,7 @@ describe('relay down-frames are default-deny: sealed, or the backend\'s own', ()const serviceRouter = vi.fn(() => true)socket.serviceRouter = serviceRouterawait dispatch(sealedDown(socket, 'web-1', 'dsh_install', { requestId: 'r', id: 'acme/some-dsh' }).frame, 'web-1')- expect(serviceRouter).toHaveBeenCalledWith('dsh_install', expect.objectContaining({ id: 'acme/some-dsh' }), { local: false, owner: expect.any(Boolean) }, expect.any(Function))+ expect(serviceRouter).toHaveBeenCalledWith('dsh_install', expect.objectContaining({ id: 'acme/some-dsh' }), { local: false, owner: expect.any(Boolean), connection: 'web-1', requestId: 'r' }, expect.any(Function))})it('refuses a plaintext RPC even from the backend itself (connId \'\'), which would read the reply', async () => {diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 1404c8b46..c7d339ba9 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -1,6 +1,6 @@import type { PurgeAgentService } from './lib/purgeAgentService.js'import { baseNode } from './harnessd/baseNode.js'-import type { Asker, BackendNotice, GatewayEvents, GatewayPort, PromptScopes, RemoteClient, RemoteRole, RemoteTransport } from './core/api.js'+import type { Asker, BackendNotice, GatewayEvents, GatewayPort, ModelsPort, PromptScopes, RemoteClient, RemoteRole, RemoteTransport } from './core/api.js'import { ServiceUnavailableError } from './core/serviceHost.js'import type { ActivityFrame } from './lib/turnActivity.js'import { MonitorCompletions } from './lib/harnessMonitor.js'@@ -28,16 +28,11 @@ import { registry, projectDisplayName, type RegisteredSession } from './lib/regiimport type { CloseAgentService } from './lib/closeAgentService.js'import { isHiddenBuiltin } from './dsh/builtinIds.js'import { ENGINES, type AgentEngine } from './engines/types.js'-import { gridCliPresence } from './lib/gridExec.js'-import { GridFleetRpc, GRID_FLEET_PROTOCOL, GRID_FLEET_MAX_TIMEOUT_MS, parseGridFleetRequest } from './lib/gridFleetRpc.js'+import { gridCliPresence } from './lib/gridBinary.js'+import { GRID_FLEET_PROTOCOL, GRID_FLEET_MAX_TIMEOUT_MS } from './lib/gridFleetProtocol.js'import { ApiConnectionError, ApiConnections } from './lib/apiConnections.js'import { resolveApiTarget } from './lib/apiModels.js'import { isApiLaunch, parseGridLaunchOverride, type GridLaunchOverride } from './lib/gridLaunch.js'-import { listAllGridModels, onGridModelsChanged, retargetPrewarm } from './lib/gridModels.js'-import { gridModelsPayload } from './lib/gridModelsPayload.js'-import { resolveGridTarget } from './lib/gridTarget.js'-import type { GridAttachResult } from './lib/gridAttach.js'-import { deriveHarnessGridName } from './lib/gridDerive.js'import { supportsFirstPrompt } from './lib/engineLaunch.js'import { probeEngines } from './lib/engineProbe.js'import { harnessDevicesRequest, type HarnessDevicesService } from './lib/harnessDevices.js'@@ -82,13 +77,9 @@ export interface LocalClientSink {export class BackendSocket {harnessDevices: HarnessDevicesService | null = null- private readonly gridFleet = new GridFleetRpc()/** This machine's name as Harness shows it (Machines), from the backend's `machine_meta`. Null* until the first one arrives. */private machineDisplayName: string | null = null- /** A read the window did not ask for changed what a picker would show: tell the window- * (`grid_models_changed`), so its one picture stays current without polling. */- private readonly stopGridModelsPush = onGridModelsChanged(() => { void this.pushGridModels() })private readonly apiConnections = new ApiConnections(env.ADAPTER_DATA_DIR)/** The relay and its E2EE (gateway/gateway.ts): the one way to a remote client. Null in a unit test* that has none, which then serves this computer alone. */@@ -569,71 +560,40 @@ export class BackendSocket {/** The account's private harness grid name, as the backend last reported it. Null until the first* `machine_meta` lands, or when this account has none yet. */private harnessGridName: string | null = null- /** Injected so the derivation (a `grid` spawn) is a seam in tests; see `lib/gridDerive.ts`. */- deriveGridName: () => Promise<string | null> = deriveHarnessGridName- /** Have grid ready for a grid feature the person is using now (`lib/gridAttach.ts`): `grid` installed,- * signed in as this account with its harness token, and — `ownGrid` — the account's own grid there.- * Asked by acts only (here a move onto a grid model, and making a Model Manager; the models service- * asks its own for Set up, Get and Use), never by a read. Set by `cli.ts`; null (tests) reads grid as- * it stands. */- ensureGrid: ((request?: { ownGrid?: boolean }) => Promise<GridAttachResult>) | null = null++ /**+ * What the socket asks of models (core/api.ts `ModelsPort`): an agent's grid note for its frame, the+ * lists it pushes the windows, and where a move onto a grid model goes. Read on each use, since models+ * can be switched off or run in a process of its own; set by core/main.ts. Unset (tests), it reads as+ * models being off.+ */+ models: (() => Pick<ModelsPort, 'annotation' | 'lists' | 'moveTarget' | 'moved'>) | null = null/** Set the account's private grid name from the reconcile that just confirmed it, so the RPCs* answer with it at once rather than waiting for the next `machine_meta` (`lib/gridAttach.ts`). */setHarnessGridName(name: string | null): void { this.harnessGridName = name }- /** Which grid this machine's agents can be pointed at — for `harness status` and the models RPC. */+ /** Which grid this machine's agents can be pointed at — for `harness status`, the models service, and a+ * relaunch that names it. The backend's word only: working one out is the models service's. */gridName(): string | null { return this.harnessGridName }/** This machine's name as the Machines list shows it — what a model it serves is labelled with. */machineName(): string | null { return this.machineDisplayName }- /** The account's private grid, resolved the way the models RPC resolves it — for the models service,- * and for a harness workspace that must be told which grid is "yours" rather than work it out or ask. */- privateGridName(): Promise<string | null> { return this.resolveGridName() }-/** `grid_models_changed` to the windows on this computer: the same payload `grid_models_list` answers,- * built from the pictures as they stand — no read is started to build it, so a push never causes one.- * On a background read's change, and on the models service's word (a local model started or stopped,- * grid set up). */+ * as the models service builds it from its pictures as they stand, each window in the form it asked+ * for. On the models service's word: a read it did not wait for changed the list, a local model started+ * or stopped, grid was set up. */async pushGridModels(): Promise<void> {- if (this.closed || this.localClients.size === 0) return+ if (this.closed || this.localClients.size === 0 || !this.models) returntry {- const gridName = await this.resolveGridName()- const grids = await listAllGridModels(gridName, { refresh: false })- // Each window in the form it asked for — see `gridModelsPayload`.- const plain: Frame = { type: 'grid_models_changed', payload: gridModelsPayload(gridName, grids, false) }- const withRowState: Frame = { type: 'grid_models_changed', payload: gridModelsPayload(gridName, grids, true) }- this.sendLocal((connId) => this.rowStateWindows.has(connId) ? withRowState : plain)+ const { plain, rowState } = await this.models().lists()+ const forPlain: Frame = { type: 'grid_models_changed', payload: plain }+ const forRowState: Frame = { type: 'grid_models_changed', payload: rowState }+ this.sendLocal((connId) => this.rowStateWindows.has(connId) ? forRowState : forPlain)} catch { /* the next ask answers the same thing */ }}- /**- * The account's private grid: the backend's word when it gave one, else what this machine can- * work out for itself (`lib/gridDerive.ts`). A backend that predates `machine_meta.gridName`- * left every picker empty while `grid models` listed the model fine; the derivation is the- * skill's own rule, so the daemon and the agent it opens agree on which grid is "yours".- */- private async resolveGridName(): Promise<string | null> {- return this.harnessGridName ?? await this.deriveGridName()- }-- /**- * Grid set up for an act, or the sentence saying why it could not be: null when it is ready — or- * when this daemon has no [ensureGrid] to ask (tests), which reads grid as it stands.- */- private async gridNotReady(ownGrid: boolean): Promise<string | null> {- if (!this.ensureGrid) return null- const ready = await this.ensureGrid({ ownGrid })- if (ready.status !== 'converged' && ready.status !== 'signed-in') {- return ready.detail || 'Grid could not be set up on this computer. Try again.'- }- if (ownGrid && ready.ownGrid && !['created', 'existed', 'adopted'].includes(ready.ownGrid)) {- return ready.detail || 'Your grid could not be created. Try again.'- }- return null- }-/** Dial the backend, through the gateway: this daemon is signed in. */connect(): void {this.gatewayPort?.connect()@@ -642,7 +602,6 @@ export class BackendSocket {async stop(): Promise<void> {this.closed = truethis.closeAgentService?.dispose()- this.stopGridModelsPush()this.orchestratorService?.stop()this.teamService?.stop()this.teamMailboxService?.stop()@@ -1099,7 +1058,7 @@ export class BackendSocket {// A request a service answers, in its own process or in this one: routed to it, or answered// SERVICE_UNAVAILABLE while it is off. Never waited on in line: the next frame is not held for it.// Who asked is established here, after the gates above, and the service trusts only that.- const asker: Asker = { local, owner }+ const asker: Asker = { local, owner, connection: connId, ...(typeof requestId === 'string' ? { requestId } : {}) }// A window that draws row state asks for the models list with `rowState`, and the list's changes are// pushed to it in that form (`pushGridModels`). Noted here, by connection: the models service answers// the list, and a request reaches it without its connection.@@ -1108,34 +1067,13 @@ export class BackendSocket {try {switch (type) {- // The Model Manager's grid commands stay here while the rest of models answers from its service- // (services/models.ts). A command is a job of the connection that started it, keyed by that- // connection, and a cancel stops only that connection's own (lib/gridFleetRpc.ts); a request the- // service answers knows who asked (`Asker`) but not over which connection. `grid_fleet_capabilities`- // is the commands' handshake (their protocol, longest timeout and thinking control): the Grid- // harness sends `grid_fleet_run` only once it answers protocol 1, and reads anything else as- // "update Harness", so it stays beside them rather than go off with the models service.+ // The Model Manager's grid commands' handshake (their protocol, longest timeout and thinking control),+ // answered here although the commands are the models service's (core/api.ts `MODELS_REQUESTS`): the+ // Grid harness sends `grid_fleet_run` only once it answers protocol 1 and reads anything else as+ // "update Harness", which a models service that is down must not make it say.case 'grid_fleet_capabilities':reply(type, requestId, { protocol: GRID_FLEET_PROTOCOL, gridCli: gridCliPresence(), maxTimeoutMs: GRID_FLEET_MAX_TIMEOUT_MS, thinkingControl: true })return- case 'grid_fleet_run': {- const request = parseGridFleetRequest(payload)- if (!request || typeof requestId !== 'string') { reply(type, requestId, { error: 'INVALID_GRID_COMMAND' }); return }- // Detached: pulls/builds can take minutes. Keep typing, cancellation, and telemetry responsive.- // ⚠️ Run against grid AS IT STANDS — never set up first. A Grid harness session issues these- // on its own the moment its viewer comes up (every open one, on every daemon start), so- // setting grid up here signed a machine in to grid right after a Harness-only sign-in,- // with nobody asking. Grid is set up by the picker's Set up, by making or opening a Model- // Manager, and by that harness's own `harness grid setup`; until then grid answers these in- // its own words.- void this.gridFleet.run(connId, requestId, request)- .then(result => reply(type, requestId, { ...result }))- .catch(() => reply(type, requestId, { ok: false, code: 1, error: 'Grid command failed unexpectedly.' }))- return- }- case 'grid_fleet_cancel':- reply(type, requestId, { cancelled: typeof payload.commandId === 'string' && this.gridFleet.cancel(connId, payload.commandId) })- return// The pairings, which the gateway holds: a window here asks it through the core// (GATEWAY_REQUEST_TYPES), and a remote client's own requests never reach this switch.case 'device_e2ee_pair':@@ -1281,23 +1219,15 @@ export class BackendSocket {}}if (picked && payload.grid === undefined && !clear) {- // The grid the model was picked FROM, when the picker says (a shared grid's section);- // the account's own grid otherwise, as before.- // A move onto a grid model is a grid feature in use: grid is signed in first, if it is not- // yet — and the account's own grid made sure of when that is where the model is.+ // The grid the model was picked FROM, when the picker says (a shared grid's section); the+ // account's own grid otherwise. The models service sets grid up first and resolves the target.const named = typeof payload.gridName === 'string' && payload.gridName.trim() ? payload.gridName.trim() : null- const notReady = await this.gridNotReady(!named || named === this.harnessGridName)- if (notReady) {- reply(type, requestId, { error: 'GRID_UNAVAILABLE', detail: notReady })+ const moving = this.models ? await this.models().moveTarget({ gridName: named, model: picked }).catch(() => null) : null+ if (!moving || !('target' in moving)) {+ reply(type, requestId, { error: 'GRID_UNAVAILABLE', detail: moving?.detail ?? 'Models are unavailable. Try again.' })return}- const pickedGrid = named ?? await this.resolveGridName()- const resolved = await resolveGridTarget(pickedGrid, picked)- if (!resolved) {- reply(type, requestId, { error: 'GRID_UNAVAILABLE', detail: 'Could not read this machine\'s grid endpoint.' })- return- }- payload.grid = resolved+ payload.grid = moving.target}const target = parseGridLaunchOverride(payload.grid)// Exactly one, and `clearGrid` is a separate field rather than `grid: null` on purpose:@@ -1321,11 +1251,10 @@ export class BackendSocket {return}reply(type, requestId, { retargeted: true })- // The agent is on a grid model now and its pane is restarting: start that grid meanwhile if it- // sleeps, so the first message rarely waits on a boot (issue 03). Detached — the move is done- // and answered — and it decides for itself whether a wake is worth it.- // An API has no sleep to wake it from, and is not a grid to look up.- if (override && !isApiLaunch(override)) void retargetPrewarm(override).catch(() => {})+ // The agent is on a grid model now and its pane is restarting: the models service starts that grid+ // meanwhile if it sleeps (issue 03). The move is done and answered. An API has no sleep to wake it+ // from, and is not a grid to look up.+ if (override && !isApiLaunch(override)) this.models?.().moved(override)return}@@ -1433,7 +1362,7 @@ export class BackendSocket {/** A stopped agent's frame: no pane, no terminal, nothing to fork. */async toStoppedProject(s: RegisteredSession): Promise<AgentFrame> {const frame = await agentFrame(s, { selectedModel: s.model, terminalAvailable: false, dsh: this.dshFrameProvider?.(s) ?? null,- tokenUsage: agentTokenUsage.get(s) })+ tokenUsage: agentTokenUsage.get(s), gridAnnotation: this.gridAnnotation })return {...frame,status: 'stopped',@@ -1452,6 +1381,11 @@ export class BackendSocket {terminalAvailable: registry.terminalAvailable(s.agentId),dsh: this.dshFrameProvider?.(s) ?? null,activity: () => this.activityFrameProvider?.(s) ?? null,+ gridAnnotation: this.gridAnnotation,})}++ /** What an agent's frame says of the grid it is on: the models service's word, from memory. */+ private readonly gridAnnotation = (grid: Parameters<ModelsPort['annotation']>[0]): ReturnType<ModelsPort['annotation']> =>+ this.models?.().annotation(grid) ?? null}diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex a5212f2c4..b4a0536ee 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -80,7 +80,8 @@ import { TrustGroupStore } from './lib/e2ee/trustGroup.js'import { confirm as confirmUpdate, fetchManifest, downloadVerified, canary, stage, semverGt, isLocalDevBuild, type UpdateEntry } from './lib/selfUpdate.js'import { managedNodePath } from './lib/nodeRuntime.js'import { updateManagedTui } from './tui/manage.js'-import { ensureHnLauncher, ensureLauncher, ensureManagedGrid, ensureManagedRuntime } from './lib/runtimeInstall.js'+import { ensureHnLauncher, ensureLauncher } from './lib/launchers.js'+import { ensureManagedGrid, ensureManagedRuntime } from './lib/runtimeInstall.js'// Before ANY child is spawned: on Linux an absent locale makes tmux and ps mangle their output,// which silently costs the daemon every pane it would have discovered. See lib/childLocale.ts.ensureUtf8Locale()diff --git a/cli/src/core/AGENTS.md b/cli/src/core/AGENTS.mdindex fb0192061..b832eeb6d 100644--- a/cli/src/core/AGENTS.md+++ b/cli/src/core/AGENTS.md@@ -39,7 +39,8 @@ questions. Everything else is a service ([../services/AGENTS.md](../services/AGEkeeps of the viewers when they run in theirs. `workspacesLink.ts`: what the core tells workspaces intheirs. `teamsLink.ts`: every change to the teams' prompt scopes, kept until their process has it.`monitorLink.ts`: the monitor's port, asked of its process. `storeLink.ts`: what the Store in its- process tells the core. `agentQueries.ts`: what a service in its own process may ask of the agents;+ process tells the core. `modelsLink.ts`: what the core keeps of models in its process for frames and+ keystrokes, and how it asks it the rest. `agentQueries.ts`: what a service in its own process may ask of the agents;`accountQueries.ts`: of the account (a token, and the fleet's lane's sealing), so it holds no credential.`gatewayLink.ts`: the relay and its E2EE in their own process (src/gateway/), as the core sees them:the link's state and the remote clients it reads in line, the frames it hands over in the clear, adiff --git a/cli/src/core/agents/create.spec.ts b/cli/src/core/agents/create.spec.tsindex 3c3561610..3afed8db6 100644--- a/cli/src/core/agents/create.spec.ts+++ b/cli/src/core/agents/create.spec.ts@@ -10,7 +10,7 @@ import { preTrustClaudeProject, preTrustCodexProject } from '../../lib/claudeTruimport { createAndRegisterPane } from '../../lib/createAgentPane.js'import { enginePathOverride } from '../../lib/engineBin.js'import { buildEngineLaunchArgv, permissionModeFlags, refusePermissionFlagIfUnsupported, supportsFirstPrompt } from '../../lib/engineLaunch.js'-import { setUpWithin } from '../../lib/gridAttach.js'+import { setUpWithin } from '../../lib/setUpWithin.js'import { writeGridConfigDir } from '../../lib/gridConfigDir.js'import { buildGridEngineLaunch } from '../../lib/gridLaunch.js'import { installCodexHooks, installOpencodePlugin } from '../../lib/hooks.js'@@ -45,7 +45,7 @@ vi.mock('../../lib/engineLaunch.js', async (real) => ({refusePermissionFlagIfUnsupported: vi.fn(async () => null),supportsFirstPrompt: vi.fn(() => true),}))-vi.mock('../../lib/gridAttach.js', async (real) => ({ ...await real<object>(), setUpWithin: vi.fn(async (run: () => Promise<unknown>) => { await run(); return 'done' }) }))+vi.mock('../../lib/setUpWithin.js', async (real) => ({ ...await real<object>(), setUpWithin: vi.fn(async (run: () => Promise<unknown>) => { await run(); return 'done' }) }))vi.mock('../../lib/gridConfigDir.js', () => ({ writeGridConfigDir: vi.fn(async () => '/config/harness-claude') }))vi.mock('../../lib/gridLaunch.js', async (real) => ({...await real<object>(),diff --git a/cli/src/core/agents/create.ts b/cli/src/core/agents/create.tsindex 43c19a1b7..999d117c9 100644--- a/cli/src/core/agents/create.ts+++ b/cli/src/core/agents/create.ts@@ -10,6 +10,7 @@ import { statSync } from 'node:fs'import { readdir } from 'node:fs/promises'import { join } from 'node:path'import type { BackendSocket } from '../../backendSocket.js'+import type { ModelsPort } from '../api.js'import { MODEL_MANAGER_ID } from '../../dsh/builtinIds.js'import { installedDsh } from '../../dsh/installed.js'import { harnessEnvToClear, type DshAccount } from '../../dsh/launch.js'@@ -27,7 +28,7 @@ import {buildEngineCommandArgv, buildEngineLaunchArgv, namedAgentArgs, permissionModeApproves, permissionModeFlags,refusePermissionFlagIfUnsupported, supportsFirstPrompt,} from '../../lib/engineLaunch.js'-import { setUpWithin } from '../../lib/gridAttach.js'+import { setUpWithin } from '../../lib/setUpWithin.js'import { writeGridConfigDir } from '../../lib/gridConfigDir.js'import { buildGridEngineLaunch, describeGridLaunch, gridConflictingEnvToClear, type GridLaunchMachine, type GridWebSearchStatus } from '../../lib/gridLaunch.js'import { DEFAULT_HARNESS_PERMISSION, freshHarnessEnvironment } from '../../lib/harnessDefaults.js'@@ -69,8 +70,9 @@ export interface CreateAgentDeps {terminalHintMachineName: () => string/** Whether a folder is being purged (PurgeAgentService.blocksFolder). */blocksFolder: (cwd: string) => boolean | undefined- /** Grid set-up, when this daemon can do it (BackendSocket.ensureGrid). */- gridSetup: () => BackendSocket['ensureGrid']+ /** Grid set-up, when this daemon can do it: the models service's (core/api.ts `ModelsPort.ensure`), null+ * while it is off. */+ gridSetup: () => ModelsPort['ensure'] | nullprivateGridName: () => Promise<string | null>}diff --git a/cli/src/core/agents/launches.spec.ts b/cli/src/core/agents/launches.spec.tsindex 50da3c327..a65379c68 100644--- a/cli/src/core/agents/launches.spec.ts+++ b/cli/src/core/agents/launches.spec.ts@@ -10,7 +10,7 @@ import type { AgentFrame } from '../../lib/agentFrame.js'import { claudeTrusts, codexTrusts, preTrustClaudeProject, preTrustCodexProject } from '../../lib/claudeTrust.js'import { MAX_FIRST_PROMPT_CHARS, permissionModeApproves, permissionModeFlags, supportsFirstPrompt, supportsNamedAgent } from '../../lib/engineLaunch.js'import { parseGridLaunchOverride } from '../../lib/gridLaunch.js'-import { parseNewAgentModel, resolveNewAgentModel } from '../../lib/newAgentModel.js'+import { parseNewAgentModel } from '../../lib/newAgentModel.js'import { parseProjectFolder, prepareProjectFolder, ProjectFolderError } from '../../lib/projectFolder.js'import type { RegisteredSession } from '../../lib/registry.js'import { createLaunchRequests, type CreateAgent, type ForkAgent, type LaunchRequestDeps, type RestartAgent, type ResumeAgent } from './launches.js'@@ -28,7 +28,7 @@ vi.mock('../../lib/claudeTrust.js', async (real) => ({}))vi.mock('../../engines/opencode/version.js', async (real) => ({ ...await real<object>(), opencodeMajorVersion: vi.fn(() => 1) }))vi.mock('../../lib/newAgentModel.js', async (real) => ({- ...await real<object>(), parseNewAgentModel: vi.fn(() => ({ state: 'absent' })), resolveNewAgentModel: vi.fn(async () => ({ networkId: 'resolved' })),+ ...await real<object>(), parseNewAgentModel: vi.fn(() => ({ state: 'absent' })),}))vi.mock('../../lib/gridLaunch.js', async (real) => ({ ...await real<object>(), parseGridLaunchOverride: vi.fn(() => ({ state: 'absent' })) }))vi.mock('../../dsh/installed.js', async (real) => ({ ...await real<object>(), installedDsh: vi.fn(() => undefined) }))@@ -44,6 +44,8 @@ vi.mock('../../lib/projectFolder.js', async (real) => {})const CREATION = 'creation-0123456789abcdef'+/** Where the models service resolves a new agent's grid model (core/api.ts `ModelsPort.launchTarget`). */+const resolveNewAgentModel = vi.fn<LaunchRequestDeps['modelTarget']>()const session = (agentId = 'a1', over: Partial<RegisteredSession> = {}) => ({ agentId, sessionId: `${agentId}-session`, engine: 'claude', ...over }) as RegisteredSessionconst frameOf = (s: RegisteredSession) => ({ id: s.agentId }) as unknown as AgentFrameconst settle = () => new Promise((resolve) => setTimeout(resolve, 0))@@ -71,6 +73,7 @@ function setup(over: Partial<LaunchRequestDeps> = {}, launches: { create?: Creatreceipts: new AgentCreationReceipts(join(dir, `receipts-${++stores}`)),createAgent: () => create, forkAgent: () => fork, resumeAgent: () => resume, restartAgent: () => restart,byAgent: (id) => known.get(id), toProject: vi.fn(async (s: RegisteredSession) => frameOf(s)),+ modelTarget: resolveNewAgentModel,...over,}const requests = createLaunchRequests(deps)@@ -214,7 +217,7 @@ describe('agent_create, launched', () => {it('points a model picked by name at its grid as read now, or says the model is unavailable', async () => {const { ask, create } = setup()vi.mocked(parseNewAgentModel).mockReturnValue({ state: 'ok', selection: { model: 'm' } } as never)- vi.mocked(resolveNewAgentModel).mockResolvedValueOnce({ networkId: 'resolved' } as never).mockResolvedValueOnce(null).mockRejectedValueOnce(new Error('offline'))+ resolveNewAgentModel.mockResolvedValueOnce({ networkId: 'resolved' } as never).mockResolvedValueOnce(null).mockRejectedValueOnce(new Error('offline'))await ask({ engine: 'claude', cwd: '/w' })expect(vi.mocked(create!).mock.calls[0][0].grid).toEqual({ networkId: 'resolved' })const unavailable = { error: 'GRID_UNAVAILABLE', detail: 'The selected model is unavailable. Choose another model or refresh the list.' }@@ -365,7 +368,7 @@ describe('agent_create with a receipt', () => {it('resolves a model picked by name inside the receipt, and records it unavailable when it cannot be read', async () => {const { ask, create, replies } = setup()vi.mocked(parseNewAgentModel).mockReturnValue({ state: 'ok', selection: { model: 'm' } } as never)- vi.mocked(resolveNewAgentModel).mockResolvedValueOnce({ networkId: 'resolved' } as never).mockRejectedValueOnce(new Error('offline'))+ resolveNewAgentModel.mockResolvedValueOnce({ networkId: 'resolved' } as never).mockRejectedValueOnce(new Error('offline'))await ask({ engine: 'claude', cwd: '/w', creationId: CREATION })await ask({ engine: 'claude', cwd: '/w', creationId: `${CREATION}-2` })await vi.waitFor(() => expect(replies).toHaveLength(2))diff --git a/cli/src/core/agents/launches.ts b/cli/src/core/agents/launches.tsindex ac1e228ce..a688928e3 100644--- a/cli/src/core/agents/launches.ts+++ b/cli/src/core/agents/launches.ts@@ -24,8 +24,8 @@ import {AGENT_NAME_RE, FirstPromptUnsupportedError, MAX_FIRST_PROMPT_CHARS, NamedAgentUnsupportedError, permissionModeApproves,permissionModeFlags, supportsFirstPrompt, supportsNamedAgent,} from '../../lib/engineLaunch.js'-import { parseGridLaunchOverride } from '../../lib/gridLaunch.js'-import { parseNewAgentModel, resolveNewAgentModel } from '../../lib/newAgentModel.js'+import { parseGridLaunchOverride, type GridLaunchOverride } from '../../lib/gridLaunch.js'+import { parseNewAgentModel, type NewAgentModel } from '../../lib/newAgentModel.js'import { parseProjectFolder, prepareProjectFolder, projectsRoot, ProjectFolderError } from '../../lib/projectFolder.js'import type { RegisteredSession } from '../../lib/registry.js'@@ -56,11 +56,15 @@ export interface LaunchRequestDeps {byAgent: (agentId: string) => RegisteredSession | undefined/** An agent's frame, as the socket builds it for every reply. */toProject: (s: RegisteredSession) => Promise<AgentFrame>+ /** Where a new agent on a grid model sends its inference: the models service's to resolve, on this+ * machine (core/api.ts `ModelsPort.launchTarget`). Null, or a rejection while models is down, refuses+ * the create with GRID_UNAVAILABLE rather than start it anywhere else. */+ modelTarget: (selection: NewAgentModel) => Promise<GridLaunchOverride | null>}type Reply = (result: Record<string, unknown>) => void-export function createLaunchRequests({ receipts, createAgent, forkAgent, resumeAgent, restartAgent, byAgent, toProject }: LaunchRequestDeps) {+export function createLaunchRequests({ receipts, createAgent, forkAgent, resumeAgent, restartAgent, byAgent, toProject, modelTarget }: LaunchRequestDeps) {/** Recover by stable runtime identity; a deleted agent must never become a fresh launch. */const creationStatusPayload = async (status: AgentCreationStatus): Promise<Record<string, unknown>> => {if (status.state === 'created') {@@ -240,7 +244,7 @@ export function createLaunchRequests({ receipts, createAgent, forkAgent, resumeAtry {void receipts.run(creationId, creationFingerprint(projectFolder ? { ...fingerprintInput, projectFolder } : fingerprintInput), async () => {if (model.state === 'ok') {- const target = await resolveNewAgentModel(model.selection).catch(() => null)+ const target = await modelTarget(model.selection).catch(() => null)if (!target) return { state: 'failed', error: 'GRID_UNAVAILABLE', detail: 'The selected model is unavailable. Choose another model or refresh the list.' }input.grid = target}@@ -302,7 +306,7 @@ export function createLaunchRequests({ receipts, createAgent, forkAgent, resumeA}// Clients predating receipts retain their existing response shape.if (model.state === 'ok') {- const target = await resolveNewAgentModel(model.selection).catch(() => null)+ const target = await modelTarget(model.selection).catch(() => null)if (!target) { reply({ error: 'GRID_UNAVAILABLE', detail: 'The selected model is unavailable. Choose another model or refresh the list.' }); return }input.grid = target}diff --git a/cli/src/core/api.spec.ts b/cli/src/core/api.spec.tsindex 45b682b8e..6b441b007 100644--- a/cli/src/core/api.spec.ts+++ b/cli/src/core/api.spec.ts@@ -1,6 +1,6 @@import { describe, expect, it, vi } from 'vitest'import { projectDisplayName, type RegisteredSession } from '../lib/registry.js'-import { createCoreApi, emptyPorts, FLEET_FALLBACKS, LANE_OFF, MONITOR_OFF, resolveAgent, TEAMS_FALLBACKS, type CoreApiDeps } from './api.js'+import { createCoreApi, emptyPorts, FLEET_FALLBACKS, LANE_OFF, LONG_ANSWERS, MODELS_OFF, MODELS_REQUESTS, MONITOR_OFF, resolveAgent, TEAMS_FALLBACKS, type CoreApiDeps } from './api.js'import { FAIL } from './serviceHost.js'const row = (agentId: string) => ({ agentId, sessionId: `s-${agentId}`, engine: 'claude', cwd: '/work/app' }) as RegisteredSession@@ -115,6 +115,26 @@ describe('the core API services stand on', () => {expect(emptyPorts()).not.toBe(emptyPorts())})+ it('answers models\' fallbacks while it is off: no set-up and no target, no note and no prewarm, no name of its own', async () => {+ const grid = { baseUrl: 'https://fixture.invalid/g/n1/relay/v1', model: 'm' }+ const launch = { networkId: 'n1', networkName: 'mine', baseUrl: grid.baseUrl, apiKey: 'k' }+ await expect(MODELS_OFF.ensure()).rejects.toThrow('the models service is unavailable')+ 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')+ expect(await MODELS_OFF.privateGridName()).toBeNull()+ expect(MODELS_OFF.annotation(grid)).toBeNull()+ expect([MODELS_OFF.prewarm(grid), MODELS_OFF.moved(launch), MODELS_OFF.machines(null, 'here'), MODELS_OFF.signedOut()]).toEqual([undefined, undefined, undefined, undefined])+ })++ it('waits longer only for answers that take longer, each a request or port call of its service', () => {+ for (const type of Object.keys(LONG_ANSWERS.models!)) {+ expect([...MODELS_REQUESTS, 'ensure', 'moveTarget', 'launchTarget', 'privateGridName', 'lists']).toContain(type)+ }+ // A grid command may run half an hour, and is waited for longer than that.+ expect(LONG_ANSWERS.models!.grid_fleet_run).toBeGreaterThan(30 * 60_000)+ })+it('answers the monitor\'s fallbacks while it is off: no readings, nothing measured to forget', async () => {await expect(MONITOR_OFF.resources()).rejects.toThrow('the monitor service is unavailable')expect(await MONITOR_OFF.storage([], true)).toEqual(new Map())diff --git a/cli/src/core/api.ts b/cli/src/core/api.tsindex 1546ca4e2..2f8698779 100644--- a/cli/src/core/api.ts+++ b/cli/src/core/api.ts@@ -18,7 +18,10 @@ import type { AgentDshContext } from '../lib/agentFrame.js'import type { GridAccess } from '../lib/gridAttach.js'import type { createHarnessResourcesReader } from '../lib/harnessResources.js'import type { createHarnessStorageReader } from '../lib/harnessTelemetry.js'-import type { AgentGridTarget } from '../lib/gridModels.js'+import type { AgentGridTarget, GridAnnotation } from '../lib/gridAnnotation.js'+import { GRID_FLEET_MAX_TIMEOUT_MS } from '../lib/gridFleetProtocol.js'+import type { GridLaunchOverride } from '../lib/gridLaunch.js'+import type { NewAgentModel } from '../lib/newAgentModel.js'import type { LiveEvent } from '../lib/normalize.js'import { projectDisplayName, type registry, type RegisteredSession } from '../lib/registry.js'import type { RuntimeModelOption } from '../lib/runtimeProfile.js'@@ -115,8 +118,9 @@ export interface CoreApi {/** The fleet's lane to the owner's other machines, sealed by the gateway with this machine's E2EE* identity, which no service holds (`LaneSeal`). */lane: LaneSeal- /** The account's private grid: the backend's word when it gave one, else what this machine works- * out (`lib/gridDerive.ts`); null when it has none. */+ /** The account's private grid as the backend named it (`machine_meta`), or as grid's set-up just+ * confirmed it; null before either. Working it out when neither has said is the models service's+ * (`lib/gridDerive.ts`). */privateGridName(): Promise<string | null>/** This machine's name as the account's Machines list shows it (the backend's `machine_meta`); null* until the first one lands. */@@ -150,6 +154,11 @@ export interface Asker {/** Whether it may act as this machine's owner: a local process, or the owner's paired app over the* relay. A device or an observer may not. */owner: boolean+ /** The connection it came over, as the core names it, and the id it asked under: what a service keys+ * work by that belongs to one connection's request (the Model Manager's grid commands, which a cancel+ * on the same connection stops). Absent when the core itself asks. */+ connection?: string+ requestId?: string}/** A request a service answers for the apps: the reply, or a promise of it. A throw or a rejection is@@ -179,19 +188,46 @@ export const PROJECTS_REQUESTS = ['git_pull_request', 'git_project_info', 'proje/*** Models (services/models.ts).*- * The Model Manager's grid commands, `grid_fleet_run` and `grid_fleet_cancel`, are still the socket's:- * a command is a job of the connection that started it, and a cancel stops only that connection's job- * (`lib/gridFleetRpc.ts`), while a request answered by a service knows who asked but not over which- * connection. Their handshake, `grid_fleet_capabilities`, stays beside them: the Grid harness runs a- * command only after it, and reads an answer without its protocol as "update Harness".+ * The Model Manager's grid commands, `grid_fleet_run` and `grid_fleet_cancel`, are among them: a command+ * is a job of the connection that started it, and a cancel stops only that connection's own+ * (`lib/gridFleetRpc.ts`), keyed by the connection and request id the core gives every request+ * (`Asker`). Their handshake, `grid_fleet_capabilities`, is still the socket's: the Grid harness runs a+ * command only after it and reads an answer without its protocol as "update Harness", which a models+ * service that is down must not make it say.* The saved APIs and the Codex profiles came out of the socket's switch (launchTargetRequests).*/export const MODELS_REQUESTS = ['grid_models_list', 'models_list','grid_fleet_models_list', 'grid_fleet_model_download', 'grid_fleet_model_start', 'grid_fleet_model_stop',+ 'grid_fleet_run', 'grid_fleet_cancel','api_connections', 'codex_profiles_list', 'codex_profile_link',] as const+const MINUTE = 60_000++/**+ * How long the core waits on a service in a process of its own for these answers before it answers+ * SERVICE_UNAVAILABLE, where the half minute it gives any other would cut short what they do+ * (core/serviceLinks.ts). By service, then by request or port call. A wait that runs out answers the+ * asker; the work itself goes on in the service's process.+ *+ * - A grid command runs as long as its caller asked, up to half an hour (`GRID_FLEET_MAX_TIMEOUT_MS`).+ * - Grid's set-up installs `grid` on first use (its installer is given ten minutes, `gridInstall.ts`),+ * hands it this machine's sign-in and makes the account's grid: a Set up, a Get, a Use, `ensure` and+ * a move onto a grid model (`moveTarget`) each wait for it.+ * - A launch target, the private grid's name and the lists each run a few `grid` calls of up to 30 s.+ * - The Store's install and update set up a harness's toolchain: minutes.+ */+export const LONG_ANSWERS: Readonly<Record<string, Readonly<Record<string, number>>>> = {+ models: {+ grid_fleet_run: GRID_FLEET_MAX_TIMEOUT_MS + MINUTE,+ grid_fleet_models_list: 15 * MINUTE, grid_fleet_model_download: 15 * MINUTE, grid_fleet_model_start: 15 * MINUTE,+ ensure: 15 * MINUTE, moveTarget: 15 * MINUTE,+ launchTarget: 3 * MINUTE, privateGridName: 2 * MINUTE, lists: 2 * MINUTE,+ },+ store: { dsh_install: 30 * MINUTE, dsh_update: 30 * MINUTE },+}+/** The core's calls into session search: index a session at its turn boundaries, forget a purged* conversation, the title it indexed for one being adopted, and stopping its sweeps. The apps' own* requests (`session_search`, `session_tail`) are its `ServiceRequests`, not the core's calls. */@@ -223,23 +259,61 @@ export const VIEWERS_FALLBACKS: PortFallbacks<ViewersPort> = {attach: undefined, detach: undefined, frameContext: null, forwardingUrl: null, stop: later(undefined),}-/** The core's calls into models (grid): have grid ready, whether it is set up, and the two things- * the core tells it — someone is typing to an agent on a grid, and the sign-in ended. */+/**+ * The core's calls into models (grid). Everything an agent's launch, its frame or a keystroke to it needs+ * of grid, so the core never loads grid's code (docs/design/2026-10-06-core-boundary-next.md, step 7):+ * in the core's process the service answers itself; in its own, core/modelsLink.ts does, from what the+ * service last told it for what a frame or a keystroke reads, and by asking it for the rest.+ */export interface ModelsPort {/** Have grid ready for what the caller is about to do; resolves with what happened, never rejects. */ensure: GridAccess['ensure']- /** Offline: is there a `grid` here holding a sign-in? */- setUp(): boolean- /** Start the agent's sleeping grid while someone types to it. */+ /** What an agent's frame says of the grid it is on: from memory, so a frame costs no I/O. */+ annotation(grid: AgentGridTarget): GridAnnotation | null+ /** Someone is typing to an agent on `grid`: start it while they type, if it sleeps. */prewarm(grid: AgentGridTarget): void+ /** Where a new agent on `selection` sends its inference, resolved from this machine's own signed-in+ * grid; null when that grid does not serve the model now. */+ launchTarget(selection: NewAgentModel): Promise<GridLaunchOverride | null>+ /** Where a running agent moved onto `model` sends its inference (`agent_retarget`): grid set up first,+ * on `gridName` or the account's own; the sentence a person reads when it cannot be. */+ moveTarget(request: { gridName: string | null; model: string }): Promise<{ target: GridLaunchOverride } | { detail: string }>+ /** An agent was just moved onto a grid model: start that grid while its pane restarts, if it sleeps. */+ moved(launch: GridLaunchOverride): void+ /** The account's private grid: the backend's word, else what this machine works out; null for none. */+ privateGridName(): Promise<string | null>+ /** What `grid_models_changed` tells the windows: the list as a window that draws row state reads it,+ * and as one that does not. */+ lists(): Promise<{ plain: Record<string, unknown>; rowState: Record<string, unknown> }>+ /** The machine list the core just read (null when signed out): which of the account's other computers+ * seem offline, for the models only they serve. */+ machines(body: Record<string, unknown> | null, computerId: string): void/** The sign-in ended: drop what lives exactly as long as it. */signedOut(): void}-/** What the core gets when models fails: a grid request answered with an error, grid read as not- * set up, and no prewarm. */+/**+ * What the core gets when models fails: grid set-up and every target answered with an error (a create on+ * a grid model answers GRID_UNAVAILABLE), frames with no note and no prewarm, the private grid as the+ * backend said it or none, and no push of the lists.+ */export const MODELS_FALLBACKS: PortFallbacks<ModelsPort> = {- ensure: later(FAIL), setUp: false, prewarm: undefined, signedOut: undefined,+ ensure: later(FAIL), annotation: null, prewarm: undefined, launchTarget: later(FAIL), moveTarget: later(FAIL), moved: undefined,+ 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. */+export const MODELS_OFF: ModelsPort = {+ ensure: () => Promise.reject(new ServiceUnavailableError('models')),+ annotation: () => null,+ prewarm: () => {},+ launchTarget: () => Promise.reject(new ServiceUnavailableError('models')),+ moveTarget: () => Promise.reject(new ServiceUnavailableError('models')),+ moved: () => {},+ privateGridName: async () => null,+ lists: () => Promise.reject(new ServiceUnavailableError('models')),+ machines: () => {},+ signedOut: () => {},}/** The core's calls into the machine monitor: the readings `agents_list` adds to its rows when a windowdiff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex c7700e9ae..3245b0640 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -43,8 +43,6 @@ import { removePidFileIf, onError } from '../lib/daemonLaunch.js'import { describeSpawnLockOwner, withSpawnLock } from '../lib/daemonSpawnLock.js'import { ensureTmuxOnPath } from '../lib/tmuxOnPath.js'import { AUTH_DIR, AuthSessionError, AuthSessionManager, clearAuthSession, ensureSignInEpoch, readAuthSession, signInOf, type AuthSession } from '../lib/authSession.js'-import { observeMachineList } from '../lib/gridModels.js'-import { managedGridPath } from '../lib/gridExec.js'import { ENGINES, enginePathOverride } from '../lib/engineBin.js'import { isTerminalEngine } from '../engines/types.js'import { engineInstallRecipe } from '../lib/engineInstall.js'@@ -78,6 +76,7 @@ import { ApiConnections } from '../lib/apiConnections.js'import { rememberSavedApis } from '../lib/apiModels.js'import { prepareApiInstructions } from '../lib/apiInstructions.js'import type { AgentDshContext } from '../lib/agentFrame.js'+import type { AgentGridTarget, GridAnnotation } from '../lib/gridAnnotation.js'import { clearPaneRemainOnExit, lookupPaneEngineProcess, resolvePaneEngineProcess, tmuxPaneInfo, tmuxPaneState } from '../lib/tmux.js'import { ALL_TERMINAL_BACKENDS } from '../config/terminalConfig.js'import { TerminalBackendCoordinator } from '../lib/terminalBackendCoordinator.js'@@ -129,7 +128,7 @@ import { createAgentUpdate } from './agents/update.js'import { createEngineHooks, installEngineHooks } from './engines/hooks.js'import { createCursorTaskHooks } from './engines/cursorTasks.js'import { databaseHistory } from './transcripts/databaseHistory.js'-import { createCoreApi, emptyPorts, FLEET_FALLBACKS, MODELS_FALLBACKS, MODELS_REQUESTS, MONITOR_FALLBACKS, MONITOR_OFF, MONITOR_REQUESTS, PROJECTS_REQUESTS, SEARCH_FALLBACKS, SEARCH_REQUESTS, STORE_REQUESTS, TEAMS_FALLBACKS, USAGE_REQUESTS, VIEWERS_FALLBACKS, WORKSPACES_FALLBACKS, type GatewayAccount, type GatewayOps, type GatewayStatus, type TeamsPort } from './api.js'+import { createCoreApi, emptyPorts, FLEET_FALLBACKS, LONG_ANSWERS, MODELS_FALLBACKS, MODELS_OFF, MODELS_REQUESTS, MONITOR_FALLBACKS, MONITOR_OFF, MONITOR_REQUESTS, PROJECTS_REQUESTS, SEARCH_FALLBACKS, SEARCH_REQUESTS, STORE_REQUESTS, TEAMS_FALLBACKS, USAGE_REQUESTS, VIEWERS_FALLBACKS, WORKSPACES_FALLBACKS, type GatewayAccount, type GatewayOps, type GatewayStatus, type TeamsPort } from './api.js'import { createServiceHost, testFaults } from './serviceHost.js'import { startStalls } from './stall.js'import { createServiceLinks, type ServiceLinks } from './serviceLinks.js'@@ -137,10 +136,10 @@ import { createViewersLink } from './viewersLink.js'import { createWorkspacesLink } from './workspacesLink.js'import { createMonitorLink } from './monitorLink.js'import { createStoreLink } from './storeLink.js'+import { createModelsLink } from './modelsLink.js'import { answerAgentQuery } from './agentQueries.js'import { KNOWN_SERVICES, servicesTheMasterRuns } from '../harnessd/services.js'import { createTeamsLink } from './teamsLink.js'-import { startModels } from '../services/models.js'import { startFleet } from '../services/fleet.js'import { CORE_EXIT_STOP, CORE_EXIT_UPDATE, PROBE_COMMAND, PROBE_TIMEOUT_MS } from '../harnessd/protocol.js'import { localSocketPath, refuseServedDataFolder, type LocalSocketServer } from '../lib/localSocket.js'@@ -164,7 +163,6 @@ import { isLoopbackRequest, loopbackHosts } from '../lib/loopbackRequest.js'import { startSelfUpdater, restore as restoreUpdate, DOWNLOAD_LIMITS, type Poller } from '../lib/selfUpdate.js'import { managedNodePath } from '../lib/nodeRuntime.js'import { startTuiUpdater } from '../tui/update.js'-import { ensureManagedGrid, startGridPinRecheck } from '../lib/runtimeInstall.js'import { type ActivityFrame } from '../lib/turnActivity.js'import { CursorTranscriptDiscovery } from '../engines/cursor/discovery.js'import { cursorDataDir } from '../engines/cursor/home.js'@@ -360,6 +358,9 @@ let activityFrameContextRef: ((s: RegisteredSession) => ActivityFrame | null) |let dshFrameContextRef: ((s: RegisteredSession) => AgentDshContext | null) | null = null+/** Set by runForeground once models can be asked: what an agent's frame says of its grid. */+let gridAnnotationRef: ((grid: AgentGridTarget) => GridAnnotation | null) | null = null+function projectFrame(s: RegisteredSession, selectedModel: string | null): Promise<AgentFrame> {return agentFrame(s, {tokenUsage: agentTokenUsage.get(s),@@ -367,6 +368,7 @@ function projectFrame(s: RegisteredSession, selectedModel: string | null): PromiterminalAvailable: registry.terminalAvailable(s.agentId),dsh: dshFrameContextRef?.(s) ?? null,activity: () => activityFrameContextRef?.(s) ?? null,+ gridAnnotation: (grid) => gridAnnotationRef?.(grid) ?? null,})}@@ -483,20 +485,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {catch { console.warn('[apis] Tool instructions could not be added. Saved connections remain available through harness api.') }}- // A managed grid already here follows its pin on EVERY daemon start — this one, and the restart a- // self-update ends in — not only on `--repair`: the pin is expected to move, and a machine installed- // last month has to notice. A machine with none gets none from a start: grid is an add-on, installed- // the first time a grid feature is used (`ensureGrid`, below). Not awaited: a download must never- // hold the control port back, and every grid call resolves the binary afresh (`gridBinaryPath`), so- // whatever lands is picked up as it lands. Best-effort by construction — it returns, never throws.- const followGridPin = (): Promise<unknown> => managedGridPath()- ? ensureManagedGrid((m) => console.log(`[grid-runtime] ${m}`))- : Promise.resolve(null)- void followGridPin()- // …and keeps following it while this daemon runs: a pin moved after the start reaches it within ten- // minutes rather than at the next restart (`startGridPinRecheck`).- startGridPinRecheck({ ensure: followGridPin })-registry.load()// 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@@ -648,7 +636,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {},gridNamed: (name) => backendRef?.setHarnessGridName(name),gridModelsChanged: () => { void backendRef?.pushGridModels() },- privateGridName: async () => (await backendRef?.privateGridName()) ?? null,+ privateGridName: async () => backendRef?.gridName() ?? null,machineName: () => backendRef?.machineName() ?? null,dshInstallStatus: (status) => backendRef?.send({ type: 'dsh_install_status', payload: status }),// The backend mints and remembers the account's grid name; this CLI holds neither the account's@@ -696,6 +684,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {const serviceHost = createServiceHost(ports, { faults: testFaults(process.env.HARNESSD_TEST_FAULTS) })// The DSH companions: each harness agent's viewer and verdict watch (services/viewers.ts), started below.dshFrameContextRef = (s) => ports.viewers?.frameContext(s) ?? null+ // Models (services/models.ts), started below: what an agent's frame says of its grid, from memory.+ gridAnnotationRef = (grid) => (ports.models ?? MODELS_OFF).annotation(grid)const attachDsh = (s: RegisteredSession): void => ports.viewers?.attach(s)const detachDsh = (agentId: string): void => ports.viewers?.detach(agentId)@@ -792,14 +782,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {// 2026-10-06), while cli.js, which the core runs, carries them anyway.ensureBundledCoreHarnesses()- // Models: grid access, the model pictures on agents' frames, the keystroke prewarm, and the models- // requests the apps send (services/models.ts).- serviceHost.start('models', startModels, coreApi, MODELS_FALLBACKS, MODELS_REQUESTS)- const models = ports.models- backend.ensureGrid = models ? (request) => models.ensure(request) : null- // Models switched off: the socket reads grid as it stands, as it does with no models at all.- serviceHost.onOff('models', () => { backend.ensureGrid = null })-/*** Is ANY device surface watching this machine?*@@ -1089,7 +1071,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {backend.handoffRequestProvider = createHandoffRequest({ prepare: (req) => prepareAgentHandoff(handoffDeps, req) })// The requests each service that can run in its own process answers, as core/api.ts declares them.- const requestsOf: Record<string, readonly string[]> = { search: SEARCH_REQUESTS, store: STORE_REQUESTS, usage: USAGE_REQUESTS, monitor: MONITOR_REQUESTS, projects: PROJECTS_REQUESTS }+ const requestsOf: Record<string, readonly string[]> = { search: SEARCH_REQUESTS, store: STORE_REQUESTS, usage: USAGE_REQUESTS, monitor: MONITOR_REQUESTS, projects: PROJECTS_REQUESTS, models: MODELS_REQUESTS }// What the core keeps of the viewers in their own process, for the frames it builds (core/viewersLink.ts).const viewersLink = createViewersLink(coreApi, (frame, opts) => serviceLinks.notify('viewers', frame, opts))// How the core tells workspaces in their own process what to do, and answers them (core/workspacesLink.ts).@@ -1098,12 +1080,16 @@ async function runForeground(session: AuthSession | null): Promise<void> {const teamsLink = createTeamsLink({ notify: (frame) => serviceLinks.notify('teams', frame) })// What the Store in its own process tells the core: an install's progress, and that what is installed changed (core/storeLink.ts).const storeLink = createStoreLink(coreApi, invalidateInstalledDsh)+ // What the core keeps of models in its own process for frames and keystrokes, and how it asks it the rest (core/modelsLink.ts).+ const modelsLink = createModelsLink(coreApi, (type, payload) => serviceLinks.call('models', type, payload), (frame) => serviceLinks.notify('models', frame))const serviceLinks = createServiceLinks({token: serviceToken,owned: Object.fromEntries([...outOfProcess].map((name) => [name, requestsOf[name] ?? []])),+ waits: LONG_ANSWERS,answer: (service, query, payload) => service === 'viewers' ? viewersLink.answer(query, payload): service === 'workspaces' ? workspacesLink.answer(query, payload): service === 'store' ? storeLink.answer(query, payload)+ : service === 'models' ? modelsLink.answer(query, payload): service === 'teams' ? teamsLink.answer(query, payload): service === 'gateway' && gatewayLink ? gatewayLink.answer(query, payload) : answerAgentQuery(coreApi, query),// The gateway's own traffic: its remote clients and what they sent, and its comings and goings.@@ -1153,6 +1139,13 @@ async function runForeground(session: AuthSession | null): Promise<void> {// media file from an agent's project (services/projects.ts): in this process, or in the edge host.if (!outOfProcess.has('projects')) serviceHost.serve('projects', inline!.startProjects, coreApi, PROJECTS_REQUESTS)serviceHost.serve('shell', startShell, coreApi, SHELL_REQUESTS)+ // Models: grid access and its pin, the model pictures on agents' frames, the keystroke prewarm, where an+ // agent on a grid model sends its inference, and the models requests the apps send (services/models.ts):+ // in this process, or in its own (services/modelsProcess.ts), reached through core/modelsLink.ts.+ if (outOfProcess.has('models')) ports.models = modelsLink.port+ else serviceHost.start('models', inline!.startModels, coreApi, MODELS_FALLBACKS, MODELS_REQUESTS)+ // What the socket asks of models: read on each use, so a models service switched off answers its fallbacks.+ backend.models = () => ports.models ?? MODELS_OFFconst runtimeController = new RuntimeProfileController({manager: runtimeProfiles,@@ -1445,7 +1438,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {)// Which of the owner's other computers have been reading offline — a label on the models only they// serve on a sleeping grid, never a removal (grid-reads-without-waking issue 03).- machineListCache.listen((body) => observeMachineList(body, computerId()))+ machineListCache.listen((body) => ports.models?.machines(body, computerId()))// The trust group swaps rosters only with the members the backend last said were online (gateway/start.ts).machineListCache.listen(() => {const { machines, source } = machineListCache.list()@@ -2221,8 +2214,12 @@ async function runForeground(session: AuthSession | null): Promise<void> {gridLaunchMachine,terminalHintMachineName,blocksFolder: (cwd) => backend.purgeAgentService?.blocksFolder(cwd),- gridSetup: () => backend.ensureGrid,- privateGridName: () => backend.privateGridName(),+ gridSetup: () => {+ const models = ports.models+ return models ? (request) => models.ensure(request) : null+ },+ // The backend's word, else what the models service works out (services/models.ts).+ privateGridName: async () => backend.gridName() ?? await (ports.models ?? MODELS_OFF).privateGridName(),})// Forking an agent (core/agents/fork.ts).@@ -2346,6 +2343,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {createAgent: () => backend.onCreateAgent, forkAgent: () => backend.onForkAgent,resumeAgent: () => lifecycle.resumeAgent, restartAgent: () => restartAgent,byAgent: (id) => registry.byAgent(id), toProject: (s) => backend.toProject(s),+ modelTarget: (selection) => (ports.models ?? MODELS_OFF).launchTarget(selection),})backend.createProvider = launches.createbackend.createStatusProvider = launches.createStatusdiff --git a/cli/src/core/modelsLink.spec.ts b/cli/src/core/modelsLink.spec.tsnew file mode 100644index 000000000..386fea61a--- /dev/null+++ b/cli/src/core/modelsLink.spec.ts@@ -0,0 +1,169 @@+import { describe, expect, it, vi } from 'vitest'+import type { GridGlance } from '../lib/gridAnnotation.js'+import type { RegisteredSession } from '../lib/registry.js'+import { fakeCore } from '../testing/fakeCore.js'+import { createModelsLink, glancesIn } from './modelsLink.js'+import { ServiceUnavailableError } from './serviceHost.js'+import type { ServiceFrame } from './serviceLinks.js'++const RELAY = 'https://fixture.invalid/g/net-own/relay/v1'+const LAUNCH = { networkId: 'net-own', networkName: 'mine', baseUrl: RELAY, apiKey: 'fixture-key', model: 'Small-Q4' }+const awake: GridGlance = { id: 'net-own', view: { state: 'awake', models: [{ id: 'Small-Q4' }, { id: 'Big', unavailable: { machine: 'Studio' } }] }, listed: true, asleep: false }+const asleep: GridGlance = { ...awake, view: { ...awake.view!, state: 'asleep' }, asleep: true }+const onGrid = (agentId: string, model: string | null = 'Small-Q4') => ({ agentId, grid: { baseUrl: RELAY, model } }) as unknown as RegisteredSession++function setup(answers: Record<string, Record<string, unknown>> = {}, agents: RegisteredSession[] = []) {+ const core = fakeCore({ agents: { advertised: vi.fn(() => agents) } })+ const call = vi.fn(async (type: string, _payload: Record<string, unknown>) => answers[type] ?? { error: 'SERVICE_UNAVAILABLE', service: 'models', retryable: true })+ const notify = vi.fn((_frame: ServiceFrame) => true)+ const link = createModelsLink(core, call, notify)+ return { core, call, notify, link, port: link.port }+}++describe('models in its own process, as the core reaches it', () => {+ describe('what a frame and a keystroke read: the glances models last told', () => {+ it('answers no note before models has said anything, and the note its last glance gives after', async () => {+ const { link, port } = setup()+ expect(port.annotation({ baseUrl: RELAY, model: 'Small-Q4' })).toBeNull()+ expect(await link.answer('glances', { glances: [awake] })).toEqual({ kept: true })+ expect(port.annotation({ baseUrl: RELAY, model: 'Small-Q4' })).toEqual({ state: 'awake' })+ expect(port.annotation({ baseUrl: RELAY, model: 'big' })).toEqual({ state: 'awake', note: { reason: 'offline', model: 'Big', machine: 'Studio' } })+ expect(port.annotation({ baseUrl: RELAY, model: 'Gone' })).toEqual({ state: 'awake', note: { reason: 'not_served', model: 'Gone' } })+ expect(port.annotation({ baseUrl: 'https://fixture.invalid/g/other/relay/v1', model: 'Small-Q4' })).toBeNull()+ })++ it('a keystroke crosses to models only for an agent whose grid is asleep', async () => {+ const { link, notify, port } = setup()+ port.prewarm({ baseUrl: RELAY, model: 'Small-Q4' })+ await link.answer('glances', { glances: [awake] })+ port.prewarm({ baseUrl: RELAY, model: 'Small-Q4' })+ expect(notify).not.toHaveBeenCalled()+ await link.answer('glances', { glances: [asleep] })+ port.prewarm({ baseUrl: RELAY, model: 'Small-Q4' })+ expect(notify).toHaveBeenCalledExactlyOnceWith({ type: 'service_event', payload: { kind: 'prewarm', grid: { baseUrl: RELAY, model: 'Small-Q4' } } })+ })++ it('sends again the frames of agents whose note moved — each on a grid the first time, then only on a change', async () => {+ const agents = [onGrid('a1'), onGrid('a2', 'Big'), { agentId: 'plain' } as RegisteredSession]+ const { core, link } = setup({}, agents)+ await link.answer('glances', { glances: [awake] })+ expect(vi.mocked(core.agents.sync).mock.calls.map(([s]) => s.agentId)).toEqual(['a1', 'a2'])+ await link.answer('glances', { glances: [awake] })+ expect(core.agents.sync).toHaveBeenCalledTimes(2)+ await link.answer('glances', { glances: [asleep] })+ expect(core.agents.sync).toHaveBeenCalledTimes(4)+ // An agent that left a grid is forgotten, so its return is announced again.+ agents.splice(0, 1)+ await link.answer('glances', { glances: [asleep] })+ agents.push(onGrid('a1'))+ await link.answer('glances', { glances: [asleep] })+ expect(vi.mocked(core.agents.sync).mock.calls.at(-1)![0].agentId).toBe('a1')+ })++ it('keeps nothing from what is not a list of glances, and reads each as far as a note does', async () => {+ const { link, port } = setup()+ expect(await link.answer('glances', { glances: 'nope' })).toEqual({ kept: false })+ expect(glancesIn([7, { id: '' }, { id: 'n1', view: { state: 'awake', models: 'nope' } }, { id: 'n2', view: { state: 'awake', models: [7, { id: 'm', unavailable: 'x' }, { id: 'n', unavailable: { machine: 'Mini' } }] }, listed: true, asleep: true }]))+ .toEqual([+ { id: 'n1', view: null, listed: false, asleep: false },+ { id: 'n2', view: { state: 'awake', models: [{ id: 'm' }, { id: 'n', unavailable: { machine: 'Mini' } }] }, listed: true, asleep: true },+ ])+ expect(port.annotation({ baseUrl: RELAY, model: 'x' })).toBeNull()+ })+ })++ describe('what the core asks models when it needs it', () => {+ it('grid set-up: what models answered, or unavailable', async () => {+ const ready = { status: 'converged', name: 'mine', detail: 'ok' }+ const { call, port } = setup({ ensure: ready })+ expect(await port.ensure({ ownGrid: true })).toEqual(ready)+ expect(call).toHaveBeenCalledWith('ensure', { ownGrid: true })+ await expect(setup().port.ensure()).rejects.toBeInstanceOf(ServiceUnavailableError)+ await expect(setup({ ensure: { requestId: 'x' } }).port.ensure()).rejects.toBeInstanceOf(ServiceUnavailableError)+ await expect(setup({ ensure: { error: 'SERVICE_FAILED', service: 'models' } }).port.ensure()).rejects.toBeInstanceOf(ServiceUnavailableError)+ })++ it('a new agent\'s target, checked as any launch is; none when models found none or said something else', async () => {+ const { call, port } = setup({ launchTarget: { target: LAUNCH } })+ expect(await port.launchTarget({ model: 'Small-Q4', grid: 'mine' })).toEqual(LAUNCH)+ expect(call).toHaveBeenCalledWith('launchTarget', { model: 'Small-Q4', grid: 'mine' })+ expect(await setup({ launchTarget: { target: null } }).port.launchTarget({ model: 'm', grid: 'g' })).toBeNull()+ expect(await setup({ launchTarget: { target: { ...LAUNCH, apiKey: '' } } }).port.launchTarget({ model: 'm', grid: 'g' })).toBeNull()+ // Down: the create that asked answers GRID_UNAVAILABLE (core/agents/launches.ts).+ await expect(setup().port.launchTarget({ model: 'm', grid: 'g' })).rejects.toBeInstanceOf(ServiceUnavailableError)+ })++ it('a move\'s target, or why there is none, in models\' words or the core\'s', async () => {+ expect(await setup({ moveTarget: { target: LAUNCH } }).port.moveTarget({ gridName: null, model: 'Small-Q4' })).toEqual({ target: LAUNCH })+ expect(await setup({ moveTarget: { detail: 'no grid on this computer' } }).port.moveTarget({ gridName: 'team', model: 'm' })).toEqual({ detail: 'no grid on this computer' })+ expect(await setup({ moveTarget: {} }).port.moveTarget({ gridName: 'team', model: 'm' })).toEqual({ detail: 'Could not read this machine\'s grid endpoint.' })+ await expect(setup().port.moveTarget({ gridName: null, model: 'm' })).rejects.toBeInstanceOf(ServiceUnavailableError)+ })++ it('the private grid\'s name, or none while models cannot say', async () => {+ expect(await setup({ privateGridName: { name: 'derived-1a2b' } }).port.privateGridName()).toBe('derived-1a2b')+ expect(await setup({ privateGridName: { name: null } }).port.privateGridName()).toBeNull()+ expect(await setup().port.privateGridName()).toBeNull()+ })++ it('the lists the windows are pushed, in both forms, or unavailable', async () => {+ const plain = { gridName: 'mine', models: [] }+ const rowState = { gridName: 'mine', models: [], grids: [] }+ expect(await setup({ lists: { plain, rowState } }).port.lists()).toEqual({ plain, rowState })+ await expect(setup({ lists: { plain } }).port.lists()).rejects.toBeInstanceOf(ServiceUnavailableError)+ await expect(setup().port.lists()).rejects.toBeInstanceOf(ServiceUnavailableError)+ })+ })++ describe('what the core only tells models', () => {+ it('a move onto a grid model, the machine list and the end of the sign-in, as events held for nobody', async () => {+ const { link, notify, port } = setup()+ port.moved(LAUNCH)+ port.machines({ data: { machines: [] } }, 'computer-here')+ port.signedOut()+ expect(notify.mock.calls.map(([frame]) => frame)).toEqual([+ { type: 'service_event', payload: { kind: 'moved', launch: LAUNCH } },+ { type: 'service_event', payload: { kind: 'machines', body: { data: { machines: [] } }, computerId: 'computer-here' } },+ { type: 'service_event', payload: { kind: 'signedOut' } },+ ])+ // A process that connects later asks for the machine list instead.+ expect(await link.answer('machines', {})).toEqual({ body: { data: { machines: [] } }, computerId: 'computer-here' })+ expect(await setup().link.answer('machines', {})).toEqual({})+ })+ })++ describe('what models asks the core', () => {+ it('the account\'s grid as the backend said it, this machine\'s name, a minted name and the token, each when asked', async () => {+ const core = fakeCore({ account: {+ privateGridName: vi.fn(async () => 'mine'), machineName: vi.fn(() => 'Studio'),+ mintGridName: vi.fn(async () => 'minted-1a2b'), accessToken: vi.fn(async () => 'fixture-token'),+ } })+ const link = createModelsLink(core, vi.fn(), vi.fn())+ expect(await link.answer('account', {})).toEqual({ gridName: 'mine', machineName: 'Studio' })+ expect(await link.answer('mintGridName', {})).toEqual({ name: 'minted-1a2b' })+ expect(await link.answer('accessToken', {})).toEqual({ token: 'fixture-token' })+ // Signed out, the token is refused: the link answers QUERY_FAILED for it (core/serviceLinks.ts).+ vi.mocked(core.account.accessToken).mockRejectedValueOnce(new Error('signed out'))+ await expect(link.answer('accessToken', {})).rejects.toThrow('signed out')+ })++ it('an agent\'s Model/Effort choices, or every live agent\'s', async () => {+ const models = [{ id: 'runtime-v1:a1:codex:o3@high', displayName: 'o3 / High' }]+ const core = fakeCore({ agents: { runtimeModels: vi.fn(async () => models) } })+ const link = createModelsLink(core, vi.fn(), vi.fn())+ expect(await link.answer('runtimeModels', { agentId: 'a1' })).toEqual({ models })+ expect(await link.answer('runtimeModels', { agentId: '' })).toEqual({ models })+ expect(vi.mocked(core.agents.runtimeModels).mock.calls).toEqual([['a1'], [undefined]])+ })++ it('the two pushes to the windows, and nothing for a question it does not know', async () => {+ const { core, link } = setup()+ expect(await link.answer('gridNamed', { name: 'mine' })).toEqual({})+ expect(await link.answer('gridNamed', { name: '' })).toEqual({})+ expect(core.clients.gridNamed).toHaveBeenCalledExactlyOnceWith('mine')+ expect(await link.answer('gridModelsChanged', {})).toEqual({})+ expect(core.clients.gridModelsChanged).toHaveBeenCalledOnce()+ expect(await link.answer('anything', {})).toEqual({ error: 'UNKNOWN_QUERY' })+ })+ })+})diff --git a/cli/src/core/modelsLink.ts b/cli/src/core/modelsLink.tsnew file mode 100644index 000000000..b79c0510f--- /dev/null+++ b/cli/src/core/modelsLink.ts@@ -0,0 +1,158 @@+/**+ * Models in its own process, as the core reaches it (`HARNESSD_SERVICES=models`; the process's side is+ * services/modelsProcess.ts).+ *+ * The core asks models two kinds of thing. What an agent's frame and a keystroke to it read — the note on+ * the agent's grid (`annotation`), and whether typing should start that grid (`prewarm`) — cannot wait on+ * another process: a frame is built in line, and a keystroke is the hottest path there is. So models tells+ * the core a glance at every grid it tracks whenever a picker would be told something new (a+ * `service_query` of kind `glances`), the core keeps the last, and the port answers from it, with what+ * models last said while it is down (lib/gridAnnotation.ts reads a glance as the service reads its own+ * pictures). Each new glance does here what the service does in the core's process: the frames of the+ * agents whose note moved go out again. A keystroke crosses to the process only when the agent's grid is+ * asleep, which is the only time the service would act on it.+ *+ * Everything else is asked when it is needed (core/serviceLinks.ts `call`): grid's set-up, where an agent+ * on a grid model sends its inference, the private grid's name, the lists the windows are pushed. An+ * answer that does not come (the process is down, or slower than its wait, core/api.ts `LONG_ANSWERS`) is+ * what the fallbacks give in the core's process (`MODELS_FALLBACKS`): an error for the one request that+ * asked, so a create on a grid model answers GRID_UNAVAILABLE, never a hang. What models is only told (a+ * move onto a grid model, the machine list, the end of the sign-in) is not held for it while it is down:+ * a restarted process asks for the machine list as it connects, starts with no sign-in cache to drop, and+ * a missed prewarm is one boot the first message waits for.+ *+ * Models asks the core what only the core holds (`answer`): the account's grid name and this machine's+ * name, a minted grid name, the access token grid's sign-in is handed (a service holds no credential: it+ * asks for it each time), each agent's Model/Effort choices, and the two pushes to the windows.+ */+import { annotate, glanceFor, type GridGlance } from '../lib/gridAnnotation.js'+import type { GridAttachResult } from '../lib/gridAttach.js'+import { parseGridLaunchOverride, type GridLaunchOverride } from '../lib/gridLaunch.js'+import type { CoreApi, ModelsPort } from './api.js'+import { ServiceUnavailableError } from './serviceHost.js'+import type { ServiceFrame } from './serviceLinks.js'++/** Ask models' process (core/serviceLinks.ts `call`, for `models`): never rejects. */+export type CallModels = (type: string, payload: Record<string, unknown>) => Promise<Record<string, unknown>>+/** Tell models' process something (core/serviceLinks.ts `notify`, for `models`). */+export type NotifyModels = (frame: ServiceFrame) => boolean++const isRecord = (value: unknown): value is Record<string, unknown> => !!value && typeof value === 'object' && !Array.isArray(value)++/** The glances in what the process said, each checked as far as an agent's note reads it; null when it+ * said none. */+export function glancesIn(value: unknown): GridGlance[] | null {+ if (!Array.isArray(value)) return null+ return value.filter(isRecord).filter((glance) => typeof glance.id === 'string' && glance.id).map((glance) => {+ const view = isRecord(glance.view) && typeof glance.view.state === 'string' && Array.isArray(glance.view.models) ? glance.view : null+ const models = (view?.models as unknown[] | undefined ?? []).filter(isRecord).filter((model) => typeof model.id === 'string').map((model) =>+ isRecord(model.unavailable) && typeof model.unavailable.machine === 'string'+ ? { id: model.id as string, unavailable: { machine: model.unavailable.machine } }+ : { id: model.id as string })+ return {+ id: glance.id as string,+ view: view ? { state: view.state as NonNullable<GridGlance['view']>['state'], models } : null,+ listed: glance.listed === true,+ asleep: glance.asleep === true,+ }+ })+}++/** A launch the process resolved, checked as any grid launch is before it is used; null when there is none. */+const launchIn = (value: unknown): GridLaunchOverride | null => {+ const parsed = parseGridLaunchOverride(value)+ return parsed.state === 'ok' ? parsed.override : null+}++export function createModelsLink(core: Pick<CoreApi, 'agents' | 'account' | 'clients'>, call: CallModels, notify: NotifyModels) {+ let glances: GridGlance[] = []+ /** What each agent's frame last said of its grid, so only a change sends the frame again. */+ const announced = new Map<string, string>()+ /** The machine list the core last read, for a process that connects after it. */+ let machines: { body: Record<string, unknown> | null; computerId: string } | null = null++ /** An answer, or models' being unavailable as a rejection: what a FAIL fallback gives in the core's process. */+ const ask = async (type: string, payload: Record<string, unknown>): Promise<Record<string, unknown>> => {+ const answer = await call(type, payload)+ if (answer.error === 'SERVICE_UNAVAILABLE' || answer.error === 'SERVICE_FAILED') throw new ServiceUnavailableError('models')+ return answer+ }+ const tell = (payload: Record<string, unknown>): void => { notify({ type: 'service_event', payload }) }++ const port: ModelsPort = {+ ensure: async (request) => {+ const answer = await ask('ensure', { ...request })+ if (typeof answer.status !== 'string') throw new ServiceUnavailableError('models')+ return answer as unknown as GridAttachResult+ },+ annotation: (grid) => annotate(glanceFor(glances, grid.baseUrl), grid),+ prewarm: (grid) => { if (glanceFor(glances, grid.baseUrl)?.asleep) tell({ kind: 'prewarm', grid }) },+ launchTarget: async (selection) => launchIn((await ask('launchTarget', { ...selection })).target),+ moveTarget: async (request) => {+ const answer = await ask('moveTarget', { ...request })+ const target = launchIn(answer.target)+ if (target) return { target }+ return { detail: typeof answer.detail === 'string' && answer.detail ? answer.detail : 'Could not read this machine\'s grid endpoint.' }+ },+ moved: (launch) => tell({ kind: 'moved', launch }),+ // Its fallback is no name, not an error: the backend's, which the caller reads first, is all there is.+ privateGridName: async () => {+ const answer = await call('privateGridName', {})+ return typeof answer.name === 'string' && answer.name ? answer.name : null+ },+ lists: async () => {+ const answer = await ask('lists', {})+ if (!isRecord(answer.plain) || !isRecord(answer.rowState)) throw new ServiceUnavailableError('models')+ return { plain: answer.plain, rowState: answer.rowState }+ },+ machines: (body, computerId) => {+ machines = { body, computerId }+ tell({ kind: 'machines', body, computerId })+ },+ signedOut: () => tell({ kind: 'signedOut' }),+ }++ /** Models says what it now sees of every grid: kept, and the frames of the agents whose note moved sent+ * again — every one on a grid the first time, as in the service's own process. */+ const heard = (payload: Record<string, unknown>): Record<string, unknown> => {+ const next = glancesIn(payload.glances)+ if (!next) return { kept: false }+ glances = next+ const onGrid = core.agents.advertised().filter((session) => session.grid)+ const present = new Set(onGrid.map((session) => session.agentId))+ for (const agentId of [...announced.keys()]) if (!present.has(agentId)) announced.delete(agentId)+ for (const session of onGrid) {+ const said = JSON.stringify(port.annotation(session.grid!))+ if (announced.get(session.agentId) === said) continue+ announced.set(session.agentId, said)+ core.agents.sync(session)+ }+ return { kept: true }+ }++ return {+ port,+ /** The core's answers to models' questions (core/serviceLinks.ts `answer`, for `models`). */+ async answer(query: string, payload: Record<string, unknown>): Promise<Record<string, unknown>> {+ if (query === 'glances') return heard(payload)+ if (query === 'account') return { gridName: await core.account.privateGridName(), machineName: core.account.machineName() }+ if (query === 'mintGridName') return { name: await core.account.mintGridName() }+ if (query === 'accessToken') return { token: await core.account.accessToken() }+ if (query === 'runtimeModels') {+ return { models: await core.agents.runtimeModels(typeof payload.agentId === 'string' && payload.agentId ? payload.agentId : undefined) }+ }+ if (query === 'machines') return machines ? { ...machines } : {}+ if (query === 'gridNamed') {+ if (typeof payload.name === 'string' && payload.name) core.clients.gridNamed(payload.name)+ return {}+ }+ if (query === 'gridModelsChanged') {+ core.clients.gridModelsChanged()+ return {}+ }+ return { error: 'UNKNOWN_QUERY' }+ },+ }+}++export type ModelsLink = ReturnType<typeof createModelsLink>diff --git a/cli/src/core/serviceLinks.spec.ts b/cli/src/core/serviceLinks.spec.tsindex 614884eaa..3ffb8b240 100644--- a/cli/src/core/serviceLinks.spec.ts+++ b/cli/src/core/serviceLinks.spec.ts@@ -148,6 +148,37 @@ describe('service links', () => {expect(reply).toHaveBeenCalledWith({ error: 'SERVICE_UNAVAILABLE', service: 'search', retryable: true })})+ it('waits longer for the answers that take longer, by service and type, and the usual half minute for the rest', async () => {+ const links = make({+ owned: { search: ['session_search', 'session_tail'], models: ['grid_fleet_run'] },+ waits: { models: { grid_fleet_run: 60_000, ensure: 30_000 }, search: { session_tail: 10_000 } },+ })+ links.accept('models', TOKEN, sink(), vi.fn())+ links.accept('search', TOKEN, sink(), vi.fn())+ const run = vi.fn()+ const ensure = vi.fn()+ const search = vi.fn()+ const tail = vi.fn()+ links.route('grid_fleet_run', {}, ASKER, run)+ void links.call('models', 'ensure', {}).then(ensure)+ links.route('session_search', {}, ASKER, search)+ links.route('session_tail', {}, ASKER, tail)+ vi.advanceTimersByTime(5_000)+ expect(search).toHaveBeenCalledWith({ error: 'SERVICE_UNAVAILABLE', service: 'search', retryable: true })+ expect(tail).not.toHaveBeenCalled()+ vi.advanceTimersByTime(5_000)+ expect(tail).toHaveBeenCalled()+ vi.advanceTimersByTime(20_000)+ await Promise.resolve()+ expect(ensure).toHaveBeenCalledWith({ error: 'SERVICE_UNAVAILABLE', service: 'models', retryable: true })+ expect(run).not.toHaveBeenCalled()+ vi.advanceTimersByTime(30_000)+ expect(run).toHaveBeenCalledWith({ error: 'SERVICE_UNAVAILABLE', service: 'models', retryable: true })+ // A type the waits only inherit from Object's prototype waits as any other does.+ links.route('session_search', {}, ASKER, vi.fn())+ expect(links.call('models', 'toString', {})).toBeInstanceOf(Promise)+ })+it('answers what was waiting on a service that goes, and lets a newer connection replace an older one', () => {const links = make({ owned: { search: ['session_search'], devices: ['harness_devices_list'] } })links.accept('devices', TOKEN, sink(), vi.fn())diff --git a/cli/src/core/serviceLinks.ts b/cli/src/core/serviceLinks.tsindex 30e5098e8..dbd2e1ce8 100644--- a/cli/src/core/serviceLinks.ts+++ b/cli/src/core/serviceLinks.ts@@ -52,6 +52,9 @@ export interface ServiceLinksOptions {disconnected?(service: string): void/** How long a routed request may wait for its service before it is answered SERVICE_UNAVAILABLE. */timeoutMs?: number+ /** Longer waits for the answers that take longer, by service and then by type (core/api.ts+ * `LONG_ANSWERS`): a grid command, grid's set-up, a harness's install. */+ waits?: Readonly<Record<string, Readonly<Record<string, number>>>>log?: (line: string) => voidnewId?: () => stringsetTimer?: (run: () => void, ms: number) => unknown@@ -104,14 +107,20 @@ export function createServiceLinks(options: ServiceLinksOptions) {entry.reply(result)}+ /** How long an answer from `service` to `type` is waited for: its own wait when it has one. */+ const waitFor = (service: string, type: string): number => {+ const waits = options.waits?.[service]+ return waits && Object.hasOwn(waits, type) ? waits[type] : timeoutMs+ }+/** Send `type` to `service`, its answer to `reply`, whatever becomes of the service. */- const ask = (service: string, type: string, payload: Record<string, unknown>, asker: Asker, reply: (result: Record<string, unknown>) => void, waitMs = timeoutMs): void => {+ const ask = (service: string, type: string, payload: Record<string, unknown>, asker: Asker, reply: (result: Record<string, unknown>) => void, waitMs?: number): void => {const link = links.get(service)if (!link) { reply(unavailable(service)); return }const id = newId()const entry: Waiting = { service, type, reply, timer: null }// Cleared whenever the entry is settled, so it only ever fires for one still waiting.- entry.timer = setTimer(() => settle(id, entry, unavailable(service)), waitMs)+ entry.timer = setTimer(() => settle(id, entry, unavailable(service)), waitMs ?? waitFor(service, type))waiting.set(id, entry)if (!link.sink.sendFrame({ type, payload: { ...payload, requestId: id }, asker })) settle(id, entry, unavailable(service))}diff --git a/cli/src/gateway/gateway.spec.ts b/cli/src/gateway/gateway.spec.tsindex d757d282e..3fb4c3b2d 100644--- a/cli/src/gateway/gateway.spec.ts+++ b/cli/src/gateway/gateway.spec.ts@@ -71,9 +71,10 @@ describe('a remote client, as the core hears it', () => {// A field in the payload claiming the owner's role is the sender's word; the session is the gateway's.await dispatchDown(socket, phone.seal('dsh_list', { requestId: 'p', owner: false }), 'phone-1')await dispatchDown(socket, dial.seal('dsh_list', { requestId: 'd', owner: true, local: true, role: 'web' }), 'dial-1')+ // With the connection and the request id it asked under, which a service keys a connection's own work by.expect(asked).toEqual([- { type: 'dsh_list', asker: { local: false, owner: true } },- { type: 'dsh_list', asker: { local: false, owner: false } },+ { type: 'dsh_list', asker: { local: false, owner: true, connection: 'phone-1', requestId: 'p' } },+ { type: 'dsh_list', asker: { local: false, owner: false, connection: 'dial-1', requestId: 'd' } },])await socket.stop()})diff --git a/cli/src/harnessd/services.ts b/cli/src/harnessd/services.tsindex 3f5f5e934..2fc35e4b3 100644--- a/cli/src/harnessd/services.ts+++ b/cli/src/harnessd/services.ts@@ -321,6 +321,9 @@ export const SERVICE_HOSTS: Readonly<Record<string, ServiceHostSpec>> = {// the terminals' WebRTC channels and their queues. Network, crypto and pure-JS WebRTC, the attack surface,// where a fault costs the remote clients and nothing else (docs/design/2026-10-06-core-boundary-next.md).gateway: { services: ['gateway'], heapLimitMiB: 512, rssLimitMiB: 1_024 },+ // Grid's pictures, the Model Manager's catalog and the models found on this machine. Its downloads, model+ // servers and `grid` commands run in processes of their own, outside this budget.+ models: { services: ['models'], heapLimitMiB: 512, rssLimitMiB: 1_024 },}/** Every service this build can run outside the core's process: what `HARNESSD_SERVICES` names. */diff --git a/cli/src/lib/agentFrame.spec.ts b/cli/src/lib/agentFrame.spec.tsindex 4137a3083..bfdc59731 100644--- a/cli/src/lib/agentFrame.spec.ts+++ b/cli/src/lib/agentFrame.spec.ts@@ -1,7 +1,7 @@import { mkdtemp, rm, utimes, writeFile } from 'node:fs/promises'import { tmpdir } from 'node:os'import { join } from 'node:path'-import { describe, expect, it } from 'vitest'+import { describe, expect, it, vi } from 'vitest'import { agentFrame } from './agentFrame.js'import type { RegisteredSession } from './registry.js'@@ -35,6 +35,18 @@ describe('agentFrame', () => {.toMatchObject({ grid: assignment })})+ it('carries what models says of the agent\'s grid, asked of the grid it is on, and nothing when it has nothing to say', async () => {+ const said = vi.fn(() => ({ state: 'asleep' as const, note: { reason: 'offline' as const, model: assignment.model, machine: 'Studio' } }))+ expect((await agentFrame(session(assignment), { selectedModel: null, terminalAvailable: true, gridAnnotation: said })).grid)+ .toEqual({ ...assignment, state: 'asleep', note: { reason: 'offline', model: assignment.model, machine: 'Studio' } })+ expect(said).toHaveBeenCalledWith(assignment)+ expect((await agentFrame(session(assignment), { selectedModel: null, terminalAvailable: true, gridAnnotation: () => null })).grid).toEqual(assignment)+ // An agent on no grid is asked about none.+ said.mockClear()+ await agentFrame(session(null), { selectedModel: null, terminalAvailable: true, gridAnnotation: said })+ expect(said).not.toHaveBeenCalled()+ })+it('never carries the grid launch — the key stays in the registry', async () => {const row = session(assignment)row.gridLaunch = { networkId: 'grid-abc', networkName: 'Team grid', baseUrl: assignment.baseUrl, apiKey: 'gridkey-SECRET' }diff --git a/cli/src/lib/agentFrame.ts b/cli/src/lib/agentFrame.tsindex 9e891fb7f..03862800b 100644--- a/cli/src/lib/agentFrame.ts+++ b/cli/src/lib/agentFrame.ts@@ -27,7 +27,7 @@ import type { AgentTokenUsage } from './agentTokenUsage.js'import type { AgentOutputStats } from './agentOutputStats.js'import type { GridAssignment } from './gridAssignment.js'import type { GridWebSearchStatus } from './gridLaunch.js'-import { gridAnnotation, type GridAnnotation } from './gridModels.js'+import type { AgentGridTarget, GridAnnotation } from './gridAnnotation.js'import { projectDisplayName, sessionDisplayTitle, type RegisteredSession } from './registry.js'import { engineCanFork } from './forkAgent.js'import { resumeMode, type ResumeMode } from './resumeCapability.js'@@ -145,6 +145,9 @@ export interface AgentFrameContext {tokenUsage?: AgentTokenUsage | null/** The DSH companions' state for this agent; absent when the caller has none to give. */dsh?: AgentDshContext | null+ /** What the models service says of the grid the agent is on (core/api.ts `ModelsPort.annotation`): from+ * memory, never I/O. Absent when the caller has none to give, and then the frame says nothing of it. */+ gridAnnotation?: (grid: AgentGridTarget) => GridAnnotation | null}/**@@ -185,7 +188,7 @@ const gitContexts = new SessionGitContextReader()export async function agentFrame(s: RegisteredSession,- { selectedModel, terminalAvailable, dsh, tokenUsage, activity: contextActivity }: AgentFrameContext,+ { selectedModel, terminalAvailable, dsh, tokenUsage, activity: contextActivity, gridAnnotation }: AgentFrameContext,): Promise<AgentFrame> {const home = agentProject(s.cwd)const context = gitContexts.read(JSON.stringify([s.agentId, s.sessionId, s.engine, s.codexHome, s.registeredAt]), async () => {@@ -229,7 +232,7 @@ export async function agentFrame(// the block — decided by the launch, kept on the row — so it is gone the moment the block is. So do// that grid's `state` and a `note` when the agent's model will not answer (issue 03), read from what// the model list last showed — no I/O, and absent for a grid this daemon is not tracking.- grid: s.grid ? { ...s.grid, ...(s.gridWebSearch ? { webSearch: s.gridWebSearch } : {}), ...gridAnnotation(s.grid) } : null,+ grid: s.grid ? { ...s.grid, ...(s.gridWebSearch ? { webSearch: s.gridWebSearch } : {}), ...gridAnnotation?.(s.grid) } : null,// The Codex profile folder this agent launched against, if one was chosen instead of the// engine's own login. Codex only; null is a real answer ("uses ~/.codex") for the same reason// `grid: null` is above.diff --git a/cli/src/lib/apiModels.ts b/cli/src/lib/apiModels.tsindex 8ea7f2e3a..123c629f1 100644--- a/cli/src/lib/apiModels.ts+++ b/cli/src/lib/apiModels.ts@@ -13,7 +13,7 @@ import { createHash } from 'node:crypto'import { ApiConnectionError, type ApiConnections } from './apiConnections.js'import { rememberApiBase } from './gridAssignment.js'import { API_NETWORK_PREFIX, contextWindowHint, isApiLaunch, type GridLaunchOverride } from './gridLaunch.js'-import { MIN_CODING_CONTEXT } from './localModels.js'+import { MIN_CODING_CONTEXT } from './codingContext.js'export interface ApiModel {id: stringdiff --git a/cli/src/lib/codingContext.ts b/cli/src/lib/codingContext.tsnew file mode 100644index 000000000..71b95e4c5--- /dev/null+++ b/cli/src/lib/codingContext.ts@@ -0,0 +1,11 @@+/**+ * The smallest context a coding agent can work in. Codex, Claude Code and OpenCode each open a+ * session with a system prompt and tool list of several thousand tokens and grow from there; Ollama's+ * own guides for all three put the floor at 64K, and below it a session survives a few turns and then+ * fails. Every model offered here is one this machine can give at least this much: a local model+ * (localModels.ts) and an API's (apiModels.ts) alike.+ *+ * Its own module because the API launches are the core's, and the local models the models service's,+ * which runs in a process of its own (docs/design/2026-10-06-core-boundary-next.md, step 7).+ */+export const MIN_CODING_CONTEXT = 64 * 1024diff --git a/cli/src/lib/engineLaunch.ts b/cli/src/lib/engineLaunch.tsindex 3abbd5a76..fc27e12cf 100644--- a/cli/src/lib/engineLaunch.ts+++ b/cli/src/lib/engineLaunch.ts@@ -10,7 +10,7 @@ import { isOpencodeV2 } from '../engines/opencode/version.js'import { binaryOnPath, resolveBinaryOnPath } from './binaryOnPath.js'import { engineBin } from './engineBin.js'import { engineInstallPaths, npmEnginePrefix, type EngineInstallRecipe } from './engineInstall.js'-import { GRID_NO_UPDATE_CHECK_VAR, gridBinaryPath } from './gridExec.js'+import { GRID_NO_UPDATE_CHECK_VAR, gridBinaryPath } from './gridBinary.js'import { loginShellEnvironment } from './loginShellEnv.js'import { managedNodePath } from './nodeRuntime.js'import { RAISE_OPEN_FILES_SH } from './openFiles.js'diff --git a/cli/src/lib/gridActs.spec.ts b/cli/src/lib/gridActs.spec.tsindex b3d4439e3..0abb230af 100644--- a/cli/src/lib/gridActs.spec.ts+++ b/cli/src/lib/gridActs.spec.ts@@ -14,6 +14,7 @@ import { join } from 'node:path'import { installFakeGrid, type FakeGrid, type FakeGridPlan } from './__fixtures__/fakeGrid.js'import { startFakeRelay, type FakeRelay, type RelayAnswer, type RelayRequest } from './__fixtures__/fakeRelay.js'import { agentFrame } from './agentFrame.js'+import { annotate, glanceFor } from './gridAnnotation.js'import { presentGridSections, resetGridModels, type GridModelsService, type GridSection } from './gridModels.js'import type { RegisteredSession } from './registry.js'@@ -416,11 +417,32 @@ describe('the note on an agent already on a model', () => {const agent = { agentId: 'a1', sessionId: 's1', engine: 'claude', active: true, cwd: '/tmp', runtimes: [], registeredAt: 1,grid: onOwn('small-q4') } as unknown as RegisteredSession- const frame = await agentFrame(agent, { selectedModel: null, terminalAvailable: true })+ const frame = await agentFrame(agent, { selectedModel: null, terminalAvailable: true, gridAnnotation: (target) => service.annotation(target) })expect(frame.grid).toEqual({ ...onOwn('small-q4'), state: 'asleep', note: { reason: 'not_served', model: 'small-q4' } })})+ it('reads the same off the glances models tells a core that runs apart from it, and says asleep where a keystroke would start it', async () => {+ answer(OWN_ID, OVERVIEW, { status: 200, body: { nodes: [node('studio', ['big-model'])], models: [{ id: 'Big-Model' }] } })+ answer(TEAM_ID, OVERVIEW, asleep(record(30, [{ name: 'rig', models: ['other-model'] }])))+ await look()+ later()+ answer(OWN_ID, OVERVIEW, asleep())+ await look()+ studioOfflineTwice()+ await service.sections(OWN, { refresh: false })+ const glances = service.glances()+ expect(glances.map((g) => g.id).sort()).toEqual([OWN_ID, TEAM_ID])+ const onTeam = (model: string | null) => ({ baseUrl: `${relay.base}/g/${TEAM_ID}/relay`, model })+ for (const target of [onOwn('big-model'), onOwn('small-q4'), onOwn(null), onTeam('other-model'), onTeam('gone'), { baseUrl: `${relay.base}/g/net-elsewhere/relay`, model: 'x' }]) {+ expect(annotate(glanceFor(glances, target.baseUrl), target)).toEqual(service.annotation(target))+ }+ // Each model is its id and the computer it waits for, nothing more: what a frame reads, and no more to send.+ expect(glances.find((g) => g.id === OWN_ID)!.view!.models).toEqual([{ id: 'Big-Model', unavailable: { machine: 'Studio' } }])+ expect(glances.find((g) => g.id === OWN_ID)!.asleep).toBe(true)+ expect(await service.keystrokePrewarm(onOwn('big-model'))).not.toBe('not-asleep')+ })+it('has no note for Auto, and no annotation for a grid this daemon does not know', async () => {answer(OWN_ID, OVERVIEW, asleep(record(30, [{ name: 'mac', models: ['other-model'] }])))await look()@@ -467,9 +489,13 @@ describe('after the daemon restarts', () => {service = freshService()const reads = relay.seen.length+ const changed = vi.fn()+ service.onChange(changed)await service.warm()expect(service.annotation(onTeam('big-model'))).toEqual({ state: 'asleep' })+ // Said as a change: a frame built before it carried no note, and a core reading models' glances has none yet.+ await vi.waitFor(() => expect(changed).toHaveBeenCalled())expect(service.annotation(onTeam('other-model'))).toEqual({ state: 'asleep', note: { reason: 'not_served', model: 'other-model' } })// Warming read the pictures on disk, not the grid.expect(relay.seen.length).toBe(reads)diff --git a/cli/src/lib/gridAnnotation.spec.ts b/cli/src/lib/gridAnnotation.spec.tsnew file mode 100644index 000000000..0209f4d98--- /dev/null+++ b/cli/src/lib/gridAnnotation.spec.ts@@ -0,0 +1,37 @@+import { describe, expect, it } from 'vitest'+import { annotate, glanceFor, idKey, type GridGlance } from './gridAnnotation.js'++const RELAY = 'https://fixture.invalid/g/net-own/relay/v1'+const glance = (over: Partial<GridGlance> = {}): GridGlance => ({+ id: 'net-own', view: { state: 'awake', models: [{ id: 'Small-Q4' }, { id: 'Big', unavailable: { machine: 'Studio' } }] }, listed: true, asleep: false, ...over,+})++describe('what an agent\'s frame says of its grid, read off a glance', () => {+ it('finds the grid an agent\'s inference goes to by its id in the relay\'s path, and none for an address it cannot read', () => {+ const own = glance()+ expect(glanceFor([glance({ id: 'other' }), own], RELAY)).toBe(own)+ expect(glanceFor([own], 'https://fixture.invalid/g/elsewhere/relay/v1')).toBeNull()+ expect(glanceFor([own], 'not a url')).toBeNull()+ })++ it('says the grid\'s state, and a note when the agent\'s model will not answer', () => {+ expect(annotate(glance(), { baseUrl: RELAY, model: ' small-q4 ' })).toEqual({ state: 'awake' })+ expect(annotate(glance(), { baseUrl: RELAY, model: 'big' })).toEqual({ state: 'awake', note: { reason: 'offline', model: 'Big', machine: 'Studio' } })+ expect(annotate(glance(), { baseUrl: RELAY, model: 'Gone' })).toEqual({ state: 'awake', note: { reason: 'not_served', model: 'Gone' } })+ })++ it('says nothing of a model a grid never listed, of an agent on the grid\'s default, or of a grid waking', () => {+ expect(annotate(glance({ listed: false }), { baseUrl: RELAY, model: 'Gone' })).toEqual({ state: 'awake' })+ expect(annotate(glance(), { baseUrl: RELAY, model: null })).toEqual({ state: 'awake' })+ expect(annotate(glance({ view: { state: 'waking', models: [] } }), { baseUrl: RELAY, model: 'Gone' })).toEqual({ state: 'waking' })+ })++ it('says nothing at all of a grid no picker was shown, or one not tracked', () => {+ expect(annotate(glance({ view: null }), { baseUrl: RELAY, model: 'Small-Q4' })).toBeNull()+ expect(annotate(null, { baseUrl: RELAY, model: 'Small-Q4' })).toBeNull()+ })++ it('joins ids without case or the spaces around them', () => {+ expect(idKey(' Qwen3-Coder ')).toBe('qwen3-coder')+ })+})diff --git a/cli/src/lib/gridAnnotation.ts b/cli/src/lib/gridAnnotation.tsnew file mode 100644index 000000000..b4e4f9606--- /dev/null+++ b/cli/src/lib/gridAnnotation.ts@@ -0,0 +1,64 @@+/**+ * What an agent's frame says about the grid it is on (grid-reads-without-waking issue 03): that grid's+ * state, and a note when the agent's model will not answer, because every computer serving it seems+ * offline or the latest list no longer has it. And whether a keystroke to the agent should start its grid.+ *+ * Asked on every frame and every keystroke, so it is answered from memory: a glance at each grid the+ * models service tracks (`gridModels.ts`). In the core's process that is the service's own pictures; with+ * models in a process of its own, the glances it last told the core (core/modelsLink.ts), so a frame and+ * a keystroke never cross a process (docs/design/2026-10-06-core-boundary-next.md, step 7). One reading+ * of a glance serves both, here, in a module the core loads without the models' code.+ */++/**+ * `awake` — the last read answered. `asleep` — the platform says it is resting. `unknown` — the last+ * read failed any other way, or nothing has been read yet (the list shown, if any, is the last known).+ * `waking` — a person asked for it to start (issue 03's explicit wake; never set by a read).+ */+export type PictureState = 'awake' | 'asleep' | 'waking' | 'unknown'++/** Where an agent's inference goes (`gridAssignment.ts`) — all a prewarm or a note needs of it. */+export interface AgentGridTarget { baseUrl: string; model: string | null }++/** What is said about an agent already on a grid model (issue 03): that grid's state, and a note when its+ * model will not answer — every computer serving it seems offline, or the latest list no longer has it. */+export interface GridNote { reason: 'offline' | 'not_served'; model: string; machine?: string }+export interface GridAnnotation { state: PictureState; note?: GridNote }++/** One grid as the models service last saw it: as much of it as an agent's frame and a keystroke read. */+export interface GridGlance {+ /** The grid's network id: a segment of the path of every relay that reaches it. */+ id: string+ /** What a picker was last told of it, or null before anyone was: its state, and the models it offers,+ * each with the computer it waits for when every one serving it seems offline. */+ view: { state: PictureState; models: ReadonlyArray<{ id: string; unavailable?: { machine: string } }> } | null+ /** It has been listed at least once. "No longer lists" needs a list: a grid never read says nothing+ * about any model. */+ listed: boolean+ /** Its picture says asleep and no wake is under way: a keystroke to an agent on it may start it. */+ asleep: boolean+}++/** A model id without case: how grids, records and pickers are joined. */+export const idKey = (id: string): string => id.trim().toLowerCase()++/** The grid an agent's inference goes to: the one whose id is a segment of its relay's path. */+export function glanceFor<T extends { id: string }>(glances: Iterable<T>, baseUrl: string): T | null {+ let segments: string[]+ try { segments = new URL(baseUrl).pathname.split('/').filter(Boolean) } catch { return null }+ for (const glance of glances) if (segments.includes(glance.id)) return glance+ return null+}++/** What an agent on `target` is told about its grid, from a glance at it; null for a grid nobody has+ * shown a picker yet, or one not tracked at all. */+export function annotate(glance: GridGlance | null, target: AgentGridTarget): GridAnnotation | null {+ const view = glance?.view+ if (!glance || !view) return null+ if (!target.model || view.state === 'waking') return { state: view.state }+ const key = idKey(target.model)+ const row = view.models.find((model) => idKey(model.id) === key)+ if (row?.unavailable) return { state: view.state, note: { reason: 'offline', model: row.id, machine: row.unavailable.machine } }+ if (!row && glance.listed) return { state: view.state, note: { reason: 'not_served', model: target.model } }+ return { state: view.state }+}diff --git a/cli/src/lib/gridAttach.spec.ts b/cli/src/lib/gridAttach.spec.tsindex 06f2951ee..71a303d7a 100644--- a/cli/src/lib/gridAttach.spec.ts+++ b/cli/src/lib/gridAttach.spec.ts@@ -1,5 +1,5 @@import { describe, expect, it, vi } from 'vitest'-import { reconcileGridAttach, createGridAccess, setUpWithin, type GridAttachDeps, type GridAttachResult } from './gridAttach.js'+import { reconcileGridAttach, createGridAccess, type GridAttachDeps, type GridAttachResult } from './gridAttach.js'import type { GridHandoffResult } from './gridHandoff.js'import type { EnsureResult } from './gridEnsure.js'@@ -268,31 +268,3 @@ describe('createGridAccess — grid set up when a feature asks', () => {await expect(grid.ensure()).resolves.toMatchObject({ status: 'handoff-failed', detail: 'boom' })})})--describe('setUpWithin: a set-up a create waits for, but not for long', () => {- it('answers done once a quick set-up lands', async () => {- await expect(setUpWithin(async () => ({ status: 'converged' }), 1_000)).resolves.toBe('done')- })-- it('stops waiting at the bound and leaves the set-up running', async () => {- vi.useFakeTimers()- try {- let finish!: () => void- const running = new Promise<void>((resolve) => { finish = resolve })- let landed = false- const waited = setUpWithin(() => running.then(() => { landed = true }), 8_000)- await vi.advanceTimersByTimeAsync(8_000)- await expect(waited).resolves.toBe('pending')- finish()- await running- await Promise.resolve()- expect(landed).toBe(true)- } finally {- vi.useRealTimers()- }- })-- it('never throws: a failed set-up is for the next use of grid to say', async () => {- await expect(setUpWithin(async () => { throw new Error('offline') }, 1_000)).resolves.toBe('done')- })-})diff --git a/cli/src/lib/gridAttach.ts b/cli/src/lib/gridAttach.tsindex 3b73c0e26..34da14927 100644--- a/cli/src/lib/gridAttach.ts+++ b/cli/src/lib/gridAttach.ts@@ -240,22 +240,6 @@ export function createGridAccess(opts: GridAccessOptions): GridAccess {}}-/**- * Start a grid set-up and wait for it at most [waitMs]. Past that it carries on — the access queue- * remembers it when it lands, and a later `ensure` waits for it — so a caller that must answer in seconds- * (a Model Manager being created) is never held for a first install. Never throws: what failed is said by- * the next thing that uses grid.- */-export async function setUpWithin(setUp: () => Promise<unknown>, waitMs: number): Promise<'done' | 'pending'> {- let timer: NodeJS.Timeout | undefined- const waited = new Promise<'pending'>((resolve) => { timer = setTimeout(() => resolve('pending'), waitMs) })- try {- return await Promise.race([setUp().then(() => 'done' as const, () => 'done' as const), waited])- } finally {- clearTimeout(timer)- }-}-export async function gridNamesLocal(): Promise<string[]> {const { value, result } = await gridJson<Array<{ grid?: unknown }>>(['--remote', 'ls'])// ⚠️ A FAILED read is NOT an empty list, and conflating the two is how "this machine has no grids"diff --git a/cli/src/lib/gridBinary.ts b/cli/src/lib/gridBinary.tsnew file mode 100644index 000000000..575ebcb2b--- /dev/null+++ b/cli/src/lib/gridBinary.ts@@ -0,0 +1,106 @@+/**+ * Which `grid` this daemon runs, and the environment it runs it in: the resolution behind every grid+ * call (`gridExec.ts`) and behind every pane the core launches on a grid (`engineLaunch.ts`).+ *+ * Its own module so the core can launch an agent on a grid without loading the code that runs `grid`+ * itself: that is the models service's (services/models.ts), which runs in a process of its own+ * (docs/design/2026-10-06-core-boundary-next.md, step 7). It reads files and never spawns.+ */+import { accessSync, constants, readFileSync } from 'node:fs'+import { join, sep } from 'node:path'+import { env } from '../config/env.js'+import { binaryOnPath } from './binaryOnPath.js'++/** The command, as it is named on PATH — the last resort of [gridBinaryPath], and the word the+ * sign-out's own "nothing to run" sentence uses (`gridLogout.ts`). */+export const GRID_BINARY = 'grid'++/**+ * grid's own update check, and the one switch that turns it off.+ *+ * A `grid` with a terminal on stderr looks for a newer release and, finding one, prints "run+ * `grid update`" — and `grid update` replaces the binary IN PLACE, wherever `which grid` found it+ * (autonomous-grid `cli/update.py`). Under a managed runtime that file is the pin, and the process+ * most likely to read that line and obey it is an agent in a pane. So the check is off for every+ * child this daemon spawns ([gridChildEnv]) and in every pane it launches (`engineLaunch.ts`), by+ * the variable grid honours for it. The daemon's own spawns pipe stderr and would be spared anyway;+ * saying it explicitly is what makes the pane and the daemon one rule.+ */+export const GRID_NO_UPDATE_CHECK_VAR = 'GRID_NO_UPDATE_CHECK'++/** The environment a `grid` child gets: the caller's own, with the update check off. */+export function gridChildEnv(processEnv: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {+ return { ...processEnv, [GRID_NO_UPDATE_CHECK_VAR]: '1' }+}++/**+ * The managed grid — the runtime `current-grid` names — or null when there is none this daemon+ * would trust.+ *+ * Containment-checked exactly like `nodeRuntime.managedNodePath`: a pointer file is only trusted+ * when it names something INSIDE the runtime directory we own, so a corrupted or hostile pointer+ * cannot turn this into "run any executable on the box". `runtimeInstall.ts` writes the pointer and+ * asks this to learn what is already laid down.+ */+export function managedGridPath(): string | null {+ try {+ const recorded = readFileSync(join(env.ADAPTER_RUNTIME_DIR, 'current-grid'), 'utf-8').trim()+ if (recorded && recorded.startsWith(env.ADAPTER_RUNTIME_DIR + sep)) {+ accessSync(recorded, constants.X_OK)+ return recorded+ }+ } catch {+ // absent, unreadable, or not executable → there is no managed grid+ }+ return null+}++/**+ * The `grid` this daemon should run: the override, the managed runtime, the name on PATH, or —+ * last — the directory grid's own public installer uses (`lib/gridInstall.ts`), which a daemon+ * started from a launcher with launchd's bare PATH does not have. Named absolutely rather than by+ * extending PATH, so the fallback reaches exactly one known file and never whatever else that+ * directory holds. The managed runtime outranks it: once the pin is published the installer's+ * copy is only ever a fallback for a machine the pin could not reach.+ */+export function gridBinaryPath(processEnv: NodeJS.ProcessEnv = process.env): string {+ const override = processEnv.HARNESS_GRID_BIN?.trim()+ if (override) return override+ const managed = managedGridPath()+ if (managed) return managed+ if (binaryOnPath(GRID_BINARY, processEnv)) return GRID_BINARY+ // Keyed on the environment's HOME rather than `os.homedir()`, so a caller that hands in an+ // environment (the tests, a deliberately bare one) gets exactly what that environment can see.+ const home = processEnv.HOME?.trim()+ if (home) {+ const installed = join(home, '.local', 'bin', GRID_BINARY)+ try { accessSync(installed, constants.X_OK); return installed } catch { /* not there either */ }+ }+ return GRID_BINARY+}++/** Is there a `grid` to run at all? Asked by reading rather than by spawning, so a missing binary is+ * a sentence rather than a spawn error every caller has to recognise — and so a present-but-not-+ * executable one (EACCES, never ENOENT) is caught too. */+export function gridAvailable(processEnv: NodeJS.ProcessEnv = process.env): boolean {+ return binaryOnPath(gridBinaryPath(processEnv), processEnv)+}++/**+ * Which `grid` this machine would run, for a desktop that has to say so.+ *+ * `managed` is the runtime this daemon owns — the pin. `path` is one the user installed themselves,+ * or a developer's override: runnable, but not the pin, and not ours to keep current. `missing` is+ * nothing to run at all, which the picker and the Local model dialog need to know BEFORE they offer+ * to start an agent whose second step is `grid`.+ */+export type GridCliPresence = 'managed' | 'path' | 'missing'++export function gridCliPresence(processEnv: NodeJS.ProcessEnv = process.env): GridCliPresence {+ const binary = gridBinaryPath(processEnv)+ if (!binaryOnPath(binary, processEnv)) return 'missing'+ // An override is the developer's wherever it lives — under the runtime dir included. Only what the+ // pointer names is the pin.+ if (processEnv.HARNESS_GRID_BIN?.trim()) return 'path'+ return binary.startsWith(env.ADAPTER_RUNTIME_DIR + sep) ? 'managed' : 'path'+}diff --git a/cli/src/lib/gridExec.ts b/cli/src/lib/gridExec.tsindex 921265540..3e335da87 100644--- a/cli/src/lib/gridExec.ts+++ b/cli/src/lib/gridExec.ts@@ -20,14 +20,12 @@* coordination point: the pin has to move before or with it.*/import { spawn } from 'node:child_process'-import { accessSync, constants, readFileSync } from 'node:fs'-import { join, sep } from 'node:path'-import { env } from '../config/env.js'import { binaryOnPath } from './binaryOnPath.js'+import { GRID_NO_UPDATE_CHECK_VAR, gridBinaryPath, gridChildEnv } from './gridBinary.js'-/** The command, as it is named on PATH — the last resort of [gridBinaryPath], and the word the- * sign-out's own "nothing to run" sentence uses (`gridLogout.ts`). */-export const GRID_BINARY = 'grid'+// Which `grid` to run is gridBinary.ts's, which the core keeps for its launches; said again here for+// every grid call that imports it from this module.+export { GRID_BINARY, GRID_NO_UPDATE_CHECK_VAR, gridAvailable, gridBinaryPath, gridChildEnv, gridCliPresence, managedGridPath, type GridCliPresence } from './gridBinary.js'/*** The oldest `grid` this daemon can drive.@@ -47,24 +45,6 @@ const MAX_CAPTURED_CHARS = 64 * 1024* sign-in path, where a hung child would otherwise hang the command that spawned it. */const DEFAULT_TIMEOUT_MS = 30_000-/**- * grid's own update check, and the one switch that turns it off.- *- * A `grid` with a terminal on stderr looks for a newer release and, finding one, prints "run- * `grid update`" — and `grid update` replaces the binary IN PLACE, wherever `which grid` found it- * (autonomous-grid `cli/update.py`). Under a managed runtime that file is the pin, and the process- * most likely to read that line and obey it is an agent in a pane. So the check is off for every- * child this daemon spawns ([gridChildEnv]) and in every pane it launches (`engineLaunch.ts`), by- * the variable grid honours for it. The daemon's own spawns pipe stderr and would be spared anyway;- * saying it explicitly is what makes the pane and the daemon one rule.- */-export const GRID_NO_UPDATE_CHECK_VAR = 'GRID_NO_UPDATE_CHECK'--/** The environment a `grid` child gets: the caller's own, with the update check off. */-export function gridChildEnv(processEnv: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {- return { ...processEnv, [GRID_NO_UPDATE_CHECK_VAR]: '1' }-}-export type GridCode = 'OK' | 'GRID_CLI_MISSING' | 'GRID_CLI_OUTDATED' | 'GRID_FAILED'export interface GridResult {@@ -93,77 +73,6 @@ function capped(sofar: string, chunk: Buffer): string {return sofar.length >= MAX_CAPTURED_CHARS ? sofar : (sofar + chunk.toString()).slice(0, MAX_CAPTURED_CHARS)}-/**- * The managed grid — the runtime `current-grid` names — or null when there is none this daemon- * would trust.- *- * Containment-checked exactly like `nodeRuntime.managedNodePath`: a pointer file is only trusted- * when it names something INSIDE the runtime directory we own, so a corrupted or hostile pointer- * cannot turn this into "run any executable on the box". `runtimeInstall.ts` writes the pointer and- * asks this to learn what is already laid down.- */-export function managedGridPath(): string | null {- try {- const recorded = readFileSync(join(env.ADAPTER_RUNTIME_DIR, 'current-grid'), 'utf-8').trim()- if (recorded && recorded.startsWith(env.ADAPTER_RUNTIME_DIR + sep)) {- accessSync(recorded, constants.X_OK)- return recorded- }- } catch {- // absent, unreadable, or not executable → there is no managed grid- }- return null-}--/**- * The `grid` this daemon should run: the override, the managed runtime, the name on PATH, or —- * last — the directory grid's own public installer uses (`lib/gridInstall.ts`), which a daemon- * started from a launcher with launchd's bare PATH does not have. Named absolutely rather than by- * extending PATH, so the fallback reaches exactly one known file and never whatever else that- * directory holds. The managed runtime outranks it: once the pin is published the installer's- * copy is only ever a fallback for a machine the pin could not reach.- */-export function gridBinaryPath(processEnv: NodeJS.ProcessEnv = process.env): string {- const override = processEnv.HARNESS_GRID_BIN?.trim()- if (override) return override- const managed = managedGridPath()- if (managed) return managed- if (binaryOnPath(GRID_BINARY, processEnv)) return GRID_BINARY- // Keyed on the environment's HOME rather than `os.homedir()`, so a caller that hands in an- // environment (the tests, a deliberately bare one) gets exactly what that environment can see.- const home = processEnv.HOME?.trim()- if (home) {- const installed = join(home, '.local', 'bin', GRID_BINARY)- try { accessSync(installed, constants.X_OK); return installed } catch { /* not there either */ }- }- return GRID_BINARY-}--/** Is there a `grid` to run at all? Asked by reading rather than by spawning, so a missing binary is- * a sentence rather than a spawn error every caller has to recognise — and so a present-but-not-- * executable one (EACCES, never ENOENT) is caught too. */-export function gridAvailable(processEnv: NodeJS.ProcessEnv = process.env): boolean {- return binaryOnPath(gridBinaryPath(processEnv), processEnv)-}--/**- * Which `grid` this machine would run, for a desktop that has to say so.- *- * `managed` is the runtime this daemon owns — the pin. `path` is one the user installed themselves,- * or a developer's override: runnable, but not the pin, and not ours to keep current. `missing` is- * nothing to run at all, which the picker and the Local model dialog need to know BEFORE they offer- * to start an agent whose second step is `grid`.- */-export type GridCliPresence = 'managed' | 'path' | 'missing'--export function gridCliPresence(processEnv: NodeJS.ProcessEnv = process.env): GridCliPresence {- const binary = gridBinaryPath(processEnv)- if (!binaryOnPath(binary, processEnv)) return 'missing'- // An override is the developer's wherever it lives — under the runtime dir included. Only what the- // pointer names is the pin.- if (processEnv.HARNESS_GRID_BIN?.trim()) return 'path'- return binary.startsWith(env.ADAPTER_RUNTIME_DIR + sep) ? 'managed' : 'path'-}export interface GridExecOptions {/** Written to the child's stdin, which is then closed. For the token hand-off and nothing else. */diff --git a/cli/src/lib/gridFleetProtocol.ts b/cli/src/lib/gridFleetProtocol.tsnew file mode 100644index 000000000..12b3be670--- /dev/null+++ b/cli/src/lib/gridFleetProtocol.ts@@ -0,0 +1,8 @@+/**+ * The Model Manager's grid commands' handshake (`grid_fleet_capabilities`): which protocol they speak and+ * the longest a command may run. The socket answers it while the commands themselves are the models+ * service's (`gridFleetRpc.ts`, services/models.ts), so a Grid harness asking while models is down hears+ * the command refused, never "update Harness" (core/api.ts `MODELS_REQUESTS`).+ */+export const GRID_FLEET_PROTOCOL = 1+export const GRID_FLEET_MAX_TIMEOUT_MS = 30 * 60_000diff --git a/cli/src/lib/gridFleetRpc.ts b/cli/src/lib/gridFleetRpc.tsindex 5db78b430..230351acb 100644--- a/cli/src/lib/gridFleetRpc.ts+++ b/cli/src/lib/gridFleetRpc.ts@@ -1,9 +1,11 @@/** Grid's complete argv API, carried over the existing paired-machine connection. No shell. */import { spawn } from 'node:child_process'import { gridBinaryPath, gridChildEnv } from './gridExec.js'+import { GRID_FLEET_MAX_TIMEOUT_MS } from './gridFleetProtocol.js'++// The handshake's own module, which the socket answers it from (gridFleetProtocol.ts).+export { GRID_FLEET_MAX_TIMEOUT_MS, GRID_FLEET_PROTOCOL } from './gridFleetProtocol.js'-export const GRID_FLEET_PROTOCOL = 1-export const GRID_FLEET_MAX_TIMEOUT_MS = 30 * 60_000const MAX_OUTPUT = 512 * 1024export interface GridFleetRequest { args: string[]; timeoutMs: number; thinking?: boolean }export interface GridFleetResult { ok: boolean; code: number; stdout: string; stderr: string; error: string | null }diff --git a/cli/src/lib/gridModels.ts b/cli/src/lib/gridModels.tsindex 17d46f4fb..56c504ea8 100644--- a/cli/src/lib/gridModels.ts+++ b/cli/src/lib/gridModels.ts@@ -23,6 +23,7 @@ import { createHash, randomUUID } from 'node:crypto'import { mkdir, readdir, readFile, rename, writeFile } from 'node:fs/promises'import { dirname, join } from 'node:path'import { env as config } from '../config/env.js'+import { annotate, glanceFor, type AgentGridTarget, type GridAnnotation, type GridGlance, type GridNote } from './gridAnnotation.js'import { gridCredentialsPath } from './gridCredentials.js'import { signedInGridEmail } from './gridDerive.js'import { gridJson } from './gridExec.js'@@ -168,13 +169,8 @@ export type PrewarmOutcome =/** A grid as a launch names it: its network id (what it is tracked and persisted under) and its name. */export interface GridRef { networkId: string; gridName: string }-/** Where an agent's inference goes (`gridAssignment.ts`) — all a prewarm or a note needs of it. */-export interface AgentGridTarget { baseUrl: string; model: string | null }--/** What is said about an agent already on a grid model (issue 03): that grid's state, and a note when its- * model will not answer — every computer serving it seems offline, or the latest list no longer has it. */-export interface GridNote { reason: 'offline' | 'not_served'; model: string; machine?: string }-export interface GridAnnotation { state: PictureState; note?: GridNote }+// An agent's grid, and what its frame says of that grid: gridAnnotation.ts's, read in the core without this module.+export type { AgentGridTarget, GridAnnotation, GridGlance, GridNote }export interface GridModelsDeps {now: () => number@@ -248,6 +244,7 @@ export class GridModelsService {async warm(): Promise<void> {const folder = join(this.deps.dataDir(), PICTURES_DIR)const names = await readdir(folder).catch(() => [] as string[])+ let warmed = 0await Promise.all(names.filter((name) => name.endsWith('.json')).map(async (name) => {try {const saved = JSON.parse(await readFile(join(folder, name), 'utf8')) as SavedPicture@@ -255,8 +252,12 @@ export class GridModelsService {const gridName = typeof saved.name === 'string' ? saved.name : ''const tracked = await this.track({ id: saved.networkId, name: gridName, type: '' }, saved.own === true ? true : undefined)await this.view(tracked)+ warmed++} catch { /* not a picture this module wrote; the list will read that grid when asked */ }}))+ // Said like any change: the frames built before this landed carried no note, and a core that reads the+ // notes from models in its own process has heard nothing of these grids yet (core/modelsLink.ts).+ if (warmed) this.changed()}/** Every read is due again — for a caller that has just changed what a grid serves, or which grid is@@ -619,9 +620,12 @@ export class GridModelsService {/** The grid an agent's inference goes to: the tracked grid whose id is a segment of its relay's path. */private trackedFor(baseUrl: string): Tracked | null {- let segments: string[]- try { segments = new URL(baseUrl).pathname.split('/').filter(Boolean) } catch { return null }- return [...this.tracked.values()].find((tracked) => !tracked.id.startsWith(NAME_ONLY_PREFIX) && segments.includes(tracked.id)) ?? null+ return glanceFor([...this.tracked.values()].filter((tracked) => !tracked.id.startsWith(NAME_ONLY_PREFIX)), baseUrl)+ }++ /** As much of a tracked grid as an agent's frame and a keystroke read (gridAnnotation.ts). */+ private glance(tracked: Tracked): GridGlance {+ return { id: tracked.id, view: tracked.lastView, listed: tracked.picture.listAt !== null, asleep: tracked.picture.state === 'asleep' && !tracked.waking }}/**@@ -630,14 +634,19 @@ export class GridModelsService {*/annotation(target: AgentGridTarget | null | undefined): GridAnnotation | null {const tracked = target ? this.trackedFor(target.baseUrl) : null- const view = tracked?.lastView- if (!tracked || !view || !target) return null- if (!target.model || view.state === 'waking') return { state: view.state }- const row = servedRow(view.models, target.model)- if (row?.unavailable) return { state: view.state, note: { reason: 'offline', model: row.id, machine: row.unavailable.machine } }- // "No longer lists" needs a list: a grid never read says nothing about any model.- if (!row && tracked.picture.listAt !== null) return { state: view.state, note: { reason: 'not_served', model: target.model } }- return { state: view.state }+ return tracked && target ? annotate(this.glance(tracked), target) : null+ }++ /**+ * Every grid tracked here at a glance, for a core that reads agents' notes without this module: what+ * models in its own process tells the core whenever a picker would be told something new+ * (services/modelsProcess.ts). Each model is its id and the computer it waits for, nothing more.+ */+ glances(): GridGlance[] {+ return [...this.tracked.values()].filter((tracked) => !tracked.id.startsWith(NAME_ONLY_PREFIX)).map((tracked) => {+ const { view, ...rest } = this.glance(tracked)+ return { ...rest, view: view && { state: view.state, models: view.models.map(({ id, unavailable }) => unavailable ? { id, unavailable: { machine: unavailable.machine } } : { id }) } }+ })}/** A machine list this daemon just read (`GET /api/machines`, or null when signed out): which of the@@ -760,6 +769,11 @@ export function gridAnnotation(target: AgentGridTarget | null | undefined): Gridreturn service.annotation(target)}+/** Every tracked grid at a glance ([GridModelsService.glances]). */+export function gridGlances(): GridGlance[] {+ return service.glances()+}+/** The context window `model` was last reported with on `grid`, read without a credential. */export function gridContextWindow(grid: GridRef, model: string): Promise<number | undefined> {return service.contextWindow(grid, model)diff --git a/cli/src/lib/gridPicture.ts b/cli/src/lib/gridPicture.tsindex 217456427..08e747736 100644--- a/cli/src/lib/gridPicture.ts+++ b/cli/src/lib/gridPicture.ts@@ -9,6 +9,7 @@* answer or record, or this computer's own run records. Everything that is not evidence leaves the list* stale, never shorter, and never wakes anything.*/+import { idKey, type PictureState } from './gridAnnotation.js'import type { OfflineReading } from './gridPresence.js'import type { LastKnown, ReadNode } from './gridReader.js'@@ -38,12 +39,8 @@ export const GRID_LAST_KNOWN_MAX_AGE_MS = 29 * 24 * 60 * 60 * 1000/** Engines that are a router rather than a model (`grid-router` serves `auto`) are never offered. */const ROUTER_ENGINE = 'grid-router'-/**- * `awake` — the last read answered. `asleep` — the platform says it is resting. `unknown` — the last- * read failed any other way, or nothing has been read yet (the list shown, if any, is the last known).- * `waking` — a person asked for it to start (issue 03's explicit wake; never set by a read).- */-export type PictureState = 'awake' | 'asleep' | 'waking' | 'unknown'+// Where a picture's state is read without the pictures' code: an agent's frame (gridAnnotation.ts).+export type { PictureState }export interface PictureModel {/** The id without case — the join key across sources. Its spelling lives in `caseMap`. */@@ -112,9 +109,10 @@ export function withDecisions(picture: GridPicture, nodes: readonly ReadNode[]):return same ? picture : { ...picture, decisions }}-/** The join key for a model id across every source: trimmed, without case. (Not `localModels.ts`'s own- * private key, which also strips `.gguf` for a different comparison.) */-export const idKey = (id: string): string => id.trim().toLowerCase()+// The join key for a model id across every source: trimmed, without case (not `localModels.ts`'s own+// private key, which also strips `.gguf` for a different comparison). gridAnnotation.ts's, which the core+// reads an agent's note with.+export { idKey }const hasUpperCase = (id: string): boolean => id !== id.toLowerCase()/**diff --git a/cli/src/lib/launchers.ts b/cli/src/lib/launchers.tsnew file mode 100644index 000000000..ac8a225eb--- /dev/null+++ b/cli/src/lib/launchers.ts@@ -0,0 +1,86 @@+/**+ * The `harness` and `hn` launchers in the bin folder: repointing `harness` at the runtime it should run on,+ * and adding `hn` beside it on a machine installed before hn shipped.+ *+ * Its own module so the hn updater, which the core runs, can repair `hn` without loading the managed+ * runtimes' installer (runtimeInstall.ts), whose grid half is the models service's.+ */+import { accessSync, constants, linkSync, lstatSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'+import { env } from '../config/env.js'++/** The trailing `exec …` line, which is the only line any launcher we ship varies. */+const EXEC_LINE = /^exec .*$/m++/**+ * Repoints the `harness` launcher at [node].+ *+ * Three launcher shapes have shipped — the public installer's two-liner, `install-cli.sh`'s, and its+ * `--no-updates` variant carrying a comment block and `ADAPTER_UPDATE_DISABLE=true`. All three end in+ * a single `exec … cli.js "$@"` line with everything else preamble, so replacing ONLY that line+ * handles all three and preserves a developer's pin for free: the interpreter is repaired, and the+ * promise that no release reaches that computer on its own is untouched.+ */+export function ensureLauncher(node: string, log: (message: string) => void = () => {}): void {+ try {+ const launcher = join(env.HARNESS_BIN_DIR, 'harness')+ const current = readFileSync(launcher, 'utf-8')+ const cli = join(env.ADAPTER_CLI_DIR, 'cli.js')+ const exec = EXEC_LINE.exec(current)+ // Only ever rewrite a launcher that runs OUR bundle. Anything else at this path belongs to+ // somebody else, and a missing launcher means the CLI is being run some other way — writing one+ // nobody asked for is a different feature.+ if (!exec || !exec[0].includes(cli)) return++ const next = current.replace(EXEC_LINE, `exec ${shellQuote(node)} ${shellQuote(cli)} "$@"`)+ if (next === current) return++ const temporary = `${launcher}.tmp-${process.pid}`+ writeFileSync(temporary, next, { mode: 0o755 })+ renameSync(temporary, launcher)+ log(` ✓ repointed ${launcher} at ${node}`)+ } catch {+ // A read-only bin dir, a launcher owned by another user — none of it is worth failing a start.+ }+}++/**+ * Add the short terminal command to an existing installation. Self-update replaces only the JS+ * bundles, so machines installed before hn shipped never re-run the installer's launcher step.+ * Run this on entry to the installed bundle, including daemon handoffs and an already-current+ * `harness update`. A checkout or update canary must never change the real installation.+ *+ * Delegate through the existing harness launcher so runtime repairs and --no-updates pins apply+ * equally to hn. Publish the complete script without replacing any existing file or symlink.+ */+export function ensureHnLauncher(scriptPath: string): boolean {+ let temporary: string | undefined+ try {+ const cli = join(env.ADAPTER_CLI_DIR, 'cli.js')+ if (realpathSync(scriptPath) !== realpathSync(cli)) return false+ const hn = join(env.HARNESS_BIN_DIR, 'hn')+ try { lstatSync(hn); return false } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') return false+ }+ const launcher = join(env.HARNESS_BIN_DIR, 'harness')+ accessSync(launcher, constants.X_OK)+ const exec = EXEC_LINE.exec(readFileSync(launcher, 'utf8'))+ if (!exec || !(exec[0].includes(cli) || exec[0].includes(shellQuote(cli)))) return false++ temporary = mkdtempSync(join(env.HARNESS_BIN_DIR, '.hn-'))+ const staged = join(temporary, 'hn')+ writeFileSync(staged, `#!/bin/sh\nexec ${shellQuote(launcher)} tui "$@"\n`, { mode: 0o755 })+ // link, unlike rename, fails if another process or the user has already created hn.+ linkSync(staged, hn)+ return true+ } catch {+ // A read-only bin dir or a racing install must not prevent the CLI or daemon from running.+ return false+ } finally {+ if (temporary) { try { rmSync(temporary, { recursive: true, force: true }) } catch { /* best effort */ } }+ }+}++function shellQuote(value: string): string {+ return `'${value.replace(/'/g, `'\\''`)}'`+}diff --git a/cli/src/lib/localModels.ts b/cli/src/lib/localModels.tsindex c3b887c5d..40544b59b 100644--- a/cli/src/lib/localModels.ts+++ b/cli/src/lib/localModels.ts@@ -12,8 +12,12 @@ import { processExists } from './processLiveness.js'import type { LocalRecord, PictureState } from './gridPicture.js'import { displayModelName } from './gridReader.js'import { readEnvExports } from './gridWake.js'+import { MIN_CODING_CONTEXT } from './codingContext.js'import { APP_LABEL, AppStartError, GRID_LABEL, appContext, readAppRecords, writeAppRecords, type AppEngine, type AppEngineOps, type AppEngineRecord, type AppModel } from './appModels.js'+// Its own module, so the API launches the core keeps need not load this one (codingContext.ts).+export { MIN_CODING_CONTEXT }+const GiB = 1024 ** 3const obj = (v: unknown): Record<string, any> => v && typeof v === 'object' && !Array.isArray(v) ? v : {}const rows = (v: unknown): Record<string, any>[] => Array.isArray(v) ? v.map(obj) : []@@ -27,11 +31,6 @@ const validArg = (v: string): boolean => !!v && !v.startsWith('-') && !/[\x00-\x/** `grid info` statuses of a grid that is not up. Grid refuses `engines` and `join` on one, and* names `grid start` as the way back. Anything else unknown stays unknown rather than "down". */const DOWN = new Set(['stopped', 'asleep'])-/** The smallest context a coding agent can work in. Codex, Claude Code and OpenCode each open a- * session with a system prompt and tool list of several thousand tokens and grow from there; Ollama's- * own guides for all three put the floor at 64K, and below it a session survives a few turns and then- * fails. Every model offered here is one this machine can give at least this much. */-export const MIN_CODING_CONTEXT = 64 * 1024/** Where a start begins for a file whose header could not be read: the size a 64 GB Mac was seen* to hold for a 35B model, one step above the floor. */const UNREAD_CONTEXT = 128 * 1024diff --git a/cli/src/lib/newAgentModel.spec.ts b/cli/src/lib/newAgentModel.spec.tsindex 36e174232..baed6d9be 100644--- a/cli/src/lib/newAgentModel.spec.ts+++ b/cli/src/lib/newAgentModel.spec.ts@@ -1,15 +1,10 @@-import { beforeEach, describe, expect, it, vi } from 'vitest'+import { describe, expect, it } from 'vitest'import { ENGINES } from '../engines/types.js'import { gridCapableEngines } from './gridLaunch.js'-import { forgetGridModels, listGridModels } from './gridModels.js'-import { resolveGridTarget } from './gridTarget.js'-import { parseNewAgentModel, resolveNewAgentModel } from './newAgentModel.js'+import { parseNewAgentModel } from './newAgentModel.js'-vi.mock('./gridModels.js', () => ({ forgetGridModels: vi.fn(), listGridModels: vi.fn() }))-vi.mock('./gridTarget.js', () => ({ resolveGridTarget: vi.fn() }))const choice = { gridModel: 'Qwen-35B', gridName: 'my-grid' }const target = { networkId: 'g', networkName: 'my-grid', baseUrl: 'https://fixture.invalid/relay/v1', apiKey: 'fixture-key', model: 'Qwen-35B' }-beforeEach(() => vi.resetAllMocks())describe('new-session model routing', () => {it('keeps ordinary launches absent and normalizes the explicit selection', () => {@@ -26,24 +21,4 @@ describe('new-session model routing', () => {it.each([{ grid: null }, { grid: target }, { codexHome: '/profiles/work' }])('refuses conflicting routing: %j', conflict => {expect(parseNewAgentModel('codex', { ...choice, ...conflict }).state).toBe('invalid')})- it('resolves the exact model on another machine through the chosen grid', async () => {- vi.mocked(listGridModels).mockResolvedValue([{ id: 'Qwen-35B', node: 'Mac Studio' }])- vi.mocked(resolveGridTarget).mockResolvedValue(target)- expect(await resolveNewAgentModel({ model: 'Qwen-35B', grid: 'my-grid' })).toEqual(target)- expect(forgetGridModels).toHaveBeenCalledOnce()- expect(listGridModels).toHaveBeenCalledWith('my-grid')- expect(resolveGridTarget).toHaveBeenCalledWith('my-grid', 'Qwen-35B')- })- it('refuses a stopped model without resolving a fallback', async () => {- vi.mocked(listGridModels).mockResolvedValue([{ id: 'Another-model', node: 'Mac Studio' }])- expect(await resolveNewAgentModel({ model: 'Qwen-35B', grid: 'my-grid' })).toBeNull()- expect(resolveGridTarget).not.toHaveBeenCalled()- })- it('preserves a missing endpoint and failures for the caller to refuse', async () => {- vi.mocked(listGridModels).mockResolvedValue([{ id: 'Qwen-35B', node: '' }])- vi.mocked(resolveGridTarget).mockResolvedValue(null)- expect(await resolveNewAgentModel({ model: 'Qwen-35B', grid: 'my-grid' })).toBeNull()- vi.mocked(listGridModels).mockRejectedValue(new Error('offline'))- await expect(resolveNewAgentModel({ model: 'Qwen-35B', grid: 'my-grid' })).rejects.toThrow('offline')- })})diff --git a/cli/src/lib/newAgentModel.ts b/cli/src/lib/newAgentModel.tsindex 77c998922..a11d6d940 100644--- a/cli/src/lib/newAgentModel.ts+++ b/cli/src/lib/newAgentModel.ts@@ -1,8 +1,8 @@import type { AgentEngine } from '../engines/types.js'-import { gridCapableEngines, type GridLaunchOverride } from './gridLaunch.js'-import { forgetGridModels, listGridModels } from './gridModels.js'-import { resolveGridTarget } from './gridTarget.js'+import { gridCapableEngines } from './gridLaunch.js'+/** A model picked for a new agent, and the grid serving it. Where its inference goes is the models+ * service's to resolve (services/models.ts `launchTarget`), on the machine the agent runs on. */export interface NewAgentModel { model: string; grid: string }/** Model routing is resolved on the agent's machine; the model can live elsewhere.@@ -23,12 +23,3 @@ export function parseNewAgentModel(engine: AgentEngine, payload: Record<string,}return { state: 'ok', selection: { model: payload.gridModel.trim(), grid: payload.gridName.trim() } }}--export async function resolveNewAgentModel(selection: NewAgentModel): Promise<GridLaunchOverride | null> {- // Refresh at launch: a model stopped after opening the picker must not silently- // fall back to a subscription or to the grid's default router.- forgetGridModels();- const models = await listGridModels(selection.grid);- if (!models.some((model) => model.id === selection.model)) return null;- return resolveGridTarget(selection.grid, selection.model);-}diff --git a/cli/src/lib/runtimeInstall.ts b/cli/src/lib/runtimeInstall.tsindex b65ebd86e..785f79f59 100644--- a/cli/src/lib/runtimeInstall.ts+++ b/cli/src/lib/runtimeInstall.ts@@ -1,5 +1,5 @@import { spawn } from 'node:child_process'-import { accessSync, chmodSync, constants, existsSync, linkSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs'+import { chmodSync, existsSync, mkdirSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs'import { dirname, join, sep } from 'node:path'import { env } from '../config/env.js'@@ -334,78 +334,6 @@ export function startGridPinRecheck(options: { ensure?: () => Promise<unknown>;return () => clearInterval(timer)}-/** The trailing `exec …` line, which is the only line any launcher we ship varies. */-const EXEC_LINE = /^exec .*$/m--/**- * Repoints the `harness` launcher at [node].- *- * Three launcher shapes have shipped — the public installer's two-liner, `install-cli.sh`'s, and its- * `--no-updates` variant carrying a comment block and `ADAPTER_UPDATE_DISABLE=true`. All three end in- * a single `exec … cli.js "$@"` line with everything else preamble, so replacing ONLY that line- * handles all three and preserves a developer's pin for free: the interpreter is repaired, and the- * promise that no release reaches that computer on its own is untouched.- */-export function ensureLauncher(node: string, log: (message: string) => void = () => {}): void {- try {- const launcher = join(env.HARNESS_BIN_DIR, 'harness')- const current = readFileSync(launcher, 'utf-8')- const cli = join(env.ADAPTER_CLI_DIR, 'cli.js')- const exec = EXEC_LINE.exec(current)- // Only ever rewrite a launcher that runs OUR bundle. Anything else at this path belongs to- // somebody else, and a missing launcher means the CLI is being run some other way — writing one- // nobody asked for is a different feature.- if (!exec || !exec[0].includes(cli)) return-- const next = current.replace(EXEC_LINE, `exec ${shellQuote(node)} ${shellQuote(cli)} "$@"`)- if (next === current) return-- const temporary = `${launcher}.tmp-${process.pid}`- writeFileSync(temporary, next, { mode: 0o755 })- renameSync(temporary, launcher)- log(` ✓ repointed ${launcher} at ${node}`)- } catch {- // A read-only bin dir, a launcher owned by another user — none of it is worth failing a start.- }-}--/**- * Add the short terminal command to an existing installation. Self-update replaces only the JS- * bundles, so machines installed before hn shipped never re-run the installer's launcher step.- * Run this on entry to the installed bundle, including daemon handoffs and an already-current- * `harness update`. A checkout or update canary must never change the real installation.- *- * Delegate through the existing harness launcher so runtime repairs and --no-updates pins apply- * equally to hn. Publish the complete script without replacing any existing file or symlink.- */-export function ensureHnLauncher(scriptPath: string): boolean {- let temporary: string | undefined- try {- const cli = join(env.ADAPTER_CLI_DIR, 'cli.js')- if (realpathSync(scriptPath) !== realpathSync(cli)) return false- const hn = join(env.HARNESS_BIN_DIR, 'hn')- try { lstatSync(hn); return false } catch (error) {- if ((error as NodeJS.ErrnoException).code !== 'ENOENT') return false- }- const launcher = join(env.HARNESS_BIN_DIR, 'harness')- accessSync(launcher, constants.X_OK)- const exec = EXEC_LINE.exec(readFileSync(launcher, 'utf8'))- if (!exec || !(exec[0].includes(cli) || exec[0].includes(shellQuote(cli)))) return false-- temporary = mkdtempSync(join(env.HARNESS_BIN_DIR, '.hn-'))- const staged = join(temporary, 'hn')- writeFileSync(staged, `#!/bin/sh\nexec ${shellQuote(launcher)} tui "$@"\n`, { mode: 0o755 })- // link, unlike rename, fails if another process or the user has already created hn.- linkSync(staged, hn)- return true- } catch {- // A read-only bin dir or a racing install must not prevent the CLI or daemon from running.- return false- } finally {- if (temporary) { try { rmSync(temporary, { recursive: true, force: true }) } catch { /* best effort */ } }- }-}--function shellQuote(value: string): string {- return `'${value.replace(/'/g, `'\\''`)}'`-}+// The launchers are launchers.ts's: the hn updater, which the core runs, repairs them without loading the+// managed runtimes' code, which grid's half of is the models service's (docs/design/2026-10-06-core-boundary-next.md, step 7).+export { ensureHnLauncher, ensureLauncher } from './launchers.js'diff --git a/cli/src/lib/setUpWithin.spec.ts b/cli/src/lib/setUpWithin.spec.tsnew file mode 100644index 000000000..0df70a644--- /dev/null+++ b/cli/src/lib/setUpWithin.spec.ts@@ -0,0 +1,30 @@+import { describe, expect, it, vi } from 'vitest'+import { setUpWithin } from './setUpWithin.js'++describe('setUpWithin: a set-up a create waits for, but not for long', () => {+ it('answers done once a quick set-up lands', async () => {+ await expect(setUpWithin(async () => ({ status: 'converged' }), 1_000)).resolves.toBe('done')+ })++ it('stops waiting at the bound and leaves the set-up running', async () => {+ vi.useFakeTimers()+ try {+ let finish!: () => void+ const running = new Promise<void>((resolve) => { finish = resolve })+ let landed = false+ const waited = setUpWithin(() => running.then(() => { landed = true }), 8_000)+ await vi.advanceTimersByTimeAsync(8_000)+ await expect(waited).resolves.toBe('pending')+ finish()+ await running+ await Promise.resolve()+ expect(landed).toBe(true)+ } finally {+ vi.useRealTimers()+ }+ })++ it('never throws: a failed set-up is for the next use of grid to say', async () => {+ await expect(setUpWithin(async () => { throw new Error('offline') }, 1_000)).resolves.toBe('done')+ })+})diff --git a/cli/src/lib/setUpWithin.ts b/cli/src/lib/setUpWithin.tsnew file mode 100644index 000000000..d5eec66c8--- /dev/null+++ b/cli/src/lib/setUpWithin.ts@@ -0,0 +1,19 @@+/**+ * Start a grid set-up and wait for it at most [waitMs]. Past that it carries on — the access queue+ * remembers it when it lands, and a later `ensure` waits for it — so a caller that must answer in seconds+ * (a Model Manager being created) is never held for a first install. Never throws: what failed is said by+ * the next thing that uses grid.+ *+ * Its own module because the create that waits is the core's, and grid's set-up is the models service's,+ * in a process of its own (docs/design/2026-10-06-core-boundary-next.md, step 7): the core waits on the+ * port's `ensure` through this, and never loads the set-up's code.+ */+export async function setUpWithin(setUp: () => Promise<unknown>, waitMs: number): Promise<'done' | 'pending'> {+ let timer: NodeJS.Timeout | undefined+ const waited = new Promise<'pending'>((resolve) => { timer = setTimeout(() => resolve('pending'), waitMs) })+ try {+ return await Promise.race([setUp().then(() => 'done' as const, () => 'done' as const), waited])+ } finally {+ clearTimeout(timer)+ }+}diff --git a/cli/src/serviceProcess.ts b/cli/src/serviceProcess.tsindex 082724a06..2856a46e3 100644--- a/cli/src/serviceProcess.ts+++ b/cli/src/serviceProcess.ts@@ -34,6 +34,7 @@ export const SERVICE_RUNNERS: ReadonlyMap<string, () => Promise<Runner>> = new M['store', async () => (await import('./services/storeProcess.js')).runStoreService],['teams', async () => (await import('./services/teamsProcess.js')).runTeamsService],['gateway', async () => (await import('./gateway/gatewayProcess.js')).runGatewayService],+ ['models', async () => (await import('./services/modelsProcess.js')).runModelsService],])export interface ServiceProcessDeps {diff --git a/cli/src/services/AGENTS.md b/cli/src/services/AGENTS.mdindex 8aa3c365e..0f081063c 100644--- a/cli/src/services/AGENTS.md+++ b/cli/src/services/AGENTS.md@@ -43,12 +43,13 @@ let several people build features at once without touching the core or each otheA service that can crash natively, hang or leak should run in a process of its own, where it costs onlythat process. A process per risk, not per feature: search (native `node:sqlite`), the viewers (their-servers) with the Store (its minutes-long installs), the teams' prompt scopes, and the edge host, one-process for the light services that only answer requests (workspaces, usage, the monitor, the project-readers). A fault in one of the edge host's services can cost the others in it, never the core. Every-service in `KNOWN_SERVICES` runs out of the core's process by default, unless `HARNESSD_SERVICES` names-a subset, by service (`search,usage`) or by process (`edge`), and `HARNESSD_SERVICES=none` runs them-all inside the core's process (for debugging or a quick way back).+servers) with the Store (its minutes-long installs), the teams' prompt scopes, models (grid's installs,+downloads and commands), and the edge host, one process for the light services that only answer requests+(workspaces, usage, the monitor, the project readers). A fault in one of the edge host's services can+cost the others in it, never the core. Every service in `KNOWN_SERVICES` runs out of the core's process+by default, unless `HARNESSD_SERVICES` names a subset, by service (`search,usage`) or by process+(`edge`), and `HARNESSD_SERVICES=none` runs them all inside the core's process (for debugging or a quick+way back).- `src/harnessd/services.ts` runs it (`SERVICE_HOSTS`: each process, the services it hosts and itsmemory budget, one heartbeat for all of them). The core routes the requests it declared (its@@ -88,6 +89,15 @@ all inside the core's process (for debugging or a quick way back).the last ones and its port answers from them, or from the fallbacks before it has heard any. Theprocess asks the core for everything it should hold each time it connects, which a restartedprocess needs anyway. `e2e/viewersProcess.e2e.ts` proves it with a real harness agent's viewer.+- Both at once, and a service that asks the core for what only the core holds: models+ (`src/services/modelsProcess.ts`, `src/core/modelsLink.ts`). What a frame and a keystroke read (an+ agent's grid note, whether its grid sleeps) is told to the core as a glance at every grid whenever it+ changes; grid's set-up and where an agent on a grid model sends its inference are asked when needed, each+ with a wait long enough for what it does (`LONG_ANSWERS` in `src/core/api.ts`: the half minute any other+ answer gets would cut a grid install short). Models asks the core for the sign-in each time it needs it,+ and work that belongs to one connection's request (a Grid harness's command) is keyed by the connection+ and request id the core gives every request (`Asker`). `e2e/serviceProcesses.e2e.ts` proves it: a create+ on a grid model while models is killed answers GRID_UNAVAILABLE, and every agent works on.- A service the core only gives commands to needs nothing kept for it while it is down. Workspaces(`src/services/workspacesProcess.ts`, `src/core/workspacesLink.ts`) is told to name branches andwhen to sweep. A command that destroys something is never held or replayed, and what it must knowdiff --git a/cli/src/services/inline.spec.ts b/cli/src/services/inline.spec.tsindex 6db81e4ae..e5e4c3e37 100644--- a/cli/src/services/inline.spec.ts+++ b/cli/src/services/inline.spec.ts@@ -1,6 +1,7 @@import { describe, expect, it } from 'vitest'import { startGateway } from '../gateway/start.js'import * as inline from './inline.js'+import { startModels } from './models.js'import { startMonitor } from './monitor.js'import { startProjects } from './projects.js'import { startSearch } from './search.js'@@ -11,6 +12,6 @@ import { startWorkspaces } from './workspaces.js'describe('the services the core runs in its own process only when they do not run in theirs', () => {it('are their own starts, unchanged: the same services either way', () => {- expect({ ...inline }).toEqual({ startGateway, startMonitor, startProjects, startSearch, startStore, startUsage, startViewers, startWorkspaces })+ expect({ ...inline }).toEqual({ startGateway, startModels, startMonitor, startProjects, startSearch, startStore, startUsage, startViewers, startWorkspaces })})})diff --git a/cli/src/services/inline.ts b/cli/src/services/inline.tsindex 2d933f96b..b5de17ba3 100644--- a/cli/src/services/inline.ts+++ b/cli/src/services/inline.ts@@ -13,6 +13,7 @@* declared in core/api.ts, which it loads either way.*/export { startGateway } from '../gateway/start.js'+export { startModels } from './models.js'export { startMonitor } from './monitor.js'export { startProjects } from './projects.js'export { startSearch } from './search.js'diff --git a/cli/src/services/models.spec.ts b/cli/src/services/models.spec.tsindex a654ca4a2..71c12cab3 100644--- a/cli/src/services/models.spec.ts+++ b/cli/src/services/models.spec.ts@@ -5,25 +5,27 @@ import { createServiceHost } from '../core/serviceHost.js'import { installedDsh } from '../dsh/installed.js'import { appEngineOps, scanAppModels } from '../lib/appModels.js'import { createGridAccess, gridNamesLocal, reconcileGridAttach, type GridAttachResult } from '../lib/gridAttach.js'-import { resetGridDeriveMemo, signedInGridEmail } from '../lib/gridDerive.js'+import { deriveHarnessGridName, resetGridDeriveMemo, signedInGridEmail } from '../lib/gridDerive.js'import { ensureHarnessGrid } from '../lib/gridEnsure.js'-import { gridAvailable } from '../lib/gridExec.js'+import { gridAvailable, managedGridPath } from '../lib/gridExec.js'+import { GridFleetRpc } from '../lib/gridFleetRpc.js'import { handOffToGrid } from '../lib/gridHandoff.js'import { gridCapableEngines } from '../lib/gridLaunch.js'import { ensureGridInstalled } from '../lib/gridInstall.js'import { clearGridMcpUrlCache } from '../lib/gridMcpUrl.js'import {- forgetGridModels, gridAnnotation, gridInventory, keystrokePrewarm, listAllGridModels, onGridModelsChanged, presentGridSections, warmGridModels,- type GridSection,+ forgetGridModels, gridAnnotation, gridInventory, keystrokePrewarm, listAllGridModels, listGridModels, observeMachineList, onGridModelsChanged,+ presentGridSections, retargetPrewarm, warmGridModels, type GridSection,} from '../lib/gridModels.js'+import { resolveGridTarget } from '../lib/gridTarget.js'import type { RegisteredSession } from '../lib/registry.js'import type { RuntimeModelOption } from '../lib/runtimeProfile.js'-import { ensureManagedGrid } from '../lib/runtimeInstall.js'+import { ensureManagedGrid, startGridPinRecheck } from '../lib/runtimeInstall.js'import { apiConnectionsRequest } from '../lib/apiConnections.js'import { apiModelsRequest, rememberSavedApis } from '../lib/apiModels.js'import { linkCodexProfile, listCodexProfiles } from '../lib/codexProfiles.js'import { fakeCore } from '../testing/fakeCore.js'-import { compactRuntimePickerModels, MODELS_REQUESTS, startModels } from './models.js'+import { compactRuntimePickerModels, launchTarget, MODELS_REQUESTS, startModels } from './models.js'const access = vi.hoisted(() => ({ ensure: vi.fn(async (_request?: { ownGrid?: boolean }): Promise<GridAttachResult> => ({ status: 'converged', name: 'grid-1', detail: 'ok' })) }))vi.mock('../lib/gridAttach.js', () => ({@@ -31,9 +33,16 @@ vi.mock('../lib/gridAttach.js', () => ({gridNamesLocal: vi.fn(() => ['grid-1']),reconcileGridAttach: vi.fn(async () => ({ status: 'signed-in', name: 'grid-1', detail: 'ok' })),}))-vi.mock('../lib/gridDerive.js', () => ({ resetGridDeriveMemo: vi.fn(), signedInGridEmail: vi.fn(() => '[email protected]') }))+vi.mock('../lib/gridDerive.js', () => ({ deriveHarnessGridName: vi.fn(async () => null), resetGridDeriveMemo: vi.fn(), signedInGridEmail: vi.fn(() => '[email protected]') }))vi.mock('../lib/gridEnsure.js', () => ({ ensureHarnessGrid: vi.fn(async () => 'converged') }))-vi.mock('../lib/gridExec.js', () => ({ gridAvailable: vi.fn(() => true), gridCliPresence: vi.fn(() => 'managed') }))+vi.mock('../lib/gridExec.js', () => ({ gridAvailable: vi.fn(() => true), gridCliPresence: vi.fn(() => 'managed'), managedGridPath: vi.fn(() => null) }))+/** The Model Manager's grid commands: what each job was run as, and what it answers. */+const fleet = vi.hoisted(() => ({ run: vi.fn(async (..._args: unknown[]): Promise<Record<string, unknown>> => ({ ok: true, code: 0, stdout: '[]', stderr: '', error: null })), cancel: vi.fn((..._args: unknown[]) => true) }))+vi.mock('../lib/gridFleetRpc.js', async (real) => ({+ ...await real<object>(),+ GridFleetRpc: vi.fn(class { run = fleet.run; cancel = fleet.cancel }),+}))+vi.mock('../lib/gridTarget.js', () => ({ resolveGridTarget: vi.fn(async () => null) }))vi.mock('../lib/gridHandoff.js', () => ({ handOffToGrid: vi.fn(async () => ({ ok: true })) }))vi.mock('../lib/gridInstall.js', () => ({ ensureGridInstalled: vi.fn(async () => ({ status: 'present', message: '' })) }))vi.mock('../lib/gridMcpUrl.js', () => ({ clearGridMcpUrlCache: vi.fn() }))@@ -43,11 +52,14 @@ vi.mock('../lib/gridModels.js', () => ({gridInventory: vi.fn(),keystrokePrewarm: vi.fn(async () => 'started'),listAllGridModels: vi.fn(async () => []),+ listGridModels: vi.fn(async () => []),+ observeMachineList: vi.fn(),onGridModelsChanged: vi.fn(),+ retargetPrewarm: vi.fn(async () => 'fired'),presentGridSections: vi.fn((sections: unknown[]) => sections),warmGridModels: vi.fn(async () => {}),}))-vi.mock('../lib/runtimeInstall.js', () => ({ ensureManagedGrid: vi.fn(async () => {}) }))+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[] }))vi.mock('../lib/apiConnections.js', () => ({@@ -191,6 +203,12 @@ describe('the models service', () => {expect(gridAnnotation).not.toHaveBeenCalledWith(undefined)})+ it('tells the core the windows\' lists may have changed, whatever the agents', () => {+ const { core, changed } = setup()+ changed()+ expect(core.clients.gridModelsChanged).toHaveBeenCalledOnce()+ })+it('forgets an agent that left a grid, so its next appearance is announced', () => {const { core, list, changed } = setup([onGrid('a1', 'awake')])changed()@@ -209,37 +227,173 @@ describe('the models service', () => {})})+ describe('the managed grid\'s pin', () => {+ it('follows a managed grid\'s pin as it starts and every recheck after, and leaves a machine with none alone', async () => {+ setup()+ expect(ensureManagedGrid).not.toHaveBeenCalled()+ const recheck = vi.mocked(startGridPinRecheck).mock.calls.at(-1)![0]!.ensure!+ vi.mocked(managedGridPath).mockReturnValue('/runtime/grid-0.3.49/bin/grid')+ try {+ await recheck()+ expect(ensureManagedGrid).toHaveBeenCalledOnce()+ vi.mocked(ensureManagedGrid).mock.calls[0]![0]!('pinned 0.3.49')+ expect(console.log).toHaveBeenCalledWith('[grid-runtime] pinned 0.3.49')+ setup()+ expect(ensureManagedGrid).toHaveBeenCalledTimes(2)+ } finally {+ vi.mocked(managedGridPath).mockReturnValue(null)+ }+ })+ })+describe('its port', () => {- it('has grid ready through the one access, and says offline whether grid is set up', async () => {+ it('has grid ready through the one access', async () => {const { port } = setup()expect(await port.ensure({ ownGrid: true })).toMatchObject({ status: 'converged' })expect(access.ensure).toHaveBeenCalledWith({ ownGrid: true })- expect(port.setUp()).toBe(true)- vi.mocked(signedInGridEmail).mockReturnValueOnce(null)- expect(port.setUp()).toBe(false)- vi.mocked(gridAvailable).mockReturnValueOnce(false)- expect(port.setUp()).toBe(false)})- it('starts a sleeping grid while someone types, ignoring a prewarm that fails, and forgets the web tools on sign-out', async () => {+ it('reads an agent\'s note off the pictures, and starts a sleeping grid while someone types, ignoring a prewarm that fails', async () => {const { port } = setup()- const grid = { networkId: 'n1', model: 'big' } as never+ const grid = { baseUrl: 'https://fixture.invalid/g/n1/relay/v1', model: 'big' }+ expect(port.annotation({ state: 'asleep' } as never)).toEqual({ state: 'asleep' })port.prewarm(grid)expect(keystrokePrewarm).toHaveBeenCalledWith(grid)vi.mocked(keystrokePrewarm).mockRejectedValueOnce(new Error('asleep'))port.prewarm(grid)await Promise.resolve()+ })++ it('starts the grid an agent was just moved onto, ignoring a prewarm that fails, and forgets the web tools on sign-out', async () => {+ const { port } = setup()+ const launch = { networkId: 'n1', networkName: 'mine', baseUrl: 'https://fixture.invalid/g/n1/relay/v1', apiKey: 'k', model: 'big' }+ port.moved(launch)+ expect(retargetPrewarm).toHaveBeenCalledWith(launch)+ vi.mocked(retargetPrewarm).mockRejectedValueOnce(new Error('offline'))+ port.moved(launch)+ await Promise.resolve()port.signedOut()expect(clearGridMcpUrlCache).toHaveBeenCalledTimes(1)})++ it('hears which of the account\'s computers seem offline from the machine list the core read', () => {+ const { port } = setup()+ port.machines({ data: { machines: [] } }, 'computer-here')+ expect(observeMachineList).toHaveBeenCalledWith({ data: { machines: [] } }, 'computer-here')+ })++ it('names the account\'s grid as the backend did, else as this machine works it out', async () => {+ const told = setup([], { account: { privateGridName: vi.fn(async () => 'mine') } })+ expect(await told.port.privateGridName()).toBe('mine')+ expect(deriveHarnessGridName).not.toHaveBeenCalled()+ vi.mocked(deriveHarnessGridName).mockResolvedValueOnce('derived-1a2b3c4d')+ expect(await setup().port.privateGridName()).toBe('derived-1a2b3c4d')+ })++ it('builds the lists the windows are pushed from the pictures as they stand, in both forms', async () => {+ const sections = [section('mine', true, [{ id: 'Small-Q4', node: 'mac' }])]+ vi.mocked(listAllGridModels).mockResolvedValueOnce(sections)+ const { port } = setup([], { account: { privateGridName: vi.fn(async () => 'mine') } })+ const lists = await port.lists()+ expect(listAllGridModels).toHaveBeenCalledWith('mine', { refresh: false })+ expect(lists.plain).toMatchObject({ gridName: 'mine', models: [{ id: 'Small-Q4', node: 'mac' }] })+ expect(lists.rowState).toMatchObject({ gridName: 'mine', grids: sections })+ expect(presentGridSections).toHaveBeenCalledWith(sections, { rowState: false })+ expect(presentGridSections).toHaveBeenCalledWith(sections, { rowState: true })+ })++ describe('where an agent on a grid model sends its inference', () => {+ const target = { networkId: 'g', networkName: 'my-grid', baseUrl: 'https://fixture.invalid/relay/v1', apiKey: 'fixture-key', model: 'Qwen-35B' }++ it('a new agent: the exact model, refreshed, on the grid it was picked from', async () => {+ vi.mocked(listGridModels).mockResolvedValueOnce([{ id: 'Qwen-35B', node: 'Mac Studio' }])+ vi.mocked(resolveGridTarget).mockResolvedValueOnce(target)+ const { port } = setup()+ expect(await port.launchTarget({ model: 'Qwen-35B', grid: 'my-grid' })).toEqual(target)+ expect(forgetGridModels).toHaveBeenCalledOnce()+ expect(listGridModels).toHaveBeenCalledWith('my-grid')+ expect(resolveGridTarget).toHaveBeenCalledWith('my-grid', 'Qwen-35B')+ })++ it('a new agent: a stopped model resolves nothing, and a failure is the caller\'s to refuse', async () => {+ vi.mocked(listGridModels).mockResolvedValueOnce([{ id: 'Another-model', node: 'Mac Studio' }])+ expect(await launchTarget({ model: 'Qwen-35B', grid: 'my-grid' })).toBeNull()+ expect(resolveGridTarget).not.toHaveBeenCalled()+ vi.mocked(listGridModels).mockResolvedValueOnce([{ id: 'Qwen-35B', node: '' }])+ expect(await launchTarget({ model: 'Qwen-35B', grid: 'my-grid' })).toBeNull()+ vi.mocked(listGridModels).mockRejectedValueOnce(new Error('offline'))+ await expect(launchTarget({ model: 'Qwen-35B', grid: 'my-grid' })).rejects.toThrow('offline')+ })++ it("a move signs grid in first — with the account's own grid only when the model is on it", async () => {+ vi.mocked(resolveGridTarget).mockResolvedValue(target)+ try {+ const { port } = setup([], { account: { privateGridName: vi.fn(async () => 'mine') } })+ expect(await port.moveTarget({ gridName: 'team-grid-0000aaaa', model: 'Shared-Model' })).toEqual({ target })+ expect(resolveGridTarget).toHaveBeenLastCalledWith('team-grid-0000aaaa', 'Shared-Model')+ expect(await port.moveTarget({ gridName: null, model: 'Own-Model' })).toEqual({ target })+ expect(resolveGridTarget).toHaveBeenLastCalledWith('mine', 'Own-Model')+ expect(await port.moveTarget({ gridName: 'mine', model: 'Own-Model' })).toEqual({ target })+ expect(access.ensure.mock.calls).toEqual([[{ ownGrid: false }], [{ ownGrid: true }], [{ ownGrid: true }]])+ } finally {+ vi.mocked(resolveGridTarget).mockReset()+ }+ })++ it('a move grid cannot be set up for says why and reads no grid; one whose endpoint cannot be read says so', async () => {+ const { port } = setup()+ access.ensure.mockResolvedValueOnce({ status: 'handoff-failed', name: null, detail: 'no grid on this computer' })+ expect(await port.moveTarget({ gridName: 'team', model: 'Shared-Model' })).toEqual({ detail: 'no grid on this computer' })+ expect(resolveGridTarget).not.toHaveBeenCalled()+ expect(await port.moveTarget({ gridName: 'team', model: 'Shared-Model' })).toEqual({ detail: 'Could not read this machine\'s grid endpoint.' })+ })+ })+ })++ describe("the Model Manager's grid commands", () => {+ const COMMAND = { args: ['--remote', 'ls', '--json'], timeoutMs: 5_000 }+ const asker = { local: true, owner: true, connection: 'local:grid', requestId: 'cmd-1' }++ it('runs against grid as it stands, as a job of the connection and request that asked — never setting grid up', async () => {+ const { requests } = setup()+ expect(await requests.grid_fleet_run!(COMMAND, asker)).toEqual({ ok: true, code: 0, stdout: '[]', stderr: '', error: null })+ expect(fleet.run).toHaveBeenCalledWith('local:grid', 'cmd-1', { args: COMMAND.args, timeoutMs: 5_000 })+ expect(access.ensure).not.toHaveBeenCalled()+ expect(GridFleetRpc).toHaveBeenCalledTimes(1)+ })++ it('refuses a command it cannot read, or one with no connection or request to belong to', async () => {+ const { requests } = setup()+ expect(await requests.grid_fleet_run!({ args: [] }, asker)).toEqual({ error: 'INVALID_GRID_COMMAND' })+ expect(await requests.grid_fleet_run!(COMMAND, { local: true, owner: true, requestId: 'cmd-1' })).toEqual({ error: 'INVALID_GRID_COMMAND' })+ expect(await requests.grid_fleet_run!(COMMAND, { local: true, owner: true, connection: 'local:grid' })).toEqual({ error: 'INVALID_GRID_COMMAND' })+ expect(fleet.run).not.toHaveBeenCalled()+ })++ it('a run that fails unexpectedly is answered in one sentence', async () => {+ fleet.run.mockRejectedValueOnce(new Error('spawn EMFILE'))+ const { requests } = setup()+ expect(await requests.grid_fleet_run!(COMMAND, asker)).toEqual({ ok: false, code: 1, error: 'Grid command failed unexpectedly.' })+ })++ it('a cancel stops only the asking connection\'s own command', async () => {+ const { requests } = setup()+ expect(await requests.grid_fleet_cancel!({ commandId: 'cmd-1' }, asker)).toEqual({ cancelled: true })+ expect(fleet.cancel).toHaveBeenCalledWith('local:grid', 'cmd-1')+ fleet.cancel.mockReturnValueOnce(false)+ expect(await requests.grid_fleet_cancel!({ commandId: 'cmd-2' }, asker)).toEqual({ cancelled: false })+ expect(await requests.grid_fleet_cancel!({ commandId: 7 }, asker)).toEqual({ cancelled: false })+ expect(await requests.grid_fleet_cancel!({ commandId: 'cmd-1' }, { local: true, owner: true })).toEqual({ cancelled: false })+ expect(fleet.cancel).toHaveBeenCalledTimes(2)+ })})describe('the requests it answers for the apps', () => {it('answers exactly the requests it declares, and while it is off the host answers them unavailable', async () => {expect(Object.keys(setup().requests).sort()).toEqual([...MODELS_REQUESTS].sort())- // Not the Model Manager's grid commands, whose jobs belong to the connection that started them, nor- // their handshake, which the Grid harness reads as "update Harness" when it does not answer.- for (const socketOwn of ['grid_fleet_run', 'grid_fleet_cancel', 'grid_fleet_capabilities']) expect(MODELS_REQUESTS).not.toContain(socketOwn)+ // Not the grid commands' handshake, which the Grid harness reads as "update Harness" when it does+ // not answer: the socket's own, so a models service that is down does not make it say that.+ expect(MODELS_REQUESTS).not.toContain('grid_fleet_capabilities')const on = createServiceHost(emptyPorts(), { log: () => {} })on.start('models', startModels, fakeCore(), MODELS_FALLBACKS, MODELS_REQUESTS)@@ -309,8 +463,10 @@ describe('the models service', () => {expect(listAllGridModels).toHaveBeenLastCalledWith('b')ofA.resolve([section('a', true, [{ id: 'from-a' }])])expect(await a).toMatchObject({ gridName: 'a', models: [{ id: 'from-a' }] })- // b's listing is still the one out: a third ask for b joins it rather than starting another.+ // b's listing is still the one out: a third ask for b joins it rather than starting another, once it+ // has the grid's name.const again = ask('grid_models_list')+ await new Promise((resolve) => setImmediate(resolve))ofB.resolve([section('b', true, [{ id: 'from-b' }])])expect(await b).toMatchObject({ gridName: 'b', models: [{ id: 'from-b' }] })expect(await again).toMatchObject({ gridName: 'b', models: [{ id: 'from-b' }] })diff --git a/cli/src/services/models.ts b/cli/src/services/models.tsindex a5311b4b6..8da9489ff 100644--- a/cli/src/services/models.ts+++ b/cli/src/services/models.ts@@ -1,12 +1,14 @@/*** 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 model pictures an- * agent's frame carries, starting a sleeping grid while someone types to its agent, and what the apps- * ask about models: the picker's list, an agent's Model/Effort choices and the Model Manager's local- * models.+ * (docs/design/2026-10-03-harnessd.md, "Models"). Grid access on first use, the managed grid's pin, the+ * model pictures an agent's frame carries, starting a sleeping grid while someone types to its agent,+ * where an agent on a grid model sends its inference, and what the apps ask about models: the picker's+ * list, an agent's Model/Effort choices, the Model Manager's local models and its grid commands.*- * A service on the core boundary (step 13): it reads the core only through `CoreApi`, the core- * reaches it only through `ports.models`, and the apps through the requests it answers.+ * A service on the core boundary: it reads the core only through `CoreApi`, the core reaches it only+ * through `ports.models`, and the apps through the requests it answers. It runs in a process of its own+ * (services/modelsProcess.ts, docs/design/2026-10-06-core-boundary-next.md step 7): its downloads, its+ * installs and the `grid` children it runs cost that process, never the core's.*/import { join } from 'node:path'import { baseNode } from '../harnessd/baseNode.js'@@ -18,26 +20,51 @@ import { apiModelsRequest, rememberSavedApis } from '../lib/apiModels.js'import { appEngineOps, scanAppModels } from '../lib/appModels.js'import { linkCodexProfile, listCodexProfiles } from '../lib/codexProfiles.js'import { createGridAccess, gridNamesLocal, reconcileGridAttach } from '../lib/gridAttach.js'-import { resetGridDeriveMemo, signedInGridEmail } from '../lib/gridDerive.js'+import { deriveHarnessGridName, resetGridDeriveMemo, signedInGridEmail } from '../lib/gridDerive.js'import { ensureHarnessGrid } from '../lib/gridEnsure.js'-import { gridAvailable } from '../lib/gridExec.js'+import { gridAvailable, managedGridPath } from '../lib/gridExec.js'+import { GridFleetRpc, parseGridFleetRequest } from '../lib/gridFleetRpc.js'import { handOffToGrid } from '../lib/gridHandoff.js'import { ensureGridInstalled } from '../lib/gridInstall.js'+import type { GridLaunchOverride } from '../lib/gridLaunch.js'import { clearGridMcpUrlCache } from '../lib/gridMcpUrl.js'import {- forgetGridModels, gridAnnotation, gridInventory, keystrokePrewarm, listAllGridModels, onGridModelsChanged, warmGridModels, type GridSection,+ forgetGridModels, gridAnnotation, gridInventory, keystrokePrewarm, listAllGridModels, listGridModels, observeMachineList, onGridModelsChanged,+ retargetPrewarm, warmGridModels, type GridSection,} from '../lib/gridModels.js'import { gridModelsPayload } from '../lib/gridModelsPayload.js'+import { resolveGridTarget } from '../lib/gridTarget.js'import { LocalModels } from '../lib/localModels.js'+import type { NewAgentModel } from '../lib/newAgentModel.js'import { parseRuntimeProfile, type RuntimeModelOption } from '../lib/runtimeProfile.js'-import { ensureManagedGrid } from '../lib/runtimeInstall.js'+import { ensureManagedGrid, startGridPinRecheck } from '../lib/runtimeInstall.js'import { internalOnThrow } from './requestErrors.js'-/** The requests models answers for the apps, declared in core/api.ts for the core to route (why the Model- * Manager's grid commands are not among them is said there). */+/** The requests models answers for the apps, declared in core/api.ts for the core to route. */export { MODELS_REQUESTS } from '../core/api.js'+/** What grid's set-up for an act needs of models: have grid ready, and whether it is set up at all. */+interface GridSetUp {+ ensure: ModelsPort['ensure']+ /** Offline, for every list read: is there a `grid` here holding a sign-in? What decides whether the+ * picker offers local and shared models or a Set up row. */+ setUp(): boolean+}+export function startModels(core: CoreApi, ports: CorePorts): ServiceRequests {+ // A managed grid already here follows its pin on EVERY start of this service — the daemon's, and the+ // restart a self-update ends in — not only on `--repair`: the pin is expected to move, and a machine+ // installed last month has to notice. A machine with none gets none from a start: grid is an add-on,+ // installed the first time a grid feature is used (`ensure`, below). Not awaited, and asynchronous+ // throughout (`runtimeInstall.ts`): every grid call resolves the binary afresh (`gridBinaryPath`), so+ // whatever lands is picked up as it lands. It keeps following it while this runs: a pin moved after+ // the start reaches it within ten minutes rather than at the next restart (`startGridPinRecheck`).+ const followGridPin = (): Promise<unknown> => managedGridPath()+ ? ensureManagedGrid((m) => console.log(`[grid-runtime] ${m}`))+ : Promise.resolve(null)+ void followGridPin()+ startGridPinRecheck({ ensure: followGridPin })+// Grid is an add-on (`lib/gridAttach.ts`): nothing on this path installs `grid`, signs this machine in// to it or creates a grid. The first grid feature a person uses — the models picker's Set up, a local// model's Get or Use, an agent moved onto a grid model, the Model Manager — asks `ports.models.ensure`,@@ -74,12 +101,27 @@ export function startModels(core: CoreApi, ports: CorePorts): ServiceRequests {log: gridLog,}, { ownGrid, signedInThisRun }),})+ const grid: GridSetUp = {+ ensure: (request) => gridAccess.ensure(request),+ setUp: () => gridAvailable() && signedInGridEmail() !== null,+ }++ /**+ * The account's private grid: the backend's word when it gave one, else what this machine can work out+ * for itself (`lib/gridDerive.ts`). A backend that predates `machine_meta.gridName` left every picker+ * empty while `grid models` listed the model fine; the derivation is the skill's own rule, so the+ * daemon and the agent it opens agree on which grid is "yours".+ */+ const privateGridName = async (): Promise<string | null> => (await core.account.privateGridName()) ?? await deriveHarnessGridName()// An agent's frame says what its grid's picture says (`grid.state`, and a `grid.note` when its model// will not answer). The picture changes on reads nobody waited for, so the frames of the agents whose- // annotation moved are pushed again — only those, and only when it moved.+ // annotation moved are pushed again — only those, and only when it moved — and the windows are pushed+ // the list. In a process of its own the core reads the notes from what it is told+ // (services/modelsProcess.ts) and the core API there has no agents to push: the core does that itself.const announcedGrid = new Map<string, string>()onGridModelsChanged(() => {+ core.clients.gridModelsChanged()const onGrid = core.agents.advertised().filter((s) => s.grid)const present = new Set(onGrid.map((s) => s.agentId))for (const agentId of [...announcedGrid.keys()]) if (!present.has(agentId)) announcedGrid.delete(agentId)@@ -94,21 +136,80 @@ export function startModels(core: CoreApi, ports: CorePorts): ServiceRequests {// frame carries its grid's state and note, and a keystroke can start its grid, before any window asks// for the list (after a self-update, a phone may be the only one typing).void warmGridModels().catch(() => {})- const grid: Pick<ModelsPort, 'ensure' | 'setUp'> = {- ensure: (request) => gridAccess.ensure(request),- // Offline, for every list read: is there a `grid` here holding a sign-in? What decides whether the- // picker offers local and shared models or a Set up row.- setUp: () => gridAvailable() && signedInGridEmail() !== null,- }+ports.models = {- ...grid,+ ensure: grid.ensure,+ annotation: (target) => gridAnnotation(target),// The keystroke prewarm (grid-reads-without-waking issue 03): typing into a pane whose agent runs on// a sleeping grid starts that grid while the person types.prewarm: (target) => { void keystrokePrewarm(target).catch(() => {}) },+ launchTarget: (selection) => launchTarget(selection),+ moveTarget: (request) => moveTarget(grid, privateGridName, core, request),+ // The agent is on a grid model now and its pane is restarting: start that grid meanwhile if it sleeps,+ // so the first message rarely waits on a boot (issue 03). It decides for itself whether a wake is+ // worth it.+ moved: (launch) => { void retargetPrewarm(launch).catch(() => {}) },+ privateGridName,+ // `grid_models_changed` to the windows: the same payload `grid_models_list` answers, built from the+ // pictures as they stand — no read is started to build it, so a push never causes one. Each window+ // gets it in the form it asked for (`gridModelsPayload`).+ lists: async () => {+ const gridName = await privateGridName()+ const grids = await listAllGridModels(gridName, { refresh: false })+ return { plain: gridModelsPayload(gridName, grids, false), rowState: gridModelsPayload(gridName, grids, true) }+ },+ // Which of the owner's other computers have been reading offline — a label on the models only they+ // serve on a sleeping grid, never a removal (grid-reads-without-waking issue 03).+ machines: (body, computerId) => observeMachineList(body, computerId),// The web-tools cache lives exactly as long as the sign-in.signedOut: () => clearGridMcpUrlCache(),}- return modelsRequests(core, grid)+ return modelsRequests(core, grid, privateGridName)+}++/**+ * Where a new agent on a grid model sends its inference, resolved on this machine. Refreshed at launch: a+ * model stopped after the picker opened must not silently fall back to a subscription or to the grid's+ * default router. Only the semantic choice goes into the creation receipt, never this rotating key.+ */+export async function launchTarget(selection: NewAgentModel): Promise<GridLaunchOverride | null> {+ forgetGridModels()+ const models = await listGridModels(selection.grid)+ if (!models.some((model) => model.id === selection.model)) return null+ return resolveGridTarget(selection.grid, selection.model)+}++/**+ * Grid set up for an act, or the sentence saying why it could not be: null when it is ready. The+ * picker's Set up, a Get, a Use and a move onto a grid model each ask it.+ */+async function notReady(grid: GridSetUp, ownGrid: boolean): Promise<string | null> {+ const ready = await grid.ensure({ ownGrid })+ if (ready.status !== 'converged' && ready.status !== 'signed-in') {+ return ready.detail || 'Grid could not be set up on this computer. Try again.'+ }+ if (ownGrid && ready.ownGrid && !['created', 'existed', 'adopted'].includes(ready.ownGrid)) {+ return ready.detail || 'Your grid could not be created. Try again.'+ }+ return null+}++/**+ * Where a running agent moved onto a grid model sends its inference (`agent_retarget`). The app names+ * the model, and the grid it was picked from when the picker says (a shared grid's section), the+ * account's own otherwise; the endpoint and the credential are resolved here, from this machine's own+ * signed-in `grid`, so neither ever crosses the relay. A move onto a grid model is a grid feature in+ * use: grid is signed in first, if it is not yet — and the account's own grid made sure of when that is+ * where the model is.+ */+async function moveTarget(+ grid: GridSetUp, privateGridName: () => Promise<string | null>, core: CoreApi, request: { gridName: string | null; model: string },+): Promise<{ target: GridLaunchOverride } | { detail: string }> {+ const named = request.gridName+ const unready = await notReady(grid, !named || named === await core.account.privateGridName())+ if (unready) return { detail: unready }+ const target = await resolveGridTarget(named ?? await privateGridName(), request.model)+ return target ? { target } : { detail: 'Could not read this machine\'s grid endpoint.' }}/** Sections one `grid_models_list` may ask to wake — a person presses one "Show models" at a time. */@@ -123,7 +224,7 @@ type LocalModelRequest = 'grid_fleet_models_list' | 'grid_fleet_model_download'* answered them itself. A failure is answered as the socket answered it, sentences included: the apps* show them.*/-function modelsRequests(core: CoreApi, grid: Pick<ModelsPort, 'ensure' | 'setUp'>): ServiceRequests {+function modelsRequests(core: CoreApi, grid: GridSetUp, privateGridName: () => Promise<string | null>): ServiceRequests {// The Model Manager reads the grid it runs on through the same credential-less reader as every picker// (never `grid engines`, which carries the grid credential and so wakes a sleeping grid on every tick),// and a start or stop it finishes makes every list read again — pushed to the window when it changes.@@ -141,21 +242,6 @@ function modelsRequests(core: CoreApi, grid: Pick<ModelsPort, 'ensure' | 'setUp'* meanwhile. */let listing: { gridName: string | null; grids: Promise<GridSection[]> } | null = null- /**- * Grid set up for an act, or the sentence saying why it could not be: null when it is ready. The- * socket says the same for a move onto a grid model (`agent_retarget`), which it still answers.- */- const notReady = async (ownGrid: boolean): Promise<string | null> => {- const ready = await grid.ensure({ ownGrid })- if (ready.status !== 'converged' && ready.status !== 'signed-in') {- return ready.detail || 'Grid could not be set up on this computer. Try again.'- }- if (ownGrid && ready.ownGrid && !['created', 'existed', 'adopted'].includes(ready.ownGrid)) {- return ready.detail || 'Your grid could not be created. Try again.'- }- return null- }-// A daemon-owned operation survives panel closure and a lost reply. Its hardware, catalog and network// reads stay off the connection's ordered queue: the host answers when they are done.//@@ -167,8 +253,8 @@ function modelsRequests(core: CoreApi, grid: Pick<ModelsPort, 'ensure' | 'setUp'try {const list = type === 'grid_fleet_models_list'const setup = list ? payload.setup === true : type !== 'grid_fleet_model_stop'- const unready = setup ? await notReady(type !== 'grid_fleet_model_download') : null- const gridName = await core.account.privateGridName()+ const unready = setup ? await notReady(grid, type !== 'grid_fleet_model_download') : null+ const gridName = await privateGridName()if (list) {const snapshot = await localModels.list(gridName, payload.refresh === true || setup)const needed = !grid.setUp()@@ -210,7 +296,7 @@ function modelsRequests(core: CoreApi, grid: Pick<ModelsPort, 'ensure' | 'setUp'? payload.wake.filter((name): name is string => typeof name === 'string' && !!name.trim()).map((name) => name.trim()).slice(0, MAX_WAKES_PER_ASK): []try {- const gridName = await core.account.privateGridName()+ const gridName = await privateGridName()const inFlight = listingconst grids = wake.length? listAllGridModels(gridName, { wake })@@ -251,10 +337,40 @@ function modelsRequests(core: CoreApi, grid: Pick<ModelsPort, 'ensure' | 'setUp'grid_fleet_model_download: localModel('grid_fleet_model_download'),grid_fleet_model_start: localModel('grid_fleet_model_start'),grid_fleet_model_stop: localModel('grid_fleet_model_stop'),+ ...gridCommands(),...launchTargetRequests(core),}}+/**+ * The Model Manager's grid commands: grid's own argv, run here (`lib/gridFleetRpc.ts`). A command is a job+ * of the connection that started it, keyed by that connection and the id it was asked under (`Asker`),+ * and a cancel stops only that connection's own. Run against grid AS IT STANDS — never set up first: a+ * Grid harness session issues these on its own the moment its viewer comes up (every open one, on every+ * daemon start), so setting grid up here signed a machine in to grid right after a Harness-only sign-in,+ * with nobody asking. Grid is set up by the picker's Set up, by making or opening a Model Manager, and by+ * that harness's own `harness grid setup`; until then grid answers these in its own words. Their+ * handshake, `grid_fleet_capabilities`, is the socket's (core/api.ts `MODELS_REQUESTS`).+ */+function gridCommands(): ServiceRequests {+ const fleet = new GridFleetRpc()+ return {+ // Pulls and builds can take minutes; the host answers when it is done and holds nothing else for it.+ grid_fleet_run: async (payload, asker) => {+ const request = parseGridFleetRequest(payload)+ if (!request || !asker.connection || !asker.requestId) return { error: 'INVALID_GRID_COMMAND' }+ try {+ return { ...await fleet.run(asker.connection, asker.requestId, request) }+ } catch {+ return { ok: false, code: 1, error: 'Grid command failed unexpectedly.' }+ }+ },+ grid_fleet_cancel: (payload, asker) => ({+ cancelled: !!asker.connection && typeof payload.commandId === 'string' && fleet.cancel(asker.connection, payload.commandId),+ }),+ }+}+/*** What an agent can be launched on besides a model: the saved APIs and the Codex profiles, moved out of the* socket's switch (docs/design/2026-10-06-core-boundary-next.md, step 4). Its own function so the socket'sdiff --git a/cli/src/services/modelsProcess.spec.ts b/cli/src/services/modelsProcess.spec.tsnew file mode 100644index 000000000..b83a079be--- /dev/null+++ b/cli/src/services/modelsProcess.spec.ts@@ -0,0 +1,287 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import type { CoreApi, CorePorts, ModelsPort, ServiceRequests } from '../core/api.js'+import type { GridGlance } from '../lib/gridAnnotation.js'+import type { CoreConnection, ServiceProcessOptions } from './process.js'+import { modelsCoreApi, runModelsService } from './modelsProcess.js'++// The real default reaches a real socket and this process's own channel: never in a test.+vi.mock('./process.js', () => ({ runServiceProcess: vi.fn(() => ({ stop: vi.fn() })) }))+// The real service reads grid and follows its pin: never in a test. Its own spec is services/models.spec.ts.+vi.mock('./models.js', () => ({ startModels: vi.fn((_core: CoreApi, ports: CorePorts) => { ports.models = fakeModels().port; return {} }) }))++const RELAY = 'https://fixture.invalid/g/net-own/relay/v1'+const LAUNCH = { networkId: 'net-own', networkName: 'mine', baseUrl: RELAY, apiKey: 'fixture-key', model: 'Small-Q4' }+const glance = (state: 'awake' | 'asleep'): GridGlance => ({ id: 'net-own', view: { state, models: [{ id: 'Small-Q4' }] }, listed: true, asleep: state === 'asleep' })++/** Models that read no grid: its port, every member a fake, and the apps' requests it answers. */+function fakeModels() {+ const port = {+ ensure: vi.fn(async () => ({ status: 'converged' as const, name: 'mine', detail: 'ok' })),+ annotation: vi.fn(() => null),+ prewarm: vi.fn(),+ launchTarget: vi.fn(async () => LAUNCH),+ moveTarget: vi.fn(async (): Promise<{ target: typeof LAUNCH } | { detail: string }> => ({ target: LAUNCH })),+ moved: vi.fn(),+ privateGridName: vi.fn(async () => 'mine'),+ lists: vi.fn(async () => ({ plain: { gridName: 'mine' }, rowState: { gridName: 'mine', grids: [] } })),+ machines: vi.fn(),+ signedOut: vi.fn(),+ } satisfies ModelsPort+ const requests: ServiceRequests = { grid_models_list: vi.fn(async () => ({ gridName: 'mine' })) }+ return { port, requests }+}++/** A connection to the core that records what it is told, and answers `machines` with `machines`. */+function connection(machines: Record<string, unknown> = {}, kept = true) {+ const query = vi.fn(async (name: string, _payload?: Record<string, unknown>): Promise<Record<string, unknown>> =>+ name === 'machines' ? machines : name === 'glances' ? { kept } : {})+ const told = () => query.mock.calls.filter(([name]) => name === 'glances').map(([, payload]) => payload)+ return { core: { query } satisfies CoreConnection, query, told }+}++const flush = () => new Promise((done) => setTimeout(done, 0))++describe('models in its own process', () => {+ afterEach(() => vi.clearAllMocks())++ const setup = (over: Partial<Parameters<typeof runModelsService>[0]> = {}) => {+ const models = fakeModels()+ let api: CoreApi | null = null+ let options: ServiceProcessOptions | null = null+ let glances: GridGlance[] = []+ let changed: () => void = () => {}+ const service = { stop: vi.fn() }+ const handle = runModelsService({+ dataDir: '/data', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't',+ run: (given) => { options = given; return service },+ start: (core: CoreApi, ports: CorePorts) => { api = core; ports.models = models.port; return models.requests },+ glances: () => glances,+ onChanged: (listener) => { changed = listener; return () => {} },+ ...over,+ })+ return { models, api: api!, options: options!, service, handle, setGlances: (next: GridGlance[]) => { glances = next }, changed: () => changed() }+ }++ 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(['ensure', '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()+ })++ it('a start that fills no port is no models at all', () => {+ expect(() => runModelsService({ dataDir: '/data', socketPath: '/s', machineId: 'm', token: 't', run: () => ({ stop: vi.fn() }), start: () => ({}) }))+ .toThrow('models did not start')+ })++ it('answers the core\'s port calls through the port, as the core\'s process would', async () => {+ const { models, options } = setup()+ const asker = { local: true, owner: true }+ expect(await options.requests.ensure!({ ownGrid: true }, asker)).toEqual({ status: 'converged', name: 'mine', detail: 'ok' })+ await options.requests.ensure!({}, asker)+ expect(models.port.ensure.mock.calls).toEqual([[{ ownGrid: true }], [{ ownGrid: false }]])+ expect(await options.requests.launchTarget!({ model: 'Small-Q4', grid: 'mine' }, asker)).toEqual({ target: LAUNCH })+ expect(await options.requests.launchTarget!({ model: 7 }, asker)).toEqual({ target: LAUNCH })+ expect(models.port.launchTarget.mock.calls).toEqual([[{ model: 'Small-Q4', grid: 'mine' }], [{ model: '', grid: '' }]])+ expect(await options.requests.moveTarget!({ gridName: 'team', model: 'Shared' }, asker)).toEqual({ target: LAUNCH })+ models.port.moveTarget.mockResolvedValueOnce({ detail: 'no grid' })+ expect(await options.requests.moveTarget!({}, asker)).toEqual({ detail: 'no grid' })+ expect(models.port.moveTarget.mock.calls).toEqual([[{ gridName: 'team', model: 'Shared' }], [{ gridName: null, model: '' }]])+ expect(await options.requests.privateGridName!({}, asker)).toEqual({ name: 'mine' })+ expect(await options.requests.lists!({}, asker)).toEqual({ plain: { gridName: 'mine' }, rowState: { gridName: 'mine', grids: [] } })+ })++ it('does what the core tells it, and passes over what it cannot read', () => {+ const { models, options } = setup()+ options.onEvent!({ kind: 'prewarm', grid: { baseUrl: RELAY, model: 'Small-Q4' } })+ options.onEvent!({ kind: 'prewarm', grid: { baseUrl: RELAY } })+ options.onEvent!({ kind: 'prewarm', grid: 'nope' })+ expect(models.port.prewarm.mock.calls).toEqual([[{ baseUrl: RELAY, model: 'Small-Q4' }], [{ baseUrl: RELAY, model: null }]])+ options.onEvent!({ kind: 'moved', launch: LAUNCH })+ options.onEvent!({ kind: 'moved', launch: { networkId: 'n' } })+ expect(models.port.moved.mock.calls).toEqual([[LAUNCH]])+ options.onEvent!({ kind: 'machines', body: { data: {} }, computerId: 'here' })+ options.onEvent!({ kind: 'machines', body: 'nope' })+ expect(models.port.machines.mock.calls).toEqual([[{ data: {} }, 'here'], [null, '']])+ options.onEvent!({ kind: 'signedOut' })+ expect(models.port.signedOut).toHaveBeenCalledOnce()+ options.onEvent!({ kind: 'anything' })+ })++ it('tells the core every grid as it connects and on each change, each change once, and again on a new connection', async () => {+ const { options, setGlances, changed } = setup()+ setGlances([glance('awake')])+ // Not connected: nothing to tell.+ changed()+ const first = connection()+ options.onConnected!(first.core)+ await flush()+ expect(first.told()).toEqual([{ glances: [glance('awake')] }])+ changed()+ expect(first.told()).toHaveLength(1)+ setGlances([glance('asleep')])+ changed()+ expect(first.told()).toEqual([{ glances: [glance('awake')] }, { glances: [glance('asleep')] }])+ // A core that restarted has heard nothing.+ const second = connection()+ options.onConnected!(second.core)+ expect(second.told()).toEqual([{ glances: [glance('asleep')] }])+ })++ it('says it again when the core did not keep it; a connection that went says it on the next', async () => {+ const { options, setGlances, changed } = setup()+ setGlances([glance('awake')])+ const refusing = connection({}, false)+ options.onConnected!(refusing.core)+ await flush()+ changed()+ expect(refusing.told()).toHaveLength(2)+ const failing = connection()+ failing.query.mockRejectedValue(new Error('the core went away'))+ options.onConnected!(failing.core)+ await flush()+ changed()+ expect(failing.told()).toHaveLength(1)+ const next = connection()+ options.onConnected!(next.core)+ expect(next.told()).toHaveLength(1)+ })++ it('asks the core for the machine list it read before this process could hear it', async () => {+ const { models, options } = setup()+ options.onConnected!(connection({ body: { data: { machines: [] } }, computerId: 'here' }).core)+ await flush()+ expect(models.port.machines).toHaveBeenCalledExactlyOnceWith({ data: { machines: [] } }, 'here')+ options.onConnected!(connection({ body: 'nope', computerId: 'here' }).core)+ await flush()+ expect(models.port.machines).toHaveBeenLastCalledWith(null, 'here')+ // None read yet, or a connection that went before it answered: nothing.+ options.onConnected!(connection({}).core)+ const gone = connection()+ gone.query.mockRejectedValue(new Error('the core went away'))+ options.onConnected!(gone.core)+ await flush()+ expect(models.port.machines).toHaveBeenCalledTimes(2)+ // An answer for a connection that was replaced meanwhile is not heard.+ let answer!: (value: Record<string, unknown>) => void+ const slow = connection()+ slow.query.mockImplementation(async (name: string) => name === 'machines' ? new Promise((done) => { answer = done }) : { kept: true })+ options.onConnected!(slow.core)+ options.onConnected!(connection().core)+ answer({ body: null, computerId: 'here' })+ await flush()+ expect(models.port.machines).toHaveBeenCalledTimes(2)+ })+})++describe('the core API models runs on in its own process', () => {+ const asking = (answers: Record<string, Record<string, unknown> | Error>) => {+ const ask = vi.fn(async (query: string, _payload?: Record<string, unknown>) => {+ const answer = answers[query]+ if (answer instanceof Error) throw answer+ return answer ?? {}+ })+ return { ask, api: modelsCoreApi('/data', ask) }+ }++ it('asks the core for the account\'s grid, and keeps this machine\'s name from the same answer', async () => {+ const { ask, api } = asking({ account: { gridName: 'mine', machineName: 'Studio' } })+ expect(api.dataDir).toBe('/data')+ expect(api.account.machineName()).toBeNull()+ expect(await api.account.privateGridName()).toBe('mine')+ expect(api.account.machineName()).toBe('Studio')+ expect(ask).toHaveBeenCalledWith('account')+ expect(await asking({ account: {} }).api.account.privateGridName()).toBeNull()+ // Unanswered (the core went away): no name, and models works one out.+ const gone = asking({ account: new Error('not connected to the core') })+ expect(await gone.api.account.privateGridName()).toBeNull()+ expect(gone.api.account.machineName()).toBeNull()+ })++ it('asks for a minted name and the token each time, and says when there is none', async () => {+ const { api } = asking({ mintGridName: { name: 'minted-1a2b' }, accessToken: { token: 'fixture-token' } })+ expect(await api.account.mintGridName()).toBe('minted-1a2b')+ expect(await api.account.accessToken()).toBe('fixture-token')+ expect(await asking({ mintGridName: {} }).api.account.mintGridName()).toBeNull()+ await expect(asking({ mintGridName: { error: 'QUERY_FAILED' } }).api.account.mintGridName()).rejects.toThrow('QUERY_FAILED')+ await expect(asking({ accessToken: { error: 'QUERY_FAILED' } }).api.account.accessToken()).rejects.toThrow('signed out')+ })++ it('asks for an agent\'s Model/Effort choices, and fails as the core\'s own would when it gets none', async () => {+ const models = [{ id: 'runtime-v1:a1:codex:o3@high', displayName: 'o3 / High' }]+ const { ask, api } = asking({ runtimeModels: { models } })+ expect(await api.agents.runtimeModels('a1')).toEqual(models)+ expect(await api.agents.runtimeModels()).toEqual(models)+ expect(ask.mock.calls).toEqual([['runtimeModels', { agentId: 'a1' }], ['runtimeModels', {}]])+ await expect(asking({ runtimeModels: { error: 'QUERY_FAILED' } }).api.agents.runtimeModels()).rejects.toThrow('QUERY_FAILED')+ await expect(asking({}).api.agents.runtimeModels()).rejects.toThrow('no answer')+ })++ it('tells the core the two pushes to the windows, a lost one lost quietly', async () => {+ const { ask, api } = asking({ gridNamed: new Error('the core went away') })+ api.clients.gridNamed('mine')+ api.clients.gridModelsChanged()+ await flush()+ expect(ask.mock.calls).toEqual([['gridNamed', { name: 'mine' }], ['gridModelsChanged', {}]])+ })++ it('has no agents of its own and drives none: what models never asks answers as nothing', async () => {+ const { ask, api } = asking({})+ expect([api.agents.all(), api.agents.live(), api.agents.advertised(), api.agents.displayName({} as never)]).toEqual([[], [], [], ''])+ expect([api.agents.byAgent('a1'), api.agents.resolve('a1'), api.agents.terminalAvailable('a1'), api.agents.runtimeProfile({} as never)]).toEqual([undefined, undefined, false, null])+ api.agents.sync({} as never)+ api.agents.setRuntime('a1')+ expect(await api.agents.fork('a1')).toEqual({ ok: false, error: 'UNSUPPORTED' })+ api.turns.send('a1', 'x')+ api.turns.stop('a1')+ expect([api.turns.recent('a1', 1), api.turns.asks('a1')]).toEqual([[], []])+ api.questions.answer('a1', 'r', {})+ expect(await api.questions.answerReviewed({} as never)).toBe(false)+ expect(api.transcripts.databaseHistory({} as never)).toBeUndefined()+ expect(api.external.sessions.list()).toEqual([])+ expect(await api.external.sessions.scan()).toEqual([])+ expect(api.external.open.known()).toEqual(new Map())+ expect(await api.external.open.fresh()).toEqual(new Map())+ api.clients.viewerChanged('a1')+ api.clients.dshInstallStatus({})+ expect(ask).not.toHaveBeenCalled()+ })+})++describe('models in its own process, before it is ever connected', () => {+ it('asks the core nothing it cannot reach: a question before the first connection is refused', async () => {+ let start: CoreApi | null = null+ runModelsService({+ dataDir: '/data', socketPath: '/s', machineId: 'm', token: 't',+ run: () => ({ stop: vi.fn() }),+ start: (core, ports) => { start = core; ports.models = fakeModels().port; return {} },+ glances: () => [], onChanged: () => () => {},+ })+ await expect(start!.account.accessToken()).rejects.toThrow('not connected to the core')+ })++ it('runs the service, the pictures and the process link it was built with when a test does not swap them', async () => {+ const { runServiceProcess } = await import('./process.js')+ const { startModels } = await import('./models.js')+ runModelsService({ dataDir: '/data', socketPath: '/s', machineId: 'm', token: 't' })+ expect(startModels).toHaveBeenCalled()+ expect(runServiceProcess).toHaveBeenCalled()+ })++ it('asks the core what models needs over the connection it has', async () => {+ let start: CoreApi | null = null+ let options: ServiceProcessOptions | null = null+ runModelsService({+ dataDir: '/data', socketPath: '/s', machineId: 'm', token: 't',+ run: (given) => { options = given; return { stop: vi.fn() } },+ start: (core, ports) => { start = core; ports.models = fakeModels().port; return {} },+ glances: () => [], onChanged: () => () => {},+ })+ const core = connection()+ options!.onConnected!(core.core)+ await start!.account.privateGridName()+ expect(core.query).toHaveBeenCalledWith('account', {})+ })+})diff --git a/cli/src/services/modelsProcess.ts b/cli/src/services/modelsProcess.tsnew file mode 100644index 000000000..c6aa232c5--- /dev/null+++ b/cli/src/services/modelsProcess.ts@@ -0,0 +1,183 @@+/**+ * Models in its own process (`harness __service models`, with `HARNESSD_SERVICES=models`).+ *+ * The same service as in the core's process (services/models.ts), on a core API built here: grid's+ * set-up, its pin, the pictures, the Model Manager's local models and grid commands, and the requests the+ * apps send about models. Its downloads, installs, model scans and `grid` children are this process's+ * alone: a crash, a hang or a leak costs models, and the master starts it again.+ *+ * What the core used to read straight off the pictures while it builds a frame or takes a keystroke is+ * told to it instead: a glance at every grid, each time a picker would be told something new and each time+ * this process connects (`service_query glances`, core/modelsLink.ts). What the core asks of models+ * through its port arrives as requests under the port's member names, which only the core sends; what it+ * only tells models arrives as events. What models needs of the core — the sign-in it holds, the+ * account's grid name, this machine's name, an agent's Model/Effort choices, the pushes to the windows —+ * it asks for (`service_query`), each time it needs it: a service keeps no credential.+ */+import type { CoreApi, ServiceRequests } from '../core/api.js'+import { emptyPorts, LANE_OFF, TERMINALS_OFF } from '../core/api.js'+import type { AgentGridTarget, GridGlance } from '../lib/gridAnnotation.js'+import { parseGridLaunchOverride } from '../lib/gridLaunch.js'+import { gridGlances, onGridModelsChanged } from '../lib/gridModels.js'+import type { RuntimeModelOption } from '../lib/runtimeProfile.js'+import { startModels } from './models.js'+import { runServiceProcess, type CoreConnection, type ServiceProcess } from './process.js'++type Payload = Record<string, unknown>++export interface ModelsServiceOptions {+ dataDir: string+ socketPath: string+ machineId: string+ token: string+ /** Swapped in tests for one that does not touch the real socket or process. */+ run?: typeof runServiceProcess+ /** Swapped in tests for models that read no grid and start nothing. */+ start?: typeof startModels+ /** Every grid at a glance, and being told when that changes: the pictures', unless a test says. */+ glances?: () => GridGlance[]+ onChanged?: (listener: () => void) => () => void+}++const isRecord = (value: unknown): value is Payload => !!value && typeof value === 'object' && !Array.isArray(value)+const text = (value: unknown): string => (typeof value === 'string' ? value : '')++/**+ * The core API models runs on in its own process: the sign-in, the account's grid and this machine's name+ * asked of the core as they are needed, an agent's Model/Effort choices likewise, and the two pushes to+ * the windows told to it. This machine's name is what the core said with the account's grid, which the+ * Model Manager asks for before every list. What models never asks (turns, questions, search) answers as+ * nothing, and it has no agents to send frames for: the core sends those itself.+ */+export function modelsCoreApi(dataDir: string, ask: (query: string, payload?: Payload) => Promise<Payload>): CoreApi {+ let machineName: string | null = null+ const told = (query: string, payload: Payload = {}): void => { void ask(query, payload).catch(() => {}) }+ return {+ dataDir,+ // Models opens no terminal.+ terminals: TERMINALS_OFF,+ agents: {+ all: () => [],+ live: () => [],+ displayName: () => '',+ byAgent: () => undefined,+ resolve: () => undefined,+ advertised: () => [],+ terminalAvailable: () => false,+ sync: () => {},+ runtimeModels: async (agentId) => {+ const answer = await ask('runtimeModels', agentId ? { agentId } : {})+ if (!Array.isArray(answer.models)) throw new Error(`the core did not list the models (${text(answer.error) || 'no answer'})`)+ return answer.models as RuntimeModelOption[]+ },+ runtimeProfile: () => null,+ setRuntime: () => {},+ fork: async () => ({ ok: false, error: 'UNSUPPORTED' }),+ },+ turns: { send: () => {}, stop: () => {}, recent: () => [], asks: () => [] },+ questions: { answer: () => {}, answerReviewed: async () => false },+ transcripts: { databaseHistory: () => undefined },+ external: {+ sessions: { list: () => [], scan: async () => [] },+ open: { known: () => new Map(), fresh: async () => new Map() },+ },+ account: {+ mintGridName: async () => {+ const answer = await ask('mintGridName')+ if (answer.error) throw new Error(`the core could not mint a grid name (${text(answer.error)})`)+ return text(answer.name) || null+ },+ accessToken: async () => {+ const token = text((await ask('accessToken')).token)+ if (!token) throw new Error('no access token: this machine is signed out')+ return token+ },+ // Unanswered, it is no name, and models works one out (services/models.ts `privateGridName`).+ privateGridName: async () => {+ const answer = await ask('account').catch(() => null)+ if (!answer) return null+ machineName = text(answer.machineName) || null+ return text(answer.gridName) || null+ },+ machineName: () => machineName,+ // Models never reaches another machine: the fleet's lane is not its to seal.+ lane: LANE_OFF,+ },+ clients: {+ viewerChanged: () => {},+ gridNamed: (name) => told('gridNamed', { name }),+ gridModelsChanged: () => told('gridModelsChanged'),+ dshInstallStatus: () => {},+ },+ }+}++/** An agent's grid as the core sent it for a prewarm, or null when it is not one. */+const targetIn = (value: unknown): AgentGridTarget | null =>+ isRecord(value) && typeof value.baseUrl === 'string' ? { baseUrl: value.baseUrl, model: typeof value.model === 'string' ? value.model : null } : null++export function runModelsService(options: ModelsServiceOptions): ServiceProcess {+ let core: CoreConnection | null = null+ const ask = (query: string, payload: Payload = {}): Promise<Payload> =>+ core ? core.query(query, payload) : Promise.reject(new Error('not connected to the core'))+ const ports = emptyPorts()+ const requests = (options.start ?? startModels)(modelsCoreApi(options.dataDir, ask), ports)+ if (!ports.models) throw new Error('models did not start')+ const models = ports.models++ /** What the current connection was last told of the grids, so a change is said once. */+ let told = ''+ const glances = options.glances ?? gridGlances+ const tellGlances = (): void => {+ const connection = core+ if (!connection) return+ const now = glances()+ const said = JSON.stringify(now)+ if (said === told) return+ told = said+ // Lost only with the connection, or the core not keeping it; the next change or connection says it again.+ void connection.query('glances', { glances: now }).then((answer) => { if (answer.kept !== true && core === connection) told = '' }, () => {})+ }+ ;(options.onChanged ?? onGridModelsChanged)(tellGlances)++ // The core's own calls into models, under its port's member names: no client's request reaches these.+ const portCalls: ServiceRequests = {+ 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) }) }),+ privateGridName: async () => ({ name: await models.privateGridName() }),+ lists: async () => ({ ...await models.lists() }),+ }++ const run = options.run ?? runServiceProcess+ return run({+ name: 'models',+ socketPath: options.socketPath,+ machineId: options.machineId,+ token: options.token,+ requests: { ...requests, ...portCalls },+ onEvent: (payload) => {+ if (payload.kind === 'prewarm') {+ const grid = targetIn(payload.grid)+ if (grid) models.prewarm(grid)+ } else if (payload.kind === 'moved') {+ const launch = parseGridLaunchOverride(payload.launch)+ if (launch.state === 'ok') models.moved(launch.override)+ } else if (payload.kind === 'machines') {+ models.machines(isRecord(payload.body) ? payload.body : null, text(payload.computerId))+ } else if (payload.kind === 'signedOut') {+ models.signedOut()+ }+ },+ onConnected: (connection) => {+ core = connection+ told = ''+ // A core that restarted has heard nothing yet: tell it every grid, and ask for the machine list it+ // read before this process could hear it.+ tellGlances()+ void connection.query('machines').then((answer) => {+ if (core === connection && typeof answer.computerId === 'string') models.machines(isRecord(answer.body) ? answer.body : null, answer.computerId)+ }, () => {})+ },+ })+}diff --git a/cli/src/services/process.spec.ts b/cli/src/services/process.spec.tsindex eefc66071..400c41932 100644--- a/cli/src/services/process.spec.ts+++ b/cli/src/services/process.spec.ts@@ -206,8 +206,14 @@ describe('a service in its own process', () => {socket().say({ type: 'session_search', payload: { requestId: 'r1' }, asker: { local: true, owner: true } })socket().say({ type: 'session_search', payload: { requestId: 'r2' }, asker: { local: 'yes', owner: 1 } })socket().say({ type: 'session_search', payload: { requestId: 'r3' } })- await vi.waitFor(() => expect(asked).toHaveLength(3))- expect(asked).toEqual([{ local: true, owner: true }, { local: false, owner: false }, { local: false, owner: false }])+ // The connection and the client's own request id, when the core gave them: what a grid command is a job of.+ socket().say({ type: 'session_search', payload: { requestId: 'r4' }, asker: { local: true, owner: true, connection: 'local:1', requestId: 'cmd-1' } })+ socket().say({ type: 'session_search', payload: { requestId: 'r5' }, asker: { local: true, owner: true, connection: 7, requestId: null } })+ await vi.waitFor(() => expect(asked).toHaveLength(5))+ expect(asked).toEqual([+ { local: true, owner: true }, { local: false, owner: false }, { local: false, owner: false },+ { local: true, owner: true, connection: 'local:1', requestId: 'cmd-1' }, { local: true, owner: true },+ ])})it('hears what the core tells it, and asks the core what it needs to know', async () => {diff --git a/cli/src/services/process.ts b/cli/src/services/process.tsindex 36101134f..51ebc90dd 100644--- a/cli/src/services/process.ts+++ b/cli/src/services/process.ts@@ -12,7 +12,7 @@* and asks the core what it needs to know.*/import WebSocket from 'ws'-import type { ServiceRequests } from '../core/api.js'+import type { Asker, ServiceRequests } from '../core/api.js'import { heartbeatInterval, processLoopDelay, type LoopDelay, type MasterChannel } from '../harnessd/coreLink.js'type Payload = Record<string, unknown>@@ -210,7 +210,7 @@ export function runServiceProcess(options: ServiceProcessOptions): ServiceProcescatch (error) { log(`[service ${options.name}] binary frame failed · ${describe(error)}`) }return}- let frame: { type?: unknown; payload?: Payload; asker?: { local?: unknown; owner?: unknown } }+ let frame: { type?: unknown; payload?: Payload; asker?: { local?: unknown; owner?: unknown; connection?: unknown; requestId?: unknown } }try { frame = JSON.parse(raw.toString()) as typeof frame } catch { return }const payload = frame.payload ?? {}if (frame.type === 'connected') {@@ -243,8 +243,14 @@ export function runServiceProcess(options: ServiceProcessOptions): ServiceProcesconst handle = Object.hasOwn(options.requests, type) ? options.requests[type] : undefinedif (!handle) returnconst requestId = payload.requestId- // Who asked, as the core established it; read as the least it could be if it is missing.- const asker = { local: frame.asker?.local === true, owner: frame.asker?.owner === true }+ // Who asked, as the core established it; read as the least it could be if it is missing. The connection+ // and its own request id, when the core gave them, are what work belonging to one connection is keyed by.+ const asker: Asker = {+ local: frame.asker?.local === true,+ owner: frame.asker?.owner === true,+ ...(typeof frame.asker?.connection === 'string' ? { connection: frame.asker.connection } : {}),+ ...(typeof frame.asker?.requestId === 'string' ? { requestId: frame.asker.requestId } : {}),+ }// A request that fails here is answered as failed, never left for the core's timeout, and in the// words the core's host uses: what went wrong goes to the log, not to whoever asked.void Promise.resolve()diff --git a/cli/src/testing/socketCore.ts b/cli/src/testing/socketCore.tsindex 08c09ff89..cf2c9f082 100644--- a/cli/src/testing/socketCore.ts+++ b/cli/src/testing/socketCore.ts@@ -9,7 +9,8 @@ import type { BackendSocket } from '../backendSocket.js'import { env } from '../config/env.js'import { createCloseRequests } from '../core/agents/close.js'import { createHandoffRequest, type Handoff, type HandoffRequest } from '../core/agents/handoff.js'-import { createLaunchRequests, type RestartAgent, type ResumeAgent } from '../core/agents/launches.js'+import { createLaunchRequests, type LaunchRequestDeps, type RestartAgent, type ResumeAgent } from '../core/agents/launches.js'+import { MODELS_OFF } from '../core/api.js'import { createPurgeRequest, createStopRequest } from '../core/agents/lifecycle.js'import { createAgentList, type AgentListDeps } from '../core/agents/list.js'import { createAgentUpdate } from '../core/agents/update.js'@@ -122,14 +123,16 @@ export function bindHandoffRequest(socket: BackendSocket, prepare: ((req: Handofsocket.handoffRequestProvider = createHandoffRequest({ prepare })}-const launchers = new WeakMap<BackendSocket, { resume: ResumeAgent | null; restart: RestartAgent | null }>()+type Launcher = { resume: ResumeAgent | null; restart: RestartAgent | null; modelTarget: LaunchRequestDeps['modelTarget'] | null }+const launchers = new WeakMap<BackendSocket, Launcher>()/** `agent_create`, `agent_create_status`, `agent_resume`, `agent_restart` and `agent_fork`* (core/agents/launches.ts), over the socket's create and fork slots and receipts of their own. A spec- * that resumes or restarts says through what; each call adds to what the last one said. */-export function bindLaunchRequests(socket: BackendSocket, over: { resume?: ResumeAgent | null; restart?: RestartAgent | null } = {}): void {+ * that resumes, restarts or creates on a grid model says through what (with none, models reads as off);+ * each call adds to what the last one said. */+export function bindLaunchRequests(socket: BackendSocket, over: Partial<Launcher> = {}): void {let launcher = launchers.get(socket)if (!launcher) {- const state = { resume: null as ResumeAgent | null, restart: null as RestartAgent | null }+ const state: Launcher = { resume: null, restart: null, modelTarget: null }launcher = statelaunchers.set(socket, state)const launches = createLaunchRequests({@@ -137,6 +140,7 @@ export function bindLaunchRequests(socket: BackendSocket, over: { resume?: ResumcreateAgent: () => socket.onCreateAgent, forkAgent: () => socket.onForkAgent,resumeAgent: () => state.resume, restartAgent: () => state.restart,byAgent: (id) => registry.byAgent(id), toProject: (s) => socket.toProject(s),+ modelTarget: (selection) => (state.modelTarget ?? MODELS_OFF.launchTarget)(selection),})socket.createProvider = launches.createsocket.createStatusProvider = launches.createStatusdiff --git a/cli/src/tui/launcher.ts b/cli/src/tui/launcher.tsindex d44bb4aba..b0be99180 100644--- a/cli/src/tui/launcher.ts+++ b/cli/src/tui/launcher.ts@@ -5,7 +5,7 @@ import { dirname, join, resolve } from 'node:path'import { promisify } from 'node:util'import { env } from '../config/env.js'import { resolveBinaryOnPath } from '../lib/binaryOnPath.js'-import { ensureHnLauncher } from '../lib/runtimeInstall.js'+import { ensureHnLauncher } from '../lib/launchers.js'import { installedTuiPath } from './paths.js'const run = promisify(execFile)