The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Delivered turns, one member of the core for the device, the teams and the orchestrator (#921)
Deeb84cac9593ea
diff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.tsindex 861e3c7e3..4a3a3eb55 100644--- a/cli/src/architecture.spec.ts+++ b/cli/src/architecture.spec.ts@@ -222,7 +222,12 @@ const SERVICE_MAY_IMPORT: Record<string, string> = {// 97 lines (#888) with it, and the core reaches grid only through its port (core/modelsLink.ts), keeping// which `grid` a pane runs (lib/gridBinary.ts), how a frame reads a grid's note (lib/gridAnnotation.ts) and// the launchers (lib/launchers.ts).-const CORE_CLOSURE_BUDGET = 89_730+//+// Then at 89,761 in 402 (step 8, its first change), from 89,632 in 401: delivered turns (core/deliveries.ts), the one way the Wi-Fi+// 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/** 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[] = [diff --git a/cli/src/core/AGENTS.md b/cli/src/core/AGENTS.mdindex b832eeb6d..b93e1a3f0 100644--- a/cli/src/core/AGENTS.md+++ b/cli/src/core/AGENTS.md@@ -29,6 +29,8 @@ questions. Everything else is a service ([../services/AGENTS.md](../services/AGE- `terminals/`: who controls a pane (the control lease).- `engines/`: the engines' hooks.- `input.ts`, `questions.ts`: messages into a pane; an agent's question and its answer.+- `deliveries.ts`: delivered turns, the Wi-Fi device's, a team's and the orchestrator's: text written into an+ agent under a delivery id of its maker's, and what became of it, told back to that maker in its process.- `main.ts`: the core's entry (`harness __run`) and composition root, `runForeground`: it builds thesemodules, starts the services through `serviceHost` and wires the socket. The one core file that importsservices and the socket, and the one outside the 100% coverage: wiring only, run end to end. Thediff --git a/cli/src/core/api.spec.ts b/cli/src/core/api.spec.tsindex 6b441b007..9a1317663 100644--- a/cli/src/core/api.spec.ts+++ b/cli/src/core/api.spec.ts@@ -1,6 +1,6 @@import { describe, expect, it, vi } from 'vitest'import { projectDisplayName, type RegisteredSession } from '../lib/registry.js'-import { createCoreApi, emptyPorts, FLEET_FALLBACKS, LANE_OFF, LONG_ANSWERS, MODELS_OFF, MODELS_REQUESTS, MONITOR_OFF, resolveAgent, TEAMS_FALLBACKS, type CoreApiDeps } from './api.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 { FAIL } from './serviceHost.js'const row = (agentId: string) => ({ agentId, sessionId: `s-${agentId}`, engine: 'claude', cwd: '/work/app' }) as RegisteredSession@@ -15,6 +15,12 @@ describe('the core API services stand on', () => {expect(LANE_OFF.drop('m')).toBeUndefined()})+ it('gives a service with no delivery of the core\'s nothing to write, take back or hear', async () => {+ expect(DELIVERIES_OFF.deliver('a', 'hello', 'd1')).toBeUndefined()+ expect(DELIVERIES_OFF.cancelDelivery('d1')).toBe(false)+ expect(DELIVERIES_OFF.onDelivery(() => {})()).toBeUndefined()+ })+it('resolves an agent in a service\'s own copy as the registry does: by agent id, then session id', () => {const agents = [{ ...row('a'), sessionId: '' }, row('b')]expect(resolveAgent(agents, 'b')?.agentId).toBe('b')@@ -51,7 +57,7 @@ describe('the core API services stand on', () => {runtimeProfile: vi.fn(() => null),setRuntime: vi.fn(),fork: vi.fn(async () => ({ ok: true as const, agentId: 'fork' })),- turns: { send: vi.fn(), stop: vi.fn(), recent: vi.fn(() => []), asks: vi.fn(() => []) },+ 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) },}const core = createCoreApi(deps)diff --git a/cli/src/core/api.ts b/cli/src/core/api.tsindex 2f8698779..3a67bc0a8 100644--- a/cli/src/core/api.ts+++ b/cli/src/core/api.ts@@ -23,6 +23,7 @@ import { GRID_FLEET_MAX_TIMEOUT_MS } from '../lib/gridFleetProtocol.js'import type { GridLaunchOverride } from '../lib/gridLaunch.js'import type { NewAgentModel } from '../lib/newAgentModel.js'import type { LiveEvent } from '../lib/normalize.js'+import type { SessionInputDelivery } from '../lib/sessionInput.js'import { projectDisplayName, type registry, type RegisteredSession } from '../lib/registry.js'import type { RuntimeModelOption } from '../lib/runtimeProfile.js'import type { RouterContinuity } from '../lib/voiceRouter.js'@@ -89,6 +90,18 @@ export interface CoreApi {recent(agentId: string, n: number): RecentTurn[]/** The person's own last questions to a live agent, newest first. */asks(agentId: string): string[]+ /** Deliver text into a live agent under a delivery id of the caller's own, as the Wi-Fi device, a team+ * and the orchestrator deliver their turns: one path for the three. What becomes of it is heard through+ * `onDelivery`, under the same id. */+ deliver(agentId: string, text: string, deliveryId: string): void+ /** Take back a delivery not yet being written: true when it was, and it never will be; false for one+ * the agent's pane is already taking. Answered at once, as the teams and the orchestrator read it in+ * line: in a service's own process the core is asked and the answer cannot wait, so it is false there,+ * and a delivery the core did take back is then heard `rejected` (`cancelled`). */+ cancelDelivery(deliveryId: string): boolean+ /** Hear what becomes of each delivery: queued, written, its turn started, refused and why, or past+ * knowing. Returns how to stop hearing. */+ onDelivery(listener: (event: TurnDelivery) => void): () => void}questions: {/** Answer a live agent's question, keyed by the question keys it asked with. */@@ -140,6 +153,19 @@ export interface CoreApi {}}+/** 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. */+export type TurnDelivery = SessionInputDelivery++/** The delivery members of a core that delivers nothing for this service: nothing is written, nothing is+ * taken back, and nothing is heard. */+export const DELIVERIES_OFF: Pick<CoreApi['turns'], 'deliver' | 'cancelDelivery' | 'onDelivery'> = {+ deliver: () => {},+ cancelDelivery: () => false,+ onDelivery: () => () => {},+}+/** `agents.resolve` over a service process's own copy of the agents, as the registry answers it: by agent* id, then by engine session id (an agent with none yet is never found by an empty one). */export function resolveAgent(agents: readonly RegisteredSession[], id: string): RegisteredSession | undefined {diff --git a/cli/src/core/deliveries.spec.ts b/cli/src/core/deliveries.spec.tsnew file mode 100644index 000000000..23a188885--- /dev/null+++ b/cli/src/core/deliveries.spec.ts@@ -0,0 +1,104 @@+import { describe, expect, it, vi } from 'vitest'+import type { TurnDelivery } from './api.js'+import { createDeliveries, KEPT_DELIVERERS, type DeliveriesDeps } from './deliveries.js'++const setup = (over: Partial<Pick<DeliveriesDeps, 'submit' | 'cancel' | 'deliverers'>> = {}) => {+ const deps = {+ submit: over.submit ?? vi.fn(),+ cancel: over.cancel ?? vi.fn(() => true),+ tell: vi.fn(),+ deliverers: over.deliverers ?? new Set(['orchestrator']),+ log: vi.fn(),+ }+ return { deps, deliveries: createDeliveries(deps) }+}+const event = (deliveryId: string, state: TurnDelivery['state'] = 'queued'): TurnDelivery => ({ deliveryId, sessionId: 'agent-1', state })++describe('delivered turns', () => {+ it('writes a delivery from the core\'s own process into the agent, and takes one back at once', () => {+ const { deps, deliveries } = setup({ cancel: vi.fn(() => false) })+ deliveries.turns.deliver('agent-1', 'hello', 'd1')+ expect(deps.submit).toHaveBeenCalledWith('agent-1', 'hello', 'd1')+ expect(deliveries.turns.cancelDelivery('d1')).toBe(false)+ expect(deps.cancel).toHaveBeenCalledWith('d1')+ })++ it('tells every listener in the core\'s process what became of each delivery, until it stops listening', () => {+ const { deliveries } = setup()+ const heard: TurnDelivery[] = []+ const stop = deliveries.turns.onDelivery((e) => heard.push(e))+ deliveries.settled(event('d1'))+ stop()+ deliveries.settled(event('d1', 'started'))+ expect(heard).toEqual([event('d1')])+ })++ it('costs a listener that throws that event alone: the next listener hears it, and nothing is thrown back', () => {+ const { deps, deliveries } = setup()+ const after = vi.fn()+ deliveries.turns.onDelivery(() => { throw new Error('a full disk') })+ deliveries.turns.onDelivery(() => { throw 'not an error' })+ deliveries.turns.onDelivery(after)+ expect(() => deliveries.settled(event('d1'))).not.toThrow()+ expect(after).toHaveBeenCalledWith(event('d1'))+ expect(deps.log).toHaveBeenCalledWith(expect.stringContaining('a full disk'))+ expect(deps.log).toHaveBeenCalledWith(expect.stringContaining('not an error'))+ })++ it('writes a process\'s delivery and tells that process alone what became of it, its first word included', () => {+ const { deps, deliveries } = setup({+ submit: vi.fn((_agentId: string, _text: string, deliveryId: string) => deliveries.settled(event(deliveryId))),+ })+ expect(deliveries.answer('orchestrator', 'deliver', { agentId: 'agent-1', text: 'hello', deliveryId: 'd1' })).toEqual({})+ expect(deps.submit).toHaveBeenCalledWith('agent-1', 'hello', 'd1')+ deliveries.settled(event('d1', 'started'))+ deliveries.settled(event('someone-else'))+ expect(deps.tell.mock.calls).toEqual([['orchestrator', event('d1')], ['orchestrator', event('d1', 'started')]])+ })++ it('takes a process\'s delivery back and says whether it could', () => {+ const { deps, deliveries } = setup()+ expect(deliveries.answer('orchestrator', 'cancel_delivery', { deliveryId: 'd1' })).toEqual({ cancelled: true })+ expect(deps.cancel).toHaveBeenCalledWith('d1')+ })++ it('refuses a process that is not a deliverer, and a delivery without its id, agent or text', () => {+ const { deps, deliveries } = setup()+ expect(deliveries.answer('search', 'deliver', { agentId: 'agent-1', text: 'hello', deliveryId: 'd1' })).toEqual({ error: 'NOT_A_DELIVERER' })+ expect(deliveries.answer('orchestrator', 'deliver', { agentId: 'agent-1', text: 'hello' })).toEqual({ error: 'INVALID_DELIVERY' })+ expect(deliveries.answer('orchestrator', 'deliver', { text: 'hello', deliveryId: 'd1' })).toEqual({ error: 'INVALID_DELIVERY' })+ expect(deliveries.answer('orchestrator', 'deliver', { agentId: 'agent-1', text: 7, deliveryId: 'd1' })).toEqual({ error: 'INVALID_DELIVERY' })+ expect(deliveries.answer('orchestrator', 'cancel_delivery', {})).toEqual({ error: 'INVALID_DELIVERY' })+ expect(deps.submit).not.toHaveBeenCalled()+ expect(deps.cancel).not.toHaveBeenCalled()+ })++ it('leaves the other queries to whoever answers them', () => {+ expect(setup().deliveries.answer('orchestrator', 'live', {})).toBeNull()+ })++ it('remembers the makers of the last deliveries only, a delivery made again as the newest', () => {+ const { deps, deliveries } = setup({ deliverers: new Set(['orchestrator', 'teams']) })+ deliveries.answer('orchestrator', 'deliver', { agentId: 'a', text: 't', deliveryId: 'first' })+ deliveries.answer('teams', 'deliver', { agentId: 'a', text: 't', deliveryId: 'second' })+ // Made again: the newest now, and by its new maker.+ deliveries.answer('teams', 'deliver', { agentId: 'a', text: 't', deliveryId: 'first' })+ for (let i = 0; i < KEPT_DELIVERERS - 1; i++) deliveries.answer('orchestrator', 'deliver', { agentId: 'a', text: 't', deliveryId: `d${i}` })+ deps.tell.mockClear()+ deliveries.settled(event('second'))+ deliveries.settled(event('first'))+ expect(deps.tell.mock.calls).toEqual([['teams', event('first')]])+ })++ it('logs to the console when given no log of its own', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ try {+ const deliveries = createDeliveries({ submit: vi.fn(), cancel: vi.fn(() => false), tell: vi.fn(), deliverers: new Set() })+ deliveries.turns.onDelivery(() => { throw new Error('boom') })+ deliveries.settled(event('d1'))+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('boom'))+ } finally {+ warn.mockRestore()+ }+ })+})diff --git a/cli/src/core/deliveries.ts b/cli/src/core/deliveries.tsnew file mode 100644index 000000000..4a23fe5c3--- /dev/null+++ b/cli/src/core/deliveries.ts@@ -0,0 +1,89 @@+/**+ * Delivered turns: text a feature writes into an agent under a delivery id of its own, and what becomes of+ * it. The Wi-Fi device, the teams and the orchestrator each deliver their turns this way, one path for the+ * three (docs/design/2026-10-06-core-boundary-next.md, "Experimental features: move only"). It is what+ * lets a feature that delivers turns run in a process of its own: before, each was a slot on the socket+ * (`onMessage`, `onCancelOrchestratorMessage`, `orchestratorDelivery`, `teamDelivery`) that only code in+ * the core's process could call.+ *+ * In the core's process a service delivers through `turns` (`CoreApi.turns`) and hears every delivery's+ * progress, as the socket's features always did: each ignores the ids that are not its own. A service in its+ * own process delivers by asking the core (`answer`, services/turnsLink.ts) and hears only its own+ * deliveries, told to it until it has them: a delivery it made is its business and no other process's.+ */+import type { CoreApi, TurnDelivery } from './api.js'++type Payload = Record<string, unknown>++/** The most deliveries whose maker is remembered: past it the oldest is forgotten, and what becomes of it+ * is told to no process. A delivery settles within minutes (its queue item lives five), and a process+ * makes a few a minute. */+export const KEPT_DELIVERERS = 10_000++export interface DeliveriesDeps {+ /** Write the text into the agent under the delivery id (core/input.ts `submitAgent`). */+ submit(agentId: string, text: string, deliveryId: string): void+ /** Take back a delivery not yet being written (`SessionInputController.cancelDelivery`). */+ cancel(deliveryId: string): boolean+ /** Tell a service in its own process what became of a delivery it made. */+ tell(service: string, event: TurnDelivery): void+ /** The services in their own processes that may deliver turns: writing into an agent is no other's to ask. */+ deliverers: ReadonlySet<string>+ log?: (line: string) => void+}++const text = (value: unknown): string => (typeof value === 'string' ? value : '')++export function createDeliveries(deps: DeliveriesDeps) {+ const log = deps.log ?? ((line: string) => console.warn(line))+ const listeners = new Set<(event: TurnDelivery) => void>()+ /** Which process made each delivery, oldest first. */+ const makers = new Map<string, string>()++ const turns: Pick<CoreApi['turns'], 'deliver' | 'cancelDelivery' | 'onDelivery'> = {+ deliver: (agentId, content, deliveryId) => deps.submit(agentId, content, deliveryId),+ cancelDelivery: (deliveryId) => deps.cancel(deliveryId),+ onDelivery: (listener) => {+ listeners.add(listener)+ return () => { listeners.delete(listener) }+ },+ }++ return {+ /** The delivery members of the core's own `CoreApi`, for the services in its process. */+ turns,++ /** The core's input says what became of a delivery: every listener here hears it, each guarded, and the+ * process that made it is told. A listener that throws costs that listener the event, never the input+ * that said it or another listener. */+ settled(event: TurnDelivery): void {+ for (const listener of listeners) {+ try { listener(event) } catch (error) {+ log(`[deliveries] a listener failed on ${event.deliveryId.slice(0, 40)} · ${error instanceof Error ? error.message : String(error)}`)+ }+ }+ const maker = makers.get(event.deliveryId)+ if (maker) deps.tell(maker, event)+ },++ /** A service in its own process delivering a turn, or taking one back (`service_query`): null when the+ * query is not one of these. Refused for a service that is not a deliverer. */+ answer(service: string, query: string, payload: Payload): Payload | null {+ if (query !== 'deliver' && query !== 'cancel_delivery') return null+ if (!deps.deliverers.has(service)) return { error: 'NOT_A_DELIVERER' }+ const deliveryId = text(payload.deliveryId)+ if (!deliveryId) return { error: 'INVALID_DELIVERY' }+ if (query === 'cancel_delivery') return { cancelled: deps.cancel(deliveryId) }+ const agentId = text(payload.agentId)+ if (!agentId || typeof payload.text !== 'string') return { error: 'INVALID_DELIVERY' }+ // Known before it is written: the input says `queued` as it takes it, and that is the maker's to hear.+ makers.delete(deliveryId)+ makers.set(deliveryId, service)+ if (makers.size > KEPT_DELIVERERS) makers.delete(makers.keys().next().value!)+ deps.submit(agentId, payload.text, deliveryId)+ return {}+ },+ }+}++export type Deliveries = ReturnType<typeof createDeliveries>diff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex 3245b0640..078beb19b 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -138,6 +138,7 @@ import { createMonitorLink } from './monitorLink.js'import { createStoreLink } from './storeLink.js'import { createModelsLink } from './modelsLink.js'import { answerAgentQuery } from './agentQueries.js'+import { createDeliveries } from './deliveries.js'import { KNOWN_SERVICES, servicesTheMasterRuns } from '../harnessd/services.js'import { createTeamsLink } from './teamsLink.js'import { startFleet } from '../services/fleet.js'@@ -620,6 +621,15 @@ async function runForeground(session: AuthSession | null): Promise<void> {// their tokens from it, so a refresh in flight is shared rather than raced.const auth = new AuthSessionManager(backendHttpBase())// The core's side of the boundary its services stand on, and the ports it reaches them through (core/api.ts).+ // Delivered turns (core/deliveries.ts): text a feature writes into an agent under a delivery id of its+ // own, and what becomes of each, told back to whoever made it, in this process or in its own.+ const deliveries = createDeliveries({+ 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(),+ })const coreApi = createCoreApi({terminals: createTerminalOpener({ tmuxBackend, registry, announceSession, blocksFolder: (cwd) => !!backendRef?.purgeAgentService?.blocksFolder(cwd) }),dataDir: env.ADAPTER_DATA_DIR,@@ -669,6 +679,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {stop: (agentId) => backendRef?.onCancel?.(agentId),recent: (agentId, n) => mirror.recent(registry.resolve(agentId)?.sessionId || agentId, n),asks: (agentId) => mirror.recentAsks(registry.resolve(agentId)?.sessionId || agentId),+ ...deliveries.turns,},questions: {// The device's own object, verbatim: rebuilt as `{ [requestId]: optionId }` it was keyed by the@@ -968,6 +979,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {delivery: (event) => {backend.orchestratorDelivery(event)backend.teamDelivery(event)+ deliveries.settled(event)},canWrite: (deliveryId) => backend.teamCanWrite(deliveryId),},@@ -1086,12 +1098,13 @@ 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) => service === 'viewers' ? viewersLink.answer(query, payload)+ answer: (service, query, payload) => deliveries.answer(service, query, payload)+ ?? (service === 'viewers' ? viewersLink.answer(query, payload): service === 'workspaces' ? workspacesLink.answer(query, payload): service === 'store' ? storeLink.answer(query, payload): service === 'models' ? modelsLink.answer(query, payload): service === 'teams' ? teamsLink.answer(query, payload)- : service === 'gateway' && gatewayLink ? gatewayLink.answer(query, payload) : answerAgentQuery(coreApi, query),+ : service === 'gateway' && gatewayLink ? gatewayLink.answer(query, payload) : answerAgentQuery(coreApi, query)),// The gateway's own traffic: its remote clients and what they sent, and its comings and goings.notice: (service, payload) => { if (service === 'gateway') gatewayLink?.notice(payload) },binary: (service, bytes) => { if (service === 'gateway') gatewayLink?.binary(bytes) },diff --git a/cli/src/services/AGENTS.md b/cli/src/services/AGENTS.mdindex 0f081063c..be0061b5d 100644--- a/cli/src/services/AGENTS.md+++ b/cli/src/services/AGENTS.md@@ -108,6 +108,11 @@ way back).(`service_notice`) and carries terminal bytes as binary frames on its link. The core drops what wouldpile up on a gateway that reads nothing, and the gateway gone is the relay gone: every remote clientwith it, never a window on this computer. `e2e/gatewayProcess.e2e.ts` proves it, with a phone.+- A service that writes turns into agents (a team's question, the orchestrator's guidance) delivers each+ under an id of its own through `core.turns.deliver`, hears what became of it through `onDelivery`, and+ takes one back with `cancelDelivery` (core/deliveries.ts). In its own process `services/turnsLink.ts`+ 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.- 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 ituntil the process acknowledges it; on each connection the process says what it applied and getsdiff --git a/cli/src/services/modelsProcess.ts b/cli/src/services/modelsProcess.tsindex c6aa232c5..707153511 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 { emptyPorts, LANE_OFF, TERMINALS_OFF } from '../core/api.js'+import { 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'@@ -74,7 +74,7 @@ export function modelsCoreApi(dataDir: string, ask: (query: string, payload?: PasetRuntime: () => {},fork: async () => ({ ok: false, error: 'UNSUPPORTED' }),},- turns: { send: () => {}, stop: () => {}, recent: () => [], asks: () => [] },+ turns: { send: () => {}, stop: () => {}, recent: () => [], asks: () => [], ...DELIVERIES_OFF },questions: { answer: () => {}, answerReviewed: async () => false },transcripts: { databaseHistory: () => undefined },external: {diff --git a/cli/src/services/processCoreApi.ts b/cli/src/services/processCoreApi.tsindex 81a18445c..1d48255bd 100644--- a/cli/src/services/processCoreApi.ts+++ b/cli/src/services/processCoreApi.ts@@ -7,7 +7,7 @@* 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).*/-import { LANE_OFF, resolveAgent, TERMINALS_OFF, type CoreApi } from '../core/api.js'+import { DELIVERIES_OFF, LANE_OFF, resolveAgent, TERMINALS_OFF, type CoreApi } from '../core/api.js'import type { RegisteredSession } from '../lib/registry.js'/** The agents a process was last told of. Those it is never told of read as none. */@@ -47,7 +47,7 @@ export function processCoreApi(dataDir: string, service: string, view: AgentsViesetRuntime: () => {},fork: async () => ({ ok: false, error: 'UNSUPPORTED' }),},- turns: { send: () => {}, stop: () => {}, recent: () => [], asks: () => [] },+ turns: { send: () => {}, stop: () => {}, recent: () => [], asks: () => [], ...DELIVERIES_OFF },questions: { answer: () => {}, answerReviewed: async () => false },transcripts: { databaseHistory: () => undefined },external: {diff --git a/cli/src/services/searchProcess.ts b/cli/src/services/searchProcess.tsindex d1460ef42..84be9bc01 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 { emptyPorts, LANE_OFF, resolveAgent, TERMINALS_OFF } from '../core/api.js'+import { 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'@@ -56,7 +56,7 @@ export function searchCoreApi(fork: async () => ({ ok: false, error: 'UNSUPPORTED' }),},// Search drives no agent: these are never asked of it.- turns: { send: () => {}, stop: () => {}, recent: () => [], asks: () => [] },+ turns: { send: () => {}, stop: () => {}, recent: () => [], asks: () => [], ...DELIVERIES_OFF },questions: { answer: () => {}, answerReviewed: async () => false },transcripts: { databaseHistory },external: {diff --git a/cli/src/services/turnsLink.spec.ts b/cli/src/services/turnsLink.spec.tsnew file mode 100644index 000000000..59779f19d--- /dev/null+++ b/cli/src/services/turnsLink.spec.ts@@ -0,0 +1,90 @@+import { describe, expect, it, vi } from 'vitest'+import type { TurnDelivery } from '../core/api.js'+import { deliveryIn, turnsLink } from './turnsLink.js'++const flush = () => new Promise((settle) => setTimeout(settle, 0))++describe('delivered turns from a service in its own process', () => {+ it('asks the core to write a delivery and to take one back, and hears whether it could', async () => {+ const query = vi.fn(async (q: string) => (q === 'cancel_delivery' ? { cancelled: true } : {}))+ const link = turnsLink(query)+ const heard: TurnDelivery[] = []+ link.turns.onDelivery((event) => heard.push(event))+ link.turns.deliver('agent-1', 'hello', 'd1')+ // Asked in line, it cannot wait for the core: not known to be taken back yet.+ expect(link.turns.cancelDelivery('d1')).toBe(false)+ expect(await link.cancel('d1')).toBe(true)+ await flush()+ expect(query.mock.calls).toEqual([+ ['deliver', { agentId: 'agent-1', text: 'hello', deliveryId: 'd1' }],+ ['cancel_delivery', { deliveryId: 'd1' }],+ ['cancel_delivery', { deliveryId: 'd1' }],+ ])+ expect(heard).toEqual([])+ })++ it('reads a cancel the core could not make, or never answered, as not taken back', async () => {+ expect(await turnsLink(async () => ({ cancelled: false })).cancel('d1')).toBe(false)+ expect(await turnsLink(async () => { throw new Error('gone') }).cancel('d1')).toBe(false)+ })++ it('says a delivery the core refused was rejected, and one it never confirmed is unknown', async () => {+ const refused = turnsLink(async () => ({ error: 'NOT_A_DELIVERER' }))+ const unconfirmed = turnsLink(async () => { throw new Error('the link went') })+ const heard: TurnDelivery[] = []+ refused.turns.onDelivery((event) => heard.push(event))+ unconfirmed.turns.onDelivery((event) => heard.push(event))+ refused.turns.deliver('agent-1', 'hello', 'd1')+ unconfirmed.turns.deliver('agent-2', 'hello', 'd2')+ await flush()+ expect(heard).toEqual([+ { deliveryId: 'd1', sessionId: 'agent-1', state: 'rejected', reason: 'NOT_A_DELIVERER' },+ { deliveryId: 'd2', sessionId: 'agent-2', state: 'unknown', reason: 'The core did not confirm this delivery.' },+ ])+ })++ it('hands what the core says became of a delivery to each listener, until it stops listening', () => {+ const link = turnsLink(async () => ({}))+ const heard: TurnDelivery[] = []+ const stop = link.turns.onDelivery((event) => heard.push(event))+ expect(link.heard({ kind: 'delivery', event: { deliveryId: 'd1', sessionId: 'agent-1', state: 'rejected', reason: 'cancelled' } })).toBe(true)+ stop()+ expect(link.heard({ kind: 'delivery', event: { deliveryId: 'd1', sessionId: 'agent-1', state: 'started' } })).toBe(true)+ expect(heard).toEqual([{ deliveryId: 'd1', sessionId: 'agent-1', state: 'rejected', reason: 'cancelled' }])+ })++ it('costs a listener that throws that event alone', () => {+ const log = vi.fn()+ const link = turnsLink(async () => ({}), log)+ const after = vi.fn()+ link.turns.onDelivery(() => { throw new Error('boom') })+ link.turns.onDelivery(() => { throw 'not an error' })+ link.turns.onDelivery(after)+ link.heard({ kind: 'delivery', event: { deliveryId: 'd1', sessionId: 'a', state: 'queued' } })+ expect(after).toHaveBeenCalledOnce()+ expect(log).toHaveBeenCalledWith(expect.stringContaining('boom'))+ expect(log).toHaveBeenCalledWith(expect.stringContaining('not an error'))+ })++ it('logs to the console when given no log of its own', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ try {+ const link = turnsLink(async () => ({}))+ link.turns.onDelivery(() => { throw new Error('boom') })+ link.heard({ kind: 'delivery', event: { deliveryId: 'd1', sessionId: 'a', state: 'queued' } })+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('boom'))+ } finally {+ warn.mockRestore()+ }+ })++ it('takes nothing else for a delivery\'s progress', () => {+ expect(turnsLink(async () => ({})).heard({ kind: 'event', event: {} })).toBe(false)+ expect(deliveryIn({ kind: 'delivery' })).toBeNull()+ expect(deliveryIn({ kind: 'delivery', event: { deliveryId: 'd1', sessionId: 'a', state: 'lost' } })).toBeNull()+ expect(deliveryIn({ kind: 'delivery', event: { deliveryId: 1, sessionId: 'a', state: 'queued' } })).toBeNull()+ expect(deliveryIn({ kind: 'delivery', event: { deliveryId: 'd1', state: 'queued' } })).toBeNull()+ expect(deliveryIn({ kind: 'delivery', event: { deliveryId: 'd1', sessionId: 'a', state: 'queued', reason: 3 } }))+ .toEqual({ deliveryId: 'd1', sessionId: 'a', state: 'queued' })+ })+})diff --git a/cli/src/services/turnsLink.ts b/cli/src/services/turnsLink.tsnew file mode 100644index 000000000..1f378f0e9--- /dev/null+++ b/cli/src/services/turnsLink.ts@@ -0,0 +1,70 @@+/**+ * Delivered turns, as a service in its own process makes them (the core's side is core/deliveries.ts): it+ * asks the core to write each one and to take one back, and the core tells it what became of each of its+ * own (`service_event` kind `delivery`), which it hands to whoever listens here.+ *+ * Asked over the one link the service has, in order: a delivery and the cancel that follows it reach the+ * core in the order they were made, so a cancel never arrives before the turn it takes back. Whether a+ * cancel took a delivery back cannot be answered at once here (`cancelDelivery` says false); a caller that+ * can wait asks `cancel`. A delivery the core never heard of (the link went before it was answered) is said+ * to be `unknown`: it may have been written, and nothing here can tell.+ */+import type { CoreApi, TurnDelivery } from '../core/api.js'++type Payload = Record<string, unknown>+type DeliveryTurns = Pick<CoreApi['turns'], 'deliver' | 'cancelDelivery' | 'onDelivery'>++const STATES: ReadonlySet<string> = new Set(['queued', 'delivered', 'started', 'rejected', 'unknown'])++/** A delivery's progress as the core sent it, or null when it is not one. */+export function deliveryIn(payload: Payload): TurnDelivery | null {+ const event = payload.kind === 'delivery' ? payload.event as Payload | undefined : undefined+ if (!event || typeof event.deliveryId !== 'string' || typeof event.sessionId !== 'string' || !STATES.has(String(event.state))) return null+ return {+ deliveryId: event.deliveryId,+ sessionId: event.sessionId,+ state: event.state as TurnDelivery['state'],+ ...(typeof event.reason === 'string' ? { reason: event.reason } : {}),+ }+}++/** `query` asks the core (`CoreConnection.query`, services/process.ts); it rejects when the link goes. */+export function turnsLink(query: (query: string, payload: Payload) => Promise<Payload>, log: (line: string) => void = (line) => console.warn(line)) {+ const listeners = new Set<(event: TurnDelivery) => void>()+ const tell = (event: TurnDelivery): void => {+ for (const listener of listeners) {+ try { listener(event) } catch (error) {+ log(`[deliveries] a listener failed on ${event.deliveryId.slice(0, 40)} · ${error instanceof Error ? error.message : String(error)}`)+ }+ }+ }+ const cancel = async (deliveryId: string): Promise<boolean> =>+ (await query('cancel_delivery', { deliveryId }).catch((): Payload => ({}))).cancelled === true+ const turns: DeliveryTurns = {+ deliver: (agentId, text, deliveryId) => {+ void query('deliver', { agentId, text, deliveryId }).then(+ (answer) => { if (typeof answer.error === 'string') tell({ deliveryId, sessionId: agentId, state: 'rejected', reason: answer.error }) },+ () => tell({ deliveryId, sessionId: agentId, state: 'unknown', reason: 'The core did not confirm this delivery.' }),+ )+ },+ // The core decides, later than this answer can wait: false here, and a delivery it did take back is+ // heard `rejected` (`cancelled`), after the cancel, on the same link.+ cancelDelivery: (deliveryId) => { void cancel(deliveryId); return false },+ onDelivery: (listener) => {+ listeners.add(listener)+ return () => { listeners.delete(listener) }+ },+ }+ return {+ turns,+ /** Take back a delivery and hear whether the core could, for a caller that can wait for the answer. */+ cancel,+ /** What the core told this service: true when it was a delivery's progress, now heard here. */+ heard(payload: Payload): boolean {+ const event = deliveryIn(payload)+ if (!event) return false+ tell(event)+ return true+ },+ }+}diff --git a/cli/src/services/viewersProcess.ts b/cli/src/services/viewersProcess.tsindex 30d2bb7be..d037f9f32 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 { emptyPorts, LANE_OFF, resolveAgent, TERMINALS_OFF } from '../core/api.js'+import { 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'@@ -63,7 +63,7 @@ export function viewersCoreApi(dataDir: string, sessions: ReadonlyMap<string, Refork: async () => ({ ok: false, error: 'UNSUPPORTED' }),},// The viewers drive no agent: these are never asked of them.- turns: { send: () => {}, stop: () => {}, recent: () => [], asks: () => [] },+ turns: { send: () => {}, stop: () => {}, recent: () => [], asks: () => [], ...DELIVERIES_OFF },questions: { answer: () => {}, answerReviewed: async () => false },transcripts: { databaseHistory: () => undefined },external: {diff --git a/cli/src/services/workspacesProcess.ts b/cli/src/services/workspacesProcess.tsindex c34001ee4..ca6735bf3 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 { emptyPorts, LANE_OFF, resolveAgent, TERMINALS_OFF } from '../core/api.js'+import { 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'@@ -65,7 +65,7 @@ export function workspacesCoreApi(fork: async () => ({ ok: false, error: 'UNSUPPORTED' }),},// The workspaces drive no agent: these are never asked of them.- turns: { send: () => {}, stop: () => {}, recent: () => [], asks: () => [] },+ turns: { send: () => {}, stop: () => {}, recent: () => [], asks: () => [], ...DELIVERIES_OFF },questions: { answer: () => {}, answerReviewed: async () => false },transcripts: { databaseHistory: () => undefined },external: {diff --git a/cli/src/testing/fakeCore.ts b/cli/src/testing/fakeCore.tsindex 447cd4965..64d2841d9 100644--- a/cli/src/testing/fakeCore.ts+++ b/cli/src/testing/fakeCore.ts@@ -27,7 +27,11 @@ export function fakeCore(over: Overrides = {}): CoreApi {fork: vi.fn(async () => ({ ok: false as const, error: 'UNSUPPORTED' })),...over.agents,},- turns: { send: vi.fn(), stop: vi.fn(), recent: vi.fn(() => []), asks: vi.fn(() => []), ...over.turns },+ turns: {+ send: vi.fn(), stop: vi.fn(), recent: vi.fn(() => []), asks: vi.fn(() => []),+ deliver: vi.fn(), cancelDelivery: vi.fn(() => false), onDelivery: vi.fn(() => () => {}),+ ...over.turns,+ },questions: { answer: vi.fn(), answerReviewed: vi.fn(async () => false), ...over.questions },transcripts: { databaseHistory: vi.fn(() => undefined), ...over.transcripts },external: {