Skip to content

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

Move remaining daemon feature boundaries into services (#1008)

Dee57a750d0ca41
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 7d2da8cb0..e0a5966c3 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -69,6 +69,12 @@ jobs:
with:
ref: ${{ env.CI_SOURCE_SHA }}
fetch-depth: 0
+ # Run 37659523265 spent the entire 5-minute planning budget fetching blobs for every
+ # historical asset. Keep all commits/trees for merge-base and the complete diff, but
+ # materialize only the workflow and planner sources this job reads.
+ sparse-checkout: |
+ .github
+ scripts
- name: Validate the integration workflows
run: >-
go run github.com/rhysd/actionlint/cmd/[email protected]
diff --git a/cli/AGENTS.md b/cli/AGENTS.md
index 9ab431c14..266695f88 100644
--- a/cli/AGENTS.md
+++ b/cli/AGENTS.md
@@ -24,10 +24,10 @@ they show as `harnessd`, `harnessd-core` and `harnessd-<process>` (`src/harnessd
| Process | Runs | Started |
|---|---|---|
| master | supervision only (`src/harnessd/`) | by `harness start`, `harness start -f`, or launchd or systemd after `harness service install` |
-| core | sessions (`src/core/`), and the shell service | always |
+| core | sessions (`src/core/`) | always |
| search | session search | always |
| viewers | the harness viewers, their remote streams and rendered surfaces, and the Store | always |
-| edge | workspaces, usage, the monitor, the project readers, the change-agent handoff, the recaps | always |
+| edge | the shell service, workspaces, usage, the monitor, the project readers, the change-agent handoff, the recaps | always |
| gateway | the relay and its E2EE (`src/gateway/`) | on demand: as the core starts when signed in or anything is paired here, or when something needs it (a pairing, a window's E2EE request, a key command, the Wi-Fi device) |
| models | grid, local models, the Model Manager | on demand: once grid is in use here (a managed grid, saved grid pictures, local models), or on a models request |
| updater | checks, downloads and stages a new build (`src/services/updaterProcess.ts`) | by the master, for the installed copy only |
diff --git a/cli/build-bundle.mjs b/cli/build-bundle.mjs
index 066cdea7e..f196a85da 100644
--- a/cli/build-bundle.mjs
+++ b/cli/build-bundle.mjs
@@ -68,12 +68,26 @@ const options = {
logLevel: 'info',
}
+// Both lean builds refer to one asset file. Moving Store setup out of the core must not duplicate the
+// release-owned harnesses in the services' build and the core's legacy inline-service fallback.
+const builtinAssetsName = 'harness-builtin-assets.mjs'
+const builtinAssets = await esbuild.build({
+ ...options, entryPoints: ['src/dsh/bundledFiles.ts'], write: false, logLevel: 'warning',
+})
+const sharedBuiltinAssets = {
+ name: 'shared-builtin-assets',
+ setup(build) {
+ build.onResolve({ filter: /^\.\/bundledFiles\.js$/ }, () => ({ path: `./${builtinAssetsName}`, external: true }))
+ },
+}
+
// harnessd's master and its services, bundled on their own (src/leanEntry.ts): Node parses all of the
// file a process starts on, and the whole CLI's cost each of them about 45 MiB at idle. Split, so that a
// process parses only the files its own code is in: the master never the services', search never the
// viewers'. Carried inside cli.js, at its end, as a comment Node only skims (scripts/lib/leanBlock.mjs).
const lean = await esbuild.build({
...options,
+ plugins: [sharedBuiltinAssets],
entryPoints: { harnessd: 'src/leanEntry.ts' },
outdir: 'lean',
splitting: true,
@@ -88,6 +102,7 @@ const lean = await esbuild.build({
// meet in the folder they are written to.
const leanCore = await esbuild.build({
...options,
+ plugins: [sharedBuiltinAssets],
entryPoints: { 'harnessd-core': 'src/leanCoreEntry.ts' },
outdir: 'lean',
splitting: true,
@@ -97,6 +112,7 @@ const leanCore = await esbuild.build({
logLevel: 'warning',
})
const leanFiles = Object.fromEntries(lean.outputFiles.map((file) => [basename(file.path), asciiOnly(file.text)]))
+leanFiles[builtinAssetsName] = asciiOnly(builtinAssets.outputFiles[0].text)
for (const file of leanCore.outputFiles) {
const name = basename(file.path)
if (name in leanFiles) throw new Error(`the core's lean file ${name} has the name of one of the master's and the services'`)
diff --git a/cli/e2e/gatewayProcess.e2e.ts b/cli/e2e/gatewayProcess.e2e.ts
index 05c21a0e8..ec72d6fff 100644
--- a/cli/e2e/gatewayProcess.e2e.ts
+++ b/cli/e2e/gatewayProcess.e2e.ts
@@ -99,6 +99,34 @@ describe('the gateway in its own process', () => {
await until('the phone to open a new session', async () => { await p.open(10_000); return true }, 60_000, 500)
}
+ it('serves the reported machine list during a gateway restart, and keeps account HTTP outside the core', async () => {
+ const { machine, backend, desk, agentId } = await fresh({ HARNESSD_SERVICE_INITIAL_BACKOFF_MS: '10000', HARNESSD_SERVICE_MAX_BACKOFF_MS: '10000' }, { phone: false })
+ const d = machine.daemon
+ const machines = async () => {
+ const response = await fetch(`http://127.0.0.1:${d.port}/api/machines`, { signal: AbortSignal.timeout(10_000) })
+ return { status: response.status, body: await response.json() as Record<string, any> }
+ }
+ const first = await machines()
+ expect(first.status).toBe(200)
+ expect(first.body.data.machines.some((row: { machineId: string }) => row.machineId === machine.machineId)).toBe(true)
+ expect(backend.seen).toContain('GET /api/machines')
+ const pids = gatewayPids(d)
+ expect(pids.length).toBe(1)
+ for (const pid of pids) process.kill(pid, 'SIGKILL')
+ await until('the gateway link to go away', () => !backend.nodeUp(machine.machineId) && gatewayPids(d).length === 0 || null, 5000, 50)
+ const pairings = await desk.request('e2ee_pairings_list', {}, 5000)
+ expect(pairings).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'gateway', retryable: true })
+ const cached = await machines()
+ expect(cached.status).toBe(200)
+ expect(cached.body.data).toMatchObject({ machines: first.body.data.machines, stale: true, staleSince: expect.any(String) })
+ await deskTurn(desk, agentId, 'the local core works while account HTTP restarts')
+ await until('the gateway to reconnect', () => backend.nodeUp(machine.machineId) || null, 30_000)
+ expect((await machines()).body.data.stale).not.toBe(true)
+ backend.goDown()
+ expect((await machines()).body.data.stale).toBe(true)
+ expect(d.coresStarted()).toBe(1)
+ })
+
it('carries the phone from a process of its own: sealed both ways, with the core speaking to it in the clear', async () => {
const { backend, machine, phone, desk, agentId } = await fresh()
expect(gatewayPids(machine.daemon)).toHaveLength(1)
diff --git a/cli/e2e/services.e2e.ts b/cli/e2e/services.e2e.ts
index 81b4c7842..fbdaa86e1 100644
--- a/cli/e2e/services.e2e.ts
+++ b/cli/e2e/services.e2e.ts
@@ -13,6 +13,7 @@ import { join } from 'node:path'
import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
import { LocalClient, type Frame } from './harness/client.js'
import { IsolatedDaemon, until } from './harness/daemon.js'
+import { SERVICE_HOSTS } from '../src/harnessd/services.js'
const row = async (client: LocalClient, agentId: string) =>
((await client.request<{ agents: Array<Record<string, any>> }>('agents_list', { includeStopped: true })).agents)
@@ -54,7 +55,10 @@ const QUICK_TO_PARK = { HARNESSD_SERVICE_PARK_CRASHES: '3', HARNESSD_SERVICE_INI
/** The processes the services run in by default, and what makes every one of them fail as it starts. The
* experiments' (the teams', the orchestrator's) start only once they are on: e2e/experiments.e2e.ts. */
const SERVICE_PROCESSES = ['search', 'viewers', 'edge', 'models'] as const
-const EVERY_PROCESS_FAILING = 'search,viewers,store,workspaces,usage,monitor,projects,handoff,recaps,windowNames,models'
+// Follow the host inventory: leaving the newly extracted shell alive kept edge running, so the old
+// fixture waited forever for a crash loop it no longer caused (E2E run 37659523605).
+const EVERY_PROCESS_FAILING = Object.entries(SERVICE_HOSTS).filter(([name]) => (SERVICE_PROCESSES as readonly string[]).includes(name))
+ .flatMap(([, host]) => host.services).join(',')
describe('a failing service never takes the core down', () => {
let daemon: IsolatedDaemon | undefined
@@ -80,6 +84,7 @@ describe('a failing service never takes the core down', () => {
expect(await client.request('fs_list_dir', { path: d.projectsDir })).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'projects', retryable: true })
expect(await client.request('window_name', { agentIds: [agentId] })).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'windowNames', retryable: true })
expect(await client.request('machine_resources', {})).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'monitor', retryable: true })
+ expect(await client.request('shell_capabilities', {})).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'shell', retryable: true })
// Models is on demand and never came up: its request waits no longer than a start (core/serviceLinks.ts
// `ON_DEMAND_START_MS`), and every one after it is answered at once.
expect(await client.request('grid_fleet_models_list', {})).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'models', retryable: true })
@@ -141,10 +146,10 @@ describe('a failing service never takes the core down', () => {
})
it('with every service in the core failing to start, the core starts, runs an agent through turns and a restart, and says each service is off', async () => {
- daemon = await IsolatedDaemon.create({ env: { HARNESSD_TEST_FAULTS: 'search,viewers,models,workspaces,store,usage,monitor,projects,recaps,windowNames', ...IN_THE_CORE } })
+ daemon = await IsolatedDaemon.create({ env: { HARNESSD_TEST_FAULTS: EVERY_PROCESS_FAILING, ...IN_THE_CORE } })
onTestFailed(() => { console.log(`---- daemon log\n${daemon?.log().split('\n').slice(-80).join('\n')}`) })
await daemon.start()
- for (const service of ['search', 'viewers', 'models', 'workspaces', 'store', 'usage', 'monitor', 'projects', 'recaps', 'windowNames']) {
+ for (const service of EVERY_PROCESS_FAILING.split(',')) {
expect(daemon.log()).toContain(`[services] ${service} did not start · injected fault: ${service} · the core runs without it`)
}
const client = await LocalClient.connect(daemon)
@@ -166,6 +171,7 @@ describe('a failing service never takes the core down', () => {
// usage_read is asked only here, with its service off: on, it reads the vendors' credentials.
expect(await client.request('usage_read', {})).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'usage', retryable: false })
expect(await client.request('machine_resources', {})).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'monitor', retryable: false })
+ expect(await client.request('shell_capabilities', {})).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'shell', retryable: false })
for (const type of ['git_pull_request', 'git_project_info', 'project_preview', 'fs_list_dir', 'agent_read_file']) {
expect(await client.request(type, { agentId, path: daemon.projectsDir }), type).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'projects', retryable: false })
}
diff --git a/cli/e2e/shell.e2e.ts b/cli/e2e/shell.e2e.ts
index 2223cc8b9..240f4e019 100644
--- a/cli/e2e/shell.e2e.ts
+++ b/cli/e2e/shell.e2e.ts
@@ -1,4 +1,5 @@
/** A connected shell opens through the service, with literal arguments and the terminal's existing access rules. */
+import { execFileSync } from 'node:child_process'
import { randomUUID } from 'node:crypto'
import { existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
@@ -59,6 +60,21 @@ describe('opening connected shells', () => {
bytes: Buffer.from('printf shell-input-ok > input.txt\r') })
await until('the shell to receive input from its attached view', () => existsSync(join(fixture.cwd, 'input.txt')) || null, 20_000, 100)
expect(readFileSync(join(fixture.cwd, 'input.txt'), 'utf8')).toBe('shell-input-ok')
+ // Kill only the edge child recorded by this fixture's master. The existing terminal stream belongs
+ // to the core and must survive, while the restarted service recovers the same durable launch.
+ await until('the shell service to connect', () => d.log().includes('[services] shell connected') || null, 30_000)
+ const connects = d.log().split('[services] shell connected').length
+ const edgePid = Number([...d.log().matchAll(/\[harnessd\] service edge started \(pid (\d+)\)/g)].at(-1)?.[1])
+ expect(Number.isInteger(edgePid) && edgePid > 0).toBe(true)
+ const processRow = execFileSync('ps', ['-o', 'ppid=,command=', '-p', String(edgePid)], { encoding: 'utf8' }).trim()
+ expect(processRow).toMatch(new RegExp(`^${d.pid}\\s+harnessd-edge$`))
+ process.kill(edgePid, 'SIGKILL')
+ await until('shell receipts to reconnect after the edge crash', () => d.log().split('[services] shell connected').length > connects || null, 30_000)
+ client.sendBinary({ kind: TerminalBinaryKind.input, streamId: ready.payload!.streamId, seq: 1, compressed: false,
+ bytes: Buffer.from('printf still-connected > after-crash.txt\r') })
+ await until('the existing stream to keep writing after the service crash', () => existsSync(join(fixture.cwd, 'after-crash.txt')) || null, 20_000)
+ expect(readFileSync(join(fixture.cwd, 'after-crash.txt'), 'utf8')).toBe('still-connected')
+ expect(d.coresStarted()).toBe(1)
client.close()
const again = await LocalClient.connect(d); clients.push(again)
expect(await again.request('shell_open_status', fixture.payload)).toMatchObject({ state: 'created', agent: { id: created.agent.id } })
diff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.ts
index d7e14bd60..2562e7d80 100644
--- a/cli/src/architecture.spec.ts
+++ b/cli/src/architecture.spec.ts
@@ -170,14 +170,6 @@ const EDGE: RegExp[] = [
* list only shrinks: an entry no longer reached fails the test, so remove it with the move that ends it.
*/
const CORE_MAY_REACH: Record<string, string> = {
- 'device/machineList.ts': 'the account\'s machine list, which /api/machines answers from and the trust group reads: with the account proxies (step 10)',
- 'dsh/builtins.ts': 'the bundled harnesses are put in place by the core\'s start, which cli.js carries them for anyway; in the Store\'s lean process they cost a second copy (core/main.ts)',
- 'dsh/lock.ts': 'with dsh/builtins.ts',
- 'dsh/registry.ts': 'with dsh/builtins.ts, which checks the bundled harnesses against the catalog\'s entries',
- 'dsh/updates.ts': 'with dsh/builtins.ts',
- 'lib/autonomous-device/localApi.ts': 'the hook server\'s routes for `harness device`, which the core serves: the pairings they answer are the gateway\'s, the receipts the Wi-Fi device\'s service\'s',
- 'lib/sessionSearch/transcript.ts': 'the readers of other engines\' sessions keep this helper: it moves beside them, out of search\'s folder',
- 'services/shell.ts': 'shell setup and launch receipts, in the edge host; only the argv launch stays in the core (#893)',
}
describe('the daemon\'s shape', () => {
diff --git a/cli/src/backendSocket.dsh.spec.ts b/cli/src/backendSocket.dsh.spec.ts
index 238ff379f..f2ab74b90 100644
--- a/cli/src/backendSocket.dsh.spec.ts
+++ b/cli/src/backendSocket.dsh.spec.ts
@@ -28,7 +28,7 @@ describe('the DSH requests on the local socket', () => {
let remove: StoreDeps['remove']
const serveStore = (faults: ReadonlySet<string> = new Set()): void => {
const host = createServiceHost(emptyPorts(), { log: () => {}, faults })
- const deps: StoreDeps = { refresh: refreshDshRegistry, rows: dshListRows, mutate: (input, progress) => mutate(input, progress), remove: (id) => remove(id) }
+ const deps: StoreDeps = { prepare: () => true, refresh: refreshDshRegistry, rows: dshListRows, mutate: (input, progress) => mutate(input, progress), remove: (id) => remove(id) }
const core = fakeCore({ clients: { dshInstallStatus: (status) => socket.send({ type: 'dsh_install_status', payload: status }) } })
host.serve('store', (api) => startStore(api, deps), core, STORE_REQUESTS)
socket.serviceRouter = (type, payload, asker, reply) => host.route(type, payload, asker, reply)
diff --git a/cli/src/core/api.spec.ts b/cli/src/core/api.spec.ts
index ffc9ecdf1..0213acc2c 100644
--- a/cli/src/core/api.spec.ts
+++ b/cli/src/core/api.spec.ts
@@ -93,7 +93,7 @@ describe('the core API services stand on', () => {
expect(createCoreApi({ ...deps, conversations }).conversations).toBe(conversations)
expect(core.dataDir).toBe('/data')
expect(await core.terminals.open({ argv: ['/bin/zsh'], cwd: '/work' })).toEqual({ ok: false, error: 'SERVICE_UNAVAILABLE' })
- const terminals = { open: vi.fn(async () => ({ ok: true as const, agentId: 'shell' })), watch: TERMINALS_OFF.watch }
+ const terminals = { ...TERMINALS_OFF, open: vi.fn(async () => ({ ok: true as const, agentId: 'shell' })), watch: TERMINALS_OFF.watch }
expect(createCoreApi({ ...deps, terminals }).terminals).toBe(terminals)
expect(core.agents.all().map((s) => s.agentId)).toEqual(['live', 'stopped'])
expect(core.agents.live().map((s) => s.agentId)).toEqual(['live'])
@@ -289,6 +289,8 @@ describe('the core API services stand on', () => {
})
it('watches no terminal and signs nothing for a service without the core\'s terminals or key', async () => {
+ await expect(TERMINALS_OFF.describe('missing')).resolves.toBeNull()
+ await expect(TERMINALS_OFF.visitStatus('missing')).resolves.toEqual({ exited: false })
await expect(TERMINALS_OFF.watch.frame('observer:x', 'terminal_open', {})).resolves.toBeUndefined()
await expect(TERMINALS_OFF.watch.close('observer:x')).resolves.toBeUndefined()
expect(TERMINALS_OFF.watch.onOutput(() => {})()).toBeUndefined()
diff --git a/cli/src/core/api.ts b/cli/src/core/api.ts
index e55f819b5..e8ae6f257 100644
--- a/cli/src/core/api.ts
+++ b/cli/src/core/api.ts
@@ -66,11 +66,17 @@ export interface TerminalWatch {
}
export interface TerminalsPort {
open(request: TerminalOpen): Promise<TerminalOpenResult>
+ /** Fresh registry facts for a shell launch receipt, never a service's cached agent snapshot. */
+ describe(agentId: string): Promise<Record<string, unknown> | null>
+ /** The exact launched engine has exited, with no newer binding replacing the evidence. */
+ visitStatus(agentId: string): Promise<{ exited: boolean }>
watch: TerminalWatch
}
/** A service without the core's launch call must refuse, never launch outside the core; it watches nothing. */
export const TERMINALS_OFF: TerminalsPort = {
open: async () => ({ ok: false, error: 'SERVICE_UNAVAILABLE' }),
+ describe: async () => null,
+ visitStatus: async () => ({ exited: false }),
watch: { frame: async () => {}, close: async () => {}, onOutput: () => () => {} },
}
@@ -1170,6 +1176,14 @@ export interface GatewayAccount {
machineId: string | null
/** Which sign-in by hand this is, and the account it was made to (lib/authSession.ts `signInOf`), or null. */
signIn: { epoch: string; adopted: boolean; at: number | null; acct?: string } | null
+ autonomousEnv?: string
+}
+
+/** The gateway's last successful machine list, scoped to the account that fetched it. No credentials. */
+export interface GatewayMachines {
+ owner: string | null
+ body: Record<string, unknown> | null
+ fetchedAt: number
}
/** A Wi-Fi device operation refused, with the code the device's local API answers it under. */
@@ -1184,6 +1198,10 @@ export interface GatewayRefusal {
* the hook server's route does; while the gateway is down, a 503.
*/
export interface GatewayOps {
+ /** Account HTTP and its cache live with the network, outside the session core. */
+ backend(method: string, path: string, body?: unknown): Promise<HttpAnswer>
+ machines(fallback?: boolean): Promise<HttpAnswer>
+ mintGridName(): Promise<string | null>
status(): Promise<GatewayStatus>
pair(code: string): Promise<HttpAnswer>
listPairs(): Promise<HttpAnswer>
diff --git a/cli/src/core/gatewayLink.spec.ts b/cli/src/core/gatewayLink.spec.ts
index d0b8bdad2..741dfc37f 100644
--- a/cli/src/core/gatewayLink.spec.ts
+++ b/cli/src/core/gatewayLink.spec.ts
@@ -17,30 +17,34 @@ function events(): { [K in keyof GatewayEvents]: ReturnType<typeof vi.fn> } {
}
}
-function setup(over: { buffered?: number; call?: (type: string, payload: Record<string, unknown>, waitMs?: number) => Promise<Record<string, unknown>>; startWaitMs?: number } = {}) {
+function setup(over: { buffered?: number; call?: (type: string, payload: Record<string, unknown>, waitMs?: number) => Promise<Record<string, unknown>>; startWaitMs?: number; start?: () => Record<string, unknown> } = {}) {
const heard = events()
const sent: Array<Record<string, unknown>> = []
const binary: Uint8Array[] = []
let buffered = over.buffered ?? 0
+ let writable = true
const log = vi.fn()
let clock = 1_000_000
const call = vi.fn(over.call ?? (async () => ({ status: 200, body: { ok: true } })))
const tokens = { accessToken: vi.fn(async () => 'token-1') }
const backend = vi.fn(async () => ({ status: 200, body: { data: { seen: {} } } }))
const want = vi.fn()
+ const machines = vi.fn()
const link = createGatewayLink({
events: heard as unknown as GatewayEvents,
- notify: (frame) => { sent.push(frame.payload as Record<string, unknown>); return true },
+ notify: (frame) => { sent.push(frame.payload as Record<string, unknown>); return writable },
notifyBinary: (bytes) => { binary.push(bytes); return true },
buffered: () => buffered,
call,
- start: () => ({ machineId: 'm1', computerId: 'c1', autonomousEnv: 'prod', signedIn: true }),
+ start: over.start ?? (() => ({ machineId: 'm1', computerId: 'c1', autonomousEnv: 'prod', signedIn: true })),
+ machines,
tokens, backend, log, now: () => clock, want, ...(over.startWaitMs ? { startWaitMs: over.startWaitMs } : {}),
})
return {
- link, heard, sent, binary, call, tokens, backend, log, want,
+ link, heard, sent, binary, call, tokens, backend, log, want, machines,
kinds: () => sent.map((payload) => payload.kind),
setBuffered: (bytes: number) => { buffered = bytes },
+ setWritable: (value: boolean) => { writable = value },
tick: (ms: number) => { clock += ms },
}
}
@@ -290,7 +294,7 @@ describe('the gateway in its own process, as the core sees it', () => {
void link.port.local('conn-1', { type: 'e2ee_pairings_list', payload: {} })
vi.advanceTimersByTime(20_000)
await expect(opening).rejects.toEqual(new RelayConnectError('the relay did not start', WINDOW_GATEWAY_GONE))
- // Its E2EE request is the window's own deadline's: not sent late to a gateway that came after all.
+ // No late E2EE request goes to a gateway that came after the startup deadline.
link.connected()
expect(sent.map((payload) => payload.kind)).toEqual(['start'])
@@ -521,3 +525,171 @@ describe('a window here working on another machine, through the gateway', () =>
await session.sendBinary(bytesOf('x'))
})
})
+
+describe('local requests when the gateway cannot answer', () => {
+ const request = (requestId: string, type = 'e2ee_pairings_list') => ({ type, payload: { requestId } })
+ const refusal = (requestId: string, type = 'e2ee_pairings_list') => ({
+ type: `${type}_result`, payload: { requestId, error: 'SERVICE_UNAVAILABLE', service: 'gateway', retryable: true },
+ })
+
+ it('refuses in-flight and new requests on disconnection, without failing an answered request or replaying one', async () => {
+ const { link, heard, kinds } = setup()
+ link.connected()
+ await link.port.local('a', request('done'))
+ await link.port.local('a', request('waiting'))
+ await link.port.local('b', request('waiting'))
+ link.notice({ kind: 'toLocal', connId: 'a', frame: { type: 'e2ee_pairings_list_result', payload: { requestId: 'done', pairs: [] } } })
+ // Neither an unrelated request type nor another connection can complete this request.
+ link.notice({ kind: 'toLocal', connId: 'a', frame: { type: 'phone_pair_result', payload: { requestId: 'waiting' } } })
+ link.notice({ kind: 'toLocal', connId: 'other', frame: { type: 'e2ee_pairings_list_result', payload: { requestId: 'waiting' } } })
+ heard.toLocal.mockClear()
+ link.disconnected()
+ expect(heard.toLocal.mock.calls).toEqual([['a', refusal('waiting')], ['b', refusal('waiting')]])
+ await link.port.local('a', request('down'))
+ expect(heard.toLocal).toHaveBeenLastCalledWith('a', refusal('down'))
+ link.connected()
+ expect(kinds()).toEqual(['start', 'localFrame', 'localFrame', 'localFrame', 'start'])
+ })
+
+ it('answers when a connected socket refuses the frame', async () => {
+ const { link, heard, setWritable } = setup()
+ link.connected()
+ setWritable(false)
+ await link.port.local('a', request('failed-send'))
+ expect(heard.toLocal.mock.calls).toEqual([['a', refusal('failed-send')]])
+ link.disconnected()
+ expect(heard.toLocal).toHaveBeenCalledOnce()
+ })
+
+ it('bounds the unanswered wait, gives interactive pairing its own deadline, and coalesces an identical pending request', async () => {
+ vi.useFakeTimers()
+ try {
+ const { link, heard, kinds } = setup()
+ link.connected()
+ await link.port.local('a', request('list'))
+ await link.port.local('a', request('list'))
+ await link.port.local('a', request('phone', 'phone_pair'))
+ await link.port.local('a', request('device', 'device_e2ee_pair'))
+ expect(kinds()).toEqual(['start', 'localFrame', 'localFrame', 'localFrame'])
+ vi.advanceTimersByTime(LANE_WAIT_MS)
+ expect(heard.toLocal.mock.calls).toEqual([['a', refusal('list')]])
+ vi.advanceTimersByTime(PAIR_WAIT_MS - LANE_WAIT_MS)
+ expect(heard.toLocal.mock.calls.slice(1)).toEqual([['a', refusal('phone', 'phone_pair')], ['a', refusal('device', 'device_e2ee_pair')]])
+ link.disconnected()
+ expect(heard.toLocal).toHaveBeenCalledTimes(3)
+ } finally { vi.useRealTimers() }
+ })
+
+ it('bounds in-flight requests and refuses excess work before it can mutate pairing state', async () => {
+ const { link, heard, kinds } = setup()
+ link.connected()
+ for (let i = 0; i < OWED_MAX; i++) await link.port.local('a', request(String(i)))
+ await link.port.local('a', request('excess', 'e2ee_pairings_unpair_all'))
+ expect(heard.toLocal.mock.calls).toEqual([['a', refusal('excess', 'e2ee_pairings_unpair_all')]])
+ expect(kinds().filter((kind) => kind === 'localFrame')).toHaveLength(OWED_MAX)
+ link.disconnected()
+ expect(heard.toLocal).toHaveBeenCalledTimes(OWED_MAX + 1)
+ })
+
+ it('refuses queued requests on startup expiry and eviction, never sending refused mutations later', async () => {
+ vi.useFakeTimers()
+ try {
+ const { link, heard, sent } = setup()
+ for (let i = 0; i <= OWED_MAX; i++) await link.port.local('a', request(String(i), 'e2ee_pairing_unpair'))
+ expect(heard.toLocal.mock.calls).toEqual([['a', refusal('0', 'e2ee_pairing_unpair')]])
+ vi.advanceTimersByTime(ON_DEMAND_START_MS)
+ expect(heard.toLocal).toHaveBeenCalledTimes(OWED_MAX + 1)
+ link.connected()
+ expect(sent.map((payload) => payload.kind)).toEqual(['start'])
+ } finally { vi.useRealTimers() }
+ })
+})
+
+describe('account HTTP owned by the gateway', () => {
+ it('forwards methods and optional bodies, and bounds the answer', async () => {
+ const { link, call } = setup()
+ expect(await link.ops.backend('GET', '/api/auth/me')).toEqual({ status: 200, body: { ok: true } })
+ expect(call).toHaveBeenLastCalledWith(GATEWAY_CALLS.backend, { method: 'GET', path: '/api/auth/me' }, 25_000)
+ await link.ops.backend('PATCH', '/api/machines/m1', { name: 'Laptop' })
+ expect(call).toHaveBeenLastCalledWith(GATEWAY_CALLS.backend, { method: 'PATCH', path: '/api/machines/m1', body: { name: 'Laptop' } }, 25_000)
+ call.mockResolvedValueOnce({ name: 'private-grid' })
+ expect(await link.ops.mintGridName()).toBe('private-grid')
+ call.mockResolvedValueOnce({})
+ expect(await link.ops.mintGridName()).toBeNull()
+ call.mockResolvedValueOnce({ error: 'SERVICE_UNAVAILABLE' })
+ await expect(link.ops.mintGridName()).rejects.toThrow('SERVICE_UNAVAILABLE')
+ })
+
+ it('answers the guest list without waking a gateway or reading a previous account', async () => {
+ const { link, call, want, machines } = setup({ start: () => ({ signedIn: true, account: { machineId: null }, computerId: 'computer', machineName: 'Laptop', hostname: 'host' }) })
+ expect(await link.ops.machines()).toMatchObject({ status: 200, body: { data: { guest: true, stale: false, machines: [
+ { machineId: 'computer', computerId: 'computer', name: 'Laptop', hostname: 'host', status: 'online' },
+ ] } } })
+ expect(call).not.toHaveBeenCalled()
+ expect(want).not.toHaveBeenCalled()
+ expect(machines).toHaveBeenCalledWith(expect.objectContaining({ owner: null }))
+ })
+
+ it('retains reported rows across a crash, but never hides a sign-out or crosses accounts', async () => {
+ let owner = 'account-a'
+ const { link, call, machines } = setup({ start: () => ({ signedIn: true, account: { machineId: owner } }) })
+ const body = { success: true, data: { machines: [{ machineId: 'm2' }] } }
+ link.notice({ kind: 'machines', owner, body, fetchedAt: 1000 })
+ expect(machines).toHaveBeenLastCalledWith({ owner, body, fetchedAt: 1000 })
+ call.mockResolvedValue({ error: 'SERVICE_UNAVAILABLE' })
+ link.disconnected()
+ expect(await link.ops.machines(true)).toEqual({ status: 200, body: { success: true, data: { machines: [{ machineId: 'm2' }], stale: true, staleSince: new Date(1000).toISOString() } } })
+ expect((await link.ops.machines()).status).toBe(503)
+ owner = 'account-b'
+ expect((await link.ops.machines(true)).status).toBe(503)
+ owner = ''
+ expect(await link.ops.machines(true)).toMatchObject({ status: 200, body: { data: { guest: true, stale: false } } })
+ owner = 'account-a'
+ call.mockResolvedValueOnce({ status: 401, body: { error: 'NOT_SIGNED_IN' } })
+ expect((await link.ops.machines(true)).status).toBe(401)
+ expect((await link.ops.machines(true)).status).toBe(503)
+ link.notice({ kind: 'machines', owner, body, fetchedAt: 1000 })
+ call.mockResolvedValueOnce({ status: 403, body: {} })
+ expect((await link.ops.machines(true)).status).toBe(403)
+ expect((await link.ops.machines(true)).status).toBe(503)
+ link.notice({ kind: 'machines', owner, body: null, fetchedAt: 1000 })
+ expect((await link.ops.machines(true)).status).toBe(503)
+ })
+
+ it('accepts empty notices and bounds malformed timestamps before a stale response uses one', () => {
+ const { link, machines } = setup()
+ for (const fetchedAt of [undefined, Infinity, 1e30]) {
+ link.notice({ kind: 'machines', owner: null, body: [], fetchedAt })
+ expect(machines).toHaveBeenLastCalledWith({ owner: null, body: null, fetchedAt: 1_000_000 })
+ }
+ link.notice({ kind: 'machines' })
+ expect(machines).toHaveBeenLastCalledWith({ owner: null, body: null, fetchedAt: 1_000_000 })
+ })
+})
+
+it('rejects a reply when the core changed accounts while the gateway was answering', async () => {
+ let owner = 'a'
+ const { link } = setup({ start: () => ({ signedIn: true, account: { machineId: owner } }),
+ call: async () => { owner = 'b'; return { status: 200, body: { machines: ['a'] } } } })
+ expect(await link.ops.machines(true)).toMatchObject({ status: 409, body: { error: { code: 'ACCOUNT_CHANGED' } } })
+})
+
+it('forgets reported presence when accounts change and ignores notices already in flight from the old account', () => {
+ let owner = 'a'
+ const { link, machines } = setup({ start: () => ({ account: { machineId: owner } }) })
+ const body = { machines: [{ machineId: 'private-a' }] }
+ link.notice({ kind: 'machines', owner, body, fetchedAt: 1000 })
+ link.ops.account({ machineId: owner, signIn: null })
+ expect(machines).toHaveBeenCalledTimes(1)
+ owner = 'b'
+ link.ops.account({ machineId: owner, signIn: null })
+ expect(machines).toHaveBeenLastCalledWith({ owner, body: null, fetchedAt: 1_000_000 })
+ link.notice({ kind: 'machines', owner: 'a', body, fetchedAt: 1001 })
+ expect(machines).toHaveBeenCalledTimes(2)
+})
+
+it('uses fresh account facts rather than the relay startup sign-in flag', async () => {
+ const { link, call } = setup({ start: () => ({ signedIn: false, account: { machineId: 'new-account' } }) })
+ expect(await link.ops.machines()).toEqual({ status: 200, body: { ok: true } })
+ expect(call).toHaveBeenCalledWith(GATEWAY_CALLS.machines, { fallback: false }, 25_000)
+})
diff --git a/cli/src/core/gatewayLink.ts b/cli/src/core/gatewayLink.ts
index 3cc0dee7f..2923df65d 100644
--- a/cli/src/core/gatewayLink.ts
+++ b/cli/src/core/gatewayLink.ts
@@ -20,6 +20,8 @@ import { RelayConnectError } from '../lib/relayFrames.js'
import { decodeGatewayBinary, encodeGatewayBinary, GatewayBinary, GATEWAY_CALLS } from '../lib/gatewayWire.js'
import { decodeTerminalLocal, encodeTerminalLocal } from '../lib/terminalBinary.js'
import { answerAccountQuery } from './accountQueries.js'
+import { guestMachineList, withStaleMarker } from '../lib/machineListReply.js'
+import type { GatewayMachines } from './api.js'
import { LANE_OFF } from './api.js'
import type {
BackendNotice, GatewayEvents, LocalWindows, GatewayOps, GatewayPort, GatewayRefusal, GatewayStatus, HttpAnswer, LaneSeal,
@@ -41,6 +43,8 @@ export interface GatewayLinkDeps {
tokens: { accessToken(opts?: { force?: boolean; failedToken?: string }): Promise<string> }
/** A read of the backend's REST API under the account's session (the core's proxy). */
backend(method: 'GET', path: string): Promise<HttpAnswer>
+ /** The last machine list reported by the gateway, for the models service's presence labels. */
+ machines?(state: GatewayMachines): void
/** Ask the master for the gateway's process (harnessd/coreLink.ts `want`): it runs on demand (core/gatewayWake.ts). */
want?(): void
/** How long what waits for the gateway's first start waits (core/serviceLinks.ts `ON_DEMAND_START_MS`). */
@@ -103,9 +107,11 @@ export function createGatewayLink(deps: GatewayLinkDeps) {
let localClients: LocalWindows = { desktop: 0, tui: 0 }
let wifiService = false
let reachable: string[] | null = null
+ let machines: GatewayMachines | null = null
/** The remote clients the gateway registered, to forget each when it goes. */
const clients = new Set<string>()
const windows = new Map<string, Window>()
+ const localRequests = new Map<string, { fail(): void; finish(): void }>()
let droppedSaidAt = -Infinity
let droppedUnsaid = 0
@@ -130,10 +136,34 @@ export function createGatewayLink(deps: GatewayLinkDeps) {
asked = true
deps.want?.()
}
- /** What waits for the first start gives up when it has not come in time: a session to open is closed, to be
- * tried again; an E2EE request is left to the window's own deadline. */
+ const localKey = (connId: string, type: unknown, requestId: unknown): string | null =>
+ requestId === undefined ? null : JSON.stringify([connId, type, requestId])
+ const refuseLocal = (connId: string, frame: Record<string, unknown>): void => {
+ const requestId = record(frame.payload).requestId
+ if (requestId !== undefined) events.toLocal(connId, {
+ type: `${frame.type}_result`, payload: { requestId, error: 'SERVICE_UNAVAILABLE', service: 'gateway', retryable: true },
+ })
+ }
+ /** Chaos testing killed the gateway between a local request and its reply. The core must answer for a
+ * lost link, including in-flight requests; the window's longer deadline is not a service fallback.
+ * Bound both the wait and the number held, and never replay a pairing or revocation after a restart. */
+ const forwardLocal = (connId: string, frame: Record<string, unknown>): void => {
+ const key = localKey(connId, `${frame.type}_result`, record(frame.payload).requestId)
+ if (key !== null) {
+ if (localRequests.has(key)) return
+ if (localRequests.size >= OWED_MAX) { refuseLocal(connId, frame); return }
+ const finish = (): void => { clearTimeout(timer); localRequests.delete(key) }
+ const fail = (): void => { finish(); refuseLocal(connId, frame) }
+ const timer = setTimeout(fail, frame.type === 'phone_pair' || frame.type === 'device_e2ee_pair' ? PAIR_WAIT_MS : LANE_WAIT_MS)
+ timer.unref?.()
+ localRequests.set(key, { fail, finish })
+ }
+ if (!send('localFrame', { connId, frame }) && key !== null) localRequests.get(key)!.fail()
+ }
+ /** What waits for the first start gives up explicitly: no late pairing or window open after refusal. */
const giveUp = (item: Record<string, unknown>): void => {
if (item.kind === 'windowOpen') closeWindow(text(item.id), WINDOW_GATEWAY_GONE, 'the relay did not start')
+ else refuseLocal(text(item.connId), record(item.frame))
}
const owe = (kind: string, payload: Record<string, unknown>): void => {
owed.push({ ...payload, kind })
@@ -164,7 +194,7 @@ export function createGatewayLink(deps: GatewayLinkDeps) {
observer: (connId, type, payload) => up && linkUp && send('observer', { connId, type, payload }),
windowOpened: (surface) => { send('windowOpened', { surface }) },
localClients: (windows) => { localClients = windows; send('localClients', { windows }) },
- local: async (connId, frame) => { if (up || seen) send('localFrame', { connId, frame }); else owe('localFrame', { connId, frame }) },
+ local: async (connId, frame) => { if (up || seen) forwardLocal(connId, frame); else owe('localFrame', { connId, frame }) },
device: (connId, type, payload) => reachableClient(connId) && send('device', { connId, type, payload }),
deviceClient: (connId, identity) => { send('deviceClient', { connId, identity }) },
stop: async () => { send('stop') },
@@ -210,6 +240,32 @@ export function createGatewayLink(deps: GatewayLinkDeps) {
}
const ops: GatewayOps = {
+ backend: (method, path, body) => http(GATEWAY_CALLS.backend, { method, path, ...(body === undefined ? {} : { body }) }, 25_000),
+ machines: async (fallback = false) => {
+ const state = deps.start()
+ const requestedOwner = text(record(state.account).machineId)
+ if (!requestedOwner) {
+ const body = guestMachineList(text(state.computerId), text(state.machineName), text(state.hostname))
+ deps.machines?.({ owner: null, body, fetchedAt: now() })
+ return { status: 200, body }
+ }
+ const answer = await http(GATEWAY_CALLS.machines, { fallback }, 25_000)
+ const currentOwner = text(record(deps.start().account).machineId)
+ if (requestedOwner !== currentOwner) return { status: 409, body: { success: false, error: { code: 'ACCOUNT_CHANGED', message: 'The account changed. Refresh and try again.' } } }
+ if (answer.status === 401 || answer.status === 403) machines = null
+ const owner = currentOwner
+ // A crashed gateway costs the network, not the app's last known roster. Never cross accounts or
+ // hide a real sign-out with rows cached for an earlier session.
+ if (fallback && answer.status >= 500 && owner && machines?.owner === owner && machines.body) {
+ return { status: 200, body: withStaleMarker(machines.body, machines.fetchedAt) }
+ }
+ return answer
+ },
+ mintGridName: async () => {
+ const answer = await deps.call(GATEWAY_CALLS.mintGridName, {}, 15_000)
+ if (typeof answer.error === 'string') throw new Error(answer.error)
+ return typeof answer.name === 'string' ? answer.name : null
+ },
status: async (): Promise<GatewayStatus> => {
// Never started, it has no pairing under way and nothing to say; `/api/status` is asked far too often to
// start it for.
@@ -248,7 +304,13 @@ export function createGatewayLink(deps: GatewayLinkDeps) {
},
wifiService: (on) => { wifiService = on; if (on) need(); send('wifiService', { on }) },
revokeIdentity: (identity) => { send('revokeIdentity', { identity }) },
- account: (next) => { send('account', { account: next }) },
+ account: (next) => {
+ if (machines && machines.owner !== next.machineId) {
+ machines = null
+ deps.machines?.({ owner: next.machineId, body: null, fetchedAt: now() })
+ }
+ send('account', { account: next })
+ },
reachable: (machineIds) => { reachable = machineIds; send('reachable', { machineIds }) },
lane: laneOps,
observerKey: {
@@ -319,9 +381,13 @@ export function createGatewayLink(deps: GatewayLinkDeps) {
case 'observer':
void events.observer(connId, text(payload.type), record(payload.payload))
return
- case 'toLocal':
- events.toLocal(connId, record(payload.frame))
+ case 'toLocal': {
+ const frame = record(payload.frame)
+ const key = localKey(connId, frame.type, record(frame.payload).requestId)
+ if (key !== null) localRequests.get(key)?.finish()
+ events.toLocal(connId, frame)
return
+ }
case 'status':
linkUp = payload.connected === true
events.status(linkUp)
@@ -341,6 +407,15 @@ export function createGatewayLink(deps: GatewayLinkDeps) {
case 'notice':
events.notice(record(payload.notice) as unknown as BackendNotice)
return
+ case 'machines': {
+ const owner = text(payload.owner) || null
+ if (owner !== (text(record(deps.start().account).machineId) || null)) return
+ const body = payload.body && typeof payload.body === 'object' && !Array.isArray(payload.body) ? record(payload.body) : null
+ machines = { owner, body,
+ fetchedAt: typeof payload.fetchedAt === 'number' && Number.isFinite(payload.fetchedAt) && Math.abs(payload.fetchedAt) <= 8.64e15 ? payload.fetchedAt : now() }
+ deps.machines?.(machines)
+ return
+ }
case 'revoked':
events.revoked()
return
@@ -421,11 +496,15 @@ export function createGatewayLink(deps: GatewayLinkDeps) {
// Then what waited for its first start, in the order it came.
if (owedTimer) clearTimeout(owedTimer)
owedTimer = null
- for (const { kind, ...payload } of owed.splice(0)) send(text(kind), payload)
+ for (const { kind, ...payload } of owed.splice(0)) {
+ if (kind === 'localFrame') forwardLocal(text(payload.connId), record(payload.frame))
+ else send(text(kind), payload)
+ }
},
/** The gateway's process went: the relay with it, as far as everything in the core is concerned. */
disconnected(): void {
up = false
+ for (const request of localRequests.values()) request.fail()
for (const id of [...windows.keys()]) closeWindow(id, WINDOW_GATEWAY_GONE, 'the relay restarted')
// Each remote client's connection ended with it: what it had open here goes (its terminals, its
// viewers, the Wi-Fi device service's hold on it).
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index 0b9839333..70cd56c70 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -9,7 +9,6 @@
* or `start -f` with `HARNESS_NO_MASTER=1`), calls in here. `start -f` runs harnessd's master, which starts
* the core with `__run`.
*/
-import { ensureBundledCoreHarnesses } from '../dsh/builtins.js'
import { readFileSync, writeFileSync, openSync, existsSync, rmSync, statSync } from 'fs'
import { join } from 'path'
import { execFile, spawn } from 'child_process'
@@ -22,7 +21,6 @@ import { warmLoginShellEnvironment } from '../lib/loginShellEnv.js'
import type { AppSwarms } from '../cable/cableSession.js'
import type { UnreadNotification } from '../lib/notificationRead.js'
import { terminalActivity } from '../lib/terminalActivity.js'
-import { MachineListCache, withStaleMarker } from '../device/machineList.js'
import { registry, projectDisplayName, validTranscriptPath, type RegisteredSession } from '../lib/registry.js'
import { engineSessionTitle } from '../lib/sessionTitle.js'
import { machineNames } from '../lib/machineNames.js'
@@ -32,7 +30,7 @@ import { clearSafeModeMarker, safeModeDisposition, safeModeStatusBody, SafeModeR
import { awakeTimeout } from '../lib/sleepAware.js'
import { removePidFileIf, onError } from '../lib/daemonLaunch.js'
import { ensureTmuxOnPath } from '../lib/tmuxOnPath.js'
-import { AUTH_DIR, AuthSessionError, AuthSessionManager, clearAuthSession, ensureSignInEpoch, readAuthSession, signInOf, type AuthSession } from '../lib/authSession.js'
+import { AUTH_DIR, AuthSessionManager, clearAuthSession, ensureSignInEpoch, readAuthSession, signInOf, type AuthSession } from '../lib/authSession.js'
import { ENGINES, enginePathOverride } from '../lib/engineBin.js'
import { isTerminalEngine } from '../engines/types.js'
import { engineInstallRecipe } from '../lib/engineInstall.js'
@@ -77,7 +75,10 @@ import { Watcher } from '../watcher/watcher.js'
import { startHookServer } from '../hookServer.js'
import { connectToMaster } from '../harnessd/coreLink.js'
import { createTerminalOpener } from './terminals/open.js'
-import { SHELL_REQUESTS, startShell } from '../services/shell.js'
+import { createTerminalSessions } from './terminals/sessions.js'
+import { checkPidRuntime } from '../lib/deleteAgentFallback.js'
+import { SHELL_REQUESTS } from '../lib/shellProtocol.js'
+import { answerShellQuery } from './shellQueries.js'
import { createTerminalControl } from './terminals/control.js'
import { createTerminalRequests } from './terminals/requests.js'
import { createAgentEvents } from './agents/events.js'
@@ -129,7 +130,7 @@ import { createMonitorLink } from './monitorLink.js'
import { createStoreLink } from './storeLink.js'
import { createModelsLink } from './modelsLink.js'
import { createRecapsLink } from './recapsLink.js'
-import { RECAPS_FALLBACKS } from './api.js'
+import { RECAPS_FALLBACKS, TERMINALS_OFF } from './api.js'
import { answerAgentQuery } from './agentQueries.js'
import { createDeliveries } from './deliveries.js'
import { createTerminalWatch } from './terminalWatch.js'
@@ -154,7 +155,7 @@ import { wakeModels } from './modelsWake.js'
import { wakeGateway } from './gatewayWake.js'
import { createWifiLink } from './wifiLink.js'
import { wifiDoors } from './wifiAgents.js'
-import { autonomousDeviceLocalRequest } from '../lib/autonomous-device/localApi.js'
+import { autonomousDeviceLocalRequest } from '../lib/deviceManagementHttp.js'
import { attachLocalWsServer, LOCAL_WS_PATH, LOCAL_WS_PROTOCOL_VERSION } from '../localWsServer.js'
import { TERMINAL_BINARY_VERSION } from '../lib/terminalBinary.js'
import { isLoopbackRequest, loopbackHosts } from '../lib/loopbackRequest.js'
@@ -174,7 +175,7 @@ import { agentTokenUsage } from '../lib/agentTokenUsage.js'
import { RuntimeProfileManager, type RuntimeModelOption } from '../lib/runtimeProfile.js'
import { RuntimeProfileController } from '../lib/runtimeProfileController.js'
import { installTimestampedConsole, sid, prepareLogFile, trimLogFile, LOG_CHECK_INTERVAL_MS } from '../lib/log.js'
-import { PROXY_BACKEND_TIMEOUT_MS, GRID_MINT_TIMEOUT_MS, backendHttpBase, postJson, controlPlaneAuth } from '../lib/controlPlane.js'
+import { backendHttpBase } from '../lib/controlPlane.js'
// Daemon stdout/stderr. Capped at LOG_MAX_BYTES — see prepareLogFile/trimLogFile in lib/log.ts.
const LOG_FILE = DAEMON_LOG_FILE
@@ -608,7 +609,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
})
const coreApi = createCoreApi({
// Agents' terminals: a literal-argv launch, and a read-only view for Share's observers (core/terminalWatch.ts).
- terminals: { ...createTerminalOpener({ tmuxBackend, registry, announceSession, blocksFolder: (cwd) => !!backendRef?.purgeAgentService?.blocksFolder(cwd) }), watch: terminalWatch.watch },
+ terminals: { ...TERMINALS_OFF, ...createTerminalOpener({ tmuxBackend, registry, announceSession, blocksFolder: (cwd) => !!backendRef?.purgeAgentService?.blocksFolder(cwd) }), watch: terminalWatch.watch },
dataDir: env.ADAPTER_DATA_DIR,
registry,
stoppedAgents,
@@ -632,10 +633,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// The backend mints and remembers the account's grid name; this CLI holds neither the account's
// email nor its id. An older backend (no route) answers nothing, which the grid reconcile treats as
// "no grid yet". Bounded so a stalled control-plane connection cannot hold the attempt open.
- mintGridName: async () => {
- const { headers } = await controlPlaneAuth()
- return (await postJson<{ gridName?: string }>('/api/grid/name', {}, headers, AbortSignal.timeout(GRID_MINT_TIMEOUT_MS))).gridName ?? null
- },
+ mintGridName: () => gatewayOps.mintGridName(),
accessToken: (options) => auth.accessToken(options),
// The fleet's lane's sessions are the gateway's, which holds this machine's E2EE identity; it starts
// below, before the devices whose fleet seals through it.
@@ -643,7 +641,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
signedIn: () => readAuthSession() !== null,
environment: () => readAuthSession()?.autonomousEnv ?? env.AUTONOMOUS_ENV,
// Built further down, with the account proxies: read when the devices ask, never now.
- machines: () => machinesNow(),
+ machines: () => gatewayOps.machines(),
machine: {
id: () => backendRef?.machineId ?? '',
computerId: () => computerId(),
@@ -782,7 +780,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// The relay and its E2EE (gateway/): the backend link, the sessions and the keys, which every remote
// client's frames go through, held at the same gate. In its own process by default (core/gatewayLink.ts),
// or here (gateway/start.ts); the socket hears it through `fromGateway` and speaks to it in the clear.
- const account = (s = readAuthSession()): GatewayAccount => ({ machineId: s?.machineId ?? null, signIn: signInOf(s?.signInEpoch, s?.signInAcct) })
+ Object.assign(coreApi.terminals, createTerminalSessions({ agents: coreApi.agents, paneState: tmuxPaneState, processState: checkPidRuntime }))
+ const account = (s = readAuthSession()): GatewayAccount => ({ machineId: s?.machineId ?? null, signIn: signInOf(s?.signInEpoch, s?.signInAcct), autonomousEnv: s?.autonomousEnv ?? env.AUTONOMOUS_ENV })
let serviceLinksRef: ServiceLinks | null = null
const gatewayLink = outOfProcess.has('gateway') ? createGatewayLink({
events: backend.fromGateway,
@@ -790,12 +789,14 @@ async function runForeground(session: AuthSession | null): Promise<void> {
notifyBinary: (bytes) => serviceLinksRef?.notifyBinary('gateway', bytes) ?? false,
buffered: () => serviceLinksRef?.buffered('gateway') ?? 0,
call: (type, payload, waitMs) => serviceLinksRef?.call('gateway', type, payload, waitMs) ?? Promise.resolve({ error: 'SERVICE_UNAVAILABLE' }),
- start: () => ({ machineId: backend.machineId, computerId: computerId(), autonomousEnv, signedIn: !!session?.machineId, account: account() }),
+ start: () => ({ machineId: backend.machineId, computerId: computerId(), autonomousEnv, signedIn: !!session?.machineId, account: account(), machineName: terminalHintMachineName(), hostname: hostname() }),
tokens: auth, backend: (method, path) => proxyBackend(method, path), want: () => coreLink.want('gateway'),
+ machines: ({ body }) => ports.models?.machines(body, computerId()),
}) : null
const gateway = gatewayLink ?? inline!.startGateway({
events: backend.fromGateway, machineId: backend.machineId, computerId: computerId(), autonomousEnv,
- signedIn: !!session?.machineId, tokens: auth, backend: (method, path) => proxyBackend(method, path), account: account(),
+ signedIn: !!session?.machineId, tokens: auth, account: account(), machineName: terminalHintMachineName(), hostname: hostname(),
+ machines: ({ body }) => ports.models?.machines(body, computerId()),
})
backend.useGateway(gateway.port)
backend.useWifi(wifiCore.fromGateway)
@@ -811,12 +812,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// This machine's viewers, served to a client over its connection by the viewers (core/viewerStreams.ts).
backend.viewerStreams = createViewerStreams(() => ports.viewers, (connId, type, payload) => backend.sendViewerFrame(connId, type, payload))
- // The harnesses the release bundles (the Model Manager, Devices, the Harness Monitor), before restore
- // relaunches an agent on one. Here and not in the Store's process: its lean bundle would carry a second
- // copy of their files (571 KB more cli.js) and the viewers' process held 12 MiB more at idle (measured
- // 2026-10-06), while cli.js, which the core runs, carries them anyway.
- ensureBundledCoreHarnesses()
-
/**
* Is ANY device surface watching this machine?
*
@@ -1091,7 +1086,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// 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, models: MODELS_REQUESTS, handoff: HANDOFF_REQUESTS,
- devices: DEVICES_REQUESTS, windowNames: WINDOW_NAMES_REQUESTS,
+ devices: DEVICES_REQUESTS, windowNames: WINDOW_NAMES_REQUESTS, shell: SHELL_REQUESTS,
...Object.fromEntries(Object.entries(EXPERIMENTS).map(([name, experiment]) => [name, experiment.requests])),
}
// The experiments (core/api.ts `EXPERIMENTS`): each may act on the core through the hooks an experiment has.
@@ -1143,7 +1138,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {
owned: Object.fromEntries([...outOfProcess].map((name) => [name, requestsOf[name] ?? []])),
waits: LONG_ANSWERS,
// An experiment's process runs once on, the devices' once there is one, models' and the gateway's once needed: a request asks.
- onDemand: new Set([...experiments, ...DEVICES_ON_DEMAND, 'models', 'gateway']),
+ // Shell is in the always-running edge host, but its first request can beat that host's connection.
+ // Hold it through the same bounded startup gate; after any disconnect, fail promptly as before.
+ onDemand: new Set([...experiments, ...DEVICES_ON_DEMAND, 'models', 'gateway', 'shell']),
want: (service) => experimentHooks.want(service),
// The gateway's first: its `backend` reads (the device key log) were refused below as NOT_AN_EXPERIMENT.
answer: async (service, query, payload) => (service === 'gateway' && gatewayLink ? gatewayLink.answer(query, payload) : null) ?? deliveries.answer(service, query, payload)
@@ -1158,6 +1155,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
: service === 'devices' ? devicesLink.answer(query, payload)
: service === 'wifi' ? wifiLink.answer(query, payload)
: service === 'handoff' ? answerConversationQuery(coreApi, query, payload)
+ : service === 'shell' ? answerShellQuery(coreApi, query, payload)
: service === 'recaps' ? recapsLink.answer(query, payload) : answerAgentQuery(coreApi, query)),
// The gateway's own traffic: its remote clients and what they sent, and its comings and goings; and what
// the devices tell the core (a turn, a frame for the windows, a dial on the wire); a viewer stream's answers.
@@ -1237,7 +1235,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
if (!outOfProcess.has('handoff')) serviceHost.serve('handoff', inline!.startHandoff, coreApi, HANDOFF_REQUESTS)
// The recaps: in this process, or in the edge host (services/recapsProcess.ts), told each turn's lifecycle.
if (outOfProcess.has('recaps')) ports.recaps = recapsLink.port; else serviceHost.start('recaps', inline!.startRecaps, coreApi, RECAPS_FALLBACKS)
- serviceHost.serve('shell', startShell, coreApi, SHELL_REQUESTS)
+ if (!outOfProcess.has('shell')) serviceHost.serve('shell', inline!.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.
@@ -1425,158 +1423,12 @@ async function runForeground(session: AuthSession | null): Promise<void> {
},
})
- /** Proxy a control-plane call to backend using THIS daemon's own SSO session — the local caller
- * (e.g. the desktop app) never needs a bearer token of its own, loopback trust does the
- * authenticating. Forwards backend's response status/body verbatim, success or error alike, so a
- * local client's model layer needs zero special-casing versus talking to backend directly. */
- //
- // A backend that cannot be reached, or does not answer in time, is reported in the SAME shape
- // (`{success:false, error:{code,message}}`, 502/504) rather than thrown: the hook server runs each
- // request as a void-discarded async, so a throw here was an unhandledRejection and a local request
- // that NEVER got a response — the desktop app then sat on its 30s receive timeout and printed a
- // DioException where "the backend is down" belonged. Same for a backend that accepts the request
- // and hangs (a Redis presence lookup, say): `fetch` waits forever by default, and the app's
- // timeout fired first. The bound is shorter than that timeout on purpose, so the daemon is the one
- // that answers, with a sentence.
- async function proxyBackend(method: string, path: string, body?: unknown): Promise<{ status: number; body: Record<string, unknown> }> {
- const failure = (status: number, code: string, message: string): { status: number; body: Record<string, unknown> } =>
- ({ status, body: { success: false, error: { code, message } } })
- let accessToken: string
- try {
- accessToken = await auth.accessToken()
- } catch (err) {
- // No session, or one the SSO service will never renew, is the caller's 401 — the answer the
- // backend itself would give — not a backend fault; a refresh the service could not serve right
- // now is. Telling them apart is what lets a local client say "sign in again" only when true.
- const signedOut = err instanceof AuthSessionError && err.code !== 'UNAVAILABLE'
- return failure(signedOut ? 401 : 502, signedOut ? 'NOT_SIGNED_IN' : 'AUTH_UNAVAILABLE', err instanceof Error ? err.message : String(err))
- }
- const latest = readAuthSession()
- let res: Response
- try {
- res = await fetch(`${backendHttpBase()}${path}`, {
- method,
- headers: {
- authorization: `Bearer ${accessToken}`,
- 'x-autonomous-env': latest?.autonomousEnv ?? env.AUTONOMOUS_ENV,
- ...(body !== undefined ? { 'content-type': 'application/json' } : {}),
- },
- ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
- signal: AbortSignal.timeout(PROXY_BACKEND_TIMEOUT_MS),
- })
- } catch (err) {
- const e = err as Error & { cause?: { message?: string } }
- if (e.name === 'TimeoutError' || e.name === 'AbortError') {
- return failure(504, 'BACKEND_TIMEOUT', `The Harness backend did not answer ${method} ${path} within ${PROXY_BACKEND_TIMEOUT_MS / 1000}s. Try again in a moment.`)
- }
- // undici wraps the socket error as `TypeError: fetch failed` with the real one in `cause`.
- const why = e.cause?.message ?? e.message
- return failure(502, 'BACKEND_UNREACHABLE', `Could not reach the Harness backend (${why}). Check the connection and try again.`)
- }
- const json = await res.json().catch(() => ({})) as Record<string, unknown>
- const result = { status: res.status, body: json }
- return result
- }
-
- /**
- * The machine list a signed-out daemon answers with: this computer, alone.
- *
- * Null when there is a session — then the backend's own list is the answer, and this must not shadow
- * it. `authMode: 'remote'` is what a computer-backed machine is once it has an account, said now so
- * nothing downstream has to special-case a guest row.
- */
- function guestMachinesBody(): Record<string, unknown> | null {
- if (readAuthSession()) return null
- const id = computerId()
- return {
- success: true,
- data: {
- machines: [{
- machineId: id,
- computerId: id,
- name: terminalHintMachineName(),
- hostname: hostname(),
- status: 'online',
- authMode: 'remote',
- }],
- stale: false,
- guest: true,
- },
- }
+ // Account HTTP and the persistent machine cache belong to the gateway. The core routes the request
+ // and keeps only state reported by that service, so a backend outage cannot stall an agent's loop.
+ function proxyBackend(method: string, path: string, body?: unknown): Promise<{ status: number; body: Record<string, unknown> }> {
+ return gatewayOps.backend(method, path, body)
}
- const machineListCache = new MachineListCache(
- () => proxyBackend('GET', '/api/machines'),
- computerId,
- (line) => console.log(`[cable] ${line}`),
- undefined,
- // A machine row is per (user, computer): the one local fact that distinguishes two ACCOUNTS here.
- // Read fresh each time — a re-login swaps it under a daemon that never restarted.
- () => readAuthSession()?.machineId ?? null,
- )
- // 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) => 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()
- gatewayOps.reachable(source !== 'backend' ? null : machines.filter((m) => m.state !== 'offline').map((m) => m.machineId))
- })
-
- /**
- * The owner's machines as the devices read them (`CoreApi.account.machines`): this computer alone when
- * signed out, else the backend's answer now. The core's own list takes it first, as its own refresh would,
- * so the windows' fallback and the trust group stay as fresh as the dial's wheel.
- */
- async function machinesNow(): Promise<{ status: number; body: Record<string, unknown> }> {
- const guest = guestMachinesBody()
- if (guest) {
- machineListCache.adopt(guest)
- return { status: 200, body: guest }
- }
- return (await machineListCache.refresh()) ?? { status: 502, body: { error: { code: 'BACKEND_UNREACHABLE' } } }
- }
-
- /**
- * `GET /api/machines` for local clients, answered from the last known-good list when the backend leg
- * is down.
- *
- * The daemon already keeps that list: it re-reads it every 60s for the dial's wheel and persists it to
- * `machines.json`, with the explicit policy that an outage keeps the rows and stops claiming they are
- * live. The desktop app was the one consumer that got none of that — a bare pass-through handed it the
- * 502 and it had nothing to draw, so a ten-second network blip emptied the machine list and left every
- * pane spinning. Stale rows are not wrong rows; the marker below says which they are.
- */
- async function machinesListWithFallback(): Promise<{ status: number; body: Record<string, unknown> }> {
- // ⚠️ SIGNED OUT, THE LIST IS THIS COMPUTER — never the backend's 401.
- //
- // 401 is the one status the desktop app reads as "the session ended": it tears its connections
- // down and puts a sign-in wall in front of agents that were running fine a moment ago. Nothing
- // here needs the backend to say what this computer is. The row is the shape the backend would
- // send, keyed by the durable computer id this daemon is already serving under, so the app
- // classifies it exactly as it will after a sign-in — local by computerId — with no guest-only
- // branch for anyone to forget.
- const guest = guestMachinesBody()
- if (guest) {
- // Into the same cache the dial's wheel reads, so the two surfaces cannot disagree about a
- // machine list one of them was handed directly.
- machineListCache.adopt(guest)
- return { status: 200, body: guest }
- }
- const res = await proxyBackend('GET', '/api/machines')
- if (res.status === 200) {
- // Feed the cache the answer we already have rather than making it fetch the same thing again.
- machineListCache.adopt(res.body)
- return res
- }
- // A real end of session is the caller's answer, not an outage: never serve a list from behind it.
- if (res.status === 401 || res.status === 403) return res
- const cached = machineListCache.lastResponse()
- if (!cached) return res
- return { status: 200, body: withStaleMarker(cached.body, cached.fetchedAt) }
- }
-
-
// The daemon's status (GET /api/status, read by `harness status`, the desktop's discovery and scripts):
// health, the computer's fingerprint and its local pairings. It deliberately does NOT expose chat or
// transcripts. The fingerprint and the pairings are the gateway's, asked for each time (bounded:
@@ -1729,7 +1581,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
onDevicesDismiss: (body) => gatewayOps.devicesDismiss(body),
onDevicesRebaseline: (confirm, head) => gatewayOps.devicesRebaseline(confirm, head),
onStatus: async () => statusBody(await gatewayOps.status()),
- onMachinesList: () => machinesListWithFallback(),
+ onMachinesList: () => gatewayOps.machines(true),
onMachineRename: (machineId, name) => proxyBackend('PATCH', `/api/machines/${encodeURIComponent(machineId)}`, { name }),
onMachineDelete: (machineId) => proxyBackend('DELETE', `/api/machines/${encodeURIComponent(machineId)}`),
onAuthMe: () => proxyBackend('GET', '/api/auth/me'),
@@ -1972,6 +1824,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {
} catch (error) {
console.warn(`[repair] cwd repair skipped · ${error instanceof Error ? error.message : error}`)
}
+ // Bundled harness installation is the Store's. Wait for its first preparation before restore reads
+ // the index, with a deadline so a broken Store never prevents ordinary agents from coming back.
+ if (outOfProcess.has('store') && !await storeLink.ready()) console.warn('[store] preparation unavailable · restoring with the installed harnesses')
watcher.start()
await cursorDiscovery.start()
// What a restored agent's engine writes from here on is live: the first attach of each folds its
diff --git a/cli/src/core/shellQueries.spec.ts b/cli/src/core/shellQueries.spec.ts
new file mode 100644
index 000000000..8b7be34a5
--- /dev/null
+++ b/cli/src/core/shellQueries.spec.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it, vi } from 'vitest'
+import { fakeCore } from '../testing/fakeCore.js'
+import { answerShellQuery } from './shellQueries.js'
+
+describe('the shell service core queries', () => {
+ it('accepts only literal bounded argv and an absolute folder before opening a pane', async () => {
+ const core = fakeCore({ terminals: { open: vi.fn(async () => ({ ok: true as const, agentId: 'new' })) } })
+ const request = { argv: ['/bin/zsh', 'a; b', '$(touch nope)', ''], cwd: '/work' }
+ expect(await answerShellQuery(core, 'open', request)).toEqual({ ok: true as const, agentId: 'new' })
+ expect(core.terminals.open).toHaveBeenCalledWith(request)
+ expect(vi.mocked(core.terminals.open).mock.calls[0]![0].argv).not.toBe(request.argv)
+ for (const payload of [{}, { argv: [] }, { argv: [''] }, { argv: [7] }, { argv: ['a\0b'] },
+ { argv: Array(257).fill('a') }, { argv: ['a'.repeat(32768)] }, { argv: ['sh'], command: 'unsafe' }]) {
+ expect(await answerShellQuery(core, 'open', { cwd: '/work', ...payload })).toEqual({ ok: false, error: 'INVALID_ARGV' })
+ }
+ for (const cwd of [undefined, 'relative', '/nul\0', '/' + 'x'.repeat(4096)]) {
+ expect(await answerShellQuery(core, 'open', { argv: ['sh'], cwd })).toEqual({ ok: false, error: 'INVALID_CWD' })
+ }
+ expect(core.terminals.open).toHaveBeenCalledTimes(1)
+ })
+ it('asks the current registry and exact exit probe, refusing malformed or unknown reads', async () => {
+ const core = fakeCore({ terminals: { describe: vi.fn(async () => ({ id: 'a' })), visitStatus: vi.fn(async () => ({ exited: true })) } })
+ expect(await answerShellQuery(core, 'describe', { agentId: 'a' })).toEqual({ agent: { id: 'a' } })
+ expect(await answerShellQuery(core, 'visitStatus', { agentId: 'a' })).toEqual({ exited: true })
+ expect(core.terminals.describe).toHaveBeenCalledWith('a')
+ expect(core.terminals.visitStatus).toHaveBeenCalledWith('a')
+ for (const query of ['describe', 'visitStatus']) for (const agentId of [null, '', 'x'.repeat(257)]) {
+ expect(await answerShellQuery(core, query, { agentId })).toEqual({ error: 'BAD_QUERY' })
+ }
+ expect(await answerShellQuery(core, 'unknown', {})).toEqual({ error: 'UNKNOWN_QUERY' })
+ })
+})
diff --git a/cli/src/core/shellQueries.ts b/cli/src/core/shellQueries.ts
new file mode 100644
index 000000000..8e91d91b3
--- /dev/null
+++ b/cli/src/core/shellQueries.ts
@@ -0,0 +1,16 @@
+/** Only the shell service may ask for these operations. Live identity and pane launch stay here. */
+import type { CoreApi } from './api.js'
+import { terminalOpenError } from '../lib/shellProtocol.js'
+
+export async function answerShellQuery(core: Pick<CoreApi, 'terminals'>, query: string, payload: Record<string, unknown>): Promise<Record<string, unknown>> {
+ if (query === 'open') {
+ const invalid = terminalOpenError(payload)
+ if (invalid) return { ok: false, error: invalid }
+ return core.terminals.open({ argv: [...payload.argv as string[]], cwd: payload.cwd as string })
+ }
+ if (query === 'describe' || query === 'visitStatus') {
+ if (typeof payload.agentId !== 'string' || !payload.agentId || payload.agentId.length > 256) return { error: 'BAD_QUERY' }
+ return query === 'describe' ? { agent: await core.terminals.describe(payload.agentId) } : core.terminals.visitStatus(payload.agentId)
+ }
+ return { error: 'UNKNOWN_QUERY' }
+}
diff --git a/cli/src/core/storeLink.spec.ts b/cli/src/core/storeLink.spec.ts
index 41601a443..01b821dec 100644
--- a/cli/src/core/storeLink.spec.ts
+++ b/cli/src/core/storeLink.spec.ts
@@ -1,8 +1,34 @@
-import { describe, expect, it, vi } from 'vitest'
+import { afterEach, describe, expect, it, vi } from 'vitest'
import { fakeCore } from '../testing/fakeCore.js'
import { createStoreLink } from './storeLink.js'
describe('the Store in its own process, as the core hears it', () => {
+ afterEach(() => vi.useRealTimers())
+
+ it('waits for preparation, refreshes the index first and remembers it for restore', async () => {
+ vi.useFakeTimers()
+ const installed = vi.fn()
+ const link = createStoreLink(fakeCore(), installed)
+ const first = link.ready()
+ const second = link.ready()
+ expect(link.answer('prepared', {})).toEqual({ read: true })
+ expect(installed).toHaveBeenCalledOnce()
+ expect(await first).toBe(true)
+ expect(await second).toBe(true)
+ expect(await link.ready()).toBe(true)
+ expect(vi.getTimerCount()).toBe(0)
+ })
+
+ it('lets ordinary agents restore when the Store is unavailable, and accepts a late preparation', async () => {
+ vi.useFakeTimers()
+ const link = createStoreLink(fakeCore(), vi.fn())
+ const waiting = link.ready(50)
+ link.answer('installed', {})
+ await vi.advanceTimersByTimeAsync(50)
+ expect(await waiting).toBe(false)
+ link.answer('prepared', {})
+ expect(await link.ready()).toBe(true)
+ })
it('pushes an install\'s progress to the apps, and reads the installed index again when told it changed', () => {
const core = fakeCore()
const installed = vi.fn()
diff --git a/cli/src/core/storeLink.ts b/cli/src/core/storeLink.ts
index f27f1675c..599e29bf2 100644
--- a/cli/src/core/storeLink.ts
+++ b/cli/src/core/storeLink.ts
@@ -1,6 +1,6 @@
/**
* The Harness Store in its own process, as the core hears it (beside the viewers; the process's side is
- * services/storeProcess.ts). The core asks the Store nothing: the apps' requests are routed to it. The
+ * services/storeProcess.ts). The apps' requests are routed to it. The
* Store tells the core how an install is going, which the core pushes to the apps
* (`CoreApi.clients.dshInstallStatus`), and that what is installed changed, so that the core reads the
* installed index again rather than from its two-second cache (dsh/installed.ts): the create that follows
@@ -9,7 +9,18 @@
import type { CoreApi } from './api.js'
export function createStoreLink(core: Pick<CoreApi, 'clients'>, installedChanged: () => void) {
+ let prepared = false
+ const waiters = new Set<() => void>()
return {
+ /** Wait only at boot, before restoring bundled harness agents. A missing Store cannot stop boot. */
+ ready(waitMs = 5_000): Promise<boolean> {
+ if (prepared) return Promise.resolve(true)
+ return new Promise((resolve) => {
+ const done = () => { clearTimeout(timer); waiters.delete(done); resolve(true) }
+ const timer = setTimeout(() => { waiters.delete(done); resolve(false) }, waitMs)
+ waiters.add(done)
+ })
+ },
/** The core's answers to the Store's questions (core/serviceLinks.ts `answer`, for `store`). */
answer(query: string, payload: Record<string, unknown>): Record<string, unknown> {
if (query === 'installStatus') {
@@ -18,8 +29,12 @@ export function createStoreLink(core: Pick<CoreApi, 'clients'>, installedChanged
core.clients.dshInstallStatus(status as Record<string, unknown>)
return { said: true }
}
- if (query === 'installed') {
+ if (query === 'prepared' || query === 'installed') {
installedChanged()
+ if (query === 'prepared') {
+ prepared = true
+ for (const done of waiters) done()
+ }
return { read: true }
}
return { error: 'UNKNOWN_QUERY' }
diff --git a/cli/src/core/terminals/sessions.ts b/cli/src/core/terminals/sessions.ts
new file mode 100644
index 000000000..59f704149
--- /dev/null
+++ b/cli/src/core/terminals/sessions.ts
@@ -0,0 +1,43 @@
+/** Terminal identity and exit evidence stay with the core's live registry. */
+import type { CoreApi, TerminalsPort } from '../api.js'
+import type { tmuxPaneState } from '../../lib/tmux.js'
+import type { checkPidRuntime } from '../../lib/deleteAgentFallback.js'
+
+interface TerminalSessionDeps {
+ agents: Pick<CoreApi['agents'], 'byAgent' | 'displayName' | 'terminalAvailable'>
+ paneState: typeof tmuxPaneState
+ processState: typeof checkPidRuntime
+}
+
+export function createTerminalSessions(deps: TerminalSessionDeps): Pick<TerminalsPort, 'describe' | 'visitStatus'> {
+ // This only restores a client's parked shell view. The core still owns archiving and resume.
+ // A banner or Ctrl-C is not proof: require the launcher's exit mark AND the exact process gone.
+ const visitStatus = async (agentId: string): Promise<{ exited: boolean }> => {
+ const row = deps.agents.byAgent(agentId)
+ // Discovery clears a completed launch record when it binds the engine's conversation.
+ // October 6 shell-return E2E: a resumed process exited after discovery marked its row inactive,
+ // before retirement. That flag cannot suppress an exact exit probe or the parked shell is stranded.
+ if (!row || row.engine === 'terminal' || row.launch?.state === 'starting' || row.launch?.state === 'failed'
+ || !row.tmuxPane || !row.processIdentity?.startMarker) return { exited: false }
+ const session = { ...row, processIdentity: { ...row.processIdentity } }
+ const identity = (value: ReturnType<typeof deps.agents.byAgent>) => JSON.stringify([value?.engine, value?.sessionId,
+ value?.registeredAt, value?.tmuxPane, value?.launch?.state, value?.processIdentity])
+ const before = identity(session)
+ const pane = await deps.paneState(session.tmuxPane)
+ if (pane === 'gone' || pane === 'unknown' || pane.engineExit == null) return { exited: false }
+ const process = await deps.processState(session)
+ return { exited: process.state === 'gone' && identity(deps.agents.byAgent(agentId)) === before }
+ }
+ return {
+ visitStatus,
+ describe: async (agentId) => {
+ const row = deps.agents.byAgent(agentId)
+ if (!row) return null
+ return {
+ id: row.agentId, sessionId: row.sessionId, engine: row.engine, name: deps.agents.displayName(row),
+ status: 'active', launch: row.launch, terminal: { available: deps.agents.terminalAvailable(row.agentId) },
+ project: { cwd: row.cwd, root: row.cwd, name: row.projectDir },
+ }
+ },
+ }
+}
diff --git a/cli/src/device/machineList.ts b/cli/src/device/machineList.ts
index 1dffd0027..90436245e 100644
--- a/cli/src/device/machineList.ts
+++ b/cli/src/device/machineList.ts
@@ -57,21 +57,7 @@ function stateOf(status: string): FleetMachine['state'] {
return 'unknown'
}
-/**
- * Tag a cached machine-list body as stale, where the client actually reads it.
- *
- * The backend answers `{success:true,data:{…}}` and this daemon forwards that verbatim, so the flag has
- * to go INSIDE `data` — a local client unwraps to `data` and would never see a top-level field. Older
- * shapes that return the machines at the top level get it there instead.
- */
-export function withStaleMarker(body: Record<string, unknown>, fetchedAt: number): Record<string, unknown> {
- const marker = { stale: true, staleSince: new Date(fetchedAt).toISOString() }
- const data = body.data
- if (data && typeof data === 'object' && !Array.isArray(data)) {
- return { ...body, data: { ...(data as Record<string, unknown>), ...marker } }
- }
- return { ...body, ...marker }
-}
+export { withStaleMarker } from '../lib/machineListReply.js'
export class MachineListCache {
private machines: ListedMachine[] = []
@@ -97,8 +83,8 @@ export class MachineListCache {
/** The machine row this session belongs to. A machine row is per (user, computer), so it is the one
* local fact that tells two ACCOUNTS on this computer apart — see `lastResponse`. */
private readonly owner: () => string | null = () => null,
- /** Whether it writes `machines.json`. The core's list does; the devices' own copy reads the file at
- * start, to draw the wheel offline, and leaves writing it to the core, so one file has one writer. */
+ /** Whether it writes `machines.json`. The gateway's list does; the devices' own copy reads the file at
+ * start, to draw the wheel offline, and leaves writing it to the gateway, so one file has one writer. */
private readonly persist = true,
) {
this.path = machineListCachePath(dataDir)
@@ -152,6 +138,7 @@ export class MachineListCache {
* rather than emptying the wheel.
*/
async refresh(): Promise<{ status: number; body: Record<string, unknown> } | null> {
+ const owner = this.owner()
let res: { status: number; body: Record<string, unknown> }
try {
res = await this.fetchMachines()
@@ -159,6 +146,8 @@ export class MachineListCache {
this.degrade(`unreachable (${(err as Error).message})`)
return null
}
+ // A sign-in changed while the request was in flight: its response belongs to the old account.
+ if (owner !== this.owner()) return null
if (res.status === 401 || res.status === 403) this.signedOut()
else if (res.status >= 400) this.degrade(`HTTP ${res.status}`)
else if (!this.adopt(res.body)) this.degrade('no machines in the response')
@@ -241,7 +230,7 @@ export class MachineListCache {
for (const m of this.machines) m.state = 'unknown'
}
- private signedOut(): void {
+ signedOut(): void {
if (this.source !== 'signed-out') this.log('machines: not signed in')
this.source = 'signed-out'
this.machines = []
diff --git a/cli/src/dsh/builtins.ts b/cli/src/dsh/builtins.ts
index cdd549a38..0411313ab 100644
--- a/cli/src/dsh/builtins.ts
+++ b/cli/src/dsh/builtins.ts
@@ -7,10 +7,8 @@ import { lockDsh } from './lock.js'
import { readDshManifest } from './manifest.js'
import { HARNESS_MONOREPO } from './registry.js'
import { samePackageSource } from './updates.js'
+import { builtinFiles } from './bundledFiles.js'
-declare const __MODEL_MANAGER_BUNDLE__: string
-declare const __DEVICES_BUNDLE__: string
-declare const __HARNESS_MONITOR_BUNDLE__: string
export {
DEVICES_BUILTIN_SOURCE, DEVICES_HARNESS_ID, HARNESS_MONITOR_BUILTIN_SOURCE, HARNESS_MONITOR_ID, isHiddenBuiltin, MODEL_MANAGER_ID,
} from './builtinIds.js'
@@ -20,21 +18,21 @@ export type BundledFiles = Record<string, { content: string; executable: boolean
* owned by the existing managed Grid installer. Versioned package directories
* keep running managers intact while a newer CLI installs its own resources. */
export function ensureBundledModelManager(files?: BundledFiles): boolean {
- files ??= typeof __MODEL_MANAGER_BUNDLE__ === 'string' ? JSON.parse(__MODEL_MANAGER_BUNDLE__) as BundledFiles : undefined
+ files ??= builtinFiles('models')
if (!files || !files['harness.json']) return false
return installBuiltin({ id: MODEL_MANAGER_ID, source: 'builtin:model-manager', folder: 'model-manager', files, what: 'Model Manager', legacyPath: 'store/agents/autonomous-grid' })
}
/** An unlisted first-party DSH. Its viewer is native; its agent uses the same daemon API. */
export function ensureBundledDevices(files?: BundledFiles): boolean {
- files ??= typeof __DEVICES_BUNDLE__ === 'string' ? JSON.parse(__DEVICES_BUNDLE__) as BundledFiles : undefined
+ files ??= builtinFiles('devices')
if (!files?.['harness.json']) return false
return installBuiltin({ id: DEVICES_HARNESS_ID, source: DEVICES_BUILTIN_SOURCE, folder: 'devices', files, what: 'Devices', legacyPath: 'store/agents/devices' })
}
/** The footer's monitor follows the CLI release, including existing official Store installations. */
export function ensureBundledHarnessMonitor(files?: BundledFiles): boolean {
- files ??= typeof __HARNESS_MONITOR_BUNDLE__ === 'string' ? JSON.parse(__HARNESS_MONITOR_BUNDLE__) as BundledFiles : undefined
+ files ??= builtinFiles('monitor')
if (!files?.['harness.json']) return false
return installBuiltin({ id: HARNESS_MONITOR_ID, source: HARNESS_MONITOR_BUILTIN_SOURCE, folder: 'harness-monitor', files,
what: 'Harness Monitor', legacyPath: 'store/agents/harness-monitor' })
diff --git a/cli/src/dsh/bundledFiles.ts b/cli/src/dsh/bundledFiles.ts
new file mode 100644
index 000000000..a5aaf3d12
--- /dev/null
+++ b/cli/src/dsh/bundledFiles.ts
@@ -0,0 +1,13 @@
+import type { BundledFiles } from './builtins.js'
+
+declare const __MODEL_MANAGER_BUNDLE__: string
+declare const __DEVICES_BUNDLE__: string
+declare const __HARNESS_MONITOR_BUNDLE__: string
+
+/** Kept in one shared asset module by the lean build; the self-contained CLI embeds the same bytes. */
+export function builtinFiles(name: 'models' | 'devices' | 'monitor'): BundledFiles | undefined {
+ const source = name === 'models' ? (typeof __MODEL_MANAGER_BUNDLE__ === 'string' ? __MODEL_MANAGER_BUNDLE__ : undefined)
+ : name === 'devices' ? (typeof __DEVICES_BUNDLE__ === 'string' ? __DEVICES_BUNDLE__ : undefined)
+ : (typeof __HARNESS_MONITOR_BUNDLE__ === 'string' ? __HARNESS_MONITOR_BUNDLE__ : undefined)
+ return source === undefined ? undefined : JSON.parse(source) as BundledFiles
+}
diff --git a/cli/src/gateway/accountHttp.spec.ts b/cli/src/gateway/accountHttp.spec.ts
new file mode 100644
index 000000000..f95b4f8fb
--- /dev/null
+++ b/cli/src/gateway/accountHttp.spec.ts
@@ -0,0 +1,113 @@
+import { mkdtempSync, readFileSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import type { GatewayAccount } from '../core/api.js'
+import { AuthSessionError } from '../lib/authSession.js'
+import { createAccountHttp } from './accountHttp.js'
+
+const roots: string[] = []
+afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) })
+const body = { success: true, data: { machines: [{ machineId: 'remote', computerId: 'other', name: 'Desktop', status: 'online' }] } }
+const response = (value: unknown, status = 200) => new Response(JSON.stringify(value), { status })
+function setup() {
+ const dataDir = mkdtempSync(join(tmpdir(), 'gateway-account-')); roots.push(dataDir)
+ let account: GatewayAccount = { machineId: 'account-a', signIn: null, autonomousEnv: 'test' }
+ const request = vi.fn<typeof fetch>(async () => response(body))
+ const tokens = { accessToken: vi.fn(async () => 'token') }
+ const changed = vi.fn(), reachable = vi.fn()
+ const deps = { dataDir, account: () => account, tokens, request, base: () => 'https://backend.invalid',
+ computer: { id: 'computer', name: 'Laptop', hostname: 'host' }, environment: 'prod', changed, reachable, log: vi.fn() }
+ return { api: createAccountHttp(deps), deps, dataDir, request, tokens, changed, reachable,
+ account: (next: GatewayAccount) => { account = next } }
+}
+
+describe('account HTTP in the gateway', () => {
+ it('forwards response bodies, status, credentials and environment without holding a credential', async () => {
+ const { api, request, tokens } = setup()
+ request.mockResolvedValueOnce(response({ error: { code: 'CONFLICT' } }, 409))
+ expect(await api.backend('PATCH', '/api/machines/local', { name: 'Renamed' })).toEqual({ status: 409, body: { error: { code: 'CONFLICT' } } })
+ expect(request).toHaveBeenCalledWith('https://backend.invalid/api/machines/local', expect.objectContaining({
+ method: 'PATCH', body: JSON.stringify({ name: 'Renamed' }),
+ headers: { authorization: 'Bearer token', 'x-autonomous-env': 'test', 'content-type': 'application/json' }, signal: expect.any(AbortSignal),
+ }))
+ await api.backend('GET', '/api/auth/me')
+ expect(request.mock.calls[1][1]?.headers).not.toHaveProperty('content-type')
+ expect(tokens.accessToken).toHaveBeenCalledTimes(2)
+ request.mockResolvedValueOnce(new Response('not json', { status: 502 }))
+ expect(await api.backend('GET', '/api/auth/me')).toEqual({ status: 502, body: {} })
+ })
+
+ it.each([['MISSING', 401, 'NOT_SIGNED_IN'], ['INVALID_REFRESH', 401, 'NOT_SIGNED_IN'], ['UNAVAILABLE', 502, 'AUTH_UNAVAILABLE']] as const)(
+ 'distinguishes %s from an unreachable backend', async (code, status, answer) => {
+ const { api, tokens, request } = setup()
+ tokens.accessToken.mockRejectedValueOnce(new AuthSessionError('session error', code))
+ expect(await api.backend('GET', '/api/auth/me')).toEqual({ status, body: { success: false, error: { code: answer, message: 'session error' } } })
+ expect(request).not.toHaveBeenCalled()
+ })
+
+ it('answers network and timeout failures instead of abandoning a local HTTP request', async () => {
+ const { api, request } = setup()
+ request.mockRejectedValueOnce(Object.assign(new Error('fetch failed'), { cause: { message: 'connection refused' } }))
+ expect(await api.backend('GET', '/api/auth/me')).toMatchObject({ status: 502, body: { error: { code: 'BACKEND_UNREACHABLE', message: expect.stringContaining('connection refused') } } })
+ for (const name of ['TimeoutError', 'AbortError']) {
+ request.mockRejectedValueOnce(Object.assign(new Error('late'), { name }))
+ expect(await api.backend('GET', '/api/auth/me')).toMatchObject({ status: 504, body: { error: { code: 'BACKEND_TIMEOUT' } } })
+ }
+ })
+
+ it('keeps the guest list local and never asks for a token', async () => {
+ const { api, account, request, changed } = setup()
+ account({ machineId: null, signIn: null })
+ expect(await api.machines()).toMatchObject({ status: 200, body: { data: { guest: true, stale: false, machines: [{ machineId: 'computer', name: 'Laptop' }] } } })
+ expect(request).not.toHaveBeenCalled()
+ expect(changed).toHaveBeenLastCalledWith(expect.objectContaining({ owner: null }))
+ })
+
+ it('owns persistence, reports fresh lists, and uses stale rows during an outage after a restart', async () => {
+ const { api, deps, dataDir, request, changed, reachable } = setup()
+ expect(await api.machines()).toEqual({ status: 200, body })
+ expect(reachable).toHaveBeenLastCalledWith(['remote'])
+ expect(JSON.parse(readFileSync(join(dataDir, 'machines.json'), 'utf8')).bodyOwner).toBe('account-a')
+ changed.mockClear()
+ const restarted = createAccountHttp(deps)
+ expect(changed).toHaveBeenCalledWith(expect.objectContaining({ owner: 'account-a', body }))
+ request.mockResolvedValueOnce(response({}, 503))
+ expect(await restarted.machines(true)).toMatchObject({ status: 200, body: { data: { ...body.data, stale: true } } })
+ request.mockResolvedValueOnce(response({}, 503))
+ expect((await restarted.machines()).status).toBe(503)
+ })
+
+ it('does not serve stale rows across accounts or after a real refusal', async () => {
+ const { api, request, account } = setup()
+ await api.machines(true)
+ account({ machineId: 'account-b', signIn: null })
+ request.mockResolvedValueOnce(response({}, 503))
+ expect((await api.machines(true)).status).toBe(503)
+ account({ machineId: 'account-a', signIn: null })
+ for (const status of [401, 403]) {
+ await api.machines(true)
+ request.mockResolvedValueOnce(response({}, status))
+ expect((await api.machines(true)).status).toBe(status)
+ request.mockResolvedValueOnce(response({}, 503))
+ expect((await api.machines(true)).status).toBe(503)
+ }
+ })
+
+ it.each([false, true])('discards an account change during a machine read (fallback %s)', async fallback => {
+ const { api, request, account, changed } = setup()
+ request.mockImplementationOnce(async () => { account({ machineId: 'account-b', signIn: null }); return response(body) })
+ expect((await api.machines(fallback)).status).not.toBe(200)
+ expect(changed).not.toHaveBeenCalled()
+ })
+
+ it('mints the private grid name in the gateway, preserving the data envelope and errors', async () => {
+ const { api, request } = setup()
+ request.mockResolvedValueOnce(response({ success: true, data: { gridName: 'private-grid' } }))
+ expect(await api.mintGridName()).toBe('private-grid')
+ request.mockResolvedValueOnce(response({ data: {} }))
+ expect(await api.mintGridName()).toBeNull()
+ request.mockResolvedValueOnce(response({ success: false, error: { message: 'refused' } }, 403))
+ await expect(api.mintGridName()).rejects.toThrow('refused')
+ })
+})
diff --git a/cli/src/gateway/accountHttp.ts b/cli/src/gateway/accountHttp.ts
new file mode 100644
index 000000000..434c6e8e9
--- /dev/null
+++ b/cli/src/gateway/accountHttp.ts
@@ -0,0 +1,87 @@
+/** Backend HTTP and the single writer of machines.json, owned by the gateway. */
+import type { GatewayAccount, GatewayMachines, HttpAnswer } from '../core/api.js'
+import { MachineListCache } from '../device/machineList.js'
+import { AuthSessionError } from '../lib/authSession.js'
+import { backendHttpBase, GRID_MINT_TIMEOUT_MS, PROXY_BACKEND_TIMEOUT_MS } from '../lib/controlPlane.js'
+import { guestMachineList, withStaleMarker } from '../lib/machineListReply.js'
+
+interface AccountHttpDeps {
+ tokens: { accessToken(): Promise<string> }
+ account(): GatewayAccount
+ computer: { id: string; name: string; hostname: string }
+ environment: string
+ dataDir?: string
+ request?: typeof fetch
+ base?: () => string
+ changed?(state: GatewayMachines): void
+ reachable?(machineIds: string[] | null): void
+ log?(line: string): void
+}
+
+const failure = (status: number, code: string, message: string): HttpAnswer =>
+ ({ status, body: { success: false, error: { code, message } } })
+
+export function createAccountHttp(deps: AccountHttpDeps) {
+ const request = deps.request ?? fetch
+ async function backend(method: string, path: string, body?: unknown, timeoutMs = PROXY_BACKEND_TIMEOUT_MS): Promise<HttpAnswer> {
+ let accessToken: string
+ try { accessToken = await deps.tokens.accessToken() } catch (error) {
+ const signedOut = error instanceof AuthSessionError && error.code !== 'UNAVAILABLE'
+ return failure(signedOut ? 401 : 502, signedOut ? 'NOT_SIGNED_IN' : 'AUTH_UNAVAILABLE', error instanceof Error ? error.message : String(error))
+ }
+ let res: Response
+ try {
+ res = await request(`${(deps.base ?? backendHttpBase)()}${path}`, {
+ method,
+ headers: { authorization: `Bearer ${accessToken}`, 'x-autonomous-env': deps.account().autonomousEnv ?? deps.environment,
+ ...(body !== undefined ? { 'content-type': 'application/json' } : {}) },
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
+ signal: AbortSignal.timeout(timeoutMs),
+ })
+ } catch (error) {
+ const e = error as Error & { cause?: { message?: string } }
+ if (e.name === 'TimeoutError' || e.name === 'AbortError') {
+ return failure(504, 'BACKEND_TIMEOUT', `The Harness backend did not answer ${method} ${path} within ${timeoutMs / 1000}s. Try again in a moment.`)
+ }
+ return failure(502, 'BACKEND_UNREACHABLE', `Could not reach the Harness backend (${e.cause?.message ?? e.message}). Check the connection and try again.`)
+ }
+ return { status: res.status, body: await res.json().catch(() => ({})) as Record<string, unknown> }
+ }
+
+ const cache = new MachineListCache(() => backend('GET', '/api/machines'), () => deps.computer.id,
+ deps.log ?? console.warn, deps.dataDir, () => deps.account().machineId)
+ cache.listen((body) => {
+ const { machines, source } = cache.list()
+ deps.reachable?.(source !== 'backend' ? null : machines.filter(m => m.state !== 'offline').map(m => m.machineId))
+ deps.changed?.({ owner: deps.account().machineId, body, fetchedAt: cache.lastResponse()?.fetchedAt ?? Date.now() })
+ })
+ const restored = cache.lastResponse()
+ if (restored) deps.changed?.({ owner: deps.account().machineId, ...restored })
+
+ async function machines(fallback = false): Promise<HttpAnswer> {
+ const owner = deps.account().machineId
+ if (!deps.account().machineId) {
+ const body = guestMachineList(deps.computer.id, deps.computer.name, deps.computer.hostname)
+ cache.adopt(body)
+ return { status: 200, body }
+ }
+ if (!fallback) return (await cache.refresh()) ?? { status: 502, body: { error: { code: 'BACKEND_UNREACHABLE' } } }
+ const res = await backend('GET', '/api/machines')
+ if (owner !== deps.account().machineId) return failure(409, 'ACCOUNT_CHANGED', 'The account changed. Refresh and try again.')
+ if (res.status === 200) { cache.adopt(res.body); return res }
+ if (res.status === 401 || res.status === 403) { cache.signedOut(); return res }
+ const cached = cache.lastResponse()
+ return cached ? { status: 200, body: withStaleMarker(cached.body, cached.fetchedAt) } : res
+ }
+
+ async function mintGridName(): Promise<string | null> {
+ const res = await backend('POST', '/api/grid/name', {}, GRID_MINT_TIMEOUT_MS)
+ if (res.status < 200 || res.status >= 300 || res.body.success === false) {
+ const error = res.body.error as { message?: string } | undefined
+ throw new Error(error?.message || `HTTP ${res.status}`)
+ }
+ return (res.body.data as { gridName?: string } | undefined)?.gridName ?? null
+ }
+
+ return { backend, machines, mintGridName }
+}
diff --git a/cli/src/gateway/gatewayProcess.spec.ts b/cli/src/gateway/gatewayProcess.spec.ts
index 46b3d53a3..d240986a1 100644
--- a/cli/src/gateway/gatewayProcess.spec.ts
+++ b/cli/src/gateway/gatewayProcess.spec.ts
@@ -25,6 +25,8 @@ function stubGateway() {
} satisfies GatewayPort
const answer = { status: 200, body: { ok: true } }
const ops = {
+ backend: vi.fn(async (_method: string, _path: string, _body?: unknown) => answer),
+ machines: vi.fn(async (_fallback?: boolean) => answer), mintGridName: vi.fn(async (): Promise<string | null> => 'private-grid'),
status: vi.fn(async () => ({ fingerprint: 'AB12', pairs: [], pending: null })),
pair: vi.fn(async () => answer), listPairs: vi.fn(async () => answer), revoke: vi.fn(async () => answer), revokeAll: vi.fn(async () => answer),
setRemotePassword: vi.fn(async () => answer), clearRemotePassword: vi.fn(async () => answer), remotePasswordStatus: vi.fn(async () => answer),
@@ -116,14 +118,12 @@ describe('the gateway\'s process, spoken to by the core', () => {
// Its tokens and its reads of the backend are the core's to hand out.
expect(await w.hosts[0].tokens.accessToken({ force: true })).toBe('token-a')
expect(w.tokens.accessToken).toHaveBeenCalledWith({ force: true })
- expect(await w.hosts[0].backend('GET', '/api/device-keys?since=0')).toEqual({ status: 200, body: { data: { acct: 'a' } } })
w.tokens.accessToken.mockRejectedValueOnce(Object.assign(new Error('session over'), { code: 'INVALID_REFRESH' }))
await expect(w.hosts[0].tokens.accessToken()).rejects.toMatchObject({ name: 'AuthSessionError', code: 'INVALID_REFRESH' })
// The core going stops it; the next core builds a new one, signed out this time serving this computer only.
w.disconnect()
expect(gateway.stop).toHaveBeenCalled()
await expect(w.hosts[0].tokens.accessToken()).rejects.toMatchObject({ code: 'UNAVAILABLE' })
- expect(await w.hosts[0].backend('GET', '/api/device-keys')).toMatchObject({ status: 502 })
w.link.port.serveThisComputerOnly()
w.link.port.openRequests()
w.connect()
@@ -358,3 +358,20 @@ describe('the gateway\'s process, spoken to by the core', () => {
expect(w.gateways).toHaveLength(0)
})
})
+
+describe('account HTTP across the gateway service link', () => {
+ it('performs backend and machine requests in the gateway, with the core supplying only tokens', async () => {
+ const w = wire()
+ w.connect()
+ const { ops } = w.gateways[0]
+ expect(await w.link.ops.backend('POST', '/api/desk/ops', { changes: [] })).toEqual({ status: 200, body: { ok: true } })
+ expect(ops.backend).toHaveBeenCalledWith('POST', '/api/desk/ops', { changes: [] })
+ await w.link.ops.machines(true)
+ expect(ops.machines).toHaveBeenCalledWith(true)
+ await w.link.ops.machines()
+ expect(ops.machines).toHaveBeenCalledWith(false)
+ expect(await w.link.ops.mintGridName()).toBe('private-grid')
+ expect(w.backend).not.toHaveBeenCalled()
+ w.hosts[0].machines!({ owner: 'machine-1', body: { machines: [{ machineId: 'm2' }] }, fetchedAt: 1000 })
+ })
+})
diff --git a/cli/src/gateway/gatewayProcess.ts b/cli/src/gateway/gatewayProcess.ts
index 3ab8b1fad..fbe973777 100644
--- a/cli/src/gateway/gatewayProcess.ts
+++ b/cli/src/gateway/gatewayProcess.ts
@@ -91,11 +91,8 @@ export function runGatewayService(options: GatewayServiceOptions): ServiceProces
autonomousEnv: text(payload.autonomousEnv) || 'prod',
signedIn: payload.signedIn === true,
tokens: { accessToken },
- backend: async (method, path) => {
- if (!core) return { status: 502, body: { success: false, error: { code: 'BACKEND_UNREACHABLE', message: 'not connected to the core' } } }
- const answer = await core.query('backend', { method, path })
- return { status: typeof answer.status === 'number' ? answer.status : 502, body: record(answer.body) }
- },
+ machineName: text(payload.machineName), hostname: text(payload.hostname),
+ machines: (state) => notice('machines', { ...state }),
account: (payload.account as GatewayAccount | null) ?? { machineId: null, signIn: null },
})
running = started
@@ -204,6 +201,9 @@ export function runGatewayService(options: GatewayServiceOptions): ServiceProces
return running.ops
}
const requests = {
+ [GATEWAY_CALLS.backend]: async (p: Payload) => ({ ...await ops().backend(text(p.method), text(p.path), p.body) }),
+ [GATEWAY_CALLS.machines]: async (p: Payload) => ({ ...await ops().machines(p.fallback === true) }),
+ [GATEWAY_CALLS.mintGridName]: async () => ({ name: await ops().mintGridName() }),
[GATEWAY_CALLS.status]: async () => ({ ...await ops().status() }),
[GATEWAY_CALLS.pair]: async (p: Payload) => ({ ...await ops().pair(text(p.code)) }),
[GATEWAY_CALLS.listPairs]: async () => ({ ...await ops().listPairs() }),
diff --git a/cli/src/gateway/start.ts b/cli/src/gateway/start.ts
index 2d9f8e2d8..fa896bd49 100644
--- a/cli/src/gateway/start.ts
+++ b/cli/src/gateway/start.ts
@@ -37,6 +37,7 @@ import { RelayGateway } from './gateway.js'
import { LaneSessions } from './lane.js'
import { observerKey } from './observerKey.js'
import { shareWindows } from './share.js'
+import { createAccountHttp } from './accountHttp.js'
/** What the gateway needs of the core, in whichever process it runs. */
export interface GatewayHost {
@@ -49,8 +50,10 @@ export interface GatewayHost {
signedIn: boolean
/** The account's tokens, as `core.account` hands them out; it never holds the session itself. */
tokens: Pick<AuthSessionManager, 'accessToken'>
- /** A read of the backend's REST API under the account's session, as the core answers it. */
- backend(method: 'GET', path: string): Promise<HttpAnswer>
+ /** Local identity for the guest list; the core reports these facts without doing network work. */
+ machineName: string
+ hostname: string
+ machines?(state: import('../core/api.js').GatewayMachines): void
/** The account's sign-in as it stood when the core started; `GatewayOps.account` says it again. */
account: GatewayAccount
}
@@ -113,6 +116,13 @@ const PAIR_STATUS: Record<string, number> = {
export function startGateway(host: GatewayHost): StartedGateway {
let account = host.account
let reachable: Set<string> | null = null
+ const accountHttp = createAccountHttp({
+ tokens: host.tokens, account: () => account,
+ computer: { id: host.computerId, name: host.machineName, hostname: host.hostname }, environment: host.autonomousEnv,
+ changed: host.machines,
+ reachable: (ids) => { reachable = ids ? new Set(ids) : null },
+ log: (line) => console.log(`[gateway] ${line}`),
+ })
const gateway = new RelayGateway({
machineId: host.machineId, auth: host.tokens, computerId: host.computerId, autonomousEnv: host.autonomousEnv, core: host.events,
})
@@ -156,7 +166,7 @@ export function startGateway(host: GatewayHost): StartedGateway {
// socket to the backend (`/api/observer-ws`), signed in with the account's token. It finds the share
// among those the backend lists for this account first.
const shareRelay = new HarnessShareRelay(host.tokens, env.BACKEND_WS_URL, host.autonomousEnv, async () => {
- const result = await host.backend('GET', '/api/harness-shares')
+ const result = await accountHttp.backend('GET', '/api/harness-shares')
if (result.status !== 200) throw new Error('Shared harnesses are temporarily unavailable.')
return ((result.body as { data?: { machines?: SharedMachineReference[] } }).data?.machines ?? [])
})
@@ -210,7 +220,7 @@ export function startGateway(host: GatewayHost): StartedGateway {
// runs: the Devices list's "last active", and what `sweepStale` judges an unused app key by. null when
// it could not be asked; `since` null from a backend that does not say.
const deviceKeysSeen = async (): Promise<DeviceKeysSeen | null> => {
- const r = await host.backend('GET', '/api/device-keys/seen').catch(() => null)
+ const r = await accountHttp.backend('GET', '/api/device-keys/seen').catch(() => null)
const data = r?.status === 200 ? r.body.data as { seen?: unknown; since?: unknown } | undefined : undefined
if (!data?.seen || typeof data.seen !== 'object') return null
return { seen: data.seen as Record<string, number>, since: Number.isSafeInteger(data.since) ? data.since as number : null }
@@ -236,7 +246,7 @@ export function startGateway(host: GatewayHost): StartedGateway {
fetch: async (since) => {
// `self`: this read counts as this machine's key being used (a backend from before it ignores it).
const self = encodeURIComponent(b64e(relayIdentityStore.getIdentity().pub))
- const r = await host.backend('GET', `/api/device-keys?since=${since}&self=${self}`)
+ const r = await accountHttp.backend('GET', `/api/device-keys?since=${since}&self=${self}`)
const data = r.status === 200 ? r.body.data as Partial<DeviceLogFetched> | undefined : undefined
const head = data?.head as { seq?: unknown; hash?: unknown } | undefined
if (!data || typeof data.acct !== 'string' || !Array.isArray(data.entries) || typeof head?.seq !== 'number'
@@ -362,6 +372,9 @@ export function startGateway(host: GatewayHost): StartedGateway {
const devicePairs = () => gateway.listPairs().filter((p) => p.role === 'device')
const ops: GatewayOps = {
+ backend: accountHttp.backend,
+ machines: accountHttp.machines,
+ mintGridName: accountHttp.mintGridName,
status: async () => ({ fingerprint: gateway.fingerprint(), pairs: gateway.listPairs(), pending: gateway.pendingPair() as Record<string, unknown> | null }),
// `harness pair <code>` → run CPace toward the waiting browser; map the result to an HTTP outcome.
pair: async (code) => {
diff --git a/cli/src/harnessd/services.spec.ts b/cli/src/harnessd/services.spec.ts
index 1ce6c0bef..57819b7be 100644
--- a/cli/src/harnessd/services.spec.ts
+++ b/cli/src/harnessd/services.spec.ts
@@ -451,7 +451,7 @@ describe('ServiceSupervisor', () => {
const hosted = Object.values(SERVICE_HOSTS).flatMap((host) => host.services)
expect(KNOWN_SERVICES).toEqual(hosted)
expect(new Set(hosted).size).toBe(hosted.length)
- expect(SERVICE_HOSTS.edge.services).toEqual(['workspaces', 'usage', 'monitor', 'projects', 'handoff', 'recaps', 'windowNames'])
+ expect(SERVICE_HOSTS.edge.services).toEqual(['workspaces', 'usage', 'monitor', 'projects', 'handoff', 'recaps', 'windowNames', 'shell'])
})
})
@@ -467,7 +467,7 @@ describe('which services the core leaves to its master', () => {
expect(serviceProcessesEnv(serviceSpecs({ HARNESSD_SERVICES: 'store' }, SERVICE_HOSTS))).toMatchObject({ [SERVICE_PROCESSES_ENV]: 'store' })
// By service, not by process: a core from before the edge host routes the services it knows of it.
const hosted = serviceSpecs({ HARNESSD_SERVICES: 'edge' }, SERVICE_HOSTS)
- expect(serviceProcessesEnv(hosted)).toEqual({ [SERVICE_PROCESSES_ENV]: 'workspaces,usage,monitor,projects,handoff,recaps,windowNames', HARNESSD_SERVICES: 'workspaces,usage,monitor,projects,handoff,recaps,windowNames' })
+ expect(serviceProcessesEnv(hosted)).toEqual({ [SERVICE_PROCESSES_ENV]: 'workspaces,usage,monitor,projects,handoff,recaps,windowNames,shell', HARNESSD_SERVICES: 'workspaces,usage,monitor,projects,handoff,recaps,windowNames,shell' })
expect([...servicesTheMasterRuns({ ...supervised, ...serviceProcessesEnv(hosted) }, known)]).toEqual(['workspaces'])
expect(serviceProcessesEnv([])).toEqual({ [SERVICE_PROCESSES_ENV]: '', HARNESSD_SERVICES: 'none' })
expect([...servicesTheMasterRuns({ ...supervised, ...serviceProcessesEnv(specs) }, known)]).toEqual(['search', 'workspaces'])
diff --git a/cli/src/harnessd/services.ts b/cli/src/harnessd/services.ts
index 2d7bf819a..5f1e1785d 100644
--- a/cli/src/harnessd/services.ts
+++ b/cli/src/harnessd/services.ts
@@ -376,7 +376,7 @@ export const SERVICE_HOSTS: Readonly<Record<string, ServiceHostSpec>> = {
// than workspaces alone had. The recaps hold each session's last three recaps, answers (8 KiB each at
// most) and asks, as the core did while they ran in it, and a few timers per open turn. The window
// names hold at most 400 short names; their model runs in its own process (lib/oneshot.ts).
- edge: { services: ['workspaces', 'usage', 'monitor', 'projects', 'handoff', 'recaps', 'windowNames'], heapLimitMiB: 384, rssLimitMiB: 768 },
+ edge: { services: ['workspaces', 'usage', 'monitor', 'projects', 'handoff', 'recaps', 'windowNames', 'shell'], heapLimitMiB: 384, rssLimitMiB: 768 },
// The orchestrator (services/orchestratorProcess.ts), an experiment: started only once it is on, for a
// saved project or a request (core/api.ts `EXPERIMENTS`). Its projects' files and the frames of their
// Directors; the agents it runs are the core's.
diff --git a/cli/src/leanEntry.spec.ts b/cli/src/leanEntry.spec.ts
index 6182dc108..86ad23648 100644
--- a/cli/src/leanEntry.spec.ts
+++ b/cli/src/leanEntry.spec.ts
@@ -57,6 +57,17 @@ describe('the lean bundle a release carries', () => {
/** The binding's loader: the module `lib/sqliteBuiltin.ts` asks Node for, a string only that code holds. */
const hasSqlite = (names: Set<string>): boolean => [...names].some((name) => files.get(name)!.includes('"node:sqlite"'))
+ it('loads the bundled harness assets in the Store alone and shares their bytes across lean builds', () => {
+ const asset = 'harness-builtin-assets.mjs'
+ expect(files.has(asset)).toBe(true)
+ expect(loads('store').has(asset)).toBe(true)
+ for (const role of ['master', 'core', 'search', 'workspaces']) expect(loads(role).has(asset), role).toBe(false)
+ // The bytes occur once in the combined lean files, even though inline mode can load the Store too.
+ const marker = '"builtinFiles")'
+ expect(files.get(asset)?.includes(marker)).toBe(true)
+ expect([...files].filter(([, code]) => code.includes(marker)).map(([name]) => name)).toEqual([asset])
+ })
+
it('is files of their own for the master, the core and each service, the code it runs and no other role\'s', () => {
for (const role of ROLES) {
const others = [...loads(role)].map(runnerOf).filter((owner) => owner && owner !== role)
diff --git a/cli/src/lib/autonomous-device/parts.spec.ts b/cli/src/lib/autonomous-device/parts.spec.ts
index 43ed64170..048c536de 100644
--- a/cli/src/lib/autonomous-device/parts.spec.ts
+++ b/cli/src/lib/autonomous-device/parts.spec.ts
@@ -3,7 +3,7 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { AutonomousDeviceDirect, type DirectDeviceHost } from './direct.js'
-import { autonomousDeviceLocalRequest } from './localApi.js'
+import { autonomousDeviceLocalRequest } from '../deviceManagementHttp.js'
import { runningDevicePart, startDevicePart } from './parts.js'
import { DeviceResultJournal } from './resultJournal.js'
import { AutonomousDeviceService } from './service.js'
diff --git a/cli/src/lib/autonomous-device/localApi.spec.ts b/cli/src/lib/deviceManagementHttp.spec.ts
similarity index 99%
rename from cli/src/lib/autonomous-device/localApi.spec.ts
rename to cli/src/lib/deviceManagementHttp.spec.ts
index 5adad0b31..783d8c184 100644
--- a/cli/src/lib/autonomous-device/localApi.spec.ts
+++ b/cli/src/lib/deviceManagementHttp.spec.ts
@@ -1,5 +1,5 @@
import { describe, expect, it, vi } from 'vitest'
-import { autonomousDeviceLocalRequest, type AutonomousDeviceManagement } from './localApi.js'
+import { autonomousDeviceLocalRequest, type AutonomousDeviceManagement } from './deviceManagementHttp.js'
const id = Buffer.alloc(32, 255).toString('base64')
function fixture() {
diff --git a/cli/src/lib/autonomous-device/localApi.ts b/cli/src/lib/deviceManagementHttp.ts
similarity index 98%
rename from cli/src/lib/autonomous-device/localApi.ts
rename to cli/src/lib/deviceManagementHttp.ts
index 902d3ad6f..fc4eccedd 100644
--- a/cli/src/lib/autonomous-device/localApi.ts
+++ b/cli/src/lib/deviceManagementHttp.ts
@@ -1,4 +1,4 @@
-/** Thin local facade for the existing relay pairing manager. */
+/** Local HTTP validation only. Pairing and device state stay behind the gateway and Wi-Fi ports. */
export interface AutonomousDeviceManagement {
discover(): unknown | Promise<unknown>
pairStart(options: { code: string; device: string }): unknown | Promise<unknown>
diff --git a/cli/src/lib/gatewayWire.ts b/cli/src/lib/gatewayWire.ts
index e88b6ce83..49b6fc033 100644
--- a/cli/src/lib/gatewayWire.ts
+++ b/cli/src/lib/gatewayWire.ts
@@ -42,6 +42,9 @@ export function decodeGatewayBinary(raw: Uint8Array): { kind: GatewayBinary; id:
/** The requests the core asks the gateway's process (`serviceLinks.call`), answered under `<type>_result`:
* one per `GatewayOps` member that answers. */
export const GATEWAY_CALLS = {
+ backend: 'gateway_backend',
+ machines: 'gateway_machines',
+ mintGridName: 'gateway_mint_grid_name',
status: 'gateway_status',
pair: 'gateway_pair',
listPairs: 'gateway_list_pairs',
diff --git a/cli/src/lib/machineListReply.ts b/cli/src/lib/machineListReply.ts
new file mode 100644
index 000000000..75431d177
--- /dev/null
+++ b/cli/src/lib/machineListReply.ts
@@ -0,0 +1,22 @@
+/** The wire shape of a machine list. State and persistence belong to the gateway. */
+export function guestMachineList(computerId: string, name: string, hostname: string): Record<string, unknown> {
+ return { success: true, data: { machines: [{ machineId: computerId, computerId, name, hostname,
+ status: 'online', authMode: 'remote' }], stale: false, guest: true } }
+}
+
+/**
+ * Tag a cached machine-list body as stale, where the client actually reads it.
+ *
+ * The backend answers `{success:true,data:{…}}` and this daemon forwards that verbatim, so the flag has
+ * to go INSIDE `data` — a local client unwraps to `data` and would never see a top-level field. Older
+ * shapes that return the machines at the top level get it there instead.
+ */
+export function withStaleMarker(body: Record<string, unknown>, fetchedAt: number): Record<string, unknown> {
+ const marker = { stale: true, staleSince: new Date(fetchedAt).toISOString() }
+ const data = body.data
+ if (data && typeof data === 'object' && !Array.isArray(data)) {
+ return { ...body, data: { ...(data as Record<string, unknown>), ...marker } }
+ }
+ return { ...body, ...marker }
+}
+
diff --git a/cli/src/lib/sessionSearch/externals/copilot.ts b/cli/src/lib/sessionSearch/externals/copilot.ts
index 2b7279ae6..813398c7e 100644
--- a/cli/src/lib/sessionSearch/externals/copilot.ts
+++ b/cli/src/lib/sessionSearch/externals/copilot.ts
@@ -18,7 +18,7 @@ import { basename, join } from 'node:path'
import { copilotHistoryTurnOpen } from '../../../engines/copilot/normalizer.js'
import { agentCommandOwnershipSnapshot } from '../../engineBin.js'
import { argvTokens, engineProcessMatch } from '../../tmux.js'
-import { forEachLine } from '../transcript.js'
+import { forEachLine } from '../../transcriptReader.js'
import { absoluteFolder, entries, epochMs, fileStamp, parseLine, readTail, record, text, UUID } from './support.js'
import type { ExternalOrigin, ExternalProvider, ExternalSession, OwnerClaim, ProcessView, RunningProcess, ScanContext } from './types.js'
diff --git a/cli/src/lib/sessionSearch/externals/grok.ts b/cli/src/lib/sessionSearch/externals/grok.ts
index 1768530fc..a8ddee570 100644
--- a/cli/src/lib/sessionSearch/externals/grok.ts
+++ b/cli/src/lib/sessionSearch/externals/grok.ts
@@ -18,7 +18,7 @@ import { basename, join } from 'node:path'
import { agentCommandOwnershipSnapshot } from '../../engineBin.js'
import { argvTokens, engineProcessMatch } from '../../tmux.js'
-import { forEachLine } from '../transcript.js'
+import { forEachLine } from '../../transcriptReader.js'
import { absoluteFolder, entries, epochMs, fileStamp, parseLine, readJson, readTail, record, text, UUID } from './support.js'
import type { ExternalProvider, ExternalSession, OwnerClaim, ProcessView, RunningProcess, ScanContext } from './types.js'
diff --git a/cli/src/lib/sessionSearch/externals/muse.ts b/cli/src/lib/sessionSearch/externals/muse.ts
index ff6421b3c..8453f6237 100644
--- a/cli/src/lib/sessionSearch/externals/muse.ts
+++ b/cli/src/lib/sessionSearch/externals/muse.ts
@@ -18,7 +18,7 @@ import { basename, dirname, join } from 'node:path'
import type { AgentCommandOwnershipSnapshot } from '../../engineBin.js'
import { engineProcessMatch, resumeSessionId } from '../../tmux.js'
-import { forEachLine } from '../transcript.js'
+import { forEachLine } from '../../transcriptReader.js'
import { absoluteFolder, entries, epochMs, fileStamp, parseLine, readHead, readTail, record, text, UUID } from './support.js'
import { type ExternalProvider, type ExternalSession, type OwnerClaim, type ProcessView, type ScanContext, UNSETTLED } from './types.js'
diff --git a/cli/src/lib/sessionSearch/externals/pi.ts b/cli/src/lib/sessionSearch/externals/pi.ts
index 62e734544..ad2bbf198 100644
--- a/cli/src/lib/sessionSearch/externals/pi.ts
+++ b/cli/src/lib/sessionSearch/externals/pi.ts
@@ -22,7 +22,7 @@ import { isAbsolute, join, resolve } from 'node:path'
import type { AgentCommandOwnershipSnapshot } from '../../engineBin.js'
import { engineProcessMatch, resumeSessionId } from '../../tmux.js'
-import { forEachLine } from '../transcript.js'
+import { forEachLine } from '../../transcriptReader.js'
import { absoluteFolder, entries, fileStamp, parseLine, readHead, readJson, readTail, record, text } from './support.js'
import { type ExternalProvider, type ExternalSession, type OwnerClaim, type ProcessView, type ScanContext, UNSETTLED } from './types.js'
diff --git a/cli/src/lib/sessionSearch/indexer.ts b/cli/src/lib/sessionSearch/indexer.ts
index 8734fb2c1..1c0904d80 100644
--- a/cli/src/lib/sessionSearch/indexer.ts
+++ b/cli/src/lib/sessionSearch/indexer.ts
@@ -15,7 +15,7 @@ import { stat } from 'node:fs/promises'
import { performance } from 'node:perf_hooks'
import type { LiveEvent } from '../normalize.js'
-import { forEachLine, lineNormalizer, lineTime, skipPredicate } from './transcript.js'
+import { forEachLine, lineNormalizer, lineTime, skipPredicate } from '../transcriptReader.js'
import { TurnCollector } from './turns.js'
import type { ExternalHit, IndexedSession, SearchHit, SessionSearchStore, SessionTail } from './store.js'
diff --git a/cli/src/lib/sessionSearch/sessionTurns.ts b/cli/src/lib/sessionSearch/sessionTurns.ts
index 2b4e2ac98..59a9b5129 100644
--- a/cli/src/lib/sessionSearch/sessionTurns.ts
+++ b/cli/src/lib/sessionSearch/sessionTurns.ts
@@ -15,7 +15,7 @@
import { performance } from 'node:perf_hooks'
import type { LiveEvent } from '../normalize.js'
-import { forEachLine, lineNormalizer, lineTime, skipPredicate } from './transcript.js'
+import { forEachLine, lineNormalizer, lineTime, skipPredicate } from '../transcriptReader.js'
import { TurnCollector, type IndexedTurn } from './turns.js'
export interface TurnSource {
diff --git a/cli/src/lib/shellProtocol.ts b/cli/src/lib/shellProtocol.ts
index fad198cdd..3a5251472 100644
--- a/cli/src/lib/shellProtocol.ts
+++ b/cli/src/lib/shellProtocol.ts
@@ -1,2 +1,13 @@
+import { isAbsolute } from 'node:path'
/** Always sealed over the relay; replies go only to the requester. */
export const SHELL_REQUESTS = ['shell_capabilities', 'shell_open', 'shell_open_status', 'shell_context_reply', 'shell_visit_status'] as const
+
+/** Checked on both sides of the service link: shell syntax is never accepted as a program. */
+export function terminalOpenError(payload: Record<string, unknown>): 'INVALID_ARGV' | 'INVALID_CWD' | null {
+ const { argv, cwd } = payload
+ if (payload.command !== undefined || !Array.isArray(argv) || argv.length === 0 || argv.length > 256
+ || argv.some(arg => typeof arg !== 'string' || arg.includes('\0')) || !argv[0]
+ || Buffer.byteLength(JSON.stringify(argv)) > 32 * 1024) return 'INVALID_ARGV'
+ if (typeof cwd !== 'string' || !isAbsolute(cwd) || cwd.includes('\0') || Buffer.byteLength(cwd) > 4096) return 'INVALID_CWD'
+ return null
+}
diff --git a/cli/src/lib/sessionSearch/transcript.spec.ts b/cli/src/lib/transcriptReader.spec.ts
similarity index 98%
rename from cli/src/lib/sessionSearch/transcript.spec.ts
rename to cli/src/lib/transcriptReader.spec.ts
index 40b71658d..e14d8030c 100644
--- a/cli/src/lib/sessionSearch/transcript.spec.ts
+++ b/cli/src/lib/transcriptReader.spec.ts
@@ -4,8 +4,8 @@ import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
-import { copilotOwnLine, forEachLine, lineNormalizer, lineTime, museOwnStream, skipPredicate } from './transcript.js'
-import { TurnCollector, type IndexedTurn } from './turns.js'
+import { copilotOwnLine, forEachLine, lineNormalizer, lineTime, museOwnStream, skipPredicate } from './transcriptReader.js'
+import { TurnCollector, type IndexedTurn } from './sessionSearch/turns.js'
const dirs: string[] = []
function file(content: string | Buffer): string {
diff --git a/cli/src/lib/sessionSearch/transcript.ts b/cli/src/lib/transcriptReader.ts
similarity index 92%
rename from cli/src/lib/sessionSearch/transcript.ts
rename to cli/src/lib/transcriptReader.ts
index 411d3b5e0..c8ba41286 100644
--- a/cli/src/lib/sessionSearch/transcript.ts
+++ b/cli/src/lib/transcriptReader.ts
@@ -1,5 +1,5 @@
/**
- * Reading a transcript for session search: line by line from a byte offset, through the same
+ * Reading a transcript for search and session discovery: line by line from a byte offset, through the same
* incremental normalizer each engine uses for its live view.
*
* Transcripts are large (a long Codex rollout runs to gigabytes) and nearly all of it is tool output.
@@ -10,18 +10,18 @@
import { open } from 'node:fs/promises'
-import type { LiveEvent } from '../normalize.js'
-import { lineToEvents, newTurnState } from '../normalize.js'
-import { AgyNormalizer } from '../../engines/agy/normalizer.js'
-import { AmpNormalizer } from '../../engines/amp/normalizer.js'
-import { CodexNormalizer } from '../../engines/codex/normalizer.js'
-import { epochMs } from './externals/support.js'
-import { CommandCodeNormalizer } from '../../engines/commandcode/normalizer.js'
-import { CopilotNormalizer } from '../../engines/copilot/normalizer.js'
-import { CursorNormalizer } from '../../engines/cursor/normalizer.js'
-import { GrokNormalizer } from '../../engines/grok/normalizer.js'
-import { MuseNormalizer } from '../../engines/muse/normalizer.js'
-import { PiNormalizer } from '../../engines/pi/normalizer.js'
+import type { LiveEvent } from './normalize.js'
+import { lineToEvents, newTurnState } from './normalize.js'
+import { AgyNormalizer } from '../engines/agy/normalizer.js'
+import { AmpNormalizer } from '../engines/amp/normalizer.js'
+import { CodexNormalizer } from '../engines/codex/normalizer.js'
+import { epochMs } from './sessionSearch/externals/support.js'
+import { CommandCodeNormalizer } from '../engines/commandcode/normalizer.js'
+import { CopilotNormalizer } from '../engines/copilot/normalizer.js'
+import { CursorNormalizer } from '../engines/cursor/normalizer.js'
+import { GrokNormalizer } from '../engines/grok/normalizer.js'
+import { MuseNormalizer } from '../engines/muse/normalizer.js'
+import { PiNormalizer } from '../engines/pi/normalizer.js'
export type LineNormalizer = (line: string) => LiveEvent[]
diff --git a/cli/src/serviceProcess.ts b/cli/src/serviceProcess.ts
index 56005a8a7..a949475b6 100644
--- a/cli/src/serviceProcess.ts
+++ b/cli/src/serviceProcess.ts
@@ -35,6 +35,7 @@ export const SERVICE_RUNNERS: ReadonlyMap<string, () => Promise<Runner>> = new M
['monitor', async () => (await import('./services/monitorProcess.js')).runMonitorService],
['projects', async () => (await import('./services/projectsProcess.js')).runProjectsService],
['windowNames', async () => (await import('./services/windowNamesProcess.js')).runWindowNamesService],
+ ['shell', async () => (await import('./services/shellProcess.js')).runShellService],
['handoff', async () => (await import('./services/handoffProcess.js')).runHandoffService],
['recaps', async () => (await import('./services/recapsProcess.js')).runRecapsService],
['store', async () => (await import('./services/storeProcess.js')).runStoreService],
diff --git a/cli/src/services/AGENTS.md b/cli/src/services/AGENTS.md
index 42fc67961..dcf94d188 100644
--- a/cli/src/services/AGENTS.md
+++ b/cli/src/services/AGENTS.md
@@ -53,9 +53,9 @@ that process. A process per risk, not per feature (`SERVICE_HOSTS` in `src/harne
|---|---|---|---|
| `search` | search | native `node:sqlite`, the index's memory | always |
| `viewers` | viewers, store | the viewer servers, the remote viewer streams and rendered surfaces, minutes-long installs | always |
-| `edge` | workspaces, usage, monitor, projects, handoff, recaps | light pure-JS services: isolated from the core, not from each other | always |
-| `gateway` | gateway | network, crypto and pure-JS WebRTC: the attack surface | always |
-| `models` | models | grid's installs, downloads and commands | always |
+| `edge` | workspaces, usage, monitor, projects, handoff, recaps, windowNames, shell | light pure-JS services: isolated from the core, not from each other | always |
+| `gateway` | gateway | network, crypto and pure-JS WebRTC: the attack surface | on demand |
+| `models` | models | grid's installs, downloads and commands | on demand |
| `devices` | devices, wifi | the dials' serial ports, the fleet's lane, the voice router's worker, the Wi-Fi device | on demand |
| `orchestrator` | orchestrator | an experiment | on demand |
| `teams` | teams, collaboration | an experiment: Tab collaboration beside the prompt scopes | on demand |
@@ -65,7 +65,7 @@ that process. A process per risk, not per feature (`SERVICE_HOSTS` in `src/harne
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`). `HARNESSD_SERVICES=none` runs them all inside the core's
-process (for debugging or a quick way back). The shell service always runs in the core's process.
+process (for debugging or a quick way back). The shell service runs in the edge host too.
The updater is not in `SERVICE_HOSTS`: the core neither routes to it nor runs it, and `HARNESSD_SERVICES` does
not turn it off. The master runs it (`UPDATER_HOST`, `src/services/updaterProcess.ts`) for the installed copy,
@@ -135,6 +135,14 @@ master too old to run it starts it beside itself, still in its own process (`src
(`service_notice`) and carries terminal bytes as binary frames on its link. The core drops what would
pile up on a gateway that reads nothing, and the gateway gone is the relay gone: every remote client
with it, never a window on this computer. `e2e/gatewayProcess.e2e.ts` proves it, with a phone.
+- The shell service (`shellProcess.ts`) owns validation, setup replies and durable creation receipts in
+ the edge host. It asks the core to launch literal argv or read live terminal identity through
+ `core.terminals` (`core/shellQueries.ts`). A lost launch reply leaves an unconfirmed receipt and is
+ never retried as a new launch. `e2e/shell.e2e.ts` keeps an attached terminal working across an edge crash.
+- The gateway owns account/backend HTTP and the single writer of `machines.json` (`gateway/accountHttp.ts`).
+ The core retains its reported list for stale replies during a restart, bound to the current account.
+ The Store prepares bundled harnesses before reporting `prepared`; the core waits at most five seconds
+ before restore. The lean bundle shares one asset file, loaded by the Store and never by the core.
- A service that writes turns into agents (a team's question, the orchestrator's guidance) delivers each
under an id of its own through `core.turns.deliver`, hears what became of it through `onDelivery`, and
takes one back with `cancelDelivery` (core/deliveries.ts). In its own process `services/turnsLink.ts`
diff --git a/cli/src/services/inline.spec.ts b/cli/src/services/inline.spec.ts
index fc670f7d1..94aefde29 100644
--- a/cli/src/services/inline.spec.ts
+++ b/cli/src/services/inline.spec.ts
@@ -11,6 +11,7 @@ import { startOrchestrator } from './orchestrator.js'
import { startProjects } from './projects.js'
import { startRecaps } from './recaps.js'
import { startSearch } from './search.js'
+import { startShell } from './shell.js'
import { startSharing } from './sharing.js'
import { startStore } from './store.js'
import { startUsage } from './usage.js'
@@ -21,6 +22,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({ startCommandBar, startDevices, startHandoff, startGateway, startModels, startMonitor, startOrchestrator, startProjects, startRecaps, startSearch, startSharing, startStore, startTeamsInCore, startUsage, startViewers, startWifi, startWindowNames, startWorkspaces })
+ expect({ ...inline }).toEqual({ startCommandBar, startDevices, startHandoff, startGateway, startModels, startMonitor, startOrchestrator, startProjects, startRecaps, startSearch, startSharing, startShell, startStore, startTeamsInCore, startUsage, startViewers, startWifi, startWindowNames, startWorkspaces })
})
})
diff --git a/cli/src/services/inline.ts b/cli/src/services/inline.ts
index 4c29a5862..4083a1ac8 100644
--- a/cli/src/services/inline.ts
+++ b/cli/src/services/inline.ts
@@ -23,6 +23,7 @@ export { startOrchestrator } from './orchestrator.js'
export { startProjects } from './projects.js'
export { startRecaps } from './recaps.js'
export { startSearch } from './search.js'
+export { startShell } from './shell.js'
export { startSharing } from './sharing.js'
export { startStore } from './store.js'
export { startUsage } from './usage.js'
diff --git a/cli/src/services/processCoreApi.ts b/cli/src/services/processCoreApi.ts
index 4649be5d6..079310a6b 100644
--- a/cli/src/services/processCoreApi.ts
+++ b/cli/src/services/processCoreApi.ts
@@ -92,7 +92,7 @@ export function processCoreApi(dataDir: string, service: string, view: AgentsVie
conversations: CONVERSATIONS_OFF,
// Terminals are launched by the core alone (the shell service, #893): a service in its own process
// is refused, never handed a way to start a process outside the core.
- terminals: { open: TERMINALS_OFF.open, watch: view.watch ?? TERMINALS_OFF.watch },
+ terminals: { ...TERMINALS_OFF, watch: view.watch ?? TERMINALS_OFF.watch },
machine: UNASKED.machine,
agents: {
// The stopped agents are never sent to these services: none of them reads one.
diff --git a/cli/src/services/shell.spec.ts b/cli/src/services/shell.spec.ts
index b723a433b..95d377677 100644
--- a/cli/src/services/shell.spec.ts
+++ b/cli/src/services/shell.spec.ts
@@ -11,6 +11,7 @@ import { checkPidRuntime } from '../lib/deleteAgentFallback.js'
import { tmuxPaneState } from '../lib/tmux.js'
import { fakeCore } from '../testing/fakeCore.js'
import { SHELL_REQUESTS, startShell } from './shell.js'
+import { createTerminalSessions } from '../core/terminals/sessions.js'
vi.mock('node:fs/promises', async importOriginal => ({
...await importOriginal<typeof import('node:fs/promises')>(), stat: vi.fn(async () => ({ isDirectory: () => true })),
@@ -25,6 +26,7 @@ function setup() {
const core = fakeCore({ dataDir, terminals: { open: vi.fn(async () => ({ ok: true as const, agentId: 'shell' })) }, agents: {
byAgent: vi.fn(() => row), displayName: () => 'project', terminalAvailable: () => true,
} })
+ Object.assign(core.terminals, createTerminalSessions({ agents: core.agents, paneState: tmuxPaneState, processState: checkPidRuntime }))
const requests = startShell(core)
const ask = (type: string, payload: Record<string, unknown> = {}, asker = OWNER) => requests[type]!(payload, asker)
const payload = { creationId: randomUUID(), cwd: '/work/project', argv: ['/bin/zsh', '/work/a script', '$(touch nope)', 'a; b', ''] }
diff --git a/cli/src/services/shell.ts b/cli/src/services/shell.ts
index 43aa061bd..a7b6cd9b8 100644
--- a/cli/src/services/shell.ts
+++ b/cli/src/services/shell.ts
@@ -1,43 +1,19 @@
/** Shell requests stay outside the core: authorization, literal argv, and durable launch receipts. */
import { stat } from 'node:fs/promises'
-import { isAbsolute, join } from 'node:path'
+import { join } from 'node:path'
import type { CoreApi, ServiceRequests } from '../core/api.js'
import { AgentCreationReceipts, AgentCreationReceiptError, creationFingerprint, validCreationId, type AgentCreationStatus } from '../lib/agentCreationReceipt.js'
import { shellContextReply } from '../lib/shellContextReply.js'
-import { checkPidRuntime } from '../lib/deleteAgentFallback.js'
-import { tmuxPaneState } from '../lib/tmux.js'
+import { terminalOpenError } from '../lib/shellProtocol.js'
export { SHELL_REQUESTS } from '../lib/shellProtocol.js'
export function startShell(core: CoreApi): ServiceRequests {
const receipts = new AgentCreationReceipts(join(core.dataDir, 'shell-creations'))
const visits = new Map<string, Promise<Record<string, unknown>>>()
- // This only restores a client's parked shell view. The core still owns archiving and resume.
- // A banner or Ctrl-C is not proof: require the launcher's exit mark AND the exact process gone.
- const visitStatus = async (agentId: string): Promise<Record<string, unknown>> => {
- const row = core.agents.byAgent(agentId)
- // Discovery clears a completed launch record when it binds the engine's conversation.
- // October 6 shell-return E2E: a resumed process exited after discovery marked its row inactive,
- // before retirement. That flag cannot suppress an exact exit probe or the parked shell is stranded.
- if (!row || row.engine === 'terminal' || row.launch?.state === 'starting' || row.launch?.state === 'failed'
- || !row.tmuxPane || !row.processIdentity?.startMarker) return { exited: false }
- const session = { ...row, processIdentity: { ...row.processIdentity } }
- const identity = (value: ReturnType<typeof core.agents.byAgent>) => JSON.stringify([value?.engine, value?.sessionId,
- value?.registeredAt, value?.tmuxPane, value?.launch?.state, value?.processIdentity])
- const before = identity(session)
- const pane = await tmuxPaneState(session.tmuxPane)
- if (pane === 'gone' || pane === 'unknown' || pane.engineExit == null) return { exited: false }
- const process = await checkPidRuntime(session)
- return { exited: process.state === 'gone' && identity(core.agents.byAgent(agentId)) === before }
- }
- const describe = (status: AgentCreationStatus): Record<string, unknown> => {
+ const describe = async (status: AgentCreationStatus): Promise<Record<string, unknown>> => {
if (status.state !== 'created') return { ...status }
- const row = core.agents.byAgent(status.agentId)
- if (!row) return { state: 'unavailable' }
- return { state: 'created', agent: {
- id: row.agentId, sessionId: row.sessionId, engine: row.engine, name: core.agents.displayName(row),
- status: 'active', launch: row.launch, terminal: { available: core.agents.terminalAvailable(row.agentId) },
- project: { cwd: row.cwd, root: row.cwd, name: row.projectDir },
- } }
+ const agent = await core.terminals.describe(status.agentId)
+ return agent ? { state: 'created', agent } : { state: 'unavailable' }
}
const guarded = (run: () => Record<string, unknown> | Promise<Record<string, unknown>>) =>
Promise.resolve().then(run).catch((error: unknown) => {
@@ -51,37 +27,34 @@ export function startShell(core: CoreApi): ServiceRequests {
if (!asker.owner) return { error: 'OWNER_REQUIRED' }
if (typeof payload.agentId !== 'string' || !payload.agentId || payload.agentId.length > 256) return { error: 'INVALID_AGENT_ID' }
const id = payload.agentId
- if (!visits.has(id)) visits.set(id, visitStatus(id).finally(() => visits.delete(id)))
+ if (!visits.has(id)) visits.set(id, core.terminals.visitStatus(id).finally(() => visits.delete(id)))
return visits.get(id)!
},
shell_open_status: (payload, asker) => {
if (!asker.owner) return { error: 'OWNER_REQUIRED' }
if (!validCreationId(payload.creationId)) return { error: 'INVALID_CREATION_ID' }
- return guarded(() => ({ creationId: payload.creationId, ...describe(receipts.status(payload.creationId as string)) }))
+ return guarded(async () => ({ creationId: payload.creationId, ...await describe(receipts.status(payload.creationId as string)) }))
},
shell_open: (payload, asker) => {
if (!asker.owner) return { error: 'OWNER_REQUIRED' }
const { argv, cwd, creationId } = payload
if (!validCreationId(creationId)) return { error: 'INVALID_CREATION_ID' }
- // Do not turn a string into a program. All arguments, including punctuation and spaces, stay literal.
- if (payload.command !== undefined || !Array.isArray(argv) || argv.length === 0 || argv.length > 256
- || argv.some(arg => typeof arg !== 'string' || arg.includes('\0')) || !argv[0]
- || Buffer.byteLength(JSON.stringify(argv)) > 32 * 1024) return { error: 'INVALID_ARGV' }
- if (typeof cwd !== 'string' || !isAbsolute(cwd) || cwd.includes('\0') || Buffer.byteLength(cwd) > 4096) return { error: 'INVALID_CWD' }
- const request = { argv: [...argv] as string[], cwd }
+ const invalid = terminalOpenError(payload)
+ if (invalid) return { error: invalid }
+ const request = { argv: [...argv as string[]], cwd: cwd as string }
return guarded(async () => {
const status = await receipts.run(creationId, creationFingerprint(request), async () => {
// Filesystem providers can stall; a stalled path must not hold a launch indefinitely.
let timer: ReturnType<typeof setTimeout> | undefined
const directory = await Promise.race([
- stat(cwd).then(s => s.isDirectory(), () => false),
+ stat(request.cwd).then(s => s.isDirectory(), () => false),
new Promise<false>(resolve => { timer = setTimeout(() => resolve(false), 4000) }),
]).finally(() => clearTimeout(timer))
if (!directory) return { state: 'failed', error: 'CWD_NOT_FOUND' }
const opened = await core.terminals.open(request)
return opened.ok ? { state: 'created', agentId: opened.agentId } : { state: 'failed', error: opened.error, detail: opened.detail }
})
- return { creationId, ...describe(status) }
+ return { creationId, ...await describe(status) }
})
},
}
diff --git a/cli/src/services/shellProcess.spec.ts b/cli/src/services/shellProcess.spec.ts
new file mode 100644
index 000000000..662cbdd33
--- /dev/null
+++ b/cli/src/services/shellProcess.spec.ts
@@ -0,0 +1,85 @@
+import { mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { randomUUID } from 'node:crypto'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import type { CoreApi } from '../core/api.js'
+import { SHELL_REQUESTS } from '../lib/shellProtocol.js'
+import { runServiceProcess, type ServiceProcessOptions } from './process.js'
+import { runShellService, shellCoreApi } from './shellProcess.js'
+import { startShell } from './shell.js'
+vi.mock('./process.js', () => ({ runServiceProcess: vi.fn(() => ({ stop: vi.fn() })) }))
+afterEach(() => vi.clearAllMocks())
+
+describe('shell requests in the edge process', () => {
+ it('preserves launch refusals and details, and treats missing confirmation as uncertain', async () => {
+ const ask = vi.fn(async () => ({ ok: true, agentId: 'a' }) as Record<string, unknown>)
+ const core = shellCoreApi('/data', ask)
+ const request = { argv: ['sh'], cwd: '/work' }
+ expect(await core.terminals.open(request)).toEqual({ ok: true, agentId: 'a' })
+ expect(ask).toHaveBeenLastCalledWith('open', request)
+ ask.mockResolvedValueOnce({ ok: false, error: 'BUSY', detail: 'worktree in use' })
+ expect(await core.terminals.open(request)).toEqual({ ok: false, error: 'BUSY', detail: 'worktree in use' })
+ ask.mockResolvedValueOnce({ ok: false, error: 'FAILED', detail: 7 })
+ expect(await core.terminals.open(request)).toEqual({ ok: false, error: 'FAILED' })
+ for (const answer of [{}, { ok: true }, { ok: true, agentId: '' }, { ok: false }, { error: 'QUERY_FAILED' }]) {
+ ask.mockResolvedValueOnce(answer)
+ await expect(core.terminals.open(request)).rejects.toThrow('did not confirm')
+ }
+ })
+ it('reads current descriptions and never guesses that an engine exited', async () => {
+ const ask = vi.fn(async () => ({ agent: { id: 'a' } }) as Record<string, unknown>)
+ const core = shellCoreApi('/data', ask)
+ expect(await core.terminals.describe('a')).toEqual({ id: 'a' })
+ expect(ask).toHaveBeenLastCalledWith('describe', { agentId: 'a' })
+ for (const agent of [null, undefined, 7, []]) {
+ ask.mockResolvedValueOnce({ agent })
+ expect(await core.terminals.describe('a')).toBeNull()
+ }
+ ask.mockResolvedValueOnce({ error: 'QUERY_FAILED' })
+ await expect(core.terminals.describe('a')).rejects.toThrow('did not answer')
+ for (const exited of [undefined, 'true', false, true]) {
+ ask.mockResolvedValueOnce({ exited })
+ expect(await core.terminals.visitStatus('a')).toEqual({ exited: exited === true })
+ expect(ask).toHaveBeenLastCalledWith('visitStatus', { agentId: 'a' })
+ }
+ ask.mockRejectedValueOnce(new Error('disconnected'))
+ await expect(core.terminals.visitStatus('a')).rejects.toThrow('disconnected')
+ })
+ it('uses the current connection and refuses calls while disconnected', async () => {
+ let options!: ServiceProcessOptions, core!: CoreApi
+ const stop = vi.fn()
+ const service = runShellService({ dataDir: '/data', socketPath: '/socket', machineId: 'm', token: 't',
+ run: o => { options = o; return { stop } }, start: c => { core = c; return {} } })
+ expect(options).toMatchObject({ name: 'shell', socketPath: '/socket', machineId: 'm', token: 't' })
+ await expect(core.terminals.describe('a')).rejects.toThrow('disconnected')
+ options.onConnected!({ query: async () => ({ agent: { id: 'a' } }) })
+ expect(await core.terminals.describe('a')).toEqual({ id: 'a' })
+ options.onDisconnected!()
+ await expect(core.terminals.describe('a')).rejects.toThrow('disconnected')
+ options.onConnected!({ query: async () => ({ agent: null }) })
+ expect(await core.terminals.describe('a')).toBeNull()
+ service.stop()
+ expect(stop).toHaveBeenCalledOnce()
+ const dataDir = mkdtempSync(join(tmpdir(), 'shell-process-'))
+ try {
+ runShellService({ dataDir, socketPath: '/socket', machineId: 'm', token: 't' })
+ expect(Object.keys(vi.mocked(runServiceProcess).mock.calls.at(-1)![0].requests).sort()).toEqual([...SHELL_REQUESTS].sort())
+ } finally { rmSync(dataDir, { recursive: true, force: true }) }
+ })
+ it('does not repeat a launch whose reply was lost, even after the service restarts', async () => {
+ const dataDir = mkdtempSync(join(tmpdir(), 'shell-receipt-'))
+ const ask = vi.fn(async () => { throw new Error('link lost after launch') })
+ const payload = { creationId: randomUUID(), argv: ['sh'], cwd: dataDir }
+ const owner = { local: true, owner: true }
+ try {
+ const first = startShell(shellCoreApi(dataDir, ask))
+ const result = await first.shell_open!(payload, owner)
+ expect(result).toMatchObject({ creationId: payload.creationId, state: 'unconfirmed' })
+ const restarted = startShell(shellCoreApi(dataDir, ask))
+ expect(await restarted.shell_open!(payload, owner)).toEqual(result)
+ expect(await restarted.shell_open_status!(payload, owner)).toEqual(result)
+ expect(ask).toHaveBeenCalledTimes(1)
+ } finally { rmSync(dataDir, { recursive: true, force: true }) }
+ })
+})
diff --git a/cli/src/services/shellProcess.ts b/cli/src/services/shellProcess.ts
new file mode 100644
index 000000000..612734179
--- /dev/null
+++ b/cli/src/services/shellProcess.ts
@@ -0,0 +1,48 @@
+/** Shell policy and durable receipts run in the edge host. Every launch and live read goes to the core. */
+import type { CoreApi } from '../core/api.js'
+import { startShell } from './shell.js'
+import { processCoreApi } from './processCoreApi.js'
+import { runServiceProcess, type CoreConnection, type ServiceProcess } from './process.js'
+
+type Payload = Record<string, unknown>
+export function shellCoreApi(dataDir: string, ask: (query: string, payload: Payload) => Promise<Payload>): CoreApi {
+ const core = processCoreApi(dataDir, 'shell')
+ core.terminals.open = async (request) => {
+ const answer = await ask('open', { ...request })
+ if (answer.ok === true && typeof answer.agentId === 'string' && answer.agentId) return { ok: true, agentId: answer.agentId }
+ if (answer.ok === false && typeof answer.error === 'string') return { ok: false, error: answer.error,
+ ...(typeof answer.detail === 'string' ? { detail: answer.detail } : {}) }
+ // A missing reply might follow a successful launch. The receipt must stay unconfirmed, never retry it.
+ throw new Error('the core did not confirm the terminal launch')
+ }
+ core.terminals.describe = async (agentId) => {
+ const answer = await ask('describe', { agentId })
+ if (answer.error) throw new Error('the core did not answer the terminal read')
+ const agent = answer.agent
+ return agent && typeof agent === 'object' && !Array.isArray(agent) ? agent as Payload : null
+ }
+ core.terminals.visitStatus = async (agentId) => ({ exited: (await ask('visitStatus', { agentId })).exited === true })
+ return core
+}
+
+export interface ShellServiceOptions {
+ dataDir: string
+ socketPath: string
+ machineId: string
+ token: string
+ run?: typeof runServiceProcess
+ start?: typeof startShell
+}
+export function runShellService(options: ShellServiceOptions): ServiceProcess {
+ let connection: CoreConnection | null = null
+ const core = shellCoreApi(options.dataDir, (query, payload) => {
+ if (!connection) return Promise.reject(new Error('the core is disconnected'))
+ return connection.query(query, payload)
+ })
+ return (options.run ?? runServiceProcess)({
+ name: 'shell', socketPath: options.socketPath, machineId: options.machineId, token: options.token,
+ requests: (options.start ?? startShell)(core),
+ onConnected: linked => { connection = linked },
+ onDisconnected: () => { connection = null },
+ })
+}
diff --git a/cli/src/services/store.spec.ts b/cli/src/services/store.spec.ts
index df38f09aa..c29601078 100644
--- a/cli/src/services/store.spec.ts
+++ b/cli/src/services/store.spec.ts
@@ -7,6 +7,7 @@ const ASKER = { local: true, owner: true }
function setup(over: Partial<StoreDeps> = {}) {
const deps: StoreDeps = {
+ prepare: vi.fn(() => true),
refresh: vi.fn(async () => [{ id: 'acme/thing' }] as never),
rows: vi.fn((_installed, catalog) => (catalog ?? []).map((entry: { id: string }) => ({ id: entry.id, installed: false }))),
remove: vi.fn(() => ({ ok: true as const })),
@@ -18,6 +19,10 @@ function setup(over: Partial<StoreDeps> = {}) {
}
describe('the store service', () => {
+ it('prepares the release-owned harnesses before answering requests', () => {
+ const { deps } = setup()
+ expect(deps.prepare).toHaveBeenCalledOnce()
+ })
it('answers exactly the requests it declares', () => {
expect(Object.keys(setup().requests).sort()).toEqual([...STORE_REQUESTS].sort())
// Started as the daemon starts it, with the real catalog and installs behind it.
diff --git a/cli/src/services/store.ts b/cli/src/services/store.ts
index cc7f87177..517f09a60 100644
--- a/cli/src/services/store.ts
+++ b/cli/src/services/store.ts
@@ -10,6 +10,7 @@
* their processes hold what they need.
*/
import type { CoreApi, ServiceRequests } from '../core/api.js'
+import { ensureBundledCoreHarnesses } from '../dsh/builtins.js'
import { refreshDshRegistry } from '../dsh/catalog.js'
import { removeDsh } from '../dsh/install.js'
import { mutateDsh } from '../dsh/service.js'
@@ -19,18 +20,21 @@ import { dshInstallReply, dshInstallRequest, dshInstallStatus, dshListRows, dshR
export { STORE_REQUESTS } from '../core/api.js'
export interface StoreDeps {
+ prepare: typeof ensureBundledCoreHarnesses
refresh: typeof refreshDshRegistry
remove: typeof removeDsh
mutate: typeof mutateDsh
rows: typeof dshListRows
}
-const DEFAULTS: StoreDeps = { refresh: refreshDshRegistry, remove: removeDsh, mutate: mutateDsh, rows: dshListRows }
+const DEFAULTS: StoreDeps = { prepare: ensureBundledCoreHarnesses, refresh: refreshDshRegistry, remove: removeDsh, mutate: mutateDsh, rows: dshListRows }
const internal = (error: unknown): Record<string, unknown> =>
({ error: 'INTERNAL', detail: error instanceof Error ? error.message : String(error) })
export function startStore(core: CoreApi, deps: StoreDeps = DEFAULTS): ServiceRequests {
+ // Release-owned harnesses follow this build; setup belongs to the Store in either process mode.
+ deps.prepare()
return {
dsh_list: () => deps.refresh().then((catalog) => ({ dsh: deps.rows(undefined, catalog) }), internal),
// The clone under ~/.harness/dsh goes (a linked install loses only its link), and the index forgets
diff --git a/cli/src/services/storeProcess.spec.ts b/cli/src/services/storeProcess.spec.ts
index 0f0faed16..8912255d2 100644
--- a/cli/src/services/storeProcess.spec.ts
+++ b/cli/src/services/storeProcess.spec.ts
@@ -54,6 +54,7 @@ describe('the Store in its own process', () => {
// A list changes nothing: the core is not told.
await options.requests.dsh_list!({}, ASKER)
expect(heard).toEqual([
+ 'told prepared',
'told installStatus {"id":"acme/thing","phase":"clone"}', 'installed', 'told installed',
'updated', 'told installed', 'removed', 'told installed', 'listed',
])
@@ -62,8 +63,8 @@ describe('the Store in its own process', () => {
it('answers all the same with no core to tell, or one that cannot hear', async () => {
const { options, heard, query, connect } = setup()
expect(await options.requests.dsh_install!({ id: 'acme/thing' }, ASKER)).toEqual({ ok: true, id: 'acme/thing' })
- connect()
query.mockRejectedValue(new Error('the core went away'))
+ connect()
expect(await options.requests.dsh_install!({ id: 'acme/thing' }, ASKER)).toEqual({ ok: true, id: 'acme/thing' })
await Promise.resolve()
expect(heard).toEqual(['installed', 'installed'])
diff --git a/cli/src/services/storeProcess.ts b/cli/src/services/storeProcess.ts
index 4d882ef70..03906266c 100644
--- a/cli/src/services/storeProcess.ts
+++ b/cli/src/services/storeProcess.ts
@@ -53,6 +53,11 @@ export function runStoreService(options: StoreServiceOptions): ServiceProcess {
machineId: options.machineId,
token: options.token,
requests,
- onConnected: (connection) => { core = connection },
+ onConnected: (connection) => {
+ core = connection
+ // startStore has prepared the bundled harnesses before this link opens. A reconnect repeats the
+ // notice so a restarted core refreshes its installed index before restoring those agents.
+ void connection.query('prepared').catch(() => {})
+ },
})
}
diff --git a/cli/src/testing/fakeCore.ts b/cli/src/testing/fakeCore.ts
index 43011cc14..59d716a78 100644
--- a/cli/src/testing/fakeCore.ts
+++ b/cli/src/testing/fakeCore.ts
@@ -14,6 +14,8 @@ export function fakeCore(over: Overrides = {}): CoreApi {
conversations: { ...CONVERSATIONS_OFF, ...over.conversations },
terminals: {
open: vi.fn(TERMINALS_OFF.open),
+ describe: vi.fn(TERMINALS_OFF.describe),
+ visitStatus: vi.fn(TERMINALS_OFF.visitStatus),
watch: { frame: vi.fn(async () => {}), close: vi.fn(async () => {}), onOutput: vi.fn(() => () => {}) },
...over.terminals,
},
diff --git a/docs/design/2026-10-06-core-boundary-next.md b/docs/design/2026-10-06-core-boundary-next.md
index 11f64e89c..b31ae9fb0 100644
--- a/docs/design/2026-10-06-core-boundary-next.md
+++ b/docs/design/2026-10-06-core-boundary-next.md
@@ -31,11 +31,16 @@
> the orchestrator, the teams with Tab collaboration, Share and the command bar. Each process and what it
> hosts is in [../../cli/src/services/AGENTS.md](../../cli/src/services/AGENTS.md).
>
+> **Boundary follow-through, 2026-10-07.** Account/backend HTTP and `machines.json` move to the
+> gateway; the core reads reported state with an account-bound stale fallback. Bundled harness setup
+> moves to the Store; one shared lean asset file avoids duplicating bundled bytes. Shell request policy
+> and receipts move to the edge host; live terminal identity and literal-argv launch remain in the core.
+> The device HTTP adapter and transcript reader are shared helpers under `lib/`, not device/search
+> implementations. `CORE_MAY_REACH` is now empty. The lean core bundle has landed.
+>
> What is left:
> - **The engines' own code still loads in the core.** The engine-interface refactor
-> ([2026-10-05-engine-interface.md](2026-10-05-engine-interface.md)) is paused.
-> - **The core's process still parses all of cli.js.** Its memory falls only with a lean core bundle, which
-> is in progress (#955).
+> ([2026-10-05-engine-interface.md](2026-10-05-engine-interface.md)) has resumed with Claude Code and Codex first, a few engines per batch.
> - **The core grew where every session needs it.** #950 added a gate for tmux before 3.7, whose server
> crashes when a terminal attaches during a notification (`lib/tmuxControlGate.ts`).
diff --git a/scripts/tests/test_ci_plan.py b/scripts/tests/test_ci_plan.py
index 0f1dfa275..749e94315 100644
--- a/scripts/tests/test_ci_plan.py
+++ b/scripts/tests/test_ci_plan.py
@@ -93,6 +93,17 @@ class GitPlanTests(unittest.TestCase):
self.assertEqual(len(plan["paths"]), 351)
self.assertEqual(plan["suites"], ["website"])
+ def test_sparse_checkout_keeps_complete_component_selection(self):
+ self.write("cli/src/changed.ts")
+ self.write("desktop/lib/changed.dart")
+ self.write("scripts/planner.py")
+ self.commit()
+ self.git("sparse-checkout", "set", ".github", "scripts")
+ self.assertFalse((self.root / "cli/src/changed.ts").exists())
+ plan = self.plan()
+ self.assertEqual(plan["paths"], ["cli/src/changed.ts", "desktop/lib/changed.dart", "scripts/planner.py"])
+ self.assertEqual(plan["suites"], ["cli", "desktop"])
+
def test_rename_selects_old_and_new_components(self):
self.write("website/source.txt")
self.base = self.commit()