The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
harnessd: the viewers' process (viewers and the Store) starts on demand (#1273)
Dee2c2c6be529fd
diff --git a/cli/AGENTS.md b/cli/AGENTS.mdindex 740dc3703..7147a306e 100644--- a/cli/AGENTS.md+++ b/cli/AGENTS.md@@ -27,7 +27,7 @@ they show as `harnessd`, `harnessd-core` and `harnessd-<process>` (`src/harnessd| core | sessions (`src/core/`) | always || engine-claude, engine-codex | history, last-turn readers, live transcript parsers, runtime profiles/catalogs, screen interpretation, submission verification readings, model control, question navigation, and (Codex) the shared app-server connection | on demand: an attach or read for that engine || search | session search | always |-| viewers | the harness viewers, their remote streams and rendered surfaces, and the Store | always |+| viewers | the harness viewers, their remote streams and rendered surfaces, and the Store | on demand: a harness here (an agent with a DSH at start, or attached since), a Store or viewers request (the list, an install, a harness's create or restore, a client's viewer stream or rendered frame), or at start when the release's own harnesses are to be put in place or an earlier process left viewer servers running || edge | the shell service, workspaces, usage, the monitor, the project readers, the change-agent handoff, the recaps, the agent cleanup | 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 |diff --git a/cli/build-bundle.mjs b/cli/build-bundle.mjsindex b815e6bfd..71db35c23 100644--- a/cli/build-bundle.mjs+++ b/cli/build-bundle.mjs@@ -11,6 +11,7 @@* `require` via the banner so ws's try/catch fallback works without them.*/import * as esbuild from 'esbuild'+import { createHash } from 'node:crypto'import { appendFileSync, readFileSync, copyFileSync, rmSync, writeFileSync } from 'fs'import { readDshRegistry } from './scripts/lib/dshRegistry.mjs'import { readBuiltinBundle, readHarnessMonitorBundle, readMemoriesBundle, readModelManagerBundle } from './scripts/lib/modelManagerBundle.mjs'@@ -23,6 +24,15 @@ const modelManagerBundle = JSON.stringify(readModelManagerBundle(fileURLToPath(nconst devicesBundle = JSON.stringify(readBuiltinBundle(fileURLToPath(new URL('../store/agents/devices', import.meta.url)), ['harness.json', 'AGENTS.md', 'LICENSE', 'template']))const harnessMonitorBundle = JSON.stringify(readHarnessMonitorBundle(fileURLToPath(new URL('../store/agents/harness-monitor', import.meta.url))))const memoriesBundle = JSON.stringify(readMemoriesBundle(fileURLToPath(new URL('../store/agents/memories', import.meta.url))))+// What src/dsh/builtins.ts records in the installed index as each bundled harness's revision once it is in place: the+// sha256 of its files' JSON, as it reads them back (src/dsh/bundledFiles.ts). The core checks the index against these+// as it starts, without loading the files, and starts the Store's process only when one is not in place+// (src/core/viewersWake.ts). A harness whose files are missing is never put in place, so it has none.+const builtinRevisions = JSON.stringify(Object.fromEntries(+ [['models', modelManagerBundle], ['devices', devicesBundle], ['monitor', harnessMonitorBundle], ['memories', memoriesBundle]]+ .filter(([, bundle]) => JSON.parse(bundle)['harness.json'])+ .map(([name, bundle]) => [name, createHash('sha256').update(JSON.stringify(JSON.parse(bundle))).digest('hex')]),+))const version =process.env.ADAPTER_VERSION ||@@ -54,6 +64,7 @@ const options = {__DEVICES_BUNDLE__: JSON.stringify(devicesBundle),__HARNESS_MONITOR_BUNDLE__: JSON.stringify(harnessMonitorBundle),__MEMORIES_BUNDLE__: JSON.stringify(memoriesBundle),+ __BUILTIN_REVISIONS__: JSON.stringify(builtinRevisions),__DARWIN_PROCESS_IMAGES__: processImages ? JSON.stringify(processImages) : 'undefined',},// The copyright line is MIT's one condition — it has to travel with the copy the user actuallydiff --git a/cli/e2e/lean.e2e.ts b/cli/e2e/lean.e2e.tsindex 976afbf50..9fe64178e 100644--- a/cli/e2e/lean.e2e.ts+++ b/cli/e2e/lean.e2e.ts@@ -21,7 +21,9 @@ import { LEAN_CORE_ENTRY, readLeanBundle } from '../src/harnessd/leanBundle.js'type Engine = 'claude' | 'codex'/** The processes the master runs the services in, and the services, each on its own link to the core. The- * experiments' start only once they are on (e2e/experiments.e2e.ts, from the run's bundle). */+ * experiments' start only once they are on (e2e/experiments.e2e.ts, from the run's bundle). The viewers' starts+ * only once something needs it: in each test's new home, a bundle's own harnesses, which its Store puts in place,+ * ask for it as the core starts (core/viewersWake.ts, e2e/viewersOnDemand.e2e.ts). */const PROCESSES = ['search', 'viewers', 'edge', 'models']const SERVICES = ['search', 'viewers', 'store', 'workspaces', 'usage', 'monitor', 'projects', 'handoff', 'recaps', 'models']diff --git a/cli/e2e/reexec.e2e.ts b/cli/e2e/reexec.e2e.tsindex 44d89c161..2612b1ced 100644--- a/cli/e2e/reexec.e2e.ts+++ b/cli/e2e/reexec.e2e.ts@@ -379,8 +379,9 @@ describe.skipIf(!RELEASED)('a released master and this one, each over the other\: 'did not answer its probe (Unknown command: __harnessd-probe) — keeping this master')// This master over a core too old to ask for a process on demand starts each as that core binds// (harnessd/services.ts `unasked`): models, which a core of protocol 4 asks for only once grid is in use,- // and the gateway, which it asks for only signed in or with something paired.- for (const name of releasedCanReexec ? [] : ['models', 'gateway']) {+ // the gateway, which it asks for only signed in or with something paired, and the viewers, which a core of+ // protocol 5 asks for only once something needs them.+ for (const name of releasedCanReexec ? [] : ['models', 'gateway', 'viewers']) {await until(`this master to start ${name} for the older core`, () => daemon!.log().slice(from).includes(`[harnessd] service ${name} started`) || null, 30_000, 200)}})diff --git a/cli/e2e/services.e2e.ts b/cli/e2e/services.e2e.tsindex 18773b7ff..457447eb7 100644--- a/cli/e2e/services.e2e.ts+++ b/cli/e2e/services.e2e.ts@@ -72,11 +72,15 @@ describe('a failing service never takes the core down', () => {mkdirSync(join(d.dataDir, 'local-models'), { recursive: true })writeFileSync(join(d.dataDir, 'local-models', 'operations.json'), '[]')await d.start()+ // The viewers' process runs once something needs it (core/viewersWake.ts): the Store's list asks for it, and+ // waits for it no longer than a start (core/serviceLinks.ts `ON_DEMAND_START_MS`).+ const client = await LocalClient.connect(d)+ const listing = client.request('dsh_list', {}, 60_000)// Each process fails as it starts, again and again, until the master parks it; the core never waits for one.for (const service of SERVICE_PROCESSES) {await until(`the master to park ${service}`, () => d.log().includes(`[harnessd] service ${service} ended 3 times`) || null, 60_000, 250)}- const client = await LocalClient.connect(d)+ expect(await listing).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'store', retryable: true })const agentId = await boundAgent(d, client, 'no-service-processes')await turn(client, agentId, 'first, with every service down')expect(await client.request('session_search', { query: 'first' })).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'search' })@@ -258,10 +262,11 @@ describe('a failing service never takes the core down', () => {const d = daemononTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-80).join('\n')}`) })await d.start()- // In the viewers' process: asked before it has connected, it is answered SERVICE_UNAVAILABLE, retryable.- await until('the store to connect', () => d.log().includes('[services] store connected') || null, 30_000, 200)+ // In the viewers' process, which runs once something needs it: the first request starts it, waits for it and+ // is answered by it (core/viewersWake.ts).const client = await LocalClient.connect(daemon)- expect(await client.request('dsh_list', {})).toMatchObject({ error: 'SERVICE_FAILED', service: 'store' })+ expect(await client.request('dsh_list', {}, 60_000)).toMatchObject({ error: 'SERVICE_FAILED', service: 'store' })+ expect(d.log()).toContain('[services] store connected')// Its other requests are still the store's own answers, refusals included.expect(await client.request('dsh_remove', { id: '../../etc' })).toMatchObject({ error: 'INVALID_DSH', detail: 'dsh_remove needs an id' })expect(await client.request('dsh_install', { url: 'https://example.com/\n' })).toMatchObject({ error: 'INVALID_DSH' })@@ -416,11 +421,12 @@ describe('a failing service never takes the core down', () => {daemon = await IsolatedDaemon.create()const d = daemonawait d.start()- await until('the store to connect', () => d.log().includes('[services] store connected') || null, 30_000, 200)+ // Its process runs once something needs it (core/viewersWake.ts): the list starts it and waits for it.const client = await LocalClient.connect(daemon)const listed = await client.request('dsh_list', {}, 60_000)expect(listed.error, JSON.stringify(listed).slice(0, 400)).toBeUndefined()expect(Array.isArray(listed.dsh)).toBe(true)+ expect(d.log()).toContain('[services] store connected')client.close()})})diff --git a/cli/e2e/storeProcess.e2e.ts b/cli/e2e/storeProcess.e2e.tsindex 4bdf67c97..6bd367cf7 100644--- a/cli/e2e/storeProcess.e2e.ts+++ b/cli/e2e/storeProcess.e2e.ts@@ -1,6 +1,7 @@/*** The Harness Store in its own process, beside the viewers (harnessd/services.ts `SERVICE_HOSTS`), on the- * real daemon. The harnesses the release bundles are put in place by the Store's start; an install from a+ * real daemon, started once something needs it (core/viewersWake.ts; e2e/viewersOnDemand.e2e.ts). The harnesses+ * the release bundles are put in place by the Store's start; an install from a* repository runs there, its progress reaches the window as `dsh_install_status` through the core, and an* agent created on the harness the moment the install answers finds it installed, though the core keeps* the installed index for two seconds (dsh/installed.ts). Whatever happens to the process costs the Store@@ -73,6 +74,10 @@ describe('the Store in its own process, beside the viewers', () => {daemon = donTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`) })await d.start()+ // Its process runs once something needs it (core/viewersWake.ts): the list asks for it, as a window's does.+ const window = await LocalClient.connect(d)+ expect(Array.isArray((await window.request('dsh_list', {}, 60_000)).dsh)).toBe(true)+ window.close()await until('the Store to connect to the core', () => connected(d) >= 1 || null, 30_000, 200)return d}@@ -184,7 +189,9 @@ describe('the Store in its own process, beside the viewers', () => {await turn(client, plain.id, 'ready without the Store')const cwd = join(d.projectsDir, 'refused-package')mkdirSync(cwd)- const refused = await client.request('agent_create', { engine: 'claude', cwd, dsh: HARNESS, bypassPermission: true }, 10_000)+ // The Store has not connected to this core since it started: on demand, a request waits for it as long as a+ // start (core/serviceLinks.ts `ON_DEMAND_START_MS`), and is then refused, as every one after it is at once.+ const refused = await client.request('agent_create', { engine: 'claude', cwd, dsh: HARNESS, bypassPermission: true }, 30_000)expect(refused).toMatchObject({ error: 'DSH_UNAVAILABLE' })expect(readdirSync(cwd)).toEqual([])for (const agent of agents) expect(await row(client, agent.id)).toMatchObject({ launch: { state: 'held' } })diff --git a/cli/e2e/viewersOnDemand.e2e.ts b/cli/e2e/viewersOnDemand.e2e.tsnew file mode 100644index 000000000..668d64e82--- /dev/null+++ b/cli/e2e/viewersOnDemand.e2e.ts@@ -0,0 +1,199 @@+/**+ * The viewers' process on demand (core/viewersWake.ts, harnessd/services.ts `viewers`: the harness viewers and the+ * Store), on the real daemon, signed out: a computer with no harness runs no viewers' process, about 96 MiB it never+ * pays, and whatever needs it starts it.+ * - Idle with no harness: no process, while the others run.+ * - A Store request, a client's rendered frame or its viewer stream: the first starts it, those that come while it+ * starts wait with it, and each is answered by it, never refused for its never having started.+ * - A harness here: created, it asks for the process and its viewer comes up; after a restart, the core asks for it+ * as it starts, and the viewer comes back.+ * - Named in `HARNESSD_SERVICES`, as every master before this one ran it: it starts with the daemon.+ * - From a release bundle (`E2E_BUNDLE=1`): the release's own harnesses are put in place as the core starts, and+ * once they are, the next start asks for nothing.+ * A core too old to ask has it started as it binds: harnessd/services.spec.ts, and e2e/reexec.e2e.ts under a release.+ */+import { randomUUID } from 'node:crypto'+import { execFileSync } from 'node:child_process'+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'+import { afterEach, describe, expect, it, onTestFailed } from 'vitest'+import { MODEL_MANAGER_ID } from '../src/dsh/builtinIds.js'+import { LocalClient, type Frame } from './harness/client.js'+import { IsolatedDaemon, until } from './harness/daemon.js'++const HARNESS = 'e2e/sketch'+/** A run from a release bundle, which carries the release's own harnesses (only a bundle does). */+const BUNDLED = !!process.env.E2E_BUNDLE_PATH+const ASKING = "asking for the viewers' process"++const viewerScript = (d: IsolatedDaemon) => join(d.env.DSH_DIR!, 'e2e', 'sketch', 'viewer.mjs')+const installedFile = (d: IsolatedDaemon) => join(d.env.DSH_DIR!, 'installed.json')+const installed = (d: IsolatedDaemon): Array<Record<string, unknown>> => {+ try { return JSON.parse(readFileSync(installedFile(d), 'utf8')) } catch { return [] }+}++/** A harness with a viewer of its own (a small web server on the port the daemon hands it), added to what is+ * installed here: a bundle's own harnesses stay in place, or every start would ask for the Store again. */+function installHarness(d: IsolatedDaemon): void {+ const dir = join(d.env.DSH_DIR!, 'e2e', 'sketch')+ mkdirSync(dir, { recursive: true })+ writeFileSync(viewerScript(d), [+ "import { createServer } from 'node:http'",+ "createServer((_, res) => res.end(`sketch viewer ${process.pid}`)).listen(Number(process.env.HARNESS_VIEWER_PORT), '127.0.0.1')",+ ].join('\n') + '\n')+ writeFileSync(join(dir, 'harness.json'), JSON.stringify({+ spec: 1, id: HARNESS, name: 'Sketch', engine: 'claude',+ viewer: { command: `'${process.execPath}' '${viewerScript(d)}'`, url: 'http://127.0.0.1:${port}/' },+ }))+ writeFileSync(installedFile(d), JSON.stringify([+ ...installed(d).filter((record) => record.id !== HARNESS),+ { id: HARNESS, dir, source: dir, ref: null, commit: null, linked: false, installedAt: Date.now() },+ ]))+}+/** The viewer servers this daemon's harness started that are still running. */+const viewerServers = (d: IsolatedDaemon): number[] =>+ execFileSync('ps', ['-A', '-o', 'pid=,command=']).toString().trim().split('\n')+ .map((line) => line.trim().match(/^(\d+)\s+(.*)$/)).filter((match): match is RegExpMatchArray => !!match)+ .filter(([, , command]) => command.includes(viewerScript(d))).map(([, pid]) => Number(pid))++/** What the log says from `from` on. */+const since = (d: IsolatedDaemon, from: number) => d.log().slice(from)+const starts = (d: IsolatedDaemon, from = 0) => [...since(d, from).matchAll(/\[harnessd\] service viewers started/g)].length+const connections = (d: IsolatedDaemon, from = 0) => [...since(d, from).matchAll(/\[services\] viewers connected/g)].length++const row = async (client: LocalClient, agentId: string) =>+ ((await client.request<{ agents: Array<Record<string, any>> }>('agents_list', { includeStopped: true }, 30_000)).agents)+ .find((agent) => agent.id === agentId)+const viewerUrl = (client: LocalClient, agentId: string): Promise<string> =>+ until(`a viewer URL for ${agentId}`, async () => {+ const url = (await row(client, agentId))?.viewerUrl+ return typeof url === 'string' ? url : null+ }, 60_000, 250)+const serves = async (url: string): Promise<string | null> => {+ const response = await fetch(url, { signal: AbortSignal.timeout(2_000) }).catch(() => null)+ return response?.ok ? response.text() : null+}++describe('the viewers\' process, once something needs it', () => {+ let daemon: IsolatedDaemon | undefined+ const started: IsolatedDaemon[] = []+ afterEach(async () => {+ await daemon?.close()+ daemon = undefined+ // A viewer server runs in a process group of its own, and a failed test may have left one.+ for (const pid of started.splice(0).flatMap(viewerServers)) {+ try { process.kill(-pid, 'SIGKILL') } catch { /* not a group leader, or gone */ }+ try { process.kill(pid, 'SIGKILL') } catch { /* gone */ }+ }+ })+ /** A daemon as a computer runs it from its second start on, settled: from a bundle, the first start puts the+ * release's own harnesses in place, which asks for the Store (the last test). Returns where its log stands then. */+ const fresh = async (env: Record<string, string> = {}): Promise<{ d: IsolatedDaemon; from: number }> => {+ const d = await IsolatedDaemon.create({ env: { HARNESSD_SERVICE_INITIAL_BACKOFF_MS: '200', ...env } })+ daemon = d+ started.push(d)+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`) })+ await d.start()+ if (BUNDLED) {+ await until('the release\'s harnesses in place', () => installed(d).some((record) => record.id === MODEL_MANAGER_ID) || null, 60_000, 250)+ await d.restart()+ }+ const from = d.log().lastIndexOf('[harnessd] core started')+ // The others are up, and the core has had time to ask for anything it would ask for as it starts.+ await until('the services to connect', () => since(d, from).includes('[services] search connected') || null, 30_000, 200)+ await new Promise((resolve) => setTimeout(resolve, 3_000))+ return { d, from }+ }++ it('runs no viewers\' process with no harness here; a Store request starts it, and the requests meanwhile wait with it', async () => {+ const { d, from } = await fresh()+ expect(starts(d, from), 'a viewers\' process on a computer with no harness').toBe(0)+ expect(since(d, from)).not.toContain(ASKING)+ const window = await LocalClient.connect(d)+ // Three while it starts, two of the Store's and one of the viewers': each waits for it and is its answer.+ const [list, again, surface] = await Promise.all([+ window.request('dsh_list', {}, 60_000),+ window.request('dsh_list', {}, 60_000),+ window.request('viewer_surface', { surfaceId: 'e2e', agentId: 'nobody', op: 'close' }, 30_000),+ ])+ expect(list.error, JSON.stringify(list)).toBeUndefined()+ expect(Array.isArray(list.dsh)).toBe(true)+ expect(again.error, JSON.stringify(again)).toBeUndefined()+ expect(surface).toMatchObject({ closed: true })+ expect(surface.error).toBeUndefined()+ expect(starts(d, from)).toBe(1)+ expect(connections(d, from)).toBe(1)+ // Started, it stays: the next request is answered by the same process.+ expect(Array.isArray((await window.request('dsh_list', {}, 60_000)).dsh)).toBe(true)+ expect(starts(d, from)).toBe(1)+ expect(d.coresStarted()).toBe(BUNDLED ? 2 : 1)+ window.close()+ })++ it('a client\'s viewer stream before it ever started starts it and is answered by the viewers, not refused for their never having started', async () => {+ const { d, from } = await fresh()+ expect(starts(d, from)).toBe(0)+ const phone = await LocalClient.connect(d)+ const streamId = randomUUID()+ const closed = phone.next((frame: Frame) => frame.type === 'viewer_close' && frame.payload?.streamId === streamId, 30_000, 'the stream\'s close')+ phone.send('viewer_request', { streamId, agentId: 'nobody', origin: 'http://127.0.0.1:9', path: '/', method: 'GET', headers: {}, upgrade: false })+ // The viewers' own answer for an agent with no viewer, once they have started and connected.+ expect((await closed).payload).toMatchObject({ streamId, error: 'Viewer is no longer available' })+ await until('the viewers to have connected', () => connections(d, from) >= 1 || null, 10_000, 100)+ expect(starts(d, from)).toBe(1)+ expect(since(d, from)).toContain(`[viewers] a viewer stream: ${ASKING}`)+ phone.close()+ })++ it('a harness created here starts it and gets its viewer; after a restart the core asks for it as it starts', async () => {+ const { d, from } = await fresh()+ installHarness(d)+ const window = await LocalClient.connect(d)+ const cwd = join(d.projectsDir, 'sketch')+ mkdirSync(cwd, { recursive: true })+ const created = await window.request('agent_create', { engine: 'claude', cwd, bypassPermission: true, dsh: HARNESS }, 90_000)+ expect(created.error, JSON.stringify(created)).toBeUndefined()+ // Started once, by whichever came first: the create asks the Store for the harness's workspace, then attaches it.+ expect(await serves(await viewerUrl(window, created.agent.id))).toMatch(/^sketch viewer \d+$/)+ expect(starts(d, from)).toBe(1)+ window.close()++ await d.restart()+ const after = d.log().lastIndexOf('[harnessd] core started')+ expect(since(d, after)).toContain(`[viewers] a harness here: ${ASKING}`)+ await until('the viewers to connect', () => connections(d, after) >= 1 || null, 30_000, 200)+ const again = await LocalClient.connect(d)+ await until('the harness\'s viewer back', async () => {+ const url = (await row(again, created.agent.id))?.viewerUrl+ return typeof url === 'string' && /^sketch viewer \d+$/.test(await serves(url) ?? '') || null+ }, 60_000, 250)+ again.close()+ })++ it('named in HARNESSD_SERVICES, as every master before this one ran it, it starts with the daemon with no harness here', async () => {+ const { d, from } = await fresh({ HARNESSD_SERVICES: 'search,viewers' })+ await until('the viewers to connect', () => connections(d, from) >= 1 || null, 30_000, 200)+ expect(since(d, from)).not.toContain(ASKING)+ const window = await LocalClient.connect(d)+ expect(Array.isArray((await window.request('dsh_list', {}, 60_000)).dsh)).toBe(true)+ expect(starts(d, from)).toBe(1)+ window.close()+ })++ it.skipIf(!BUNDLED)('from a release bundle, puts the release\'s own harnesses in place as the core starts, and asks nothing once they are', async () => {+ const d = await IsolatedDaemon.create({ env: { HARNESSD_SERVICE_INITIAL_BACKOFF_MS: '200' } })+ daemon = d+ started.push(d)+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`) })+ await d.start()+ expect(d.log()).toContain(`[viewers] Model Manager to put in place: ${ASKING}`)+ await until('the release\'s harnesses in place', () => installed(d).some((record) => record.id === MODEL_MANAGER_ID) || null, 60_000, 250)+ await d.restart()+ const from = d.log().lastIndexOf('[harnessd] core started')+ await until('the services to connect', () => since(d, from).includes('[services] search connected') || null, 30_000, 200)+ await new Promise((resolve) => setTimeout(resolve, 3_000))+ // This build's revisions are what the Store recorded (build-bundle.mjs, dsh/builtins.ts): nothing to ask for.+ expect(since(d, from)).not.toContain(ASKING)+ expect(starts(d, from)).toBe(0)+ })+})diff --git a/cli/src/core/AGENTS.md b/cli/src/core/AGENTS.mdindex e366c567c..131662d2c 100644--- a/cli/src/core/AGENTS.md+++ b/cli/src/core/AGENTS.md@@ -57,7 +57,7 @@ questions. Everything else is a service ([../services/AGENTS.md](../services/AGE- `api.ts`: the contract with services, their ports, fallbacks and requests. `serviceHost.ts`: servicesin this process. `serviceLinks.ts`: services in their own processes. `viewersLink.ts`: what the corekeeps of the viewers when they run in theirs. `viewerStreams.ts`: a client's viewer stream and rendered- frames, handed to the viewers, and refused at once while they are down. `workspacesLink.ts`: what the core tells workspaces in+ frames, handed to the viewers, refused at once while they are down, and held while they first start. `workspacesLink.ts`: what the core tells workspaces intheirs. `messagesLink.ts`: which of Agent Messages' deliveries may be written, as its process last said.`monitorLink.ts`: the monitor's port, asked of its process. `recapsLink.ts`: the recaps in their process,told each turn's lifecycle and never waited on, and read back from what they last said@@ -83,4 +83,5 @@ questions. Everything else is a service ([../services/AGENTS.md](../services/AGEthat process is asked for, once there is a device (a dial's port in /dev, a paired Wi-Fi device).`modelsWake.ts`: when models' process is asked for as the core starts, once grid is in use here.`gatewayWake.ts`: when the gateway's process is asked for as the core starts, before it binds: signed in, or- anything paired here.+ anything paired here. `viewersWake.ts`: when the viewers' process (the viewers and the Store) is asked for: a+ harness here, or as the core starts, the release's own harnesses to put in place or viewer servers to stop.diff --git a/cli/src/core/api.ts b/cli/src/core/api.tsindex e6e43ff19..1b61e9fd2 100644--- a/cli/src/core/api.ts+++ b/cli/src/core/api.ts@@ -749,7 +749,8 @@ export const VIEWERS_UNAVAILABLE = { error: 'SERVICE_UNAVAILABLE', service: 'vie/** What the core gets when the viewers fail: agents' frames carry no DSH context and the windows* no viewer, a client's viewer stream is refused at once (core/viewerStreams.ts) and its surface- * answered unavailable, and a restart or shutdown goes on. */+ * answered unavailable, and a restart or shutdown goes on. Their process on demand, before it has+ * first connected, holds a stream and a surface while it starts instead (core/viewersLink.ts). */export const VIEWERS_FALLBACKS: PortFallbacks<ViewersPort> = {attach: undefined, detach: undefined, frameContext: null, forwardingUrl: null, stop: later(undefined),stream: false, surface: later(VIEWERS_UNAVAILABLE), closed: undefined,diff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex 2f4280136..1119a4ae9 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -197,6 +197,7 @@ import { createWifiCore, WIFI_START_MS } from './wifi.js'import { createDevicesWake, DEVICES_ON_DEMAND } from './devicesWake.js'import { wakeModels } from './modelsWake.js'import { wakeGateway } from './gatewayWake.js'+import { createViewersWake, VIEWERS_ON_DEMAND, wakeViewers } from './viewersWake.js'import { createWifiLink } from './wifiLink.js'import { wifiDoors } from './wifiAgents.js'import { autonomousDeviceLocalRequest } from '../lib/deviceManagementHttp.js'@@ -610,6 +611,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {ports.devices?.engines(registry.active().map((session) => session.engine))}const outOfProcess = servicesTheMasterRuns(harnessd, KNOWN_SERVICES)+ // The viewers' process (the viewers and the Store) runs once something needs it (core/viewersWake.ts).+ const viewersWake = createViewersWake({ want: (service) => coreLink.want(service), outOfProcess })const liveHosted = masterRunsLiveEngines(harnessd, process.ppid)const runtimeHosted = liveHosted && masterRunsEngineRuntime(harnessd, process.ppid)// An older master's explicit capability report selects compatibility. A failed worker never does.@@ -1258,7 +1261,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {const orchestratorLink = createOrchestratorLink((frame) => serviceLinks.notify('orchestrator', frame))// What the core keeps of the viewers in their own process, for the frames it builds (core/viewersLink.ts).const viewersLink = createViewersLink(coreApi, (frame, opts) => serviceLinks.notify('viewers', frame, opts),- { call: (type, payload, waitMs) => serviceLinks.call('viewers', type, payload, waitMs), buffered: () => serviceLinks.buffered('viewers') })+ { call: (type, payload, waitMs) => serviceLinks.call('viewers', type, payload, waitMs), buffered: () => serviceLinks.buffered('viewers') },+ { wake: (why) => viewersWake.ask('viewers', why) })// How the core tells workspaces in their own process what to do, and answers them (core/workspacesLink.ts).const workspacesLink = createWorkspacesLink(coreApi, (frame) => serviceLinks.notify('workspaces', frame), forgetAgentProject)// Agent Messages in its own process: which of its deliveries may be written, as it last said (core/messagesLink.ts).@@ -1309,10 +1313,10 @@ async function runForeground(session: AuthSession | null): Promise<void> {token: serviceToken,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.- // 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, ...Object.values(READER_SERVICES), 'models', 'gateway', 'shell']),+ // An experiment's process runs once on, the devices' once there is one, models', the gateway's and the viewers'+ // once needed: a request asks. 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, ...VIEWERS_ON_DEMAND, ...Object.values(READER_SERVICES), '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, authority) => await questionControls.answer(service, query, payload) ?? await modelControls.answer(service, query, payload) ?? await nativeControls.answer(service, query, payload) ?? engineReaders.answer(service) ?? (service === 'gateway' && gatewayLink ? gatewayLink.answer(query, payload) : null) ?? deliveries.answer(service, query, payload)@@ -1350,7 +1354,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {if (service === 'gateway') gatewayLink?.connected()if (service === 'devices') devicesLink.connected()if (service === 'wifi') wifiCore.started(appVoiceFocus ?? null)+ if (service === 'viewers') viewersLink.connected()devicesWake.connected(service)+ viewersWake.connected(service)// A service up again (or up at last): the agents held for it are launched (core/agents/heldLaunches.ts).void heldLaunches.restoreHeld(service)},@@ -1854,6 +1860,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {wakeExperiments({ dataDir: env.ADAPTER_DATA_DIR, experiments: EXPERIMENTS, outOfProcess, want: (service) => experimentHooks.want(service) })devicesWake.start(outOfProcess)wakeModels({ outOfProcess, dataDir: env.ADAPTER_DATA_DIR, runtimeDir: env.ADAPTER_RUNTIME_DIR, want: (service) => coreLink.want(service) })+ wakeViewers({ wake: viewersWake, agents: () => registry.list(), dataDir: env.ADAPTER_DATA_DIR })} else {try { writeFileSync(PID_FILE, String(process.pid) + '\n') } catch { /* best effort */ }}diff --git a/cli/src/core/serviceLinks.ts b/cli/src/core/serviceLinks.tsindex 7b4758208..1f0b4bb40 100644--- a/cli/src/core/serviceLinks.ts+++ b/cli/src/core/serviceLinks.ts@@ -63,7 +63,7 @@ export interface ServiceLinksOptions {* `LONG_ANSWERS`): a grid command, grid's set-up, a harness's install. */waits?: Readonly<Record<string, Readonly<Record<string, number>>>>/** The services whose process runs only once asked for: the experiments (core/api.ts `EXPERIMENTS`), the- * devices (core/devicesWake.ts) and models (core/modelsWake.ts). A request for one that has not connected yet+ * devices (core/devicesWake.ts), models (core/modelsWake.ts) and the viewers and the Store (core/viewersWake.ts). A request for one that has not connected yet* asks for it (`want`) and waits for it to connect, for its own wait or `startWaitMs`, whichever is shorter,* and then for its answer, for its own wait. One that has connected and is down again is answered as any* service is, at once; so is one that did not connect in time, until it does. */diff --git a/cli/src/core/viewerStreams.ts b/cli/src/core/viewerStreams.tsindex 56b8aa6d7..3c868774e 100644--- a/cli/src/core/viewerStreams.ts+++ b/cli/src/core/viewerStreams.ts@@ -9,7 +9,9 @@* passed on as it comes, and its answers go back to that one connection when the viewers send them* (`CoreApi.clients.viewerFrame`). While the viewers are off, hung behind a full socket or failing, a* stream is refused at once with `viewer_close`, so a client never waits out its own timeout for a viewer- * nobody is serving, and a surface is answered unavailable.+ * nobody is serving, and a surface is answered unavailable. Their process runs on demand: before it has+ * first connected, it is asked for and a stream and a surface wait for it, within a start's wait+ * (core/viewersLink.ts, core/viewersWake.ts).*/import { viewerStreamId } from '../lib/viewerFrames.js'import { VIEWERS_UNAVAILABLE, type ViewersPort } from './api.js'diff --git a/cli/src/core/viewersLink.spec.ts b/cli/src/core/viewersLink.spec.tsindex 2915ee0fa..dd3b53758 100644--- a/cli/src/core/viewersLink.spec.ts+++ b/cli/src/core/viewersLink.spec.ts@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest'import type { RegisteredSession } from '../lib/registry.js'import { fakeCore } from '../testing/fakeCore.js'import { VIEWERS_UNAVAILABLE } from './api.js'+import { ON_DEMAND_START_MS } from './serviceLinks.js'import { createViewersLink, SURFACE_WAIT_MS, VIEWERS_BUFFER_LIMIT } from './viewersLink.js'const agent = (over: Partial<RegisteredSession> = {}) =>@@ -202,3 +203,121 @@ describe('a viewer served to a client over its connection, through the viewers\'expect(core.clients.viewerFrame).not.toHaveBeenCalled()})})++describe('the viewers\' process on demand (core/viewersWake.ts)', () => {+ const onDemand = (connected = true) => {+ const core = fakeCore()+ vi.mocked(core.clients.viewerFrame).mockReturnValue(true)+ const notify = vi.fn(() => connected)+ const wake = vi.fn()+ const timers: Array<{ run: () => void; ms: number; cleared: boolean }> = []+ const link = createViewersLink(core, notify, { call: vi.fn(async () => ({})), buffered: () => 0 }, {+ wake,+ startWaitMs: 5_000,+ setTimer: (run, ms) => { const timer = { run, ms, cleared: false }; timers.push(timer); return timer },+ clearTimer: (timer) => { (timer as { cleared: boolean }).cleared = true },+ })+ return { core, notify, wake, timers, link, port: link.port }+ }+ const stream = (connId: string, type: string, streamId = 's1') =>+ ({ type: 'service_event', payload: { kind: 'stream', connId, type, frame: { streamId } } })++ it('asks for the process for an agent with a harness, and not for one without', () => {+ const { wake, port } = onDemand()+ port.attach(agent({ agentId: 'plain', dsh: undefined }))+ expect(wake).not.toHaveBeenCalled()+ port.attach(agent())+ expect(wake).toHaveBeenCalledWith('a harness here')+ })++ it('holds a stream that comes before the process ever connected, asks for it once, and tells it every frame in order once it connects', () => {+ const { core, notify, wake, timers, link, port } = onDemand()+ expect(port.stream('c1', 'viewer_request', { streamId: 's1' })).toBe(true)+ expect(port.stream('c2', 'viewer_request', { streamId: 's2' })).toBe(true)+ expect(port.stream('c1', 'viewer_data', { streamId: 's1' })).toBe(true)+ expect(wake.mock.calls).toEqual([['a viewer stream']])+ expect(timers).toHaveLength(1)+ expect(timers[0].ms).toBe(5_000)+ expect(notify).not.toHaveBeenCalled()+ link.connected()+ expect(timers[0].cleared).toBe(true)+ expect(notify.mock.calls).toEqual([[stream('c1', 'viewer_request')], [stream('c2', 'viewer_request', 's2')], [stream('c1', 'viewer_data')]])+ expect(core.clients.viewerFrame).not.toHaveBeenCalled()+ // Connected once, a frame is told as it comes, and refused at once while the process is down again.+ notify.mockReturnValue(false)+ expect(port.stream('c1', 'viewer_data', { streamId: 's1' })).toBe(false)+ expect(timers).toHaveLength(1)+ })++ it('refuses what it held, and every stream after it at once, when the process does not connect within a start\'s wait', () => {+ const { core, notify, wake, timers, link, port } = onDemand(false)+ port.stream('c1', 'viewer_request', { streamId: 's1' })+ port.stream('c1', 'viewer_close', { streamId: 's1' })+ port.stream('c1', 'viewer_data', {})+ timers[0].run()+ // Only the stream's own frames that need an answer are answered: a close and a frame of no stream need none.+ expect(core.clients.viewerFrame).toHaveBeenCalledTimes(1)+ expect(core.clients.viewerFrame).toHaveBeenCalledWith('c1', 'viewer_close', { streamId: 's1', error: 'Viewer is no longer available' })+ expect(port.stream('c1', 'viewer_request', { streamId: 's2' })).toBe(false)+ expect(notify).toHaveBeenCalledTimes(1)+ expect(wake).toHaveBeenCalledTimes(1)+ // It came at last: streams go to it again.+ notify.mockReturnValue(true)+ link.connected()+ expect(port.stream('c1', 'viewer_request', { streamId: 's3' })).toBe(true)+ expect(notify).toHaveBeenLastCalledWith(stream('c1', 'viewer_request', 's3'))+ })++ it('refuses a held frame the process does not take as it connects', () => {+ const { core, notify, link, port } = onDemand(false)+ port.stream('c1', 'viewer_request', { streamId: 's1' })+ link.connected()+ expect(notify).toHaveBeenCalledWith(stream('c1', 'viewer_request'))+ expect(core.clients.viewerFrame).toHaveBeenCalledWith('c1', 'viewer_close', { streamId: 's1', error: 'Viewer is no longer available' })+ })++ it('holds no more than a hung process\'s socket may keep: past it, a frame is refused', () => {+ const { port } = onDemand()+ const chunk = 'A'.repeat(VIEWERS_BUFFER_LIMIT / 2)+ expect(port.stream('c1', 'viewer_data', { streamId: 's1', data: chunk })).toBe(true)+ expect(port.stream('c1', 'viewer_data', { streamId: 's1', data: chunk })).toBe(false)+ expect(port.stream('c1', 'viewer_close', { streamId: 's1' })).toBe(true)+ })++ it('drops what it held for a connection that closed, or for every one', () => {+ const { notify, link, port } = onDemand()+ port.stream('c1', 'viewer_request', { streamId: 's1' })+ port.stream('c2', 'viewer_request', { streamId: 's2' })+ port.closed('c1')+ link.connected()+ expect(notify.mock.calls).toEqual([+ [{ type: 'service_event', payload: { kind: 'closed', connId: 'c1' } }],+ [stream('c2', 'viewer_request', 's2')],+ ])+ const again = onDemand()+ again.port.stream('c1', 'viewer_request', { streamId: 's1' })+ again.port.closed()+ again.link.connected()+ expect(again.notify.mock.calls).toEqual([[{ type: 'service_event', payload: { kind: 'closed' } }]])+ })++ it('waits a start\'s wait by default, on the real clock', () => {+ vi.useFakeTimers()+ try {+ const core = fakeCore()+ const link = createViewersLink(core, vi.fn(() => false), undefined, { wake: vi.fn() })+ link.port.stream('c1', 'viewer_request', { streamId: 's1' })+ vi.advanceTimersByTime(ON_DEMAND_START_MS - 1)+ expect(core.clients.viewerFrame).not.toHaveBeenCalled()+ vi.advanceTimersByTime(1)+ expect(core.clients.viewerFrame).toHaveBeenCalledWith('c1', 'viewer_close', { streamId: 's1', error: 'Viewer is no longer available' })+ // Connected, the default clock's timer is cleared too.+ link.port.stream('c1', 'viewer_request', { streamId: 's2' })+ const other = createViewersLink(core, vi.fn(() => true), undefined, { wake: vi.fn() })+ other.port.stream('c1', 'viewer_request', { streamId: 's3' })+ other.connected()+ vi.advanceTimersByTime(ON_DEMAND_START_MS)+ expect(core.clients.viewerFrame).toHaveBeenCalledTimes(1)+ } finally { vi.useRealTimers() }+ })+})diff --git a/cli/src/core/viewersLink.ts b/cli/src/core/viewersLink.tsindex df2898b45..2fd97bc09 100644--- a/cli/src/core/viewersLink.ts+++ b/cli/src/core/viewersLink.ts@@ -29,11 +29,20 @@* that stream in the process, as a frame the forwarder could not send ended it in the core's. A rendered* frame (`viewer_surface`) is asked of the process (`surface`), and answered unavailable, as a routed* request is, if it is down or slower than a client waits.+ *+ * The process runs on demand (core/viewersWake.ts): an agent with a harness attached asks for it, and so does a+ * client's stream that comes before it has ever connected to this core. That stream's frames are held, in order and+ * bounded, until it connects, as a request to a service on demand waits for it (core/serviceLinks.ts `onDemand`), and+ * refused if it has not come within a start's wait. Once it has connected, a stream is refused at once while it is+ * down, as before: a process that went down is the master's to bring back, and a client waits for nobody meanwhile.+ * Held, a stream that woke a process with no viewer yet is refused by the viewers themselves; one that came while a+ * running process reconnects to a core that restarted is served.*/import type { AgentDshContext } from '../lib/agentFrame.js'import { viewerStreamId } from '../lib/viewerFrames.js'import { VIEWERS_UNAVAILABLE, type CoreApi, type ViewersPort } from './api.js'-import type { ServiceFrame } from './serviceLinks.js'+import { ON_DEMAND_START_MS, type ServiceFrame } from './serviceLinks.js'+import { NOT_SERVED } from './viewerStreams.js'/** Tell the viewers' process something (core/serviceLinks.ts `notify`, for `viewers`). */export type NotifyViewers = (frame: ServiceFrame, opts?: { untilDelivered?: boolean }) => boolean@@ -55,20 +64,81 @@ export const SURFACE_WAIT_MS = 20_000const CLOSED: ViewersChannel = { call: async () => VIEWERS_UNAVAILABLE, buffered: () => 0 }+/** The viewers' process on demand: how the link asks for it, and how long a stream waits for it to connect. */+export interface ViewersDemand {+ /** Ask for the process (core/viewersWake.ts `ask`); `why` is what the log says. */+ wake(why: string): void+ /** How long a stream's frames are held for a process that has not connected yet (`ON_DEMAND_START_MS`). */+ startWaitMs?: number+ setTimer?: (run: () => void, ms: number) => unknown+ clearTimer?: (timer: unknown) => void+}++/** A client's stream frame held until the process connects. */+interface Held {+ connId: string+ type: string+ frame: Record<string, unknown>+ bytes: number+}+/** What the viewers last said of one agent. */interface Known {context: AgentDshContext | nullforwardingUrl: string | null}-export function createViewersLink(core: Pick<CoreApi, 'agents' | 'clients'>, notify: NotifyViewers, channel: ViewersChannel = CLOSED) {+export function createViewersLink(core: Pick<CoreApi, 'agents' | 'clients'>, notify: NotifyViewers, channel: ViewersChannel = CLOSED, demand?: ViewersDemand) {const attached = new Set<string>()const known = new Map<string, Known>()+ const setTimer = demand?.setTimer ?? ((run, ms) => setTimeout(run, ms))+ const clearTimer = demand?.clearTimer ?? ((timer) => clearTimeout(timer as ReturnType<typeof setTimeout>))+ /** Connected to this core at least once, or run by the master from the start (no `demand`): a stream is told or+ * refused at once from then on. */+ let seen = !demand+ /** Asked for by a stream and not connected within a start's wait: its streams are refused at once, as a request+ * to a service on demand that did not start is (core/serviceLinks.ts `unstarted`), until it connects. */+ let unstarted = false+ let held: Held[] = []+ let heldBytes = 0+ let startTimer: unknown = null++ const tell = (connId: string, type: string, frame: Record<string, unknown>): boolean =>+ channel.buffered() <= VIEWERS_BUFFER_LIMIT && notify({ type: 'service_event', payload: { kind: 'stream', connId, type, frame } })+ /** A stream's frame nobody will take ends that stream on the client's side; a close needs no answer. */+ const refuse = (connId: string, type: string, frame: Record<string, unknown>): void => {+ if (type !== 'viewer_close' && viewerStreamId(frame.streamId)) core.clients.viewerFrame(connId, 'viewer_close', { streamId: frame.streamId, error: NOT_SERVED })+ }+ const release = (): Held[] => {+ const frames = held+ held = []+ heldBytes = 0+ if (startTimer !== null) clearTimer(startTimer)+ startTimer = null+ return frames+ }+ /** Held for a process not yet connected, within the bound a hung process's socket gets: past it, refused. */+ const hold = (connId: string, type: string, frame: Record<string, unknown>): boolean => {+ const bytes = JSON.stringify(frame).length+ if (heldBytes + bytes > VIEWERS_BUFFER_LIMIT) return false+ held.push({ connId, type, frame, bytes })+ heldBytes += bytes+ if (startTimer === null) {+ demand!.wake('a viewer stream')+ startTimer = setTimer(() => {+ startTimer = null+ unstarted = true+ for (const each of release()) refuse(each.connId, each.type, each.frame)+ }, demand!.startWaitMs ?? ON_DEMAND_START_MS)+ }+ return true+ }const port: ViewersPort = {attach: (session) => {if (!session.dsh) returnattached.add(session.agentId)+ demand?.wake('a harness here')notify({ type: 'service_event', payload: { kind: 'attach', session } })},detach: (agentId) => {@@ -81,10 +151,14 @@ export function createViewersLink(core: Pick<CoreApi, 'agents' | 'clients'>, not// The viewers are the process's: a core restarting or stopping leaves them running for the next core,// and the master stops the process itself when the daemon stops.stop: async () => {},- stream: (connId, type, frame) =>- channel.buffered() <= VIEWERS_BUFFER_LIMIT && notify({ type: 'service_event', payload: { kind: 'stream', connId, type, frame } }),+ stream: (connId, type, frame) => seen || unstarted ? tell(connId, type, frame) : hold(connId, type, frame),surface: (connId, payload) => channel.call('surface', { ...payload, connId }, SURFACE_WAIT_MS),- closed: (connId) => { notify({ type: 'service_event', payload: { kind: 'closed', ...(connId === undefined ? {} : { connId }) } }) },+ closed: (connId) => {+ // What it held for the connection goes with it: nobody is left to read the answer.+ held = held.filter((each) => connId !== undefined && each.connId !== connId)+ heldBytes = held.reduce((sum, each) => sum + each.bytes, 0)+ notify({ type: 'service_event', payload: { kind: 'closed', ...(connId === undefined ? {} : { connId }) } })+ },}/** What the process tells the core without asking: a stream's frame for one client's connection. */@@ -119,6 +193,12 @@ export function createViewersLink(core: Pick<CoreApi, 'agents' | 'clients'>, notreturn {port,notice,+ /** The process connected: the streams held for it go to it, in the order they came. */+ connected(): void {+ seen = true+ unstarted = false+ for (const each of release()) if (!tell(each.connId, each.type, each.frame)) refuse(each.connId, each.type, each.frame)+ },/** The core's answers to the viewers' questions (core/serviceLinks.ts `answer`, for `viewers`). */answer(query: string, payload: Record<string, unknown>): Record<string, unknown> {// Every agent the core has with a harness, dormant ones too: the ones it attaches at start.diff --git a/cli/src/core/viewersWake.spec.ts b/cli/src/core/viewersWake.spec.tsnew file mode 100644index 000000000..d0686b6a8--- /dev/null+++ b/cli/src/core/viewersWake.spec.ts@@ -0,0 +1,119 @@+import { mkdtempSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { describe, expect, it, vi } from 'vitest'+import { DEVICES_HARNESS_ID, MEMORIES_BUILTIN_SOURCE, MEMORIES_ID, MODEL_MANAGER_BUILTIN_SOURCE, MODEL_MANAGER_ID } from '../dsh/builtinIds.js'+import type { InstalledDshRecord } from '../dsh/installed.js'+import { bundledPending, createViewersWake, VIEWER_LEDGER, VIEWERS_ON_DEMAND, wakeViewers, type BundledState } from './viewersWake.js'++const record = (over: Partial<InstalledDshRecord>): InstalledDshRecord =>+ ({ id: MODEL_MANAGER_ID, dir: '/dsh/x', source: MODEL_MANAGER_BUILTIN_SOURCE, ref: null, commit: null, revision: 'r1', linked: false, installedAt: 1, ...over }) as InstalledDshRecord++const state = (index: InstalledDshRecord[], over: Partial<BundledState> = {}): BundledState =>+ ({ revisions: { models: 'r1' }, index: () => index, broken: () => false, ...over })++describe('the release\'s own harnesses, as the core checks them for the Store', () => {+ it('has nothing to put in place in a build from the sources, which bundles none', () => {+ expect(bundledPending(state([], { revisions: {} }))).toBeNull()+ // The real index and this build's revisions: a test's own throwaway folder, and none.+ expect(bundledPending()).toBeNull()+ })++ it('asks for one missing, from another release or broken', () => {+ expect(bundledPending(state([]))).toBe('Model Manager to put in place')+ expect(bundledPending(state([record({ revision: 'r0' })]))).toBe('Model Manager to bring to this release')+ expect(bundledPending(state([record({ revision: undefined })]))).toBe('Model Manager to bring to this release')+ expect(bundledPending(state([record({})], { broken: () => true }))).toBe('Model Manager to repair')+ // Read as the installed index reads a record: a package whose folder is gone is broken.+ expect(bundledPending({ revisions: { models: 'r1' }, index: () => [record({ dir: join(tmpdir(), 'no-such-harness') })] })).toBe('Model Manager to repair')+ })++ it('has nothing to do when the index has this build\'s of each', () => {+ const revisions = { models: 'r1', memories: 'm1' }+ expect(bundledPending(state([record({}), record({ id: MEMORIES_ID, source: MEMORIES_BUILTIN_SOURCE, revision: 'm1' })], { revisions }))).toBeNull()+ expect(bundledPending(state([record({})], { revisions }))).toBe('Memories to put in place')+ })++ it('leaves a developer\'s linked checkout and a package of another source to the Store, which never replaces them', () => {+ const broken = vi.fn(() => true)+ expect(bundledPending(state([record({ linked: true, revision: 'r0' })], { broken }))).toBeNull()+ expect(bundledPending(state([record({ source: 'https://example.com/fork', revision: 'r0' })], { broken }))).toBeNull()+ expect(broken).not.toHaveBeenCalled()+ // Another harness's record is not this one's.+ expect(bundledPending(state([record({ id: DEVICES_HARNESS_ID })]))).toBe('Model Manager to put in place')+ })+})++describe('when the viewers\' process is asked for', () => {+ const setup = (outOfProcess: string[] = ['viewers', 'store']) => {+ const want = vi.fn()+ const log = vi.fn()+ const wake = createViewersWake({ want, outOfProcess: new Set(outOfProcess), log })+ return { want, log, wake }+ }++ it('asks once for each service, saying why, however often a harness is attached', () => {+ const { want, log, wake } = setup()+ wake.ask('viewers', 'a harness here')+ wake.ask('viewers', 'a harness here')+ wake.ask('store', 'Memories to put in place')+ expect(want.mock.calls).toEqual([['viewers'], ['store']])+ expect(log.mock.calls).toEqual([["[viewers] a harness here: asking for the viewers' process"], ["[viewers] Memories to put in place: asking for the viewers' process"]])+ })++ it('asks nothing for a service in the core\'s process, or one that has connected', () => {+ const inCore = setup([])+ inCore.wake.ask('viewers', 'a harness here')+ expect(inCore.want).not.toHaveBeenCalled()+ const connected = setup()+ connected.wake.connected('search')+ connected.wake.connected('viewers')+ connected.wake.ask('viewers', 'a harness here')+ connected.wake.ask('store', 'Memories to put in place')+ expect(connected.want.mock.calls).toEqual([['store']])+ expect(VIEWERS_ON_DEMAND).toEqual(['viewers', 'store'])+ })++ it('logs to the console unless told otherwise', () => {+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})+ try {+ const want = vi.fn()+ createViewersWake({ want, outOfProcess: new Set(['viewers']) }).ask('viewers', 'a harness here')+ expect(log).toHaveBeenCalledWith("[viewers] a harness here: asking for the viewers' process")+ } finally { log.mockRestore() }+ })+})++describe('the viewers\' process as the core starts', () => {+ const data = () => mkdtempSync(join(tmpdir(), 'viewers-wake-'))+ const nothing = state([], { revisions: {} })++ it('is asked for when an agent the registry kept has a harness', () => {+ const ask = vi.fn()+ wakeViewers({ wake: { ask }, agents: () => [{ dsh: undefined }, { dsh: 'acme/blender' }], dataDir: data(), bundled: nothing })+ expect(ask.mock.calls).toEqual([['viewers', 'a harness here']])+ })++ it('is asked for when an earlier process left viewer servers in its ledger, to stop them', () => {+ const dir = data()+ writeFileSync(join(dir, VIEWER_LEDGER), JSON.stringify([{ pid: 4242, startedAt: 1, agentId: 'a1', dshId: 'acme/blender', viewerDir: '/x' }]))+ const ask = vi.fn()+ wakeViewers({ wake: { ask }, agents: () => [], dataDir: dir, bundled: nothing })+ expect(ask.mock.calls).toEqual([['viewers', 'viewer servers an earlier process left running']])+ // An empty ledger, as a clean stop and the reaping leave it, asks nothing.+ writeFileSync(join(dir, VIEWER_LEDGER), '[]')+ ask.mockClear()+ wakeViewers({ wake: { ask }, agents: () => [], dataDir: dir, bundled: nothing })+ expect(ask).not.toHaveBeenCalled()+ })++ it('asks for the Store when the release\'s harnesses are not in place, and for nothing on an idle computer', () => {+ const ask = vi.fn()+ wakeViewers({ wake: { ask }, agents: () => [], dataDir: data(), bundled: state([]) })+ expect(ask.mock.calls).toEqual([['store', 'Model Manager to put in place']])+ ask.mockClear()+ // The real index and this build's revisions, a throwaway folder and none: nothing.+ wakeViewers({ wake: { ask }, agents: () => [{ dsh: null }], dataDir: data() })+ expect(ask).not.toHaveBeenCalled()+ })+})diff --git a/cli/src/core/viewersWake.ts b/cli/src/core/viewersWake.tsnew file mode 100644index 000000000..81d3c475e--- /dev/null+++ b/cli/src/core/viewersWake.ts@@ -0,0 +1,112 @@+/**+ * When the viewers' process starts (harnessd/services.ts `viewers`: the harness viewers and the Store, on demand since+ * protocol 5). It started with every daemon and idled at about 96 MiB, and few harnesses have a viewer: 1 of 14 on+ * one real machine, 2 of 35 on another (2026-10-12). So it starts once something needs it:+ *+ * - **a harness here**: an agent with a DSH in the registry as the core starts, or attached since (created, forked,+ * restored, found). Its viewer, its verdict and the name its frame carries are the viewers' (core/viewersLink.ts).+ * - **a request**: the Store's (`dsh_list`, an install, an update, a removal), a harness's create or restore, which+ * asks the Store for its workspace and launch (core/storeLink.ts), and a client's viewer stream or rendered frame+ * (core/viewersLink.ts). Each waits for it to start (core/serviceLinks.ts `onDemand`).+ * - **what it does on its own as it starts**, asked for as the core starts when there is something to do. The Store+ * puts in place the harnesses the release bundles (dsh/builtins.ts: the Model Manager, Devices, the Harness Monitor,+ * Memories) when the installed index does not have this build's. That cannot wait for a request: the core checks a+ * create against the index before it asks the Store, and memory and models run those packages' own files. And the+ * viewers stop the viewer servers an earlier process of theirs left running (dsh/viewerLedger.ts), when its ledger+ * names any.+ *+ * Nothing else in it runs on a timer: the Store's catalog is fetched when it is listed, and the viewers' watches and+ * restarts are each harness's. Once asked for, it is the master's to keep running, as every service is.+ */+import { BUNDLED_HARNESSES, bundledRevisions } from '../dsh/builtinIds.js'+import { isBrokenDsh, readInstalledIndex, resolveInstalled, type InstalledDshRecord } from '../dsh/installed.js'+import type { RegisteredSession } from '../lib/registry.js'+import { savedRows } from './devicesWake.js'++/** The services in the viewers' process, which a request or a harness wakes. */+export const VIEWERS_ON_DEMAND = ['viewers', 'store'] as const+export type ViewersService = typeof VIEWERS_ON_DEMAND[number]++/** The viewers' ledger of the viewer servers they started, in the data folder (dsh/viewerLedger.ts `VIEWER_LEDGER_FILE`). */+export const VIEWER_LEDGER = 'viewers.json'++/** What the core reads of the harnesses the release bundles: how it checks them without loading their files. */+export interface BundledState {+ /** This build's revision of each, by its name (dsh/builtinIds.ts `bundledRevisions`); none from the sources. */+ revisions: Readonly<Record<string, string>>+ /** The installed index. */+ index(): readonly InstalledDshRecord[]+ /** Whether a record's package is gone or no longer reads as it. */+ broken(record: InstalledDshRecord): boolean+}++const BUNDLED: BundledState = {+ revisions: bundledRevisions(),+ index: readInstalledIndex,+ broken: (record) => isBrokenDsh(resolveInstalled(record)),+}++/**+ * Why the Store has one of the release's harnesses to put in place, as the log says it; null when the index has this+ * build's of each. The same reading as dsh/builtins.ts `installBuiltin`, but for one case it leaves to the Store's next+ * start: a record of another source, which is a developer's or someone else's package it never replaces, or the old+ * Store package it adopts once, which every Store has done since (it ran at every start until this).+ */+export function bundledPending(given: Partial<BundledState> = {}): string | null {+ const state: BundledState = { ...BUNDLED, ...given }+ const index = state.index()+ for (const harness of BUNDLED_HARNESSES) {+ const revision = state.revisions[harness.name]+ if (!revision) continue+ const record = index.find((each) => each.id === harness.id)+ if (!record) return `${harness.what} to put in place`+ if (record.linked || record.source !== harness.source) continue+ if (record.revision !== revision) return `${harness.what} to bring to this release`+ if (state.broken(record)) return `${harness.what} to repair`+ }+ return null+}++export interface ViewersWakeDeps {+ /** Ask the master for the process that runs this service (harnessd/coreLink.ts `want`). */+ want(service: string): void+ /** The services the master runs in their own processes: one in the core's needs no asking. */+ outOfProcess: ReadonlySet<string>+ log?: (line: string) => void+}++export function createViewersWake(deps: ViewersWakeDeps) {+ const log = deps.log ?? ((line: string) => console.log(line))+ const asked = new Set<string>()+ return {+ /** Ask for the process this service runs in, once: a harness is attached on every pass that sees it, and the+ * master keeps a process it has started. `why` is what the log says. */+ ask(service: ViewersService, why: string): void {+ if (asked.has(service) || !deps.outOfProcess.has(service)) return+ asked.add(service)+ log(`[viewers] ${why}: asking for the viewers' process`)+ deps.want(service)+ },+ /** It connected: the master runs it, whoever asked for it, or it started with the others. */+ connected(service: string): void {+ if ((VIEWERS_ON_DEMAND as readonly string[]).includes(service)) asked.add(service)+ },+ }+}++export type ViewersWake = ReturnType<typeof createViewersWake>++/** At the core's start: the viewers' process asked for when a harness is here or it has something of its own to do. */+export function wakeViewers(deps: {+ wake: Pick<ViewersWake, 'ask'>+ /** The agents the registry kept. */+ agents: () => readonly Pick<RegisteredSession, 'dsh'>[]+ dataDir: string+ bundled?: Partial<BundledState>+ read?: (file: string) => string+}): void {+ if (deps.agents().some((agent) => !!agent.dsh)) deps.wake.ask('viewers', 'a harness here')+ else if (savedRows(deps.dataDir, VIEWER_LEDGER, deps.read).length) deps.wake.ask('viewers', 'viewer servers an earlier process left running')+ const pending = bundledPending(deps.bundled)+ if (pending) deps.wake.ask('store', pending)+}diff --git a/cli/src/dsh/builtinIds.ts b/cli/src/dsh/builtinIds.tsindex 443f83c7f..3dcb4c22f 100644--- a/cli/src/dsh/builtinIds.ts+++ b/cli/src/dsh/builtinIds.ts@@ -6,6 +6,7 @@* (docs/design/2026-10-06-core-boundary-next.md, step 6).*/export const MODEL_MANAGER_ID = 'autonomous/autonomous-grid'+export const MODEL_MANAGER_BUILTIN_SOURCE = 'builtin:model-manager'export const DEVICES_HARNESS_ID = 'autonomous/devices'export const DEVICES_BUILTIN_SOURCE = 'builtin:devices'export const HARNESS_MONITOR_ID = 'autonomous/harness-monitor'@@ -17,3 +18,30 @@ export const MEMORIES_BUILTIN_SOURCE = 'builtin:memories'export function isHiddenBuiltin(record: { source?: string | null }): boolean {return record.source === 'builtin:pair' || record.source === DEVICES_BUILTIN_SOURCE}++/** The harnesses a release bundles, under the names its build gives their files (./bundledFiles.ts), and what the+ * installed index records of each once the Store has put it in place (./builtins.ts `installBuiltin`). */+export const BUNDLED_HARNESSES = [+ { name: 'models', id: MODEL_MANAGER_ID, source: MODEL_MANAGER_BUILTIN_SOURCE, what: 'Model Manager' },+ { name: 'devices', id: DEVICES_HARNESS_ID, source: DEVICES_BUILTIN_SOURCE, what: 'Devices' },+ { name: 'monitor', id: HARNESS_MONITOR_ID, source: HARNESS_MONITOR_BUILTIN_SOURCE, what: 'Harness Monitor' },+ { name: 'memories', id: MEMORIES_ID, source: MEMORIES_BUILTIN_SOURCE, what: 'Memories' },+] as const++declare const __BUILTIN_REVISIONS__: string | undefined++/**+ * The revision of each harness this build bundles, by its name: what ./builtins.ts records in the installed index+ * once it is in place (the sha256 of its files' JSON), worked out by the release build (build-bundle.mjs). The core+ * checks the index against it as it starts, without loading the files (core/viewersWake.ts). None in a build from the+ * sources, which bundles no files and so has none to put in place.+ */+export function bundledRevisions(): Readonly<Record<string, string>> {+ if (typeof __BUILTIN_REVISIONS__ !== 'string') return {}+ try {+ const revisions: unknown = JSON.parse(__BUILTIN_REVISIONS__)+ return revisions && typeof revisions === 'object' && !Array.isArray(revisions) ? revisions as Record<string, string> : {}+ } catch {+ return {}+ }+}diff --git a/cli/src/dsh/builtins.spec.ts b/cli/src/dsh/builtins.spec.tsindex a1b9b462f..39e8e5aa1 100644--- a/cli/src/dsh/builtins.spec.ts+++ b/cli/src/dsh/builtins.spec.ts@@ -9,6 +9,9 @@ import { dshListRows } from './wire.js'import { installedDsh, invalidateInstalledDsh, readInstalledIndex, upsertInstalledRecord } from './installed.js'import { lockDsh } from './lock.js'import * as packageLock from './lock.js'+import { createHash } from 'node:crypto'+import { bundledRevisions } from './builtinIds.js'+import { bundledPending } from '../core/viewersWake.js'let root: stringlet original: string@@ -45,6 +48,22 @@ it('uses the embedded release bundle and returns unavailable in unbundled develoexpect(installedDsh(MODEL_MANAGER_ID)?.manifest.name).toBe('Model Manager')})+it('records each harness under the revision the release build works out for the core to check (core/viewersWake.ts)', () => {+ expect(bundledRevisions()).toEqual({})+ // build-bundle.mjs: the sha256 of each bundle's JSON as the Store reads it back.+ const text = JSON.stringify(bundle())+ vi.stubGlobal('__MODEL_MANAGER_BUNDLE__', text)+ vi.stubGlobal('__BUILTIN_REVISIONS__', JSON.stringify({ models: createHash('sha256').update(JSON.stringify(JSON.parse(text))).digest('hex') }))+ expect(bundledPending({ revisions: bundledRevisions() })).toBe('Model Manager to put in place')+ expect(ensureBundledModelManager()).toBe(true)+ expect(bundledPending({ revisions: bundledRevisions() })).toBeNull()+ // Revisions that do not read as a list of them are none.+ for (const malformed of ['[]', 'null', '{']) {+ vi.stubGlobal('__BUILTIN_REVISIONS__', malformed)+ expect(bundledRevisions()).toEqual({})+ }+})+it('joins a later attempt after another installer releases the package lock', () => {const release = lockDsh(MODEL_MANAGER_ID)!expect(ensureBundledModelManager(bundle())).toBe(false)diff --git a/cli/src/dsh/builtins.ts b/cli/src/dsh/builtins.tsindex 51a11e234..50ba67d5c 100644--- a/cli/src/dsh/builtins.ts+++ b/cli/src/dsh/builtins.ts@@ -1,7 +1,7 @@import { createHash, randomUUID } from 'node:crypto'import { existsSync, mkdirSync, renameSync, rmSync, writeFileSync } from 'node:fs'import { dirname, join } from 'node:path'-import { DEVICES_BUILTIN_SOURCE, DEVICES_HARNESS_ID, HARNESS_MONITOR_BUILTIN_SOURCE, HARNESS_MONITOR_ID, MEMORIES_BUILTIN_SOURCE, MEMORIES_ID, MODEL_MANAGER_ID } from './builtinIds.js'+import { DEVICES_BUILTIN_SOURCE, DEVICES_HARNESS_ID, HARNESS_MONITOR_BUILTIN_SOURCE, HARNESS_MONITOR_ID, MEMORIES_BUILTIN_SOURCE, MEMORIES_ID, MODEL_MANAGER_BUILTIN_SOURCE, MODEL_MANAGER_ID } from './builtinIds.js'import { dshRootDir, isBrokenDsh, readInstalledIndex, resolveInstalled, upsertInstalledRecord } from './installed.js'import { lockDsh } from './lock.js'import { readDshManifest } from './manifest.js'@@ -21,7 +21,7 @@ export type BundledFiles = Record<string, { content: string; executable: booleanexport function ensureBundledModelManager(files?: BundledFiles): boolean {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' })+ return installBuiltin({ id: MODEL_MANAGER_ID, source: MODEL_MANAGER_BUILTIN_SOURCE, 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. */diff --git a/cli/src/harnessd/protocol.ts b/cli/src/harnessd/protocol.tsindex 49ab92f65..e8b0254c7 100644--- a/cli/src/harnessd/protocol.ts+++ b/cli/src/harnessd/protocol.ts@@ -17,8 +17,10 @@ import type { SupervisorStatus } from './supervisor.js'* master's updater: the master tells its core to hand over for a build its updater staged (`harnessd:update`).* 4: `want` for the devices' process too, which runs only once there is a device, for models', which runs* only once grid is in use here or a request needs it, and for the gateway's, which runs once this machine is- * signed in, has anything paired or needs it; and `want` before `bound` (./services.ts `askedSince`). */-export const HARNESSD_PROTOCOL = 4+ * signed in, has anything paired or needs it; and `want` before `bound` (./services.ts `askedSince`).+ * 5: `want` for the viewers' process (the harness viewers and the Store), which runs once a harness is here, a+ * request needs it or the release's own harnesses are to be put in place (core/viewersWake.ts). */+export const HARNESSD_PROTOCOL = 5/** The command a bundle's master answers its probe on, and what it answers. */export const PROBE_COMMAND = '__harnessd-probe'@@ -65,8 +67,9 @@ export type CoreMessage =* loop was held since the last one (protocol 2). */| { type: 'harnessd:heartbeat'; rssBytes: number; heapUsedBytes: number; loopDelayMs?: number }/** Start the process that runs this service (harnessd/services.ts `onDemand`): an experiment that is on now- * (protocol 3), or the devices, models or the gateway, now that they are needed (protocol 4, and before- * `bound` too). A master from before ignores it, having started every service at once. */+ * (protocol 3), the devices, models or the gateway, now that they are needed (protocol 4, and before+ * `bound` too), or the viewers (protocol 5). A master from before ignores it, or finds that process already+ * running, having started it at once. */| { type: 'harnessd:want'; service: string }export type MasterMessage =diff --git a/cli/src/harnessd/services.spec.ts b/cli/src/harnessd/services.spec.tsindex b460756a7..7be703ec0 100644--- a/cli/src/harnessd/services.spec.ts+++ b/cli/src/harnessd/services.spec.ts@@ -458,6 +458,38 @@ describe('ServiceSupervisor', () => {expect(named.onDemand).toBeUndefined()})+ it('runs the viewers and the Store only once something needs them, asked for by a core of protocol 5, and from the start when named', () => {+ const [viewers] = serviceSpecs({}, SERVICE_HOSTS).filter((spec) => spec.name === 'viewers')+ expect(viewers).toMatchObject({ services: ['viewers', 'store'], onDemand: true, askedSince: 5 })+ // Named, as tests and support name it: from the start, as every master before it ran them.+ const [named] = serviceSpecs({ HARNESSD_SERVICES: 'viewers' }, SERVICE_HOSTS)+ expect(named.services).toEqual(['viewers', 'store'])+ expect(named.onDemand).toBeUndefined()+ // Asked for by either of its services.+ const supervisor = make([search, viewers])+ supervisor.start()+ expect(children.map((child) => child.spec.name)).toEqual(['search'])+ supervisor.want('store')+ supervisor.want('viewers')+ expect(children.map((child) => child.spec.name)).toEqual(['search', 'viewers'])+ })++ it('starts the viewers as a core of protocol 4 binds, which never asks for them, and leaves the rest to it', () => {+ const onDemand = serviceSpecs({}, SERVICE_HOSTS).filter((spec) => spec.onDemand)+ const four = make(onDemand)+ four.start()+ expect(children).toHaveLength(0)+ // Models, the devices and the gateway it asks for itself (protocol 4); the engines' workers are new to it.+ four.unasked(4)+ expect(children.map((child) => child.spec.name)).toEqual(['viewers'])+ // A core of this protocol asks for each itself.+ children.length = 0+ const five = make(onDemand)+ five.start()+ five.unasked(5)+ expect(children).toHaveLength(0)+ })+it('knows every service each process this build runs hosts, and each in one process only', () => {const hosted = Object.values(SERVICE_HOSTS).flatMap((host) => host.services)expect(KNOWN_SERVICES).toEqual(hosted)diff --git a/cli/src/harnessd/services.ts b/cli/src/harnessd/services.tsindex c6757da41..79fcd8024 100644--- a/cli/src/harnessd/services.ts+++ b/cli/src/harnessd/services.ts@@ -24,8 +24,8 @@ export interface ServiceSpec {heapLimitMiB: number/** Resident memory past which it is restarted, MiB; 0: off. */rssLimitMiB: number- /** A process on demand (an experiment's, the devices'): not started with the others, only once the core- * asks for one of its services (`want`), and then kept running like any other. */+ /** A process on demand (an experiment's, the devices', the viewers'): not started with the others, only once+ * the core asks for one of its services (`want`), and then kept running like any other. */onDemand?: boolean/** The core protocol (./protocol.ts) from which a core asks for this process on demand; 3, the experiments',* when unset. A core that speaks an older one never asks for it, and it is started as that core binds. */@@ -331,7 +331,8 @@ export class ServiceSupervisor {/*** A core bound that speaks [protocol], older than this master's: every process that became on demand after it* starts now, since that core never asks for one and ran it as it ran every other service. A core from before- * `want` (2) asks for none; one from before the devices were on demand (3) never asks for theirs.+ * `want` (2) asks for none; one from before the devices were on demand (3) never asks for theirs, and one from+ * before the viewers were (4) never for theirs.*/unasked(protocol: number): void {for (const each of this.services) if (each.spec.onDemand && (each.spec.askedSince ?? 3) > protocol) each.want()@@ -374,7 +375,10 @@ export const SERVICE_HOSTS: Readonly<Record<string, ServiceHostSpec>> = {// Its file watches on every harness's workspace; the viewer servers it starts are processes of their// own, outside this budget. The Store beside them: its installs run git and the harnesses' toolchains// in their own processes too, and take minutes, which is what it must not spend in the core.- viewers: { services: ['viewers', 'store'], heapLimitMiB: 512, rssLimitMiB: 1_024 },+ // Started only once something needs it (core/viewersWake.ts): a harness here, a Store or viewer request, or+ // the release's own harnesses to put in place. It idled at about 96 MiB on every computer, and few harnesses+ // have a viewer: 1 of 14 on one real machine, 2 of 35 on another (2026-10-12).+ viewers: { services: ['viewers', 'store'], heapLimitMiB: 512, rssLimitMiB: 1_024, onDemand: true, askedSince: 5 },// The git work (workspaces, the project readers) runs in git's own processes, and the monitor's// samples in ps's and ioreg's; what it holds is the agents the core sent it and one parsed sample.// The monitor parses up to 8 MB of ioreg output per Monitor poll on a Mac with a GPU, hence more@@ -517,7 +521,7 @@ export function servicesTheMasterRuns(env: NodeJS.ProcessEnv, known: readonly st* named as one of its services is named whole: `viewers` runs the viewers' process, the Store beside* them, as it ran the viewers' before the Store joined it. `HARNESSD_SERVICE_HEAP_LIMIT_MIB` gives every* one the same heap limit instead (tests, support). A process on demand (`onDemand`: an experiment's, the- * devices') waits for the core to ask for it; named in `HARNESSD_SERVICES`, it starts with the others.+ * devices', the viewers') waits for the core to ask for it; named in `HARNESSD_SERVICES`, it starts with the others.*/export function serviceSpecs(env: NodeJS.ProcessEnv, hosts: Readonly<Record<string, ServiceHostSpec>>): ServiceSpec[] {const named = env.HARNESSD_SERVICES === undefined ? nulldiff --git a/cli/src/harnessd/supervisor.spec.ts b/cli/src/harnessd/supervisor.spec.tsindex 8471083b1..5aa9d164b 100644--- a/cli/src/harnessd/supervisor.spec.ts+++ b/cli/src/harnessd/supervisor.spec.ts@@ -131,7 +131,10 @@ describe('Supervisor', () => {core().bind(2)crash()core().bind(3)- expect(unasked).toEqual([2, 3])+ // A core of protocol 4 asks for models, the devices and the gateway, never for the viewers.+ crash()+ core().bind(4)+ expect(unasked).toEqual([2, 3, 4])// A master with no services to start ignores both.make().start()core().bind(2)diff --git a/cli/src/services/AGENTS.md b/cli/src/services/AGENTS.mdindex 529e445d8..2c23277c9 100644--- a/cli/src/services/AGENTS.md+++ b/cli/src/services/AGENTS.md@@ -53,7 +53,7 @@ that process. A process per risk, not per feature (`SERVICE_HOSTS` in `src/harne|---|---|---|---|| `engine-claude`, `engine-codex` | history, live parsers, runtime profiles, screens, submission readings, model control, question navigation and Codex's app-server connection (`src/engines/worker/`) | engine behavior outside core; snapshots and revocable model- and question-control grants | on demand || `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 |+| `viewers` | viewers, store | the viewer servers, the remote viewer streams and rendered surfaces, minutes-long installs | on demand || `edge` | workspaces, usage, monitor, projects, handoff, recaps, windowNames, shell, connectors, agentCleanup | 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 |@@ -194,14 +194,23 @@ like any other. Named in `HARNESSD_SERVICES`, it starts with the others.signed in or has anything paired or linked directly (`src/core/gatewayWake.ts`), so the relay comes upbeside the core as before; otherwise by what needs it (`src/core/gatewayLink.ts`): a pairing, a window'sE2EE request or session to another machine, which wait for its first start, a key or device command, or- the Wi-Fi device's service. `/api/status` never starts it.+ the Wi-Fi device's service. `/api/status` never starts it. The viewers' process (the viewers and the Store)+ is asked for by a harness here, as the core starts or as one is attached (created, forked, restored, found),+ by a request (the Store's, a harness's create or restore, a client's viewer stream or rendered frame, which+ wait for it), and as the core starts when the release's own harnesses are not in the installed index as this+ build ships them (`src/dsh/builtinIds.ts` `bundledRevisions`) or the viewers' ledger names viewer servers an earlier+ process left running (`src/core/viewersWake.ts`). A stream before it has first connected is held, bounded,+ until it does (`src/core/viewersLink.ts`).- **Older cores.** `askedSince` is the core protocol (`HARNESSD_PROTOCOL`, `src/harnessd/protocol.ts`) fromwhich a core asks for this process. A core that speaks an older one never asks, so the master starts theprocess as that core binds (`ServiceSupervisor.unasked`). It is 3 by default, the experiments'; the- devices, models and the gateway became on demand at protocol 4, which may also ask before it binds. Making another process on demand needs a protocol bump, and that- number in its `askedSince`.-- **Proof.** `e2e/experiments.e2e.ts`, `e2e/devicesOnDemand.e2e.ts`, `e2e/modelsOnDemand.e2e.ts` and- `e2e/gatewayOnDemand.e2e.ts`: off, it has no process; asked for, it starts and answers.+ devices, models and the gateway became on demand at protocol 4, which may also ask before it binds; the+ viewers at protocol 5. Making another process on demand needs a protocol bump, and that number in its+ `askedSince`. A newer core under an older master asks for a process that master started with the others,+ which changes nothing.+- **Proof.** `e2e/experiments.e2e.ts`, `e2e/devicesOnDemand.e2e.ts`, `e2e/modelsOnDemand.e2e.ts`,+ `e2e/gatewayOnDemand.e2e.ts` and `e2e/viewersOnDemand.e2e.ts`: off, it has no process; asked for, it starts+ and answers.## Experimentsdiff --git a/docs/design/2026-10-03-harnessd.md b/docs/design/2026-10-03-harnessd.mdindex 946690b88..5fce47d89 100644--- a/docs/design/2026-10-03-harnessd.md+++ b/docs/design/2026-10-03-harnessd.md@@ -321,6 +321,23 @@ The steps, each a pull request with its end-to-end proof:started it stays, as every service does; stopping it when the last device leaves was measured and leftout (the PR says why). `HARNESSD_SERVICES=devices` still starts it with the daemon, and `none` runs itin the core. Proven by e2e/devicesOnDemand.e2e.ts and e2e/wifiDevice.e2e.ts.+- **The viewers on demand (done, 12 October).** The viewers' process (the harness viewers and the Store) started+ with every daemon and idled at about 96 MiB, and few harnesses have a viewer: 1 of 14 on one real machine, 2 of+ 35 on another. It now starts once something needs it (protocol 5; a core of protocol 4 or older never asks, so+ the master starts it as that core binds; a newer core under an older master asks for a process already+ running, which changes nothing). A harness here asks for it: an agent with a DSH in the registry as the core+ starts, or attached since. So does a request: the Store's, a harness's create or restore (the Store prepares its+ workspace and launch), a client's rendered frame, and a client's viewer stream, whose frames the core holds,+ bounded, until the process first connects (core/viewersLink.ts). And so does its own work at start, checked by+ the core: the Store puts the release's own harnesses in place (the Model Manager, Devices, the Harness Monitor,+ Memories) when the installed index does not have this build's revisions, which the release build computes for+ the core (build-bundle.mjs), since a create is checked against that index before the Store is asked and memory+ and models run those packages' files; and the viewers stop the viewer servers an earlier process left in their+ ledger (core/viewersWake.ts). The desktop still asks `dsh_list` with no click in three cases: the welcome+ composer on an empty tab, a restored Store tab (and its one-minute refresh), and a pending fork link.+ Measured idle with no harness, from release bundles on an isolated daemon, after the first start had put the+ bundled harnesses in place, three runs each, median: 526 to 531 MiB resident in all over seven processes+ before, 434 to 440 over six after, the viewers' 86 to 88 MiB gone. Proven by e2e/viewersOnDemand.e2e.ts.### Models