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.

The orchestrator is an experiment: a process of its own, started only once it is on (#924)

Dee28395afeb117
diff --git a/cli/e2e/experiments.e2e.ts b/cli/e2e/experiments.e2e.ts
new file mode 100644
index 000000000..f65934c67
--- /dev/null
+++ b/cli/e2e/experiments.e2e.ts
@@ -0,0 +1,147 @@
+/**
+ * The experiments, on the real daemon: each runs in a process of its own that the master starts only once it is
+ * on (core/api.ts `EXPERIMENTS`, harnessd/services.ts `onDemand`), the orchestrator first. Off, it has no
+ * process: a daemon whose person never used it pays nothing for it. Its first request, or its saved state as
+ * the daemon starts, turns it on. Whatever then happens to its process (killed, hung, crashing on every start)
+ * costs that process alone: the core never restarts, every agent keeps working, and the window on this
+ * computer stays connected and hears every turn.
+ */
+import { mkdirSync, writeFileSync } from 'node:fs'
+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'
+
+/** The orchestrator's process the master runs now: the last one it said it started, read from its log. */
+const orchestratorPid = (d: IsolatedDaemon): number | null => {
+ const started = [...d.log().matchAll(/\[harnessd\] service orchestrator started \(pid (\d+)\)/g)]
+ return started.length ? Number(started[started.length - 1][1]) : null
+}
+const starts = (d: IsolatedDaemon) => [...d.log().matchAll(/\[harnessd\] service orchestrator started/g)].length
+const connected = (d: IsolatedDaemon) => d.log().split('[services] orchestrator connected').length - 1
+
+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)
+async function create(d: IsolatedDaemon, client: LocalClient, folder: string, engine = 'claude'): Promise<Record<string, any>> {
+ const cwd = join(d.projectsDir, folder)
+ mkdirSync(cwd, { recursive: true })
+ const created = await client.request('agent_create', { engine, cwd, bypassPermission: true }, 90_000)
+ expect(created.error, `${folder}: ${JSON.stringify(created)}`).toBeUndefined()
+ return until(`${folder} to bind its conversation`, async () => {
+ const agent = await row(client, created.agent.id)
+ return agent?.sessionId && agent.status === 'active' ? agent : null
+ }, 60_000, 500)
+}
+/** A message to the agent and its whole turn, heard by the window that sent it. */
+async function turn(client: LocalClient, agentId: string, content: string): Promise<void> {
+ const ended = client.next((frame: Frame) => frame.type === 'turn_ended' && frame.agentId === agentId, 45_000, `turn_ended (${content})`)
+ client.send('message', { agentId, content })
+ await ended
+}
+const projects = (client: LocalClient) => client.request('orchestrator', { action: 'list' }, 40_000)
+
+describe('the experiments, each in a process started only when it is on', () => {
+ let daemon: IsolatedDaemon | undefined
+ afterEach(async () => { await daemon?.close(); daemon = undefined })
+ const fresh = async (env: Record<string, string> = {}, before?: (d: IsolatedDaemon) => void) => {
+ const d = await IsolatedDaemon.create({ env: {
+ HARNESSD_SERVICE_INITIAL_BACKOFF_MS: '200',
+ HARNESSD_SERVICE_MAX_BACKOFF_MS: '1000',
+ ...env,
+ } })
+ daemon = d
+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`) })
+ before?.(d)
+ await d.start()
+ return d
+ }
+
+ it('off, the orchestrator has no process; its first request starts it, and is answered', async () => {
+ const d = await fresh()
+ const client = await LocalClient.connect(d)
+ const agent = await create(d, client, 'experiment-off')
+ await turn(client, agent.id, 'nothing here uses an experiment')
+ await until('the services to connect', () => d.log().includes('[services] search connected') || null, 30_000, 200)
+ expect(starts(d), 'an experiment no one asked for').toBe(0)
+ expect(await projects(client)).toMatchObject({ projects: [] })
+ expect(starts(d)).toBe(1)
+ expect(connected(d)).toBe(1)
+ // On now: asked again, the same process answers.
+ expect(await projects(client)).toMatchObject({ projects: [] })
+ expect(starts(d)).toBe(1)
+ expect(d.coresStarted()).toBe(1)
+ client.close()
+ })
+
+ it('a saved project turns it on as the daemon starts, with no request', async () => {
+ const id = 'c'.repeat(32)
+ const d = await fresh({}, (daemon) => {
+ const stateDir = join(daemon.dataDir, 'orchestrator')
+ mkdirSync(stateDir, { recursive: true, mode: 0o700 })
+ writeFileSync(join(stateDir, `${id}.json`), JSON.stringify({
+ version: 1, id, fingerprint: 'f', prompt: 'Build the robot', engine: 'claude', bypassPermission: false, parallelism: 3,
+ root: stateDir, directorId: null, directorWorking: false, state: 'paused', error: null,
+ tasks: [], messages: [], revision: 1, createdAt: 1, updatedAt: 1,
+ }), { mode: 0o600 })
+ })
+ await until('the orchestrator to start for its saved project', () => connected(d) >= 1 || null, 30_000, 200)
+ const client = await LocalClient.connect(d)
+ const answer = await projects(client)
+ expect((answer.projects as Array<{ id: string }>).map((project) => project.id)).toEqual([id])
+ client.close()
+ })
+
+ it('with HARNESSD_SERVICES=none it runs in the core\'s process, as before', async () => {
+ const d = await fresh({ HARNESSD_SERVICES: 'none' })
+ const client = await LocalClient.connect(d)
+ expect(await projects(client)).toMatchObject({ projects: [] })
+ expect(starts(d)).toBe(0)
+ client.close()
+ })
+
+ it('killed outright: the core, the agents and the window go on; it is back for its next request', async () => {
+ const d = await fresh()
+ const client = await LocalClient.connect(d)
+ const agent = await create(d, client, 'experiment-killed', 'codex')
+ expect(await projects(client)).toMatchObject({ projects: [] })
+ process.kill(orchestratorPid(d)!, 'SIGKILL')
+ await until('the master to see it gone', () => d.log().includes('[harnessd] service orchestrator exited') || null, 30_000, 100)
+ // The agent never noticed, and the window that asked heard its whole turn.
+ await turn(client, agent.id, 'while the orchestrator was gone')
+ await until('the master to start it again', () => starts(d) >= 2 && connected(d) >= 2 || null, 30_000, 200)
+ expect(await projects(client)).toMatchObject({ projects: [] })
+ expect(d.coresStarted()).toBe(1)
+ client.close()
+ })
+
+ it('hung: killed at the heartbeat watch and started again; nothing else waited on it', async () => {
+ const d = await fresh({ HARNESSD_SERVICE_HEARTBEAT_TIMEOUT_MS: '2000' })
+ const client = await LocalClient.connect(d)
+ const agent = await create(d, client, 'experiment-hung')
+ expect(await projects(client)).toMatchObject({ projects: [] })
+ const first = orchestratorPid(d)!
+ process.kill(first, 'SIGSTOP')
+ await turn(client, agent.id, 'the core never waits on an experiment')
+ await until('the master to find it hung', () => d.log().includes('[harnessd] service orchestrator sent no heartbeat') || null, 30_000, 200)
+ await until('it to be started again', () => starts(d) >= 2 && connected(d) >= 2 || null, 30_000, 200)
+ expect(orchestratorPid(d)).not.toBe(first)
+ expect(await projects(client)).toMatchObject({ projects: [] })
+ expect(d.coresStarted()).toBe(1)
+ client.close()
+ })
+
+ it('crashing on every start, it is parked once turned on, and says so; agents and the window go on', async () => {
+ const d = await fresh({ HARNESSD_TEST_FAULTS: 'orchestrator.crash', HARNESSD_SERVICE_PARK_CRASHES: '3' })
+ const client = await LocalClient.connect(d)
+ const agent = await create(d, client, 'experiment-crash-loop', 'codex')
+ expect(starts(d)).toBe(0)
+ // Its first request turns it on; whatever it is answered, it is an answer.
+ await projects(client)
+ await until('the master to park it', () => d.log().includes('[harnessd] service orchestrator ended 3 times') || null, 60_000, 250)
+ expect(await projects(client)).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'orchestrator' })
+ await turn(client, agent.id, 'the orchestrator is parked and nothing else cares')
+ expect(d.coresStarted()).toBe(1)
+ client.close()
+ })
+})
diff --git a/cli/e2e/master.e2e.ts b/cli/e2e/master.e2e.ts
index 3f90d1ed2..fab098e8b 100644
--- a/cli/e2e/master.e2e.ts
+++ b/cli/e2e/master.e2e.ts
@@ -7,6 +7,7 @@ import { execFileSync } from 'node:child_process'
import { existsSync, mkdirSync, readFileSync } from 'node:fs'
import { join } from 'node:path'
import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
+import { HARNESSD_PROTOCOL } from '../src/harnessd/protocol.js'
import { LocalClient, type Frame } from './harness/client.js'
import { IsolatedDaemon, until } from './harness/daemon.js'
@@ -169,7 +170,7 @@ describe('harnessd', () => {
const statusFile = join(d.dataDir, 'harnessd-status.json')
const read = () => JSON.parse(readFileSync(statusFile, 'utf8'))
await until('the status file to say running', () => existsSync(statusFile) && read().state === 'running', 10_000)
- expect(read()).toMatchObject({ masterPid: d.pid, corePid: d.corePid(), restarts: 0, safeMode: null, protocol: 2 })
+ expect(read()).toMatchObject({ masterPid: d.pid, corePid: d.corePid(), restarts: 0, safeMode: null, protocol: HARNESSD_PROTOCOL })
const core = d.corePid()!
process.kill(core, 'SIGKILL')
await until('the status file to name the crash', () => read().restarts === 1 && read().lastExitReason === 'crashed', 10_000)
diff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.ts
index 4a3a3eb55..c1a4ac7d4 100644
--- a/cli/src/architecture.spec.ts
+++ b/cli/src/architecture.spec.ts
@@ -227,7 +227,12 @@ const SERVICE_MAY_IMPORT: Record<string, string> = {
// device, the teams and the orchestrator write a turn and hear of it, which lets the latter two run in
// processes of their own. Its lines are added here, ahead of the moves that take the teams and the
// orchestrator out of this process.
-const CORE_CLOSURE_BUDGET = 89_860
+//
+// Then at 89,443 in 402, from 89,796 in 402: the orchestrator is an experiment, in a process of its own
+// started only once it is on (services/orchestratorProcess.ts); its 640 lines leave. What stays is what any
+// experiment acts on the core through (core/experiments.ts, core/experimentQueries.ts) and what the core
+// keeps of the orchestrator (core/orchestratorLink.ts): 290 lines.
+const CORE_CLOSURE_BUDGET = 89_540
/** What is not the core's, by path: each goes to a service or its own process, in the plan's order. */
const EDGE: RegExp[] = [
@@ -305,11 +310,7 @@ const CORE_MAY_REACH: Record<string, string> = {
'lib/sessionSearch/sessionTurns.ts': 'the handoff (lib/agentHandoff.ts), in the edge host once CoreApi gives it the stopped agents, recaps and discovery it reads',
'lib/sessionSearch/transcript.ts': 'the readers of other engines\' sessions keep this helper: it moves beside them, out of search\'s folder',
'lib/sessionSearch/turns.ts': 'the handoff (lib/agentHandoff.ts), in the edge host once CoreApi gives it the stopped agents, recaps and discovery it reads',
- 'orchestrator/artifacts.ts': 'step 8: the experimental host',
- 'orchestrator/model.ts': 'step 8: the experimental host',
- 'orchestrator/prompts.ts': 'step 8: the experimental host',
- 'orchestrator/service.ts': 'step 8: the experimental host',
- 'orchestrator/wire.ts': 'step 8: the experimental host',
+ 'orchestrator/prompts.ts': 'step 8: the teams\' command line quotes with it (backendSocket.ts), until the teams leave',
'services/fleet.ts': 'step 9: the fleet, beside the dial',
'services/fleetRouter.ts': 'step 9: the fleet, beside the dial',
'services/shell.ts': 'shell setup and launch receipts, in the edge host; only the argv launch stays in the core (#893)',
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index 2fa2c6e57..65337f911 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -675,9 +675,7 @@ describe('BackendSocket outbound queue', () => {
// A full disk: reading the orchestrator's state makes its folder, and that threw out of every send,
// so a turn's end never reached a window (e2e/diskfull.e2e.ts).
const socket = relaySocket('token')
- ;(socket as unknown as { orchestratorService: { ingest(): void; stop(): void } }).orchestratorService = {
- ingest: () => { throw new Error('ENOSPC: no space left on device, mkdir') }, stop: () => {},
- }
+ socket.onFrameSent = () => { throw new Error('ENOSPC: no space left on device, mkdir') }
socket.connect()
const ws = wsMock.instances[0]
ws.open()
@@ -686,55 +684,6 @@ describe('BackendSocket outbound queue', () => {
await socket.stop()
})
- it('answers a turn end "no role" without building the orchestrator on a machine that has no project', async () => {
- // Asked at every turn's end. Building the service makes its folder and parses every saved run on
- // the core's event loop, and from then on every frame sent is handed to it.
- const stateDir = join(process.env.ADAPTER_DATA_DIR!, 'orchestrator')
- rmSync(stateDir, { recursive: true, force: true })
- const socket = relaySocket('token')
- try {
- expect(socket.orchestratorRoleOf('agent-1')).toBeNull()
- expect(socket.orchestratorRoleOf('agent-2')).toBeNull()
- expect(existsSync(stateDir)).toBe(false)
- expect((socket as unknown as { orchestratorService: unknown }).orchestratorService).toBeNull()
- } finally { await socket.stop() }
- })
-
- it('answers a turn end from a project an earlier run of the daemon saved', async () => {
- const stateDir = join(process.env.ADAPTER_DATA_DIR!, 'orchestrator')
- rmSync(stateDir, { recursive: true, force: true })
- mkdirSync(stateDir, { recursive: true, mode: 0o700 })
- const id = 'a'.repeat(32)
- const task = { id: 'part', title: 'Part', harness: 'cad', prompt: 'Draw the part', dependsOn: [], state: 'running', attempt: 1, agentId: 'agent-worker', cwd: stateDir, summary: '', error: null, uncertain: false, artifacts: [], inputs: {} }
- writeFileSync(join(stateDir, `${id}.json`), JSON.stringify({
- version: 1, id, fingerprint: 'f', prompt: 'Build the robot', engine: 'claude', bypassPermission: false, parallelism: 3,
- root: stateDir, directorId: 'agent-director', directorWorking: false, state: 'active', error: null,
- tasks: [task], messages: [], revision: 1, createdAt: 1, updatedAt: 1,
- }), { mode: 0o600 })
- const socket = relaySocket('token')
- try {
- expect(socket.orchestratorRoleOf('agent-worker')).toEqual({ role: 'worker' })
- expect(socket.orchestratorRoleOf('agent-director')).toEqual({ role: 'director', busy: true })
- expect(socket.orchestratorRoleOf('agent-other')).toBeNull()
- } finally {
- await socket.stop()
- rmSync(stateDir, { recursive: true, force: true })
- }
- })
-
- it('leaves an orchestrator folder it cannot list to the service to report, as before', async () => {
- const stateDir = join(process.env.ADAPTER_DATA_DIR!, 'orchestrator')
- rmSync(stateDir, { recursive: true, force: true })
- writeFileSync(stateDir, 'not a folder')
- const socket = relaySocket('token')
- try {
- expect(() => socket.orchestratorRoleOf('agent-1')).toThrow()
- } finally {
- await socket.stop()
- rmSync(stateDir, { force: true })
- }
- })
-
it('signed out, seals and queues nothing for a cloud link that never opens, and still serves its windows', async () => {
const socket = relaySocket('token')
const internal = { e2ee: gatewayOf(socket).e2ee, get queue() { return upstreamOf(socket).queue } }
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index c7d339ba9..f9a850369 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -22,27 +22,21 @@ import type { AutonomousDeviceService, AutonomousDeviceFrame } from './lib/auton
import { existsSync } from 'node:fs'
import { join } from 'path'
-import { hostname, homedir } from 'os'
+import { hostname } from 'os'
import { env } from './config/env.js'
import { registry, projectDisplayName, type RegisteredSession } from './lib/registry.js'
import type { CloseAgentService } from './lib/closeAgentService.js'
-import { isHiddenBuiltin } from './dsh/builtinIds.js'
import { ENGINES, type AgentEngine } from './engines/types.js'
import { gridCliPresence } from './lib/gridBinary.js'
import { GRID_FLEET_PROTOCOL, GRID_FLEET_MAX_TIMEOUT_MS } from './lib/gridFleetProtocol.js'
import { ApiConnectionError, ApiConnections } from './lib/apiConnections.js'
import { resolveApiTarget } from './lib/apiModels.js'
import { isApiLaunch, parseGridLaunchOverride, type GridLaunchOverride } from './lib/gridLaunch.js'
-import { supportsFirstPrompt } from './lib/engineLaunch.js'
import { probeEngines } from './lib/engineProbe.js'
import { harnessDevicesRequest, type HarnessDevicesService } from './lib/harnessDevices.js'
import { engineInstallRecipe } from './lib/engineInstall.js'
import { agentFrame, type AgentDshContext, type AgentFrame } from './lib/agentFrame.js'
import { agentTokenUsage } from './lib/agentTokenUsage.js'
-import { listInstalledDsh } from './dsh/installed.js'
-import { OrchestratorService, hasSavedProjects } from './orchestrator/service.js'
-import { OrchestratorError } from './orchestrator/model.js'
-import { orchestratorRequest } from './orchestrator/wire.js'
import { TeamService } from './teams/service.js'
import { SwarmPromptScopes } from './teams/promptScope.js'
import { ChannelDirectory } from './teams/channels.js'
@@ -197,14 +191,11 @@ export class BackendSocket {
})
/** Injectable for queue-isolation tests; production uses the machine-local probe. */
engineProbeProvider: typeof probeEngines = probeEngines
- /** Entrypoint override for isolated integration fixtures; never a wire option. */
- orchestratorCommand: string | null = null
readonly ownerCommands = new OwnerCommands()
onCancelOrchestratorMessage: ((deliveryId: string) => boolean) | null = null
- orchestratorDelivery(event: SessionInputDelivery): void {
- this.orchestratorService?.delivery(event)
- }
- private orchestratorService: OrchestratorService | null = null
+ /** Every frame sent to the apps, as it is sent: the orchestrator reads its Directors' turns from them
+ * (services/orchestrator.ts, through its port). One that throws costs it that frame, never the apps. */
+ onFrameSent: ((frame: Frame) => void) | null = null
/** Isolated daemon fixtures can override these without touching installed state. */
teamStateDir = join(env.ADAPTER_DATA_DIR, 'teams')
teamCommand: string | null = null
@@ -290,45 +281,6 @@ export class BackendSocket {
try { this.teamMailbox().start(); this.teams().start() }
catch { console.warn('[teams] preserved unreadable team state; inspect Team for recovery') }
}
- /** The commander asks this for every turn that ends — see OrchestratorService.roleOf. "No role",
- * without building the service, on a machine with no saved project (see hasSavedProjects). */
- orchestratorRoleOf(agentId: string): ReturnType<OrchestratorService['roleOf']> {
- if (!this.orchestratorService && !(this.orchestratorSaved ??= hasSavedProjects(join(env.ADAPTER_DATA_DIR, 'orchestrator')))) return null
- return this.orchestration().roleOf(agentId)
- }
- private orchestratorSaved: boolean | null = null
- private orchestration(): OrchestratorService {
- return this.orchestratorService ??= new OrchestratorService({
- stateDir: join(env.ADAPTER_DATA_DIR, 'orchestrator'),
- workspaceDir: join(homedir(), 'harnesses', 'orchestrated'),
- command: this.orchestratorCommand ?? `${[baseNode(process.execPath), ...process.execArgv, process.argv[1]].map(shellQuote).join(' ')} orchestrator --port ${env.PORT} --machine ${shellQuote(this.machineId)}`,
- catalog: () => listInstalledDsh().filter(d => d.manifest.kind !== 'viewer' && !isHiddenBuiltin(d) && !!d.manifest.engine && supportsFirstPrompt(d.manifest.engine)).map(d => ({
- id: d.id, name: d.manifest.name, description: d.manifest.description ?? '', engine: d.manifest.engine!, viewer: !!d.manifest.viewer,
- })),
- supportsEngine: engine => ENGINES.includes(engine as AgentEngine) && supportsFirstPrompt(engine as AgentEngine),
- create: async input => {
- if (!this.onCreateAgent) throw new OrchestratorError('UNSUPPORTED', 'This daemon cannot create agents.')
- const available = await this.engineProbeProvider([input.engine])
- if (!available.some(e => e.engine === input.engine && e.installed)) throw new OrchestratorError('ENGINE_NOT_INSTALLED', `${input.engine} must be installed before starting this specialist.`)
- const result = await this.onCreateAgent({ ...input, grid: null, codexHome: null, agent: null, permissionMode: null })
- if (!result.ok) throw new OrchestratorError(result.error, result.detail ?? result.error)
- return { agentId: result.session.agentId }
- },
- send: (id, text, deliveryId) => {
- if (!this.onMessage || !registry.resolve(id)) throw new OrchestratorError('AGENT_UNAVAILABLE', 'The agent is not available to receive a message.')
- this.onMessage(id, text, deliveryId)
- },
- cancelDelivery: id => this.onCancelOrchestratorMessage?.(id) ?? false,
- cancel: id => this.onCancel?.(id),
- agent: id => {
- const agent = registry.resolve(id)
- if (!agent) return null
- const context = this.dshFrameProvider?.(agent)
- return { viewerUrl: context?.viewerUrl, viewerName: context?.viewerName, error: agent.launch?.state === 'failed' ? agent.launch.detail ?? agent.launch.error : null }
- },
- changed: (id, revision) => this.sendLocal({ type: 'orchestrator_changed', payload: { id, revision } }),
- })
- }
/**
* Called on `agent_retarget` — cli.ts re-execs an EXISTING agent's pane against a different grid,
* or, when `grid` is null, back onto its own login.
@@ -602,7 +554,6 @@ export class BackendSocket {
async stop(): Promise<void> {
this.closed = true
this.closeAgentService?.dispose()
- this.orchestratorService?.stop()
this.teamService?.stop()
this.teamMailboxService?.stop()
this.channelDirectory?.stop()
@@ -644,10 +595,9 @@ export class BackendSocket {
* what carries content and queues it while the link is down. */
send(frame: Frame): void {
this.monitorCompletions.observe(frame)
- // Only an already-open orchestration service observes events; ordinary sessions
- // do not create project state or incur disk work. Project payloads stay local. Its state it cannot
- // read (a full disk: reading makes its folder) must not cost every frame after it (e2e/diskfull.e2e.ts).
- try { this.orchestratorService?.ingest(frame) } catch { /* the frame goes out regardless */ }
+ // The orchestrator's state it cannot read (a full disk: reading makes its folder) must not cost every
+ // frame after it (e2e/diskfull.e2e.ts).
+ try { this.onFrameSent?.(frame) } catch { /* the frame goes out regardless */ }
if (env.LOG_FRAMES) logFrame('→', 'web', frame)
for (const [connId, sink] of this.localClients) {
if (!sink.sendFrame(frame)) void this.unregisterLocalClient(connId)
@@ -1004,15 +954,6 @@ export class BackendSocket {
return
}
- if (type === 'orchestrator') {
- if (!owner) { reply(type, requestId, { error: 'OWNER_REQUIRED' }); return }
- // Detached: a large artifact snapshot must not block cancel/status on this connection.
- void orchestratorRequest(this.orchestration(), payload)
- .then(result => reply(type, requestId, result))
- .catch(() => reply(type, requestId, { error: 'ORCHESTRATOR_FAILED' }))
- return
- }
-
// Retired optional-feature requests remain reserved. Never reinterpret one as an
// ordinary command or weaken its existing encryption / local transport boundary.
if (PAIR_REQUESTS.has(type) || type === 'pair' || type === PLATE_REQUEST) {
diff --git a/cli/src/core/AGENTS.md b/cli/src/core/AGENTS.md
index b93e1a3f0..8595ee45b 100644
--- a/cli/src/core/AGENTS.md
+++ b/cli/src/core/AGENTS.md
@@ -44,6 +44,8 @@ questions. Everything else is a service ([../services/AGENTS.md](../services/AGE
process tells the core. `modelsLink.ts`: what the core keeps of models in its process for frames and
keystrokes, and how it asks it the rest. `agentQueries.ts`: what a service in its own process may ask of the agents;
`accountQueries.ts`: of the account (a token, and the fleet's lane's sealing), so it holds no credential.
+ `experimentQueries.ts`: what an experiment acts on the core through; `experiments.ts`: which are on as the
+ core starts; `orchestratorLink.ts`: what the core keeps of the orchestrator in its own process.
`gatewayLink.ts`: the relay and its E2EE in their own process (src/gateway/), as the core sees them:
the link's state and the remote clients it reads in line, the frames it hands over in the clear, a
window's sessions to another machine or a shared harness, and the fleet's lane's sealing
diff --git a/cli/src/core/api.spec.ts b/cli/src/core/api.spec.ts
index 9a1317663..a69095504 100644
--- a/cli/src/core/api.spec.ts
+++ b/cli/src/core/api.spec.ts
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from 'vitest'
import { projectDisplayName, type RegisteredSession } from '../lib/registry.js'
-import { createCoreApi, DELIVERIES_OFF, emptyPorts, FLEET_FALLBACKS, LANE_OFF, LONG_ANSWERS, MODELS_OFF, MODELS_REQUESTS, MONITOR_OFF, resolveAgent, TEAMS_FALLBACKS, type CoreApiDeps } from './api.js'
+import { AGENT_ACTIONS_OFF, createCoreApi, DAEMON_UNKNOWN, DELIVERIES_OFF, emptyPorts, FLEET_FALLBACKS, LANE_OFF, LONG_ANSWERS, MODELS_OFF, MODELS_REQUESTS, MONITOR_OFF, ORCHESTRATOR_FALLBACKS, resolveAgent, TEAMS_FALLBACKS, type CoreApiDeps } from './api.js'
import { FAIL } from './serviceHost.js'
const row = (agentId: string) => ({ agentId, sessionId: `s-${agentId}`, engine: 'claude', cwd: '/work/app' }) as RegisteredSession
@@ -57,6 +57,10 @@ describe('the core API services stand on', () => {
runtimeProfile: vi.fn(() => null),
setRuntime: vi.fn(),
fork: vi.fn(async () => ({ ok: true as const, agentId: 'fork' })),
+ create: vi.fn(async () => ({ ok: true as const, agentId: 'made' })),
+ dsh: vi.fn(() => null),
+ windows: vi.fn(),
+ daemon: { command: 'harness', port: 18473, machineId: () => 'machine-1' },
turns: { send: vi.fn(), stop: vi.fn(), recent: vi.fn(() => []), asks: vi.fn(() => []), deliver: vi.fn(), cancelDelivery: vi.fn(() => true), onDelivery: vi.fn(() => () => {}) },
questions: { answer: vi.fn(), answerReviewed: vi.fn(async () => true) },
}
@@ -92,6 +96,11 @@ describe('the core API services stand on', () => {
expect(core.agents.runtimeProfile).toBe(deps.runtimeProfile)
expect(core.agents.setRuntime).toBe(deps.setRuntime)
expect(core.agents.fork).toBe(deps.fork)
+ // What an experiment acts on the core through.
+ expect(core.agents.create).toBe(deps.create)
+ expect(core.agents.dsh).toBe(deps.dsh)
+ expect(core.clients.windows).toBe(deps.windows)
+ expect(core.daemon).toBe(deps.daemon)
expect(core.turns).toBe(deps.turns)
expect(core.questions).toBe(deps.questions)
})
@@ -117,7 +126,7 @@ describe('the core API services stand on', () => {
})
it('starts with every port empty: a service fills its own when it starts', () => {
- expect(emptyPorts()).toEqual({ search: null, viewers: null, models: null, workspaces: null, teams: null, fleet: null, monitor: null })
+ expect(emptyPorts()).toEqual({ search: null, viewers: null, models: null, workspaces: null, teams: null, fleet: null, monitor: null, orchestrator: null })
expect(emptyPorts()).not.toBe(emptyPorts())
})
@@ -141,6 +150,17 @@ describe('the core API services stand on', () => {
expect(LONG_ANSWERS.models!.grid_fleet_run).toBeGreaterThan(30 * 60_000)
})
+ it('gives a service that acts on no agent nothing to create and no harness to read, and a daemon it was never told of', async () => {
+ expect(await AGENT_ACTIONS_OFF.create({ engine: 'claude', cwd: '/w', dsh: null, prompt: 'p', name: 'n', bypassPermission: false }))
+ .toEqual({ ok: false, error: 'SERVICE_UNAVAILABLE' })
+ expect(AGENT_ACTIONS_OFF.dsh(row('a'))).toBeNull()
+ expect(DAEMON_UNKNOWN.machineId()).toBe('')
+ })
+
+ it('answers no role and reads no frame while the orchestrator is off', () => {
+ expect(ORCHESTRATOR_FALLBACKS).toEqual({ roleOf: null, frame: undefined, stop: undefined })
+ })
+
it('answers the monitor\'s fallbacks while it is off: no readings, nothing measured to forget', async () => {
await expect(MONITOR_OFF.resources()).rejects.toThrow('the monitor service is unavailable')
expect(await MONITOR_OFF.storage([], true)).toEqual(new Map())
diff --git a/cli/src/core/api.ts b/cli/src/core/api.ts
index 3a67bc0a8..13f1aa91e 100644
--- a/cli/src/core/api.ts
+++ b/cli/src/core/api.ts
@@ -14,6 +14,7 @@ import type { RecentTurn } from '../cable/cableHost.js'
import type { CableAgent, CableMachine, CableMachineSource } from '../cable/cableSession.js'
import type { FleetEvent } from '../cable/machineFleet.js'
import type { AnswerReceipt, ReviewedAnswer } from '../cable/questionInbox.js'
+import type { AgentEngine } from '../engines/types.js'
import type { AgentDshContext } from '../lib/agentFrame.js'
import type { GridAccess } from '../lib/gridAttach.js'
import type { createHarnessResourcesReader } from '../lib/harnessResources.js'
@@ -79,6 +80,11 @@ export interface CoreApi {
setRuntime(agentId: string, model?: string, effort?: string): void
/** Fork a live agent, as the window's `agent_fork` does: the new agent's id, or the refusal. */
fork(agentId: string): Promise<{ ok: true; agentId: string } | { ok: false; error: string; detail?: string }>
+ /** Create an agent, as the window's `agent_create` does with no grid, profile or model of its own: the
+ * new agent's id, or the refusal. */
+ create(request: AgentCreateRequest): Promise<{ ok: true; agentId: string } | { ok: false; error: string; detail?: string }>
+ /** What a live agent's frame says about its harness: its name, its viewer and its verdict; null for none. */
+ dsh(session: RegisteredSession): AgentDshContext | null
}
/** A device's or another machine's turns for an agent on this one: the doors the web and the hooks use. */
turns: {
@@ -150,9 +156,44 @@ export interface CoreApi {
/** A harness being installed or updated moved on (`dsh_install_status`): the apps show it in the
* create dialog. */
dshInstallStatus(status: Record<string, unknown>): void
+ /** A frame for every window on this computer, as an experiment tells them it changed
+ * (`orchestrator_changed`, `team_changed`); never sent off this computer. */
+ windows(frame: { type: string; payload: Record<string, unknown> }): void
}
+ /** How an agent's shell reaches this daemon: the command that runs this harness's CLI, the port the daemon
+ * serves and the machine it serves as. An experiment writes them into the prompts of the agents it runs
+ * (`… orchestrator --port 18473 --machine …`). */
+ daemon: DaemonAddress
}
+/** An agent to create, as an experiment asks for one (the orchestrator's Director and specialists). */
+export interface AgentCreateRequest {
+ engine: AgentEngine
+ cwd: string
+ /** The harness to create it as, installed here; null for the engine alone. */
+ dsh: string | null
+ /** The message it opens with, already submitted. */
+ prompt: string
+ name: string
+ bypassPermission: boolean
+}
+
+/** See `CoreApi.daemon`. */
+export interface DaemonAddress {
+ command: string
+ port: number
+ machineId(): string
+}
+
+/** A service in its own process that acts on no agent: it creates none and reads no harness's frame. */
+export const AGENT_ACTIONS_OFF: Pick<CoreApi['agents'], 'create' | 'dsh'> = {
+ create: async () => ({ ok: false, error: 'SERVICE_UNAVAILABLE' }),
+ dsh: () => null,
+}
+
+/** Where a service that was never told runs this daemon from: the installed CLI, on no port it knows. */
+export const DAEMON_UNKNOWN: DaemonAddress = { command: 'harness', port: 0, machineId: () => '' }
+
/** What became of a delivered turn (`turns.deliver`), as the core's input says it: `queued`, written
* (`delivered`), its turn `started`, `rejected` with why, or `unknown`. `sessionId` is the agent it was
* delivered to, as the delivery named it. */
@@ -254,6 +295,43 @@ export const LONG_ANSWERS: Readonly<Record<string, Readonly<Record<string, numbe
store: { dsh_install: 30 * MINUTE, dsh_update: 30 * MINUTE },
}
+/** The orchestrator (services/orchestrator.ts): its projects, for the apps and for the agents it runs. */
+export const ORCHESTRATOR_REQUESTS = ['orchestrator'] as const
+
+/**
+ * The experiments: services that cost nothing until they are on (docs/design/2026-10-06-core-boundary-next.md,
+ * "Experimental features: move only"). Each runs in a process of its own that the master starts only once the
+ * core asks for it (harnessd/services.ts `onDemand`): when one of its `requests` arrives, or at start when its
+ * saved `state` is in the data folder (paths under it; `dir/*.ext` for a file of that kind in that folder).
+ * Off, it has no process and none of its code is loaded anywhere. Each may act on the core through the hooks
+ * an experiment has (core/experimentQueries.ts, core/deliveries.ts), and no other process may.
+ *
+ * Adding one: its service (`start<Name>(core, ports)`, returning its requests' handlers) and its process's
+ * runner (`SERVICE_RUNNERS`, src/serviceProcess.ts); its process (`SERVICE_HOSTS`, `onDemand: true`); its
+ * entry here; and its start for the core's own process (services/inline.ts `EXPERIMENT_STARTS`). Removing
+ * one is deleting those.
+ */
+export const EXPERIMENTS: Readonly<Record<string, { requests: readonly string[]; state: readonly string[] }>> = {
+ orchestrator: { requests: ORCHESTRATOR_REQUESTS, state: ['orchestrator/*.json'] },
+}
+
+/** What an agent is to the orchestrator's projects: a specialist (`worker`), or a project's Director, and
+ * whether work is still out under it. */
+export type OrchestratorRole = { role: 'worker' } | { role: 'director'; busy: boolean }
+
+/** The core's calls into the orchestrator: what an agent is to its projects, asked at every turn's end
+ * (core/turns/recaps.ts), the frames the apps are sent, which its projects read their Directors' turns
+ * from, and stopping it. */
+export interface OrchestratorPort {
+ roleOf(agentId: string): OrchestratorRole | null
+ frame(frame: Record<string, unknown>): void
+ stop(): void
+}
+
+/** What the core gets when the orchestrator fails: no agent is a specialist or a Director, so every turn's
+ * end is announced; no project hears a frame; a shutdown goes on. */
+export const ORCHESTRATOR_FALLBACKS: PortFallbacks<OrchestratorPort> = { roleOf: null, frame: undefined, stop: undefined }
+
/** The core's calls into session search: index a session at its turn boundaries, forget a purged
* conversation, the title it indexed for one being adopted, and stopping its sweeps. The apps' own
* requests (`session_search`, `session_tail`) are its `ServiceRequests`, not the core's calls. */
@@ -741,10 +819,11 @@ export interface CorePorts {
teams: TeamsPort | null
fleet: FleetPort | null
monitor: MonitorPort | null
+ orchestrator: OrchestratorPort | null
}
export function emptyPorts(): CorePorts {
- return { search: null, viewers: null, models: null, workspaces: null, teams: null, fleet: null, monitor: null }
+ return { search: null, viewers: null, models: null, workspaces: null, teams: null, fleet: null, monitor: null, orchestrator: null }
}
export interface CoreApiDeps {
@@ -766,6 +845,10 @@ export interface CoreApiDeps {
lane: CoreApi['account']['lane']
privateGridName: CoreApi['account']['privateGridName']
machineName: CoreApi['account']['machineName']
+ create: CoreApi['agents']['create']
+ dsh: CoreApi['agents']['dsh']
+ windows: CoreApi['clients']['windows']
+ daemon: DaemonAddress
runtimeProfile: CoreApi['agents']['runtimeProfile']
setRuntime: CoreApi['agents']['setRuntime']
fork: CoreApi['agents']['fork']
@@ -776,7 +859,7 @@ export interface CoreApiDeps {
export function createCoreApi({
dataDir, registry, stoppedAgents, databaseHistory, externalSessions, openSessions, syncSession, runtimeModels, viewerChanged,
gridNamed, gridModelsChanged, dshInstallStatus, mintGridName, accessToken, lane, privateGridName, machineName,
- runtimeProfile, setRuntime, fork, turns, questions, terminals = TERMINALS_OFF,
+ runtimeProfile, setRuntime, fork, create, dsh, windows, daemon, turns, questions, terminals = TERMINALS_OFF,
}: CoreApiDeps): CoreApi {
return {
dataDir,
@@ -794,12 +877,15 @@ export function createCoreApi({
runtimeProfile,
setRuntime,
fork,
+ create,
+ dsh,
},
turns,
questions,
transcripts: { databaseHistory },
external: { sessions: externalSessions, open: openSessions },
account: { mintGridName, accessToken, lane, privateGridName, machineName },
- clients: { viewerChanged, gridNamed, gridModelsChanged, dshInstallStatus },
+ clients: { viewerChanged, gridNamed, gridModelsChanged, dshInstallStatus, windows },
+ daemon,
}
}
diff --git a/cli/src/core/experimentQueries.spec.ts b/cli/src/core/experimentQueries.spec.ts
new file mode 100644
index 000000000..f9053e744
--- /dev/null
+++ b/cli/src/core/experimentQueries.spec.ts
@@ -0,0 +1,78 @@
+import { describe, expect, it, vi } from 'vitest'
+import type { RegisteredSession } from '../lib/registry.js'
+import { fakeCore } from '../testing/fakeCore.js'
+import { answerExperimentQuery, createForExperiment } from './experimentQueries.js'
+
+const agent = (agentId: string) => ({ agentId, sessionId: `s-${agentId}`, engine: 'claude', cwd: '/w' }) as RegisteredSession
+const experiments = new Set(['orchestrator'])
+
+describe('what an experiment in its own process may ask of the core', () => {
+ it('shows the live agents as the apps are shown them: name, terminal and harness', async () => {
+ const core = fakeCore({
+ agents: {
+ live: () => [agent('a1'), agent('a2')],
+ displayName: (session) => `name of ${session.agentId}`,
+ terminalAvailable: (agentId) => agentId === 'a1',
+ dsh: (session) => (session.agentId === 'a1' ? { viewerUrl: 'http://127.0.0.1:1/' } as never : null),
+ },
+ })
+ expect(await answerExperimentQuery(core, experiments, 'orchestrator', 'shown', {})).toEqual({
+ agents: [
+ { ...agent('a1'), displayName: 'name of a1', terminalAvailable: true, dshContext: { viewerUrl: 'http://127.0.0.1:1/' } },
+ { ...agent('a2'), displayName: 'name of a2', terminalAvailable: false, dshContext: null },
+ ],
+ })
+ })
+
+ it('creates an agent as asked, and refuses a request it cannot read', async () => {
+ const create = vi.fn(async () => ({ ok: true as const, agentId: 'made' }))
+ const core = fakeCore({ agents: { create } })
+ const request = { engine: 'claude', cwd: '/w', dsh: 'cad', prompt: 'Plan it', name: 'Director', bypassPermission: true }
+ expect(await answerExperimentQuery(core, experiments, 'orchestrator', 'create', request)).toEqual({ ok: true, agentId: 'made' })
+ expect(create).toHaveBeenLastCalledWith(request)
+ await answerExperimentQuery(core, experiments, 'orchestrator', 'create', { ...request, dsh: '', bypassPermission: 'yes' })
+ expect(create).toHaveBeenLastCalledWith({ ...request, dsh: null, bypassPermission: false })
+ for (const bad of [{ ...request, engine: 3 }, { ...request, cwd: '' }, { ...request, prompt: null }, { ...request, name: undefined }]) {
+ expect(await answerExperimentQuery(core, experiments, 'orchestrator', 'create', bad)).toEqual({ ok: false, error: 'INVALID_REQUEST' })
+ }
+ expect(create).toHaveBeenCalledTimes(2)
+ })
+
+ it('stops a turn, and tells the windows a change notice and nothing else', async () => {
+ const stop = vi.fn()
+ const windows = vi.fn()
+ const core = fakeCore({ turns: { stop }, clients: { windows } })
+ expect(await answerExperimentQuery(core, experiments, 'orchestrator', 'stop_turn', { agentId: 'a1' })).toEqual({})
+ expect(await answerExperimentQuery(core, experiments, 'orchestrator', 'stop_turn', {})).toEqual({})
+ expect(stop.mock.calls).toEqual([['a1']])
+ expect(await answerExperimentQuery(core, experiments, 'orchestrator', 'windows', { frame: { type: 'orchestrator_changed', payload: { id: 'p', revision: 2 } } })).toEqual({})
+ expect(windows).toHaveBeenCalledWith({ type: 'orchestrator_changed', payload: { id: 'p', revision: 2 } })
+ for (const frame of [undefined, { type: 'agents_list', payload: {} }, { type: 'orchestrator_changed' }, { type: 'orchestrator_changed', payload: 'x' }]) {
+ expect(await answerExperimentQuery(core, experiments, 'orchestrator', 'windows', { frame })).toEqual({ error: 'INVALID_FRAME' })
+ }
+ expect(windows).toHaveBeenCalledOnce()
+ })
+
+ it('says how an agent\'s shell reaches this daemon', async () => {
+ const core = fakeCore({ daemon: { command: `'node' 'cli.js'`, port: 18473, machineId: () => 'machine-7' } })
+ expect(await answerExperimentQuery(core, experiments, 'orchestrator', 'daemon', {})).toEqual({ command: `'node' 'cli.js'`, port: 18473, machineId: 'machine-7' })
+ })
+
+ it('answers none of these for a process that is not an experiment, and leaves other queries to whoever answers them', async () => {
+ const core = fakeCore()
+ expect(await answerExperimentQuery(core, experiments, 'gateway', 'create', {})).toEqual({ error: 'NOT_AN_EXPERIMENT' })
+ expect(await answerExperimentQuery(core, experiments, 'orchestrator', 'live', {})).toBeNull()
+ })
+
+ it('creates an experiment\'s agent as the window\'s agent_create does, with nothing of its own beyond what it asked', async () => {
+ const request = { engine: 'claude' as const, cwd: '/w', dsh: 'cad', prompt: 'Plan it', name: 'Director', bypassPermission: false }
+ const create = vi.fn(async () => ({ ok: true as const, session: agent('made') }))
+ expect(await createForExperiment(create as never, request)).toEqual({ ok: true, agentId: 'made' })
+ expect(create).toHaveBeenCalledWith({ ...request, grid: null, codexHome: null, agent: null, permissionMode: null })
+ create.mockResolvedValueOnce({ ok: false, error: 'ENGINE_MISSING', detail: 'not here' } as never)
+ expect(await createForExperiment(create as never, request)).toEqual({ ok: false, error: 'ENGINE_MISSING', detail: 'not here' })
+ create.mockResolvedValueOnce({ ok: false, error: 'ENGINE_MISSING' } as never)
+ expect(await createForExperiment(create as never, request)).toEqual({ ok: false, error: 'ENGINE_MISSING' })
+ expect(await createForExperiment(null, request)).toEqual({ ok: false, error: 'UNSUPPORTED', detail: 'This daemon cannot create agents.' })
+ })
+})
diff --git a/cli/src/core/experimentQueries.ts b/cli/src/core/experimentQueries.ts
new file mode 100644
index 000000000..399851dbf
--- /dev/null
+++ b/cli/src/core/experimentQueries.ts
@@ -0,0 +1,74 @@
+/**
+ * What an experiment in its own process may ask of the core (`service_query`, core/serviceLinks.ts), beside
+ * the agents (core/agentQueries.ts) and its delivered turns (core/deliveries.ts): the generic hooks an
+ * experiment acts on the core through, so that none of its own code runs in the core's process
+ * (docs/design/2026-10-06-core-boundary-next.md, step 8).
+ * - `shown`: the live agents as the apps are shown them: each with its name, whether its terminal is there,
+ * and what its frame says about its harness (its viewer);
+ * - `create`: create an agent, as the window's `agent_create` does;
+ * - `stop_turn`: stop an agent's turn;
+ * - `windows`: a change notice for every window on this computer (`orchestrator_changed`);
+ * - `daemon`: how an agent's shell reaches this daemon, for the prompts the experiment writes.
+ * The core answers them only for the experiments (core/api.ts `EXPERIMENTS`): creating an agent or
+ * telling the windows something is no other process's to ask. The process's side is
+ * services/processCoreApi.ts.
+ */
+import type { BackendSocket } from '../backendSocket.js'
+import type { AgentCreateRequest, CoreApi } from './api.js'
+
+type Payload = Record<string, unknown>
+type Core = Pick<CoreApi, 'agents' | 'turns' | 'clients' | 'daemon'>
+
+const QUERIES: ReadonlySet<string> = new Set(['shown', 'create', 'stop_turn', 'windows', 'daemon'])
+const text = (value: unknown): string => (typeof value === 'string' ? value : '')
+
+/** The answer to an experiment's query, or null when it is not one of these. */
+export async function answerExperimentQuery(core: Core, experiments: ReadonlySet<string>, service: string, query: string, payload: Payload): Promise<Payload | null> {
+ if (!QUERIES.has(query)) return null
+ if (!experiments.has(service)) return { error: 'NOT_AN_EXPERIMENT' }
+ switch (query) {
+ case 'shown':
+ return {
+ agents: core.agents.live().map((session) => ({
+ ...session,
+ displayName: core.agents.displayName(session),
+ terminalAvailable: core.agents.terminalAvailable(session.agentId),
+ dshContext: core.agents.dsh(session),
+ })),
+ }
+ case 'create': {
+ if (!text(payload.engine) || !text(payload.cwd) || typeof payload.prompt !== 'string' || typeof payload.name !== 'string') return { ok: false, error: 'INVALID_REQUEST' }
+ const request: AgentCreateRequest = {
+ engine: payload.engine as AgentCreateRequest['engine'],
+ cwd: text(payload.cwd),
+ dsh: text(payload.dsh) || null,
+ prompt: payload.prompt,
+ name: payload.name,
+ bypassPermission: payload.bypassPermission === true,
+ }
+ return { ...await core.agents.create(request) }
+ }
+ case 'stop_turn':
+ if (text(payload.agentId)) core.turns.stop(text(payload.agentId))
+ return {}
+ case 'windows': {
+ const frame = payload.frame as Payload | undefined
+ // A change notice and nothing else: what the windows hear from the core itself is the core's to say.
+ if (!frame || !/^[a-z]+_changed$/.test(text(frame.type)) || !frame.payload || typeof frame.payload !== 'object') return { error: 'INVALID_FRAME' }
+ core.clients.windows({ type: text(frame.type), payload: frame.payload as Payload })
+ return {}
+ }
+ default:
+ return { command: core.daemon.command, port: core.daemon.port, machineId: core.daemon.machineId() }
+ }
+}
+
+/**
+ * `core.agents.create`: the window's `agent_create` (the socket's `onCreateAgent`) with no grid, Codex profile,
+ * named agent or permission mode of the agent's own, as the socket created the orchestrator's agents for it.
+ */
+export async function createForExperiment(create: BackendSocket['onCreateAgent'], request: AgentCreateRequest): ReturnType<CoreApi['agents']['create']> {
+ if (!create) return { ok: false, error: 'UNSUPPORTED', detail: 'This daemon cannot create agents.' }
+ const result = await create({ ...request, grid: null, codexHome: null, agent: null, permissionMode: null })
+ return result.ok ? { ok: true, agentId: result.session.agentId } : { ok: false, error: result.error, ...(result.detail ? { detail: result.detail } : {}) }
+}
diff --git a/cli/src/core/experiments.spec.ts b/cli/src/core/experiments.spec.ts
new file mode 100644
index 000000000..46db330ec
--- /dev/null
+++ b/cli/src/core/experiments.spec.ts
@@ -0,0 +1,41 @@
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { stateIsThere, wakeExperiments } from './experiments.js'
+
+describe('the experiments on as the core starts', () => {
+ let dataDir: string
+ beforeEach(() => { dataDir = mkdtempSync(join(tmpdir(), 'experiments-')) })
+ afterEach(() => rmSync(dataDir, { recursive: true, force: true }))
+
+ it('finds saved state by path, or by a file of its kind in its folder', () => {
+ expect(stateIsThere(dataDir, ['teams'])).toBe(false)
+ expect(stateIsThere(dataDir, ['orchestrator/*.json'])).toBe(false)
+ mkdirSync(join(dataDir, 'orchestrator'))
+ // A folder made by a look, with no project in it, is not a project.
+ writeFileSync(join(dataDir, 'orchestrator', 'notes.txt'), '')
+ expect(stateIsThere(dataDir, ['orchestrator/*.json'])).toBe(false)
+ writeFileSync(join(dataDir, 'orchestrator', `${'a'.repeat(32)}.json`), '{}')
+ expect(stateIsThere(dataDir, ['orchestrator/*.json'])).toBe(true)
+ mkdirSync(join(dataDir, 'teams'))
+ expect(stateIsThere(dataDir, ['nothing', 'teams'])).toBe(true)
+ expect(stateIsThere(dataDir, [])).toBe(false)
+ })
+
+ it('asks for each experiment in its own process that has saved state, and for no other', () => {
+ mkdirSync(join(dataDir, 'orchestrator'))
+ writeFileSync(join(dataDir, 'orchestrator', 'p.json'), '{}')
+ writeFileSync(join(dataDir, 'harness-shares.json'), '[]')
+ const want = vi.fn()
+ const woken = wakeExperiments({
+ dataDir,
+ experiments: { orchestrator: { state: ['orchestrator/*.json'] }, sharing: { state: ['harness-shares.json'] }, teams: { state: ['teams'] } },
+ // Share runs in the core's process here: it is started there, not asked for.
+ outOfProcess: new Set(['orchestrator', 'teams']),
+ want,
+ })
+ expect(woken).toEqual(['orchestrator'])
+ expect(want.mock.calls).toEqual([['orchestrator']])
+ })
+})
diff --git a/cli/src/core/experiments.ts b/cli/src/core/experiments.ts
new file mode 100644
index 000000000..5dcdaa9ef
--- /dev/null
+++ b/cli/src/core/experiments.ts
@@ -0,0 +1,37 @@
+/**
+ * Which experiments are on as the core starts (core/api.ts `EXPERIMENTS`): one whose saved state is in the
+ * data folder is asked for at once, so that what it does on its own (a saved project's queued work) goes on
+ * after a restart, as it did when it ran in the core's process. One with none waits for its first request:
+ * off, it has no process. Read once, at start, and bounded: a name or a folder listing, never a file's
+ * contents.
+ */
+import { readdirSync, existsSync } from 'node:fs'
+import { join } from 'node:path'
+
+/** Whether any of `state` is in `dataDir`: a path under it, or `dir/*.ext` for a file of that kind in that folder. */
+export function stateIsThere(dataDir: string, state: readonly string[]): boolean {
+ return state.some((entry) => {
+ const star = entry.lastIndexOf('/*')
+ if (star < 0) return existsSync(join(dataDir, entry))
+ const suffix = entry.slice(star + 2)
+ try {
+ return readdirSync(join(dataDir, entry.slice(0, star))).some((name) => name.endsWith(suffix))
+ } catch {
+ return false
+ }
+ })
+}
+
+/** Ask for each experiment that runs in its own process and has saved state here. */
+export function wakeExperiments(options: {
+ dataDir: string
+ experiments: Readonly<Record<string, { state: readonly string[] }>>
+ outOfProcess: ReadonlySet<string>
+ want: (service: string) => void
+}): string[] {
+ const woken = Object.entries(options.experiments)
+ .filter(([name, experiment]) => options.outOfProcess.has(name) && stateIsThere(options.dataDir, experiment.state))
+ .map(([name]) => name)
+ for (const name of woken) options.want(name)
+ return woken
+}
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index 078beb19b..a11bf4415 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -128,7 +128,7 @@ import { createAgentUpdate } from './agents/update.js'
import { createEngineHooks, installEngineHooks } from './engines/hooks.js'
import { createCursorTaskHooks } from './engines/cursorTasks.js'
import { databaseHistory } from './transcripts/databaseHistory.js'
-import { createCoreApi, emptyPorts, FLEET_FALLBACKS, LONG_ANSWERS, MODELS_FALLBACKS, MODELS_OFF, MODELS_REQUESTS, MONITOR_FALLBACKS, MONITOR_OFF, MONITOR_REQUESTS, PROJECTS_REQUESTS, SEARCH_FALLBACKS, SEARCH_REQUESTS, STORE_REQUESTS, TEAMS_FALLBACKS, USAGE_REQUESTS, VIEWERS_FALLBACKS, WORKSPACES_FALLBACKS, type GatewayAccount, type GatewayOps, type GatewayStatus, type TeamsPort } from './api.js'
+import { createCoreApi, emptyPorts, EXPERIMENTS, FLEET_FALLBACKS, LONG_ANSWERS, MODELS_FALLBACKS, MODELS_OFF, MODELS_REQUESTS, MONITOR_FALLBACKS, MONITOR_OFF, MONITOR_REQUESTS, ORCHESTRATOR_FALLBACKS, ORCHESTRATOR_REQUESTS, PROJECTS_REQUESTS, SEARCH_FALLBACKS, SEARCH_REQUESTS, STORE_REQUESTS, TEAMS_FALLBACKS, USAGE_REQUESTS, VIEWERS_FALLBACKS, WORKSPACES_FALLBACKS, type GatewayAccount, type GatewayOps, type GatewayStatus, type TeamsPort } from './api.js'
import { createServiceHost, testFaults } from './serviceHost.js'
import { startStalls } from './stall.js'
import { createServiceLinks, type ServiceLinks } from './serviceLinks.js'
@@ -139,6 +139,10 @@ import { createStoreLink } from './storeLink.js'
import { createModelsLink } from './modelsLink.js'
import { answerAgentQuery } from './agentQueries.js'
import { createDeliveries } from './deliveries.js'
+import { wakeExperiments } from './experiments.js'
+import { answerExperimentQuery, createForExperiment } from './experimentQueries.js'
+import { createOrchestratorLink } from './orchestratorLink.js'
+import { daemonCommand } from '../lib/daemonCommand.js'
import { KNOWN_SERVICES, servicesTheMasterRuns } from '../harnessd/services.js'
import { createTeamsLink } from './teamsLink.js'
import { startFleet } from '../services/fleet.js'
@@ -627,8 +631,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {
submit: (agentId, text, deliveryId) => backendRef?.onMessage?.(agentId, text, deliveryId),
cancel: (deliveryId) => backendRef?.onCancelOrchestratorMessage?.(deliveryId) ?? false,
tell: (service, event) => { serviceLinksRef?.notify(service, { type: 'service_event', payload: { kind: 'delivery', event } }, { untilDelivered: true }) },
- // None yet: the teams and the orchestrator, which deliver turns, still run in this process.
- deliverers: new Set(),
+ // The experiments: the orchestrator's turns, and those of the experiments after it.
+ deliverers: new Set(Object.keys(EXPERIMENTS)),
})
const coreApi = createCoreApi({
terminals: createTerminalOpener({ tmuxBackend, registry, announceSession, blocksFolder: (cwd) => !!backendRef?.purgeAgentService?.blocksFolder(cwd) }),
@@ -668,6 +672,11 @@ async function runForeground(session: AuthSession | null): Promise<void> {
if (!s || !model) return
void runtimeController.setProfile(s.sessionId || agentId, `runtime-v1:${s.sessionId || agentId}:${s.engine}:${model}@${effort || 'auto'}`)
},
+ // The window's `agent_create` for an experiment's agents (core/experimentQueries.ts).
+ create: (request) => createForExperiment(backendRef?.onCreateAgent ?? null, request),
+ dsh: (session) => backendRef?.dshFrameProvider?.(session) ?? null,
+ windows: (frame) => backendRef?.sendLocal(frame),
+ daemon: { command: daemonCommand(), port: env.PORT, machineId: () => backendRef?.machineId ?? '' },
// The same path the window's `agent_fork` takes.
fork: async (agentId) => {
if (!backendRef?.onForkAgent) return { ok: false, error: 'UNSUPPORTED' }
@@ -977,7 +986,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {
teams: {
prepare: (id, text, tabId, deliveryId) => teams.prepare(id, text, tabId, deliveryId),
delivery: (event) => {
- backend.orchestratorDelivery(event)
backend.teamDelivery(event)
deliveries.settled(event)
},
@@ -1049,7 +1057,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
bySession: (sessionId) => registry.bySession(sessionId),
resolve: (id) => registry.resolve(id),
stopped: (agentId) => stoppedAgents.get(agentId),
- orchestratorRoleOf: (agentId) => backend.orchestratorRoleOf(agentId),
+ orchestratorRoleOf: (agentId) => ports.orchestrator?.roleOf(agentId) ?? null,
readLastTurn,
dataDir: env.ADAPTER_DATA_DIR,
recapForce: env.RECAP_FORCE,
@@ -1083,7 +1091,15 @@ async function runForeground(session: AuthSession | null): Promise<void> {
backend.handoffRequestProvider = createHandoffRequest({ prepare: (req) => prepareAgentHandoff(handoffDeps, req) })
// The requests each service that can run in its own process answers, as core/api.ts declares them.
- const requestsOf: Record<string, readonly string[]> = { search: SEARCH_REQUESTS, store: STORE_REQUESTS, usage: USAGE_REQUESTS, monitor: MONITOR_REQUESTS, projects: PROJECTS_REQUESTS, models: MODELS_REQUESTS }
+ const requestsOf: Record<string, readonly string[]> = {
+ search: SEARCH_REQUESTS, store: STORE_REQUESTS, usage: USAGE_REQUESTS, monitor: MONITOR_REQUESTS, projects: PROJECTS_REQUESTS, models: MODELS_REQUESTS,
+ ...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.
+ const experiments = new Set(Object.keys(EXPERIMENTS))
+ // What the core keeps of the orchestrator in its own process: each agent's role, and which frames are its
+ // Directors' (core/orchestratorLink.ts).
+ 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))
// How the core tells workspaces in their own process what to do, and answers them (core/workspacesLink.ts).
@@ -1098,7 +1114,12 @@ async function runForeground(session: AuthSession | null): Promise<void> {
token: serviceToken,
owned: Object.fromEntries([...outOfProcess].map((name) => [name, requestsOf[name] ?? []])),
waits: LONG_ANSWERS,
- answer: (service, query, payload) => deliveries.answer(service, query, payload)
+ // An experiment's process runs only once it is on: a request for one that is off asks the master for it.
+ onDemand: experiments,
+ want: (service) => coreLink.want(service),
+ answer: async (service, query, payload) => deliveries.answer(service, query, payload)
+ ?? await answerExperimentQuery(coreApi, experiments, service, query, payload)
+ ?? (service === 'orchestrator' ? orchestratorLink.answer(query, payload) : null)
?? (service === 'viewers' ? viewersLink.answer(query, payload)
: service === 'workspaces' ? workspacesLink.answer(query, payload)
: service === 'store' ? storeLink.answer(query, payload)
@@ -1135,6 +1156,11 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// Workspaces: in this process, or in the edge host (services/workspacesProcess.ts), told what to do and when.
if (outOfProcess.has('workspaces')) ports.workspaces = workspacesLink.port
else serviceHost.start('workspaces', inline!.startWorkspaces, coreApi, WORKSPACES_FALLBACKS)
+ // The orchestrator, an experiment (services/orchestrator.ts): in this process, or in its own once it is on,
+ // as the core sees it there (core/orchestratorLink.ts). It reads its Directors' turns from the frames sent.
+ if (outOfProcess.has('orchestrator')) ports.orchestrator = orchestratorLink.port
+ else serviceHost.start('orchestrator', inline!.startOrchestrator, coreApi, ORCHESTRATOR_FALLBACKS, ORCHESTRATOR_REQUESTS)
+ backend.onFrameSent = (frame) => ports.orchestrator?.frame(frame)
// The prompt scopes, behind the service host's guard (a fault there costs no message its write) or in their own process.
if (outOfProcess.has('teams')) ports.teams = backend.swarmPromptScopes = teamsLink.scopes
else serviceHost.start('teams', (_core, started) => { started.teams = backend.swarmPromptScopes }, coreApi, TEAMS_FALLBACKS)
@@ -1682,6 +1708,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {
if (coreLink.supervised) {
coreLink.bound(hookPort)
coreLink.startHeartbeat()
+ // The experiments with saved state are on: their processes are asked for now, the master heeding a
+ // bound core alone (core/experiments.ts). The others wait for their first request.
+ wakeExperiments({ dataDir: env.ADAPTER_DATA_DIR, experiments: EXPERIMENTS, outOfProcess, want: (service) => coreLink.want(service) })
} else {
try { writeFileSync(PID_FILE, String(process.pid) + '\n') } catch { /* best effort */ }
}
diff --git a/cli/src/core/orchestratorLink.spec.ts b/cli/src/core/orchestratorLink.spec.ts
new file mode 100644
index 000000000..91a03da34
--- /dev/null
+++ b/cli/src/core/orchestratorLink.spec.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it, vi } from 'vitest'
+import { createOrchestratorLink, DIRECTOR_FRAMES } from './orchestratorLink.js'
+
+describe('the orchestrator in its own process, as the core sees it', () => {
+ it('answers a role from the last report, none before the first, and keeps it while the process is down', () => {
+ const link = createOrchestratorLink(vi.fn(() => true))
+ expect(link.port.roleOf('agent-1')).toBeNull()
+ expect(link.answer('roles', { roles: { 'agent-1': { role: 'worker' }, 'agent-2': { role: 'director', busy: true } } })).toEqual({})
+ expect(link.port.roleOf('agent-1')).toEqual({ role: 'worker' })
+ expect(link.port.roleOf('agent-2')).toEqual({ role: 'director', busy: true })
+ // A new report replaces the last whole: an agent no longer in a project has no role.
+ link.answer('roles', { roles: { 'agent-2': { role: 'director', busy: false } } })
+ expect(link.port.roleOf('agent-1')).toBeNull()
+ expect(link.port.roleOf('agent-2')).toEqual({ role: 'director', busy: false })
+ expect(link.port.stop()).toBeUndefined()
+ })
+
+ it('takes no role it cannot read', () => {
+ const link = createOrchestratorLink(vi.fn(() => true))
+ link.answer('roles', { roles: { a: { role: 'director' }, b: { role: 'boss' }, c: null, d: 'worker', e: { role: 'worker' } } })
+ expect(['a', 'b', 'c', 'd', 'e'].map((id) => link.port.roleOf(id))).toEqual([null, null, null, null, { role: 'worker' }])
+ link.answer('roles', {})
+ expect(link.port.roleOf('e')).toBeNull()
+ })
+
+ it('hands its process only a Director\'s frames of the kinds a project reads', () => {
+ const notify = vi.fn((_frame: unknown) => true)
+ const link = createOrchestratorLink(notify)
+ link.answer('roles', { roles: { director: { role: 'director', busy: true }, worker: { role: 'worker' } } })
+ for (const type of DIRECTOR_FRAMES) link.port.frame({ type, agentId: 'director', payload: {} })
+ link.port.frame({ type: 'agent_updated', agentId: 'director', payload: {} })
+ link.port.frame({ type: 'text_delta', agentId: 'worker', payload: {} })
+ link.port.frame({ type: 'text_delta', agentId: 'stranger', payload: {} })
+ link.port.frame({ type: 'text_delta', payload: {} })
+ expect(notify.mock.calls.map(([frame]) => (frame as { payload: { frame: { type: string } } }).payload.frame.type)).toEqual([...DIRECTOR_FRAMES])
+ expect(notify).toHaveBeenCalledWith({ type: 'service_event', payload: { kind: 'frame', frame: { type: 'turn_started', agentId: 'director', payload: {} } } })
+ })
+
+ it('leaves every other query to whoever answers it', () => {
+ expect(createOrchestratorLink(vi.fn(() => true)).answer('live', {})).toBeNull()
+ })
+})
diff --git a/cli/src/core/orchestratorLink.ts b/cli/src/core/orchestratorLink.ts
new file mode 100644
index 000000000..bbc2ccfe7
--- /dev/null
+++ b/cli/src/core/orchestratorLink.ts
@@ -0,0 +1,54 @@
+/**
+ * The orchestrator in its own process, as the core sees it (an experiment, step 8; the process's side is
+ * services/orchestratorProcess.ts).
+ *
+ * The core asks it one thing in line: what an agent is to its projects, at every turn's end
+ * (core/turns/recaps.ts). That cannot wait on another process, so the process reports the role of every
+ * live agent that has one whenever a project changes (`roles`), and the core answers from the last report:
+ * no role before the first, as while it is off. A report holds while the process is down, since only the
+ * orchestrator changes a role, and it cannot while it is down.
+ *
+ * It reads its Directors' turns from the frames the apps are sent. Only an agent reported as a Director's,
+ * and only the four kinds it reads, go to its process, so every other frame (every agent's `text_delta`)
+ * stays in the core. Nothing is held for it while it is down: an open service in the core's process read
+ * nothing it missed either.
+ */
+import type { OrchestratorPort, OrchestratorRole } from './api.js'
+import type { ServiceFrame } from './serviceLinks.js'
+
+/** The frames a project reads its Director's turn from (orchestrator/service.ts `ingest`). */
+export const DIRECTOR_FRAMES: ReadonlySet<string> = new Set(['turn_started', 'turn_ended', 'text_delta', 'error'])
+
+const roleIn = (value: unknown): OrchestratorRole | null => {
+ const role = value as { role?: unknown; busy?: unknown } | null
+ if (role?.role === 'worker') return { role: 'worker' }
+ if (role?.role === 'director' && typeof role.busy === 'boolean') return { role: 'director', busy: role.busy }
+ return null
+}
+
+/** `notify` tells the orchestrator's process something (core/serviceLinks.ts `notify`, for `orchestrator`). */
+export function createOrchestratorLink(notify: (frame: ServiceFrame) => boolean) {
+ let roles = new Map<string, OrchestratorRole>()
+ const port: OrchestratorPort = {
+ roleOf: (agentId) => roles.get(agentId) ?? null,
+ frame: (frame) => {
+ if (typeof frame.agentId !== 'string' || roles.get(frame.agentId)?.role !== 'director' || !DIRECTOR_FRAMES.has(String(frame.type))) return
+ notify({ type: 'service_event', payload: { kind: 'frame', frame } })
+ },
+ // Its process is the master's to stop.
+ stop: () => {},
+ }
+ return {
+ port,
+ /** The orchestrator's report of every role, replacing the last (`service_query roles`); null for any other query. */
+ answer(query: string, payload: Record<string, unknown>): Record<string, unknown> | null {
+ if (query !== 'roles') return null
+ const reported = payload.roles && typeof payload.roles === 'object' ? payload.roles as Record<string, unknown> : {}
+ roles = new Map(Object.entries(reported).flatMap(([agentId, value]) => {
+ const role = roleIn(value)
+ return role ? [[agentId, role] as const] : []
+ }))
+ return {}
+ },
+ }
+}
diff --git a/cli/src/core/serviceLinks.spec.ts b/cli/src/core/serviceLinks.spec.ts
index 3ffb8b240..020080020 100644
--- a/cli/src/core/serviceLinks.spec.ts
+++ b/cli/src/core/serviceLinks.spec.ts
@@ -70,6 +70,50 @@ describe('service links', () => {
plain.closed()
})
+ it('asks for an experiment that is off, and sends the request that woke it once it connects, in order', () => {
+ const want = vi.fn()
+ const links = make({ owned: { orchestrator: ['orchestrator'] }, onDemand: new Set(['orchestrator']), want })
+ const replies: Array<Record<string, unknown>> = []
+ links.route('orchestrator', { action: 'list' }, ASKER, (result) => replies.push(result))
+ links.route('orchestrator', { action: 'catalog' }, ASKER, (result) => replies.push(result))
+ expect(want.mock.calls).toEqual([['orchestrator'], ['orchestrator']])
+ expect(replies).toEqual([])
+ const orchestrator = sink()
+ const link = links.accept('orchestrator', TOKEN, orchestrator, vi.fn())!
+ expect(orchestrator.sent).toEqual([
+ { type: 'orchestrator', payload: { action: 'list', requestId: 'route-1' }, asker: ASKER },
+ { type: 'orchestrator', payload: { action: 'catalog', requestId: 'route-2' }, asker: ASKER },
+ ])
+ link.receive({ type: 'orchestrator_result', payload: { requestId: 'route-2', projects: [] } })
+ link.receive({ type: 'orchestrator_result', payload: { requestId: 'route-1', projects: [] } })
+ expect(replies).toEqual([{ projects: [] }, { projects: [] }])
+ // Connected again later, nothing is sent twice.
+ const again = links.accept('orchestrator', TOKEN, sink(), vi.fn())!
+ expect(want).toHaveBeenCalledTimes(2)
+ // On, then down: answered at once, as any service is, and not asked for again.
+ again.closed()
+ const down = vi.fn()
+ links.route('orchestrator', { action: 'list' }, ASKER, down)
+ expect(down).toHaveBeenCalledWith({ error: 'SERVICE_UNAVAILABLE', service: 'orchestrator', retryable: true })
+ expect(want).toHaveBeenCalledTimes(2)
+ })
+
+ it('answers SERVICE_UNAVAILABLE for an experiment that does not come in time, or will not take the request', () => {
+ const links = make({ owned: { orchestrator: ['orchestrator'], search: ['session_search'] }, onDemand: new Set(['orchestrator']) })
+ const late = vi.fn()
+ links.route('orchestrator', { action: 'list' }, ASKER, late)
+ vi.advanceTimersByTime(5_000)
+ expect(late).toHaveBeenCalledWith({ error: 'SERVICE_UNAVAILABLE', service: 'orchestrator', retryable: true })
+ const refused = vi.fn()
+ links.route('orchestrator', { action: 'list' }, ASKER, refused)
+ links.accept('orchestrator', TOKEN, sink(false), vi.fn())
+ expect(refused).toHaveBeenCalledWith({ error: 'SERVICE_UNAVAILABLE', service: 'orchestrator', retryable: true })
+ // A service that is not an experiment is never waited for.
+ const search = vi.fn()
+ links.route('session_search', {}, ASKER, search)
+ expect(search).toHaveBeenCalledWith({ error: 'SERVICE_UNAVAILABLE', service: 'search', retryable: true })
+ })
+
it('waits as long as a call says it may (a pairing), and answers SERVICE_UNAVAILABLE after', async () => {
const links = make({ owned: { gateway: [] } })
links.accept('gateway', TOKEN, sink(), vi.fn())
diff --git a/cli/src/core/serviceLinks.ts b/cli/src/core/serviceLinks.ts
index dbd2e1ce8..6a5061ecf 100644
--- a/cli/src/core/serviceLinks.ts
+++ b/cli/src/core/serviceLinks.ts
@@ -55,6 +55,12 @@ export interface ServiceLinksOptions {
/** Longer waits for the answers that take longer, by service and then by type (core/api.ts
* `LONG_ANSWERS`): a grid command, grid's set-up, a harness's install. */
waits?: Readonly<Record<string, Readonly<Record<string, number>>>>
+ /** The experiments: services whose process runs only once it is on (core/api.ts `EXPERIMENTS`). A request
+ * for one that has not connected yet asks for it (`want`) and waits for it to connect, within the same
+ * time. One that has connected and is down again is answered as any service is, at once. */
+ onDemand?: ReadonlySet<string>
+ /** Ask the master for an experiment's process (harnessd/coreLink.ts `want`). */
+ want?(service: string): void
log?: (line: string) => void
newId?: () => string
setTimer?: (run: () => void, ms: number) => unknown
@@ -71,6 +77,8 @@ interface Waiting {
type: string
reply: (result: Record<string, unknown>) => void
timer: unknown
+ /** Sent once its service connects: an experiment's request that woke it. */
+ frame?: ServiceFrame
}
/** The most notifications held for one service while it is down. */
@@ -88,6 +96,8 @@ export function createServiceLinks(options: ServiceLinksOptions) {
const ownerOf = new Map<string, string>()
for (const [service, types] of Object.entries(options.owned)) for (const type of types) ownerOf.set(type, service)
const links = new Map<string, Connected>()
+ /** The services that have connected in this core's life: an experiment among them is on, not off. */
+ const seen = new Set<string>()
const waiting = new Map<string, Waiting>()
/** What a service must hear even if it is down when it is said (a purge's forgetting), delivered on
* its next connection; bounded, the oldest dropped first. */
@@ -113,16 +123,20 @@ export function createServiceLinks(options: ServiceLinksOptions) {
return waits && Object.hasOwn(waits, type) ? waits[type] : timeoutMs
}
- /** Send `type` to `service`, its answer to `reply`, whatever becomes of the service. */
+ /** Send `type` to `service`, its answer to `reply`, whatever becomes of the service. An experiment that is
+ * not connected is asked for, and the request goes once it connects: off, it costs nothing until asked. */
const ask = (service: string, type: string, payload: Record<string, unknown>, asker: Asker, reply: (result: Record<string, unknown>) => void, waitMs?: number): void => {
const link = links.get(service)
- if (!link) { reply(unavailable(service)); return }
+ const starting = !link && !!options.onDemand?.has(service) && !seen.has(service)
+ if (!link && !starting) { reply(unavailable(service)); return }
const id = newId()
- const entry: Waiting = { service, type, reply, timer: null }
+ const frame: ServiceFrame = { type, payload: { ...payload, requestId: id }, asker }
+ const entry: Waiting = { service, type, reply, timer: null, ...(starting ? { frame } : {}) }
// Cleared whenever the entry is settled, so it only ever fires for one still waiting.
entry.timer = setTimer(() => settle(id, entry, unavailable(service)), waitMs ?? waitFor(service, type))
waiting.set(id, entry)
- if (!link.sink.sendFrame({ type, payload: { ...payload, requestId: id }, asker })) settle(id, entry, unavailable(service))
+ if (starting) { options.want?.(service); return }
+ if (!link!.sink.sendFrame(frame)) settle(id, entry, unavailable(service))
}
return {
@@ -136,10 +150,18 @@ export function createServiceLinks(options: ServiceLinksOptions) {
links.get(service)?.close(4409, 'replaced by a newer connection')
const connected: Connected = { sink, close }
links.set(service, connected)
+ seen.add(service)
log(`[services] ${service} connected`)
const owed = held.get(service) ?? []
held.delete(service)
for (const frame of owed) sink.sendFrame(frame)
+ // The requests that woke an experiment, in the order they came.
+ for (const [id, entry] of waiting) {
+ if (entry.service !== service || !entry.frame) continue
+ const frame = entry.frame
+ delete entry.frame
+ if (!sink.sendFrame(frame)) settle(id, entry, unavailable(service))
+ }
options.connected?.(service)
return {
receive: (frame) => {
diff --git a/cli/src/harnessd/coreLink.spec.ts b/cli/src/harnessd/coreLink.spec.ts
index d7fd0e7af..ff3d661f0 100644
--- a/cli/src/harnessd/coreLink.spec.ts
+++ b/cli/src/harnessd/coreLink.spec.ts
@@ -94,6 +94,13 @@ describe('connectToMaster', () => {
expect(channel.sent.filter((message) => message.type === 'harnessd:heartbeat')).toHaveLength(3)
})
+ it('asks its master for an experiment\'s process, and asks nothing without one', () => {
+ const channel = new FakeChannel()
+ connectToMaster(channel, supervised).want('orchestrator')
+ connectToMaster(channel, {}).want('orchestrator')
+ expect(channel.sent).toEqual([{ type: 'harnessd:want', service: 'orchestrator' }])
+ })
+
it('says why when start-up gave way to safe mode', () => {
const channel = new FakeChannel()
connectToMaster(channel, supervised).ready('no tmux')
diff --git a/cli/src/harnessd/coreLink.ts b/cli/src/harnessd/coreLink.ts
index 210f8f2ac..9409ba937 100644
--- a/cli/src/harnessd/coreLink.ts
+++ b/cli/src/harnessd/coreLink.ts
@@ -67,6 +67,8 @@ export interface CoreLink {
/** Start-up is done and requests are served — or it gave way to safe mode, and why: the master stops
* waiting for it either way, and rolls back an update whose first core ends up in safe mode. */
ready(safeMode?: string): void
+ /** Ask the master to start the experiment's process that runs [service]: it is on (protocol 3). */
+ want(service: string): void
/** Tell the master, every `heartbeatInterval`, that this core is alive and how big it is. */
startHeartbeat(): void
/** The master is gone. A core without one stops, so nothing is left holding the port. */
@@ -123,6 +125,7 @@ export function connectToMaster(
masterPid: supervised ? channel.parentPid : null,
bound: (port) => send({ type: 'harnessd:bound', protocol: HARNESSD_PROTOCOL, port }),
ready: (safeMode) => send(safeMode === undefined ? { type: 'harnessd:ready' } : { type: 'harnessd:ready', safeMode }),
+ want: (service) => send({ type: 'harnessd:want', service }),
startHeartbeat: () => {
if (!supervised || heartbeat) return
delay = loopDelay()
diff --git a/cli/src/harnessd/master.spec.ts b/cli/src/harnessd/master.spec.ts
index b7e713c95..a835feae6 100644
--- a/cli/src/harnessd/master.spec.ts
+++ b/cli/src/harnessd/master.spec.ts
@@ -11,6 +11,7 @@ import {
import { ignoreLogWriteErrors } from '../lib/log.js'
import { folderFingerprint } from './leanBundle.js'
import { PROBE_ANSWER, RESUME_ENV, decodeResume, encodeResume, fingerprint, readMarker, writeMarker } from './reexec.js'
+import { HARNESSD_PROTOCOL } from './protocol.js'
import { DEFAULT_SUPERVISOR_OPTIONS, type ResumeState } from './supervisor.js'
describe('supervisorOptions', () => {
@@ -165,7 +166,7 @@ describe('the probe a re-executing master asks a bundle', () => {
expect(probeMaster({ env: {}, execArgv: [], version: '9.9.9' }, (line) => said.push(line))).toBe(0)
const resume: ResumeState = { restarts: 1, lastExit: 'code 75', lastExitReason: 'update', update: 'pending', claimed: true, reexecs: 1, unproven: 1 }
expect(probeMaster({ env: { [RESUME_ENV]: encodeResume(resume) }, execArgv: [], version: '9.9.9' }, (line) => said.push(line))).toBe(0)
- expect(said).toEqual([`${PROBE_ANSWER} · protocol 2 · v9.9.9`, `${PROBE_ANSWER} · protocol 2 · v9.9.9`])
+ expect(said).toEqual([`${PROBE_ANSWER} · protocol ${HARNESSD_PROTOCOL} · v9.9.9`, `${PROBE_ANSWER} · protocol ${HARNESSD_PROTOCOL} · v9.9.9`])
})
it('refuses a state it cannot read, and says so on stdout by default', () => {
diff --git a/cli/src/harnessd/master.ts b/cli/src/harnessd/master.ts
index 7b7df0dc0..929fc1cb5 100644
--- a/cli/src/harnessd/master.ts
+++ b/cli/src/harnessd/master.ts
@@ -345,6 +345,8 @@ export function runMaster(config: MasterConfig): Supervisor {
confirmUpdate: config.confirmUpdate,
bundle,
log,
+ // An experiment's process, started once the core says it is on (./services.ts `onDemand`).
+ want: (service) => services.want(service),
// The services go with the master, after the core: none is left holding the core's socket.
exit: (code) => {
stopping = true
diff --git a/cli/src/harnessd/protocol.spec.ts b/cli/src/harnessd/protocol.spec.ts
index 448f34414..4c4c654c5 100644
--- a/cli/src/harnessd/protocol.spec.ts
+++ b/cli/src/harnessd/protocol.spec.ts
@@ -12,6 +12,9 @@ describe('the spawn channel protocol', () => {
[{ type: 'harnessd:heartbeat', rssBytes: 1, heapUsedBytes: 1, loopDelayMs: '12' }, false],
[{ type: 'harnessd:heartbeat', rssBytes: '1', heapUsedBytes: 1 }, false],
[{ type: 'harnessd:heartbeat', rssBytes: 1 }, false],
+ [{ type: 'harnessd:want', service: 'orchestrator' }, true],
+ [{ type: 'harnessd:want', service: '' }, false],
+ [{ type: 'harnessd:want' }, false],
[{ type: 'harnessd:status', status: {} }, false],
[{ type: 'other' }, false],
[null, false],
diff --git a/cli/src/harnessd/protocol.ts b/cli/src/harnessd/protocol.ts
index 82ea3cb1c..d9c11d9e8 100644
--- a/cli/src/harnessd/protocol.ts
+++ b/cli/src/harnessd/protocol.ts
@@ -12,8 +12,8 @@
*/
import type { SupervisorStatus } from './supervisor.js'
-/** 2: `ready`, the event-loop delay on the heartbeat, and the exit-code contract below. */
-export const HARNESSD_PROTOCOL = 2
+/** 2: `ready`, the event-loop delay on the heartbeat, and the exit-code contract below. 3: `want`. */
+export const HARNESSD_PROTOCOL = 3
/** The command a bundle's master answers its probe on, and what it answers. */
export const PROBE_COMMAND = '__harnessd-probe'
@@ -51,6 +51,9 @@ export type CoreMessage =
/** Sent every few seconds; a core that stops sending is hung. `loopDelayMs`: the longest the event
* loop was held since the last one (protocol 2). */
| { type: 'harnessd:heartbeat'; rssBytes: number; heapUsedBytes: number; loopDelayMs?: number }
+ /** Start the experiment's process that runs this service (harnessd/services.ts `onDemand`): it is on now
+ * (protocol 3). A master from before ignores it, having started every service at once. */
+ | { type: 'harnessd:want'; service: string }
export type MasterMessage =
| { type: 'harnessd:status'; status: SupervisorStatus }
@@ -66,6 +69,8 @@ export function isCoreMessage(value: unknown): value is CoreMessage {
case 'harnessd:heartbeat':
return typeof message.rssBytes === 'number' && typeof message.heapUsedBytes === 'number'
&& (message.loopDelayMs === undefined || typeof message.loopDelayMs === 'number')
+ case 'harnessd:want':
+ return typeof message.service === 'string' && message.service.length > 0
default:
return false
}
diff --git a/cli/src/harnessd/services.spec.ts b/cli/src/harnessd/services.spec.ts
index 291f1fd76..3ac13795a 100644
--- a/cli/src/harnessd/services.spec.ts
+++ b/cli/src/harnessd/services.spec.ts
@@ -251,6 +251,42 @@ describe('ServiceSupervisor', () => {
expect(supervisor.status().map((status) => status.state)).toEqual(['stopped', 'stopped'])
})
+ it('starts an experiment\'s process only once the core asks for one of its services, and keeps it like any other', () => {
+ const experiment: ServiceSpec = { name: 'experiments', services: ['orchestrator', 'teams'], heapLimitMiB: 256, rssLimitMiB: 512, onDemand: true }
+ const supervisor = make([search, experiment])
+ supervisor.start()
+ expect(children.map((child) => child.spec.name)).toEqual(['search'])
+ expect(supervisor.status().map((status) => status.state)).toEqual(['starting', 'off'])
+ supervisor.want('search')
+ supervisor.want('nobody')
+ expect(children).toHaveLength(1)
+ supervisor.want('teams')
+ expect(latest('experiments').env.HARNESSD_SERVICE).toBe('experiments')
+ // Asked again, while it runs or after it crashed: the master's to restart, once.
+ supervisor.want('orchestrator')
+ latest('experiments').exit(1)
+ supervisor.want('teams')
+ expect(children.filter((child) => child.spec.name === 'experiments')).toHaveLength(1)
+ vi.advanceTimersByTime(1_000)
+ expect(children.filter((child) => child.spec.name === 'experiments')).toHaveLength(2)
+ expect(lines.filter((line) => line.includes('service experiments started'))).toHaveLength(2)
+ })
+
+ it('starts every experiment for a core that never asks, and stops one never started at once', () => {
+ const experiment: ServiceSpec = { name: 'orchestrator', services: ['orchestrator'], heapLimitMiB: 256, rssLimitMiB: 512, onDemand: true }
+ const idle: ServiceSpec = { ...experiment, name: 'teams', services: ['teams'] }
+ const supervisor = make([experiment])
+ supervisor.start()
+ supervisor.want(null)
+ expect(children.map((child) => child.spec.name)).toEqual(['orchestrator'])
+ const never = make([idle])
+ never.start()
+ const done = vi.fn()
+ never.stop(done)
+ expect(done).toHaveBeenCalledOnce()
+ expect(never.status()[0].state).toBe('stopped')
+ })
+
it('with no services, starting does nothing and stopping is done at once', () => {
const supervisor = make([])
supervisor.start()
@@ -315,6 +351,15 @@ describe('ServiceSupervisor', () => {
expect(serviceSpecs({ HARNESSD_SERVICES: 'usage' }, hosts)).toEqual([{ name: 'edge', ...edge, services: ['usage'] }])
})
+ it('leaves an experiment\'s process to the core\'s asking, unless it is named: then it starts with the others', () => {
+ const orchestrator = { services: ['orchestrator'], heapLimitMiB: 256, rssLimitMiB: 512, onDemand: true }
+ const hosts = { search: { services: ['search'], heapLimitMiB: 512, rssLimitMiB: 1_024 }, orchestrator }
+ expect(serviceSpecs({}, hosts)).toEqual([search, { name: 'orchestrator', ...orchestrator }])
+ expect(serviceSpecs({ HARNESSD_SERVICES: 'search,orchestrator' }, hosts))
+ .toEqual([search, { name: 'orchestrator', services: ['orchestrator'], heapLimitMiB: 256, rssLimitMiB: 512 }])
+ expect(serviceSpecs({ HARNESSD_SERVICES: 'search' }, hosts)).toEqual([search])
+ })
+
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.ts
index 2fc35e4b3..bc4436109 100644
--- a/cli/src/harnessd/services.ts
+++ b/cli/src/harnessd/services.ts
@@ -24,6 +24,9 @@ export interface ServiceSpec {
heapLimitMiB: number
/** Resident memory past which it is restarted, MiB; 0: off. */
rssLimitMiB: number
+ /** An experiment's process: 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
}
export interface ServiceSupervisorDeps {
@@ -69,7 +72,8 @@ export const DEFAULT_SERVICE_OPTIONS: ServiceSupervisorOptions = {
parkRetryMs: 1_800_000,
}
-export type ServiceState = 'starting' | 'running' | 'restarting' | 'parked' | 'stopping' | 'stopped'
+/** `off`: an experiment's process that no one has asked for yet, and so was never started. */
+export type ServiceState = 'off' | 'starting' | 'running' | 'restarting' | 'parked' | 'stopping' | 'stopped'
export type ServiceExitReason = 'crashed' | 'hung' | 'memory' | 'stopped'
export interface ServiceStatus {
@@ -89,7 +93,7 @@ const describeExit = (code: number | null, signal: NodeJS.Signals | null): strin
/** One service's process, restarted for as long as the master runs. */
class Service {
- state: ServiceState = 'starting'
+ state: ServiceState
private since: number
private child: CoreHandle | null = null
private restarts = 0
@@ -114,6 +118,7 @@ class Service {
) {
this.backoff = options.initialBackoffMs
this.since = deps.wallClock()
+ this.state = spec.onDemand ? 'off' : 'starting'
}
status(): ServiceStatus {
@@ -146,6 +151,12 @@ class Service {
this.watchHeartbeat(child)
}
+ /** Start an experiment's process the core asked for: once, while it is off. One already started is
+ * the master's to keep running, parked included. */
+ want(): void {
+ if (this.state === 'off') this.start()
+ }
+
/** SIGTERM, then SIGKILL after the grace; `done` once it is gone. A parked or waiting one is simply stopped. */
stop(done: () => void): void {
if (this.state === 'stopped') { done(); return }
@@ -272,9 +283,18 @@ export class ServiceSupervisor {
this.services = specs.map((spec) => new Service(spec, deps, options, env))
}
- /** Start every service; none waits on another, or on the core. */
+ /** Start every service but the experiments; none waits on another, or on the core. */
start(): void {
- for (const service of this.services) service.start()
+ for (const service of this.services) if (!service.spec.onDemand) service.start()
+ }
+
+ /**
+ * Start the experiment's process that hosts [service], if it is not running yet: the core asked for it
+ * (`harnessd:want`). With null, every experiment's: a core from before `want` never asks, and ran them
+ * all as it ran every other service.
+ */
+ want(service: string | null): void {
+ for (const each of this.services) if (service === null || each.spec.services.includes(service)) each.want()
}
/** Stop every service; `done` once all are gone. */
@@ -315,6 +335,10 @@ export const SERVICE_HOSTS: Readonly<Record<string, ServiceHostSpec>> = {
// The monitor parses up to 8 MB of ioreg output per Monitor poll on a Mac with a GPU, hence more
// than workspaces alone had.
edge: { services: ['workspaces', 'usage', 'monitor', 'projects'], 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.
+ orchestrator: { services: ['orchestrator'], heapLimitMiB: 256, rssLimitMiB: 512, onDemand: true },
// The prompt scopes hold a few drafts and fingerprints per agent: small, bounded state.
teams: { services: ['teams'], heapLimitMiB: 256, rssLimitMiB: 512 },
// The relay and its E2EE (gateway/gatewayProcess.ts): the backend link, every remote client's session,
@@ -388,7 +412,8 @@ export function servicesTheMasterRuns(env: NodeJS.ProcessEnv, known: readonly st
* opt-in. Each process hosts the services named of its own, and is not started for none. A process
* 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).
+ * one the same heap limit instead (tests, support). An experiment's process (`onDemand`) 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 ? null
@@ -396,6 +421,9 @@ export function serviceSpecs(env: NodeJS.ProcessEnv, hosts: Readonly<Record<stri
const heap = Number(env.HARNESSD_SERVICE_HEAP_LIMIT_MIB)
return Object.entries(hosts).flatMap(([name, host]) => {
const services = host.services.filter((service) => !named || named.has(service) || named.has(name))
- return services.length ? [{ name, ...host, services, ...(Number.isInteger(heap) && heap > 0 ? { heapLimitMiB: heap } : {}) }] : []
+ // An experiment named outright runs from the start, as every service named does (a test, support).
+ const onDemand = host.onDemand && !named ? { onDemand: true } : {}
+ const { onDemand: _given, ...rest } = host
+ return services.length ? [{ name, ...rest, services, ...onDemand, ...(Number.isInteger(heap) && heap > 0 ? { heapLimitMiB: heap } : {}) }] : []
})
}
diff --git a/cli/src/harnessd/supervisor.spec.ts b/cli/src/harnessd/supervisor.spec.ts
index 5e9e21f8c..26003588c 100644
--- a/cli/src/harnessd/supervisor.spec.ts
+++ b/cli/src/harnessd/supervisor.spec.ts
@@ -116,6 +116,23 @@ describe('Supervisor', () => {
expect(statuses).toHaveLength(3)
})
+ it('starts the experiment a bound core asks for, and every experiment for a core too old to ask', () => {
+ const wanted: Array<string | null> = []
+ make({}, { want: (service) => wanted.push(service) }).start()
+ core().say({ type: 'harnessd:want', service: 'orchestrator' })
+ expect(wanted).toEqual([])
+ core().bind()
+ core().say({ type: 'harnessd:want', service: 'orchestrator' })
+ expect(wanted).toEqual(['orchestrator'])
+ crash()
+ core().bind(2)
+ expect(wanted).toEqual(['orchestrator', null])
+ // A master with no services to start ignores both.
+ make().start()
+ core().bind(2)
+ core().say({ type: 'harnessd:want', service: 'orchestrator' })
+ })
+
it('ignores what is not a core message, and anything but a bind before the bind', () => {
const supervisor = make()
supervisor.start()
diff --git a/cli/src/harnessd/supervisor.ts b/cli/src/harnessd/supervisor.ts
index 8210ffd5b..f7c582c44 100644
--- a/cli/src/harnessd/supervisor.ts
+++ b/cli/src/harnessd/supervisor.ts
@@ -63,6 +63,12 @@ export interface SupervisorDeps {
* since it started. Left out, such an exit is the update failing, as it was before.
*/
bundle?(): string | null
+ /**
+ * Start the experiment's process that runs [service] (./services.ts `ServiceSupervisor.want`): the core
+ * asked for it. Null for every experiment: a core from before `want` (protocol 2 or less) never asks,
+ * and expects each service it routes to run, as every one did.
+ */
+ want?(service: string | null): void
}
/**
@@ -365,6 +371,7 @@ export class Supervisor {
this.clearTimer('bindTimer')
if (!this.claimed) { this.deps.claimPidFile(); this.claimed = true }
this.deps.log(`[harnessd] core bound (pid ${core.pid ?? '?'}, protocol ${message.protocol})`)
+ if (message.protocol < 3) this.deps.want?.(null)
this.watchHeartbeat()
// A core from before `ready` is running once bound, and its update is judged from there.
const readiness = message.protocol >= 2
@@ -398,6 +405,9 @@ export class Supervisor {
this.setState('running')
this.up()
return
+ case 'harnessd:want':
+ if (this.bound) this.deps.want?.(message.service)
+ return
case 'harnessd:heartbeat': {
if (!this.bound) return
this.watchHeartbeat()
diff --git a/cli/src/lib/apiConnectionsRpc.spec.ts b/cli/src/lib/apiConnectionsRpc.spec.ts
index b2bdef9ba..dae48e0a5 100644
--- a/cli/src/lib/apiConnectionsRpc.spec.ts
+++ b/cli/src/lib/apiConnectionsRpc.spec.ts
@@ -82,20 +82,28 @@ describe('API connection RPC', () => {
})
it('requires a sealed owner web session for remote orchestration', async () => {
- const socket = relaySocket('fixture'), internals = socket as any
+ const socket = relaySocket('fixture')
const list = vi.fn().mockReturnValue([])
- const service = vi.spyOn(internals, 'orchestration').mockReturnValue({ list })
+ // The orchestrator is a service the socket routes to (services/orchestrator.ts): it answers an owner alone.
+ const askers: Array<{ local: boolean; owner: boolean }> = []
+ socket.serviceRouter = (type, _payload, asker, reply) => {
+ if (type !== 'orchestrator') return false
+ askers.push(asker)
+ reply(asker.owner ? { projects: list() } : { error: 'OWNER_REQUIRED' })
+ return true
+ }
vi.spyOn(gatewayOf(socket).e2ee, 'hasSession').mockReturnValue(true)
const role = vi.spyOn(gatewayOf(socket).e2ee, 'sessionRole').mockReturnValue('web')
const clear = { type: 'orchestrator', payload: { requestId: 'owner', action: 'list' } }
vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown').mockReturnValue(clear)
const sealedReply = vi.spyOn(gatewayOf(socket).e2ee, 'wrapRpcReply').mockReturnValue({ type: 'orchestrator_result', payload: { __e2e: 'sealed' } })
await dispatchDown(socket, clear, 'remote')
- expect(service).not.toHaveBeenCalled()
+ expect(askers).toEqual([])
const sealed = { type: 'orchestrator', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'fixture' } } }
role.mockReturnValue('device')
await dispatchDown(socket, sealed, 'remote')
- expect(service).not.toHaveBeenCalled()
+ expect(askers).toMatchObject([{ local: false, owner: false }])
+ expect(list).not.toHaveBeenCalled()
role.mockReturnValue('web')
await dispatchDown(socket, sealed, 'remote')
await vi.waitFor(() => expect(list).toHaveBeenCalledOnce())
diff --git a/cli/src/lib/daemonCommand.spec.ts b/cli/src/lib/daemonCommand.spec.ts
new file mode 100644
index 000000000..a478f13c6
--- /dev/null
+++ b/cli/src/lib/daemonCommand.spec.ts
@@ -0,0 +1,10 @@
+import { describe, expect, it } from 'vitest'
+import { daemonCommand } from './daemonCommand.js'
+
+describe('the command an agent\'s shell runs this harness\'s CLI with', () => {
+ it('is this process\'s Node, its flags and its script, each quoted for a shell', () => {
+ expect(daemonCommand('/usr/local/bin/node', ['--import', 'tsx'], "/Users/o'neil/cli.js"))
+ .toBe(`'/usr/local/bin/node' '--import' 'tsx' '/Users/o'"'"'neil/cli.js'`)
+ expect(daemonCommand()).toContain(`'${process.argv[1]}'`)
+ })
+})
diff --git a/cli/src/lib/daemonCommand.ts b/cli/src/lib/daemonCommand.ts
new file mode 100644
index 000000000..b83d19062
--- /dev/null
+++ b/cli/src/lib/daemonCommand.ts
@@ -0,0 +1,14 @@
+/**
+ * How an agent's shell runs this harness's CLI against the daemon it runs under: this process's Node (the
+ * stable path, never a versioned one an update removes: harnessd/baseNode.ts), its flags (tsx's loader, run
+ * from the sources) and its script, each quoted for a POSIX shell. The orchestrator writes it into the
+ * prompts of the agents it runs (`… orchestrator --port 18473`), as the socket did while it ran inside it.
+ * Read in the core's process, whose script is the CLI: a service's process may run the lean bundle instead.
+ */
+import { baseNode } from '../harnessd/baseNode.js'
+
+const quote = (value: string): string => `'${value.replace(/'/g, `'"'"'`)}'`
+
+export function daemonCommand(execPath = process.execPath, execArgv: readonly string[] = process.execArgv, script = process.argv[1]): string {
+ return [baseNode(execPath), ...execArgv, script].map(quote).join(' ')
+}
diff --git a/cli/src/serviceProcess.ts b/cli/src/serviceProcess.ts
index 2856a46e3..c7cba9d87 100644
--- a/cli/src/serviceProcess.ts
+++ b/cli/src/serviceProcess.ts
@@ -33,6 +33,7 @@ export const SERVICE_RUNNERS: ReadonlyMap<string, () => Promise<Runner>> = new M
['projects', async () => (await import('./services/projectsProcess.js')).runProjectsService],
['store', async () => (await import('./services/storeProcess.js')).runStoreService],
['teams', async () => (await import('./services/teamsProcess.js')).runTeamsService],
+ ['orchestrator', async () => (await import('./services/orchestratorProcess.js')).runOrchestratorService],
['gateway', async () => (await import('./gateway/gatewayProcess.js')).runGatewayService],
['models', async () => (await import('./services/modelsProcess.js')).runModelsService],
])
diff --git a/cli/src/services/AGENTS.md b/cli/src/services/AGENTS.md
index be0061b5d..dd8b6de39 100644
--- a/cli/src/services/AGENTS.md
+++ b/cli/src/services/AGENTS.md
@@ -112,7 +112,7 @@ way back).
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`
asks the core over its link, in order, and hears only its own deliveries; the core lets a process deliver
- only when `core/main.ts` names it a deliverer.
+ only when it is an experiment (below).
- State built from every change must get every change exactly once. The teams show how
(`src/services/teamsProcess.ts`, `src/core/teamsLink.ts`): the core numbers each change and keeps it
until the process acknowledges it; on each connection the process says what it applied and gets
@@ -120,6 +120,31 @@ way back).
process last reported, and is "unknown" (the fallback) while a change to it is on its way.
`e2e/teamsProcess.e2e.ts` proves it.
+## Experiments
+
+An experiment (the orchestrator; Tab collaboration and Share next) is a service that costs nothing until it is
+on: its own process, which the master starts only when the core asks for it (`want`), when one of its
+requests arrives or, as the core starts, when its saved state is in the data folder. Off, nothing of it runs or
+is loaded anywhere; one failing costs its own process and nothing else. `e2e/experiments.e2e.ts` proves it:
+off, on by request, on by saved state, killed, hung and crashing on every start.
+
+To add one:
+
+1. Its service, `start<Name>(core, ports)` in `src/services/<name>.ts`, returning its requests' handlers, and
+ its process's runner (`src/services/<name>Process.ts`, `run<Name>Service`; copy
+ `src/services/orchestratorProcess.ts`). Its `CoreApi` in its process is `processCoreApi` with `ask`, which
+ gives it what an experiment acts on the core through (`src/core/experimentQueries.ts`): the agents as the
+ apps are shown them, creating an agent, stopping a turn, delivering turns (`services/turnsLink.ts`), a
+ change notice for the windows (`<name>_changed`) and how an agent's shell reaches this daemon.
+2. Its entry in `EXPERIMENTS` (`src/core/api.ts`): its requests and its saved state.
+3. Its process in `SERVICE_HOSTS` (`src/harnessd/services.ts`) with `onDemand: true`, and its runner in
+ `SERVICE_RUNNERS` (`src/serviceProcess.ts`).
+4. Its start for the core's own process, in `services/inline.ts`, and one line in `core/main.ts` that starts
+ it there when `HARNESSD_SERVICES` keeps it in (`serviceHost.serve`, or `start` with a port).
+
+Removing one is deleting those. A port the core calls in line (the orchestrator's `roleOf`) is answered
+from what the process last reported (`src/core/orchestratorLink.ts`), as the viewers' are.
+
## Do not
- Do not keep state the core needs. If the core would break without your data, it is not a service.
diff --git a/cli/src/services/inline.spec.ts b/cli/src/services/inline.spec.ts
index e5e4c3e37..9ab9c5280 100644
--- a/cli/src/services/inline.spec.ts
+++ b/cli/src/services/inline.spec.ts
@@ -3,6 +3,7 @@ import { startGateway } from '../gateway/start.js'
import * as inline from './inline.js'
import { startModels } from './models.js'
import { startMonitor } from './monitor.js'
+import { startOrchestrator } from './orchestrator.js'
import { startProjects } from './projects.js'
import { startSearch } from './search.js'
import { startStore } from './store.js'
@@ -12,6 +13,6 @@ import { startWorkspaces } from './workspaces.js'
describe('the services the core runs in its own process only when they do not run in theirs', () => {
it('are their own starts, unchanged: the same services either way', () => {
- expect({ ...inline }).toEqual({ startGateway, startModels, startMonitor, startProjects, startSearch, startStore, startUsage, startViewers, startWorkspaces })
+ expect({ ...inline }).toEqual({ startGateway, startModels, startMonitor, startOrchestrator, startProjects, startSearch, startStore, startUsage, startViewers, startWorkspaces })
})
})
diff --git a/cli/src/services/inline.ts b/cli/src/services/inline.ts
index b5de17ba3..7e2646f7c 100644
--- a/cli/src/services/inline.ts
+++ b/cli/src/services/inline.ts
@@ -15,6 +15,7 @@
export { startGateway } from '../gateway/start.js'
export { startModels } from './models.js'
export { startMonitor } from './monitor.js'
+export { startOrchestrator } from './orchestrator.js'
export { startProjects } from './projects.js'
export { startSearch } from './search.js'
export { startStore } from './store.js'
diff --git a/cli/src/services/modelsProcess.spec.ts b/cli/src/services/modelsProcess.spec.ts
index b83a079be..3a40bd731 100644
--- a/cli/src/services/modelsProcess.spec.ts
+++ b/cli/src/services/modelsProcess.spec.ts
@@ -246,6 +246,7 @@ describe('the core API models runs on in its own process', () => {
expect(await api.external.open.fresh()).toEqual(new Map())
api.clients.viewerChanged('a1')
api.clients.dshInstallStatus({})
+ api.clients.windows({ type: 'orchestrator_changed', payload: {} })
expect(ask).not.toHaveBeenCalled()
})
})
diff --git a/cli/src/services/modelsProcess.ts b/cli/src/services/modelsProcess.ts
index 707153511..a32a1a4b6 100644
--- a/cli/src/services/modelsProcess.ts
+++ b/cli/src/services/modelsProcess.ts
@@ -15,7 +15,7 @@
* it asks for (`service_query`), each time it needs it: a service keeps no credential.
*/
import type { CoreApi, ServiceRequests } from '../core/api.js'
-import { DELIVERIES_OFF, emptyPorts, LANE_OFF, TERMINALS_OFF } from '../core/api.js'
+import { AGENT_ACTIONS_OFF, DAEMON_UNKNOWN, DELIVERIES_OFF, emptyPorts, LANE_OFF, TERMINALS_OFF } from '../core/api.js'
import type { AgentGridTarget, GridGlance } from '../lib/gridAnnotation.js'
import { parseGridLaunchOverride } from '../lib/gridLaunch.js'
import { gridGlances, onGridModelsChanged } from '../lib/gridModels.js'
@@ -73,6 +73,7 @@ export function modelsCoreApi(dataDir: string, ask: (query: string, payload?: Pa
runtimeProfile: () => null,
setRuntime: () => {},
fork: async () => ({ ok: false, error: 'UNSUPPORTED' }),
+ ...AGENT_ACTIONS_OFF,
},
turns: { send: () => {}, stop: () => {}, recent: () => [], asks: () => [], ...DELIVERIES_OFF },
questions: { answer: () => {}, answerReviewed: async () => false },
@@ -108,7 +109,9 @@ export function modelsCoreApi(dataDir: string, ask: (query: string, payload?: Pa
gridNamed: (name) => told('gridNamed', { name }),
gridModelsChanged: () => told('gridModelsChanged'),
dshInstallStatus: () => {},
+ windows: () => {},
},
+ daemon: DAEMON_UNKNOWN,
}
}
diff --git a/cli/src/services/orchestrator.spec.ts b/cli/src/services/orchestrator.spec.ts
new file mode 100644
index 000000000..176e2f330
--- /dev/null
+++ b/cli/src/services/orchestrator.spec.ts
@@ -0,0 +1,178 @@
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { homedir, tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { emptyPorts, type CorePorts, type TurnDelivery } from '../core/api.js'
+import type { InstalledDsh } from '../dsh/installed.js'
+import type { RegisteredSession } from '../lib/registry.js'
+import type { OrchestratorDependencies } from '../orchestrator/service.js'
+import { fakeCore } from '../testing/fakeCore.js'
+
+/** The dependencies each service was built with: what the socket used to hand it, now the core's API. */
+const built = vi.hoisted(() => [] as OrchestratorDependencies[])
+vi.mock('../orchestrator/service.js', async (original) => {
+ const actual = await original<typeof import('../orchestrator/service.js')>()
+ return {
+ ...actual,
+ OrchestratorService: class extends actual.OrchestratorService {
+ constructor(deps: OrchestratorDependencies) { super(deps); built.push(deps) }
+ },
+ }
+})
+const { startOrchestrator, ORCHESTRATOR_REQUESTS } = await import('./orchestrator.js')
+
+const owner = { local: true, owner: true }
+const agent = (agentId: string, over: Partial<RegisteredSession> = {}) => ({ agentId, sessionId: `s-${agentId}`, engine: 'claude', cwd: '/w', ...over }) as RegisteredSession
+const harness = (id: string, manifest: Record<string, unknown>, source = 'https://example.invalid/x') =>
+ ({ id, source, manifest: { name: id, ...manifest } }) as unknown as InstalledDsh
+
+describe('the orchestrator, as a service', () => {
+ let dataDir: string
+ beforeEach(() => {
+ dataDir = mkdtempSync(join(tmpdir(), 'orchestrator-service-'))
+ built.length = 0
+ })
+ afterEach(() => rmSync(dataDir, { recursive: true, force: true }))
+
+ const start = (over: Parameters<typeof fakeCore>[0] = {}, options: Parameters<typeof startOrchestrator>[2] = {}) => {
+ const listeners: Array<(event: TurnDelivery) => void> = []
+ const stopHearing = vi.fn()
+ const core = fakeCore({
+ dataDir,
+ ...over,
+ turns: { onDelivery: vi.fn((listener: (event: TurnDelivery) => void) => { listeners.push(listener); return stopHearing }), ...over.turns },
+ })
+ const ports: CorePorts = emptyPorts()
+ const requests = startOrchestrator(core, ports, { workspaceDir: join(dataDir, 'work'), ...options })
+ return { core, ports, port: ports.orchestrator!, requests, listeners, stopHearing }
+ }
+
+ it('declares the one request it answers, and makes its projects\' workspaces under the home by default', async () => {
+ expect(ORCHESTRATOR_REQUESTS).toEqual(['orchestrator'])
+ const { requests } = start({}, { workspaceDir: undefined })
+ await requests.orchestrator({ action: 'list' }, owner)
+ expect(built[0].workspaceDir).toBe(join(homedir(), 'harnesses', 'orchestrated'))
+ })
+
+ it('answers a turn end "no role" without building itself on a machine that has no project', () => {
+ // Asked at every turn's end. Building the service makes its folder and parses every saved run, and
+ // from then on every frame sent is handed to it.
+ const { port } = start()
+ expect(port.roleOf('agent-1')).toBeNull()
+ expect(port.roleOf('agent-2')).toBeNull()
+ expect(existsSync(join(dataDir, 'orchestrator'))).toBe(false)
+ expect(built).toHaveLength(0)
+ // Not built, it reads no frame.
+ expect(port.frame({ type: 'turn_started', agentId: 'agent-1' })).toBeUndefined()
+ })
+
+ it('answers a turn end from a project an earlier run of the daemon saved', () => {
+ const stateDir = join(dataDir, 'orchestrator')
+ mkdirSync(stateDir, { recursive: true, mode: 0o700 })
+ const id = 'a'.repeat(32)
+ const task = { id: 'part', title: 'Part', harness: 'cad', prompt: 'Draw the part', dependsOn: [], state: 'running', attempt: 1, agentId: 'agent-worker', cwd: stateDir, summary: '', error: null, uncertain: false, artifacts: [], inputs: {} }
+ writeFileSync(join(stateDir, `${id}.json`), JSON.stringify({
+ version: 1, id, fingerprint: 'f', prompt: 'Build the robot', engine: 'claude', bypassPermission: false, parallelism: 3,
+ root: stateDir, directorId: 'agent-director', directorWorking: false, state: 'active', error: null,
+ tasks: [task], messages: [], revision: 1, createdAt: 1, updatedAt: 1,
+ }), { mode: 0o600 })
+ const { port } = start()
+ expect(port.roleOf('agent-worker')).toEqual({ role: 'worker' })
+ expect(port.roleOf('agent-director')).toEqual({ role: 'director', busy: true })
+ expect(port.roleOf('agent-other')).toBeNull()
+ })
+
+ it('leaves an orchestrator folder it cannot list to the service to report, as before', () => {
+ writeFileSync(join(dataDir, 'orchestrator'), 'not a folder')
+ const { port } = start()
+ expect(() => port.roleOf('agent-1')).toThrow()
+ })
+
+ it('answers an owner\'s requests, refuses anyone else\'s, and answers a request that fails outright as failed', async () => {
+ const { requests } = start()
+ expect(await requests.orchestrator({ action: 'list' }, { local: false, owner: false })).toEqual({ error: 'OWNER_REQUIRED' })
+ expect(await requests.orchestrator({ action: 'list' }, owner)).toEqual({ projects: [] })
+ const failing = start({}, { request: async () => { throw new Error('boom') } })
+ expect(await failing.requests.orchestrator({ action: 'list' }, owner)).toEqual({ error: 'ORCHESTRATOR_FAILED' })
+ })
+
+ it('once built, reads the frames and the deliveries the core says, and stops with the core', async () => {
+ const { port, requests, listeners, stopHearing } = start()
+ const event: TurnDelivery = { deliveryId: 'd1', sessionId: 'agent-1', state: 'started' }
+ // Not built: nothing to tell.
+ for (const listener of listeners) listener(event)
+ await requests.orchestrator({ action: 'list' }, owner)
+ const service = built.length
+ expect(service).toBe(1)
+ for (const listener of listeners) listener(event)
+ expect(port.frame({ type: 'turn_started', agentId: 'agent-1' })).toBeUndefined()
+ port.stop()
+ expect(stopHearing).toHaveBeenCalledOnce()
+ // Stopped before it was built: nothing to stop but the hearing.
+ const idle = start()
+ idle.port.stop()
+ expect(idle.stopHearing).toHaveBeenCalledOnce()
+ })
+
+ it('gives the service what the socket gave it, from the core\'s API', async () => {
+ const live = new Map([['agent-1', agent('agent-1', { launch: { state: 'failed', error: 'E_LAUNCH', detail: 'it would not start' } } as never)], ['agent-2', agent('agent-2', { launch: { state: 'failed', error: 'E_ONLY' } } as never)], ['agent-3', agent('agent-3')]])
+ const deliver = vi.fn()
+ const cancelDelivery = vi.fn(() => true)
+ const stop = vi.fn()
+ const windows = vi.fn()
+ const create = vi.fn(async () => ({ ok: true as const, agentId: 'made' }))
+ const probe = vi.fn(async (engines?: readonly string[]) => (engines ?? []).map((engine) => ({ engine, installed: engine === 'claude' })))
+ const { requests } = start({
+ agents: {
+ resolve: (id: string) => live.get(id),
+ dsh: (session: RegisteredSession) => (session.agentId === 'agent-3' ? { viewerUrl: 'http://127.0.0.1:9/', viewerName: 'CAD' } as never : null),
+ create,
+ },
+ turns: { deliver, cancelDelivery, stop },
+ clients: { windows },
+ daemon: { command: `'/usr/bin/node' '/app/cli.js'`, port: 18473, machineId: () => "it's" },
+ }, {
+ probe: probe as never,
+ installed: () => [
+ harness('cad', { engine: 'claude', description: 'Parts', viewer: { command: 'x' } }),
+ harness('plain', { engine: 'codex' }),
+ harness('viewer-only', { engine: 'claude', kind: 'viewer' }),
+ harness('no-engine', {}),
+ harness('hidden', { engine: 'claude' }, 'builtin:pair'),
+ ],
+ })
+ await requests.orchestrator({ action: 'list' }, owner)
+ const deps = built[0]
+ expect(deps.stateDir).toBe(join(dataDir, 'orchestrator'))
+ expect(deps.workspaceDir).toBe(join(dataDir, 'work'))
+ // The command the agents it runs reach this daemon with, its machine quoted for the shell.
+ expect(deps.command).toBe(`'/usr/bin/node' '/app/cli.js' orchestrator --port 18473 --machine 'it'"'"'s'`)
+ expect(deps.catalog()).toEqual([
+ { id: 'cad', name: 'cad', description: 'Parts', engine: 'claude', viewer: true },
+ { id: 'plain', name: 'plain', description: '', engine: 'codex', viewer: false },
+ ])
+ expect(deps.supportsEngine('claude')).toBe(true)
+ expect(deps.supportsEngine('no-such-engine')).toBe(false)
+ const request = { engine: 'claude' as const, cwd: '/w', dsh: null, prompt: 'Plan it', name: 'Director', bypassPermission: false }
+ expect(await deps.create(request)).toEqual({ agentId: 'made' })
+ expect(create).toHaveBeenCalledWith(request)
+ await expect(deps.create({ ...request, engine: 'codex' })).rejects.toMatchObject({ code: 'ENGINE_NOT_INSTALLED' })
+ create.mockResolvedValueOnce({ ok: false, error: 'CREATE_FAILED', detail: 'no room' } as never)
+ await expect(deps.create(request)).rejects.toMatchObject({ code: 'CREATE_FAILED', message: 'no room' })
+ create.mockResolvedValueOnce({ ok: false, error: 'CREATE_FAILED' } as never)
+ await expect(deps.create(request)).rejects.toMatchObject({ code: 'CREATE_FAILED', message: 'CREATE_FAILED' })
+ deps.send('agent-1', 'Go', 'm1')
+ deps.send('agent-1', 'Go again')
+ expect(deliver.mock.calls).toEqual([['agent-1', 'Go', 'm1'], ['agent-1', 'Go again', '']])
+ expect(() => deps.send('nobody', 'Go', 'm2')).toThrow('not available to receive a message')
+ expect(deps.cancelDelivery!('m1')).toBe(true)
+ deps.cancel('agent-1')
+ expect(stop).toHaveBeenCalledWith('agent-1')
+ expect(deps.agent('nobody')).toBeNull()
+ expect(deps.agent('agent-1')).toEqual({ viewerUrl: undefined, viewerName: undefined, error: 'it would not start' })
+ expect(deps.agent('agent-2')).toEqual({ viewerUrl: undefined, viewerName: undefined, error: 'E_ONLY' })
+ expect(deps.agent('agent-3')).toEqual({ viewerUrl: 'http://127.0.0.1:9/', viewerName: 'CAD', error: null })
+ deps.changed!('p1', 4)
+ expect(windows).toHaveBeenCalledWith({ type: 'orchestrator_changed', payload: { id: 'p1', revision: 4 } })
+ })
+})
diff --git a/cli/src/services/orchestrator.ts b/cli/src/services/orchestrator.ts
new file mode 100644
index 000000000..9e41e268d
--- /dev/null
+++ b/cli/src/services/orchestrator.ts
@@ -0,0 +1,98 @@
+/**
+ * The orchestrator, an experiment: a Director agent that plans a project and specialist agents that do its
+ * tasks (orchestrator/service.ts). Moved out of the socket as it was (docs/design/2026-10-06-core-boundary-next.md,
+ * step 8, "move only"): what the socket gave it, it now gets from the core's API, in this process
+ * (`HARNESSD_SERVICES=none`) or in its own (services/orchestratorProcess.ts).
+ * - The apps' and the agents' `orchestrator` requests, for an owner alone, as the socket answered them.
+ * - What an agent is to a project (`roleOf`), asked at every turn's end: "no role", without building the
+ * service, on a machine with no saved project (`hasSavedProjects`), as the socket answered it.
+ * - The frames the apps are sent, which an open service reads its Directors' turns from; one not yet built
+ * reads none, as before.
+ * - Its turns, delivered through the core (`core.turns.deliver`), and what became of each.
+ */
+import { homedir } from 'node:os'
+import { join } from 'node:path'
+import type { CoreApi, CorePorts, ServiceRequests } from '../core/api.js'
+import { isHiddenBuiltin } from '../dsh/builtinIds.js'
+import { listInstalledDsh } from '../dsh/installed.js'
+import { ENGINES, type AgentEngine } from '../engines/types.js'
+import { supportsFirstPrompt } from '../lib/engineLaunch.js'
+import { probeEngines } from '../lib/engineProbe.js'
+import { OrchestratorError } from '../orchestrator/model.js'
+import { shellQuote } from '../orchestrator/prompts.js'
+import { hasSavedProjects, OrchestratorService } from '../orchestrator/service.js'
+import { orchestratorRequest } from '../orchestrator/wire.js'
+
+/** The request the orchestrator answers, declared in core/api.ts for the core to route. */
+export { ORCHESTRATOR_REQUESTS } from '../core/api.js'
+
+export interface OrchestratorOptions {
+ /** Where its projects' workspaces are made. */
+ workspaceDir?: string
+ /** Which engines are installed here; swapped in tests for one that runs nothing. */
+ probe?: typeof probeEngines
+ /** The installed harnesses it offers its Directors. */
+ installed?: typeof listInstalledDsh
+ /** How a request is answered; swapped in tests for one that fails outright. */
+ request?: typeof orchestratorRequest
+}
+
+export function startOrchestrator(core: CoreApi, ports: CorePorts, options: OrchestratorOptions = {}): ServiceRequests {
+ const stateDir = join(core.dataDir, 'orchestrator')
+ const probe = options.probe ?? probeEngines
+ const installed = options.installed ?? listInstalledDsh
+ const request = options.request ?? orchestratorRequest
+ let service: OrchestratorService | null = null
+ let saved: boolean | null = null
+ const build = (): OrchestratorService => service ??= new OrchestratorService({
+ stateDir,
+ workspaceDir: options.workspaceDir ?? join(homedir(), 'harnesses', 'orchestrated'),
+ command: `${core.daemon.command} orchestrator --port ${core.daemon.port} --machine ${shellQuote(core.daemon.machineId())}`,
+ catalog: () => installed().filter(d => d.manifest.kind !== 'viewer' && !isHiddenBuiltin(d) && !!d.manifest.engine && supportsFirstPrompt(d.manifest.engine)).map(d => ({
+ id: d.id, name: d.manifest.name, description: d.manifest.description ?? '', engine: d.manifest.engine!, viewer: !!d.manifest.viewer,
+ })),
+ supportsEngine: engine => ENGINES.includes(engine as AgentEngine) && supportsFirstPrompt(engine as AgentEngine),
+ create: async input => {
+ const available = await probe([input.engine])
+ if (!available.some(e => e.engine === input.engine && e.installed)) throw new OrchestratorError('ENGINE_NOT_INSTALLED', `${input.engine} must be installed before starting this specialist.`)
+ const result = await core.agents.create(input)
+ if (!result.ok) throw new OrchestratorError(result.error, result.detail ?? result.error)
+ return { agentId: result.agentId }
+ },
+ send: (id, text, deliveryId) => {
+ if (!core.agents.resolve(id)) throw new OrchestratorError('AGENT_UNAVAILABLE', 'The agent is not available to receive a message.')
+ core.turns.deliver(id, text, deliveryId ?? '')
+ },
+ // In its own process the core's answer cannot wait: not taken back here, and one the core did take back
+ // is then heard rejected (`cancelled`), which the project reads as failed (`delivery` below).
+ cancelDelivery: id => core.turns.cancelDelivery(id),
+ cancel: id => core.turns.stop(id),
+ agent: id => {
+ const agent = core.agents.resolve(id)
+ if (!agent) return null
+ const context = core.agents.dsh(agent)
+ return { viewerUrl: context?.viewerUrl, viewerName: context?.viewerName, error: agent.launch?.state === 'failed' ? agent.launch.detail ?? agent.launch.error : null }
+ },
+ changed: (id, revision) => core.clients.windows({ type: 'orchestrator_changed', payload: { id, revision } }),
+ })
+ const stopHearing = core.turns.onDelivery((event) => service?.delivery(event))
+ ports.orchestrator = {
+ roleOf: (agentId) => {
+ if (!service && !(saved ??= hasSavedProjects(stateDir))) return null
+ return build().roleOf(agentId)
+ },
+ // Only an open service reads frames: ordinary sessions make no project state and no disk work.
+ frame: (frame) => service?.ingest(frame),
+ stop: () => {
+ stopHearing()
+ service?.stop()
+ },
+ }
+ return {
+ orchestrator: (payload, asker) => {
+ // A paired owner can run the machine's orchestrator; observers and device sessions cannot.
+ if (!asker.owner) return { error: 'OWNER_REQUIRED' }
+ return request(build(), payload).catch(() => ({ error: 'ORCHESTRATOR_FAILED' }))
+ },
+ }
+}
diff --git a/cli/src/services/orchestratorProcess.spec.ts b/cli/src/services/orchestratorProcess.spec.ts
new file mode 100644
index 000000000..887b2f9c6
--- /dev/null
+++ b/cli/src/services/orchestratorProcess.spec.ts
@@ -0,0 +1,149 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import type { CoreApi, CorePorts, OrchestratorPort, OrchestratorRole } from '../core/api.js'
+import type { RegisteredSession } from '../lib/registry.js'
+import { runOrchestratorService } from './orchestratorProcess.js'
+import { type CoreConnection, type ServiceProcessOptions } from './process.js'
+
+// The real default reaches a real socket: never in a test.
+vi.mock('./process.js', () => ({ runServiceProcess: vi.fn(() => ({ stop: vi.fn() })) }))
+
+const agent = (agentId: string) => ({ agentId, sessionId: `s-${agentId}`, engine: 'claude', cwd: `/work/${agentId}`, displayName: agentId }) as unknown as RegisteredSession
+const OWNER = { local: true, owner: true }
+const flush = () => new Promise((settle) => setTimeout(settle, 0))
+
+describe('the orchestrator in its own process', () => {
+ afterEach(() => vi.clearAllMocks())
+
+ const setup = (roles: Record<string, OrchestratorRole> = {}) => {
+ let options: ServiceProcessOptions | null = null
+ let api: CoreApi | null = null
+ const port = {
+ roleOf: vi.fn((agentId: string) => roles[agentId] ?? null),
+ frame: vi.fn(),
+ stop: vi.fn(),
+ } satisfies OrchestratorPort
+ const stop = vi.fn()
+ const service = runOrchestratorService({
+ dataDir: '/data', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't',
+ run: (given) => { options = given; return { stop } },
+ start: (core: CoreApi, ports: CorePorts) => {
+ api = core
+ ports.orchestrator = port
+ return { orchestrator: async (payload) => ({ asked: payload.action, agents: core.agents.live().map((session) => session.agentId), command: core.daemon.command }) }
+ },
+ })
+ return { options: options!, api: () => api!, port, service, stop }
+ }
+ /** A core that answers as told, and records what it was asked. */
+ const coreSaying = (answers: Record<string, unknown>) => {
+ const asked: Array<[string, Record<string, unknown> | undefined]> = []
+ const query = vi.fn(async (name: string, payload?: Record<string, unknown>) => {
+ asked.push([name, payload])
+ const answer = answers[name]
+ if (answer instanceof Error) throw answer
+ return (answer ?? {}) as Record<string, unknown>
+ })
+ return { query, asked }
+ }
+
+ it('answers its request on the agents the core shows as it starts, and how the daemon is run, asked once', async () => {
+ const { options } = setup()
+ expect(options).toMatchObject({ name: 'orchestrator', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't' })
+ const core = coreSaying({ shown: { agents: [agent('a1')] }, daemon: { command: `'node' 'cli.js'`, port: 18473, machineId: 'm' } })
+ options.onConnected!({ query: core.query } satisfies CoreConnection)
+ expect(await options.requests.orchestrator!({ action: 'list' }, OWNER)).toEqual({ asked: 'list', agents: ['a1'], command: `'node' 'cli.js'` })
+ await options.requests.orchestrator!({ action: 'list' }, OWNER)
+ expect(core.asked.filter(([name]) => name === 'daemon')).toHaveLength(1)
+ expect(core.asked.filter(([name]) => name === 'shown').length).toBeGreaterThanOrEqual(2)
+ })
+
+ it('starts the orchestrator again under the machine a new core serves as, its projects read again from disk', async () => {
+ const { options, port } = setup()
+ options.onConnected!({ query: coreSaying({ daemon: { command: 'x', port: 1, machineId: 'computer' } }).query })
+ await options.requests.orchestrator!({ action: 'list' }, OWNER)
+ // A new core, the same machine: the same orchestrator.
+ options.onConnected!({ query: coreSaying({ daemon: { command: 'x', port: 1, machineId: 'computer' } }).query })
+ await options.requests.orchestrator!({ action: 'list' }, OWNER)
+ expect(port.stop).not.toHaveBeenCalled()
+ // Signed in since: the account's machine.
+ options.onConnected!({ query: coreSaying({ daemon: { command: 'x', port: 1, machineId: 'account-machine' } }).query })
+ expect(await options.requests.orchestrator!({ action: 'list' }, OWNER)).toMatchObject({ asked: 'list' })
+ expect(port.stop).toHaveBeenCalledOnce()
+ })
+
+ it('keeps the agents and the daemon it knew when the core cannot say, and acts on nothing before it connects', async () => {
+ const { options, api } = setup()
+ expect(await options.requests.orchestrator!({ action: 'list' }, OWNER)).toEqual({ asked: 'list', agents: [], command: 'harness' })
+ const core = coreSaying({ shown: { agents: [agent('a1')] }, daemon: { command: 'x', port: 1, machineId: 'm' } })
+ options.onConnected!({ query: core.query })
+ await options.requests.orchestrator!({ action: 'list' }, OWNER)
+ const failing = coreSaying({ shown: new Error('gone'), daemon: new Error('gone') })
+ options.onConnected!({ query: failing.query })
+ expect(await options.requests.orchestrator!({ action: 'list' }, OWNER)).toEqual({ asked: 'list', agents: ['a1'], command: 'x' })
+ options.onDisconnected!()
+ expect(await api().agents.create({ engine: 'claude', cwd: '/w', dsh: null, prompt: 'p', name: 'n', bypassPermission: false }))
+ .toEqual({ ok: false, error: 'SERVICE_UNAVAILABLE' })
+ })
+
+ it('tells the core each live agent\'s role as it connects and whenever a project changes, once at a time', async () => {
+ const { options, api, port } = setup({ a1: { role: 'director', busy: true }, a2: { role: 'worker' } })
+ const core = coreSaying({ shown: { agents: [agent('a1'), agent('a2'), agent('a3')] } })
+ options.onConnected!({ query: core.query })
+ // Two changes while a report is on its way: one more report, not two.
+ api().clients.windows({ type: 'orchestrator_changed', payload: { id: 'p', revision: 1 } })
+ api().clients.windows({ type: 'orchestrator_changed', payload: { id: 'p', revision: 2 } })
+ await flush()
+ await flush()
+ const reports = core.asked.filter(([name]) => name === 'roles')
+ expect(reports).toHaveLength(2)
+ expect(reports[0][1]).toEqual({ roles: { a1: { role: 'director', busy: true }, a2: { role: 'worker' } } })
+ // The windows were told each change, as in the core's process.
+ expect(core.asked.filter(([name]) => name === 'windows').map(([, payload]) => payload)).toEqual([
+ { frame: { type: 'orchestrator_changed', payload: { id: 'p', revision: 1 } } },
+ { frame: { type: 'orchestrator_changed', payload: { id: 'p', revision: 2 } } },
+ ])
+ expect(port.roleOf).toHaveBeenCalledWith('a3')
+ })
+
+ it('says why when it cannot read a role, and reports again on the next change', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ try {
+ const { options, port } = setup()
+ port.roleOf.mockImplementationOnce(() => { throw new Error('not a folder') }).mockImplementationOnce(() => { throw 'odd' })
+ const core = coreSaying({ shown: { agents: [agent('a1')] }, roles: new Error('the core went away') })
+ options.onConnected!({ query: core.query })
+ await flush()
+ options.onConnected!({ query: core.query })
+ await flush()
+ options.onConnected!({ query: core.query })
+ await flush()
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('not a folder'))
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('odd'))
+ expect(core.asked.filter(([name]) => name === 'roles')).toHaveLength(1)
+ } finally {
+ warn.mockRestore()
+ }
+ })
+
+ it('hands its Directors\' frames and its deliveries\' progress to the service, and stops it with the process', async () => {
+ const { options, api, port, service, stop } = setup()
+ const heard = vi.fn()
+ api().turns.onDelivery(heard)
+ options.onEvent!({ kind: 'delivery', event: { deliveryId: 'd1', sessionId: 'a1', state: 'started' } })
+ options.onEvent!({ kind: 'frame', frame: { type: 'turn_started', agentId: 'a1' } })
+ options.onEvent!({ kind: 'frame' })
+ options.onEvent!({ kind: 'nothing' })
+ expect(heard).toHaveBeenCalledWith({ deliveryId: 'd1', sessionId: 'a1', state: 'started' })
+ expect(port.frame.mock.calls).toEqual([[{ type: 'turn_started', agentId: 'a1' }]])
+ service.stop()
+ expect(port.stop).toHaveBeenCalledOnce()
+ expect(stop).toHaveBeenCalledOnce()
+ })
+
+ it('starts the real service and runs the real process when given neither', async () => {
+ const { runServiceProcess } = await import('./process.js')
+ runOrchestratorService({ dataDir: '/data', socketPath: '/s', machineId: 'm', token: 't' })
+ expect(runServiceProcess).toHaveBeenCalledOnce()
+ expect(vi.mocked(runServiceProcess).mock.calls[0][0].requests.orchestrator).toBeTypeOf('function')
+ })
+})
diff --git a/cli/src/services/orchestratorProcess.ts b/cli/src/services/orchestratorProcess.ts
new file mode 100644
index 000000000..8d5e55f2d
--- /dev/null
+++ b/cli/src/services/orchestratorProcess.ts
@@ -0,0 +1,126 @@
+/**
+ * The orchestrator in its own process (`harness __service orchestrator`), an experiment: started only once it
+ * is on (core/api.ts `EXPERIMENTS`). The same service as in the core's process (services/orchestrator.ts),
+ * on the core's API as a process reaches it (services/processCoreApi.ts):
+ * - the agents it reads as the apps are shown them, asked of the core as each request starts, with how this
+ * daemon is run, which its prompts name, asked before its first request builds it;
+ * - its turns delivered, its agents created and stopped and the windows told, each asked of the core;
+ * - what an agent is to its projects, reported to the core whenever a project changes and each time it
+ * connects (core/orchestratorLink.ts), since the core asks it in line at every turn's end;
+ * - its Directors' frames, which the core sends it, and what became of its deliveries.
+ */
+import { emptyPorts, type DaemonAddress } from '../core/api.js'
+import { startOrchestrator } from './orchestrator.js'
+import { runServiceProcess, type CoreConnection, type ServiceProcess } from './process.js'
+import { agentsIn, daemonIn, processCoreApi, type ShownAgent } from './processCoreApi.js'
+import { turnsLink } from './turnsLink.js'
+
+type Payload = Record<string, unknown>
+
+export interface OrchestratorServiceOptions {
+ dataDir: string
+ socketPath: string
+ machineId: string
+ token: string
+ /** Swapped in tests for one that does not touch the real socket or process. */
+ run?: typeof runServiceProcess
+ /** Swapped in tests for a service that runs no engine and reads no installed harness. */
+ start?: typeof startOrchestrator
+}
+
+export function runOrchestratorService(options: OrchestratorServiceOptions): ServiceProcess {
+ let core: CoreConnection | null = null
+ let live: ShownAgent[] = []
+ let daemon: DaemonAddress | null = null
+ const ask = (query: string, payload: Payload): Promise<Payload> =>
+ core ? core.query(query, payload) : Promise.reject(new Error('not connected to the core'))
+ const deliveries = turnsLink(ask)
+ /** How this daemon is run, asked once per connection however many ask at once (a request, a report). */
+ let asking: Promise<void> | null = null
+ /** The agents as the core shows them now, and how this daemon is run: what a request reads. */
+ let askedOn: CoreConnection | null = null
+ const ready = async (): Promise<void> => {
+ live = (agentsIn(await ask('shown', {}).catch(() => null)) as ShownAgent[] | null) ?? live
+ if (daemon && askedOn === core) return
+ // A core that cannot say leaves what the last one said.
+ await (asking ??= ask('daemon', {}).then((answer) => { daemon = daemonIn(answer) ?? daemon; askedOn = core }, () => {}).finally(() => { asking = null }))
+ }
+
+ let reporting = false
+ let again = false
+ /** Tell the core what each live agent is to the projects; once at a time, once more for what changed meanwhile. */
+ const report = async (): Promise<void> => {
+ if (reporting) { again = true; return }
+ reporting = true
+ try {
+ do {
+ again = false
+ await ready()
+ const roles: Payload = {}
+ const { port } = current()
+ for (const agent of live) {
+ const role = port.roleOf(agent.agentId)
+ if (role) roles[agent.agentId] = role
+ }
+ await ask('roles', { roles }).catch(() => {})
+ } while (again)
+ } catch (error) {
+ console.warn(`[service orchestrator] could not report its agents' roles · ${error instanceof Error ? error.message : String(error)}`)
+ } finally {
+ reporting = false
+ }
+ }
+
+ const base = processCoreApi(options.dataDir, 'orchestrator', { live: () => live, ask, deliveries, daemon: () => daemon })
+ // A project that changed may have changed a role: the windows are told, and the core is told the roles.
+ const api = { ...base, clients: { ...base.clients, windows: (frame: { type: string; payload: Payload }) => { base.clients.windows(frame); void report() } } }
+ const build = () => {
+ const ports = emptyPorts()
+ const requests = (options.start ?? startOrchestrator)(api, ports)
+ return { requests, port: ports.orchestrator! }
+ }
+ let built = build()
+ /** The machine the service was first read under; null until then. */
+ let builtFor: string | null = null
+ /**
+ * The service, for the machine this daemon serves as now. One read under another machine is stopped and a
+ * new one built: a sign-in starts a new core under the account's machine, and the orchestrator it ran inside
+ * used to go with it, which this process outlives. Its projects are on disk, read again by the new one.
+ */
+ const current = () => {
+ const machine = daemon?.machineId() ?? null
+ if (machine !== null && builtFor !== null && builtFor !== machine) {
+ built.port.stop()
+ built = build()
+ }
+ if (machine !== null) builtFor = machine
+ return built
+ }
+ const service = (options.run ?? runServiceProcess)({
+ name: 'orchestrator',
+ socketPath: options.socketPath,
+ machineId: options.machineId,
+ token: options.token,
+ requests: {
+ orchestrator: async (payload, asker) => {
+ await ready()
+ return current().requests.orchestrator(payload, asker)
+ },
+ },
+ onEvent: (payload) => {
+ if (deliveries.heard(payload)) return
+ if (payload.kind === 'frame' && payload.frame && typeof payload.frame === 'object') built.port.frame(payload.frame as Payload)
+ },
+ onConnected: (connection) => {
+ core = connection
+ void report()
+ },
+ onDisconnected: () => { core = null },
+ })
+ return {
+ stop: () => {
+ built.port.stop()
+ return service.stop()
+ },
+ }
+}
diff --git a/cli/src/services/processCoreApi.spec.ts b/cli/src/services/processCoreApi.spec.ts
index d98165c82..e622a5000 100644
--- a/cli/src/services/processCoreApi.spec.ts
+++ b/cli/src/services/processCoreApi.spec.ts
@@ -1,6 +1,7 @@
-import { describe, expect, it } from 'vitest'
+import { describe, expect, it, vi } from 'vitest'
import type { RegisteredSession } from '../lib/registry.js'
-import { agentsIn, isSession, processCoreApi } from './processCoreApi.js'
+import { agentsIn, daemonIn, isSession, processCoreApi, type ShownAgent } from './processCoreApi.js'
+import { turnsLink } from './turnsLink.js'
const agent = (agentId: string, over: Partial<RegisteredSession> = {}) => ({ agentId, sessionId: `s-${agentId}`, engine: 'claude', cwd: `/work/${agentId}`, ...over }) as RegisteredSession
@@ -51,6 +52,68 @@ describe('the core API a light service runs on in its own process', () => {
api.clients.gridNamed('grid')
api.clients.gridModelsChanged()
api.clients.dshInstallStatus({ phase: 'clone' })
+ // With no way to ask the core, it acts on nothing: no agent made, no turn, no window told.
+ await expect(api.agents.create({ engine: 'claude', cwd: '/w', dsh: null, prompt: 'p', name: 'n', bypassPermission: false }))
+ .resolves.toEqual({ ok: false, error: 'SERVICE_UNAVAILABLE' })
+ expect(api.agents.dsh(agent('a1'))).toBeNull()
+ api.clients.windows({ type: 'orchestrator_changed', payload: {} })
+ api.turns.deliver('a1', 'text', 'd1')
+ expect(api.turns.cancelDelivery('d1')).toBe(false)
+ expect(api.daemon).toMatchObject({ command: 'harness', port: 0 })
+ expect(api.daemon.machineId()).toBe('')
+ })
+
+ it('acts on the core for an experiment: agents made, turns stopped and delivered, windows told, each asked', async () => {
+ const answers: Record<string, Record<string, unknown> | Error> = {
+ create: { ok: true, agentId: 'made' }, stop_turn: {}, windows: {}, deliver: {}, cancel_delivery: { cancelled: true },
+ }
+ const ask = vi.fn(async (query: string) => {
+ const answer = answers[query]
+ if (answer instanceof Error) throw answer
+ return answer
+ })
+ const shown = { ...agent('a1'), displayName: 'Planner', terminalAvailable: true, dshContext: { viewerUrl: 'http://127.0.0.1:1/', viewerName: 'CAD' } } as unknown as ShownAgent
+ const api = processCoreApi('/data', 'orchestrator', {
+ live: () => [shown, agent('a2')], ask, deliveries: turnsLink(ask),
+ daemon: () => ({ command: `'node' 'cli.js'`, port: 18473, machineId: () => 'm' }),
+ })
+ const request = { engine: 'claude' as const, cwd: '/w', dsh: null, prompt: 'p', name: 'n', bypassPermission: false }
+ expect(await api.agents.create(request)).toEqual({ ok: true, agentId: 'made' })
+ expect(ask).toHaveBeenCalledWith('create', request)
+ answers.create = { ok: false, error: 'ENGINE_NOT_INSTALLED', detail: 'not here' }
+ expect(await api.agents.create(request)).toEqual({ ok: false, error: 'ENGINE_NOT_INSTALLED', detail: 'not here' })
+ answers.create = {}
+ expect(await api.agents.create(request)).toEqual({ ok: false, error: 'CREATE_FAILED' })
+ answers.create = new Error('the link went')
+ expect(await api.agents.create(request)).toEqual({ ok: false, error: 'SERVICE_UNAVAILABLE' })
+ expect(api.agents.displayName(shown)).toBe('Planner')
+ expect(api.agents.terminalAvailable('a1')).toBe(true)
+ expect(api.agents.terminalAvailable('a2')).toBe(false)
+ expect(api.agents.dsh(shown)).toEqual({ viewerUrl: 'http://127.0.0.1:1/', viewerName: 'CAD' })
+ api.turns.stop('a1')
+ api.clients.windows({ type: 'orchestrator_changed', payload: { id: 'p' } })
+ answers.stop_turn = new Error('gone')
+ answers.windows = new Error('gone')
+ api.turns.stop('a1')
+ api.clients.windows({ type: 'orchestrator_changed', payload: { id: 'p' } })
+ api.turns.deliver('a1', 'go', 'd1')
+ await new Promise((settle) => setTimeout(settle, 0))
+ expect(ask).toHaveBeenCalledWith('stop_turn', { agentId: 'a1' })
+ expect(ask).toHaveBeenCalledWith('windows', { frame: { type: 'orchestrator_changed', payload: { id: 'p' } } })
+ expect(ask).toHaveBeenCalledWith('deliver', { agentId: 'a1', text: 'go', deliveryId: 'd1' })
+ expect(api.daemon.command).toBe(`'node' 'cli.js'`)
+ expect(api.daemon.port).toBe(18473)
+ expect(api.daemon.machineId()).toBe('m')
+ })
+
+ it('reads the daemon\'s address out of the core\'s answer, and nothing out of anything else', () => {
+ const address = daemonIn({ command: 'harness', port: 18473, machineId: 'm' })!
+ expect(address).toMatchObject({ command: 'harness', port: 18473 })
+ expect(address.machineId()).toBe('m')
+ expect(daemonIn({ command: 'harness', port: '18473', machineId: 'm' })).toBeNull()
+ expect(daemonIn({ command: 'harness', port: 18473 })).toBeNull()
+ expect(daemonIn({ error: 'NOT_AN_EXPERIMENT' })).toBeNull()
+ expect(daemonIn(null)).toBeNull()
})
it('reads the agents out of the core\'s answer, and nothing out of anything else', () => {
diff --git a/cli/src/services/processCoreApi.ts b/cli/src/services/processCoreApi.ts
index 1d48255bd..eae826987 100644
--- a/cli/src/services/processCoreApi.ts
+++ b/cli/src/services/processCoreApi.ts
@@ -6,14 +6,33 @@
*
* What these services never ask (turns, questions, sign-in, the windows) answers as nothing, and a
* credential is refused: a service holds none (services/AGENTS.md).
+ *
+ * An experiment acts on the core as well (core/experimentQueries.ts): it creates agents, stops a turn,
+ * delivers turns (services/turnsLink.ts) and tells the windows it changed, each asked of the core over its
+ * link (`ask`). The agents it reads come as the apps are shown them (`service_query shown`): each with its
+ * name, whether its terminal is there and its harness's viewer.
*/
-import { DELIVERIES_OFF, LANE_OFF, resolveAgent, TERMINALS_OFF, type CoreApi } from '../core/api.js'
+import { DAEMON_UNKNOWN, DELIVERIES_OFF, LANE_OFF, resolveAgent, TERMINALS_OFF, type CoreApi, type DaemonAddress } from '../core/api.js'
+import type { AgentDshContext } from '../lib/agentFrame.js'
import type { RegisteredSession } from '../lib/registry.js'
+import type { turnsLink } from './turnsLink.js'
+
+type Payload = Record<string, unknown>
-/** The agents a process was last told of. Those it is never told of read as none. */
+/** An agent as the core shows it to an experiment (core/experimentQueries.ts `shown`). */
+export type ShownAgent = RegisteredSession & { displayName?: string; terminalAvailable?: boolean; dshContext?: AgentDshContext | null }
+
+/** The agents a process was last told of, and how it asks the core to act. Those it is never told of read
+ * as none, and with no way to ask, it acts on nothing. */
export interface AgentsView {
- live?: () => RegisteredSession[]
+ live?: () => ShownAgent[]
advertised?: () => RegisteredSession[]
+ /** Ask the core (`CoreConnection.query`, services/process.ts), for an experiment that acts. */
+ ask?: (query: string, payload: Payload) => Promise<Payload>
+ /** The delivered turns it makes and hears of, through `ask` (services/turnsLink.ts). */
+ deliveries?: ReturnType<typeof turnsLink>
+ /** Where this daemon runs, as the core last said (`service_query daemon`). */
+ daemon?: () => DaemonAddress | null
}
/** Whether what the core sent is an agent. */
@@ -25,8 +44,17 @@ export function agentsIn(answer: Record<string, unknown> | null | undefined): Re
return Array.isArray(answer?.agents) ? answer.agents.filter(isSession) : null
}
+/** The daemon's address in a core's answer (`service_query daemon`), or null when it is not one. */
+export function daemonIn(answer: Payload | null | undefined): DaemonAddress | null {
+ if (typeof answer?.command !== 'string' || typeof answer.port !== 'number' || typeof answer.machineId !== 'string') return null
+ const machineId = answer.machineId
+ return { command: answer.command, port: answer.port, machineId: () => machineId }
+}
+
export function processCoreApi(dataDir: string, service: string, view: AgentsView = {}): CoreApi {
- const live = (): RegisteredSession[] => view.live?.() ?? []
+ const live = (): ShownAgent[] => view.live?.() ?? []
+ const ask = view.ask
+ const daemon = (): DaemonAddress => view.daemon?.() ?? DAEMON_UNKNOWN
return {
dataDir,
// Terminals are launched by the core alone (the shell service, #893): a service in its own process
@@ -36,18 +64,31 @@ export function processCoreApi(dataDir: string, service: string, view: AgentsVie
// The stopped agents are never sent to these services: none of them reads one.
all: live,
live,
- displayName: () => '',
+ displayName: (session) => (session as ShownAgent).displayName ?? '',
byAgent: (agentId) => live().find((session) => session.agentId === agentId),
resolve: (id) => resolveAgent(live(), id),
advertised: () => view.advertised?.() ?? [],
- terminalAvailable: () => false,
+ terminalAvailable: (agentId) => live().find((session) => session.agentId === agentId)?.terminalAvailable === true,
sync: () => {},
runtimeModels: async () => [],
runtimeProfile: () => null,
setRuntime: () => {},
fork: async () => ({ ok: false, error: 'UNSUPPORTED' }),
+ create: async (request) => {
+ if (!ask) return { ok: false, error: 'SERVICE_UNAVAILABLE' }
+ const answer = await ask('create', { ...request }).catch((): Payload => ({ error: 'SERVICE_UNAVAILABLE' }))
+ if (answer.ok === true && typeof answer.agentId === 'string') return { ok: true, agentId: answer.agentId }
+ return { ok: false, error: typeof answer.error === 'string' ? answer.error : 'CREATE_FAILED', ...(typeof answer.detail === 'string' ? { detail: answer.detail } : {}) }
+ },
+ dsh: (session) => (session as ShownAgent).dshContext ?? null,
+ },
+ turns: {
+ send: () => {},
+ stop: (agentId) => { void ask?.('stop_turn', { agentId }).catch(() => {}) },
+ recent: () => [],
+ asks: () => [],
+ ...(view.deliveries?.turns ?? DELIVERIES_OFF),
},
- turns: { send: () => {}, stop: () => {}, recent: () => [], asks: () => [], ...DELIVERIES_OFF },
questions: { answer: () => {}, answerReviewed: async () => false },
transcripts: { databaseHistory: () => undefined },
external: {
@@ -61,6 +102,14 @@ export function processCoreApi(dataDir: string, service: string, view: AgentsVie
privateGridName: async () => null,
machineName: () => null,
},
- clients: { viewerChanged: () => {}, gridNamed: () => {}, gridModelsChanged: () => {}, dshInstallStatus: () => {} },
+ clients: {
+ viewerChanged: () => {}, gridNamed: () => {}, gridModelsChanged: () => {}, dshInstallStatus: () => {},
+ windows: (frame) => { void ask?.('windows', { frame }).catch(() => {}) },
+ },
+ daemon: {
+ get command() { return daemon().command },
+ get port() { return daemon().port },
+ machineId: () => daemon().machineId(),
+ },
}
}
diff --git a/cli/src/services/searchProcess.spec.ts b/cli/src/services/searchProcess.spec.ts
index 278af25a1..aed1fa095 100644
--- a/cli/src/services/searchProcess.spec.ts
+++ b/cli/src/services/searchProcess.spec.ts
@@ -142,6 +142,7 @@ describe('search in its own process', () => {
api.clients.gridNamed('grid')
api.clients.gridModelsChanged()
api.clients.dshInstallStatus({ phase: 'clone' })
+ api.clients.windows({ type: 'orchestrator_changed', payload: {} })
})
it('runs as a real service process, over the conversations this machine has, by default', () => {
diff --git a/cli/src/services/searchProcess.ts b/cli/src/services/searchProcess.ts
index 84be9bc01..9e96cd8f3 100644
--- a/cli/src/services/searchProcess.ts
+++ b/cli/src/services/searchProcess.ts
@@ -8,7 +8,7 @@
* process's alone: a crash or a leak in search costs search, and the master starts it again.
*/
import type { CoreApi } from '../core/api.js'
-import { DELIVERIES_OFF, emptyPorts, LANE_OFF, resolveAgent, TERMINALS_OFF } from '../core/api.js'
+import { AGENT_ACTIONS_OFF, DAEMON_UNKNOWN, DELIVERIES_OFF, emptyPorts, LANE_OFF, resolveAgent, TERMINALS_OFF } from '../core/api.js'
import { databaseHistory } from '../core/transcripts/databaseHistory.js'
import { ExternalSessions, OpenSessions } from '../lib/sessionSearch/external.js'
import { externalProviders } from '../lib/sessionSearch/externals/index.js'
@@ -54,6 +54,7 @@ export function searchCoreApi(
runtimeProfile: () => null,
setRuntime: () => {},
fork: async () => ({ ok: false, error: 'UNSUPPORTED' }),
+ ...AGENT_ACTIONS_OFF,
},
// Search drives no agent: these are never asked of it.
turns: { send: () => {}, stop: () => {}, recent: () => [], asks: () => [], ...DELIVERIES_OFF },
@@ -71,7 +72,8 @@ export function searchCoreApi(
privateGridName: async () => null,
machineName: () => null,
},
- clients: { viewerChanged: () => {}, gridNamed: () => {}, gridModelsChanged: () => {}, dshInstallStatus: () => {} },
+ clients: { viewerChanged: () => {}, gridNamed: () => {}, gridModelsChanged: () => {}, dshInstallStatus: () => {}, windows: () => {} },
+ daemon: DAEMON_UNKNOWN,
}
}
diff --git a/cli/src/services/viewersProcess.spec.ts b/cli/src/services/viewersProcess.spec.ts
index 17242271e..eeea57566 100644
--- a/cli/src/services/viewersProcess.spec.ts
+++ b/cli/src/services/viewersProcess.spec.ts
@@ -237,6 +237,7 @@ describe('the viewers in their own process', () => {
api.clients.gridNamed('grid')
api.clients.gridModelsChanged()
api.clients.dshInstallStatus({ phase: 'clone' })
+ api.clients.windows({ type: 'orchestrator_changed', payload: {} })
})
it('runs as a real service by default: its viewers, on its own link to the core', async () => {
diff --git a/cli/src/services/viewersProcess.ts b/cli/src/services/viewersProcess.ts
index d037f9f32..50ce761cf 100644
--- a/cli/src/services/viewersProcess.ts
+++ b/cli/src/services/viewersProcess.ts
@@ -18,7 +18,7 @@
* no longer restarts every viewer: they stay up here, and the new core hears their URLs at once.
*/
import type { CoreApi } from '../core/api.js'
-import { DELIVERIES_OFF, emptyPorts, LANE_OFF, resolveAgent, TERMINALS_OFF } from '../core/api.js'
+import { AGENT_ACTIONS_OFF, DAEMON_UNKNOWN, DELIVERIES_OFF, emptyPorts, LANE_OFF, resolveAgent, TERMINALS_OFF } from '../core/api.js'
import type { RegisteredSession } from '../lib/registry.js'
import { runServiceProcess, type CoreConnection, type ServiceProcess } from './process.js'
import { startViewers } from './viewers.js'
@@ -61,6 +61,7 @@ export function viewersCoreApi(dataDir: string, sessions: ReadonlyMap<string, Re
runtimeProfile: () => null,
setRuntime: () => {},
fork: async () => ({ ok: false, error: 'UNSUPPORTED' }),
+ ...AGENT_ACTIONS_OFF,
},
// The viewers drive no agent: these are never asked of them.
turns: { send: () => {}, stop: () => {}, recent: () => [], asks: () => [], ...DELIVERIES_OFF },
@@ -77,7 +78,8 @@ export function viewersCoreApi(dataDir: string, sessions: ReadonlyMap<string, Re
privateGridName: async () => null,
machineName: () => null,
},
- clients: { viewerChanged: tell, gridNamed: () => {}, gridModelsChanged: () => {}, dshInstallStatus: () => {} },
+ clients: { viewerChanged: tell, gridNamed: () => {}, gridModelsChanged: () => {}, dshInstallStatus: () => {}, windows: () => {} },
+ daemon: DAEMON_UNKNOWN,
}
}
diff --git a/cli/src/services/workspacesProcess.spec.ts b/cli/src/services/workspacesProcess.spec.ts
index b605f07b6..19c2cc4d1 100644
--- a/cli/src/services/workspacesProcess.spec.ts
+++ b/cli/src/services/workspacesProcess.spec.ts
@@ -181,6 +181,7 @@ describe('workspaces in their own process', () => {
api.clients.viewerChanged('a1')
api.clients.gridNamed('grid')
api.clients.dshInstallStatus({ phase: 'clone' })
+ api.clients.windows({ type: 'orchestrator_changed', payload: {} })
})
it('runs as a real service process, with the real workspaces, by default', () => {
diff --git a/cli/src/services/workspacesProcess.ts b/cli/src/services/workspacesProcess.ts
index ca6735bf3..ba1c7123c 100644
--- a/cli/src/services/workspacesProcess.ts
+++ b/cli/src/services/workspacesProcess.ts
@@ -13,7 +13,7 @@
* alone: a hang or a crash in it costs workspaces, and the master starts them again.
*/
import type { CoreApi } from '../core/api.js'
-import { DELIVERIES_OFF, emptyPorts, LANE_OFF, resolveAgent, TERMINALS_OFF } from '../core/api.js'
+import { AGENT_ACTIONS_OFF, DAEMON_UNKNOWN, DELIVERIES_OFF, emptyPorts, LANE_OFF, resolveAgent, TERMINALS_OFF } from '../core/api.js'
import type { RegisteredSession } from '../lib/registry.js'
import { runServiceProcess, type CoreConnection, type ServiceProcess } from './process.js'
import { startWorkspaces } from './workspaces.js'
@@ -63,6 +63,7 @@ export function workspacesCoreApi(
runtimeProfile: () => null,
setRuntime: () => {},
fork: async () => ({ ok: false, error: 'UNSUPPORTED' }),
+ ...AGENT_ACTIONS_OFF,
},
// The workspaces drive no agent: these are never asked of them.
turns: { send: () => {}, stop: () => {}, recent: () => [], asks: () => [], ...DELIVERIES_OFF },
@@ -79,7 +80,8 @@ export function workspacesCoreApi(
privateGridName: async () => null,
machineName: () => null,
},
- clients: { viewerChanged: () => {}, gridNamed: () => {}, gridModelsChanged: () => {}, dshInstallStatus: () => {} },
+ clients: { viewerChanged: () => {}, gridNamed: () => {}, gridModelsChanged: () => {}, dshInstallStatus: () => {}, windows: () => {} },
+ daemon: DAEMON_UNKNOWN,
}
}
diff --git a/cli/src/socketBindings.spec.ts b/cli/src/socketBindings.spec.ts
index dae9a5b0b..156595f4e 100644
--- a/cli/src/socketBindings.spec.ts
+++ b/cli/src/socketBindings.spec.ts
@@ -14,7 +14,6 @@ const SRC = join(__dirname)
/** Slots left unbound on purpose, and why. */
const NOT_BOUND_ON_PURPOSE: Record<string, string> = {
- orchestratorCommand: 'a test override: null runs the daemon\'s own `orchestrator` command',
teamCommand: 'a test override: null runs the daemon\'s own `team` command',
onLocalClient: 'declared and never wired (the design doc\'s "Found while mapping")',
}
diff --git a/cli/src/testing/fakeCore.ts b/cli/src/testing/fakeCore.ts
index 64d2841d9..bc1d65049 100644
--- a/cli/src/testing/fakeCore.ts
+++ b/cli/src/testing/fakeCore.ts
@@ -25,6 +25,8 @@ export function fakeCore(over: Overrides = {}): CoreApi {
runtimeProfile: vi.fn(() => null),
setRuntime: vi.fn(),
fork: vi.fn(async () => ({ ok: false as const, error: 'UNSUPPORTED' })),
+ create: vi.fn(async () => ({ ok: false as const, error: 'UNSUPPORTED' })),
+ dsh: vi.fn(() => null),
...over.agents,
},
turns: {
@@ -54,6 +56,7 @@ export function fakeCore(over: Overrides = {}): CoreApi {
machineName: vi.fn(() => null),
...over.account,
},
- clients: { viewerChanged: vi.fn(), gridNamed: vi.fn(), gridModelsChanged: vi.fn(), dshInstallStatus: vi.fn(), ...over.clients },
+ clients: { viewerChanged: vi.fn(), gridNamed: vi.fn(), gridModelsChanged: vi.fn(), dshInstallStatus: vi.fn(), windows: vi.fn(), ...over.clients },
+ daemon: { command: 'harness', port: 18473, machineId: () => 'machine-1', ...over.daemon },
}
}