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.

Cloud agents: Fo, Devin Cloud and Cursor Cloud as harnesses (Phase 1) (#1178)

Deee37a32384660
diff --git a/cli/AGENTS.md b/cli/AGENTS.md
index e0eea6328..a5f1432b7 100644
--- a/cli/AGENTS.md
+++ b/cli/AGENTS.md
@@ -33,7 +33,7 @@ they show as `harnessd`, `harnessd-core` and `harnessd-<process>` (`src/harnessd
| models | grid, local models, the Model Manager | on demand: once grid is in use here (a managed grid, saved grid pictures, local models), or on a models request |
| updater | checks, downloads and stages a new build (`src/services/updaterProcess.ts`) | by the master, for the installed copy only |
| devices | the dials, the window bridges, the fleet, the voice router, the Wi-Fi device | on demand: once there is a device |
-| orchestrator, sharing, memory, router | the experiments | on demand: on a request, or saved state at start |
+| orchestrator, sharing, memory, router, cloud (cloud agents) | the experiments | on demand: on a request, or saved state at start |
`HARNESSD_SERVICES` names a subset to run in their own processes, by service or by process.
`HARNESSD_SERVICES=none` runs every service in the core's process, for debugging or a quick way back. How
diff --git a/cli/e2e/cloudAgents.e2e.ts b/cli/e2e/cloudAgents.e2e.ts
new file mode 100644
index 000000000..e12227d4a
--- /dev/null
+++ b/cli/e2e/cloudAgents.e2e.ts
@@ -0,0 +1,236 @@
+/**
+ * Cloud agents on the real daemon (docs/design/2026-10-11-cloud-agents.md), against a fake of Devin's v3 API
+ * shaped as its documentation says, reached through a key-only connection and the Connections bridge exactly
+ * as a person's Devin key would be. Never the real Devin.
+ *
+ * A window makes a Devin Cloud harness with New Harness's request (`agent_create`); the cloud experiment starts
+ * only then; the harness is listed with no pane; Devin's question reaches the window as any agent's does, and
+ * the answer goes to Devin; Devin's pull request reaches the frame; Stop archives the session; and the harness
+ * is watched again after the daemon restarts.
+ */
+import { mkdirSync } from 'node:fs'
+import { createServer, type Server } from 'node:http'
+import { createServer as netServer } from 'node:net'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
+import { Store } from '../src/lib/connectors/store.js'
+import { LocalClient, type Frame } from './harness/client.js'
+import { IsolatedDaemon, until } from './harness/daemon.js'
+
+const freePort = (): Promise<number> => new Promise((resolve) => {
+ const probe = netServer().listen(0, '127.0.0.1', () => {
+ const port = (probe.address() as { port: number }).port
+ probe.close(() => resolve(port))
+ })
+})
+
+/** Devin's v3 sessions: one session, which asks which branch, then finishes with a pull request. */
+class FakeDevin {
+ server: Server | null = null
+ base = ''
+ auth: string[] = []
+ seen: string[] = []
+ created: Record<string, unknown>[] = []
+ sent: string[] = []
+ archived = 0
+ private status = 'running'
+ private detail = 'working'
+ private messages: Array<{ event_id: string; source: string; message: string; created_at: string }> = []
+ private pulls: Array<{ pr_url: string; pr_state: string }> = []
+
+ async start(): Promise<this> {
+ this.server = createServer((request, response) => {
+ const chunks: Buffer[] = []
+ request.on('data', (chunk) => chunks.push(chunk)).on('end', () => {
+ this.auth.push(String(request.headers.authorization))
+ this.seen.push(`${request.method} ${request.url}`)
+ const body = chunks.length ? JSON.parse(Buffer.concat(chunks).toString()) as Record<string, unknown> : {}
+ const url = new URL(request.url!, 'http://x')
+ const reply = (json: unknown, status = 200) => response.writeHead(status, { 'content-type': 'application/json' }).end(JSON.stringify(json))
+ const session = () => ({ session_id: 'devin-e2e', url: 'https://app.devin.ai/sessions/devin-e2e', status: this.status, status_detail: this.detail,
+ pull_requests: this.pulls, tags: [], org_id: 'org-e2e', created_at: 't', updated_at: 't', acus_consumed: 0 })
+ if (url.pathname === '/v3/self') return reply({ org_id: 'org-e2e', principal_type: 'service_user' })
+ if (request.method === 'POST' && url.pathname === '/v3/organizations/org-e2e/sessions') { this.created.push(body); return reply(session()) }
+ if (request.method === 'GET' && url.pathname === '/v3/organizations/org-e2e/sessions/devin-e2e') {
+ // Its first look finds Devin asking.
+ if (!this.messages.length) {
+ this.detail = 'waiting_for_user'
+ this.messages.push({ event_id: 'e1', source: 'devin', message: 'Which branch should I base it on?', created_at: '2026-10-11T10:01:00Z' })
+ }
+ return reply(session())
+ }
+ if (request.method === 'GET' && url.pathname.endsWith('/messages')) {
+ const after = Number(url.searchParams.get('after') ?? 0)
+ return reply({ items: this.messages.slice(after), end_cursor: String(this.messages.length), has_next_page: false })
+ }
+ if (request.method === 'POST' && url.pathname.endsWith('/messages')) {
+ this.sent.push(String(body.message))
+ this.detail = 'finished'
+ this.messages.push({ event_id: `e${this.messages.length + 1}`, source: 'devin', message: 'Opened #42. Tests pass.', created_at: '2026-10-11T10:03:00Z' })
+ this.pulls = [{ pr_url: 'https://github.com/acme/api/pull/42', pr_state: 'open' }]
+ return reply({})
+ }
+ if (request.method === 'POST' && url.pathname.endsWith('/archive')) { this.archived += 1; this.status = 'suspended'; this.detail = 'user_request'; return reply(session()) }
+ return reply({ detail: 'not found' }, 404)
+ })
+ })
+ await new Promise<void>((resolve) => this.server!.listen(0, '127.0.0.1', resolve))
+ this.base = `http://127.0.0.1:${(this.server!.address() as { port: number }).port}`
+ return this
+ }
+
+ close(): Promise<void> {
+ return new Promise((resolve) => { if (!this.server) return resolve(); this.server.closeAllConnections(); this.server.close(() => resolve()) })
+ }
+}
+
+const cloudStarts = (d: IsolatedDaemon) => [...d.log().matchAll(/\[harnessd\] service cloud started/g)].length
+
+describe('cloud agents on the real daemon', () => {
+ let daemon: IsolatedDaemon | undefined
+ let devin: FakeDevin | undefined
+ afterEach(async () => {
+ await daemon?.close(); daemon = undefined
+ await devin?.close(); devin = undefined
+ })
+
+ it('a Devin Cloud harness: made, listed with no pane, asked, answered, finished with its pull request, stopped, and watched again after a restart', async () => {
+ const fake = devin = await new FakeDevin().start()
+ const port = await freePort()
+ const d = daemon = await IsolatedDaemon.create({ env: {
+ HARNESS_CONNECTIONS_PORT: String(port), HARNESSD_SERVICE_INITIAL_BACKOFF_MS: '200',
+ // Devin here is the fake: the key is found by where it points, as the person's would be at api.devin.ai.
+ HARNESS_CLOUD_ENDPOINTS: JSON.stringify({ 'devin-cloud': devin.base }),
+ } })
+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-120).join('\n')}\n---- devin saw\n${fake.seen.join('\n')}`) })
+ // The person's Devin key, as `harness connections add-key Devin <url>` saves it: for Harness, never for an agent.
+ const vault = new Store(join(d.root, 'home', '.harness', 'connections'))
+ mkdirSync(vault.root, { recursive: true, mode: 0o700 })
+ vault.save('devin', { access_token: 'cog_e2e', token_type: 'Bearer', source: 'custom', label: 'Devin', transport: 'none', api_entry: { origin: devin.base } })
+ await d.start()
+ const client = await LocalClient.connect(d)
+
+ await until('the services to connect', () => d.log().includes('[services] search connected') || null, 30_000, 200)
+ expect(cloudStarts(d), 'an experiment no one asked for').toBe(0)
+
+ // The question can come within seconds of the harness being made: listened for from before.
+ const asked = client.next((frame: Frame) => frame.type === 'commander_question', 60_000, 'Devin\'s question')
+ const created = await client.request<{ agent?: Record<string, any>; error?: string; detail?: string }>('agent_create', {
+ engine: 'devin-cloud', prompt: 'fix the flaky login test', repositoryUrl: 'https://github.com/acme/api', acuLimit: 2,
+ }, 90_000)
+ expect(created.error, JSON.stringify(created)).toBeUndefined()
+ const agent = created.agent!
+ expect(agent).toMatchObject({ engine: 'devin-cloud', location: 'cloud', tmuxPane: null, terminal: { available: false }, project: { remote: 'https://github.com/acme/api' } })
+ expect(cloudStarts(d)).toBe(1)
+ expect(devin.created).toEqual([{ prompt: 'fix the flaky login test', repos: ['acme/api'], max_acu_limit: 2, title: 'fix the flaky login test' }])
+ // The key went to Devin and nowhere else: the daemon's log never has it.
+ expect(new Set(devin.auth)).toEqual(new Set(['Bearer cog_e2e']))
+ expect(d.log()).not.toContain('cog_e2e')
+
+ const question = await asked
+ expect(question).toMatchObject({ agentId: agent.id, payload: { questions: [{ q: 'Which branch should I base it on?', canText: true }] } })
+ const listed = (await client.request<{ agents: Array<Record<string, any>> }>('agents_list', {})).agents.find((row) => row.id === agent.id)
+ expect(listed).toMatchObject({ location: 'cloud', cloud: { place: "Devin's cloud", state: 'needs_input' } })
+
+ const finished = client.next((frame: Frame) => frame.type === 'agent_synced' && frame.payload?.agent?.id === agent.id && frame.payload.agent.cloud?.state === 'idle', 60_000, 'the harness to finish')
+ // Answered as the dial and the windows answer any agent's question: under the question's own id.
+ const answered = client.next((frame: Frame) => frame.type === 'question_response_result' && frame.payload?.requestId === question.payload.requestId, 30_000, 'the answer\'s result')
+ client.send('question_response', { requestId: question.payload.requestId, agentId: agent.id, answers: { answer: 'main' } })
+ expect((await answered).payload).toMatchObject({ ok: true })
+ expect(devin.sent).toEqual(['main'])
+ const done = (await finished).payload.agent
+ expect(done.cloud.links).toContainEqual({ label: 'Pull request #42', url: 'https://github.com/acme/api/pull/42' })
+
+ const transcript = await client.request<{ messages: Array<{ from: string; text: string }> }>('cloud_transcript', { agentId: agent.id })
+ expect(transcript.messages.map((message) => [message.from, message.text])).toEqual([
+ ['person', 'fix the flaky login test'], ['agent', 'Which branch should I base it on?'], ['person', 'main'], ['agent', 'Opened #42. Tests pass.'],
+ ])
+ expect(await client.request('cloud_send', { agentId: agent.id, text: 'thanks' })).toMatchObject({ ok: true })
+
+ expect(await client.request('agent_delete', { agentId: agent.id })).toMatchObject({ deleted: true })
+ expect(devin.archived).toBe(1)
+
+ // A restart: the saved harness wakes the experiment, and the window lists it again (stopped).
+ client.close()
+ await d.restart()
+ const again = await LocalClient.connect(d)
+ const back = await until('the harness to be listed again', async () =>
+ (await again.request<{ agents: Array<Record<string, any>> }>('agents_list', { includeStopped: true }, 30_000)).agents.find((row) => row.id === agent.id) ?? null, 60_000, 500)
+ expect(back).toMatchObject({ status: 'stopped', location: 'cloud' })
+ again.close()
+ }, 240_000)
+
+ it('a Fo harness: through the bridge\'s MCP address, its reply waited for, its choices asked, and Stop said as Fo has none', async () => {
+ // Fo's MCP server's Fo profile: replies as an event stream, sessions by header, the reply waited for.
+ const calls: Array<{ tool: string; args: Record<string, unknown>; key: string }> = []
+ let replies = 0
+ const fo = createServer((request, response) => {
+ const chunks: Buffer[] = []
+ request.on('data', (chunk) => chunks.push(chunk)).on('end', () => {
+ const message = JSON.parse(Buffer.concat(chunks).toString()) as { id?: number; method: string; params?: { name: string; arguments: Record<string, unknown> } }
+ const send = (result: unknown, headers: Record<string, string> = {}) => response.writeHead(200, { 'content-type': 'text/event-stream', ...headers })
+ .end(`data: ${JSON.stringify({ jsonrpc: '2.0', id: message.id, result })}\n\n`)
+ if (message.method === 'initialize') return send({}, { 'mcp-session-id': 'fo-session' })
+ if (!message.id) return response.writeHead(202).end()
+ if (message.method === 'tools/list') return send({ tools: [
+ { name: 'ask_fo', inputSchema: { properties: { message: { type: 'string' }, conversation_id: { type: 'string' } }, required: ['message'] } },
+ { name: 'get_fo_reply', inputSchema: { properties: { conversation_id: { type: 'string' } } } },
+ ] })
+ calls.push({ tool: message.params!.name, args: message.params!.arguments, key: String(request.headers['x-api-key']) })
+ const text = message.params!.name === 'ask_fo'
+ ? (calls.length === 1 ? { status: 'working', conversation_id: 'c1', message: 'Looking for a barber' } : { status: 'done', reply: 'Booked for 9:30.', conversation_id: 'c1' })
+ : (++replies === 1 ? { status: 'working', message: 'Calling Hair Lab' } : { status: 'done', reply: 'They have two times.\n1) 9:30\n2) 11:00\nWhich one?' })
+ send({ content: [{ type: 'text', text: JSON.stringify(text) }] })
+ })
+ })
+ await new Promise<void>((resolve) => fo.listen(0, '127.0.0.1', resolve))
+ const foBase = `http://127.0.0.1:${(fo.address() as { port: number }).port}`
+ try {
+ const port = await freePort()
+ const d = daemon = await IsolatedDaemon.create({ env: { HARNESS_CONNECTIONS_PORT: String(port), HARNESS_CLOUD_ENDPOINTS: JSON.stringify({ fo: `${foBase}/fo` }) } })
+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-80).join('\n')}\n---- fo saw\n${JSON.stringify(calls)}`) })
+ const vault = new Store(join(d.root, 'home', '.harness', 'connections'))
+ mkdirSync(vault.root, { recursive: true, mode: 0o700 })
+ // As Add custom saves Fo with its key as a header.
+ vault.save('fo', { source: 'custom', label: 'Fo', mcp_entry: { url: `${foBase}/fo`, headers: { 'X-API-Key': 'wak_e2e' } } })
+ await d.start()
+ const client = await LocalClient.connect(d)
+ const asked = client.next((frame: Frame) => frame.type === 'commander_question', 90_000, 'Fo\'s question')
+ const created = await client.request<{ agent?: Record<string, any>; error?: string }>('agent_create', { engine: 'fo', prompt: 'book a haircut saturday morning near me' }, 90_000)
+ expect(created.error, JSON.stringify(created)).toBeUndefined()
+ const agent = created.agent!
+ expect(agent).toMatchObject({ engine: 'fo', location: 'cloud', project: null, cloud: { place: "Fo's cloud" } })
+ const question = await asked
+ expect(question).toMatchObject({ agentId: agent.id, payload: { questions: [{ q: 'They have two times.\n1) 9:30\n2) 11:00\nWhich one?', options: ['9:30', '11:00'] }] } })
+ expect(calls.map((call) => call.tool)).toEqual(['ask_fo', 'get_fo_reply', 'get_fo_reply'])
+ expect(new Set(calls.map((call) => call.key))).toEqual(new Set(['wak_e2e']))
+ const answered = client.next((frame: Frame) => frame.type === 'question_response_result' && frame.payload?.requestId === question.payload.requestId, 30_000, 'the answer\'s result')
+ client.send('question_response', { requestId: question.payload.requestId, agentId: agent.id, answers: { answer: '9:30' } })
+ expect((await answered).payload).toMatchObject({ ok: true })
+ expect(calls.at(-1)).toMatchObject({ tool: 'ask_fo', args: { message: '9:30', conversation_id: 'c1' } })
+ const booked = await until('Fo\'s booking', async () => {
+ const transcript = await client.request<{ messages: Array<{ from: string; text: string }> }>('cloud_transcript', { agentId: agent.id })
+ return transcript.messages.some((message) => message.text === 'Booked for 9:30.') ? transcript : null
+ }, 30_000, 500)
+ expect(booked.messages.map((message) => message.from)).toEqual(['person', 'agent', 'person', 'agent'])
+ expect(await client.request('agent_delete', { agentId: agent.id })).toEqual(expect.objectContaining({ deleted: true, detail: 'Fo keeps working on its own.' }))
+ expect(d.log()).not.toContain('wak_e2e')
+ client.close()
+ } finally {
+ fo.closeAllConnections()
+ fo.close()
+ }
+ }, 240_000)
+
+ it('refuses a cloud agent that is not connected, in words a person reads', async () => {
+ const port = await freePort()
+ const d = daemon = await IsolatedDaemon.create({ env: { HARNESS_CONNECTIONS_PORT: String(port) } })
+ await d.start()
+ const client = await LocalClient.connect(d)
+ const refused = await client.request('agent_create', { engine: 'cursor-cloud', prompt: 'x', repositoryUrl: 'https://github.com/acme/api' }, 90_000)
+ expect(refused).toMatchObject({ error: 'NOT_CONNECTED', detail: expect.stringContaining('harness connections add-key Cursor') })
+ const agents = await client.request<{ agents: Array<{ id: string; name: string; connected: boolean }> }>('cloud_agents', {})
+ expect(agents.agents.map((row) => [row.id, row.connected])).toEqual([['fo', false], ['devin-cloud', false], ['cursor-cloud', false]])
+ client.close()
+ }, 180_000)
+})
diff --git a/cli/src/cloud/adapters.spec.ts b/cli/src/cloud/adapters.spec.ts
new file mode 100644
index 000000000..da92c8bdf
--- /dev/null
+++ b/cli/src/cloud/adapters.spec.ts
@@ -0,0 +1,348 @@
+/**
+ * Each maker's adapter against a fake of its API, shaped as its documentation says: Devin's v3 sessions,
+ * Cursor's v1 agents and runs, and Fo's MCP tools over streamable HTTP. Never a real maker.
+ */
+import { createServer, type IncomingMessage, type Server } from 'node:http'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { connectionFor, connectionsBridge, endpointFor, refusal, type Bridge } from './bridge.js'
+import { cursorAdapter, cursorLinks, cursorState, runResult } from './cursor.js'
+import { DEFAULT_ACU_LIMIT, devinAdapter, devinLinks, devinState } from './devin.js'
+import { foAdapter, questionIn, readReply, wordsParam } from './fo.js'
+import { McpClient, replyTo } from './mcp.js'
+import { CloudError } from './types.js'
+
+const servers: Server[] = []
+afterEach(() => { for (const server of servers.splice(0)) { server.close(); server.closeAllConnections() } })
+
+type Answer = { status?: number; headers?: Record<string, string>; body: string }
+async function serve(handler: (request: IncomingMessage, body: string) => Answer): Promise<string> {
+ const server = createServer((request, response) => {
+ const chunks: Buffer[] = []
+ request.on('data', (chunk) => chunks.push(chunk)).on('end', () => {
+ const answer = handler(request, Buffer.concat(chunks).toString())
+ response.writeHead(answer.status ?? 200, { 'content-type': 'application/json', ...answer.headers }).end(answer.body)
+ })
+ })
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
+ servers.push(server)
+ return `http://127.0.0.1:${(server.address() as { port: number }).port}`
+}
+
+/** A bridge whose API calls the test answers, in order, recording each. */
+function apiBridge(answers: Array<{ status?: number; json: Record<string, unknown> }>) {
+ const calls: Array<[string, string, unknown]> = []
+ const bridge: Bridge = {
+ connections: async () => [],
+ mcpUrl: () => '',
+ api: vi.fn(async (_code, method, path, body) => {
+ calls.push([method, path, body])
+ const next = answers.shift() ?? { json: {} }
+ return { status: next.status ?? 200, json: next.json }
+ }),
+ }
+ return { bridge, calls }
+}
+
+describe('the bridge', () => {
+ it('lists connections and calls an API with nothing of its own to sign', async () => {
+ const seen: string[] = []
+ const base = await serve((request, body) => {
+ seen.push(`${request.method} ${request.url} ${body}`)
+ if (request.url === '/k/connections') return { body: JSON.stringify({ connections: [{ code: 'devin', api: 'https://api.devin.ai', state: 'connected' }] }) }
+ if (request.url === '/k/devin/api/v3/self') return { body: '{"org_id":"org-1"}' }
+ return { status: 500, body: 'not json' }
+ })
+ const bridge = connectionsBridge(() => `${base}/k`)
+ expect(await bridge.connections()).toEqual([{ code: 'devin', api: 'https://api.devin.ai', state: 'connected' }])
+ expect(await bridge.api('devin', 'GET', '/v3/self')).toEqual({ status: 200, json: { org_id: 'org-1' } })
+ expect(await bridge.api('devin', 'POST', '/v3/other', { a: 1 })).toEqual({ status: 500, json: { raw: 'not json' } })
+ expect(seen.at(-1)).toBe('POST /k/devin/api/v3/other {"a":1}')
+ expect(bridge.mcpUrl('fo')).toBe(`${base}/k/fo/mcp`)
+ const down = connectionsBridge(() => `${base}/missing`)
+ await expect(down.connections()).rejects.toThrow('Connections is not running here.')
+ })
+
+ it('finds the connection that signs in each cloud agent by where it points', async () => {
+ const connections = [
+ { code: 'my-fo', name: 'Fo', mcp: 'https://mcp.api.wajo.ai/fo', api: null, state: 'connected' },
+ { code: 'devin', name: 'Devin', mcp: null, api: 'https://api.devin.ai', state: 'reconnect' },
+ ]
+ const bridge = { connections: async () => connections } as unknown as Bridge
+ expect((await connectionFor(bridge, 'fo')).code).toBe('my-fo')
+ await expect(connectionFor(bridge, 'devin-cloud')).rejects.toThrow('needs to be connected again')
+ await expect(connectionFor(bridge, 'cursor-cloud')).rejects.toThrow('add-key Cursor')
+ await expect(connectionFor({ connections: async () => { throw new Error('down') } } as unknown as Bridge, 'fo')).rejects.toThrow('Connections is not running here')
+ })
+
+ it('finds a maker at another address when one is named for it', async () => {
+ const env = { HARNESS_CLOUD_ENDPOINTS: JSON.stringify({ 'devin-cloud': 'http://127.0.0.1:9/x', fo: 'https://fo.example/fo', 'cursor-cloud': 'not a url' }) }
+ expect(endpointFor('devin-cloud', env)).toEqual({ api: 'http://127.0.0.1:9' })
+ expect(endpointFor('fo', env)).toEqual({ mcp: 'fo.example' })
+ expect(endpointFor('cursor-cloud', env)).toEqual({ api: 'https://api.cursor.com' })
+ expect(endpointFor('devin-cloud', { HARNESS_CLOUD_ENDPOINTS: '{' })).toEqual({ api: 'https://api.devin.ai' })
+ expect(endpointFor('devin-cloud', {})).toEqual({ api: 'https://api.devin.ai' })
+ const bridge = { connections: async () => [{ code: 'fake', name: 'Devin', mcp: null, api: 'http://127.0.0.1:9', state: 'connected' }] } as unknown as Bridge
+ expect((await connectionFor(bridge, 'devin-cloud', env)).code).toBe('fake')
+ })
+
+ it('says a maker\'s refusal as a person reads it', () => {
+ expect(refusal('Devin Cloud', 401, {}).code).toBe('NOT_CONNECTED')
+ expect(refusal('Devin Cloud', 409, {}).message).toContain('still working')
+ expect(refusal('Devin Cloud', 429, {}).code).toBe('RATE_LIMITED')
+ expect(refusal('Devin Cloud', 400, { detail: 'bad repo' }).message).toBe('Devin Cloud answered 400: bad repo')
+ expect(refusal('Devin Cloud', 500, { error: { message: 'boom' } }).message).toBe('Devin Cloud answered 500: boom')
+ expect(refusal('Devin Cloud', 500, {}).message).toBe('Devin Cloud answered 500.')
+ })
+})
+
+describe('Devin Cloud', () => {
+ it('reads where a session is as Harness says it', () => {
+ expect(['new', 'claimed', 'resuming'].map((status) => devinState(status, null))).toEqual(['starting', 'starting', 'starting'])
+ expect(devinState('running', 'working')).toBe('working')
+ expect(devinState('running', null)).toBe('working')
+ expect(devinState('running', 'waiting_for_user')).toBe('needs_input')
+ expect(devinState('running', 'waiting_for_approval')).toBe('needs_input')
+ expect(devinState('running', 'finished')).toBe('idle')
+ expect(devinState('exit', null)).toBe('idle')
+ expect(devinState('error', null)).toBe('failed')
+ expect(devinState('suspended', 'user_request')).toBe('stopped')
+ expect(devinState('suspended', 'out_of_credits')).toBe('failed')
+ expect(devinLinks({ url: 'https://app.devin.ai/s/1', pull_requests: [{ pr_url: 'https://github.com/a/b/pull/42' }, { pr_url: 'https://x/y' }, {}] }))
+ .toEqual([{ label: 'Session', url: 'https://app.devin.ai/s/1' }, { label: 'Pull request #42', url: 'https://github.com/a/b/pull/42' }, { label: 'Pull request', url: 'https://x/y' }])
+ })
+
+ it('starts a session in the key\'s organization with a limit, and reads it a page at a time', async () => {
+ const { bridge, calls } = apiBridge([
+ { json: { org_id: 'org-1' } },
+ { json: { session_id: 'devin-9', url: 'https://app.devin.ai/s/9', status: 'new' } },
+ { json: { status: 'running', status_detail: 'waiting_for_user', url: 'https://app.devin.ai/s/9', pull_requests: [] } },
+ { json: { items: [{ event_id: 'e1', source: 'user', message: 'fix it', created_at: 't0' }, { event_id: 'e2', source: 'devin', message: 'Which branch?', created_at: 't1' }], end_cursor: 'c1', has_next_page: true } },
+ { json: { items: [], end_cursor: null, has_next_page: false } },
+ ])
+ const devin = devinAdapter(bridge, async () => 'devin')
+ const started = await devin.start({ task: 'fix it', repository: 'acme/api', options: {} })
+ expect(started).toEqual({ remote: { id: 'devin-9' }, links: [{ label: 'Session', url: 'https://app.devin.ai/s/9' }], update: { messages: [], state: 'starting' } })
+ expect(calls[1]).toEqual(['POST', '/v3/organizations/org-1/sessions', { prompt: 'fix it', repos: ['acme/api'], max_acu_limit: DEFAULT_ACU_LIMIT, title: 'fix it' }])
+ const update = await devin.poll({ id: 'devin-9' })
+ expect(update).toMatchObject({ messages: [{ id: 'e2', text: 'Which branch?', at: 't1' }], state: 'needs_input', question: { text: 'Which branch?', choices: [] }, remote: { cursor: 'c1' } })
+ expect(calls.slice(2).map(([method, path]) => `${method} ${path}`)).toEqual([
+ 'GET /v3/organizations/org-1/sessions/devin-9',
+ 'GET /v3/organizations/org-1/sessions/devin-9/messages?first=100',
+ 'GET /v3/organizations/org-1/sessions/devin-9/messages?first=100&after=c1',
+ ])
+ })
+
+ it('says why a session went to sleep, takes words, archives on Stop, and refuses what Devin refuses', async () => {
+ const { bridge, calls } = apiBridge([
+ { json: { org_id: 'org-1' } },
+ { json: { status: 'suspended', status_detail: 'usage_limit_exceeded' } },
+ { json: { items: [] } },
+ { json: {} },
+ { json: {} },
+ { status: 401, json: {} },
+ ])
+ const devin = devinAdapter(bridge, async () => 'devin')
+ expect(await devin.poll({ id: 'd', cursor: 'c0' })).toMatchObject({ state: 'failed', activity: 'It reached its ACU limit.', question: null, remote: { cursor: 'c0' } })
+ await devin.send({ id: 'd' }, 'go on')
+ await devin.stop!({ id: 'd' })
+ expect(calls.slice(3)).toEqual([['POST', '/v3/organizations/org-1/sessions/d/messages', { message: 'go on' }], ['POST', '/v3/organizations/org-1/sessions/d/archive', undefined]])
+ await expect(devin.poll({ id: 'd' })).rejects.toMatchObject({ code: 'NOT_CONNECTED' })
+ })
+
+ it('refuses a key with no organization, and a session it was not given', async () => {
+ await expect(devinAdapter(apiBridge([{ json: {} }]).bridge, async () => 'd').start({ task: 't', repository: null, options: { acuLimit: 2 } })).rejects.toThrow('refused the key')
+ const { bridge, calls } = apiBridge([{ json: { org_id: 'o' } }, { json: {} }])
+ await expect(devinAdapter(bridge, async () => 'd').start({ task: 't', repository: null, options: { acuLimit: 2 } })).rejects.toThrow('No session was made')
+ expect(calls[1][2]).toEqual({ prompt: 't', max_acu_limit: 2, title: 't' })
+ const waiting = apiBridge([{ json: { org_id: 'o' } }, { json: { status: 'running', status_detail: 'waiting_for_approval' } }, { json: { items: [] } }])
+ // Waiting with nothing new said: the question already asked stands (the service asks one if none was).
+ expect((await devinAdapter(waiting.bridge, async () => 'd').poll({ id: 'x' })).question).toBeUndefined()
+ })
+})
+
+describe('Cursor Cloud', () => {
+ it('reads a run as Harness says it', () => {
+ expect(['CREATING', 'RUNNING', 'FINISHED', 'CANCELLED', 'ERROR', 'EXPIRED', 'OTHER'].map(cursorState)).toEqual(['starting', 'working', 'idle', 'stopped', 'failed', 'failed', 'working'])
+ expect(runResult({ result: 'done' })).toBe('done')
+ expect(runResult({ result: { summary: 'did it' } })).toBe('did it')
+ expect(runResult({})).toBeNull()
+ expect(cursorLinks({ url: 'https://cursor.com/agents/1' }, { git: { prUrl: 'https://github.com/a/b/pull/7' } }))
+ .toEqual([{ label: 'Agent', url: 'https://cursor.com/agents/1' }, { label: 'Pull request #7', url: 'https://github.com/a/b/pull/7' }])
+ expect(cursorLinks({ repos: [{ prUrl: 'https://x/pr' }] }, {})).toEqual([{ label: 'Pull request', url: 'https://x/pr' }])
+ })
+
+ it('starts an agent on a repository, tells a finished run once, and makes a run per follow-up', async () => {
+ const { bridge, calls } = apiBridge([
+ { json: { agent: { id: 'bc-1', url: 'https://cursor.com/agents/bc-1' }, run: { id: 'run-1', status: 'CREATING' } } },
+ { json: { id: 'run-1', status: 'RUNNING' } },
+ { json: { id: 'run-1', status: 'FINISHED', result: 'Fixed it.', git: { branch: 'cursor/fix', prUrl: 'https://github.com/acme/api/pull/3' }, updatedAt: 't2' } },
+ { json: { id: 'bc-1', url: 'https://cursor.com/agents/bc-1' } },
+ { json: { id: 'run-1', status: 'FINISHED', result: 'Fixed it.' } },
+ { json: { id: 'bc-1' } },
+ { json: { run: { id: 'run-2' } } },
+ { json: {} },
+ ])
+ const cursor = cursorAdapter(bridge, async () => 'cursor')
+ const started = await cursor.start({ task: 'fix it', repository: 'acme/api', options: { model: 'composer-2' } })
+ expect(started.remote).toEqual({ id: 'bc-1', run: 'run-1' })
+ expect(calls[0][2]).toEqual({ prompt: { text: 'fix it' }, repos: [{ url: 'https://github.com/acme/api' }], model: { id: 'composer-2' }, autoCreatePR: true })
+ expect(await cursor.poll({ id: 'bc-1', run: 'run-1' })).toEqual({ messages: [], state: 'working', branch: undefined, links: undefined, remote: {} })
+ const finished = await cursor.poll({ id: 'bc-1', run: 'run-1' })
+ expect(finished).toMatchObject({ messages: [{ id: 'run-1-result', text: 'Fixed it.', at: 't2' }], state: 'idle', branch: 'cursor/fix', remote: { cursor: 'run-1' },
+ links: [{ label: 'Agent', url: 'https://cursor.com/agents/bc-1' }, { label: 'Pull request #3', url: 'https://github.com/acme/api/pull/3' }] })
+ expect((await cursor.poll({ id: 'bc-1', run: 'run-1', cursor: 'run-1' })).messages).toEqual([])
+ expect(await cursor.send({ id: 'bc-1' }, 'also tests')).toEqual({ run: 'run-2' })
+ await cursor.stop!({ id: 'bc-1', run: 'run-2' })
+ expect(calls.at(-1)).toEqual(['POST', '/v1/agents/bc-1/runs/run-2/cancel', undefined])
+ expect(await cursor.poll({ id: 'bc-1' })).toEqual({ messages: [] })
+ await cursor.stop!({ id: 'bc-1' })
+ expect(calls).toHaveLength(8)
+ })
+
+ it('refuses an agent it was not given, and a follow-up while busy', async () => {
+ await expect(cursorAdapter(apiBridge([{ json: {} }]).bridge, async () => 'c').start({ task: 't', repository: null, options: {} })).rejects.toThrow('No agent was made')
+ await expect(cursorAdapter(apiBridge([{ status: 409, json: { error: 'agent_busy' } }]).bridge, async () => 'c').send({ id: 'a' }, 'x')).rejects.toMatchObject({ code: 'BUSY' })
+ expect(await cursorAdapter(apiBridge([{ json: {} }]).bridge, async () => 'c').send({ id: 'a' }, 'x')).toEqual({})
+ })
+})
+
+/** Fo's MCP server, as its Fo profile behaves: replies as an event stream, sessions by header. */
+async function fakeFo(script: { ask: Array<Record<string, unknown>>; reply: Array<Record<string, unknown>>; schema?: Record<string, unknown> }) {
+ const calls: Array<{ tool: string; args: Record<string, unknown> }> = []
+ let sessions = 0
+ const base = await serve((request, body): Answer => {
+ const message = JSON.parse(body) as { id?: number; method: string; params?: { name?: string; arguments?: Record<string, unknown> } }
+ if (message.method === 'initialize') return { headers: { 'mcp-session-id': `s${++sessions}` }, body: JSON.stringify({ jsonrpc: '2.0', id: message.id, result: {} }) }
+ if (!message.id) return { status: 202, body: '' }
+ if (request.headers['mcp-session-id'] !== `s${sessions}`) return { status: 404, body: 'session expired' }
+ let result: Record<string, unknown>
+ if (message.method === 'tools/list') {
+ result = { tools: [
+ { name: 'ask_fo', inputSchema: script.schema ?? { properties: { request: { type: 'string' }, conversation_id: { type: 'string' }, newConversation: { type: 'boolean' } }, required: ['request'] } },
+ { name: 'get_fo_reply', inputSchema: { properties: { conversation_id: { type: 'string' }, request_id: { type: 'string' } } } },
+ ] }
+ } else {
+ calls.push({ tool: message.params!.name!, args: message.params!.arguments! })
+ const next = (message.params!.name === 'ask_fo' ? script.ask : script.reply).shift() ?? { status: 'working' }
+ result = { content: [{ type: 'text', text: JSON.stringify(next) }] }
+ }
+ return { headers: { 'content-type': 'text/event-stream' }, body: `: ping\n\nevent: message\ndata: ${JSON.stringify({ jsonrpc: '2.0', id: message.id, result })}\n\n` }
+ })
+ return { base, calls, expire: () => { sessions += 1 } }
+}
+
+describe('Fo', () => {
+ it('reads its tools\' parameters and its replies by what they mean', () => {
+ expect(wordsParam({ name: 'ask_fo', inputSchema: { properties: { Message: { type: 'string' } } } })).toBe('Message')
+ expect(wordsParam({ name: 'ask_fo', inputSchema: { properties: { ask: { type: 'string' } }, required: ['ask'] } })).toBe('ask')
+ expect(wordsParam(undefined)).toBe('message')
+ expect(readReply({ status: 'working', message: 'Calling Hair Lab', request_id: 'r1', conversation: { id: 'c1' } }))
+ .toEqual({ working: true, text: null, ids: { request_id: 'r1', conversation_id: 'c1' }, progress: 'Calling Hair Lab' })
+ expect(readReply({ status: 'done', reply: 'Booked.' })).toMatchObject({ working: false, text: 'Booked.', progress: null })
+ expect(readReply({ text: 'Hi' })).toMatchObject({ working: false, text: 'Hi' })
+ expect(questionIn('They have two times.\n\n1) 9:30\n2) 11:00\n3) neither\n\nWhich one?')).toEqual({ text: 'Which one?', choices: ['9:30', '11:00', 'neither'] })
+ expect(questionIn('Booked for 9:30.')).toBeNull()
+ // A question in Fo's words, with no choices, ends its turn: Fo chats, and most replies end with one.
+ expect(questionIn('Hey! Did that trip ever get a destination?')).toBeNull()
+ expect(questionIn('Which one?\n1) 9:30')).toBeNull()
+ expect(questionIn('Options:\n- a\n- b')).toEqual({ text: 'Options:\n- a\n- b', choices: ['a', 'b'] })
+ })
+
+ it('asks, waits for the reply, and asks the person when Fo does', async () => {
+ const fo = await fakeFo({
+ ask: [{ status: 'working', conversation_id: 'c1', request_id: 'r1', message: 'Looking' }, { status: 'done', reply: 'Booked for 9:30.', conversation_id: 'c1' }],
+ reply: [{ status: 'working', message: 'Calling Hair Lab' }, { status: 'done', reply: 'They have 9:30 or 11:00.\n1) 9:30\n2) 11:00\nWhich one?' }],
+ })
+ const client = new McpClient(`${fo.base}/fo`, 'Fo')
+ const adapter = foAdapter(async () => client, () => new Date('2026-10-11T10:00:00Z'))
+ const started = await adapter.start({ task: 'book a haircut', repository: null, options: {} })
+ expect(started).toEqual({ remote: { id: 'c1', run: '{"request_id":"r1"}' }, links: [], update: { messages: [], state: 'working', activity: 'Looking' } })
+ // A new harness is a new Fo conversation, never the person's current one.
+ expect(fo.calls[0]).toEqual({ tool: 'ask_fo', args: { request: 'book a haircut', newConversation: true } })
+ expect(await adapter.poll(started.remote)).toEqual({ messages: [], state: 'working', activity: 'Calling Hair Lab', waited: true })
+ expect(fo.calls[1]).toEqual({ tool: 'get_fo_reply', args: { conversation_id: 'c1', request_id: 'r1' } })
+ expect(await adapter.poll(started.remote)).toMatchObject({ state: 'needs_input', question: { text: 'They have 9:30 or 11:00.\n1) 9:30\n2) 11:00\nWhich one?', choices: ['9:30', '11:00'] }, remote: { run: undefined } })
+ // An answer Fo gives at once is read on the next look.
+ expect(await adapter.send({ id: 'c1' }, '9:30')).toEqual({ id: 'c1', run: undefined })
+ expect(fo.calls.at(-1)).toEqual({ tool: 'ask_fo', args: { request: '9:30', conversation_id: 'c1' } })
+ expect(adapter.answered!({ id: 'c1' })).toBe(true)
+ expect(await adapter.poll({ id: 'c1' })).toMatchObject({ messages: [{ text: 'Booked for 9:30.' }], state: 'idle', question: null })
+ expect(adapter.answered!({ id: 'c1' })).toBe(false)
+ expect(await adapter.poll({ id: 'c1' })).toEqual({ messages: [] })
+ expect(adapter.stop).toBeUndefined()
+ })
+
+ it('opens a session again when Fo forgot it, and says what failed', async () => {
+ const fo = await fakeFo({ ask: [{ status: 'done', reply: 'Hi' }, { status: 'done', reply: 'Again' }], reply: [], schema: { properties: { message: { type: 'string' } } } })
+ const client = new McpClient(`${fo.base}/fo`, 'Fo')
+ const adapter = foAdapter(async () => client)
+ expect((await adapter.start({ task: 'hello', repository: null, options: {} })).remote).toEqual({ id: 'current' })
+ fo.expire()
+ expect(await adapter.send({ id: 'current' }, 'again')).toEqual({ id: 'current', run: undefined })
+ expect(fo.calls.at(-1)!.args).toEqual({ message: 'again' })
+ })
+
+ it('retries while Fo says its conversation is busy, then says so', async () => {
+ let busy = 2
+ const call = vi.fn(async (tool: string) => {
+ if (tool === 'ask_fo' && busy-- > 0) throw new CloudError('CLOUD_FAILED', 'Fo: ask_fo: session busy with another run, retry')
+ return { status: 'done', reply: 'Blue it is.', conversationId: 'c1' }
+ })
+ const mcp = { tools: async () => [{ name: 'ask_fo', inputSchema: { properties: { message: { type: 'string' }, conversationId: { type: 'string' } } } }], call } as unknown as McpClient
+ const pauses: number[] = []
+ const adapter = foAdapter(async () => mcp, () => new Date(), async (ms) => { pauses.push(ms) })
+ expect(await adapter.send({ id: 'c1' }, 'Blue')).toEqual({ id: 'c1', run: undefined })
+ expect(pauses).toEqual([3_000, 3_000])
+ busy = 100
+ await expect(adapter.send({ id: 'c1' }, 'Blue')).rejects.toMatchObject({ code: 'BUSY', message: 'Fo is still working. Send it again in a moment.' })
+ call.mockImplementationOnce(async () => { throw new CloudError('CLOUD_FAILED', 'Fo: bad args') })
+ busy = 0
+ await expect(adapter.send({ id: 'c1' }, 'Blue')).rejects.toThrow('bad args')
+ })
+
+ it('refuses an MCP server with no ask_fo', async () => {
+ const adapter = foAdapter(async () => ({ tools: async () => [], call: async () => ({}) }) as unknown as McpClient)
+ await expect(adapter.start({ task: 't', repository: null, options: {} })).rejects.toThrow('no ask_fo')
+ const failing = foAdapter(async () => ({ tools: async () => { throw new CloudError('NOT_CONNECTED', 'x') } }) as unknown as McpClient)
+ await expect(failing.start({ task: 't', repository: null, options: {} })).rejects.toThrow('x')
+ })
+})
+
+describe('the MCP client', () => {
+ it('finds its answer in JSON or an event stream', () => {
+ expect(replyTo(2, 'application/json', '{"jsonrpc":"2.0","id":2,"result":{}}')).toEqual({ jsonrpc: '2.0', id: 2, result: {} })
+ expect(replyTo(2, 'text/event-stream', 'data: {"id":1}\n\ndata: {"id":2,"result":{"a":1}}\n\n')).toEqual({ id: 2, result: { a: 1 } })
+ expect(replyTo(2, 'application/json', 'nope')).toBeNull()
+ })
+
+ it('says a refused connection, an error and a failed tool as a person reads them', async () => {
+ let mode = 'ok'
+ const base = await serve((_request, body) => {
+ const message = JSON.parse(body) as { id?: number; method: string }
+ if (mode === 'refused') return { status: 401, body: '' }
+ if (mode === 'missing') return { status: 404, body: '{"error":{"message":"Fo is not connected."}}' }
+ if (mode === 'broken') return { status: 500, body: '' }
+ if (message.method === 'initialize' || !message.id) return { body: JSON.stringify({ jsonrpc: '2.0', id: message.id, result: {} }) }
+ if (mode === 'error') return { body: JSON.stringify({ jsonrpc: '2.0', id: message.id, error: { message: 'bad args' } }) }
+ if (mode === 'tool') return { body: JSON.stringify({ jsonrpc: '2.0', id: message.id, result: { isError: true, content: [{ type: 'text', text: 'no such conversation' }] } }) }
+ if (mode === 'structured') return { body: JSON.stringify({ jsonrpc: '2.0', id: message.id, result: { structuredContent: { reply: 'hi' }, content: [] } }) }
+ return { body: JSON.stringify({ jsonrpc: '2.0', id: message.id, result: { content: [{ type: 'text', text: 'plain words' }] } }) }
+ })
+ const client = new McpClient(base, 'Fo')
+ expect(await client.call('ask_fo', {})).toEqual({ text: 'plain words' })
+ expect(await client.tools()).toEqual([])
+ mode = 'structured'
+ expect(await client.call('ask_fo', {})).toEqual({ reply: 'hi' })
+ mode = 'tool'
+ await expect(client.call('ask_fo', {})).rejects.toThrow('Fo: no such conversation')
+ mode = 'error'
+ await expect(client.call('ask_fo', {})).rejects.toThrow('Fo: bad args')
+ mode = 'broken'
+ await expect(client.call('ask_fo', {})).rejects.toThrow('Fo answered 500.')
+ for (const [given, said] of [['refused', 'connected again'], ['missing', 'not connected']]) {
+ mode = given
+ await expect(new McpClient(base, 'Fo').tools()).rejects.toThrow(said)
+ }
+ await expect(new McpClient('http://127.0.0.1:1/', 'Fo').tools()).rejects.toThrow('could not be reached')
+ })
+})
diff --git a/cli/src/cloud/bridge.ts b/cli/src/cloud/bridge.ts
new file mode 100644
index 000000000..73af6409f
--- /dev/null
+++ b/cli/src/cloud/bridge.ts
@@ -0,0 +1,82 @@
+/**
+ * The cloud service's way to its makers: the Connections bridge (lib/connectors/bridge.ts), which adds each
+ * connection's credential, so this service holds none (services/AGENTS.md, "Do not hold credentials").
+ * A connection is found by where it points (Fo's MCP server, Devin's API), not by what the person named it.
+ */
+import { bridgePort, harnessKey } from '../lib/connectors/agents.js'
+import { Store } from '../lib/connectors/store.js'
+import { CLOUD_AGENTS, type CloudAgentId } from '../lib/cloudAgents.js'
+import { CloudError } from './types.js'
+
+export interface Connection { code: string; name: string; mcp: string | null; api: string | null; state: string }
+
+export interface Bridge {
+ connections(): Promise<Connection[]>
+ /** The bridge's MCP address for a connection. */
+ mcpUrl(code: string): string
+ /** One call to a key-only connection's API, as JSON. A non-2xx status is the answer, not a throw. */
+ api(code: string, method: string, path: string, body?: unknown, timeoutMs?: number): Promise<{ status: number; json: Record<string, unknown> }>
+}
+
+/** Through Harness's own key (agents.ts `harnessKey`), never the one in the agents' configurations. */
+export function connectionsBridge(base: () => string = () => `http://127.0.0.1:${bridgePort()}/${harnessKey(new Store())}`): Bridge {
+ return {
+ async connections() {
+ const answer = await fetch(`${base()}/connections`, { signal: AbortSignal.timeout(10_000) })
+ if (!answer.ok) throw new CloudError('CONNECTIONS_UNAVAILABLE', 'Connections is not running here.')
+ const body = await answer.json() as { connections?: unknown }
+ return Array.isArray(body.connections) ? body.connections as Connection[] : []
+ },
+ mcpUrl: (code) => `${base()}/${code}/mcp`,
+ async api(code, method, path, body, timeoutMs = 30_000) {
+ const answer = await fetch(`${base()}/${code}/api${path}`, {
+ method,
+ headers: { accept: 'application/json', ...(body === undefined ? {} : { 'content-type': 'application/json' }) },
+ body: body === undefined ? undefined : JSON.stringify(body),
+ signal: AbortSignal.timeout(timeoutMs),
+ })
+ const raw = await answer.text()
+ let json: Record<string, unknown> = {}
+ try { json = raw ? JSON.parse(raw) as Record<string, unknown> : {} } catch { json = { raw: raw.slice(0, 500) } }
+ return { status: answer.status, json }
+ },
+ }
+}
+
+/**
+ * Where a cloud agent's maker is: its own address, or another named in `HARNESS_CLOUD_ENDPOINTS` (JSON, by
+ * agent id): a test's fake, or an organization's own host for the maker.
+ */
+export function endpointFor(agent: CloudAgentId, env: NodeJS.ProcessEnv = process.env): { mcp: string } | { api: string } {
+ const want = CLOUD_AGENTS[agent].connection
+ let moved: unknown
+ try { moved = (JSON.parse(env.HARNESS_CLOUD_ENDPOINTS ?? '{}') as Record<string, unknown>)[agent] } catch { moved = undefined }
+ if (typeof moved !== 'string') return want
+ try {
+ const url = new URL(moved)
+ return 'mcp' in want ? { mcp: url.host } : { api: url.origin }
+ } catch { return want }
+}
+
+/** The connection that signs in a cloud agent, or why there is none. */
+export async function connectionFor(bridge: Bridge, agent: CloudAgentId, env: NodeJS.ProcessEnv = process.env): Promise<Connection> {
+ const want = endpointFor(agent, env)
+ let connections: Connection[]
+ try { connections = await bridge.connections() } catch { throw new CloudError('CONNECTIONS_UNAVAILABLE', 'Connections is not running here. Try again in a moment.') }
+ const found = connections.find((connection) => 'mcp' in want
+ ? !!connection.mcp && new URL(connection.mcp).host === want.mcp
+ : connection.api === want.api)
+ if (!found) throw new CloudError('NOT_CONNECTED', CLOUD_AGENTS[agent].connect)
+ if (found.state === 'reconnect') throw new CloudError('NOT_CONNECTED', `${found.name} needs to be connected again in Connections.`)
+ return found
+}
+
+/** A maker's refusal, said as the person reads it, with a status the service can act on. */
+export function refusal(name: string, status: number, json: Record<string, unknown>): CloudError {
+ const said = [json.detail, json.message, json.error, (json.error as Record<string, unknown> | undefined)?.message]
+ .find((value): value is string => typeof value === 'string' && value.length > 0)
+ if (status === 401 || status === 403) return new CloudError('NOT_CONNECTED', `${name} refused the key. Connect it again in Connections.`)
+ if (status === 409) return new CloudError('BUSY', `${name} is still working. Send it again once it stops.`)
+ if (status === 429) return new CloudError('RATE_LIMITED', `${name} is busy. Try again in a minute.`)
+ return new CloudError('CLOUD_FAILED', `${name} answered ${status}${said ? `: ${said.slice(0, 200)}` : '.'}`)
+}
diff --git a/cli/src/cloud/cursor.ts b/cli/src/cloud/cursor.ts
new file mode 100644
index 000000000..62e3a1c57
--- /dev/null
+++ b/cli/src/cloud/cursor.ts
@@ -0,0 +1,92 @@
+/**
+ * Cursor Cloud, through Cursor's Cloud Agents API v1 (public beta, cursor.com/docs/cloud-agent/api): an
+ * agent per harness on a GitHub repository, and a run per message (`POST /v1/agents` makes the first,
+ * `POST /v1/agents/{id}/runs` each follow-up; one at a time, `409 agent_busy` otherwise). A run is read
+ * by its status; its `result` is what the agent said. Stop cancels the run in flight.
+ */
+import { CLOUD_AGENTS, type CloudState } from '../lib/cloudAgents.js'
+import { refusal, type Bridge } from './bridge.js'
+import type { CloudAdapter, CloudLink, CloudUpdate } from './types.js'
+
+const NAME = CLOUD_AGENTS['cursor-cloud'].name
+type Json = Record<string, unknown>
+const str = (value: unknown): string | null => (typeof value === 'string' && value.trim() ? value.trim() : null)
+
+export function cursorState(status: unknown): CloudState {
+ switch (status) {
+ case 'CREATING': return 'starting'
+ case 'RUNNING': return 'working'
+ case 'FINISHED': return 'idle'
+ case 'CANCELLED': return 'stopped'
+ case 'ERROR': case 'EXPIRED': return 'failed'
+ default: return 'working'
+ }
+}
+
+/** What a run said: its result as text, or the text a result object carries. */
+export function runResult(run: Json): string | null {
+ const result = run.result
+ if (str(result)) return str(result)
+ const value = (result && typeof result === 'object' ? result : {}) as Json
+ return str(value.text) ?? str(value.summary) ?? str(value.message) ?? str(value.output) ?? null
+}
+
+export function cursorLinks(agent: Json, run: Json): CloudLink[] {
+ const links: CloudLink[] = []
+ if (str(agent.url)) links.push({ label: 'Agent', url: str(agent.url)! })
+ const git = (run.git && typeof run.git === 'object' ? run.git : {}) as Json
+ const pr = str(git.prUrl) ?? str(git.pullRequestUrl) ?? str((agent.repos as Json[] | undefined)?.[0]?.prUrl)
+ if (pr) links.push({ label: `Pull request #${/\/pull\/(\d+)/.exec(pr)?.[1] ?? ''}`.replace(/ #$/, ''), url: pr })
+ return links
+}
+
+export function cursorAdapter(bridge: Bridge, code: () => Promise<string>): CloudAdapter {
+ const call = async (method: string, path: string, body?: unknown): Promise<Json> => {
+ const answer = await bridge.api(await code(), method, path, body)
+ if (answer.status >= 300) throw refusal(NAME, answer.status, answer.json)
+ return answer.json
+ }
+ const runOf = (answer: Json): Json => (answer.run && typeof answer.run === 'object' ? answer.run as Json : answer)
+
+ return {
+ id: 'cursor-cloud',
+ async start(request) {
+ const answer = await call('POST', '/v1/agents', {
+ prompt: { text: request.task },
+ ...(request.repository ? { repos: [{ url: `https://github.com/${request.repository}` }] } : {}),
+ ...(request.options.model ? { model: { id: request.options.model } } : {}),
+ autoCreatePR: true,
+ })
+ const agent = (answer.agent && typeof answer.agent === 'object' ? answer.agent : answer) as Json
+ const run = runOf(answer)
+ const id = str(agent.id)
+ if (!id) throw refusal(NAME, 502, { detail: 'No agent was made.' })
+ return { remote: { id, ...(str(run.id) ? { run: str(run.id)! } : {}) }, links: cursorLinks(agent, run), update: { messages: [], state: cursorState(run.status ?? 'CREATING') } }
+ },
+ async send(remote, text) {
+ const run = runOf(await call('POST', `/v1/agents/${encodeURIComponent(remote.id)}/runs`, { prompt: { text } }))
+ return str(run.id) ? { run: str(run.id)! } : {}
+ },
+ async poll(remote): Promise<CloudUpdate> {
+ if (!remote.run) return { messages: [] }
+ const agentPath = `/v1/agents/${encodeURIComponent(remote.id)}`
+ const run = await call('GET', `${agentPath}/runs/${encodeURIComponent(remote.run)}`)
+ const state = cursorState(run.status)
+ const said = runResult(run)
+ // A run's result is read once, when it ends: the cursor remembers the run already told.
+ const told = remote.cursor === remote.run
+ const messages = state !== 'working' && state !== 'starting' && said && !told ? [{ id: `${remote.run}-result`, text: said, at: str(run.updatedAt) ?? new Date().toISOString() }] : []
+ const git = (run.git && typeof run.git === 'object' ? run.git : {}) as Json
+ return {
+ messages,
+ state,
+ branch: str(git.branch) ?? str(git.branchName) ?? undefined,
+ links: state === 'working' ? undefined : cursorLinks(await call('GET', agentPath), run),
+ remote: state === 'working' || state === 'starting' ? {} : { cursor: remote.run },
+ }
+ },
+ async stop(remote) {
+ if (remote.run) await call('POST', `/v1/agents/${encodeURIComponent(remote.id)}/runs/${encodeURIComponent(remote.run)}/cancel`)
+ },
+ }
+}
diff --git a/cli/src/cloud/devin.ts b/cli/src/cloud/devin.ts
new file mode 100644
index 000000000..80d8949c2
--- /dev/null
+++ b/cli/src/cloud/devin.ts
@@ -0,0 +1,105 @@
+/**
+ * Devin Cloud, through Devin's v3 API (docs.devin.ai/api-reference): a session per harness in the
+ * organization the key belongs to (`GET /v3/self`), read by its status and its messages, every few seconds
+ * while someone watches. `status` + `status_detail` say where it is: `running`/`working`, waiting on the
+ * person (`waiting_for_user`, `waiting_for_approval`), `finished`, or `suspended` (asleep: Stop archives
+ * it, and a message wakes it). It bills ACUs while it works, so every session gets a limit.
+ */
+import { CLOUD_AGENTS, type CloudState } from '../lib/cloudAgents.js'
+import { refusal, type Bridge } from './bridge.js'
+import type { CloudAdapter, CloudLink, CloudUpdate, Remote } from './types.js'
+
+const NAME = CLOUD_AGENTS['devin-cloud'].name
+/** A first session's limit when the person sets none: enough for a small fix, never a runaway bill. */
+export const DEFAULT_ACU_LIMIT = 5
+
+type Json = Record<string, unknown>
+const str = (value: unknown): string | null => (typeof value === 'string' && value ? value : null)
+
+/** Where a session is, as Harness says it. */
+export function devinState(status: unknown, detail: unknown): CloudState {
+ if (status === 'new' || status === 'claimed' || status === 'resuming') return 'starting'
+ if (status === 'error') return 'failed'
+ if (status === 'suspended') return detail === 'inactivity' || detail === 'user_request' ? 'stopped' : 'failed'
+ if (status === 'exit') return 'idle'
+ if (detail === 'waiting_for_user' || detail === 'waiting_for_approval') return 'needs_input'
+ if (detail === 'finished') return 'idle'
+ return 'working'
+}
+
+const SUSPENDED: Record<string, string> = {
+ usage_limit_exceeded: 'It reached its ACU limit.', out_of_credits: 'The Devin account is out of credits.', out_of_quota: 'The Devin account is out of quota.',
+ payment_declined: 'Devin declined the payment.', org_usage_limit_exceeded: 'The organization reached its ACU limit.',
+}
+
+export function devinLinks(session: Json): CloudLink[] {
+ const links: CloudLink[] = []
+ if (str(session.url)) links.push({ label: 'Session', url: str(session.url)! })
+ for (const pr of Array.isArray(session.pull_requests) ? session.pull_requests as Json[] : []) {
+ const url = str(pr.pr_url)
+ if (url) links.push({ label: `Pull request #${/\/pull\/(\d+)/.exec(url)?.[1] ?? ''}`.replace(/ #$/, ''), url })
+ }
+ return links
+}
+
+export function devinAdapter(bridge: Bridge, code: () => Promise<string>): CloudAdapter {
+ let org: string | null = null
+
+ const call = async (method: string, path: string, body?: unknown): Promise<Json> => {
+ const answer = await bridge.api(await code(), method, path, body)
+ if (answer.status >= 300) throw refusal(NAME, answer.status, answer.json)
+ return answer.json
+ }
+ const base = async (): Promise<string> => {
+ org ??= str((await call('GET', '/v3/self')).org_id)
+ if (!org) throw refusal(NAME, 403, { detail: 'The key belongs to no organization.' })
+ return `/v3/organizations/${encodeURIComponent(org)}/sessions`
+ }
+
+ return {
+ id: 'devin-cloud',
+ async start(request) {
+ const session = await call('POST', await base(), {
+ prompt: request.task,
+ ...(request.repository ? { repos: [request.repository] } : {}),
+ max_acu_limit: request.options.acuLimit ?? DEFAULT_ACU_LIMIT,
+ title: request.task.slice(0, 80),
+ })
+ const id = str(session.session_id)
+ if (!id) throw refusal(NAME, 502, { detail: 'No session was made.' })
+ return { remote: { id }, links: devinLinks(session), update: { messages: [], state: devinState(session.status, session.status_detail) } }
+ },
+ async send(remote, text) {
+ await call('POST', `${await base()}/${encodeURIComponent(remote.id)}/messages`, { message: text })
+ },
+ async poll(remote: Remote): Promise<CloudUpdate> {
+ const path = `${await base()}/${encodeURIComponent(remote.id)}`
+ const session = await call('GET', path)
+ const messages: CloudUpdate['messages'] = []
+ let cursor = remote.cursor
+ // A page at a time, at most five: a session read for the first time in a while catches up over a few looks.
+ for (let page = 0; page < 5; page++) {
+ const read = await call('GET', `${path}/messages?first=100${cursor ? `&after=${encodeURIComponent(cursor)}` : ''}`)
+ for (const item of Array.isArray(read.items) ? read.items as Json[] : []) {
+ if (item.source === 'devin' && str(item.message)) messages.push({ id: str(item.event_id) ?? `${path}-${messages.length}`, text: str(item.message)!, at: str(item.created_at) ?? new Date().toISOString() })
+ }
+ cursor = str(read.end_cursor) ?? cursor
+ if (read.has_next_page !== true) break
+ }
+ const state = devinState(session.status, session.status_detail)
+ const lastWords = messages.at(-1)?.text ?? null
+ return {
+ messages,
+ state,
+ activity: session.status === 'suspended' ? SUSPENDED[String(session.status_detail)] ?? null : null,
+ // Asked from Devin's newest words; with none new, the question already asked stands (cloud/service.ts).
+ question: state !== 'needs_input' ? null : lastWords ? { text: lastWords.slice(0, 500), choices: [] } : undefined,
+ links: devinLinks(session),
+ remote: { cursor },
+ }
+ },
+ async stop(remote) {
+ await call('POST', `${await base()}/${encodeURIComponent(remote.id)}/archive`)
+ },
+ }
+}
diff --git a/cli/src/cloud/fo.ts b/cli/src/cloud/fo.ts
new file mode 100644
index 000000000..42097da7e
--- /dev/null
+++ b/cli/src/cloud/fo.ts
@@ -0,0 +1,132 @@
+/**
+ * Fo (Wajo), a personal agent that runs errands, through its MCP server's Fo profile
+ * (https://mcp.api.wajo.ai/fo): `ask_fo` sends the person's words and answers at once or with
+ * `status: "working"`, and `get_fo_reply` waits up to 40 s for the reply (wajo.ai/docs/mcp-tools.md).
+ *
+ * Wajo publishes what the tools do but not their parameters' names, so they are read from `tools/list` on
+ * first use and filled by what they mean: the person's words, the conversation, the pending reply. A reply
+ * that lists choices waits on the person, with those choices; one that only ends with a question is a turn
+ * ended, as Claude Code's is. Fo cannot be stopped from here: it keeps working on its own.
+ */
+import { CLOUD_AGENTS } from '../lib/cloudAgents.js'
+import type { McpClient, McpTool } from './mcp.js'
+import { CloudError, type CloudAdapter, type CloudUpdate, type Remote } from './types.js'
+
+const NAME = CLOUD_AGENTS.fo.name
+const WORDS = ['message', 'request', 'text', 'prompt', 'query', 'content', 'task', 'input']
+const REPLY = ['reply', 'text', 'message', 'response', 'answer', 'content', 'result']
+
+const props = (tool: McpTool | undefined): Record<string, { type?: string }> => tool?.inputSchema?.properties ?? {}
+const str = (value: unknown): string | null => (typeof value === 'string' && value.trim() ? value.trim() : null)
+
+/** The parameter that takes the person's words: one named for them, else the first required string. */
+export function wordsParam(tool: McpTool | undefined): string {
+ const names = Object.keys(props(tool))
+ return names.find((name) => WORDS.includes(name.toLowerCase()))
+ ?? (tool?.inputSchema?.required ?? []).find((name) => props(tool)[name]?.type === 'string')
+ ?? 'message'
+}
+
+/** A reply as Fo gave it: whether it is still working, its words, and every id it named. */
+export function readReply(result: Record<string, unknown>): { working: boolean; text: string | null; ids: Record<string, string>; progress: string | null } {
+ const ids: Record<string, string> = {}
+ for (const [key, value] of Object.entries(result)) if (/id$/i.test(key) && str(value)) ids[key] = str(value)!
+ const conversation = result.conversation as Record<string, unknown> | undefined
+ if (conversation && str(conversation.id)) ids.conversation_id ??= str(conversation.id)!
+ const status = str(result.status)?.toLowerCase() ?? ''
+ const working = ['working', 'pending', 'in_progress', 'running'].includes(status)
+ // While working, what it says is progress, not its reply: only an explicit `reply` is one.
+ const text = working ? str(result.reply) : REPLY.map((key) => str(result[key])).find(Boolean) ?? null
+ return { working, text,
+ ids, progress: str(result.progress) ?? str(result.activity) ?? (working ? str(result.message) ?? str(result.text) : null) }
+}
+
+/**
+ * A reply that offers choices: the paragraph that asks, and the choices it lists (up to six). Only choices make
+ * it a question. Fo chats, and most of its replies end with one ("Did that trip ever get a destination?"):
+ * as questions they lit its pane amber after every turn (2026-10-11), where a Claude Code turn that ends
+ * with a question in its words is simply over.
+ */
+export function questionIn(text: string): { text: string; choices: string[] } | null {
+ const paragraphs = text.trim().split(/\n\s*\n/)
+ const choices = text.split('\n').map((line) => /^\s*(?:\d+[.)]|[-•])\s+(.{1,60})\s*$/.exec(line)?.[1]?.trim()).filter((choice): choice is string => !!choice).slice(0, 6)
+ if (choices.length < 2) return null
+ const asking = paragraphs.find((paragraph) => /\?\s*$/.test(paragraph.trim()))
+ return { text: (asking ?? paragraphs[0]).trim().slice(0, 500), choices }
+}
+
+/** A refusal Fo asks to be retried: its conversation is still finishing the run that just replied (2026-10-11:
+ * an answer sent a second after Fo's question was refused "session busy with another run, retry"). */
+const BUSY = /session busy|busy with another run|retry/i
+
+export function foAdapter(client: () => Promise<McpClient>, now: () => Date = () => new Date(),
+ pause: (ms: number) => Promise<void> = (ms) => new Promise((resolve) => setTimeout(resolve, ms))): CloudAdapter {
+ let schema: Promise<Map<string, McpTool>> | null = null
+ /** A reply Fo gave at once, kept for the next look. */
+ const ready = new Map<string, string>()
+
+ const tools = (): Promise<Map<string, McpTool>> => {
+ schema ??= client().then((mcp) => mcp.tools()).then((list) => new Map(list.map((tool) => [tool.name, tool])))
+ .catch((error) => { schema = null; throw error })
+ return schema
+ }
+
+ /** `ask_fo`, with the conversation named when there is one to continue, and a fresh one asked for when not:
+ * by default Fo continues the person's current conversation, which a new harness must not land in. */
+ const ask = async (text: string, conversation: string | null): Promise<{ remote: Remote; reply: ReturnType<typeof readReply> }> => {
+ const known = await tools()
+ const askTool = known.get('ask_fo')
+ if (!askTool) throw new CloudError('CLOUD_FAILED', `${NAME}'s MCP server has no ask_fo. Connect https://mcp.api.wajo.ai/fo.`)
+ const args: Record<string, unknown> = { [wordsParam(askTool)]: text }
+ const conversationParam = Object.keys(props(askTool)).find((name) => /conversation/i.test(name) && props(askTool)[name]?.type === 'string')
+ const freshParam = Object.keys(props(askTool)).find((name) => /^new/i.test(name) && props(askTool)[name]?.type === 'boolean')
+ if (conversation && conversationParam) args[conversationParam] = conversation
+ else if (!conversation && freshParam) args[freshParam] = true
+ let reply: ReturnType<typeof readReply> | null = null
+ // Retried while Fo says its conversation is busy, for up to half a minute; then the person is told.
+ for (let attempt = 0; !reply; attempt++) {
+ try {
+ reply = readReply(await (await client()).call('ask_fo', args, 60_000))
+ } catch (error) {
+ if (!(error instanceof CloudError) || !BUSY.test(error.message) || attempt >= 9) {
+ throw error instanceof CloudError && BUSY.test(error.message) ? new CloudError('BUSY', `${NAME} is still working. Send it again in a moment.`) : error
+ }
+ await pause(3_000)
+ }
+ }
+ const id = reply.ids.conversation_id ?? reply.ids.conversationId ?? conversation ?? 'current'
+ const pending = Object.fromEntries(Object.entries(reply.ids).filter(([key]) => !/conversation/i.test(key)))
+ if (!reply.working && reply.text) ready.set(id, reply.text)
+ return { remote: { id, ...(reply.working ? { run: JSON.stringify(pending) } : {}) }, reply }
+ }
+
+ const answered = (text: string): CloudUpdate => {
+ const question = questionIn(text)
+ return { messages: [{ id: `fo-${now().getTime()}`, text, at: now().toISOString() }], state: question ? 'needs_input' : 'idle',
+ question, activity: null, remote: { run: undefined } }
+ }
+
+ return {
+ id: 'fo',
+ async start(request) {
+ const { remote, reply } = await ask(request.task, null)
+ return { remote, links: [], update: reply.working ? { messages: [], state: 'working', activity: reply.progress } : undefined }
+ },
+ async send(remote, text) {
+ const { remote: next } = await ask(text, remote.id === 'current' ? null : remote.id)
+ return { ...next, run: next.run }
+ },
+ async poll(remote, signal) {
+ const waiting = ready.get(remote.id)
+ if (waiting) { ready.delete(remote.id); return answered(waiting) }
+ if (!remote.run) return { messages: [] }
+ const replyTool = (await tools()).get('get_fo_reply')
+ const known: Record<string, string> = { ...JSON.parse(remote.run) as Record<string, string>, conversation_id: remote.id, conversationId: remote.id }
+ const args = Object.fromEntries(Object.keys(props(replyTool)).flatMap((name) => (known[name] ? [[name, known[name]]] : [])))
+ const reply = readReply(await (await client()).call('get_fo_reply', args, 60_000, signal))
+ if (reply.working || !reply.text) return { messages: [], state: 'working', activity: reply.progress, waited: true }
+ return answered(reply.text)
+ },
+ answered: (remote) => ready.has(remote.id),
+ }
+}
diff --git a/cli/src/cloud/mcp.ts b/cli/src/cloud/mcp.ts
new file mode 100644
index 000000000..57019e8df
--- /dev/null
+++ b/cli/src/cloud/mcp.ts
@@ -0,0 +1,99 @@
+/**
+ * The smallest MCP client the cloud agents need: initialize, list tools, call one, over streamable HTTP
+ * (a reply is JSON or an event stream). Written here rather than taken from the SDK, which brings zod into
+ * the process (leanEntry.spec.ts) for three requests.
+ */
+import { CloudError } from './types.js'
+
+const PROTOCOL = '2025-06-18'
+
+export interface McpTool { name: string; inputSchema?: { properties?: Record<string, { type?: string }>; required?: string[] } }
+
+/** The JSON-RPC message answering `id` in a reply, JSON or an event stream. */
+export function replyTo(id: number, contentType: string, body: string): Record<string, unknown> | null {
+ const candidates: string[] = contentType.includes('text/event-stream')
+ ? body.split(/\r?\n\r?\n/).map((event) => event.split(/\r?\n/).filter((line) => line.startsWith('data:')).map((line) => line.slice(5).trimStart()).join('\n')).filter(Boolean)
+ : [body]
+ for (const candidate of candidates) {
+ try {
+ const message = JSON.parse(candidate) as Record<string, unknown>
+ if (message.id === id) return message
+ } catch { /* Not JSON: a keep-alive or a comment. */ }
+ }
+ return null
+}
+
+export class McpClient {
+ private session: string | null = null
+ private ready: Promise<void> | null = null
+ private next = 1
+
+ constructor(private readonly url: string, private readonly name: string) {}
+
+ private async post(message: Record<string, unknown>, timeoutMs: number, signal?: AbortSignal): Promise<{ status: number; type: string; body: string; session: string | null }> {
+ const timeout = AbortSignal.timeout(timeoutMs)
+ const answer = await fetch(this.url, {
+ method: 'POST',
+ headers: {
+ accept: 'application/json, text/event-stream', 'content-type': 'application/json', 'mcp-protocol-version': PROTOCOL,
+ ...(this.session ? { 'mcp-session-id': this.session } : {}),
+ },
+ body: JSON.stringify(message),
+ signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
+ }).catch(() => { throw new CloudError('UNREACHABLE', `${this.name} could not be reached. Try again.`) })
+ return { status: answer.status, type: answer.headers.get('content-type') ?? '', body: await answer.text(), session: answer.headers.get('mcp-session-id') }
+ }
+
+ private initialize(): Promise<void> {
+ this.ready ??= (async () => {
+ const id = this.next++
+ const answer = await this.post({ jsonrpc: '2.0', id, method: 'initialize', params: { protocolVersion: PROTOCOL, capabilities: {}, clientInfo: { name: 'Harness', version: '1' } } }, 20_000)
+ this.check(answer.status, answer.body)
+ this.session = answer.session
+ await this.post({ jsonrpc: '2.0', method: 'notifications/initialized' }, 20_000)
+ })().catch((error) => { this.ready = null; throw error })
+ return this.ready
+ }
+
+ private check(status: number, body: string): void {
+ if (status === 401 || status === 403) throw new CloudError('NOT_CONNECTED', `${this.name} needs to be connected again in Connections.`)
+ if (status === 404 && /not connected/i.test(body)) throw new CloudError('NOT_CONNECTED', `${this.name} is not connected. Connect it in Connections.`)
+ if (status >= 400) throw new CloudError('CLOUD_FAILED', `${this.name} answered ${status}.`)
+ }
+
+ /** One request, after initializing; a session the server forgot (404) is opened again, once. */
+ async request(method: string, params: Record<string, unknown>, timeoutMs = 30_000, signal?: AbortSignal, again = true): Promise<Record<string, unknown>> {
+ await this.initialize()
+ const id = this.next++
+ const answer = await this.post({ jsonrpc: '2.0', id, method, params }, timeoutMs, signal)
+ if (answer.status === 404 && this.session && again) {
+ this.session = null
+ this.ready = null
+ return this.request(method, params, timeoutMs, signal, false)
+ }
+ this.check(answer.status, answer.body)
+ const reply = replyTo(id, answer.type, answer.body)
+ const error = reply?.error as { message?: unknown } | undefined
+ if (!reply || error) throw new CloudError('CLOUD_FAILED', `${this.name}: ${typeof error?.message === 'string' ? error.message.slice(0, 200) : 'no answer.'}`)
+ return (reply.result ?? {}) as Record<string, unknown>
+ }
+
+ async tools(): Promise<McpTool[]> {
+ const result = await this.request('tools/list', {})
+ return Array.isArray(result.tools) ? result.tools as McpTool[] : []
+ }
+
+ /** A tool's result, as JSON when its text is JSON, else `{ text }`. */
+ async call(tool: string, args: Record<string, unknown>, timeoutMs = 30_000, signal?: AbortSignal): Promise<Record<string, unknown>> {
+ const result = await this.request('tools/call', { name: tool, arguments: args }, timeoutMs, signal)
+ const text = (Array.isArray(result.content) ? result.content as { type?: string; text?: string }[] : [])
+ .filter((part) => part.type === 'text' && typeof part.text === 'string').map((part) => part.text).join('\n')
+ if (result.isError === true) throw new CloudError('CLOUD_FAILED', `${this.name}: ${text.slice(0, 300) || 'the request failed.'}`)
+ if (result.structuredContent && typeof result.structuredContent === 'object') return result.structuredContent as Record<string, unknown>
+ try {
+ const parsed = JSON.parse(text) as unknown
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed as Record<string, unknown>
+ } catch { /* Plain text: the answer itself. */ }
+ return { text }
+ }
+}
diff --git a/cli/src/cloud/service.spec.ts b/cli/src/cloud/service.spec.ts
new file mode 100644
index 000000000..1dc4c30c1
--- /dev/null
+++ b/cli/src/cloud/service.spec.ts
@@ -0,0 +1,463 @@
+/**
+ * The cloud service against scripted makers: never a real Fo, Devin or Cursor, and a throwaway data folder.
+ */
+import { mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import type { CloudCore } from '../core/api.js'
+import type { CloudHarness } from '../lib/cloudAgents.js'
+import type { Bridge } from './bridge.js'
+import { nameFor, repositoryOf, startCloudService } from './service.js'
+import { CloudError, type CloudAdapter, type CloudUpdate } from './types.js'
+
+const owner = { local: true, owner: true }
+let dataDir: string
+let clock: number
+let timers: Map<number, { fn: () => void; ms: number }>
+let nextTimer: number
+let doors: { publish: ReturnType<typeof vi.fn>; ask: ReturnType<typeof vi.fn>; unask: ReturnType<typeof vi.fn> }
+
+beforeEach(() => {
+ dataDir = mkdtempSync(join(tmpdir(), 'cloud-'))
+ clock = Date.parse('2026-10-11T10:00:00Z')
+ timers = new Map()
+ nextTimer = 1
+ doors = { publish: vi.fn(), ask: vi.fn(), unask: vi.fn() }
+})
+afterEach(() => rmSync(dataDir, { recursive: true, force: true }))
+
+/** A maker whose answers the test scripts, one look at a time. */
+function maker(over: Partial<CloudAdapter> = {}) {
+ const looks: CloudUpdate[] = []
+ const adapter: CloudAdapter & { looks: CloudUpdate[] } = {
+ id: 'devin-cloud',
+ looks,
+ start: vi.fn(async () => ({ remote: { id: 'devin-1' }, links: [{ label: 'Session', url: 'https://app.devin.ai/sessions/1' }] })),
+ send: vi.fn(async () => {}),
+ poll: vi.fn(async () => looks.shift() ?? { messages: [] }),
+ stop: vi.fn(async () => {}),
+ ...over,
+ }
+ return adapter
+}
+
+const bridge = (connections: unknown[] = []): Bridge => ({
+ connections: vi.fn(async () => connections as never),
+ mcpUrl: (code) => `http://bridge/${code}/mcp`,
+ api: vi.fn(async () => ({ status: 200, json: {} })),
+})
+
+function start(adapters: Record<string, CloudAdapter>, given = bridge()) {
+ return startCloudService({
+ dataDir, core: doors as unknown as CloudCore, bridge: given, adapters: adapters as never,
+ now: () => clock,
+ setTimer: (fn, ms) => { const id = nextTimer++; timers.set(id, { fn, ms }); return id },
+ clearTimer: (id) => { timers.delete(id as number) },
+ log: () => {},
+ })
+}
+
+/** Runs every timer due now, as many times as it takes, then lets the looks settle. */
+async function tick(): Promise<void> {
+ for (let round = 0; round < 5; round++) {
+ const due = [...timers.entries()]
+ timers.clear()
+ for (const [, timer] of due) timer.fn()
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ }
+}
+
+const published = (): CloudHarness[] => doors.publish.mock.calls.at(-1)![0] as CloudHarness[]
+
+describe('names and repositories', () => {
+ it('reads a repository from a GitHub address or the pair', () => {
+ expect(repositoryOf('https://github.com/acme/api')).toBe('acme/api')
+ expect(repositoryOf('https://github.com/acme/api.git')).toBe('acme/api')
+ expect(repositoryOf('[email protected]:acme/api.git')).toBe('acme/api')
+ expect(repositoryOf('acme/api')).toBe('acme/api')
+ expect(repositoryOf('https://gitlab.com/acme/api')).toBeNull()
+ expect(repositoryOf(3)).toBeNull()
+ })
+
+ it('names a harness by its task\'s first line, short', () => {
+ expect(nameFor('\n fix the flaky login test\nmore', 'devin-cloud')).toBe('fix the flaky login test')
+ expect(nameFor('a'.repeat(60), 'fo')).toHaveLength(40)
+ expect(nameFor(' ', 'fo')).toBe('Fo')
+ })
+})
+
+describe('a cloud harness', () => {
+ it('starts on its maker, is told to the core, and keeps its conversation', async () => {
+ const devin = maker()
+ const service = start({ 'devin-cloud': devin })
+ const made = await service.port.create({ engine: 'devin-cloud', prompt: 'fix the flaky login test', repositoryUrl: 'https://github.com/acme/api', acuLimit: 3 })
+ expect(made.ok).toBe(true)
+ expect(devin.start).toHaveBeenCalledWith({ task: 'fix the flaky login test', repository: 'acme/api', options: { acuLimit: 3, model: undefined } })
+ const harness = published()[0]
+ expect(harness).toMatchObject({ agent: 'devin-cloud', name: 'fix the flaky login test', state: 'working', repository: 'acme/api', messages: 1,
+ links: [{ label: 'Session', url: 'https://app.devin.ai/sessions/1' }] })
+ expect(made.ok && made.agent).toMatchObject({ id: harness.agentId, location: 'cloud', engine: 'devin-cloud' })
+ expect(service.transcript(harness.agentId)).toEqual([{ id: expect.any(String), from: 'person', text: 'fix the flaky login test', at: expect.any(String) }])
+ const saved = JSON.parse(readFileSync(join(dataDir, 'cloud', 'harnesses.json'), 'utf8'))
+ expect(saved.harnesses[0]).toMatchObject({ remote: { id: 'devin-1' }, harness: { agentId: harness.agentId } })
+ })
+
+ it('refuses what it cannot start, in words a person reads', async () => {
+ const devin = maker({ start: vi.fn(async () => { throw new CloudError('NOT_CONNECTED', 'Add your Devin API key') }) })
+ const service = start({ 'devin-cloud': devin, fo: maker({ id: 'fo', start: vi.fn(async () => { throw new Error('boom') }) }) })
+ expect(await service.port.create({ engine: 'claude', prompt: 'x' })).toMatchObject({ ok: false, error: 'INVALID_ENGINE' })
+ expect(await service.port.create({ engine: 'devin-cloud', prompt: ' ' })).toMatchObject({ ok: false, error: 'INVALID_REQUEST' })
+ expect(await service.port.create({ engine: 'devin-cloud', prompt: 'x' })).toMatchObject({ ok: false, detail: expect.stringContaining('GitHub repository') })
+ expect(await service.port.create({ engine: 'devin-cloud', prompt: 'x', repository: 'acme/api' })).toEqual({ ok: false, error: 'NOT_CONNECTED', detail: 'Add your Devin API key' })
+ expect(await service.port.create({ engine: 'fo', prompt: 'x' })).toEqual({ ok: false, error: 'CLOUD_FAILED', detail: 'Fo could not be reached. Try again.' })
+ expect(doors.publish).not.toHaveBeenCalled()
+ })
+
+ it('reads what its maker says, asks the person when it waits, and stops looking once idle', async () => {
+ const devin = maker()
+ const service = start({ 'devin-cloud': devin })
+ await service.port.create({ engine: 'devin-cloud', prompt: 'fix it', repository: 'acme/api', name: 'login fix' })
+ const agentId = published()[0].agentId
+ expect(published()[0].name).toBe('login fix')
+ devin.looks.push(
+ { messages: [{ id: 'm1', text: 'Found a race.', at: '2026-10-11T10:01:00Z' }], state: 'working', activity: 'Reading code' },
+ { messages: [{ id: 'm1', text: 'Found a race.', at: '2026-10-11T10:01:00Z' }, { id: 'm2', text: 'Which branch?', at: '2026-10-11T10:02:00Z' }], state: 'needs_input', question: { text: 'Which branch?', choices: ['main', 'dev'] } },
+ )
+ await tick()
+ expect(published()[0]).toMatchObject({ state: 'needs_input', activity: 'Reading code', messages: 3 })
+ expect(doors.ask).toHaveBeenCalledWith(agentId, expect.stringMatching(/^cloud_q_/), { text: 'Which branch?', choices: ['main', 'dev'] })
+ const requestId = doors.ask.mock.calls[0][1] as string
+ // A waiting harness is looked at less often.
+ expect([...timers.values()].at(-1)?.ms).toBe(30_000)
+
+ expect(await service.port.answer(agentId, 'cloud_q_stale', { answer: 'main' })).toMatchObject({ ok: false, error: 'STALE_QUESTION' })
+ expect(await service.port.answer(agentId, requestId, { answer: 'main' })).toEqual({ ok: true })
+ expect(devin.send).toHaveBeenCalledWith({ id: 'devin-1' }, 'main')
+ expect(doors.unask).toHaveBeenCalledWith(agentId, requestId)
+ expect(published()[0]).toMatchObject({ state: 'working', messages: 4 })
+
+ devin.looks.push({ messages: [{ id: 'm3', text: 'Opened #42.', at: '2026-10-11T10:05:00Z' }], state: 'idle', links: [{ label: 'Pull request #42', url: 'https://github.com/acme/api/pull/42' }], branch: 'devin/fix' })
+ await tick()
+ expect(published()[0]).toMatchObject({ state: 'idle', branch: 'devin/fix', links: [{ label: 'Pull request #42', url: 'https://github.com/acme/api/pull/42' }] })
+ expect(timers.size).toBe(0)
+ expect(service.transcript(agentId).map((message) => [message.from, message.text])).toEqual([
+ ['person', 'fix it'], ['agent', 'Found a race.'], ['agent', 'Which branch?'], ['person', 'main'], ['agent', 'Opened #42.'],
+ ])
+ })
+
+ it('says why it cannot reach its maker and looks again later', async () => {
+ const devin = maker({ poll: vi.fn(async () => { throw new CloudError('RATE_LIMITED', 'Devin Cloud is busy.') }) })
+ const fo = maker({ id: 'fo', poll: vi.fn(async () => { throw new Error('socket') }) })
+ const service = start({ 'devin-cloud': devin, fo })
+ await service.port.create({ engine: 'devin-cloud', prompt: 'fix it', repository: 'acme/api' })
+ await tick()
+ expect(published()[0].activity).toBe('Devin Cloud is busy.')
+ expect([...timers.values()][0].ms).toBeGreaterThan(10_000)
+ await service.port.create({ engine: 'fo', prompt: 'book a haircut' })
+ await tick()
+ expect(published().find((harness) => harness.agent === 'fo')!.activity).toBe('Fo could not be reached.')
+ })
+
+ it('takes words and refuses them when its maker does', async () => {
+ const devin = maker()
+ const service = start({ 'devin-cloud': devin })
+ await service.port.create({ engine: 'devin-cloud', prompt: 'fix it', repository: 'acme/api' })
+ const agentId = published()[0].agentId
+ expect(await service.port.deliver('cloud_none', 'hi')).toMatchObject({ ok: false, error: 'UNKNOWN_AGENT' })
+ expect(await service.port.deliver(agentId, ' ')).toMatchObject({ ok: false, error: 'INVALID_REQUEST' })
+ devin.send = vi.fn(async () => ({ run: 'run-2' }))
+ expect(await service.requests.cloud_send!({ agentId, text: 'also the tests' }, owner)).toEqual({ ok: true })
+ devin.send = vi.fn(async () => { throw new CloudError('BUSY', 'Devin Cloud is still working.') })
+ expect(await service.requests.cloud_send!({ agentId, text: 'more' }, owner)).toEqual({ error: 'BUSY', detail: 'Devin Cloud is still working.' })
+ expect(await service.requests.cloud_send!({ agentId, text: 'more' }, { local: false, owner: false })).toEqual({ error: 'OWNER_REQUIRED' })
+ const saved = JSON.parse(readFileSync(join(dataDir, 'cloud', 'harnesses.json'), 'utf8'))
+ expect(saved.harnesses[0].remote).toEqual({ id: 'devin-1', run: 'run-2' })
+ })
+
+ it('stops it where its maker can, and says so where it cannot', async () => {
+ const devin = maker()
+ const fo = maker({ id: 'fo', stop: undefined })
+ const service = start({ 'devin-cloud': devin, fo })
+ await service.port.create({ engine: 'devin-cloud', prompt: 'fix it', repository: 'acme/api' })
+ await service.port.create({ engine: 'fo', prompt: 'book a haircut' })
+ const [devinId, foId] = published().map((harness) => harness.agentId)
+ expect(await service.port.stopHarness(devinId)).toEqual({ ok: true })
+ expect(devin.stop).toHaveBeenCalledWith({ id: 'devin-1' })
+ expect(await service.port.stopHarness(foId)).toEqual({ ok: true, detail: 'Fo keeps working on its own.' })
+ expect(published().map((harness) => [harness.state, harness.activity])).toEqual([['stopped', null], ['stopped', 'Fo keeps working on its own.']])
+ expect(await service.port.stopHarness('cloud_none')).toMatchObject({ ok: false, error: 'UNKNOWN_AGENT' })
+ devin.stop = vi.fn(async () => { throw new CloudError('CLOUD_FAILED', 'Devin Cloud answered 500.') })
+ expect(await service.port.stopHarness(devinId)).toEqual({ ok: false, error: 'CLOUD_FAILED', detail: 'Devin Cloud answered 500.' })
+ })
+
+ it('renames one in Harness alone, and keeps the name', async () => {
+ const devin = maker()
+ const service = start({ 'devin-cloud': devin })
+ await service.port.create({ engine: 'devin-cloud', prompt: 'fix it', repository: 'acme/api' })
+ const [{ agentId, updatedAt }] = published()
+ expect(await service.port.rename(agentId, ' Login flake ')).toEqual({ ok: true })
+ expect(published()[0]).toMatchObject({ name: 'Login flake', updatedAt })
+ expect(JSON.parse(readFileSync(join(dataDir, 'cloud', 'harnesses.json'), 'utf8')).harnesses[0].harness.name).toBe('Login flake')
+ expect(await service.port.rename(agentId, ' ')).toMatchObject({ ok: false, error: 'MISSING_NAME' })
+ expect(await service.port.rename('cloud_none', 'x')).toMatchObject({ ok: false, error: 'UNKNOWN_AGENT' })
+ })
+
+ it('keeps what it said last for the dial, and finds it in the conversation of a harness saved before it did', async () => {
+ const devin = maker()
+ const first = start({ 'devin-cloud': devin })
+ await first.port.create({ engine: 'devin-cloud', prompt: 'fix it', repository: 'acme/api' })
+ expect(published()[0].said).toBeUndefined()
+ devin.looks.push({ messages: [{ id: 'm1', text: 'Opened #42.', at: 'x' }], state: 'idle' })
+ await tick()
+ expect(published()[0].said).toBe('Opened #42.')
+ first.stop()
+ const file = join(dataDir, 'cloud', 'harnesses.json')
+ const saved = JSON.parse(readFileSync(file, 'utf8'))
+ delete saved.harnesses[0].harness.said
+ writeFileSync(file, JSON.stringify(saved))
+ start({ 'devin-cloud': devin }).republish()
+ expect(published()[0].said).toBe('Opened #42.')
+ // Nothing said at all: nothing to find.
+ saved.harnesses[0].harness.said = null
+ writeFileSync(file, JSON.stringify(saved))
+ rmSync(join(dataDir, 'cloud', `${saved.harnesses[0].harness.agentId}.jsonl`))
+ start({ 'devin-cloud': devin }).republish()
+ expect(published()[0].said).toBeNull()
+ })
+
+ it('is watched again after a restart, and tells a reconnected core everything again', async () => {
+ const devin = maker()
+ const first = start({ 'devin-cloud': devin })
+ await first.port.create({ engine: 'devin-cloud', prompt: 'fix it', repository: 'acme/api' })
+ devin.looks.push({ messages: [], state: 'needs_input', question: { text: 'Which branch?', choices: [] } })
+ await tick()
+ first.stop()
+ expect(timers.size).toBe(0)
+ // Nothing more is told once stopped.
+ const told = doors.publish.mock.calls.length
+ first.republish()
+ expect(doors.publish.mock.calls.length).toBe(told)
+
+ doors.publish.mockClear()
+ doors.ask.mockClear()
+ // Still waiting and nothing new said: what it asks is what it last said, asked once.
+ devin.looks.push({ messages: [], state: 'needs_input' }, { messages: [], state: 'needs_input' })
+ const second = start({ 'devin-cloud': devin })
+ expect([...timers.values()][0].ms).toBe(1_000)
+ await tick()
+ expect(doors.ask).toHaveBeenCalledTimes(1)
+ expect(doors.ask.mock.calls[0][2]).toEqual({ text: 'Devin Cloud is waiting for you.', choices: [] })
+ second.republish()
+ expect(doors.publish).toHaveBeenCalled()
+ expect(doors.ask).toHaveBeenCalledTimes(2)
+ second.stop()
+ })
+
+ it('reads a saved file that is broken or half-written as nothing it cannot use', () => {
+ mkdirSync(join(dataDir, 'cloud'), { recursive: true })
+ writeFileSync(join(dataDir, 'cloud', 'harnesses.json'), JSON.stringify({ harnesses: [null, { harness: { agentId: 'cloud_x', agent: 'nope' }, remote: { id: 'r' } }, { harness: { agentId: 'cloud_y', agent: 'fo', state: 'idle' }, remote: {} }] }))
+ writeFileSync(join(dataDir, 'cloud', 'cloud_x.jsonl'), 'not json\n{"id":"a","from":"agent","text":"hi","at":"x"}\n')
+ const service = start({})
+ expect(timers.size).toBe(0)
+ service.republish()
+ expect(published()).toEqual([])
+ expect(service.transcript('cloud_x')).toEqual([{ id: 'a', from: 'agent', text: 'hi', at: 'x' }])
+ })
+
+ it('asks what it last said when it waits with nothing new and nothing asked', async () => {
+ const devin = maker()
+ const service = start({ 'devin-cloud': devin })
+ await service.port.create({ engine: 'devin-cloud', prompt: 'fix it', repository: 'acme/api' })
+ devin.looks.push({ messages: [{ id: 'm1', text: 'Shall I also update the docs?', at: 'x' }], state: 'working' }, { messages: [], state: 'needs_input' })
+ await tick()
+ clock += 1
+ for (const [, timer] of timers) timer.fn()
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ expect(doors.ask.mock.calls.at(-1)![2]).toEqual({ text: 'Shall I also update the docs?', choices: [] })
+ service.stop()
+ })
+
+ it('stops looking at one unchanged for a day', async () => {
+ const devin = maker()
+ const service = start({ 'devin-cloud': devin })
+ await service.port.create({ engine: 'devin-cloud', prompt: 'fix it', repository: 'acme/api' })
+ clock += 25 * 60 * 60_000
+ await tick()
+ expect(devin.poll).not.toHaveBeenCalled()
+ expect(timers.size).toBe(0)
+ service.stop()
+ })
+
+ it('looks again at once when its maker waited for news itself (Fo)', async () => {
+ const fo = maker({ id: 'fo', start: vi.fn(async () => ({ remote: { id: 'c1', run: '{}' }, links: [], update: { messages: [], state: 'working' as const, waited: true } })) })
+ const service = start({ fo })
+ await service.port.create({ engine: 'fo', prompt: 'book a haircut' })
+ expect([...timers.values()][0].ms).toBe(0)
+ fo.looks.push({ messages: [], state: 'working', waited: true })
+ await tick()
+ expect(fo.poll).toHaveBeenCalled()
+ service.stop()
+ })
+})
+
+describe('what the review found', () => {
+ it('cuts a long wait short when the person writes, rather than queueing their words behind it', async () => {
+ let aborted = false
+ const fo = maker({ id: 'fo', poll: vi.fn((_remote, signal?: AbortSignal) => new Promise<CloudUpdate>((resolve, reject) => {
+ signal?.addEventListener('abort', () => { aborted = true; reject(new Error('aborted')) })
+ })) })
+ const service = start({ fo })
+ await service.port.create({ engine: 'fo', prompt: 'book a haircut' })
+ const agentId = published()[0].agentId
+ for (const [, timer] of timers) timer.fn()
+ timers.clear()
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ expect(await service.port.deliver(agentId, 'make it 10')).toEqual({ ok: true })
+ expect(aborted).toBe(true)
+ // Cut short is not a failure: nothing says it could not be reached.
+ expect(published()[0].activity).toBeNull()
+ service.stop()
+ })
+
+ it('is working from the moment the words go, and back where it was when they are refused', async () => {
+ let release: () => void = () => {}
+ const devin = maker()
+ const service = start({ 'devin-cloud': devin })
+ await service.port.create({ engine: 'devin-cloud', prompt: 'fix it', repository: 'acme/api' })
+ devin.looks.push({ messages: [{ id: 'm1', text: 'Done.', at: 'x' }], state: 'idle', activity: null })
+ await tick()
+ const agentId = published()[0].agentId
+ expect(published()[0].state).toBe('idle')
+ // Fo answers its `ask_fo` with its whole reply: the person sees it working all that time.
+ devin.send = vi.fn(() => new Promise<void>((resolve) => { release = resolve }))
+ const sent = service.port.deliver(agentId, 'and the docs')
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ expect(published()[0]).toMatchObject({ state: 'working', activity: null })
+ release()
+ expect(await sent).toEqual({ ok: true })
+ expect([...timers.values()].map((timer) => timer.ms)).toEqual([2_000])
+ devin.looks.push({ messages: [{ id: 'm2', text: 'Docs too.', at: 'x' }], state: 'idle', activity: 'Finished' })
+ await tick()
+ devin.send = vi.fn(async () => { throw new CloudError('BUSY', 'Devin Cloud is still working.') })
+ expect(await service.port.deliver(agentId, 'more')).toMatchObject({ ok: false, error: 'BUSY' })
+ expect(published()[0]).toMatchObject({ state: 'idle', activity: 'Finished' })
+ // Not saved while it was only told.
+ expect(JSON.parse(readFileSync(join(dataDir, 'cloud', 'harnesses.json'), 'utf8')).harnesses[0].harness.state).toBe('idle')
+ service.stop()
+ })
+
+ it('reads a reply that came with the words at once, not after the wait', async () => {
+ let ready = true
+ const fo = maker({ id: 'fo', answered: () => ready })
+ const service = start({ fo })
+ await service.port.create({ engine: 'fo', prompt: 'weather in New York?' })
+ expect([...timers.values()].map((timer) => timer.ms)).toEqual([0])
+ fo.looks.push({ messages: [{ id: 'f1', text: 'Rain, 15°C.', at: 'x' }], state: 'idle' })
+ await tick()
+ expect(await service.port.deliver(published()[0].agentId, 'and tomorrow?')).toEqual({ ok: true })
+ expect([...timers.values()].map((timer) => timer.ms)).toEqual([0])
+ ready = false
+ expect(await service.port.deliver(published()[0].agentId, 'and Sunday?')).toEqual({ ok: true })
+ expect([...timers.values()].map((timer) => timer.ms)).toEqual([2_000])
+ service.stop()
+ })
+
+ it('never looks again at once at a maker that answered at once', async () => {
+ const fo = maker({ id: 'fo' })
+ const service = start({ fo })
+ await service.port.create({ engine: 'fo', prompt: 'book a haircut' })
+ fo.looks.push({ messages: [], state: 'working', waited: true })
+ const due = [...timers.values()]
+ timers.clear()
+ for (const timer of due) timer.fn()
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ expect([...timers.values()].map((timer) => timer.ms)).toEqual([5_000])
+ service.stop()
+ })
+
+ it('takes a question\'s answer once, and asks it again when the maker did not take it', async () => {
+ const devin = maker()
+ const service = start({ 'devin-cloud': devin })
+ await service.port.create({ engine: 'devin-cloud', prompt: 'fix it', repository: 'acme/api' })
+ const agentId = published()[0].agentId
+ devin.looks.push({ messages: [{ id: 'm1', text: 'Which branch?', at: 'x' }], state: 'needs_input', question: { text: 'Which branch?', choices: ['main'] } })
+ await tick()
+ const requestId = doors.ask.mock.calls[0][1] as string
+ const [first, second] = await Promise.all([service.port.answer(agentId, requestId, { answer: 'main' }), service.port.answer(agentId, requestId, { answer: 'main' })])
+ expect([first.ok, second.ok]).toEqual([true, false])
+ expect(devin.send).toHaveBeenCalledTimes(1)
+ // Refused by the maker: the question stands again, under a new id.
+ devin.looks.push({ messages: [{ id: 'm2', text: 'And the tests?', at: 'x' }], state: 'needs_input', question: { text: 'And the tests?', choices: [] } })
+ await tick()
+ const again = doors.ask.mock.calls.at(-1)![1] as string
+ devin.send = vi.fn(async () => { throw new CloudError('BUSY', 'Devin Cloud is still working.') })
+ expect(await service.port.answer(agentId, again, { answer: 'yes' })).toMatchObject({ ok: false, error: 'BUSY' })
+ expect(doors.ask.mock.calls.at(-1)![2]).toEqual({ text: 'And the tests?', choices: [] })
+ service.stop()
+ })
+
+ it('does not ask again the wait the person just answered', async () => {
+ const devin = maker()
+ const service = start({ 'devin-cloud': devin })
+ await service.port.create({ engine: 'devin-cloud', prompt: 'fix it', repository: 'acme/api' })
+ const agentId = published()[0].agentId
+ devin.looks.push({ messages: [{ id: 'm1', text: 'Which branch?', at: 'x' }], state: 'needs_input', question: { text: 'Which branch?', choices: [] } })
+ await tick()
+ await service.port.answer(agentId, doors.ask.mock.calls[0][1] as string, { answer: 'main' })
+ doors.ask.mockClear()
+ // Devin has not caught up: still "waiting for you", nothing new said.
+ devin.looks.push({ messages: [], state: 'needs_input' })
+ await tick()
+ expect(doors.ask).not.toHaveBeenCalled()
+ expect(published()[0].state).toBe('working')
+ service.stop()
+ })
+
+ it('makes one harness for one New Harness, however often the window asks', async () => {
+ let release!: () => void
+ const devin = maker({ start: vi.fn(() => new Promise((resolve) => { release = () => resolve({ remote: { id: 'd1' }, links: [] }) })) as never })
+ const service = start({ 'devin-cloud': devin })
+ const request = { engine: 'devin-cloud', prompt: 'fix it', repository: 'acme/api', creationId: 'c-1' }
+ const first = service.port.create(request)
+ const retried = service.port.create(request)
+ release()
+ const [a, b] = await Promise.all([first, retried])
+ expect(devin.start).toHaveBeenCalledTimes(1)
+ expect(a.ok && b.ok && a.agent.id === b.agent.id).toBe(true)
+ const later = await service.port.create(request)
+ expect(later.ok && a.ok && later.agent.id === a.agent.id).toBe(true)
+ expect(published()).toHaveLength(1)
+ service.stop()
+ })
+})
+
+describe('what the apps ask', () => {
+ it('reads a harness\'s conversation, from where the pane has read to', async () => {
+ const devin = maker()
+ const service = start({ 'devin-cloud': devin })
+ await service.port.create({ engine: 'devin-cloud', prompt: 'fix it', repository: 'acme/api' })
+ const agentId = published()[0].agentId
+ devin.looks.push({ messages: [{ id: 'm1', text: 'On it.', at: 'x' }], state: 'working' })
+ await tick()
+ expect(await service.requests.cloud_transcript!({ agentId }, owner)).toMatchObject({ total: 2, messages: [{ from: 'person' }, { from: 'agent', text: 'On it.' }] })
+ expect(await service.requests.cloud_transcript!({ agentId, after: 1 }, owner)).toMatchObject({ total: 2, messages: [{ text: 'On it.' }] })
+ expect(await service.requests.cloud_transcript!({ agentId: 'cloud_none' }, owner)).toEqual({ error: 'UNKNOWN_AGENT' })
+ expect(await service.requests.cloud_transcript!({ agentId }, { local: false, owner: false })).toEqual({ error: 'OWNER_REQUIRED' })
+ service.stop()
+ })
+
+ it('says which cloud agents are connected here, and how to connect the others', async () => {
+ const service = start({}, bridge([{ code: 'fo', name: 'Fo', mcp: 'https://mcp.api.wajo.ai/fo', api: null, state: 'connected' }]))
+ const answer = await service.requests.cloud_agents!({}, owner) as { agents: Array<Record<string, unknown>> }
+ expect(answer.agents).toEqual([
+ { id: 'fo', name: 'Fo', place: "Fo's cloud", kind: 'personal', connected: true },
+ { id: 'devin-cloud', name: 'Devin Cloud', place: "Devin's cloud", kind: 'coding', connected: false, connect: expect.stringContaining('add-key Devin') },
+ { id: 'cursor-cloud', name: 'Cursor Cloud', place: "Cursor's cloud", kind: 'coding', connected: false, connect: expect.stringContaining('add-key Cursor') },
+ ])
+ expect(await service.requests.cloud_agents!({}, { local: false, owner: false })).toEqual({ error: 'OWNER_REQUIRED' })
+ })
+})
diff --git a/cli/src/cloud/service.ts b/cli/src/cloud/service.ts
new file mode 100644
index 000000000..1ede7eca1
--- /dev/null
+++ b/cli/src/cloud/service.ts
@@ -0,0 +1,407 @@
+/**
+ * Cloud agents (docs/design/2026-10-11-cloud-agents.md): harnesses that run on their maker's servers. This
+ * service owns them. It starts one through its adapter, keeps its conversation, looks at the maker while it
+ * works, and tells the core every change (`core.cloud`), which lists them with the terminal agents and puts
+ * their questions in front of the person.
+ *
+ * - Its harnesses and their makers' ids are in `<data>/cloud/harnesses.json`, and each conversation in
+ * `<data>/cloud/<agentId>.jsonl`: the core's experiment start finds the first and wakes this service.
+ * - It looks every 10 s while one works, 30 s while it waits on the person, and not at all once it is idle,
+ * stopped or failed, until the person writes to it. Fo's reply is a long wait of its own (`waited`).
+ * - Nothing here holds a credential: each call goes through the Connections bridge (cloud/bridge.ts).
+ */
+import { randomBytes } from 'node:crypto'
+import { appendFileSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import type { CloudCore, CloudPort, CloudResult, ServiceRequests } from '../core/api.js'
+import { CLOUD_AGENT_IDS, CLOUD_AGENTS, SAID_MAX, cloudAgentFrame, isCloudAgent, type CloudAgentId, type CloudHarness } from '../lib/cloudAgents.js'
+import { connectionFor, connectionsBridge, type Bridge } from './bridge.js'
+import { cursorAdapter } from './cursor.js'
+import { devinAdapter } from './devin.js'
+import { foAdapter } from './fo.js'
+import { McpClient } from './mcp.js'
+import { CloudError, type CloudAdapter, type CloudUpdate, type Remote } from './types.js'
+
+interface Entry {
+ harness: CloudHarness
+ remote: Remote
+ question: { requestId: string; text: string; choices: string[] } | null
+ /** When it last changed: one unchanged for a day is no longer looked at. */
+ changedAt: number
+ failures: number
+ /** Whether the agent has said anything since the person last wrote: until it has, a maker still reporting
+ * "waiting for you" is reporting the wait the person just answered (core rule 6, evidence newer than state). */
+ heard: boolean
+ /** The New Harness that made it (`creationId`): a retry of the same one gets this harness, never a second. */
+ creationId?: string
+}
+
+export interface TranscriptMessage { id: string; from: 'agent' | 'person'; text: string; at: string }
+
+export interface CloudServiceOptions {
+ dataDir: string
+ core: CloudCore
+ bridge?: Bridge
+ /** Swapped in tests for fakes of the makers. */
+ adapters?: Partial<Record<CloudAgentId, CloudAdapter>>
+ now?: () => number
+ setTimer?: (fn: () => void, ms: number) => unknown
+ clearTimer?: (timer: unknown) => void
+ log?: (line: string) => void
+}
+
+const WORKING_MS = 10_000
+const WAITING_MS = 30_000
+const BACKOFF_MAX_MS = 5 * 60_000
+const QUIET_MS = 24 * 60 * 60_000
+/** The least time between looks, even for a maker that waits for news itself: one that answers at once must
+ * never be asked again at once, for a day. */
+const LOOK_MIN_MS = 5_000
+const TRANSCRIPT_MAX = 500
+
+/** `owner/name` from a GitHub address or the pair itself, or null. */
+export function repositoryOf(value: unknown): string | null {
+ if (typeof value !== 'string') return null
+ const match = /^(?:https:\/\/github\.com\/|git@github\.com:)?([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/.exec(value.trim())
+ return match ? `${match[1]}/${match[2]}` : null
+}
+
+/** A harness's name from its task: its first line, short. */
+export function nameFor(task: string, agent: CloudAgentId): string {
+ const line = task.split('\n').map((part) => part.trim()).find(Boolean) ?? ''
+ return line ? (line.length > 40 ? `${line.slice(0, 39).trimEnd()}…` : line) : CLOUD_AGENTS[agent].name
+}
+
+export function startCloudService(options: CloudServiceOptions) {
+ const now = options.now ?? Date.now
+ const setTimer = options.setTimer ?? ((fn: () => void, ms: number) => setTimeout(fn, ms).unref())
+ const clearTimer = options.clearTimer ?? ((timer: unknown) => clearTimeout(timer as ReturnType<typeof setTimeout>))
+ const log = options.log ?? ((line: string) => console.log(line))
+ const bridge = options.bridge ?? connectionsBridge()
+ const dir = join(options.dataDir, 'cloud')
+ const stateFile = join(dir, 'harnesses.json')
+ const entries = new Map<string, Entry>()
+ const timers = new Map<string, unknown>()
+ /** One thing at a time per harness: a look and a message never cross. */
+ const queues = new Map<string, Promise<unknown>>()
+ /** The look in flight, by harness: the person's words cut short a long wait (Fo's reply waits 40 s) rather
+ * than queue behind it. */
+ const looking = new Map<string, AbortController>()
+ const interrupt = (agentId: string): void => { looking.get(agentId)?.abort() }
+ let stopped = false
+
+ // Each maker's connection, found by where it points, for a minute at a time; a refusal finds it again.
+ const codes = new Map<CloudAgentId, { code: string; at: number }>()
+ const codeFor = (agent: CloudAgentId) => async (): Promise<string> => {
+ const known = codes.get(agent)
+ if (known && now() - known.at < 60_000) return known.code
+ const { code } = await connectionFor(bridge, agent)
+ codes.set(agent, { code, at: now() })
+ return code
+ }
+ const mcpClients = new Map<string, McpClient>()
+ const adapters: Record<CloudAgentId, CloudAdapter> = {
+ fo: options.adapters?.fo ?? foAdapter(async () => {
+ const url = bridge.mcpUrl(await codeFor('fo')())
+ let client = mcpClients.get(url)
+ if (!client) { client = new McpClient(url, CLOUD_AGENTS.fo.name); mcpClients.set(url, client) }
+ return client
+ }),
+ 'devin-cloud': options.adapters?.['devin-cloud'] ?? devinAdapter(bridge, codeFor('devin-cloud')),
+ 'cursor-cloud': options.adapters?.['cursor-cloud'] ?? cursorAdapter(bridge, codeFor('cursor-cloud')),
+ }
+
+ const transcriptFile = (agentId: string): string => join(dir, `${agentId}.jsonl`)
+ const save = (): void => {
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
+ const temp = `${stateFile}.${process.pid}.tmp`
+ writeFileSync(temp, JSON.stringify({ harnesses: [...entries.values()].map(({ harness, remote, question, changedAt, creationId }) => ({ harness, remote, question, changedAt, creationId })) }), { mode: 0o600 })
+ renameSync(temp, stateFile)
+ }
+ const transcript = (agentId: string): TranscriptMessage[] => {
+ try {
+ return readFileSync(transcriptFile(agentId), 'utf8').split('\n').flatMap((line) => {
+ try { return line ? [JSON.parse(line) as TranscriptMessage] : [] } catch { return [] }
+ })
+ } catch { return [] }
+ }
+ const record = (entry: Entry, message: TranscriptMessage): void => {
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
+ appendFileSync(transcriptFile(entry.harness.agentId), `${JSON.stringify(message)}\n`, { mode: 0o600 })
+ entry.harness.messages += 1
+ if (message.from === 'agent') entry.harness.said = message.text.slice(0, SAID_MAX)
+ }
+
+ const publish = (): void => {
+ if (stopped) return
+ options.core.publish([...entries.values()].map((entry) => ({ ...entry.harness, links: [...entry.harness.links] })))
+ }
+ const touched = (entry: Entry): void => {
+ entry.harness.updatedAt = new Date(now()).toISOString()
+ entry.changedAt = now()
+ save()
+ publish()
+ }
+ const serial = <T>(agentId: string, work: () => Promise<T>): Promise<T> => {
+ const run = (queues.get(agentId) ?? Promise.resolve()).catch(() => {}).then(work)
+ queues.set(agentId, run)
+ return run
+ }
+
+ const ask = (entry: Entry, question: { text: string; choices: string[] } | null): void => {
+ const asked = entry.question
+ if (asked && question && asked.text === question.text && asked.choices.join('\n') === question.choices.join('\n')) return
+ if (asked) { options.core.unask(entry.harness.agentId, asked.requestId); entry.question = null }
+ if (!question) return
+ entry.question = { requestId: `cloud_q_${randomBytes(6).toString('hex')}`, ...question }
+ options.core.ask(entry.harness.agentId, entry.question.requestId, question)
+ }
+
+ /** What one look found, applied: new messages recorded, where it is now, and its question. */
+ const apply = (entry: Entry, update: CloudUpdate): boolean => {
+ const before = JSON.stringify([entry.harness, entry.remote, entry.question?.text])
+ const seen = new Set(transcript(entry.harness.agentId).slice(-TRANSCRIPT_MAX).map((message) => message.id))
+ for (const message of update.messages) {
+ if (seen.has(message.id)) continue
+ record(entry, { ...message, from: 'agent' })
+ entry.heard = true
+ }
+ // "Waiting for you" with nothing said since the person wrote is the wait they just answered: not a new one.
+ if (update.state === 'needs_input' && !entry.heard) update = { ...update, state: undefined, question: undefined }
+ if (update.state) entry.harness.state = update.state
+ if (update.activity !== undefined) entry.harness.activity = update.activity
+ if (update.branch !== undefined) entry.harness.branch = update.branch
+ if (update.links) entry.harness.links = update.links
+ if (update.remote) entry.remote = { ...entry.remote, ...update.remote }
+ if (entry.harness.state !== 'needs_input') ask(entry, null)
+ else if (update.question) ask(entry, update.question)
+ // Waiting, with nothing new said and nothing asked yet (a restart): it asks what it last said.
+ else if (!entry.question) {
+ const said = transcript(entry.harness.agentId).filter((message) => message.from === 'agent').at(-1)?.text
+ ask(entry, { text: (said ?? `${CLOUD_AGENTS[entry.harness.agent].name} is waiting for you.`).slice(0, 500), choices: [] })
+ }
+ return JSON.stringify([entry.harness, entry.remote, entry.question?.text]) !== before
+ }
+
+ const schedule = (agentId: string, ms: number): void => {
+ clearTimer(timers.get(agentId))
+ timers.delete(agentId)
+ if (stopped) return
+ timers.set(agentId, setTimer(() => { timers.delete(agentId); void look(agentId) }, ms))
+ }
+ const watching = (entry: Entry): boolean => ['starting', 'working', 'needs_input'].includes(entry.harness.state) && now() - entry.changedAt < QUIET_MS
+
+ const look = (agentId: string): Promise<void> => serial(agentId, async () => {
+ const entry = entries.get(agentId)
+ if (!entry || stopped || !watching(entry)) return
+ let update: CloudUpdate
+ const controller = new AbortController()
+ looking.set(agentId, controller)
+ const started = now()
+ try {
+ update = await adapters[entry.harness.agent].poll(entry.remote, controller.signal)
+ entry.failures = 0
+ } catch (error) {
+ // Cut short by the person's words: they are next in line, and look again after.
+ if (controller.signal.aborted) return
+
+ entry.failures += 1
+ const said = error instanceof CloudError ? error.message : `${CLOUD_AGENTS[entry.harness.agent].name} could not be reached.`
+ log(`[cloud] ${agentId} look failed (${entry.failures}): ${error instanceof Error ? error.name : 'error'}`)
+ if (entry.harness.activity !== said) { entry.harness.activity = said; touched(entry) }
+ schedule(agentId, Math.min(BACKOFF_MAX_MS, WORKING_MS * 2 ** entry.failures))
+ return
+ }
+ finally {
+ if (looking.get(agentId) === controller) looking.delete(agentId)
+ }
+ if (apply(entry, update)) touched(entry)
+ const waitedLong = update.waited && now() - started >= LOOK_MIN_MS
+ if (watching(entry)) schedule(agentId, waitedLong ? 0 : update.waited ? LOOK_MIN_MS : entry.harness.state === 'needs_input' ? WAITING_MS : WORKING_MS)
+ })
+
+ const refused = (error: unknown, agent?: CloudAgentId): { ok: false; error: string; detail: string } => error instanceof CloudError
+ ? { ok: false, error: error.code, detail: error.message }
+ : { ok: false, error: 'CLOUD_FAILED', detail: `${agent ? CLOUD_AGENTS[agent].name : 'The cloud agent'} could not be reached. Try again.` }
+
+ /** New Harnesses still starting at their maker, by `creationId`: a retry while one starts gets its answer. */
+ const creating = new Map<string, ReturnType<CloudPort['create']>>()
+
+ const create: CloudPort['create'] = (request) => {
+ // The same New Harness asked again (a window that timed out waiting): the harness it made, not a second.
+ const creationId = typeof request.creationId === 'string' && request.creationId ? request.creationId.slice(0, 120) : undefined
+ if (!creationId) return createNew(request, undefined)
+ const made = [...entries.values()].find((entry) => entry.creationId === creationId)
+ if (made) return Promise.resolve({ ok: true, agent: cloudAgentFrame(made.harness) })
+ const pending = creating.get(creationId) ?? createNew(request, creationId).finally(() => creating.delete(creationId))
+ creating.set(creationId, pending)
+ return pending
+ }
+
+ const createNew = async (request: Record<string, unknown>, creationId: string | undefined): ReturnType<CloudPort['create']> => {
+ const agent = request.engine
+ if (!isCloudAgent(agent)) return { ok: false, error: 'INVALID_ENGINE', detail: 'That is not a cloud agent.' }
+ const task = typeof request.prompt === 'string' ? request.prompt.trim() : ''
+ if (!task) return { ok: false, error: 'INVALID_REQUEST', detail: `Tell ${CLOUD_AGENTS[agent].name} what to do.` }
+ const repository = repositoryOf(request.repositoryUrl) ?? repositoryOf(request.repository)
+ if (CLOUD_AGENTS[agent].kind === 'coding' && !repository) return { ok: false, error: 'INVALID_REQUEST', detail: `Choose a GitHub repository for ${CLOUD_AGENTS[agent].name}.` }
+ const acuLimit = typeof request.acuLimit === 'number' && Number.isInteger(request.acuLimit) && request.acuLimit > 0 && request.acuLimit <= 1000 ? request.acuLimit : undefined
+ const model = typeof request.model === 'string' && request.model ? request.model.slice(0, 120) : undefined
+ let started: Awaited<ReturnType<CloudAdapter['start']>>
+ try {
+ started = await adapters[agent].start({ task, repository, options: { acuLimit, model } })
+ } catch (error) {
+ codes.delete(agent)
+ return refused(error, agent)
+ }
+ const at = new Date(now()).toISOString()
+ const entry: Entry = {
+ harness: {
+ agentId: `cloud_${randomBytes(8).toString('hex')}`, agent,
+ name: typeof request.name === 'string' && request.name.trim() ? request.name.trim().slice(0, 120) : nameFor(task, agent),
+ state: 'starting', activity: null, repository, branch: null, links: started.links, messages: 0, createdAt: at, updatedAt: at,
+ },
+ remote: started.remote,
+ question: null,
+ changedAt: now(),
+ failures: 0,
+ heard: false,
+ ...(creationId ? { creationId } : {}),
+ }
+ entries.set(entry.harness.agentId, entry)
+ record(entry, { id: `person-${now()}`, from: 'person', text: task, at })
+ if (started.update) apply(entry, started.update)
+ if (entry.harness.state === 'starting' && !started.update?.state) entry.harness.state = 'working'
+ touched(entry)
+ log(`[cloud] ${entry.harness.agentId} started on ${agent}`)
+ schedule(entry.harness.agentId, started.update?.waited || adapters[agent].answered?.(entry.remote) ? 0 : 2_000)
+ return { ok: true, agent: cloudAgentFrame(entry.harness) }
+ }
+
+ const deliver = (agentId: string, text: string): Promise<CloudResult> => { interrupt(agentId); return serial(agentId, async () => {
+ const entry = entries.get(agentId)
+ if (!entry) return { ok: false, error: 'UNKNOWN_AGENT', detail: 'That cloud harness is gone.' }
+ const words = text.trim()
+ if (!words) return { ok: false, error: 'INVALID_REQUEST', detail: 'Write something to send.' }
+ // Working from the moment the words go, as a terminal agent's turn starts with its prompt: Fo answers
+ // `ask_fo` with its whole reply, 15 s later, and the dial sat on the last recap all that time (2026-10-11).
+ // Told, not saved: refused, it is back where it was.
+ const was = { state: entry.harness.state, activity: entry.harness.activity }
+ entry.harness.state = 'working'
+ entry.harness.activity = null
+ publish()
+ const adapter = adapters[entry.harness.agent]
+ try {
+ const moved = await adapter.send(entry.remote, words)
+ if (moved) entry.remote = { ...entry.remote, ...moved }
+ } catch (error) {
+ Object.assign(entry.harness, was)
+ publish()
+ return refused(error, entry.harness.agent)
+ }
+ record(entry, { id: `person-${now()}`, from: 'person', text: words, at: new Date(now()).toISOString() })
+ entry.heard = false
+ ask(entry, null)
+ touched(entry)
+ // Its reply already here: read now, not after the wait a maker that is only starting needs.
+ schedule(agentId, adapter.answered?.(entry.remote) ? 0 : 2_000)
+ return { ok: true }
+ }) }
+
+ const answer = async (agentId: string, requestId: string, answers: Record<string, string>): Promise<CloudResult> => {
+ const entry = entries.get(agentId)
+ const question = entry?.question
+ if (!entry || !question || question.requestId !== requestId) return { ok: false, error: 'STALE_QUESTION', detail: 'That question was already answered.' }
+ const words = Object.values(answers).filter((value) => typeof value === 'string' && value.trim()).join('\n')
+ // Taken at once, before anything waits: a second answer (the dial and the window both) finds it answered.
+ entry.question = null
+ options.core.unask(agentId, question.requestId)
+ const result = await deliver(agentId, words)
+ // Not taken: the question stands, asked again.
+ if (!result.ok && !entry.question && entry.harness.state === 'needs_input') ask(entry, { text: question.text, choices: question.choices })
+ return result
+ }
+
+ /** Only the name Harness shows: nothing is asked of the maker, and its activity time stands. */
+ const rename = async (agentId: string, name: string): Promise<CloudResult> => {
+ const entry = entries.get(agentId)
+ if (!entry) return { ok: false, error: 'UNKNOWN_AGENT', detail: 'That cloud harness is gone.' }
+ const trimmed = name.trim().slice(0, 120)
+ if (!trimmed) return { ok: false, error: 'MISSING_NAME', detail: 'A harness needs a name.' }
+ entry.harness.name = trimmed
+ save()
+ publish()
+ return { ok: true }
+ }
+
+ const stopHarness = (agentId: string): Promise<CloudResult> => { interrupt(agentId); return serial(agentId, async () => {
+ const entry = entries.get(agentId)
+ if (!entry) return { ok: false, error: 'UNKNOWN_AGENT', detail: 'That cloud harness is gone.' }
+ const adapter = adapters[entry.harness.agent]
+ try { await adapter.stop?.(entry.remote) } catch (error) { return refused(error, entry.harness.agent) }
+ clearTimer(timers.get(agentId))
+ timers.delete(agentId)
+ entry.harness.state = 'stopped'
+ entry.harness.activity = adapter.stop ? null : `${CLOUD_AGENTS[entry.harness.agent].name} keeps working on its own.`
+ ask(entry, null)
+ touched(entry)
+ return adapter.stop ? { ok: true } : { ok: true, detail: `${CLOUD_AGENTS[entry.harness.agent].name} keeps working on its own.` }
+ }) }
+
+ const requests: ServiceRequests = {
+ cloud_transcript: (payload, asker) => {
+ if (!asker.owner) return { error: 'OWNER_REQUIRED' }
+ const agentId = typeof payload.agentId === 'string' ? payload.agentId : ''
+ if (!entries.has(agentId)) return { error: 'UNKNOWN_AGENT' }
+ const all = transcript(agentId)
+ const after = typeof payload.after === 'number' && payload.after > 0 ? Math.floor(payload.after) : 0
+ return { messages: all.slice(Math.max(after, all.length - TRANSCRIPT_MAX)), total: all.length }
+ },
+ // The chat pane's prompt: answered, so the pane can say why words were not taken ("still working").
+ cloud_send: (payload, asker) => {
+ if (!asker.owner) return { error: 'OWNER_REQUIRED' }
+ return deliver(typeof payload.agentId === 'string' ? payload.agentId : '', typeof payload.text === 'string' ? payload.text : '')
+ .then((result) => (result.ok ? { ok: true } : { error: result.error, detail: result.detail ?? '' }))
+ },
+ cloud_agents: async (_payload, asker) => {
+ if (!asker.owner) return { error: 'OWNER_REQUIRED' }
+ const agents = await Promise.all(CLOUD_AGENT_IDS.map(async (id) => {
+ const info = CLOUD_AGENTS[id]
+ const connected = await connectionFor(bridge, id).then(() => true, () => false)
+ return { id, name: info.name, place: info.place, kind: info.kind, connected, ...(connected ? {} : { connect: info.connect }) }
+ }))
+ return { agents }
+ },
+ }
+
+ // The harnesses from before this start: told to the core again, and looked at where one was working.
+ try {
+ const saved = JSON.parse(readFileSync(stateFile, 'utf8')) as { harnesses?: Array<Omit<Entry, 'failures'>> }
+ for (const raw of saved.harnesses ?? []) {
+ if (!raw?.harness?.agentId || !isCloudAgent(raw.harness.agent) || !raw.remote?.id) continue
+ // A harness saved before it kept its last words finds them in its conversation.
+ if (typeof raw.harness.said !== 'string') raw.harness.said = transcript(raw.harness.agentId).filter((message) => message.from === 'agent').at(-1)?.text.slice(0, SAID_MAX) ?? null
+ entries.set(raw.harness.agentId, { harness: raw.harness, remote: raw.remote, question: null, changedAt: raw.changedAt ?? now(), failures: 0, heard: true,
+ ...(typeof raw.creationId === 'string' ? { creationId: raw.creationId } : {}) })
+ }
+ } catch { /* None yet. */ }
+ for (const entry of entries.values()) if (watching(entry)) schedule(entry.harness.agentId, 1_000)
+
+ return {
+ requests,
+ port: { create, deliver, answer, rename, stopHarness } satisfies CloudPort,
+ /** The core connected again (its restart): it is told every harness, and asked every open question, again. */
+ republish(): void {
+ publish()
+ for (const entry of entries.values()) if (entry.question) options.core.ask(entry.harness.agentId, entry.question.requestId, { text: entry.question.text, choices: entry.question.choices })
+ },
+ transcript,
+ stop(): void {
+ stopped = true
+ for (const timer of timers.values()) clearTimer(timer)
+ timers.clear()
+ },
+ }
+}
+
+export type CloudService = ReturnType<typeof startCloudService>
diff --git a/cli/src/cloud/types.ts b/cli/src/cloud/types.ts
new file mode 100644
index 000000000..b8dc14b40
--- /dev/null
+++ b/cli/src/cloud/types.ts
@@ -0,0 +1,61 @@
+/**
+ * What a cloud agent's adapter does (docs/design/2026-10-11-cloud-agents.md, "The adapter"): it only
+ * translates between Harness and one maker's API. The service (cloud/service.ts) does the rest: the
+ * harnesses and their transcripts, how often to look, the questions, and what the core is told.
+ */
+import type { CloudAgentId, CloudState } from '../lib/cloudAgents.js'
+
+export interface CloudLink { label: string; url: string }
+
+/** A message from the agent. The person's own are recorded by the service as they are sent. */
+export interface CloudMessage { id: string; text: string; at: string }
+
+/** Where the maker's conversation is: its ids and how far it has been read. The service keeps it. */
+export interface Remote {
+ /** The maker's id for the conversation or session. */
+ id: string
+ /** The run or request in flight, where the maker has one (Cursor's runs, Fo's pending reply). */
+ run?: string
+ /** How far its messages have been read. */
+ cursor?: string
+}
+
+/** What one look at the maker found: what is new, and where the harness is now. Absent fields are unchanged. */
+export interface CloudUpdate {
+ messages: CloudMessage[]
+ state?: CloudState
+ activity?: string | null
+ /** The agent waits on the person: what it asks, with the choices it offers. Absent: the question already asked stands. */
+ question?: { text: string; choices: string[] } | null
+ branch?: string | null
+ links?: CloudLink[]
+ remote?: Partial<Remote>
+ /** The adapter waited for news itself (Fo's reply waits up to 40 s): look again at once, not after a pause. */
+ waited?: boolean
+}
+
+export interface StartRequest {
+ task: string
+ /** `owner/name`, for a coding agent. */
+ repository: string | null
+ /** Devin's ACU limit, Cursor's model. */
+ options: { acuLimit?: number; model?: string }
+}
+
+export interface CloudAdapter {
+ readonly id: CloudAgentId
+ start(request: StartRequest, signal?: AbortSignal): Promise<{ remote: Remote; links: CloudLink[]; update?: CloudUpdate }>
+ /** A follow-up or an answer. What it returns replaces parts of the remote (a new run). */
+ send(remote: Remote, text: string): Promise<Partial<Remote> | void>
+ /** One bounded look: never longer than about a minute. */
+ poll(remote: Remote, signal?: AbortSignal): Promise<CloudUpdate>
+ /** Whether a reply already came with the words (Fo's `ask_fo` can answer with it), for a look at once. */
+ answered?(remote: Remote): boolean
+ /** Absent where the maker offers no way to stop it: Fo keeps working on its own. */
+ stop?(remote: Remote): Promise<void>
+}
+
+/** A refusal said to the person as it is: "Connect Fo in Connections", "Cursor is still working". */
+export class CloudError extends Error {
+ constructor(readonly code: string, message: string) { super(message) }
+}
diff --git a/cli/src/core/AGENTS.md b/cli/src/core/AGENTS.md
index 432ad4f13..a1c9bdc40 100644
--- a/cli/src/core/AGENTS.md
+++ b/cli/src/core/AGENTS.md
@@ -24,6 +24,10 @@ questions. Everything else is a service ([../services/AGENTS.md](../services/AGE
## Where things are
- `agents/`: create, fork, restart, retarget, stop, resume, close, discovery, adoption, binding, the list.
+ `agents/cloud.ts`: agents a service owns, the cloud agents: listed with the rest from what the cloud
+ service publishes, their questions shown as a pane's are, the dial's turn cards made from what changes
+ (working, then what it said), and New Harness, words, an answer, a rename and Stop Harness for one handed
+ to its port (`cloudLink.ts` when it runs in its own process).
- `transcripts/`: attach (bounded reads from the end), ingest, live tail, relaunch marks, normalizers.
Claude Code/Codex live interpretation is injected through `Engine.live`; core keeps parser handles
and immutable turn snapshots, never edits their engine state. Supervised Claude Code/Codex parsers
diff --git a/cli/src/core/agents/cloud.spec.ts b/cli/src/core/agents/cloud.spec.ts
new file mode 100644
index 000000000..38b0a5799
--- /dev/null
+++ b/cli/src/core/agents/cloud.spec.ts
@@ -0,0 +1,223 @@
+import { describe, expect, it, vi } from 'vitest'
+import { CLOUD_DOWN, type CloudPort } from '../api.js'
+import type { CloudHarness } from '../../lib/cloudAgents.js'
+import { createCloudAgents } from './cloud.js'
+
+const harness = (over: Partial<CloudHarness> = {}): CloudHarness => ({
+ agentId: 'cloud_1', agent: 'devin-cloud', name: 'fix it', state: 'working', activity: null, repository: 'acme/api', branch: null,
+ links: [], messages: 1, createdAt: '2026-10-11T10:00:00.000Z', updatedAt: '2026-10-11T10:00:00.000Z', ...over,
+})
+
+function setup(port: CloudPort | null = null) {
+ const clients = { send: vi.fn(), sendCommander: vi.fn(), sendLocal: vi.fn() }
+ const openQuestions = new Map<string, Record<string, unknown>>()
+ const deviceInput = { setUserAction: vi.fn() }
+ const cloud = createCloudAgents({ port: () => port, clients, openQuestions, deviceInput, log: () => {} })
+ return { cloud, clients, openQuestions, deviceInput }
+}
+
+const port = (): CloudPort & { [K in keyof CloudPort]: ReturnType<typeof vi.fn> } => ({
+ create: vi.fn(async () => ({ ok: true as const, agent: { id: 'cloud_2' } })),
+ deliver: vi.fn(async () => ({ ok: true as const })),
+ answer: vi.fn(async () => ({ ok: true as const })),
+ rename: vi.fn(async () => ({ ok: true as const })),
+ stopHarness: vi.fn(async () => ({ ok: true as const, detail: 'Fo keeps working on its own.' })),
+})
+
+describe('agents a service owns', () => {
+ it('lists what the service publishes and tells every client what changed', () => {
+ const { cloud, clients } = setup()
+ cloud.doors.publish([harness(), { agentId: 'not-cloud' }, null] as never)
+ expect(cloud.owns('cloud_1')).toBe(true)
+ expect(cloud.frames()).toMatchObject([{ id: 'cloud_1', location: 'cloud', engine: 'devin-cloud', terminal: { available: false } }])
+ expect(clients.send).toHaveBeenCalledWith({ type: 'agent_synced', payload: { agent: expect.objectContaining({ id: 'cloud_1' }) } })
+ expect(clients.sendCommander).toHaveBeenCalledWith(expect.objectContaining({ type: 'agent_synced' }))
+ // The same list again changes nothing, and is told to nobody.
+ clients.send.mockClear()
+ cloud.doors.publish([harness()])
+ expect(clients.send).not.toHaveBeenCalled()
+ // A stopped one leaves the dial's wheel; a gone one leaves every list.
+ cloud.doors.publish([harness({ state: 'stopped' })])
+ expect(clients.sendCommander).toHaveBeenLastCalledWith({ type: 'agent_deleted', payload: { agentId: 'cloud_1' } })
+ // On the dial's wheel while it runs, and what it is doing for its working card.
+ cloud.doors.publish([harness({ activity: 'Reading code' }), harness({ agentId: 'cloud_2', state: 'stopped' })])
+ expect(cloud.dialRows()).toEqual([expect.objectContaining({ agentId: 'cloud_1', engine: 'devin-cloud', displayName: 'fix it', tmuxPane: '', transcriptPath: null,
+ registeredAt: Date.parse('2026-10-11T10:00:00.000Z') })])
+ expect(cloud.activity('cloud_1')).toBe('Reading code')
+ expect(cloud.activity('cloud_2')).toBeNull()
+ expect(cloud.activity('cloud_9')).toBeNull()
+ cloud.doors.publish('nonsense' as never)
+ expect(clients.send).toHaveBeenCalledWith({ type: 'agent_deleted', payload: { agentId: 'cloud_1' } })
+ expect(cloud.owns('cloud_1')).toBe(false)
+ })
+
+ it('makes the dial\'s turn cards from what changes: working, then what it said, as a terminal agent\'s turn', () => {
+ const { cloud, clients } = setup()
+ const cards = () => clients.sendCommander.mock.calls.map(([frame]) => frame).filter((frame) => frame.type === 'commander_event')
+ // New and working: the tile is told, since it is idle until it is.
+ cloud.doors.publish([harness({ agent: 'fo', name: 'trip', said: null })])
+ expect(cards()).toEqual([{ type: 'commander_event', agentId: 'cloud_1', dbSessionId: 'cloud_1', payload: { kind: 'processing', text: 'Working…' } }])
+ expect(cloud.liveCards()).toEqual(cards())
+ // Still working, now saying what: no second start.
+ cloud.doors.publish([harness({ agent: 'fo', name: 'trip', activity: 'Calling Hair Lab' })])
+ expect(cards()).toHaveLength(1)
+ expect(cloud.liveCards()).toEqual([{ type: 'commander_event', agentId: 'cloud_1', dbSessionId: 'cloud_1', payload: { kind: 'processing', text: 'Calling Hair Lab' } }])
+ // Its reply ends the turn: the recap and the text under it, named, and ringing.
+ cloud.doors.publish([harness({ agent: 'fo', name: 'trip', state: 'idle', said: '## Booked\n\nBooked for **9:30** at Hair Lab. See you Saturday.', messages: 3 })])
+ expect(cards().at(-1)).toEqual({ type: 'commander_event', agentId: 'cloud_1', dbSessionId: 'cloud_1', name: 'trip',
+ payload: { kind: 'summary', recap: 'Booked for 9:30 at Hair Lab. See you Saturday.', text: 'Booked Booked for 9:30 at Hair Lab. See you Saturday.', notification: { id: 'cloud_1:3', kind: 'done' } } })
+ expect(cloud.recent('cloud_1')).toEqual([{ kind: 'summary', recap: 'Booked for 9:30 at Hair Lab. See you Saturday.', text: 'Booked Booked for 9:30 at Hair Lab. See you Saturday.', fullText: '## Booked\n\nBooked for **9:30** at Hair Lab. See you Saturday.' }])
+ expect(cloud.said('cloud_1')).toBe('## Booked\n\nBooked for **9:30** at Hair Lab. See you Saturday.')
+ expect(cloud.liveCards()).toEqual([])
+ // The same words again (a name changed) are not told twice.
+ cloud.doors.publish([harness({ agent: 'fo', name: 'trip!', state: 'idle', said: '## Booked\n\nBooked for **9:30** at Hair Lab. See you Saturday.', messages: 3 })])
+ expect(cards()).toHaveLength(2)
+ // Waiting on the person: its question rings, not its words.
+ cloud.doors.publish([harness({ agent: 'fo', name: 'trip!', state: 'working', said: '## Booked\n\nBooked for **9:30** at Hair Lab. See you Saturday.' })])
+ cloud.doors.publish([harness({ agent: 'fo', name: 'trip!', state: 'needs_input', said: 'Which one?\n1) 9:30\n2) 11:00', messages: 5 })])
+ expect(cards().at(-1)).toMatchObject({ payload: { kind: 'summary', notification: null } })
+ // A turn that ends with nothing said is done; one that failed says why.
+ cloud.doors.publish([harness({ agent: 'fo', name: 'trip!', state: 'working', said: 'Which one?\n1) 9:30\n2) 11:00' })])
+ cloud.doors.publish([harness({ agent: 'fo', name: 'trip!', state: 'idle', said: 'Which one?\n1) 9:30\n2) 11:00' })])
+ expect(cards().at(-1)).toMatchObject({ payload: { kind: 'done', text: 'done' } })
+ cloud.doors.publish([harness({ agent: 'fo', name: 'trip!', state: 'starting', said: 'Which one?\n1) 9:30\n2) 11:00' })])
+ cloud.doors.publish([harness({ agent: 'fo', name: 'trip!', state: 'failed', activity: 'Fo answered 500.', said: 'Which one?\n1) 9:30\n2) 11:00' })])
+ expect(cards().at(-1)).toMatchObject({ payload: { kind: 'error', text: 'Fo answered 500.' } })
+ cloud.doors.publish([harness({ agent: 'fo', name: 'trip!', state: 'working', said: 'Which one?\n1) 9:30\n2) 11:00' })])
+ cloud.doors.publish([harness({ agent: 'fo', name: 'trip!', state: 'failed', said: 'Which one?\n1) 9:30\n2) 11:00' })])
+ expect(cards().at(-1)).toMatchObject({ payload: { kind: 'error', text: 'It stopped with an error.' } })
+ // Idle and changed, with nothing new said: nothing to tell.
+ const before = cards().length
+ cloud.doors.publish([harness({ agent: 'fo', name: 'renamed', state: 'failed', said: 'Which one?\n1) 9:30\n2) 11:00' })])
+ // Stopped: it leaves the wheel, and no card follows it.
+ cloud.doors.publish([harness({ agent: 'fo', name: 'renamed', state: 'working', said: 'Which one?\n1) 9:30\n2) 11:00' })])
+ cloud.doors.publish([harness({ agent: 'fo', name: 'renamed', state: 'stopped', said: 'Which one?\n1) 9:30\n2) 11:00' })])
+ expect(cards()).toHaveLength(before + 1)
+ expect(clients.sendCommander).toHaveBeenLastCalledWith({ type: 'agent_deleted', payload: { agentId: 'cloud_1' } })
+ // A list told again whole (a restart) is not news; nor is a harness first seen idle.
+ const { cloud: again, clients: fresh } = setup()
+ again.doors.publish([harness({ state: 'idle', said: 'Opened #42.' })])
+ again.doors.publish([harness({ state: 'idle', said: 'Opened #42.', name: 'x' })])
+ expect(fresh.sendCommander.mock.calls.filter(([frame]) => frame.type === 'commander_event')).toEqual([])
+ expect(again.recent('cloud_1')).toEqual([expect.objectContaining({ recap: 'Opened #42.' })])
+ // Nothing said yet; not one at all.
+ again.doors.publish([harness({ said: null })])
+ expect(again.recent('cloud_1')).toEqual([])
+ expect(again.said('cloud_1')).toBeUndefined()
+ expect(again.recent('a1')).toBeNull()
+ expect(again.said('a1')).toBeUndefined()
+ })
+
+ it('shows its questions where questions show, and closes them', () => {
+ const { cloud, clients, openQuestions, deviceInput } = setup()
+ cloud.doors.publish([harness()])
+ cloud.doors.ask('cloud_none', 'cloud_q_1', { text: 'Which?', choices: [] })
+ cloud.doors.ask('cloud_1', 'q_1', { text: 'Which?', choices: [] })
+ expect(clients.sendLocal).not.toHaveBeenCalled()
+ cloud.doors.ask('cloud_1', 'cloud_q_1', { text: 'Which branch?', choices: ['main', '', 3, 'dev'] as never })
+ const asked = { type: 'commander_question', agentId: 'cloud_1', dbSessionId: 'cloud_1',
+ payload: { requestId: 'cloud_q_1', questions: [{ key: 'answer', q: 'Which branch?', options: ['main', 'dev'], multi: false, canText: true }], notification: { id: 'cloud_q_1', kind: 'needsYou' } } }
+ expect(clients.sendLocal).toHaveBeenCalledWith(asked)
+ expect(clients.sendCommander).toHaveBeenCalledWith(asked)
+ expect(openQuestions.get('cloud_1')).toEqual(asked)
+ expect(deviceInput.setUserAction).toHaveBeenCalledWith('cloud_1', true)
+ // One with no choices is the windows' alone: the dial's question screen takes no words.
+ clients.sendCommander.mockClear()
+ cloud.doors.ask('cloud_1', 'cloud_q_2', { text: 'Sure?', choices: 'x' as never })
+ expect(clients.sendLocal).toHaveBeenLastCalledWith(expect.objectContaining({ payload: expect.objectContaining({ questions: [expect.objectContaining({ options: [] })] }) }))
+ expect(clients.sendCommander).not.toHaveBeenCalled()
+ cloud.doors.unask('cloud_1', 'cloud_q_2')
+ expect(clients.sendCommander).not.toHaveBeenCalled()
+ expect(clients.sendLocal).toHaveBeenLastCalledWith(expect.objectContaining({ type: 'commander_question_close', payload: { requestId: 'cloud_q_2' } }))
+ cloud.doors.unask('cloud_1', 'cloud_q_9')
+ cloud.doors.unask('cloud_1', 'cloud_q_1')
+ expect(clients.sendLocal).toHaveBeenLastCalledWith({ type: 'commander_question_close', agentId: 'cloud_1', dbSessionId: 'cloud_1', payload: { requestId: 'cloud_q_1' } })
+ expect(openQuestions.has('cloud_1')).toBe(false)
+ expect(deviceInput.setUserAction).toHaveBeenLastCalledWith('cloud_1', false)
+ })
+
+ it('hands New Harness, words, an answer and Stop for its agents to the service, and nothing else', async () => {
+ const service = port()
+ const { cloud } = setup(service)
+ cloud.doors.publish([harness()])
+ expect(cloud.create({ engine: 'claude' })).toBeNull()
+ expect(await cloud.create({ engine: 'fo', prompt: 'x' })).toEqual({ agent: { id: 'cloud_2' } })
+ service.create.mockResolvedValueOnce({ ok: false, error: 'NOT_CONNECTED', detail: 'Connect Fo' })
+ expect(await cloud.create({ engine: 'fo' })).toEqual({ error: 'NOT_CONNECTED', detail: 'Connect Fo' })
+ service.create.mockResolvedValueOnce({ ok: false, error: 'X' })
+ expect(await cloud.create({ engine: 'fo' })).toEqual({ error: 'X' })
+
+ expect(cloud.deliver('a1', 'hi')).toBeNull()
+ expect(await cloud.deliver('cloud_1', 'hi')).toEqual({ ok: true })
+ expect(service.deliver).toHaveBeenCalledWith('cloud_1', 'hi')
+
+ expect(cloud.answer({ requestId: 'q_pane' })).toBeNull()
+ expect(cloud.answer({})).toBeNull()
+ cloud.doors.ask('cloud_1', 'cloud_q_1', { text: 'Which?', choices: [] })
+ expect(await cloud.answer({ requestId: 'cloud_q_1', answers: { answer: 'main', other: 3 } })).toEqual({ ok: true })
+ expect(service.answer).toHaveBeenCalledWith('cloud_1', 'cloud_q_1', { answer: 'main' })
+ service.answer.mockResolvedValueOnce({ ok: false, error: 'STALE_QUESTION', detail: 'gone' }).mockResolvedValueOnce({ ok: false, error: 'BUSY' })
+ expect(await cloud.answer({ requestId: 'cloud_q_1', answers: 'x' })).toEqual({ ok: false, error: 'STALE_QUESTION', detail: 'gone' })
+ expect(await cloud.answer({ requestId: 'cloud_q_1' })).toEqual({ ok: false, error: 'ANSWER_FAILED', detail: '' })
+
+ expect(cloud.stop('a1')).toBeNull()
+ expect(await cloud.stop('cloud_1')).toEqual({ deleted: true, detail: 'Fo keeps working on its own.' })
+ service.stopHarness.mockResolvedValueOnce({ ok: true }).mockResolvedValueOnce({ ok: false, error: 'CLOUD_FAILED', detail: 'down' }).mockResolvedValueOnce({ ok: false, error: 'X' })
+ expect(await cloud.stop('cloud_1')).toEqual({ deleted: true })
+ expect(await cloud.stop('cloud_1')).toEqual({ error: 'CLOUD_FAILED', detail: 'down' })
+ expect(await cloud.stop('cloud_1')).toEqual({ error: 'X' })
+ })
+
+ it('renames one through the service, tells every window and the dial, and answers an open with its frame', async () => {
+ const service = port()
+ const { cloud, clients } = setup(service)
+ cloud.doors.publish([harness({ agent: 'fo', name: 'hi' })])
+ clients.send.mockClear()
+ clients.sendCommander.mockClear()
+ expect(cloud.update({ agentId: 'a1', name: 'x' })).toBeNull()
+ expect(cloud.update({})).toBeNull()
+ expect(await cloud.update({ agentId: 'cloud_1', name: ' Trip planning ' })).toEqual({ agent: expect.objectContaining({ id: 'cloud_1', name: 'Trip planning' }) })
+ expect(service.rename).toHaveBeenCalledWith('cloud_1', 'Trip planning')
+ const renamed = { type: 'agent_renamed', payload: { agentId: 'cloud_1', name: 'Trip planning', engine: 'fo' } }
+ expect(clients.send).toHaveBeenCalledWith(renamed)
+ expect(clients.sendCommander).toHaveBeenCalledWith(renamed)
+ expect(await cloud.update({ agentId: 'cloud_1', name: ' ' })).toEqual({ error: 'MISSING_NAME' })
+ expect(await cloud.update({ agentId: 'cloud_1', name: 3 })).toEqual({ error: 'MISSING_NAME' })
+ service.rename.mockResolvedValueOnce({ ok: false, error: 'UNKNOWN_AGENT', detail: 'gone' }).mockResolvedValueOnce({ ok: false, error: 'X' })
+ expect(await cloud.update({ agentId: 'cloud_1', name: 'y' })).toEqual({ error: 'UNKNOWN_AGENT', detail: 'gone' })
+ expect(await cloud.update({ agentId: 'cloud_1', name: 'y' })).toEqual({ error: 'X' })
+ // An app opening it: its frame as it stands, nothing told.
+ clients.send.mockClear()
+ expect(await cloud.update({ agentId: 'cloud_1', opened: true })).toEqual({ agent: expect.objectContaining({ id: 'cloud_1', name: 'hi' }) })
+ expect(await cloud.update({ agentId: 'cloud_1' })).toEqual({ error: 'MISSING_UPDATE' })
+ expect(clients.send).not.toHaveBeenCalled()
+ })
+
+ it('says "stopping" when the maker is slow to stop, so the connection waits on no vendor', async () => {
+ const service = port()
+ service.stopHarness.mockImplementation(() => new Promise(() => {}))
+ const { cloud } = setup(service)
+ cloud.doors.publish([harness()])
+ expect(await cloud.stop('cloud_1', 5)).toEqual({ deleted: true, detail: 'Stopping. Its pane says when it has.' })
+ })
+
+ it('refuses with a reason while the service is off', async () => {
+ const { cloud } = setup(null)
+ cloud.doors.publish([harness()])
+ expect(await cloud.create({ engine: 'devin-cloud' })).toEqual({ error: 'SERVICE_UNAVAILABLE', detail: CLOUD_DOWN.detail })
+ expect(await cloud.deliver('cloud_1', 'x')).toEqual(CLOUD_DOWN)
+ cloud.doors.ask('cloud_1', 'cloud_q_1', { text: 'Which?', choices: [] })
+ expect(await cloud.answer({ requestId: 'cloud_q_1' })).toEqual({ ok: false, error: 'ANSWER_FAILED', detail: CLOUD_DOWN.detail })
+ expect(await cloud.stop('cloud_1')).toEqual({ error: 'SERVICE_UNAVAILABLE', detail: CLOUD_DOWN.detail })
+ expect(await cloud.update({ agentId: 'cloud_1', name: 'x' })).toEqual({ error: 'SERVICE_UNAVAILABLE', detail: CLOUD_DOWN.detail })
+ })
+
+ it('logs a question by default', () => {
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const cloud = createCloudAgents({ port: () => null, clients: { send: vi.fn(), sendCommander: vi.fn(), sendLocal: vi.fn() }, openQuestions: new Map(), deviceInput: { setUserAction: vi.fn() } })
+ cloud.doors.publish([harness()])
+ cloud.doors.ask('cloud_1', 'cloud_q_1', { text: 'Which?', choices: [] })
+ expect(log).toHaveBeenCalledWith(expect.stringContaining('[cloud] cloud_1 asking'))
+ log.mockRestore()
+ })
+})
diff --git a/cli/src/core/agents/cloud.ts b/cli/src/core/agents/cloud.ts
new file mode 100644
index 000000000..15822ccff
--- /dev/null
+++ b/cli/src/core/agents/cloud.ts
@@ -0,0 +1,240 @@
+/**
+ * Agents a service owns: the cloud agents (docs/design/2026-10-11-cloud-agents.md, "The one core change").
+ * They have no pane, so they are never registry rows. The cloud service publishes them through `core.cloud`
+ * (`doors`); the core keeps the last list, sends each change to the apps and the dial as any agent's frame
+ * (`location: 'cloud'`), and puts their questions wherever questions show. What a person does to one comes
+ * back here first: a New Harness for a cloud agent, words for it, an answer to its question, a rename and Stop
+ * are handed to the service's port, and everything else goes on to the terminal agents' own paths.
+ *
+ * The dial reads a turn from its cards (lib/commander.ts): working as it starts, its answer as it ends. A cloud
+ * harness has no turns to read, so its cards are made here, from what changes between two lists.
+ */
+import type { CloudCore, CloudPort, CloudResult } from '../api.js'
+import { CLOUD_DOWN } from '../api.js'
+import { cloudAgentFrame, cloudHarnessIn, isCloudAgent, type CloudAgentFrame, type CloudHarness } from '../../lib/cloudAgents.js'
+import type { AutonomousDeviceInput } from '../deviceInput.js'
+import type { QuestionAnswerResult } from '../../lib/questionController.js'
+import { deriveTurnSummary } from '../../lib/deviceRecap.js'
+import { splitSummary } from '../../lib/recapReads.js'
+
+type Frame = { type: string; agentId?: string; dbSessionId?: string; payload: Record<string, unknown> }
+
+export interface CloudAgentsDeps {
+ /** The cloud service's port, or null while it is off. */
+ port: () => CloudPort | null
+ /** Every client (`send`), the dial (`sendCommander`) and the windows on this computer (`sendLocal`). */
+ clients: { send(frame: Frame): void; sendCommander(frame: Frame): void; sendLocal(frame: Frame): void }
+ /** What is still being asked, by agent, for a window that connects later (core/questions.ts). */
+ openQuestions: Map<string, Record<string, unknown>>
+ deviceInput: Pick<AutonomousDeviceInput, 'setUserAction'>
+ log?: (line: string) => void
+}
+
+const DOWN = async (): Promise<typeof CLOUD_DOWN> => CLOUD_DOWN
+const busy = (harness: CloudHarness): boolean => harness.state === 'working' || harness.state === 'starting'
+/** Its last words as the dial's recap and the text under it, or null when it has said nothing. */
+const recapOf = (harness: CloudHarness): { recap: string; text: string } | null => {
+ const summary = harness.said ? deriveTurnSummary(harness.said) : null
+ if (!summary) return null
+ const { recap, body } = splitSummary(summary)
+ return { recap, text: body }
+}
+
+export function createCloudAgents({ port, clients, openQuestions, deviceInput, log = (line) => console.log(line) }: CloudAgentsDeps) {
+ let harnesses = new Map<string, CloudHarness>()
+ /** Each open question's agent, by request id: an answer to one of these goes to the service. */
+ const asked = new Map<string, string>()
+ /** The questions the dial was shown: only those with choices, since its question screen takes no words. */
+ const onDial = new Set<string>()
+ /** The last words each harness's card told, so a list told again is not told twice. */
+ const told = new Map<string, string>()
+
+ const card = (harness: CloudHarness, payload: Record<string, unknown>): void => {
+ // The name rides a summary's outer frame, as a terminal agent's does: a notification's second line.
+ clients.sendCommander({ type: 'commander_event', agentId: harness.agentId, dbSessionId: harness.agentId, ...(payload.kind === 'summary' ? { name: harness.name } : {}), payload })
+ }
+ /**
+ * Its cards, from one list to the next: working as it starts; once it stops, what it said, or done. First seen
+ * (new, or a list told again whole after a restart), what it said is not news: the dial restores its tile by
+ * `recent`. Working is, since the tile is idle until told.
+ */
+ const cards = (before: CloudHarness | undefined, harness: CloudHarness): void => {
+ if (!before) told.set(harness.agentId, harness.said ?? '')
+ // Stopped, it leaves the dial's wheel (`sync`): there is no tile to tell.
+ if (harness.state === 'stopped') return
+ if (busy(harness)) {
+ if (!before || !busy(before)) card(harness, { kind: 'processing', text: harness.activity ?? 'Working…' })
+ return
+ }
+ if (!before) return
+ const recap = recapOf(harness)
+ if (recap && harness.said !== told.get(harness.agentId)) {
+ told.set(harness.agentId, harness.said!)
+ // Waiting on the person, its question rings instead (lib/agentNotifications.ts keeps the same rule).
+ card(harness, { kind: 'summary', ...recap, notification: harness.state === 'needs_input' ? null : { id: `${harness.agentId}:${harness.messages}`, kind: 'done' } })
+ } else if (busy(before)) {
+ card(harness, harness.state === 'failed' ? { kind: 'error', text: harness.activity ?? 'It stopped with an error.' } : { kind: 'done', text: 'done' })
+ }
+ }
+
+ const sync = (harness: CloudHarness): void => {
+ const frame: Frame = { type: 'agent_synced', payload: { agent: cloudAgentFrame(harness) } }
+ clients.send(frame)
+ // The dial lists the harnesses it can drive: a stopped one leaves its wheel.
+ clients.sendCommander(harness.state === 'stopped' ? { type: 'agent_deleted', payload: { agentId: harness.agentId } } : frame)
+ }
+ const gone = (agentId: string): void => {
+ const frame: Frame = { type: 'agent_deleted', payload: { agentId } }
+ clients.send(frame)
+ clients.sendCommander(frame)
+ }
+
+ const doors: CloudCore = {
+ publish(list) {
+ const next = new Map<string, CloudHarness>()
+ for (const raw of Array.isArray(list) ? list : []) {
+ const harness = cloudHarnessIn(raw)
+ if (harness) next.set(harness.agentId, harness)
+ }
+ const before = harnesses
+ harnesses = next
+ for (const [agentId, harness] of next) {
+ const prior = before.get(agentId)
+ if (JSON.stringify(prior) === JSON.stringify(harness)) continue
+ sync(harness)
+ cards(prior, harness)
+ }
+ for (const agentId of before.keys()) if (!next.has(agentId)) { told.delete(agentId); gone(agentId) }
+ },
+ ask(agentId, requestId, question) {
+ if (!harnesses.has(agentId) || typeof requestId !== 'string' || !requestId.startsWith('cloud_q_') || typeof question?.text !== 'string') return
+ const choices = (Array.isArray(question.choices) ? question.choices : []).filter((choice): choice is string => typeof choice === 'string' && !!choice).slice(0, 6)
+ asked.set(requestId, agentId)
+ const frame: Frame = {
+ type: 'commander_question', agentId, dbSessionId: agentId,
+ // As a terminal agent's question (core/questions.ts): one key, its choices, and free text, which the
+ // windows take and the dial does not.
+ payload: { requestId, questions: [{ key: 'answer', q: question.text.slice(0, 500), options: choices, multi: false, canText: true }], notification: { id: requestId, kind: 'needsYou' } },
+ }
+ deviceInput.setUserAction(agentId, true)
+ if (choices.length) {
+ onDial.add(requestId)
+ clients.sendCommander(frame)
+ }
+ clients.sendLocal(frame)
+ openQuestions.set(agentId, frame)
+ log(`[cloud] ${agentId} asking the person · req=${requestId}`)
+ },
+ unask(agentId, requestId) {
+ if (asked.get(requestId) !== agentId) return
+ asked.delete(requestId)
+ const frame: Frame = { type: 'commander_question_close', agentId, dbSessionId: agentId, payload: { requestId } }
+ deviceInput.setUserAction(agentId, false)
+ if (onDial.delete(requestId)) clients.sendCommander(frame)
+ clients.sendLocal(frame)
+ openQuestions.delete(agentId)
+ },
+ }
+
+ const call = async <T>(work: (cloud: CloudPort) => Promise<T>, fallback: () => Promise<T>): Promise<T> => {
+ const cloud = port()
+ return cloud ? work(cloud) : fallback()
+ }
+
+ return {
+ doors,
+ /** Every cloud harness's frame, for `agents_list`. */
+ frames: (): CloudAgentFrame[] => [...harnesses.values()].map(cloudAgentFrame),
+ owns: (agentId: string): boolean => harnesses.has(agentId),
+ /** Its last turn as the dial restores a tile (`agent_recent`), what it said; null when it is not one. */
+ recent: (agentId: string): Array<{ kind: 'summary'; recap: string; text: string; fullText: string }> | null => {
+ const harness = harnesses.get(agentId)
+ if (!harness) return null
+ const recap = recapOf(harness)
+ return recap ? [{ kind: 'summary', ...recap, fullText: harness.said! }] : []
+ },
+ /** All it said last, for a dial that draws a long recap; undefined when it is not one or said nothing. */
+ said: (agentId: string): string | undefined => harnesses.get(agentId)?.said ?? undefined,
+ /** The working cards, for a dial attaching mid-turn. */
+ liveCards: (): Frame[] => [...harnesses.values()].filter(busy).map((harness) => ({
+ type: 'commander_event', agentId: harness.agentId, dbSessionId: harness.agentId, payload: { kind: 'processing', text: harness.activity ?? 'Working…' },
+ })),
+ /** What a working cloud harness is doing, for the dial's working card; null when it says nothing. */
+ activity: (agentId: string): string | null => {
+ const harness = harnesses.get(agentId)
+ return harness && (harness.state === 'working' || harness.state === 'starting') ? harness.activity : null
+ },
+ /**
+ * The running cloud harnesses as the dial lists agents (services/fleetRouter.ts reads an agent's id, its
+ * start, its engine and its name): rows with no pane, no transcript and no process, so nothing that reads a
+ * terminal agent's files finds one to read. A stopped one is off the wheel, as a stopped agent is.
+ */
+ dialRows: (): Array<Record<string, unknown>> => [...harnesses.values()].filter((harness) => harness.state !== 'stopped').map((harness) => ({
+ agentId: harness.agentId, sessionId: harness.agentId, engine: harness.agent, displayName: harness.name, defaultName: harness.name, runtimeProfile: null,
+ registeredAt: Date.parse(harness.createdAt), lastHookAt: Date.parse(harness.updatedAt), active: true,
+ tmuxPane: '', cwd: '', projectDir: '', transcriptPath: null, runtimes: [], primaryRuntimeKey: '',
+ })),
+ /** `agent_create` for a cloud agent, answered as the socket answers one (`{ agent }`, or the refusal); null for any other engine. */
+ create(payload: Record<string, unknown>): Promise<Record<string, unknown>> | null {
+ if (!isCloudAgent(payload.engine)) return null
+ return call((cloud) => cloud.create(payload), DOWN).then((result) => (result.ok ? { agent: result.agent } : { error: result.error, ...(result.detail ? { detail: result.detail } : {}) }))
+ },
+ /** Words for a cloud harness; null when it is not one. */
+ deliver(agentId: string, text: string): Promise<CloudResult> | null {
+ if (!harnesses.has(agentId)) return null
+ return call((cloud) => cloud.deliver(agentId, text), DOWN)
+ },
+ /** `question_response` to a cloud harness's question, answered as a terminal agent's is; null when it is not one. */
+ answer(payload: { requestId?: unknown; answers?: unknown }): Promise<QuestionAnswerResult> | null {
+ const requestId = typeof payload.requestId === 'string' ? payload.requestId : ''
+ const agentId = asked.get(requestId)
+ if (!agentId) return null
+ const answers = Object.fromEntries(Object.entries(payload.answers && typeof payload.answers === 'object' ? payload.answers : {})
+ .filter((entry): entry is [string, string] => typeof entry[1] === 'string'))
+ return call((cloud) => cloud.answer(agentId, requestId, answers), DOWN)
+ .then((result): QuestionAnswerResult => (result.ok ? { ok: true }
+ : { ok: false, error: result.error === 'STALE_QUESTION' ? 'STALE_QUESTION' : 'ANSWER_FAILED', detail: result.detail ?? '' }))
+ },
+ /**
+ * `agent_update` for a cloud harness, answered as a terminal agent's is (core/agents/update.ts): its frame
+ * after a rename, told to every window and the dial; its frame as it stands for an app opening it, since
+ * nothing here keeps a "last used"; null when it is not one. It has no model to move.
+ */
+ update(payload: Record<string, unknown>): Promise<Record<string, unknown>> | null {
+ const agentId = typeof payload.agentId === 'string' ? payload.agentId : ''
+ const harness = harnesses.get(agentId)
+ if (!harness) return null
+ if (!Object.prototype.hasOwnProperty.call(payload, 'name')) {
+ return Promise.resolve(payload.opened === true ? { agent: cloudAgentFrame(harness) } : { error: 'MISSING_UPDATE' })
+ }
+ const name = typeof payload.name === 'string' ? payload.name.trim().slice(0, 120) : ''
+ if (!name) return Promise.resolve({ error: 'MISSING_NAME' })
+ return call((cloud) => cloud.rename(agentId, name), DOWN).then((result) => {
+ if (!result.ok) return { error: result.error, ...(result.detail ? { detail: result.detail } : {}) }
+ // As a terminal agent's rename is told; the service's next list says it again, which changes nothing.
+ const renamed: Frame = { type: 'agent_renamed', payload: { agentId, name, engine: harness.agent } }
+ clients.send(renamed)
+ clients.sendCommander(renamed)
+ return { agent: cloudAgentFrame({ ...harness, name }) }
+ })
+ },
+ /**
+ * Stop Harness for a cloud harness, answered as `agent_delete` is; null when it is not one. The socket waits
+ * on this in the connection's line, so a maker slower than a few seconds is answered "stopping" and its
+ * harness's frame says when it has: the window's other requests never wait behind a vendor.
+ */
+ stop(agentId: string, quickMs = 3_000): Promise<Record<string, unknown>> | null {
+ if (!harnesses.has(agentId)) return null
+ const stopped = call((cloud) => cloud.stopHarness(agentId), DOWN)
+ .then((result) => (result.ok ? { deleted: true, ...(result.detail ? { detail: result.detail } : {}) } : { error: result.error, ...(result.detail ? { detail: result.detail } : {}) }))
+ let timer: ReturnType<typeof setTimeout> | undefined
+ const stopping = new Promise<Record<string, unknown>>((resolve) => {
+ timer = setTimeout(() => resolve({ deleted: true, detail: 'Stopping. Its pane says when it has.' }), quickMs)
+ timer.unref?.()
+ })
+ return Promise.race([stopped, stopping]).finally(() => clearTimeout(timer))
+ },
+ }
+}
+
+export type CloudAgents = ReturnType<typeof createCloudAgents>
diff --git a/cli/src/core/agents/list.spec.ts b/cli/src/core/agents/list.spec.ts
index bc33da8e1..8db65e931 100644
--- a/cli/src/core/agents/list.spec.ts
+++ b/cli/src/core/agents/list.spec.ts
@@ -60,6 +60,21 @@ describe('the agents a window asks for', () => {
})
})
+describe('the cloud harnesses', () => {
+ const cloud = (id: string, createdAt: string, status = 'active') => ({ id, name: id, engine: 'fo', createdAt, status, selectedModel: null, location: 'cloud' }) as never
+
+ it('are listed with the rest in the same order, and a stopped one only where stopped agents are asked for', async () => {
+ const a1 = session('a1')
+ const { ask, replies } = setup([a1], [], { cloudFrames: () => [cloud('cloud_1', '2026-10-05T09:00:00.000Z'), cloud('cloud_2', '2026-10-05T11:00:00.000Z', 'stopped')] })
+ await ask({})
+ expect(replies[0].agents.map((agent: { id: string }) => agent.id)).toEqual(['cloud_1', 'a1'])
+ await ask({ includeStopped: true })
+ expect(replies[1].agents.map((agent: { id: string }) => agent.id)).toEqual(['cloud_1', 'a1', 'cloud_2'])
+ await ask({ includeStopped: true }, 'device')
+ expect(replies[2].agents).toEqual([{ id: 'cloud_1', name: 'cloud_1', engine: 'fo', selectedModel: null }, { id: 'a1', name: 'a1 name', engine: 'claude', selectedModel: null }])
+ })
+})
+
describe('the agents a device asks for', () => {
it('only the rows it drives, at most a hundred, each with only what its firmware reads, and never a stopped one', async () => {
const live = [session('shell', { engine: 'terminal' }), ...Array.from({ length: 105 }, (_, i) => session(`agent-${String(i).padStart(3, '0')}`))]
@@ -173,6 +188,8 @@ describe('the device\'s rows', () => {
expect(deviceAgentListItem({ id: 'a', engine: 'codex', selectedModel: 'runtime-v1:s:codex:gpt@high' }))
.toStrictEqual({ id: 'a', engine: 'codex', selectedModel: 'runtime-v1:s:codex:gpt@high' })
expect(deviceAgentListItem({ id: 'a', engine: 42, selectedModel: null })).toStrictEqual({ id: 'a', selectedModel: null })
+ // A cloud agent is driven from the dial too: its question screen answers it.
+ expect(deviceAgentListItem({ id: 'cloud_1', engine: 'devin-cloud', selectedModel: null })).toStrictEqual({ id: 'cloud_1', engine: 'devin-cloud', selectedModel: null })
})
it('a terminal is no row of a device\'s; anything else is', () => {
diff --git a/cli/src/core/agents/list.ts b/cli/src/core/agents/list.ts
index b2b9ead12..ecd6a361b 100644
--- a/cli/src/core/agents/list.ts
+++ b/cli/src/core/agents/list.ts
@@ -9,6 +9,7 @@
*/
import { isTerminalEngine, PROCESS_ENGINES, type ProcessEngine } from '../../engines/types.js'
import type { AgentFrame } from '../../lib/agentFrame.js'
+import { isCloudAgent, type CloudAgentFrame, type CloudAgentId } from '../../lib/cloudAgents.js'
import type { MonitorActivity, MonitorCompletions } from '../../lib/harnessMonitor.js'
import type { createHarnessResourcesReader } from '../../lib/harnessResources.js'
import type { createHarnessStorageReader } from '../../lib/harnessTelemetry.js'
@@ -38,13 +39,13 @@ function clipDeviceAgentName(input: string): string {
export function deviceAgentListItem(
raw: unknown,
-): { id: unknown; name?: string; engine?: ProcessEngine; selectedModel?: string | null } {
+): { id: unknown; name?: string; engine?: ProcessEngine | CloudAgentId; selectedModel?: string | null } {
const o = (raw ?? {}) as Record<string, unknown>
- const item: { id: unknown; name?: string; engine?: ProcessEngine; selectedModel?: string | null } = { id: o.id }
+ const item: { id: unknown; name?: string; engine?: ProcessEngine | CloudAgentId; selectedModel?: string | null } = { id: o.id }
if (typeof o.name === 'string') item.name = clipDeviceAgentName(o.name)
- // The dial only ever meets process engines — a terminal never reaches it (see `deviceAgentRow`),
- // and the union here says so rather than repeating fourteen string literals.
- if (typeof o.engine === 'string' && (PROCESS_ENGINES as readonly string[]).includes(o.engine)) item.engine = o.engine as ProcessEngine
+ // The dial only ever meets process engines and cloud agents — a terminal never reaches it (see
+ // `deviceAgentRow`), and the union here says so rather than repeating fourteen string literals.
+ if (typeof o.engine === 'string' && ((PROCESS_ENGINES as readonly string[]).includes(o.engine) || isCloudAgent(o.engine))) item.engine = o.engine as ProcessEngine | CloudAgentId
// Runtime model/effort profile (opaque runtime-v1:...) — lets the device render + change model/effort.
if (typeof o.selectedModel === 'string' || o.selectedModel === null) item.selectedModel = o.selectedModel
return item
@@ -75,11 +76,13 @@ export interface AgentListDeps {
monitorActivityProvider: ((sessionId: string) => MonitorActivity) | null
/** How an agent's last turn ended, from the turn frames the socket sent. */
monitorCompletions: Pick<MonitorCompletions, 'state'>
+ /** The cloud agents' harnesses (core/agents/cloud.ts): listed with the rest, with no pane. */
+ cloudFrames?: () => CloudAgentFrame[]
}
export function createAgentList({
registry, stoppedAgents, toProject, toStoppedProject, harnessResourcesReader, harnessStorageReader,
- monitorActivityProvider, monitorCompletions,
+ monitorActivityProvider, monitorCompletions, cloudFrames = () => [],
}: AgentListDeps) {
/**
* Answers `agents_list` through `reply`: before it returns, or, for the monitor's readings, once
@@ -91,11 +94,13 @@ export function createAgentList({
reply: (result: Record<string, unknown>) => void,
): Promise<void> => {
const sessions = registry.advertised()
- const projects = await Promise.all(sessions.map((s) => toProject(s)))
+ const projects: Array<AgentFrame | CloudAgentFrame> = await Promise.all(sessions.map((s) => toProject(s)))
// Older clients/devices keep their live-only contract. The desktop picker
// explicitly asks for stopped work and receives no stale terminal routes.
const savedSessions = payload.includeStopped === true && sessionRole() !== 'device' ? stoppedAgents.available(sessions) : []
projects.push(...await Promise.all(savedSessions.map(s => toStoppedProject(s))))
+ // A cloud harness is listed while it runs, and once stopped where stopped agents are asked for.
+ projects.push(...cloudFrames().filter((frame) => frame.status !== 'stopped' || (payload.includeStopped === true && sessionRole() !== 'device')))
// Ordered by creation time, oldest → newest — a stable tab order that doesn't reshuffle as
// sessions become active (createdAt = the session's registeredAt). The id breaks a tie so the
// order is TOTAL: without it two agents registered in the same millisecond fall through to array
diff --git a/cli/src/core/api.spec.ts b/cli/src/core/api.spec.ts
index 6be57c8bf..b31ed155e 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 { CONNECTOR_VAULT_OFF, CONVERSATIONS_OFF, ACCOUNT_BACKEND_OFF, AGENT_ACTIONS_OFF, AGENT_CLEANUP_FALLBACKS, createCoreApi, DAEMON_UNKNOWN, DELIVERIES_OFF, DEVICES_FALLBACKS, emptyPorts, LANE_OFF, LONG_ANSWERS, MODELS_OFF, STORE_OFF, MODELS_REQUESTS, MONITOR_OFF, OBSERVER_KEY_OFF, ORCHESTRATOR_FALLBACKS, RECAPS_FALLBACKS, resolveAgent, SHARING_FALLBACKS, MESSAGES_FALLBACKS, TERMINALS_OFF, WIFI_FALLBACKS, WIFI_OFF, type CoreApiDeps } from './api.js'
+import { CLOUD_DOWN, CLOUD_FALLBACKS, CONNECTOR_VAULT_OFF, CONVERSATIONS_OFF, ACCOUNT_BACKEND_OFF, AGENT_ACTIONS_OFF, AGENT_CLEANUP_FALLBACKS, createCoreApi, DAEMON_UNKNOWN, DELIVERIES_OFF, DEVICES_FALLBACKS, emptyPorts, LANE_OFF, LONG_ANSWERS, MODELS_OFF, STORE_OFF, MODELS_REQUESTS, MONITOR_OFF, OBSERVER_KEY_OFF, ORCHESTRATOR_FALLBACKS, RECAPS_FALLBACKS, resolveAgent, SHARING_FALLBACKS, MESSAGES_FALLBACKS, TERMINALS_OFF, WIFI_FALLBACKS, WIFI_OFF, type CoreApiDeps } from './api.js'
import { FAIL, readFallback } from './serviceHost.js'
const row = (agentId: string) => ({ agentId, sessionId: `s-${agentId}`, engine: 'claude', cwd: '/work/app' }) as RegisteredSession
@@ -90,6 +90,13 @@ describe('the core API services stand on', () => {
expect(core.conversations).toBe(CONVERSATIONS_OFF)
const conversations = { ...CONVERSATIONS_OFF }
expect(createCoreApi({ ...deps, conversations }).conversations).toBe(conversations)
+ // The cloud agents' doors, only from a core that offers them.
+ expect(core.cloud).toBeUndefined()
+ const cloud = { publish: vi.fn(), ask: vi.fn(), unask: vi.fn() }
+ expect(createCoreApi({ ...deps, cloud }).cloud).toBe(cloud)
+ expect(core.agents.cloud).toBeUndefined()
+ const rows = [{ agentId: 'cloud_1' }] as RegisteredSession[]
+ expect(createCoreApi({ ...deps, cloudRows: () => rows }).agents.cloud!()).toBe(rows)
expect(core.dataDir).toBe('/data')
expect(await core.terminals.open({ argv: ['/bin/zsh'], cwd: '/work' })).toEqual({ ok: false, error: 'SERVICE_UNAVAILABLE' })
const terminals = { ...TERMINALS_OFF, open: vi.fn(async () => ({ ok: true as const, agentId: 'shell' })), watch: TERMINALS_OFF.watch }
@@ -274,8 +281,13 @@ describe('the core API services stand on', () => {
expect(MESSAGES_FALLBACKS.canWrite).toBe(false)
})
+ it('falls back, when cloud agents fail, to refusing each call with a reason a person reads', () => {
+ for (const fallback of Object.values(CLOUD_FALLBACKS)) expect(readFallback(fallback)).toEqual({ deferred: true, value: CLOUD_DOWN })
+ expect(CLOUD_DOWN.detail).toContain('Cloud agents are not running here')
+ })
+
it('starts with every port empty: a service fills its own when it starts', () => {
- expect(emptyPorts()).toEqual({ usage: null, store: null, search: null, viewers: null, models: null, workspaces: null, messages: null, devices: null, wifi: null, monitor: null, orchestrator: null, sharing: null, recaps: null, agentCleanup: null })
+ expect(emptyPorts()).toEqual({ usage: null, store: null, search: null, viewers: null, models: null, workspaces: null, messages: null, devices: null, wifi: null, monitor: null, orchestrator: null, sharing: null, recaps: null, agentCleanup: null, cloud: null })
expect(emptyPorts()).not.toBe(emptyPorts())
})
diff --git a/cli/src/core/api.ts b/cli/src/core/api.ts
index 3598027f5..e89e3a1bb 100644
--- a/cli/src/core/api.ts
+++ b/cli/src/core/api.ts
@@ -1,5 +1,6 @@
import type { PreparedHandoff, HandoffPermit, HandoffOutcome } from '../lib/handoffAuthority.js'
import type { AgentTokenUsage, AgentUsageTarget } from '../lib/agentUsageWire.js'
+import type { CloudHarness } from '../lib/cloudAgents.js'
import type { GridAssignmentProcess, GridAssignmentAnswer } from '../lib/gridAssignmentWire.js'
/**
* The boundary the services stand on (docs/design/2026-10-03-harnessd.md, "The core boundary"):
@@ -149,6 +150,10 @@ export interface CoreApi {
resolve(id: string): RegisteredSession | undefined
/** The live agents the apps are shown. */
advertised(): RegisteredSession[]
+ /** The running cloud harnesses (core/agents/cloud.ts) as rows an agent list reads: an id, a start, an
+ * engine and a name, with no pane, transcript or process. Only the lists that show them ask (the dial,
+ * the fleet); absent where a core or process offers none. */
+ cloud?(): RegisteredSession[]
/** Whether the agent's terminal is attached: a frame without one reads to the apps as "agent gone". */
terminalAvailable(agentId: string): boolean
/** Send the agent's frame to the apps again. */
@@ -302,6 +307,8 @@ export interface CoreApi {
* 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
+ /** The cloud agents' doors into the core (services/cloud.ts): absent from a core or a process that offers them none. */
+ cloud?: CloudCore
/** The Wi-Fi device's doors into the core (services/wifi.ts): each one call it made when it ran here. */
wifi: {
/** What it lists and reads in line (`WifiView`), asked again before each request it answers. */
@@ -559,6 +566,9 @@ export const LONG_ANSWERS: Readonly<Record<string, Readonly<Record<string, numbe
launchTarget: 3 * MINUTE, privateGridName: 2 * MINUTE, lists: 2 * MINUTE,
},
store: { dsh_install: 30 * MINUTE, dsh_update: 30 * MINUTE, dshMaterialize: 6 * MINUTE },
+ // A cloud agent's maker answers on its own time: Fo's reply waits 40 s, and a busy Fo is retried for half a
+ // minute more. A wait shorter than that said "not running" of words that were then sent anyway.
+ cloud: { create: 3 * MINUTE, deliver: 3 * MINUTE, answer: 3 * MINUTE, stopHarness: 2 * MINUTE, cloud_send: 3 * MINUTE },
}
/** The orchestrator (services/orchestrator.ts): its projects, for the apps and for the agents it runs. */
@@ -574,6 +584,10 @@ export const SHARE_REQUESTS = [
* experiment: its own process cost every computer it was on 62 MiB at idle for a few MiB of messaging. */
export const MESSAGES_REQUESTS = ['agent_messages'] as const
+/** Cloud agents (services/cloud.ts, cloud/service.ts): a cloud harness's conversation for its chat pane, and
+ * which cloud agents are connected here, for New Harness. */
+export const CLOUD_REQUESTS = ['cloud_transcript', 'cloud_send', 'cloud_agents'] as const
+
/**
* What Agent Messages in a process of its own may do through the core, and nothing more (core/messagesLink.ts
* answers it, and checks each): the agents as the apps are shown them (`shown`) and how an agent's shell reaches
@@ -609,6 +623,9 @@ export const EXPERIMENTS: Readonly<Record<string, { requests: readonly string[];
memory: { requests: MEMORY_REQUESTS, state: [] },
// Request-only too: it keeps nothing, and asks Jev only when a client asks it.
router: { requests: ROUTER_REQUESTS, state: [] },
+ // Cloud agents. Its harnesses: one was started here, and is watched again as the daemon starts. A New Harness
+ // for one, an answer or a message to one wakes it too (its port's calls, core/agents/cloud.ts).
+ cloud: { requests: CLOUD_REQUESTS, state: ['cloud/harnesses.json'] },
}
/** The services that may write turns into agents from a process of their own (core/deliveries.ts): the experiments,
@@ -890,6 +907,40 @@ export interface MessagesPort {
* a settings write tells it nothing. */
export const MESSAGES_FALLBACKS: PortFallbacks<MessagesPort> = { canWrite: false, settingsChanged: undefined }
+/**
+ * The cloud agents' doors into the core (docs/design/2026-10-11-cloud-agents.md, "The one core change"): the
+ * harnesses its service owns, which have no pane, and the questions they ask. The core lists them beside the
+ * terminal agents and tells every client what changed (core/agents/cloud.ts).
+ */
+export interface CloudCore {
+ /** Every cloud harness, replacing the last list. */
+ publish(harnesses: CloudHarness[]): void
+ /** One waits on the person: shown wherever questions show; the answer comes back through `CloudPort.answer`. */
+ ask(agentId: string, requestId: string, question: { text: string; choices: string[] }): void
+ /** That question is no longer asked. */
+ unask(agentId: string, requestId: string): void
+}
+
+/** What the cloud service answers the core: done, or why not, in words a person reads. */
+export type CloudResult = { ok: true; detail?: string } | { ok: false; error: string; detail?: string }
+
+/** The core's calls into the cloud agents' service: a New Harness for one, a person's words, an answer, a new name, a Stop. */
+export interface CloudPort {
+ /** `agent_create` for a cloud agent: the new harness's frame, or why not. */
+ create(request: Record<string, unknown>): Promise<{ ok: true; agent: Record<string, unknown> } | { ok: false; error: string; detail?: string }>
+ deliver(agentId: string, text: string): Promise<CloudResult>
+ answer(agentId: string, requestId: string, answers: Record<string, string>): Promise<CloudResult>
+ /** Rename Harness: the name Harness shows. The maker's own name for the work stays as it is. */
+ rename(agentId: string, name: string): Promise<CloudResult>
+ /** Stop Harness. Not `stop`: a service host reads a port's `stop` as stopping the service itself. */
+ stopHarness(agentId: string): Promise<CloudResult>
+}
+
+/** A call the cloud service could not take: it is off, failing, or slower than the core waits. */
+export const CLOUD_DOWN = { ok: false as const, error: 'SERVICE_UNAVAILABLE', detail: 'Cloud agents are not running here. Try again in a moment.' }
+/** What the core gets when the cloud service fails: each call is refused with a reason, and nothing is lost but it. */
+export const CLOUD_FALLBACKS: PortFallbacks<CloudPort> = { create: later(CLOUD_DOWN), deliver: later(CLOUD_DOWN), answer: later(CLOUD_DOWN), rename: later(CLOUD_DOWN), stopHarness: later(CLOUD_DOWN) }
+
/** What a delivered turn answers: delivered, or refused with the machine's name and a reason a person can read. */
export type SendResult = { ok: true } | { ok: false; machine: string; reason: string }
/** What a fork answers: the new agent's id, or why not. */
@@ -1387,10 +1438,11 @@ export interface CorePorts {
sharing: SharingPort | null
recaps: RecapsPort | null
agentCleanup: AgentCleanupPort | null
+ cloud: CloudPort | null
}
export function emptyPorts(): CorePorts {
- return { usage: null, store: null, search: null, viewers: null, models: null, workspaces: null, messages: null, devices: null, wifi: null, monitor: null, orchestrator: null, sharing: null, recaps: null, agentCleanup: null }
+ return { usage: null, store: null, search: null, viewers: null, models: null, workspaces: null, messages: null, devices: null, wifi: null, monitor: null, orchestrator: null, sharing: null, recaps: null, agentCleanup: null, cloud: null }
}
export interface CoreApiDeps {
@@ -1445,6 +1497,10 @@ export interface CoreApiDeps {
dialWatching: CoreApi['clients']['dialWatching']
/** The Wi-Fi device's doors (core/wifi.ts). */
wifi: CoreApi['wifi']
+ /** The cloud agents' doors (core/agents/cloud.ts). */
+ cloud?: CloudCore
+ /** The running cloud harnesses as list rows (`agents.cloud`). */
+ cloudRows?: () => RegisteredSession[]
lastTurn: CoreApi['transcripts']['lastTurn']
/** Where a turn's cards and recaps go: the devices, and the apps. Only their own frame types reach these. */
turnCard: CoreApi['clients']['turnCard']
@@ -1457,7 +1513,7 @@ export function createCoreApi({
gridNamed, gridModelsChanged, dshInstallStatus, mintGridName, accessToken, lane, observerKey, connectorVault, observer, privateGridName, machineName, backend, onNotice,
runtimeProfile, setRuntime, fork, create, dsh, windows, daemon, turns, questions, terminals = TERMINALS_OFF, conversations = CONVERSATIONS_OFF, viewerFrame, machine, activityText, activitySnapshot,
closeAgent, activityAt,
- signedIn, environment, machines, sendLocal, sendToWindow, hasWindow, devicesChanged, dialWatching, wifi, lastTurn, turnCard, turnSummary,
+ signedIn, environment, machines, sendLocal, sendToWindow, hasWindow, devicesChanged, dialWatching, wifi, cloud, cloudRows, lastTurn, turnCard, turnSummary,
log = (line) => console.warn(line),
}: CoreApiDeps): CoreApi {
// The devices reach the windows through these alone, and only with their own frames: a devices process
@@ -1479,6 +1535,7 @@ export function createCoreApi({
byAgent: (agentId) => registry.byAgent(agentId),
resolve: (id) => registry.resolve(id),
advertised: () => registry.advertised(),
+ ...(cloudRows ? { cloud: cloudRows } : {}),
terminalAvailable: (agentId) => registry.terminalAvailable(agentId),
sync: syncSession,
runtimeModels,
@@ -1526,5 +1583,6 @@ export function createCoreApi({
},
daemon,
wifi,
+ ...(cloud ? { cloud } : {}),
}
}
diff --git a/cli/src/core/cloudLink.spec.ts b/cli/src/core/cloudLink.spec.ts
new file mode 100644
index 000000000..fa58a9ae4
--- /dev/null
+++ b/cli/src/core/cloudLink.spec.ts
@@ -0,0 +1,29 @@
+import { describe, expect, it, vi } from 'vitest'
+import { CLOUD_DOWN } from './api.js'
+import { createCloudLink } from './cloudLink.js'
+
+describe('cloud agents in their own process, as the core reaches them', () => {
+ it('asks the process for each call, named as the port\'s members', async () => {
+ const call = vi.fn(async (type: string) => (type === 'create' ? { ok: true, agent: { id: 'cloud_1' } } : { ok: true, detail: 'done' }))
+ const port = createCloudLink(call)
+ expect(await port.create({ engine: 'fo' })).toEqual({ ok: true, agent: { id: 'cloud_1' } })
+ expect(await port.deliver('cloud_1', 'hi')).toEqual({ ok: true, detail: 'done' })
+ expect(await port.answer('cloud_1', 'cloud_q_1', { answer: 'main' })).toEqual({ ok: true, detail: 'done' })
+ expect(await port.rename('cloud_1', 'Trip')).toEqual({ ok: true, detail: 'done' })
+ expect(await port.stopHarness('cloud_1')).toEqual({ ok: true, detail: 'done' })
+ expect(call.mock.calls).toEqual([
+ ['create', { engine: 'fo' }], ['deliver', { agentId: 'cloud_1', text: 'hi' }],
+ ['answer', { agentId: 'cloud_1', questionId: 'cloud_q_1', answers: { answer: 'main' } }], ['rename', { agentId: 'cloud_1', name: 'Trip' }], ['stopHarness', { agentId: 'cloud_1' }],
+ ])
+ })
+
+ it('carries a refusal through, and reads no answer as the fallback', async () => {
+ const answers: Record<string, unknown>[] = [{ ok: false, error: 'NOT_CONNECTED', detail: 'Connect Fo' }, { ok: false, error: 'X' }, { error: 'SERVICE_UNAVAILABLE' }, { ok: true }, { ok: true, agent: 'nope' }]
+ const port = createCloudLink(async () => answers.shift()!)
+ expect(await port.create({})).toEqual({ ok: false, error: 'NOT_CONNECTED', detail: 'Connect Fo' })
+ expect(await port.deliver('a', 'b')).toEqual({ ok: false, error: 'X' })
+ expect(await port.stopHarness('a')).toEqual(CLOUD_DOWN)
+ expect(await port.stopHarness('a')).toEqual({ ok: true })
+ expect(await port.create({})).toEqual(CLOUD_DOWN)
+ })
+})
diff --git a/cli/src/core/cloudLink.ts b/cli/src/core/cloudLink.ts
new file mode 100644
index 000000000..d52412135
--- /dev/null
+++ b/cli/src/core/cloudLink.ts
@@ -0,0 +1,35 @@
+/**
+ * Cloud agents in their own process, as the core reaches them (an experiment; the process's side is
+ * services/cloudProcess.ts). The core asks them five things, each when a person does it and never in a
+ * connection's line: a New Harness for a cloud agent, words for one, an answer to its question, a new name,
+ * and Stop Harness (`stopHarness`: never `stop`, which a service host reads as stopping the service).
+ * Each is a request to the process (core/serviceLinks.ts `call`, which starts it when it is off); an answer
+ * that does not come is the port's fallback (core/api.ts `CLOUD_FALLBACKS`): refused, with a reason.
+ */
+import { CLOUD_DOWN as DOWN, type CloudPort, type CloudResult } from './api.js'
+
+/** Ask the cloud process (core/serviceLinks.ts `call`, for `cloud`): never rejects. */
+export type CallCloud = (type: string, payload: Record<string, unknown>) => Promise<Record<string, unknown>>
+
+/** An answer as the port's result: done, or the refusal it carried, or the fallback for one that is neither. */
+function result(answer: Record<string, unknown>): CloudResult {
+ if (answer.ok === true) return typeof answer.detail === 'string' ? { ok: true, detail: answer.detail } : { ok: true }
+ if (answer.ok === false && typeof answer.error === 'string') return { ok: false, error: answer.error, ...(typeof answer.detail === 'string' ? { detail: answer.detail } : {}) }
+ return DOWN
+}
+
+export function createCloudLink(call: CallCloud): CloudPort {
+ return {
+ create: async (request) => {
+ const answer = await call('create', request)
+ if (answer.ok === true && answer.agent && typeof answer.agent === 'object') return { ok: true, agent: answer.agent as Record<string, unknown> }
+ const refused = result(answer)
+ return refused.ok ? DOWN : refused
+ },
+ deliver: async (agentId, text) => result(await call('deliver', { agentId, text })),
+ // `questionId`: a call's own `requestId` is the link's, written over whatever the payload carried.
+ answer: async (agentId, requestId, answers) => result(await call('answer', { agentId, questionId: requestId, answers })),
+ rename: async (agentId, name) => result(await call('rename', { agentId, name })),
+ stopHarness: async (agentId) => result(await call('stopHarness', { agentId })),
+ }
+}
diff --git a/cli/src/core/devicesLink.spec.ts b/cli/src/core/devicesLink.spec.ts
index 90131a53f..ded89cc25 100644
--- a/cli/src/core/devicesLink.spec.ts
+++ b/cli/src/core/devicesLink.spec.ts
@@ -118,6 +118,14 @@ describe('what the devices ask of the core', () => {
})
})
+ it('lists the cloud harnesses after this computer\'s agents, as the dial lists agents', async () => {
+ const row = { agentId: 'cloud_1', engine: 'fo', displayName: 'haircut', registeredAt: 1 } as unknown as RegisteredSession
+ const core = fakeCore({ agents: { cloud: () => [row] } })
+ const devices = createDevicesLink({ core, notify: () => true, call: vi.fn(), state: () => STATE })
+ vi.mocked(core.agents.advertised).mockReturnValue([{ agentId: 'a1', engine: 'claude' } as RegisteredSession])
+ expect(((await devices.answer('view', {})) as { agents: Array<{ agentId: string }> }).agents.map((agent) => agent.agentId)).toEqual(['a1', 'cloud_1'])
+ })
+
it('is the core\'s own doors and the sign-in, asked when they need them', async () => {
const { core, devices } = link()
vi.mocked(core.agents.activityText).mockResolvedValue('Reading')
diff --git a/cli/src/core/devicesLink.ts b/cli/src/core/devicesLink.ts
index 0b754d830..cddbac402 100644
--- a/cli/src/core/devicesLink.ts
+++ b/cli/src/core/devicesLink.ts
@@ -101,7 +101,11 @@ export function createDevicesLink(deps: DevicesLinkDeps) {
// This computer's agents as the dial lists them, and what else the dial reads in line: asked as its
// tick or ⌘K builds a list, so the devices read the registry as it is then.
view: () => ({
- agents: core.agents.advertised().map((session) => ({ ...session, displayName: core.agents.displayName(session), runtimeProfile: core.agents.runtimeProfile(session) })),
+ agents: [
+ ...core.agents.advertised().map((session) => ({ ...session, displayName: core.agents.displayName(session), runtimeProfile: core.agents.runtimeProfile(session) })),
+ // The cloud harnesses: on the dial's wheel as on the desk, with no pane behind them.
+ ...core.agents.cloud?.() ?? [],
+ ],
machine: { id: core.machine.id(), computerId: core.machine.computerId(), name: core.machine.name() },
signedIn: core.account.signedIn(),
environment: core.account.environment(),
diff --git a/cli/src/core/experimentQueries.spec.ts b/cli/src/core/experimentQueries.spec.ts
index 5fbc0460d..8f37fe626 100644
--- a/cli/src/core/experimentQueries.spec.ts
+++ b/cli/src/core/experimentQueries.spec.ts
@@ -6,6 +6,26 @@ import { answerExperimentQuery, createForExperiment } from './experimentQueries.
const agent = (agentId: string) => ({ agentId, sessionId: `s-${agentId}`, engine: 'claude', cwd: '/w' }) as RegisteredSession
const experiments = new Set(['orchestrator'])
+describe('the cloud agents\' doors', () => {
+ it('are the cloud service\'s alone, and carry its harnesses and questions to the core', async () => {
+ const cloud = { publish: vi.fn(), ask: vi.fn(), unask: vi.fn() }
+ const core = fakeCore({ cloud })
+ const both = new Set(['orchestrator', 'cloud'])
+ expect(await answerExperimentQuery(core, both, 'cloud', 'cloud_publish', { harnesses: [{ agentId: 'cloud_1' }] })).toEqual({})
+ expect(cloud.publish).toHaveBeenLastCalledWith([{ agentId: 'cloud_1' }])
+ await answerExperimentQuery(core, both, 'cloud', 'cloud_publish', { harnesses: 'x' })
+ expect(cloud.publish).toHaveBeenLastCalledWith([])
+ await answerExperimentQuery(core, both, 'cloud', 'cloud_ask', { agentId: 'cloud_1', questionId: 'cloud_q_1', requestId: 'the-link-s-own', question: { text: 'Which?', choices: [] } })
+ expect(cloud.ask).toHaveBeenCalledWith('cloud_1', 'cloud_q_1', { text: 'Which?', choices: [] })
+ await answerExperimentQuery(core, both, 'cloud', 'cloud_ask', {})
+ expect(cloud.ask).toHaveBeenLastCalledWith('', '', {})
+ await answerExperimentQuery(core, both, 'cloud', 'cloud_unask', { agentId: 'cloud_1', questionId: 'cloud_q_1' })
+ expect(cloud.unask).toHaveBeenCalledWith('cloud_1', 'cloud_q_1')
+ expect(await answerExperimentQuery(core, both, 'orchestrator', 'cloud_publish', {})).toEqual({ error: 'NOT_CLOUD' })
+ expect(await answerExperimentQuery(fakeCore(), both, 'cloud', 'cloud_publish', {})).toEqual({ error: 'NOT_CLOUD' })
+ })
+})
+
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({
diff --git a/cli/src/core/experimentQueries.ts b/cli/src/core/experimentQueries.ts
index 1f4a42324..547cd38d8 100644
--- a/cli/src/core/experimentQueries.ts
+++ b/cli/src/core/experimentQueries.ts
@@ -13,7 +13,9 @@
* sign-in (Share's links);
* - `observer_key`: this machine's public key, or its signature on a welcome to one observer of one share, by
* the gateway, which holds the identity (Share's owner);
- * - `observer_send`: a frame Share sealed for one of its observers, to the relay through the gateway.
+ * - `observer_send`: a frame Share sealed for one of its observers, to the relay through the gateway;
+ * - `cloud_publish`, `cloud_ask`, `cloud_unask`: the cloud agents' harnesses and their questions
+ * (`core.cloud`, core/agents/cloud.ts), for the cloud service alone.
* 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. Agent Messages, an experiment until 2026-10-12, asks a few of the same and is
@@ -23,9 +25,9 @@ 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' | 'account'>
+type Core = Pick<CoreApi, 'agents' | 'turns' | 'clients' | 'daemon' | 'account' | 'cloud'>
-const QUERIES: ReadonlySet<string> = new Set(['shown', 'create', 'stop_turn', 'windows', 'daemon', 'backend', 'observer_key', 'observer_send'])
+const QUERIES: ReadonlySet<string> = new Set(['shown', 'create', 'stop_turn', 'windows', 'daemon', 'backend', 'observer_key', 'observer_send', 'cloud_publish', 'cloud_ask', 'cloud_unask'])
const METHODS: ReadonlySet<string> = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE'])
const text = (value: unknown): string => (typeof value === 'string' ? value : '')
@@ -88,6 +90,15 @@ export async function answerExperimentQuery(core: Core, experiments: ReadonlySet
} catch (error) {
return { error: error instanceof Error ? error.message : String(error) }
}
+ case 'cloud_publish':
+ case 'cloud_ask':
+ case 'cloud_unask': {
+ if (service !== 'cloud' || !core.cloud) return { error: 'NOT_CLOUD' }
+ if (query === 'cloud_publish') core.cloud.publish(Array.isArray(payload.harnesses) ? payload.harnesses : [])
+ else if (query === 'cloud_ask') core.cloud.ask(text(payload.agentId), text(payload.questionId), (payload.question ?? {}) as { text: string; choices: string[] })
+ else core.cloud.unask(text(payload.agentId), text(payload.questionId))
+ return {}
+ }
case 'observer_send': {
const connId = text(payload.connId), type = text(payload.type)
if (!connId.startsWith('observer:') || !type.startsWith('observer_') || !payload.payload || typeof payload.payload !== 'object') return { error: 'INVALID_FRAME' }
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index 90ed5636b..43ae03349 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -115,7 +115,9 @@ import { createTerminalRequests } from './terminals/requests.js'
import { createAgentEvents } from './agents/events.js'
import { createSessionNormalizers } from './transcripts/normalizers.js'
import { createInput } from './input.js'
-import { createQuestions } from './questions.js'
+import { createQuestionResponse, createQuestions } from './questions.js'
+import { createCloudAgents, type CloudAgents } from './agents/cloud.js'
+import { createCloudLink } from './cloudLink.js'
import { createTurnActivity } from './turns/activity.js'
import { createLastTurnReader } from './transcripts/lastTurn.js'
import { createEngineReaders } from './engines/readers.js'
@@ -162,7 +164,7 @@ import { createEngineHooks, installEngineHooks, installOpencodePluginBeforeSpawn
import { createCursorDiscovery } from './engines/cursorDiscovery.js'
import { createCursorTaskHooks, loadPendingCursorTasks } from './engines/cursorTasks.js'
import { databaseHistory, hermesDb } from './transcripts/databaseHistory.js'
-import { CONNECTORS_REQUESTS, MEMORY_REQUESTS, ROUTER_REQUESTS, createCoreApi, DEVICES_FALLBACKS, DEVICES_REQUESTS, emptyPorts, HANDOFF_REQUESTS, EXPERIMENTS, LONG_ANSWERS, MODELS_FALLBACKS, MODELS_OFF, MODELS_REQUESTS, MONITOR_FALLBACKS, MONITOR_OFF, MONITOR_REQUESTS, ORCHESTRATOR_FALLBACKS, ORCHESTRATOR_REQUESTS, SHARE_REQUESTS, SHARING_FALLBACKS, PROJECTS_REQUESTS, SEARCH_FALLBACKS, SEARCH_REQUESTS, STORE_FALLBACKS, STORE_OFF, STORE_REQUESTS, MESSAGES_FALLBACKS, MESSAGES_REQUESTS, TURN_DELIVERERS, USAGE_FALLBACKS, USAGE_REQUESTS, VIEWERS_FALLBACKS, WIFI_FALLBACKS, WINDOW_NAMES_REQUESTS, WORKSPACES_FALLBACKS, type GatewayAccount, type GatewayOps, type GatewayStatus, type RouteAnswer, type WindowFocus } from './api.js'
+import { CLOUD_FALLBACKS, CLOUD_REQUESTS, type CloudCore, CONNECTORS_REQUESTS, MEMORY_REQUESTS, ROUTER_REQUESTS, createCoreApi, DEVICES_FALLBACKS, DEVICES_REQUESTS, emptyPorts, HANDOFF_REQUESTS, EXPERIMENTS, LONG_ANSWERS, MODELS_FALLBACKS, MODELS_OFF, MODELS_REQUESTS, MONITOR_FALLBACKS, MONITOR_OFF, MONITOR_REQUESTS, ORCHESTRATOR_FALLBACKS, ORCHESTRATOR_REQUESTS, SHARE_REQUESTS, SHARING_FALLBACKS, PROJECTS_REQUESTS, SEARCH_FALLBACKS, SEARCH_REQUESTS, STORE_FALLBACKS, STORE_OFF, STORE_REQUESTS, MESSAGES_FALLBACKS, MESSAGES_REQUESTS, TURN_DELIVERERS, USAGE_FALLBACKS, USAGE_REQUESTS, VIEWERS_FALLBACKS, WIFI_FALLBACKS, WINDOW_NAMES_REQUESTS, WORKSPACES_FALLBACKS, type GatewayAccount, type GatewayOps, type GatewayStatus, type RouteAnswer, type WindowFocus } from './api.js'
import { createServiceHost, testFaults } from './serviceHost.js'
import { startStalls } from './stall.js'
import { createServiceLinks, type ServiceLinks } from './serviceLinks.js'
@@ -741,11 +743,21 @@ async function runForeground(session: AuthSession | null): Promise<void> {
want: () => devicesWake.ask('wifi', 'a Wi-Fi device'),
doors: wifiDoors({
registry, machineId: machineIdNow, displayName: projectDisplayName, running: (sessionId) => turnStartedAt.has(sessionId),
- socket: () => backendRef ?? null, deviceInput: () => deviceInput, answer: (request) => questions.answer(request),
+ socket: () => backendRef ?? null, deviceInput: () => deviceInput, answer: (request) => cloudAgents?.answer(request) ?? questions.answer(request),
stop: (agentId) => cancelAgent(agentId, true), devices: () => ports.devices,
}),
})
+ // The cloud agents' doors (core/agents/cloud.ts), handed to the core API now and built once the questions and
+ // the socket are, below; the cloud service starts after both.
+ let cloudAgents: CloudAgents | null = null
+ const cloudDoors: CloudCore = {
+ publish: (harnesses) => cloudAgents?.doors.publish(harnesses),
+ ask: (agentId, requestId, question) => cloudAgents?.doors.ask(agentId, requestId, question),
+ unask: (agentId, requestId) => cloudAgents?.doors.unask(agentId, requestId),
+ }
const coreApi = createCoreApi({
+ cloud: cloudDoors,
+ cloudRows: () => (cloudAgents?.dialRows() ?? []) as unknown as RegisteredSession[],
// Agents' terminals: a literal-argv launch, and a read-only view for Share's observers (core/terminalWatch.ts).
terminals: { ...TERMINALS_OFF, ...createTerminalOpener({ tmuxBackend, registry, announceSession, blocksFolder: (cwd) => !!backendRef?.purgeAgentService?.blocksFolder(cwd) }), watch: terminalWatch.watch },
dataDir: env.ADAPTER_DATA_DIR,
@@ -786,6 +798,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// The dial's working card: what a Claude Code or Codex pane's footer says, read here so the pane never
// leaves the core.
activityText: async (agentId) => {
+ // A cloud harness says what it is doing on its frame ("Calling Hair Lab").
+ if (cloudAgents?.owns(agentId)) return cloudAgents.activity(agentId)
const session = registry.resolve(agentId)
if (!session || (session.engine !== 'claude' && session.engine !== 'codex')) return null
const screen = await terminals.capture(session, { mode: 'visible', ansi: false })
@@ -793,6 +807,10 @@ async function runForeground(session: AuthSession | null): Promise<void> {
},
// The same footer for a Harness Pro, with its timer beside it (the agent's sentence comes from the cards).
activitySnapshot: async (agentId) => {
+ if (cloudAgents?.owns(agentId)) {
+ const text = cloudAgents.activity(agentId)
+ return text ? { text } : null
+ }
const session = registry.resolve(agentId)
if (!session || (session.engine !== 'claude' && session.engine !== 'codex')) return null
const screen = await terminals.capture(session, { mode: 'visible', ansi: false })
@@ -819,6 +837,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// The working tiles are the recaps' to say: asked, and sent to the dial when they answer.
if (attached) for (const frame of openQuestions.values()) ports.devices?.card(frame)
if (attached) void mirror.liveCards().then((cards) => { for (const frame of cards) ports.devices?.card(frame) })
+ if (attached) for (const frame of cloudAgents?.liveCards() ?? []) ports.devices?.card(frame)
},
// What a device or another machine asks of an agent here: the SAME handlers the backend socket
// drives, called directly — the slash-command adaptation and the turn and question plumbing live there.
@@ -851,16 +870,16 @@ async function runForeground(session: AuthSession | null): Promise<void> {
turns: {
send: (agentId, text) => backendRef?.onMessage?.(agentId, text),
stop: (agentId) => backendRef?.onCancel?.(agentId),
- recent: async (agentId, n) => mirror.recent(registry.resolve(agentId)?.sessionId || agentId, n),
+ recent: async (agentId, n) => cloudAgents?.recent(agentId) ?? mirror.recent(registry.resolve(agentId)?.sessionId || agentId, n),
asks: async (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
// REQUEST id, not the question key `asking.answer` expects, and named a question that does not exist.
- answer: (agentId, requestId, answers) => { void asking.answer({ agentId, requestId, answers }) },
- answerReviewed: async (answer) => (await questions.answer({ agentId: answer.agentId, requestId: answer.requestId,
- answers: answer.answers, expectedQuestions: answer.questions, selectedLabels: answer.selections, freeTextKeys: answer.freeTextKeys })).ok,
+ answer: (agentId, requestId, answers) => { void (cloudAgents?.answer({ requestId, answers }) ?? asking.answer({ agentId, requestId, answers })) },
+ answerReviewed: async (answer) => (await (cloudAgents?.answer({ requestId: answer.requestId, answers: answer.answers }) ?? questions.answer({ agentId: answer.agentId, requestId: answer.requestId,
+ answers: answer.answers, expectedQuestions: answer.questions, selectedLabels: answer.selections, freeTextKeys: answer.freeTextKeys }))).ok,
},
})
// Each service starts and is called through the host, so one that fails is logged and left off and
@@ -1196,7 +1215,11 @@ async function runForeground(session: AuthSession | null): Promise<void> {
deviceInput,
})
const questions = asking.questions
- backend.questionProvider = asking.questionResponse
+ // Cloud harnesses (core/agents/cloud.ts): listed with the rest; their questions shown as the panes' are, and
+ // answered through the cloud service.
+ cloudAgents = createCloudAgents({ port: () => ports.cloud, clients: backend, openQuestions: asking.openQuestions, deviceInput })
+ const cloud = cloudAgents
+ backend.questionProvider = createQuestionResponse((payload) => cloud.answer(payload) ?? asking.answer(payload))
const openQuestions = asking.openQuestions
// The agents on this machine (core/agents/list.ts), in the socket's frames, with its monitor readings.
backend.agentsProvider = createAgentList({
@@ -1204,6 +1227,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
toProject: (s) => backend.toProject(s), toStoppedProject: (s) => backend.toStoppedProject(s),
// The monitor's readings, through its port (services/monitor.ts): none while it is off.
harnessResourcesReader: () => (ports.monitor ?? MONITOR_OFF).resources(), harnessStorageReader: (agents, invalidate) => (ports.monitor ?? MONITOR_OFF).storage(agents, invalidate),
+ cloudFrames: () => cloud.frames(),
}).agentsList
const questionWatcher = asking.questionWatcher
@@ -1415,6 +1439,10 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// 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)
+ // Cloud agents, an experiment (services/cloud.ts): in its own process once it is on, asked through its port
+ // (core/cloudLink.ts), which starts it; or in this one behind the service host's guard.
+ if (outOfProcess.has('cloud')) ports.cloud = createCloudLink((type, payload) => serviceLinks.call('cloud', type, payload))
+ else serviceHost.start('cloud', inline!.startCloud, coreApi, CLOUD_FALLBACKS, CLOUD_REQUESTS)
backend.onFrameSent = (frame) => ports.orchestrator?.frame(frame)
// Share (services/sharing.ts): in this process, or in its own once it is on (core/sharingLink.ts). Its
// observers' frames reach it as the relay hands them over.
@@ -1498,11 +1526,17 @@ async function runForeground(session: AuthSession | null): Promise<void> {
.find((session) => session.tmuxPane === tmuxPane
|| session.runtimes.some((runtime) => runtime.backend === 'tmux' && runtime.paneId === tmuxPane))?.agentId ?? null
// A rename, a model and effort, or an app opening an agent (core/agents/update.ts).
- backend.agentUpdateProvider = createAgentUpdate({
+ const agentUpdate = createAgentUpdate({
registry, clients: backend, toProject: (s) => backend.toProject(s), closeAgentService: () => backend.closeAgentService,
onAgentRename: (session, name) => { void terminals.setTitle(session, name) },
onRuntimeProfileUpdate: (sessionId, selectedModel) => runtimeController.setProfile(sessionId, selectedModel),
}).agentUpdate
+ // A cloud harness is no registry row: its rename goes to the cloud service (core/agents/cloud.ts).
+ backend.agentUpdateProvider = async (payload, reply) => {
+ const cloud = cloudAgents?.update(payload)
+ if (cloud) reply(await cloud)
+ else await agentUpdate(payload, reply)
+ }
runtimeProfiles.onChanged = (sessionId) => {
const session = registry.resolve(sessionId)
if (session) syncSession(session)
@@ -2474,7 +2508,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {
restoreCancelled = (agentId) => stopJobs.has(agentId) || pinnedControls.has(agentId) || (restartJobs.operation(agentId) !== undefined && restartJobs.operation(agentId) !== 'restart')
binding.whileChanging((agentId) => restorePanes.busy(agentId) || restartJobs.busy(agentId) || stopJobs.has(agentId))
const stopAgent = lifecycle.stopAgent
- backend.stopProvider = createStopRequest({ byAgent: (id) => registry.byAgent(id), stop: stopAgent })
+ const stopTerminalAgent = createStopRequest({ byAgent: (id) => registry.byAgent(id), stop: stopAgent })
+ backend.stopProvider = (payload) => cloud.stop(String(payload.agentId ?? payload.sessionId ?? '')) ?? stopTerminalAgent(payload)
backend.purgeAgentService = lifecycle.purgeAgentService
backend.purgeProvider = createPurgeRequest({ purgeAgentService: () => lifecycle.purgeAgentService, invalidateStorage: () => { void (ports.monitor ?? MONITOR_OFF).storage([], true) } })
// Closing agents no window shows, and the cleanup preview (core/agents/close.ts).
@@ -2530,15 +2565,35 @@ async function runForeground(session: AuthSession | null): Promise<void> {
byAgent: (id) => registry.byAgent(id), toProject: (s) => backend.toProject(s),
modelTarget: (selection) => (ports.models ?? MODELS_OFF).launchTarget(selection),
})
- backend.createProvider = launches.create
+ // A cloud agent is made by its service (core/agents/cloud.ts); every other engine launches here.
+ // Answered when the service answers, never in the connection's line: the window's next requests go on.
+ backend.createProvider = async (payload, asker, answer) => {
+ const made = cloud.create(payload)
+ if (made) void made.then(answer)
+ else await launches.create(payload, asker, answer)
+ }
backend.createStatusProvider = launches.createStatus
backend.cancelCreateProvider = launches.cancelCreate
backend.restartProvider = launches.relaunch
backend.forkProvider = launches.fork
const submitAgent = inputs.submitAgent
- backend.onMessage = (id, content, deliveryId) => submitAgent(id, content, deliveryId)
- backend.messageProvider = inputs.messageRequest
+ // Words for a cloud harness go to its service, and a delivery among them is settled as the pane's are.
+ backend.onMessage = (id, content, deliveryId) => {
+ // An Agent Messages turn its mailbox no longer wants written waits, as a pane's does (core/input.ts).
+ if (cloud.owns(id) && deliveryId?.startsWith('team:') && !(ports.messages?.canWrite(deliveryId) ?? false)) {
+ deliveries.settled({ deliveryId, sessionId: id, state: 'rejected', reason: 'team_waiting_control' })
+ return
+ }
+ const sent = cloud.deliver(id, content)
+ if (!sent) { submitAgent(id, content, deliveryId); return }
+ if (deliveryId) void sent.then((result) => deliveries.settled({ deliveryId, sessionId: id, state: result.ok ? 'delivered' : 'rejected', ...(result.ok ? {} : { reason: result.error }) }))
+ }
+ backend.messageProvider = (payload) => {
+ const agentId = typeof payload.agentId === 'string' ? payload.agentId : typeof payload.sessionId === 'string' ? payload.sessionId : ''
+ if (cloud.owns(agentId)) { void cloud.deliver(agentId, typeof payload.content === 'string' ? payload.content : ''); return }
+ inputs.messageRequest(payload)
+ }
backend.onCancelOrchestratorMessage = id => input.cancelDelivery(id)
deliveries.ready() // The input is wired: what was delivered meanwhile (Agent Messages' queue resuming) is written now.
@@ -2738,7 +2793,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
if (!isLocalOnly(card)) wifiCore.card(withoutUpdate(card))
const payload = card.payload as Record<string, unknown> | undefined
const full = card.type === 'commander_event' && payload?.kind === 'summary' && typeof card.agentId === 'string'
- ? mirror.lastFullText(registry.byAgent(card.agentId)?.sessionId ?? card.agentId) : undefined
+ ? mirror.lastFullText(registry.byAgent(card.agentId)?.sessionId ?? card.agentId) ?? cloudAgents?.said(card.agentId) : undefined
ports.devices?.card(full ? { ...card, payload: { ...payload, fullText: full } } : card)
}
diff --git a/cli/src/harnessd/services.ts b/cli/src/harnessd/services.ts
index 0df1411a1..46e69d195 100644
--- a/cli/src/harnessd/services.ts
+++ b/cli/src/harnessd/services.ts
@@ -403,6 +403,9 @@ export const SERVICE_HOSTS: Readonly<Record<string, ServiceHostSpec>> = {
// The router (services/routerProcess.ts), an experiment: started at its first request. A few decisions in
// flight, each one bounded Jev answer.
router: { services: ['router'], heapLimitMiB: 128, rssLimitMiB: 384, onDemand: true },
+ // Cloud agents (services/cloudProcess.ts), an experiment: started once one is on, for a saved harness or a
+ // request. A timer and a bounded look per working harness, and each conversation read a file at a time.
+ cloud: { services: ['cloud'], heapLimitMiB: 128, rssLimitMiB: 384, onDemand: true },
// Share, an experiment (services/sharingProcess.ts): its invitations, its observers' sessions and their
// ciphers; the headless Chrome it captures a shared viewer in is a process of its own, outside this budget.
sharing: { services: ['sharing'], heapLimitMiB: 256, rssLimitMiB: 512, onDemand: true },
diff --git a/cli/src/lib/cloudAgents.spec.ts b/cli/src/lib/cloudAgents.spec.ts
new file mode 100644
index 000000000..c52f42d7e
--- /dev/null
+++ b/cli/src/lib/cloudAgents.spec.ts
@@ -0,0 +1,45 @@
+import { describe, expect, it } from 'vitest'
+import { CLOUD_AGENT_IDS, cloudAgentFrame, cloudHarnessIn, isCloudAgent, type CloudHarness } from './cloudAgents.js'
+
+const harness: CloudHarness = {
+ agentId: 'cloud_1', agent: 'devin-cloud', name: 'fix it', state: 'working', activity: null, repository: 'acme/api', branch: 'devin/fix',
+ links: [{ label: 'Pull request #42', url: 'https://github.com/acme/api/pull/42' }], messages: 3, createdAt: '2026-10-11T10:00:00.000Z', updatedAt: '2026-10-11T10:05:00.000Z',
+}
+
+describe('cloud agents', () => {
+ it('are never engines, and are named by the Naming System\'s rule', () => {
+ expect(CLOUD_AGENT_IDS).toEqual(['fo', 'devin-cloud', 'cursor-cloud'])
+ expect(isCloudAgent('devin-cloud')).toBe(true)
+ expect(isCloudAgent('devin')).toBe(false)
+ expect(isCloudAgent('toString')).toBe(false)
+ })
+
+ it('keep nothing of a reported harness they cannot read', () => {
+ expect(cloudHarnessIn(harness)).toEqual({ ...harness, said: null })
+ // Its last words, kept to what the dial's longest card can use.
+ expect(cloudHarnessIn({ ...harness, said: ` ${'a'.repeat(5_000)}` })!.said).toHaveLength(4_000)
+ expect(cloudFrameHasNoWords()).toBe(true)
+ for (const bad of [null, 'x', { ...harness, agentId: 'a1' }, { ...harness, agent: 'claude' }, { ...harness, state: 'odd' }, { ...harness, createdAt: 'never' }]) expect(cloudHarnessIn(bad)).toBeNull()
+ expect(cloudHarnessIn({ ...harness, name: '', activity: 5, repository: '', links: [{ label: 'x', url: 'http://no' }, { url: 'https://a' }, null], messages: -1 }))
+ .toMatchObject({ name: 'Devin Cloud', activity: null, repository: null, links: [], messages: 0 })
+ expect(cloudHarnessIn({ ...harness, links: 'x', messages: 1.5 })).toMatchObject({ links: [], messages: 0 })
+ })
+
+ // What it said stays in the core: the apps read the whole conversation.
+ const cloudFrameHasNoWords = (): boolean => !JSON.stringify(cloudAgentFrame({ ...harness, said: 'secret words' })).includes('secret words')
+
+ it('travel as an agent\'s frame with no pane, its repository as its project', () => {
+ expect(cloudAgentFrame(harness)).toMatchObject({
+ id: 'cloud_1', sessionId: 'cloud_1', name: 'fix it', status: 'active', engine: 'devin-cloud', location: 'cloud', tmuxPane: null,
+ terminal: { available: false, primary: '', runtimes: [] }, launch: { state: 'ready' }, closeSupported: false, forkable: false,
+ activity: { state: 'working', validForMs: 120_000 },
+ project: { kind: 'git', name: 'api', remote: 'https://github.com/acme/api', branch: 'devin/fix' },
+ gitContext: { state: 'workspace' },
+ cloud: { place: "Devin's cloud", state: 'working', activity: null, links: harness.links, messages: 3 },
+ })
+ expect(cloudAgentFrame({ ...harness, state: 'stopped', repository: null })).toMatchObject({ status: 'stopped', project: null, gitContext: { state: 'unavailable', current: null }, activity: { state: 'idle', validForMs: 0 } })
+ expect(cloudAgentFrame({ ...harness, state: 'starting' }).launch).toEqual({ state: 'starting' })
+ expect(cloudAgentFrame({ ...harness, state: 'failed' }).launch).toEqual({ state: 'failed', error: 'CLOUD_FAILED', detail: 'Devin Cloud stopped with an error.' })
+ expect(cloudAgentFrame({ ...harness, state: 'failed', activity: 'It reached its ACU limit.' }).launch).toMatchObject({ detail: 'It reached its ACU limit.' })
+ })
+})
diff --git a/cli/src/lib/cloudAgents.ts b/cli/src/lib/cloudAgents.ts
new file mode 100644
index 000000000..1ff131f52
--- /dev/null
+++ b/cli/src/lib/cloudAgents.ts
@@ -0,0 +1,173 @@
+/**
+ * Cloud agents: agents that run on their maker's servers and are reached through its API rather than started
+ * as a terminal program here (docs/design/2026-10-11-cloud-agents.md). The cloud service owns them
+ * (services/cloud.ts); the core lists them beside the terminal agents and routes a person's answers,
+ * messages and Stop to that service (core/agents/cloud.ts). This file is what the two, and the frames the
+ * apps read, share.
+ *
+ * A cloud agent's id is never an engine id (engines/types.ts `ENGINES`): it has no launch, transcript or pane,
+ * and every per-engine table in the core would otherwise need a row for it that could only refuse.
+ */
+import type { AgentFrame } from './agentFrame.js'
+
+export interface CloudAgentInfo {
+ /** What the apps call it: a CLI agent's name plus "Cloud" for its maker's cloud coding agent (Naming System). */
+ name: string
+ /** Where it runs, said where a remote computer's name goes. */
+ place: string
+ /** A coding agent works on a GitHub repository; a personal agent runs errands and takes no repository. */
+ kind: 'coding' | 'personal'
+ /** How its connection is found among the person's Connections: by the host its MCP server or API is at. */
+ connection: { mcp: string } | { api: string }
+ /** What to connect, said when it is not connected. */
+ connect: string
+}
+
+export const CLOUD_AGENTS = {
+ fo: {
+ name: 'Fo', place: "Fo's cloud", kind: 'personal', connection: { mcp: 'mcp.api.wajo.ai' },
+ connect: 'Connect Fo in Connections (Add custom, https://mcp.api.wajo.ai/fo).',
+ },
+ 'devin-cloud': {
+ name: 'Devin Cloud', place: "Devin's cloud", kind: 'coding', connection: { api: 'https://api.devin.ai' },
+ connect: 'Add your Devin API key: harness connections add-key Devin https://api.devin.ai',
+ },
+ 'cursor-cloud': {
+ name: 'Cursor Cloud', place: "Cursor's cloud", kind: 'coding', connection: { api: 'https://api.cursor.com' },
+ connect: 'Add your Cursor API key: harness connections add-key Cursor https://api.cursor.com',
+ },
+} as const satisfies Record<string, CloudAgentInfo>
+
+export type CloudAgentId = keyof typeof CLOUD_AGENTS
+export const CLOUD_AGENT_IDS = Object.keys(CLOUD_AGENTS) as CloudAgentId[]
+
+export function isCloudAgent(id: unknown): id is CloudAgentId {
+ return typeof id === 'string' && Object.hasOwn(CLOUD_AGENTS, id)
+}
+
+/** Where a cloud harness is: working, waiting on the person, done with its turn, failed, or stopped. */
+export type CloudState = 'starting' | 'working' | 'needs_input' | 'idle' | 'failed' | 'stopped'
+export const CLOUD_STATES: readonly CloudState[] = ['starting', 'working', 'needs_input', 'idle', 'failed', 'stopped']
+
+/** One cloud harness, as the cloud service tells the core about it (`core.cloud.publish`). */
+export interface CloudHarness {
+ /** Harness's own id for it, `cloud_…`: never the vendor's session id, which the service keeps. */
+ agentId: string
+ agent: CloudAgentId
+ name: string
+ state: CloudState
+ /** What it is doing, in a line ("Calling Hair Lab"), or null. */
+ activity: string | null
+ /** The GitHub repository a coding agent works on (`owner/name`), or null. */
+ repository: string | null
+ branch: string | null
+ /** Where to see it at its maker (the session page) and what it made (a pull request). */
+ links: { label: string; url: string }[]
+ /** How many messages its conversation holds: a client that shows it reads the conversation again when this moves. */
+ messages: number
+ /** What it said last, for the dial's card: a terminal agent's turn ends with its answer the same way. Kept in
+ * the core alone, never in a frame: the apps read the whole conversation. */
+ said?: string | null
+ createdAt: string
+ updatedAt: string
+}
+
+/** As much of its last words as the dial's longest card draws, and some over (lib/deviceRecap.ts). */
+export const SAID_MAX = 4_000
+
+const text = (value: unknown, max = 500): string | null => (typeof value === 'string' && value.trim() ? value.trim().slice(0, max) : null)
+const stamp = (value: unknown): string | null => (typeof value === 'string' && Number.isFinite(Date.parse(value)) ? value : null)
+
+/** A harness as a service reported it, or null for anything else: the core keeps nothing it cannot read. */
+export function cloudHarnessIn(raw: unknown): CloudHarness | null {
+ if (!raw || typeof raw !== 'object') return null
+ const value = raw as Record<string, unknown>
+ const agentId = text(value.agentId, 80)
+ const createdAt = stamp(value.createdAt), updatedAt = stamp(value.updatedAt)
+ if (!agentId?.startsWith('cloud_') || !isCloudAgent(value.agent) || !CLOUD_STATES.includes(value.state as CloudState) || !createdAt || !updatedAt) return null
+ const links = Array.isArray(value.links) ? value.links.flatMap((link) => {
+ const entry = link as Record<string, unknown> | null
+ const label = text(entry?.label, 80), url = text(entry?.url, 2048)
+ return label && url && /^https:\/\//.test(url) ? [{ label, url }] : []
+ }).slice(0, 8) : []
+ return {
+ agentId,
+ agent: value.agent,
+ name: text(value.name, 120) ?? CLOUD_AGENTS[value.agent].name,
+ state: value.state as CloudState,
+ activity: text(value.activity, 200),
+ repository: text(value.repository, 200),
+ branch: text(value.branch, 200),
+ links,
+ messages: typeof value.messages === 'number' && Number.isInteger(value.messages) && value.messages >= 0 ? value.messages : 0,
+ said: text(value.said, SAID_MAX),
+ createdAt,
+ updatedAt,
+ }
+}
+
+/** What the apps read about a cloud agent beyond an agent's usual frame: `location: 'cloud'` and this. */
+export interface CloudFrameBlock {
+ place: string
+ state: CloudState
+ activity: string | null
+ links: { label: string; url: string }[]
+ messages: number
+}
+
+export type CloudAgentFrame = Omit<AgentFrame, 'engine'> & { engine: CloudAgentId; location: 'cloud'; cloud: CloudFrameBlock }
+
+/**
+ * A cloud harness as every client reads an agent: the same frame a terminal agent has, with no pane and no
+ * terminal (as a stopped agent's), `location: 'cloud'` for the chat pane, and its repository as its project
+ * so the footer and the pull request read it as they read any other.
+ */
+export function cloudAgentFrame(harness: CloudHarness): CloudAgentFrame {
+ const working = harness.state === 'working' || harness.state === 'starting'
+ const project = harness.repository
+ ? { kind: 'git' as const, name: harness.repository.split('/').pop() ?? harness.repository, cwd: '', root: null,
+ remote: `https://github.com/${harness.repository}`, branch: harness.branch }
+ : null
+ return {
+ id: harness.agentId,
+ sessionId: harness.agentId,
+ userId: '',
+ name: harness.name,
+ title: null,
+ status: harness.state === 'stopped' ? 'stopped' : 'active',
+ activity: { state: working ? 'working' : 'idle', epoch: harness.agentId, revision: Date.parse(harness.updatedAt), validForMs: working ? 120_000 : 0 },
+ closePlan: null,
+ closeSupported: false,
+ launch: harness.state === 'failed' ? { state: 'failed', error: 'CLOUD_FAILED', detail: harness.activity ?? `${CLOUD_AGENTS[harness.agent].name} stopped with an error.` }
+ : harness.state === 'starting' ? { state: 'starting' } : { state: 'ready' },
+ createdAt: harness.createdAt,
+ updatedAt: harness.updatedAt,
+ lastOpenedAt: null,
+ tokenUsage: null,
+ outputStats: null,
+ tmuxPane: null,
+ terminal: { available: false, primary: '', runtimes: [] },
+ engine: harness.agent,
+ selectedModel: null,
+ grid: null,
+ codexHome: null,
+ project,
+ gitContext: { state: project ? 'workspace' : 'unavailable', current: project, observedAt: null, locations: [], pullRequests: [], truncated: false },
+ dsh: null,
+ dshName: null,
+ viewerUrl: null,
+ viewerName: null,
+ verdict: null,
+ forkedFrom: null,
+ forkable: false,
+ // A person starts a cloud harness from New Harness: no agent here or elsewhere started it.
+ parentAgentId: null,
+ startedBy: null,
+ resumeMode: 'conversation',
+ permissionMode: null,
+ bypassPermission: null,
+ namedAgent: null,
+ location: 'cloud',
+ cloud: { place: CLOUD_AGENTS[harness.agent].place, state: harness.state, activity: harness.activity, links: harness.links, messages: harness.messages },
+ }
+}
diff --git a/cli/src/lib/connectors/agents.ts b/cli/src/lib/connectors/agents.ts
index 0f9b0291a..dd99e0f31 100644
--- a/cli/src/lib/connectors/agents.ts
+++ b/cli/src/lib/connectors/agents.ts
@@ -31,6 +31,22 @@ export function bridgeKey(vault: Store): string {
})
}
+/**
+ * The capability for Harness's own calls through the bridge (its cloud agents, services/cloud.ts): a second key,
+ * in `harness-key.json`, never written into an agent's configuration. The bridge's key is in every agent's MCP
+ * entry, so an agent (one a page talked into it) could otherwise list the connections and spend a Devin or
+ * Cursor key through the `/api/` route.
+ */
+export function harnessKey(vault: Store): string {
+ return locked(vault.root, () => {
+ const key = vault.file('harness-key.json').key
+ if (typeof key === 'string' && key.length >= 32) return key
+ const fresh = randomBytes(32).toString('base64url')
+ writePrivate(join(vault.root, 'harness-key.json'), { key: fresh })
+ return fresh
+ })
+}
+
export function bridgeUrl(key: string, code: string, port = bridgePort()): string {
return `http://127.0.0.1:${port}/${key}/${code}/mcp`
}
diff --git a/cli/src/lib/connectors/bridge.ts b/cli/src/lib/connectors/bridge.ts
index 3dd0af939..764cc8634 100644
--- a/cli/src/lib/connectors/bridge.ts
+++ b/cli/src/lib/connectors/bridge.ts
@@ -3,17 +3,24 @@
* service's MCP server with the stored credential, renewing it first when it is about to expire, and streams
* the answer back (event streams included). A service reached by REST (no MCP server the grant can use) is
* answered here instead, its REST tools served as MCP (rest.ts). Runs in the daemon (services/connectors.ts).
+ *
+ * Two more addresses serve Harness's own cloud agents (services/cloud.ts), which hold no credential either:
+ * - `/<key>/connections`: what is connected, by address and with no secret, so the service finds the
+ * connection that signs in Fo or Devin by where it points rather than by what the person named it;
+ * - `/<key>/<code>/api/<path>`: one request to a key-only connection's own API (`api_entry`), with its key.
*/
import { timingSafeEqual } from 'node:crypto'
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'
import { Readable } from 'node:stream'
import { label } from './catalog.js'
-import { needsRefresh, refreshable, type Store, type Token } from './store.js'
+import { bearer, needsRefresh, refreshable, type Store, type Token } from './store.js'
import { refresh } from './renew.js'
import { answer as answerRest, transport } from './rest.js'
/** Headers an MCP client sends that the service must see. Authorization never comes from the agent. */
const FORWARD = ['accept', 'content-type', 'mcp-session-id', 'mcp-protocol-version', 'last-event-id']
+/** Headers a REST call through `/api/` may carry. */
+const FORWARD_API = ['accept', 'content-type', 'last-event-id']
const RETURN = ['content-type', 'mcp-session-id', 'mcp-protocol-version', 'cache-control']
const MAX_BODY = 16 * 1024 * 1024
@@ -40,16 +47,69 @@ function readBody(request: IncomingMessage): Promise<Buffer | null> {
export interface BridgeOptions {
/** The capability agents' addresses carry (agents.ts bridgeKey), read per request. */
key: () => string
+ /** Harness's own capability (agents.ts harnessKey), never in an agent's configuration: only it lists the
+ * connections or calls a key-only connection's API. Absent, those two addresses answer nothing. */
+ harnessKey?: () => string
}
+type Target = { kind: 'mcp'; code: string } | { kind: 'api'; code: string; path: string } | { kind: 'list' }
+
export function createBridge(vault: Store, options: BridgeOptions): Server {
- const target = (url: string): string | null => {
+ const target = (url: string): Target | null => {
const parts = new URL(url, 'http://127.0.0.1').pathname.replace(/^\/|\/$/g, '').split('/')
- if (parts.length !== 3 || parts[2] !== 'mcp') return null
- const key = options.key()
const given = Buffer.from(parts[0])
- if (!key || given.length !== Buffer.byteLength(key) || !timingSafeEqual(given, Buffer.from(key))) return null
- return parts[1]
+ const matches = (key: string): boolean => !!key && given.length === Buffer.byteLength(key) && timingSafeEqual(given, Buffer.from(key))
+ const harness = matches(options.harnessKey?.() ?? '')
+ if (!harness && !matches(options.key())) return null
+ if (parts.length === 3 && parts[2] === 'mcp') return { kind: 'mcp', code: parts[1] }
+ // An agent's key reaches MCP servers only: the list and the API keys are Harness's alone.
+ if (!harness) return null
+ if (parts.length === 2 && parts[1] === 'connections') return { kind: 'list' }
+ if (parts.length >= 4 && parts[2] === 'api') return { kind: 'api', code: parts[1], path: `/${parts.slice(3).join('/')}` }
+ return null
+ }
+
+ /** What is connected, with no secret: an MCP server's address without its query, which can carry a key. */
+ const list = (response: ServerResponse): void => {
+ const connections = Object.entries(vault.tokens()).map(([code, token]) => {
+ const mcp = token.mcp_entry ? new URL(token.mcp_entry.url) : null
+ return { code, name: token.label || label(code), mcp: mcp ? `${mcp.origin}${mcp.pathname}` : null, api: token.api_entry?.origin ?? null,
+ state: token.needs_reconnect ? 'reconnect' : 'connected' }
+ })
+ const raw = JSON.stringify({ connections })
+ response.writeHead(200, { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(raw) }).end(raw)
+ }
+
+ /** One request to a key-only connection's API, pinned to its origin: a path such as `//elsewhere` cannot
+ * carry the key to another host. A key is never renewed, so a 401 means connect it again. */
+ const serveApi = async (name: string, token: Token, path: string, request: IncomingMessage, response: ServerResponse, body: Buffer | null): Promise<void> => {
+ const origin = token.api_entry?.origin
+ if (!origin || !token.access_token) { fail(response, 404, `${name} has no API to call.`); return }
+ const upstream = new URL(`${origin}${path}`)
+ if (upstream.origin !== origin) { fail(response, 404, 'Unknown connection address.'); return }
+ upstream.search = new URL(request.url ?? '/', 'http://127.0.0.1').search
+ const headers: Record<string, string> = {}
+ for (const header of FORWARD_API) {
+ const value = request.headers[header]
+ if (typeof value === 'string') headers[header] = value
+ }
+ Object.assign(headers, { authorization: bearer(token), 'user-agent': 'Harness-Connections' })
+ let answer: Response
+ try {
+ answer = await fetch(upstream, { method: request.method, headers, body: body ?? undefined, redirect: 'manual', signal: AbortSignal.timeout(300_000) })
+ } catch { fail(response, 502, `${name} could not be reached. Try again.`); return }
+ if (answer.status === 401) {
+ await answer.body?.cancel()
+ fail(response, 401, `${name} needs to be connected again. Open harness connections.`); return
+ }
+ const back: Record<string, string> = {}
+ for (const header of ['content-type', 'cache-control']) {
+ const value = answer.headers.get(header)
+ if (value) back[header] = value
+ }
+ response.writeHead(answer.status, back)
+ if (!answer.body) { response.end(); return }
+ Readable.fromWeb(answer.body as import('node:stream/web').ReadableStream).on('error', () => response.destroy()).pipe(response)
}
const forward = (token: Token, request: IncomingMessage, body: Buffer | null): Promise<Response> => {
@@ -89,14 +149,17 @@ export function createBridge(vault: Store, options: BridgeOptions): Server {
if (request.headers.origin || !['127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(request.socket.remoteAddress ?? '')) {
fail(response, 403, 'Forbidden.'); return
}
- const code = target(request.url ?? '/')
- if (!code) { fail(response, 404, 'Unknown connection address. Run harness connections sync.'); return }
+ const address = target(request.url ?? '/')
+ if (!address) { fail(response, 404, 'Unknown connection address. Run harness connections sync.'); return }
+ if (address.kind === 'list') { list(response); return }
+ const code = address.code
if (request.headers['transfer-encoding'] && !request.headers['content-length']) { fail(response, 411, 'Send the request with a Content-Length.'); return }
let body: Buffer | null
try { body = await readBody(request) } catch { fail(response, 413, 'Request is too large.'); return }
const name = vault.token(code)?.label || label(code)
let stored: Token | undefined
try { stored = vault.token(code) } catch (error) { fail(response, 401, `${name}: ${(error as Error).message}`); return }
+ if (stored && address.kind === 'api') { await serveApi(name, stored, address.path, request, response, body); return }
const via = stored ? transport(stored) : 'none'
if (!stored || via === 'none') { fail(response, 404, `${name} is not connected. Open harness connections to connect it.`); return }
if (via === 'rest') { await serveRest(code, request, response, body); return }
diff --git a/cli/src/lib/connectors/command.ts b/cli/src/lib/connectors/command.ts
index eab3959b0..cd9957da8 100644
--- a/cli/src/lib/connectors/command.ts
+++ b/cli/src/lib/connectors/command.ts
@@ -4,7 +4,7 @@ import { existsSync } from 'node:fs'
import { join } from 'node:path'
import { label, services } from './catalog.js'
import { sync } from './agents.js'
-import { disconnect, finish, signInFor } from './connect.js'
+import { addApiKey, disconnect, finish, signInFor } from './connect.js'
import { call, CallFailure, OFFICIAL_HOSTS, type Output } from './call.js'
import * as gateway from './gateway.js'
import { forgetPage, PageServer, rememberPage, runningPage } from './page.js'
@@ -17,6 +17,9 @@ export const connectionsUsage = `Connected services (Linear, Notion, GitHub, Goo
harness connections list [--json] this computer's connections (no secrets)
harness connections info <code>
harness connections disconnect <code>
+ harness connections add-key <name> <https-url>
+ a service's API key, read from stdin, for Harness's cloud agents
+ (Devin Cloud, Cursor Cloud); never given to the agents here
harness connections refresh [<code>] renew tokens that are due (or this one now)
harness connections sync give Claude Code, Codex and OpenCode their MCP entries again
harness connections call <code> <METHOD> <https-url> [--query K=V] [--json BODY|-] [--data K=V]
@@ -101,8 +104,26 @@ function info(vault: Store, code: string, io: Output): number {
return 0
}
+/** A key from stdin: piped, or typed at a prompt that does not echo it. */
+async function readKey(): Promise<string> {
+ if (!process.stdin.isTTY) {
+ const chunks: Buffer[] = []
+ for await (const chunk of process.stdin) chunks.push(chunk as Buffer)
+ return Buffer.concat(chunks).toString('utf8').trim()
+ }
+ const { createInterface } = await import('node:readline')
+ const prompt = createInterface({ input: process.stdin, output: process.stdout, terminal: true })
+ process.stdout.write('API key (not shown): ')
+ // Nothing typed is drawn: the key never reaches the screen or the terminal's scrollback.
+ ;(prompt as unknown as { _writeToOutput: (text: string) => void })._writeToOutput = () => {}
+ const key = await new Promise<string>(resolve => prompt.question('', resolve))
+ prompt.close()
+ process.stdout.write('\n')
+ return key.trim()
+}
+
export async function connectionsCommand(argv: string[], io: Output = { out: text => process.stdout.write(text), err: text => process.stderr.write(text + '\n') },
- vault = new Store()): Promise<number> {
+ vault = new Store(), key: () => Promise<string> = readKey): Promise<number> {
const [verb, ...rest] = argv
try {
if (!verb || verb === 'open') return await openPage(vault, io)
@@ -115,6 +136,11 @@ export async function connectionsCommand(argv: string[], io: Output = { out: tex
io.out('Disconnected on this computer. Revoke access at the provider to remove it elsewhere.\n')
return 0
}
+ if (verb === 'add-key' && rest.length === 2) {
+ const added = addApiKey(vault, { name: rest[0], url: rest[1], key: await key() })
+ io.out(`Connected ${rest[0]} as ${String(added.connector)}.\n`)
+ return 0
+ }
if (verb === 'sync' && rest.length === 0) {
const changed = sync(vault)
io.out(`Agents updated: ${Object.keys(changed).sort().join(', ') || 'none installed'}\n`)
diff --git a/cli/src/lib/connectors/connect.ts b/cli/src/lib/connectors/connect.ts
index 4c5f6a690..e0a6e5cfb 100644
--- a/cli/src/lib/connectors/connect.ts
+++ b/cli/src/lib/connectors/connect.ts
@@ -92,7 +92,7 @@ export function cards(vault: Store, offered: Record<string, GatewayRow>): { conn
for (const [code, token] of Object.entries(tokens)) {
if (code in known) continue
const custom = token.source === 'custom'
- result.push({ ...vault.status(code, code, token), description: token.mcp_entry?.url ?? '', auth: custom ? 'custom' : token.source ?? 'dcr', custom, reason: '' })
+ result.push({ ...vault.status(code, code, token), description: token.mcp_entry?.url ?? token.api_entry?.origin ?? '', auth: custom ? 'custom' : token.source ?? 'dcr', custom, reason: '' })
}
return { connections: result, signed_in: signedIn }
}
@@ -112,4 +112,20 @@ export async function addCustom(vault: Store, flows: Flows, data: Record<string,
return { connector: code, ...(await flows.start(code, new LocalSignIn(vault, url), name)) }
}
+/**
+ * A key-only connection: a service's own API, called with a key by Harness's cloud agents through the bridge
+ * (`/<key>/<code>/api/…`, bridge.ts). Kept from every agent's MCP configuration (`transport: none`): the key is
+ * for the cloud agent the service starts, not a tool for the agents on this computer.
+ */
+export function addApiKey(vault: Store, data: Record<string, unknown>, env: NodeJS.ProcessEnv = process.env): Record<string, unknown> {
+ const name = text(data.name, 64).trim()
+ const origin = new URL(cleanUrl(typeof data.url === 'string' ? data.url.trim() : data.url)).origin
+ const key = text(data.key, 4096).trim()
+ if (!name) throw new ConnectorError('Give the service a name.')
+ if (!key) throw new ConnectorError('Paste the API key.')
+ const code = customCode(name, new Set([...Object.keys(vault.tokens()), ...Object.keys(services())]))
+ finish(vault, code, { access_token: key, token_type: 'Bearer', api_entry: { origin }, transport: 'none', obtained_at: Math.floor(Date.now() / 1000) }, name, env)
+ return { connector: code, state: 'connected' }
+}
+
export { CODE }
diff --git a/cli/src/lib/connectors/connectors.spec.ts b/cli/src/lib/connectors/connectors.spec.ts
index e95ae1d74..98998fccc 100644
--- a/cli/src/lib/connectors/connectors.spec.ts
+++ b/cli/src/lib/connectors/connectors.spec.ts
@@ -8,12 +8,12 @@ import { createServer, request as httpRequest } from 'node:http'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { FakeGateway, FakeService } from '../../testing/connectorServers.js'
-import { bridgeKey, sync } from './agents.js'
+import { bridgeKey, harnessKey, sync } from './agents.js'
import { createBridge } from './bridge.js'
import { CATALOG, services } from './catalog.js'
-import { addCustom, cards, customCode, disconnect, finish, Flows, signInFor } from './connect.js'
+import { addApiKey, addCustom, cards, customCode, disconnect, finish, Flows, signInFor } from './connect.js'
import * as gateway from './gateway.js'
-import { LocalSignIn } from './oauth.js'
+import { LocalSignIn, probe } from './oauth.js'
import { forgetPage, PageServer, rememberPage, runningPage } from './page.js'
import { refresh } from './renew.js'
import { call, OFFICIAL_HOSTS } from './call.js'
@@ -64,6 +64,14 @@ describe('signing in from this computer (MCP OAuth)', () => {
expect(fake.registered).toHaveLength(1)
})
+ it('signs in to a server that answers its handshake to anyone but says it is protected', async () => {
+ const fake = await service()
+ fake.openHandshake = true
+ expect(await probe(fake.base + '/mcp')).toMatchObject({ kind: 'oauth' })
+ finish(vault, 'fo', await signIn(fake), undefined, env)
+ expect(vault.token('fo')).toMatchObject({ source: 'dcr', mcp_entry: { headers: { Authorization: 'Bearer access-1' } } })
+ })
+
it('refuses a callback for another sign-in', async () => {
const fake = await service()
await expect(signIn(fake, true)).rejects.toThrow('could not be confirmed')
@@ -154,6 +162,93 @@ describe('the bridge', () => {
})
})
+describe('key-only connections for the cloud agents', () => {
+ let port: number
+ let key: string
+ let agentKey: string
+ const seen: { method: string, url: string, auth: string, body: string }[] = []
+ let status = 200
+ let api: string
+
+ beforeEach(async () => {
+ seen.length = 0
+ status = 200
+ const upstream = createServer((request, response) => {
+ const chunks: Buffer[] = []
+ request.on('data', chunk => chunks.push(chunk)).on('end', () => {
+ seen.push({ method: request.method!, url: request.url!, auth: String(request.headers.authorization), body: Buffer.concat(chunks).toString() })
+ response.writeHead(status, { 'Content-Type': 'application/json' }).end(JSON.stringify({ ok: true }))
+ })
+ })
+ await new Promise<void>(resolve => upstream.listen(0, '127.0.0.1', resolve))
+ api = `http://127.0.0.1:${(upstream.address() as { port: number }).port}`
+ closers.push(() => { upstream.close(); upstream.closeAllConnections() })
+ key = harnessKey(vault)
+ agentKey = bridgeKey(vault)
+ const bridge = createBridge(vault, { key: () => String(vault.file('bridge.json').key), harnessKey: () => String(vault.file('harness-key.json').key) })
+ await new Promise<void>(resolve => bridge.listen(0, '127.0.0.1', resolve))
+ port = (bridge.address() as { port: number }).port
+ closers.push(() => { bridge.close(); bridge.closeAllConnections() })
+ })
+
+ const send = (method: string, path: string, body?: string) => fetch(`http://127.0.0.1:${port}${path}`, { method, body, headers: body ? { 'Content-Type': 'application/json' } : {} })
+
+ it('saves a key only for Harness, never in an agent\'s MCP configuration', async () => {
+ expect(addApiKey(vault, { name: 'Devin', url: `${api}/ignored/path?q=1`, key: 'cog_secret' }, env)).toEqual({ connector: 'devin', state: 'connected' })
+ expect(vault.token('devin')).toMatchObject({ access_token: 'cog_secret', api_entry: { origin: api }, transport: 'none', source: 'custom', label: 'Devin' })
+ expect(JSON.stringify(sync(vault, env))).not.toContain('devin')
+ expect(() => addApiKey(vault, { name: 'Devin', url: api, key: ' ' }, env)).toThrow('Paste the API key.')
+ expect(() => addApiKey(vault, { name: '', url: api, key: 'k' }, env)).toThrow('Give the service a name.')
+ expect(() => addApiKey(vault, { name: 'Bad', url: 'http://example.com', key: 'k' }, env)).toThrow('https://')
+ })
+
+ it('calls the API with the key, pinned to its origin, and lists connections without a secret', async () => {
+ addApiKey(vault, { name: 'Devin', url: api, key: 'cog_secret' }, env)
+ finish(vault, 'fo', { mcp_entry: { url: 'https://mcp.example.com/fo?key=hidden', headers: { 'X-API-Key': 'wak_secret' } } }, 'Fo', env)
+ const answer = await send('POST', `/${key}/devin/api/v3/self?x=1`, '{"a":1}')
+ expect(answer.status).toBe(200)
+ expect(await answer.json()).toEqual({ ok: true })
+ expect(seen.at(-1)).toEqual({ method: 'POST', url: '/v3/self?x=1', auth: 'Bearer cog_secret', body: '{"a":1}' })
+ const listed = await (await send('GET', `/${key}/connections`)).text()
+ expect(listed).not.toContain('secret')
+ expect(listed).not.toContain('hidden')
+ expect(JSON.parse(listed).connections).toEqual(expect.arrayContaining([
+ { code: 'devin', name: 'Devin', mcp: null, api, state: 'connected' },
+ { code: 'fo', name: 'Fo', mcp: 'https://mcp.example.com/fo', api: null, state: 'connected' },
+ ]))
+ // Its MCP address is not served: nothing an agent could use.
+ expect((await send('POST', `/${key}/devin/mcp`, '{}')).status).toBe(404)
+ expect((await send('GET', `/${key}/fo/api/v1/x`)).status).toBe(404)
+ expect((await send('GET', `/wrong/devin/api/v3/self`)).status).toBe(404)
+ expect((await send('GET', `/${key}/devin/other/v3/self`)).status).toBe(404)
+ // The key in every agent's MCP entry reaches no API key and lists nothing.
+ expect(JSON.stringify(sync(vault, env))).not.toContain(key)
+ expect((await send('GET', `/${agentKey}/connections`)).status).toBe(404)
+ expect((await send('GET', `/${agentKey}/devin/api/v3/self`)).status).toBe(404)
+ expect(seen.filter((call) => call.url.startsWith('/v3/self'))).toHaveLength(1)
+ })
+
+ it('adds a key from the command, read from stdin rather than the command line', async () => {
+ const out: string[] = []
+ const io = { out: (text: string) => { out.push(text) }, err: (text: string) => { out.push(text) } }
+ expect(await connectionsCommand(['add-key', 'Cursor', api], io, vault, async () => 'key_secret')).toBe(0)
+ expect(out.join('')).toContain('Connected Cursor as cursor.')
+ expect(out.join('')).not.toContain('key_secret')
+ expect(vault.token('cursor')).toMatchObject({ access_token: 'key_secret', api_entry: { origin: api } })
+ expect(await connectionsCommand(['add-key', 'Cursor'], io, vault, async () => 'k')).toBe(2)
+ })
+
+ it('turns a refused key into Reconnect and an unreachable API into a retry', async () => {
+ addApiKey(vault, { name: 'Devin', url: api, key: 'cog_secret' }, env)
+ status = 401
+ const refused = await send('GET', `/${key}/devin/api/v3/self`)
+ expect(refused.status).toBe(401)
+ expect(((await refused.json()) as { error: { message: string } }).error.message).toContain('connected again')
+ vault.save('devin', { ...vault.token('devin')!, api_entry: { origin: 'http://127.0.0.1:1' } })
+ expect((await send('GET', `/${key}/devin/api/v3/self`)).status).toBe(502)
+ })
+})
+
describe('agent configs', () => {
it('gives each agent bridge addresses and keeps its own servers', () => {
const claude = join(home, '.claude.json')
diff --git a/cli/src/lib/connectors/oauth.ts b/cli/src/lib/connectors/oauth.ts
index 0192cebee..8c0c873d6 100644
--- a/cli/src/lib/connectors/oauth.ts
+++ b/cli/src/lib/connectors/oauth.ts
@@ -52,32 +52,46 @@ export interface OAuthMeta {
}
export type Probe = { kind: 'open' } | OAuthMeta
-/** What signing in to this MCP server takes: nothing (`open`) or its OAuth metadata. */
-export async function probe(server: string): Promise<Probe> {
- const url = cleanUrl(server)
- const initialize = JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: {
- protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'Harness', version: '1' } } })
- const first = await http(url, { body: initialize, headers: { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' } })
- if (first.status >= 200 && first.status < 300) return { kind: 'open' }
- if (first.status !== 401 && first.status !== 403) throw new SignInError(`The server answered ${first.status}. Check the address.`)
- const challenge = first.headers.get('www-authenticate') ?? ''
- const pointed = /resource_metadata="([^"]+)"/.exec(challenge)?.[1]
+/** The protected-resource metadata a server publishes (RFC 9728): its authorization server, the resource it names, its scopes. */
+async function protectedResource(url: string, pointed?: string): Promise<{ issuer: string; resource: string; scopes: string[] } | null> {
const path = new URL(url).pathname
- let issuer: string | undefined
- let resource = url
- let scopes: string[] = []
for (const candidate of [pointed, wellKnown(url, 'oauth-protected-resource', path), wellKnown(url, 'oauth-protected-resource')]) {
if (!candidate) continue
const answer = await http(candidate)
const meta = answer.status === 200 ? jsonOf(answer.body) : null
const servers = meta?.authorization_servers
if (Array.isArray(servers) && typeof servers[0] === 'string') {
- issuer = servers[0]
- resource = typeof meta!.resource === 'string' ? meta!.resource : url
- scopes = Array.isArray(meta!.scopes_supported) ? meta!.scopes_supported.filter((s): s is string => typeof s === 'string') : []
- break
+ return {
+ issuer: servers[0],
+ resource: typeof meta!.resource === 'string' ? meta!.resource : url,
+ scopes: Array.isArray(meta!.scopes_supported) ? meta!.scopes_supported.filter((s): s is string => typeof s === 'string') : [],
+ }
}
}
+ return null
+}
+
+/** What signing in to this MCP server takes: nothing (`open`) or its OAuth metadata. */
+export async function probe(server: string): Promise<Probe> {
+ const url = cleanUrl(server)
+ const initialize = JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: {
+ protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'Harness', version: '1' } } })
+ const first = await http(url, { body: initialize, headers: { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' } })
+ let found: { issuer: string; resource: string; scopes: string[] } | null
+ if (first.status >= 200 && first.status < 300) {
+ // A server may answer `initialize` (and list its tools) to anyone and refuse only a tool's call: Wajo's Fo
+ // did (2026-10-11), and was saved with no sign-in, every call then refused. It still says it is protected
+ // in its resource metadata: that, and only that, makes an open answer a sign-in.
+ found = await protectedResource(url)
+ if (!found) return { kind: 'open' }
+ } else {
+ if (first.status !== 401 && first.status !== 403) throw new SignInError(`The server answered ${first.status}. Check the address.`)
+ const challenge = first.headers.get('www-authenticate') ?? ''
+ found = await protectedResource(url, /resource_metadata="([^"]+)"/.exec(challenge)?.[1])
+ }
+ let issuer = found?.issuer
+ const resource = found?.resource ?? url
+ const scopes = found?.scopes ?? []
const base = new URL(url)
issuer ??= `${base.protocol}//${base.host}`
const issuerPath = new URL(issuer).pathname
diff --git a/cli/src/lib/connectors/store.ts b/cli/src/lib/connectors/store.ts
index 0fc3396dc..931cce8fc 100644
--- a/cli/src/lib/connectors/store.ts
+++ b/cli/src/lib/connectors/store.ts
@@ -23,6 +23,12 @@ export class ConnectorError extends Error {}
export type Source = 'dcr' | 'gateway' | 'custom'
export interface McpEntry { url: string, headers: Record<string, string> }
+/**
+ * A service reached by its own REST API with a key, for Harness itself rather than for the agents: the cloud
+ * agents' service calls Devin's and Cursor's APIs through the bridge (`/<key>/<code>/api/…`, bridge.ts), which
+ * adds the key. With no MCP server or REST tools beside it, `transport` is `none`, so no agent is given it.
+ */
+export interface ApiEntry { origin: string }
export interface Token {
access_token?: string
refresh_token?: string
@@ -41,6 +47,7 @@ export interface Token {
rest_entry?: RestEntry
/** The gateway's word on which of the two agents use. */
transport?: Transport
+ api_entry?: ApiEntry
}
export interface Client {
client_id: string
@@ -183,6 +190,12 @@ export function cleanToken(entry: unknown): Token {
const rest = cleanRestEntry(raw.rest_entry)
if (rest) result.rest_entry = rest
if (raw.transport === 'mcp' || raw.transport === 'rest' || raw.transport === 'none') result.transport = raw.transport
+ const api = raw.api_entry
+ if (api) {
+ if (typeof api !== 'object' || Array.isArray(api)) throw new ConnectorError('Invalid connection server.')
+ // Only the origin: a path or query saved here would be where a request was bent somewhere else.
+ result.api_entry = { origin: new URL(cleanUrl((api as Record<string, unknown>).origin)).origin }
+ }
if (!result.access_token && !result.mcp_entry) throw new ConnectorError('No access token was supplied.')
return result
}
diff --git a/cli/src/lib/e2ee/applicationFrames.ts b/cli/src/lib/e2ee/applicationFrames.ts
index 8fe202b56..6752dbec1 100644
--- a/cli/src/lib/e2ee/applicationFrames.ts
+++ b/cli/src/lib/e2ee/applicationFrames.ts
@@ -27,7 +27,9 @@ const MACHINE_REQUESTS = new Set([...SHELL_REQUESTS, 'agent_purge', 'agent_workt
// A held launch's cancellation and its receipt contain the client's private request identity.
'agent_create_cancel',
// Memories (services/memory.ts): what this machine's agents remember, and About You and its on/off choice.
- 'memory_snapshot', 'memory_about_put', 'memory_deliver', ...ROUTE_COMMAND_TYPES])
+ 'memory_snapshot', 'memory_about_put', 'memory_deliver',
+ // Cloud agents (services/cloud.ts): a cloud harness's conversation, the person's words for it, which are connected.
+ 'cloud_transcript', 'cloud_send', 'cloud_agents', ...ROUTE_COMMAND_TYPES])
const MACHINE_RESULTS = new Set([...MACHINE_REQUESTS].map(type => `${type}_result`))
/** The pair brain, machine to machine (daemons/BRAIN.md). A watch carries question text and recaps; the
* writes (answer, send, stop, start, pause, resume) act on a harness through the owning machine's floor
diff --git a/cli/src/serviceProcess.ts b/cli/src/serviceProcess.ts
index 55d04d484..fd02338b9 100644
--- a/cli/src/serviceProcess.ts
+++ b/cli/src/serviceProcess.ts
@@ -50,6 +50,7 @@ export const SERVICE_RUNNERS: ReadonlyMap<string, () => Promise<Runner>> = new M
['orchestrator', async () => (await import('./services/orchestratorProcess.js')).runOrchestratorService],
['memory', async () => (await import('./services/memoryProcess.js')).runMemoryService],
['router', async () => (await import('./services/routerProcess.js')).runRouterService],
+ ['cloud', async () => (await import('./services/cloudProcess.js')).runCloudService],
// Not a service the core knows: the master runs it beside them (harnessd/services.ts `UPDATER_HOST`).
['updater', async () => (await import('./services/updaterProcess.js')).runUpdaterService],
['gateway', async () => (await import('./gateway/gatewayProcess.js')).runGatewayService],
diff --git a/cli/src/services/AGENTS.md b/cli/src/services/AGENTS.md
index 60ea99a01..4a66abd38 100644
--- a/cli/src/services/AGENTS.md
+++ b/cli/src/services/AGENTS.md
@@ -62,6 +62,7 @@ that process. A process per risk, not per feature (`SERVICE_HOSTS` in `src/harne
| `sharing` | sharing | an experiment: Share | on demand |
| `memory` | memory | an experiment: Memories across machines | on demand |
| `router` | router | an experiment: where ⌘B sends a task, decided by Jev | on demand |
+| `cloud` | cloud | an experiment: cloud agents (Fo, Devin Cloud, Cursor Cloud), harnesses on their makers' servers | on demand |
A fault in one of the edge host's services can cost the others in it, never the core. Every service in
`KNOWN_SERVICES` runs out of the core's process by default, unless `HARNESSD_SERVICES` names a subset, by
@@ -223,11 +224,11 @@ like any other. Named in `HARNESSD_SERVICES`, it starts with the others.
## Experiments
-An experiment (the orchestrator, Share, memory, the router) 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.
+An experiment (the orchestrator, Share, memory, the router, cloud agents) 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.
Agent Messages was one until 2026-10-12: a process of its own on every computer it was on, 62 MiB resident at idle for
a few MiB of messaging. It is a service in the edge host now (above), off costing nothing there.
@@ -249,7 +250,11 @@ To add one:
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
+Removing one is deleting those. Cloud agents (`src/services/cloud.ts`, `src/cloud/`) show an experiment that owns
+agents with no pane: it tells the core its harnesses and their questions through `core.cloud` (asked over its link
+out of process, `core/experimentQueries.ts`), and the core lists them, shows their questions and hands a New Harness,
+words, an answer, a rename and Stop Harness for one to its port (`core/agents/cloud.ts`, `core/cloudLink.ts`). A port member is
+never called `stop`: the service host reads that as stopping the service. 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. Agent Messages
(`src/services/messages.ts`) shows the rest: whether one of its typed deliveries may still be written, which
the core asks as it writes it, is reported for a few seconds at a time, so a process that stops reporting
diff --git a/cli/src/services/cloud.spec.ts b/cli/src/services/cloud.spec.ts
new file mode 100644
index 000000000..2fd294211
--- /dev/null
+++ b/cli/src/services/cloud.spec.ts
@@ -0,0 +1,28 @@
+import { mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { emptyPorts } from '../core/api.js'
+import { fakeCore } from '../testing/fakeCore.js'
+import { CLOUD_REQUESTS, startCloud, startCloudOn } from './cloud.js'
+
+let dataDir: string
+beforeEach(() => { dataDir = mkdtempSync(join(tmpdir(), 'cloud-service-')) })
+afterEach(() => rmSync(dataDir, { recursive: true, force: true }))
+
+describe('cloud agents in the core\'s process', () => {
+ it('fills its port, tells the core its harnesses at once, and answers its requests', async () => {
+ const cloud = { publish: vi.fn(), ask: vi.fn(), unask: vi.fn() }
+ const ports = emptyPorts()
+ const requests = startCloud(fakeCore({ dataDir, cloud }), ports, { bridge: { connections: async () => [], mcpUrl: () => '', api: async () => ({ status: 200, json: {} }) } })
+ expect(Object.keys(requests).sort()).toEqual([...CLOUD_REQUESTS].sort())
+ expect(cloud.publish).toHaveBeenCalledWith([])
+ expect(ports.cloud).toMatchObject({ create: expect.any(Function), deliver: expect.any(Function), answer: expect.any(Function), rename: expect.any(Function), stopHarness: expect.any(Function), stop: expect.any(Function) })
+ expect(await ports.cloud!.create({ engine: 'claude' })).toMatchObject({ ok: false, error: 'INVALID_ENGINE' })
+ ;(ports.cloud as unknown as { stop: () => void }).stop()
+ })
+
+ it('does not start on a core that offers it no doors', () => {
+ expect(() => startCloudOn(fakeCore({ dataDir }), emptyPorts())).toThrow('no doors')
+ })
+})
diff --git a/cli/src/services/cloud.ts b/cli/src/services/cloud.ts
new file mode 100644
index 000000000..781d19ba8
--- /dev/null
+++ b/cli/src/services/cloud.ts
@@ -0,0 +1,28 @@
+/**
+ * Cloud agents (`cloud`), an experiment: harnesses that run on their maker's servers (Fo, Devin Cloud, Cursor
+ * Cloud) and have no pane (cloud/service.ts, docs/design/2026-10-11-cloud-agents.md). The core lists them,
+ * puts their questions in front of the person, and hands a New Harness for one, a message, an answer and a
+ * Stop to this service through its port (core/agents/cloud.ts).
+ * - In the core's process (`HARNESSD_SERVICES=none`) it starts here, on `core.cloud`; in its own process,
+ * services/cloudProcess.ts starts the same service on `core.cloud` asked over its link.
+ */
+import type { CoreApi, CorePorts, ServiceRequests } from '../core/api.js'
+import { startCloudService, type CloudService, type CloudServiceOptions } from '../cloud/service.js'
+
+/** The requests cloud agents answer, declared in core/api.ts for the core to route. */
+export { CLOUD_REQUESTS } from '../core/api.js'
+
+/** The service on a core's doors, its port in `ports.cloud`: what its process keeps to tell a reconnected core again. */
+export function startCloudOn(core: CoreApi, ports: CorePorts, options: Partial<CloudServiceOptions> = {}): CloudService {
+ if (!core.cloud) throw new Error('this core offers cloud agents no doors')
+ const service = startCloudService({ dataDir: core.dataDir, core: core.cloud, ...options })
+ ports.cloud = Object.assign(service.port, { stop: () => service.stop() })
+ return service
+}
+
+/** Cloud agents in the core's process (`HARNESSD_SERVICES=none`): its harnesses told at once. */
+export function startCloud(core: CoreApi, ports: CorePorts, options: Partial<CloudServiceOptions> = {}): ServiceRequests {
+ const service = startCloudOn(core, ports, options)
+ service.republish()
+ return service.requests
+}
diff --git a/cli/src/services/cloudProcess.spec.ts b/cli/src/services/cloudProcess.spec.ts
new file mode 100644
index 000000000..bcc802bc5
--- /dev/null
+++ b/cli/src/services/cloudProcess.spec.ts
@@ -0,0 +1,55 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { runServiceProcess, type CoreConnection, type ServiceProcessOptions } from './process.js'
+import { runCloudService } from './cloudProcess.js'
+import type { startCloudOn } from './cloud.js'
+
+// The real default reaches a real socket: never in a test.
+vi.mock('./process.js', () => ({ runServiceProcess: vi.fn(() => ({ stop: vi.fn() })) }))
+
+describe('cloud agents in their own process', () => {
+ afterEach(() => vi.clearAllMocks())
+
+ it('answers the apps and the core\'s port, and tells a core that connects everything again', async () => {
+ let options: ServiceProcessOptions | null = null
+ const port = { create: vi.fn(async () => ({ ok: true, agent: {} })), deliver: vi.fn(async () => ({ ok: true })), answer: vi.fn(async () => ({ ok: true })), rename: vi.fn(async () => ({ ok: true })), stopHarness: vi.fn(async () => ({ ok: true })) }
+ const republish = vi.fn()
+ let core: Parameters<typeof startCloudOn>[0] | null = null
+ const start = vi.fn((given, ports) => { core = given; ports.cloud = port; return { requests: { cloud_agents: async () => ({ agents: [] }) }, republish } }) as unknown as typeof startCloudOn
+ runCloudService({ dataDir: '/data', socketPath: '/s', machineId: 'm', token: 't', run: (given) => { options = given; return { stop: vi.fn() } }, start })
+ const requests = options!.requests
+ const asker = { local: true, owner: true }
+ expect(await requests.cloud_agents!({}, asker)).toEqual({ agents: [] })
+ await requests.create!({ engine: 'fo' }, asker)
+ await requests.deliver!({ agentId: 'cloud_1', text: 'hi' }, asker)
+ await requests.deliver!({}, asker)
+ await requests.answer!({ agentId: 'cloud_1', questionId: 'cloud_q_1', requestId: 'the-link-s-own', answers: { answer: 'main', bad: 3 } }, asker)
+ await requests.answer!({ answers: null }, asker)
+ await requests.rename!({ agentId: 'cloud_1', name: 'Trip' }, asker)
+ await requests.stopHarness!({ agentId: 'cloud_1' }, asker)
+ expect(port.rename).toHaveBeenCalledWith('cloud_1', 'Trip')
+ expect(port.create).toHaveBeenCalledWith({ engine: 'fo' })
+ expect(port.deliver.mock.calls).toEqual([['cloud_1', 'hi'], ['', '']])
+ expect(port.answer.mock.calls).toEqual([['cloud_1', 'cloud_q_1', { answer: 'main' }], ['', '', {}]])
+ expect(port.stopHarness).toHaveBeenCalledWith('cloud_1')
+
+ // Before a core connects, what it tells the core goes nowhere; once one does, it is asked of that core.
+ core!.cloud!.publish([])
+ const query = vi.fn(async () => ({}))
+ options!.onConnected!({ query } as unknown as CoreConnection)
+ expect(republish).toHaveBeenCalled()
+ core!.cloud!.publish([])
+ core!.cloud!.ask('cloud_1', 'cloud_q_1', { text: 'Which?', choices: [] })
+ core!.cloud!.unask('cloud_1', 'cloud_q_1')
+ expect(query.mock.calls).toEqual([
+ ['cloud_publish', { harnesses: [] }], ['cloud_ask', { agentId: 'cloud_1', questionId: 'cloud_q_1', question: { text: 'Which?', choices: [] } }],
+ ['cloud_unask', { agentId: 'cloud_1', questionId: 'cloud_q_1' }],
+ ])
+ })
+
+ it('runs as a real service by default', () => {
+ runCloudService({ dataDir: '/data-cloud-spec-unused', socketPath: '/s', machineId: 'm', token: 't' })
+ expect(runServiceProcess).toHaveBeenCalledWith(expect.objectContaining({
+ name: 'cloud', requests: expect.objectContaining({ cloud_transcript: expect.any(Function), cloud_send: expect.any(Function), cloud_agents: expect.any(Function), create: expect.any(Function) }),
+ }))
+ })
+})
diff --git a/cli/src/services/cloudProcess.ts b/cli/src/services/cloudProcess.ts
new file mode 100644
index 000000000..b66dfe745
--- /dev/null
+++ b/cli/src/services/cloudProcess.ts
@@ -0,0 +1,55 @@
+/**
+ * Cloud agents in their own process (`harness __service cloud`), an experiment: the same service as in the
+ * core's process (services/cloud.ts), answering two askers:
+ * - the apps' requests, `cloud_transcript` and `cloud_agents`;
+ * - the core, through its port (core/cloudLink.ts): `create`, `deliver`, `answer`, `rename` and `stopHarness`, named as the
+ * port's members so that a test's fault names the same member whichever process it runs in.
+ *
+ * What it tells the core (its harnesses, their questions) is asked of the core over its link
+ * (services/processCoreApi.ts `cloud`), and told again whole each time it connects: a core that restarted
+ * knows none of it.
+ */
+import { emptyPorts } from '../core/api.js'
+import { startCloudOn } from './cloud.js'
+import { runServiceProcess, type CoreConnection, type ServiceProcess } from './process.js'
+import { processCoreApi } from './processCoreApi.js'
+
+export interface CloudProcessOptions {
+ 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 with fake makers. */
+ start?: typeof startCloudOn
+}
+
+type Payload = Record<string, unknown>
+const text = (value: unknown): string => (typeof value === 'string' ? value : '')
+const answers = (value: unknown): Record<string, string> => Object.fromEntries(Object.entries(value && typeof value === 'object' ? value : {})
+ .filter((entry): entry is [string, string] => typeof entry[1] === 'string'))
+
+export function runCloudService(options: CloudProcessOptions): ServiceProcess {
+ let core: CoreConnection | null = null
+ const ask = (query: string, payload: Payload): Promise<Payload> => (core ? core.query(query, payload) : Promise.reject(new Error('the core is not connected')))
+ const ports = emptyPorts()
+ const service = (options.start ?? startCloudOn)(processCoreApi(options.dataDir, 'cloud', { ask }), ports)
+ const port = ports.cloud!
+ return (options.run ?? runServiceProcess)({
+ name: 'cloud',
+ socketPath: options.socketPath,
+ machineId: options.machineId,
+ token: options.token,
+ requests: {
+ ...service.requests,
+ // The port's members, asked only by the core (core/cloudLink.ts).
+ create: (payload) => port.create(payload),
+ deliver: (payload) => port.deliver(text(payload.agentId), text(payload.text)),
+ answer: (payload) => port.answer(text(payload.agentId), text(payload.questionId), answers(payload.answers)),
+ rename: (payload) => port.rename(text(payload.agentId), text(payload.name)),
+ stopHarness: (payload) => port.stopHarness(text(payload.agentId)),
+ },
+ onConnected: (connection) => { core = connection; service.republish() },
+ })
+}
diff --git a/cli/src/services/connectors.spec.ts b/cli/src/services/connectors.spec.ts
index 154044dae..ad77b67ee 100644
--- a/cli/src/services/connectors.spec.ts
+++ b/cli/src/services/connectors.spec.ts
@@ -86,6 +86,10 @@ describe('the connectors service', () => {
expect(await requests.connectors!({ action: 'nope' }, OWNER)).toEqual({ error: 'CONNECTORS_FAILED', detail: 'Unknown action.' })
expect(await requests.connectors!({ action: 'custom', name: 'Mine', url: 'https://mine.example/mcp', headers: { Authorization: 'Bearer pat' } }, OWNER))
.toEqual({ connector: 'mine', state: 'connected' })
+ // An API key for a cloud agent, never an agent's MCP server.
+ expect(await requests.connectors!({ action: 'custom', kind: 'api', name: 'Devin', url: 'https://api.devin.ai', key: 'cog_x' }, OWNER))
+ .toEqual({ connector: 'devin', state: 'connected' })
+ expect(vault.token('devin')).toMatchObject({ api_entry: { origin: 'https://api.devin.ai' }, transport: 'none' })
expect(await requests.connectors!({ action: 'disconnect', connector: 'linear' }, OWNER)).toEqual({ connector: 'linear', state: 'not_connected' })
expect(vault.token('linear')).toBeUndefined()
})
diff --git a/cli/src/services/connectors.ts b/cli/src/services/connectors.ts
index 343410b74..26c40f4d2 100644
--- a/cli/src/services/connectors.ts
+++ b/cli/src/services/connectors.ts
@@ -18,7 +18,7 @@ import type { CoreApi, ServiceRequests } from '../core/api.js'
import { bridgePort, sync } from '../lib/connectors/agents.js'
import { createBridge } from '../lib/connectors/bridge.js'
import { services, type GatewayRow } from '../lib/connectors/catalog.js'
-import { addCustom, cards, disconnect, Flows, signInFor } from '../lib/connectors/connect.js'
+import { addApiKey, addCustom, cards, disconnect, Flows, signInFor } from '../lib/connectors/connect.js'
import * as gateway from '../lib/connectors/gateway.js'
import { ConnectorError, Store, validateCode } from '../lib/connectors/store.js'
import { answerVaultOp, VaultSync, vaultPortOf, type VaultPort } from '../lib/connectors/vaultSync.js'
@@ -57,7 +57,7 @@ export function startConnectors(core: CoreApi, overrides: Partial<ConnectorsDeps
}
const { vault } = deps
const flows = new Flows(vault, env)
- const bridge = createBridge(vault, { key: () => String(vault.file('bridge.json').key ?? '') })
+ const bridge = createBridge(vault, { key: () => String(vault.file('bridge.json').key ?? ''), harnessKey: () => String(vault.file('harness-key.json').key ?? '') })
bridge.unref()
listen(bridge, deps.port, deps.retryMs)
try { sync(vault, env) } catch { /* A config that cannot be written now is written at the next connect. */ }
@@ -100,7 +100,7 @@ export function startConnectors(core: CoreApi, overrides: Partial<ConnectorsDeps
await disconnect(vault, code, env)
return { connector: code, state: 'not_connected' }
}
- case 'custom': return addCustom(vault, flows, payload, env)
+ case 'custom': return payload.kind === 'api' ? addApiKey(vault, payload, env) : addCustom(vault, flows, payload, env)
case 'callback': return { ...flows.deliver(String(payload.flow ?? ''), String(payload.url ?? '')) }
default: return { error: 'CONNECTORS_FAILED', detail: 'Unknown action.' }
}
diff --git a/cli/src/services/devices.spec.ts b/cli/src/services/devices.spec.ts
index 61f8fb72e..6d526e507 100644
--- a/cli/src/services/devices.spec.ts
+++ b/cli/src/services/devices.spec.ts
@@ -802,6 +802,16 @@ describe('⌘K, the Wi-Fi device\'s borrowed walk, the voice router and stopping
expect(vi.mocked(core.clients.sendLocal).mock.calls.map(([frame]) => frame.type)).toEqual(['dial_focus', 'dial_scroll'])
})
+ it('walk the cloud harnesses on the desk too, where the core offers them', async () => {
+ const { core, port } = start()
+ port.desk(['a1', 'cloud_1'], true)
+ port.swarms({ active: 't1', swarms: [{ id: 't1', name: 'Tab', agentIds: ['a1', 'cloud_1'], panes: 2 }], tiles: [] })
+ vi.mocked(core.agents.advertised).mockReturnValue([{ agentId: 'a1', registeredAt: 1, engine: 'claude' }] as RegisteredSession[])
+ core.agents.cloud = () => [{ agentId: 'cloud_1', registeredAt: 2, engine: 'fo' }] as unknown as RegisteredSession[]
+ seen.fleet!.fail = true
+ expect(await port.stepFocus('next', 'a1')).toEqual(expect.objectContaining({ agentId: 'cloud_1' }))
+ })
+
it('tell the voice router the engines here and whether a device watches, and stop everything', async () => {
const { port } = start()
port.engines(['claude', 'codex'])
diff --git a/cli/src/services/devices.ts b/cli/src/services/devices.ts
index ad60d7c24..39bf4f689 100644
--- a/cli/src/services/devices.ts
+++ b/cli/src/services/devices.ts
@@ -145,7 +145,8 @@ export function startDevices(core: CoreApi, ports: CorePorts, deps: DevicesDeps)
// The assistant's latest paragraph per agent, as the processing cards carry it; gone when the turn ends.
const latestUpdate = new Map<string, string>()
const cableHost = new DaemonCableHost({
- sessions: () => core.agents.advertised(),
+ // The cloud harnesses too, where the core offers them: tiles on the desk the dial walks like any other.
+ sessions: () => [...core.agents.advertised(), ...core.agents.cloud?.() ?? []],
refresh: deps.refresh,
displayName: (session) => core.agents.displayName(session),
appFocus: () => focus.voice ?? undefined,
diff --git a/cli/src/services/fleet.spec.ts b/cli/src/services/fleet.spec.ts
index d4452a4aa..f0031336a 100644
--- a/cli/src/services/fleet.spec.ts
+++ b/cli/src/services/fleet.spec.ts
@@ -272,6 +272,19 @@ describe('⌘K: which agent a typed task belongs to', () => {
expect(route.mock.calls[1]![4]).toMatchObject({ agentId: 'a2' })
})
+ it('weighs the cloud harnesses too, where the core offers them', async () => {
+ const core = fakeCore({
+ agents: {
+ advertised: vi.fn(() => [session('a1')]),
+ cloud: vi.fn(() => [{ ...session('cloud_1', 2, 'fo'), defaultName: 'haircut' } as RegisteredSession]),
+ displayName: vi.fn((s: RegisteredSession) => s.agentId),
+ },
+ })
+ const { fleet } = setup({}, core)
+ route.mockResolvedValue(decision({ agentId: 'cloud_1', confidence: 0.9, reason: 'errands', via: 'claude' }))
+ expect((await fleet.routeTask('book a haircut')).candidates.map((candidate) => [candidate.agentId, candidate.engine])).toEqual([['cloud_1', 'fo'], ['a1', 'claude']])
+ })
+
it('weighs the first fifteen in rail order and says so; ranks the router’s runners-up first', async () => {
const sessions = Array.from({ length: 17 }, (_, i) => session(`a${String(i).padStart(2, '0')}`, i))
const { fleet } = setup({}, fakeCore({ agents: { advertised: vi.fn(() => sessions), displayName: vi.fn((s: RegisteredSession) => s.agentId) } }))
diff --git a/cli/src/services/fleet.ts b/cli/src/services/fleet.ts
index 78139949c..7e44ad0bb 100644
--- a/cli/src/services/fleet.ts
+++ b/cli/src/services/fleet.ts
@@ -167,7 +167,7 @@ export function startFleet(core: CoreApi, deps: FleetDeps): { fleet: Fleet; rout
machineName: () => core.machine.name(),
machineId: () => core.machine.id(),
computerId: () => core.machine.computerId(),
- sessions: () => core.agents.advertised(),
+ sessions: () => [...core.agents.advertised(), ...core.agents.cloud?.() ?? []],
refresh: deps.refresh,
displayName: (session) => core.agents.displayName(session),
runtimeProfile: (session) => core.agents.runtimeProfile(session),
diff --git a/cli/src/services/inline.spec.ts b/cli/src/services/inline.spec.ts
index b01aa894a..2b3346a9f 100644
--- a/cli/src/services/inline.spec.ts
+++ b/cli/src/services/inline.spec.ts
@@ -21,6 +21,7 @@ import { startOrchestrator } from './orchestrator.js'
import { startProjects } from './projects.js'
import { startRecaps } from './recaps.js'
import { startRouter } from './router.js'
+import { startCloud } from './cloud.js'
import { startSearch } from './search.js'
import { startShell } from './shell.js'
import { startSharing } from './sharing.js'
@@ -33,6 +34,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({ engineTranscriptFor, liveFor, runtimeFor, screenFor, submissionFor, nativeControlFor, modelControlFor, questionControlFor, startAgentCleanup, startConnectors, startDevices, startHandoff, startGateway, startMemory, startModels, startMonitor, startOrchestrator, startProjects, startRecaps, startRouter, startSearch, startSharing, startShell, startStoreInCore, startMessagesInCore, startUsageInCore, startViewers, startWifi, startWindowNames, startWorkspaces })
+ expect({ ...inline }).toEqual({ engineTranscriptFor, liveFor, runtimeFor, screenFor, submissionFor, nativeControlFor, modelControlFor, questionControlFor, startAgentCleanup, startCloud, startConnectors, startDevices, startHandoff, startGateway, startMemory, startModels, startMonitor, startOrchestrator, startProjects, startRecaps, startRouter, startSearch, startSharing, startShell, startStoreInCore, startMessagesInCore, startUsageInCore, startViewers, startWifi, startWindowNames, startWorkspaces })
})
})
diff --git a/cli/src/services/inline.ts b/cli/src/services/inline.ts
index b0a987636..6877e6bda 100644
--- a/cli/src/services/inline.ts
+++ b/cli/src/services/inline.ts
@@ -23,6 +23,7 @@ export { runtimeFor } from '../engines/runtime.js'
export { startGateway } from '../gateway/start.js'
export { startAgentCleanup } from './agentCleanup.js'
export { startMemory } from './memory.js'
+export { startCloud } from './cloud.js'
export { startConnectors } from './connectors.js'
export { startDevices } from './devices.js'
export { startHandoff } from './handoff.js'
diff --git a/cli/src/services/processCoreApi.spec.ts b/cli/src/services/processCoreApi.spec.ts
index b101bb53b..256cf5d0c 100644
--- a/cli/src/services/processCoreApi.spec.ts
+++ b/cli/src/services/processCoreApi.spec.ts
@@ -111,6 +111,17 @@ describe('the core API a light service runs on in its own process', () => {
expect(listeners).toHaveLength(1)
})
+ it('gives the cloud agents their doors only with a core to ask, and never waits on or throws from them', async () => {
+ expect(processCoreApi('/data', 'cloud').cloud).toBeUndefined()
+ const ask = vi.fn(async (_query: string): Promise<Record<string, unknown>> => { throw new Error('gone') })
+ const doors = processCoreApi('/data', 'cloud', { ask }).cloud!
+ doors.publish([])
+ doors.ask('cloud_1', 'cloud_q_1', { text: 'Which?', choices: [] })
+ doors.unask('cloud_1', 'cloud_q_1')
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ expect(ask.mock.calls.map(([query]) => query)).toEqual(['cloud_publish', 'cloud_ask', 'cloud_unask'])
+ })
+
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 },
diff --git a/cli/src/services/processCoreApi.ts b/cli/src/services/processCoreApi.ts
index 9b2d43c78..92fee1656 100644
--- a/cli/src/services/processCoreApi.ts
+++ b/cli/src/services/processCoreApi.ts
@@ -14,7 +14,7 @@ import { usageTarget, usageTargetKey, usageSnapshot, validUsage, validUsageTarge
* 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 { CONNECTOR_VAULT_OFF, CONVERSATIONS_OFF, DAEMON_UNKNOWN, DELIVERIES_OFF, LANE_OFF, OBSERVER_KEY_OFF, resolveAgent, TERMINALS_OFF, WIFI_OFF, type CoreApi, type DaemonAddress, type TerminalWatch } from '../core/api.js'
+import { CONNECTOR_VAULT_OFF, CONVERSATIONS_OFF, DAEMON_UNKNOWN, DELIVERIES_OFF, LANE_OFF, OBSERVER_KEY_OFF, resolveAgent, TERMINALS_OFF, WIFI_OFF, type CloudCore, type CoreApi, type DaemonAddress, type TerminalWatch } from '../core/api.js'
import type { AgentDshContext } from '../lib/agentFrame.js'
import type { RegisteredSession } from '../lib/registry.js'
import type { turnsLink } from './turnsLink.js'
@@ -174,5 +174,15 @@ export function processCoreApi(dataDir: string, service: string, view: AgentsVie
get autonomousEnv() { return daemon().autonomousEnv },
},
wifi: UNASKED.wifi,
+ // The cloud agents' doors (core/experimentQueries.ts): told to the core in order, never waited on. A core
+ // that is not connected hears it all again when it is (services/cloudProcess.ts `republish`). A question's
+ // id travels as `questionId`: `requestId` is the query's own, which the link writes over.
+ ...(ask ? {
+ cloud: {
+ publish: (harnesses) => { void ask('cloud_publish', { harnesses }).catch(() => {}) },
+ ask: (agentId, requestId, question) => { void ask('cloud_ask', { agentId, questionId: requestId, question }).catch(() => {}) },
+ unask: (agentId, requestId) => { void ask('cloud_unask', { agentId, questionId: requestId }).catch(() => {}) },
+ } satisfies CloudCore,
+ } : {}),
}
}
diff --git a/cli/src/testing/connectorServers.ts b/cli/src/testing/connectorServers.ts
index 808a6e8a3..059188d2d 100644
--- a/cli/src/testing/connectorServers.ts
+++ b/cli/src/testing/connectorServers.ts
@@ -26,6 +26,8 @@ export class FakeService {
access = ''
refresh = ''
revoked = false
+ /** Answers `initialize` to anyone and refuses only what follows, as Wajo's Fo does: still protected. */
+ openHandshake = false
registered: Record<string, unknown>[] = []
seen: { auth?: string, session?: string, body: string }[] = []
private challenge = new Map<string, string>()
@@ -70,6 +72,10 @@ export class FakeService {
}
if (url.pathname === '/mcp') {
this.seen.push({ auth: request.headers.authorization, session: request.headers['mcp-session-id'] as string | undefined, body: text })
+ const handshake = /"method"\s*:\s*"initialize"/.test(text)
+ if (this.openHandshake && handshake && !request.headers.authorization) {
+ send(response, 200, { jsonrpc: '2.0', id: 1, result: { protocolVersion: '2025-06-18' } }); return
+ }
if (request.headers.authorization !== `Bearer ${this.access}`) {
send(response, 401, { error: 'invalid_token' }, { 'WWW-Authenticate': `Bearer resource_metadata="${this.base}/.well-known/oauth-protected-resource/mcp"` }); return
}
diff --git a/cli/src/testing/fakeCore.ts b/cli/src/testing/fakeCore.ts
index 438411fd8..8858924e8 100644
--- a/cli/src/testing/fakeCore.ts
+++ b/cli/src/testing/fakeCore.ts
@@ -85,5 +85,7 @@ export function fakeCore(over: Overrides = {}): CoreApi {
transcripts: vi.fn(), watching: vi.fn(), streams: vi.fn(),
...over.wifi,
},
+ // Only a spec that gives the cloud agents doors has them, as only a core that offers them does.
+ ...(over.cloud ? { cloud: Object.assign({ publish: vi.fn(), ask: vi.fn(), unask: vi.fn() }, over.cloud) } : {}),
}
}
diff --git a/desktop/lib/core/models.dart b/desktop/lib/core/models.dart
index fce91c1c8..cf1f1b079 100644
--- a/desktop/lib/core/models.dart
+++ b/desktop/lib/core/models.dart
@@ -289,6 +289,75 @@ class AgentOutputStats {
Object.hash(linesAdded, linesRemoved, pullRequestsCreated, updatedAt);
}
+/// What a cloud agent's frame says beyond an agent's usual one (CLI
+/// lib/cloudAgents.ts `CloudFrameBlock`): where it runs, where it is, what it
+/// is doing, its links at its maker (the session, a pull request) and how many
+/// messages its conversation holds, which the chat pane reads again when it moves.
+class AgentCloud {
+ final String place;
+
+ /// `starting`, `working`, `needs_input`, `idle`, `failed` or `stopped`.
+ final String state;
+ final String? activity;
+ final List<({String label, String url})> links;
+ final int messages;
+
+ const AgentCloud({
+ required this.place,
+ required this.state,
+ this.activity,
+ this.links = const [],
+ this.messages = 0,
+ });
+
+ bool get working => state == 'working' || state == 'starting';
+
+ /// The pull request among its links, for the footer; null with none.
+ ({String label, String url})? get pullRequest {
+ for (final link in links) {
+ if (RegExp(r'^https://github\.com/[^/]+/[^/]+/pull/\d+$')
+ .hasMatch(link.url))
+ return link;
+ }
+ return null;
+ }
+
+ static AgentCloud fromJson(Object? raw) {
+ final j = raw is Map ? raw : const {};
+ String? text(Object? value, int max) =>
+ value is String && value.trim().isNotEmpty
+ ? (value.length > max ? value.substring(0, max) : value)
+ : null;
+ final links = <({String label, String url})>[];
+ if (j['links'] is List) {
+ for (final link in j['links'] as List) {
+ if (link is! Map) continue;
+ final label = text(link['label'], 80), url = text(link['url'], 2048);
+ if (label != null && url != null && url.startsWith('https://')) {
+ links.add((label: label, url: url));
+ }
+ }
+ }
+ const states = {
+ 'starting',
+ 'working',
+ 'needs_input',
+ 'idle',
+ 'failed',
+ 'stopped',
+ };
+ final state = j['state'];
+ final messages = j['messages'];
+ return AgentCloud(
+ place: text(j['place'], 80) ?? 'The cloud',
+ state: state is String && states.contains(state) ? state : 'idle',
+ activity: text(j['activity'], 200),
+ links: links,
+ messages: messages is int && messages >= 0 ? messages : 0,
+ );
+ }
+}
+
class Agent {
final AgentActivity? activity;
final String id;
@@ -421,6 +490,13 @@ class Agent {
/// or null for a general session.
final String? namedAgent;
+ /// A cloud agent's harness (`location: 'cloud'`): it runs on its maker's
+ /// servers and has no terminal, so its pane is a chat pane. Null for every
+ /// agent that runs on a computer (docs/design/2026-10-11-cloud-agents.md).
+ final AgentCloud? cloud;
+
+ bool get isCloud => cloud != null;
+
const Agent({
this.activity,
required this.id,
@@ -468,6 +544,7 @@ class Agent {
this.permissionMode,
this.bypassPermission,
this.namedAgent,
+ this.cloud,
});
bool get isStopped => status == 'stopped';
@@ -654,6 +731,7 @@ class Agent {
? j['bypassPermission'] as bool
: null,
namedAgent: _safeNamedAgent(j['namedAgent']),
+ cloud: j['location'] == 'cloud' ? AgentCloud.fromJson(j['cloud']) : null,
);
}
@@ -711,6 +789,7 @@ class Agent {
permissionMode: permissionMode,
bypassPermission: bypassPermission,
namedAgent: namedAgent,
+ cloud: cloud,
);
/// A mode id as `PERMISSION_MODES` spells them (`acceptEdits`, `readOnly`):
diff --git a/desktop/lib/e2ee/envelope.dart b/desktop/lib/e2ee/envelope.dart
index d0d408aca..b33c04cc9 100644
--- a/desktop/lib/e2ee/envelope.dart
+++ b/desktop/lib/e2ee/envelope.dart
@@ -73,6 +73,10 @@ const Set<String> encryptedDownTypes = {
'memory_snapshot',
'memory_about_put',
'memory_deliver',
+ // Cloud agents (CLI services/cloud.ts): a cloud harness's conversation and the person's words for it.
+ 'cloud_transcript',
+ 'cloud_send',
+ 'cloud_agents',
// The trust-group roster swap (`viewer/group_sync.dart`): the keys every member trusts.
'group_sync',
'codex_profiles_list',
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 680f78bcf..d54e8e3db 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -84,7 +84,7 @@ import '../shared/theme/app_theme.dart' as grid;
import '../terminal/remote_media_download.dart';
import 'take_over.dart';
import '../widgets/engine_identity.dart'
- show allEngines, engineIdentity, isTerminalEngine;
+ show allEngines, engineIdentity, isCloudAgentId, isTerminalEngine;
import '../store/store_screen.dart' show openStoreAgent;
import 'dial_status.dart';
import 'grid_pictures.dart';
@@ -11281,6 +11281,52 @@ class AppNotifier extends ChangeNotifier {
}
}
+ /// A cloud harness's conversation from message [after] on (`cloud_transcript`,
+ /// CLI services/cloud.ts): `{messages: [{id, from, text, at}], total}`, or
+ /// null when its machine cannot answer.
+ Future<Map<String, dynamic>?> readCloudTranscript(
+ String machineId,
+ String agentId, {
+ int after = 0,
+ }) async {
+ try {
+ final reply = await _conn(machineId).request(
+ 'cloud_transcript',
+ payload: {'agentId': agentId, if (after > 0) 'after': after},
+ timeout: const Duration(seconds: 8),
+ );
+ return reply['error'] != null ? null : reply;
+ } catch (_) {
+ return null;
+ }
+ }
+
+ /// The person's words for a cloud harness (`cloud_send`): null once its
+ /// maker took them, else why not, in words a person reads ("Cursor Cloud is
+ /// still working").
+ Future<String?> sendCloudMessage(
+ String machineId,
+ String agentId,
+ String text,
+ ) async {
+ try {
+ final reply = await _conn(machineId).request(
+ 'cloud_send',
+ payload: {'agentId': agentId, 'text': text},
+ // Longer than the machine waits on its cloud service (3 min, CLI
+ // core/api.ts LONG_ANSWERS): a maker answering slowly is not a failure.
+ timeout: const Duration(seconds: 200),
+ );
+ if (reply['error'] == null) return null;
+ final detail = reply['detail'];
+ return detail is String && detail.isNotEmpty
+ ? detail
+ : 'It could not be sent. Try again.';
+ } catch (_) {
+ return 'It could not be sent. Try again.';
+ }
+ }
+
/// The rows of [sessionId] on [machineId] before [beforeTurn], or its last
/// rows (`session_tail`, the same index as [searchSessions]). Null when the
/// machine cannot answer: offline, a CLI that predates the request, or a
@@ -11732,6 +11778,31 @@ class AppNotifier extends ChangeNotifier {
return answer;
}
+ /// A cloud harness (CLI services/cloud.ts): made by the machine's cloud
+ /// service at its maker, opened in a pane as any new harness is. Null when it
+ /// started; otherwise what to tell the person ("Add your Devin API key…").
+ Future<String?> createCloudHarness(
+ String machineId, {
+ required String engine,
+ required String prompt,
+ String? repositoryUrl,
+ int? acuLimit,
+ String? swarmId,
+ PaneSplitRequest? split,
+ HarnessPlacement? placement,
+ }) => _create(
+ machineId,
+ {
+ 'engine': engine,
+ 'prompt': prompt,
+ 'repositoryUrl': ?repositoryUrl,
+ 'acuLimit': ?acuLimit,
+ },
+ swarmId: swarmId,
+ split: split,
+ placement: placement,
+ );
+
/// How long, from its start, a create waits for its agent's download beside setup
/// ([agentPrefetch]). OpenCode took 7–12 s in the VM runs, Codex and Claude Code (one npm, after
/// setup's Node) 25 s more; on a slow network the wait is the download's, since a pane that stopped
@@ -12182,6 +12253,26 @@ class AppNotifier extends ChangeNotifier {
'SESSION_STOP_FAILED',
'INVALID_SESSION',
};
+ // A cloud agent's service refuses in words a person reads ("Add your
+ // Devin API key…"), and a retry of the same New Harness gets the same
+ // harness (its `creationId`), so none of these is left unconfirmed.
+ const cloudRefusals = {
+ 'NOT_CONNECTED',
+ 'INVALID_REQUEST',
+ 'CONNECTIONS_UNAVAILABLE',
+ 'CLOUD_FAILED',
+ 'BUSY',
+ 'RATE_LIMITED',
+ 'UNREACHABLE',
+ 'SERVICE_UNAVAILABLE',
+ };
+ final cloudRefusal =
+ isCloudAgentId(choices['engine'] as String?) &&
+ cloudRefusals.contains(failure.code);
+ if (cloudRefusal) {
+ creation._refusal = failure.code;
+ return creation._complete(failure.detail ?? 'Could not start it.');
+ }
if (refusedBeforeLaunch.contains(failure.code)) {
creation._refusal = failure.code;
if (failure.code == 'INVALID_CWD' && choices['projectSource'] != null) {
diff --git a/desktop/lib/state/new_harness.dart b/desktop/lib/state/new_harness.dart
index c172215cc..dbc38b2e0 100644
--- a/desktop/lib/state/new_harness.dart
+++ b/desktop/lib/state/new_harness.dart
@@ -623,7 +623,11 @@ class NewHarnessController extends ChangeNotifier {
_harnessId!,
);
List<String> get compatibleEngines => _harnessId == null
- ? [for (final engine in allEngines) engine.id, kTerminalEngine]
+ ? [
+ for (final engine in allEngines) engine.id,
+ for (final agent in cloudAgents) agent.id,
+ kTerminalEngine,
+ ]
: selectedHarness?.supportedEngines ??
[knownHarnessBase[canonicalHarnessId(_harnessId!)] ?? 'claude'];
@@ -734,7 +738,7 @@ class NewHarnessController extends ChangeNotifier {
bool refreshingBranches = false;
String? branchRefreshError;
DateTime? _branchesCheckedAt;
- bool get isGitProject => _gitProject.isGit && !isTerminal;
+ bool get isGitProject => _gitProject.isGit && !isTerminal && !isCloud;
bool get canUseWorktree => isGitProject && !checkingGit;
bool get worktree =>
isGitProject &&
@@ -1285,10 +1289,10 @@ class NewHarnessController extends ChangeNotifier {
_settingsModes.any((mode) => mode.id == _permissionFor(_settingsEngine))
? _permissionFor(_settingsEngine)
: kDefaultPermissionMode;
- bool get takesTask => takesFirstTask(_base);
+ bool get takesTask => isCloud || takesFirstTask(_base);
bool get taskTooLong => task.trim().length > kFirstTaskMaxLength;
List<PermissionMode> get _modes =>
- isTerminal ? const [] : permissionModesOf(_base);
+ isTerminal || isCloud ? const [] : permissionModesOf(_base);
bool get hasModes => _modes.isNotEmpty;
String get mode =>
_modes.any((mode) => mode.id == _mode) ? _mode : kDefaultPermissionMode;
@@ -1399,8 +1403,44 @@ class NewHarnessController extends ChangeNotifier {
MachineState? get _machine => app.stateOf(_machineId);
bool get isTerminal => isTerminalEngine(_engine);
+
+ /// A cloud agent (Fo, Devin Cloud, Cursor Cloud): it runs on its maker's
+ /// servers, so it takes no folder, model, approvals or branch here — a coding
+ /// one takes a GitHub repository, and Devin Cloud an ACU limit.
+ bool get isCloud => _harnessId == null && isCloudAgentId(_engine);
+
+ /// The GitHub repository a cloud coding agent works on: the one chosen to
+ /// clone, else the chosen folder's own remote; null when neither is on GitHub.
+ String? get cloudRepository {
+ final cloned = _project.repository?.url;
+ if (cloned != null) return cloned;
+ final folder = _project.folder;
+ final machine = _machine;
+ if (folder == null || machine == null) return null;
+ for (final agent in machine.agents) {
+ final project = machine.projectOf(agent);
+ final remote = project?.remote;
+ if (remote != null &&
+ remote.contains('github.com') &&
+ (project!.cwd == folder || project.root == folder)) {
+ return remote;
+ }
+ }
+ return null;
+ }
+
+ /// Devin Cloud's ACU limit for the session: low by default, since it bills
+ /// while it works.
+ int acuLimit = 5;
+ static const acuLimits = [2, 5, 10, 20];
+ void setAcuLimit(int value) {
+ acuLimit = value;
+ notifyListeners();
+ }
+
bool get needsProject =>
!isTerminal &&
+ !isCloud &&
_project.folder == null &&
_project.repository == null &&
projectFolderSlug(_project.name ?? '') == null;
@@ -1419,6 +1459,21 @@ class NewHarnessController extends ChangeNotifier {
message: 'This machine is unavailable. Choose a machine.',
);
}
+ if (isCloud) {
+ if (cloudAgentTakesRepository(_engine) && cloudRepository == null) {
+ return (
+ field: NewHarnessField.projectMenu,
+ message: 'Choose a GitHub repository for $agentLabel.',
+ );
+ }
+ if (task.trim().isEmpty) {
+ return (
+ field: NewHarnessField.task,
+ message: 'Tell $agentLabel what to do.',
+ );
+ }
+ return null;
+ }
if (_harnessId != null && !_offered(_harnessId!)) {
return (
field: NewHarnessField.harness,
@@ -2903,6 +2958,9 @@ class NewHarnessController extends ChangeNotifier {
'amp',
'kilo',
'devin',
+ 'devin-cloud',
+ 'cursor-cloud',
+ 'fo',
'pi',
'hermes',
'commandcode',
@@ -2921,7 +2979,9 @@ class NewHarnessController extends ChangeNotifier {
])
if (isHarnessId(id)
? _offered(id)
- : engines.contains(id) || id == kTerminalEngine)
+ : engines.contains(id) ||
+ isCloudAgentId(id) ||
+ id == kTerminalEngine)
isHarnessId(id) ? operationId(id) : id,
})
isHarnessId(id)
@@ -3476,6 +3536,7 @@ class NewHarnessController extends ChangeNotifier {
focusField(choice.field);
return _fail(choice.message);
}
+ if (isCloud) return _createCloud();
if (!checking) {
_syncGitProject();
if (gitError != null) retryGitProject();
@@ -3709,6 +3770,32 @@ class NewHarnessController extends ChangeNotifier {
return NewHarnessOutcome.created;
}
+ /// A cloud harness: made by the cloud service on this machine (CLI
+ /// services/cloud.ts), which starts it at its maker; no folder, no install.
+ Future<NewHarnessOutcome> _createCloud() async {
+ busy = true;
+ error = null;
+ status = 'Starting $agentLabel…';
+ notifyListeners();
+ final failure = await app.createCloudHarness(
+ _machineId,
+ engine: _engine,
+ prompt: task.trim(),
+ repositoryUrl: cloudAgentTakesRepository(_engine)
+ ? cloudRepository
+ : null,
+ acuLimit: _engine == 'devin-cloud' ? acuLimit : null,
+ swarmId: _targetId,
+ split: split,
+ placement: effectivePlacement,
+ );
+ if (_disposed) return NewHarnessOutcome.failed;
+ if (failure != null) return _fail(failure);
+ busy = false;
+ status = null;
+ return NewHarnessOutcome.created;
+ }
+
/// Hands a created harness its files and then its task, detached from this
/// box, which may already be gone ([deliverAttachedTask]).
void _deliverFiles(
diff --git a/desktop/lib/state/workspace_pull_request.dart b/desktop/lib/state/workspace_pull_request.dart
index 96856bff0..54665ff4c 100644
--- a/desktop/lib/state/workspace_pull_request.dart
+++ b/desktop/lib/state/workspace_pull_request.dart
@@ -36,6 +36,38 @@ class WorkspacePullRequest extends ChangeNotifier {
void _focusChanged() {
final focused = WorkspacePaneContext.focused(app);
final agent = focused?.agent;
+ // A cloud harness's pull request is on its frame, from its maker: nothing
+ // here has its branch to ask Git about.
+ if (agent?.cloud case final cloud?) {
+ final link = cloud.pullRequest;
+ final number = link == null
+ ? null
+ : int.tryParse(
+ RegExp(r'/pull/(\d+)$').firstMatch(link.url)?.group(1) ?? '',
+ );
+ final identity = (
+ focused!.pane.machineId,
+ agent!.id,
+ null,
+ link?.url,
+ null,
+ );
+ if (identity == _identity) return;
+ _identity = identity;
+ ++_revision;
+ value = PullRequestStatus.fromResult(
+ link == null
+ ? null
+ : {
+ 'status': 'found',
+ 'number': number,
+ 'state': 'Open',
+ 'url': link.url,
+ },
+ );
+ notifyListeners();
+ return;
+ }
final project = agent == null
? null
: app.stateOf(focused!.pane.machineId)?.projectOf(agent);
diff --git a/desktop/lib/state/workspace_status.dart b/desktop/lib/state/workspace_status.dart
index b77c20cea..464646b87 100644
--- a/desktop/lib/state/workspace_status.dart
+++ b/desktop/lib/state/workspace_status.dart
@@ -242,7 +242,10 @@ class WorkspacePaneContext {
final agentId = pane.isViewer ? pane.ownerAgentId : pane.agentId;
final agent = _agentFor(app, pane.machineId, agentId);
final project = agent == null ? null : machine?.projectOf(agent);
- final machineName = machine?.machine.displayName ?? pane.machineId;
+ // A cloud harness runs in its maker's cloud: that is said where a remote
+ // computer's name goes ("Devin's cloud").
+ final machineName =
+ agent?.cloud?.place ?? machine?.machine.displayName ?? pane.machineId;
final engine = agent?.engine ?? pane.session?.engineId;
final provider =
agent?.gridModel ??
diff --git a/desktop/lib/widgets/cloud_chat_pane.dart b/desktop/lib/widgets/cloud_chat_pane.dart
new file mode 100644
index 000000000..e11f8ae86
--- /dev/null
+++ b/desktop/lib/widgets/cloud_chat_pane.dart
@@ -0,0 +1,441 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+
+import '../core/models.dart';
+import '../shared/theme/app_theme.dart' as grid;
+import '../shared/theme/workspace_bar_style.dart';
+import '../state/app_state.dart';
+import '../state/pending_question.dart';
+import '../terminal/terminal_theme.dart';
+import '../terminal/terminal_theme_store.dart';
+import '../theme/app_theme.dart';
+import 'agent_drag.dart';
+import 'harness_activity_mark.dart';
+import 'engine_identity.dart';
+import 'pane_header_actions.dart';
+import 'rename_agent_dialog.dart';
+
+/// One message of a cloud harness's conversation, as `cloud_transcript` gives it.
+typedef CloudMessage = ({String id, String from, String text});
+
+/// A cloud harness's pane (docs/design/2026-10-11-cloud-agents.md): it runs on
+/// its maker's servers and has no terminal, so its pane is a conversation, a
+/// line saying what it is doing, its question's choices, and a prompt. Its
+/// header is every pane's header: the harness's name and activity mark on the
+/// left, its agent and × on the right. Where it runs is said in the footer, where
+/// a remote computer's name goes (`WorkspacePaneContext`), never here.
+class CloudChatPane extends StatefulWidget {
+ const CloudChatPane({
+ super.key,
+ required this.notifier,
+ required this.machineId,
+ required this.agent,
+ this.onClose,
+ this.compactHeader = false,
+ this.visible = true,
+ this.read,
+ });
+
+ final AppNotifier notifier;
+ final String machineId;
+ final Agent agent;
+ final VoidCallback? onClose;
+ final bool compactHeader;
+ final bool visible;
+
+ /// How the conversation is read; the notifier's `cloud_transcript` unless a
+ /// test hands one in.
+ final Future<Map<String, dynamic>?> Function(
+ String machineId,
+ String agentId,
+ )?
+ read;
+
+ @override
+ State<CloudChatPane> createState() => _CloudChatPaneState();
+}
+
+class _CloudChatPaneState extends State<CloudChatPane> {
+ /// The agent's own name ("Devin Cloud"), and the one its lines are said by ("Devin").
+ String get _agentLabel => engineIdentity(widget.agent.engine).label;
+ String get _speaker => _agentLabel.split(' ').first;
+
+ final _prompt = TextEditingController();
+ final _promptFocus = FocusNode(debugLabel: 'Cloud harness prompt');
+ final _scroll = ScrollController();
+ List<CloudMessage> _messages = const [];
+ bool _loaded = false;
+ bool _sending = false;
+ String? _error;
+ int _readAt = -1;
+
+ @override
+ void initState() {
+ super.initState();
+ unawaited(_load());
+ }
+
+ @override
+ void didUpdateWidget(CloudChatPane old) {
+ super.didUpdateWidget(old);
+ // The frame says how many messages its conversation holds: read again when that moves.
+ if (old.agent.id != widget.agent.id ||
+ (widget.agent.cloud?.messages ?? 0) != _readAt) {
+ unawaited(_load());
+ }
+ }
+
+ @override
+ void dispose() {
+ _prompt.dispose();
+ _promptFocus.dispose();
+ _scroll.dispose();
+ super.dispose();
+ }
+
+ Future<void> _load() async {
+ final wanted = widget.agent.cloud?.messages ?? 0;
+ _readAt = wanted;
+ final read = widget.read ?? widget.notifier.readCloudTranscript;
+ final reply = await read(widget.machineId, widget.agent.id);
+ if (!mounted || reply == null) return;
+ final rows = reply['messages'];
+ setState(() {
+ _loaded = true;
+ _messages = [
+ if (rows is List)
+ for (final row in rows)
+ if (row is Map && row['text'] is String)
+ (
+ id: '${row['id']}',
+ from: row['from'] == 'person' ? 'person' : 'agent',
+ text: row['text'] as String,
+ ),
+ ];
+ });
+ }
+
+ /// The person's words, typed or a choice tapped, as words for it
+ /// (`cloud_send`), which its service takes as the answer to an open question
+ /// too. Answered, so a refusal is said here and the words stay in the prompt.
+ Future<void> _send([String? words]) async {
+ final text = (words ?? _prompt.text).trim();
+ if (text.isEmpty || _sending) return;
+ setState(() {
+ _sending = true;
+ _error = null;
+ });
+ final refused = await widget.notifier.sendCloudMessage(
+ widget.machineId,
+ widget.agent.id,
+ text,
+ );
+ if (!mounted) return;
+ setState(() {
+ _sending = false;
+ _error = refused;
+ if (refused == null && words == null) _prompt.clear();
+ });
+ if (refused == null) unawaited(_load());
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final theme = terminalThemeFor(
+ grid.AppTheme.palette.value,
+ terminalThemeStore.value,
+ );
+ return ColoredBox(
+ color: theme.background,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ MediaQuery.withNoTextScaling(child: _header(theme.foreground)),
+ Divider(height: 1, color: AppColors.border),
+ Expanded(child: _conversation(theme.foreground)),
+ _prompter(theme.foreground),
+ ],
+ ),
+ );
+ }
+
+ Widget _header(Color ink) => SizedBox(
+ height: widget.compactHeader ? 38 : 46,
+ child: Padding(
+ padding: const EdgeInsets.only(
+ left: 14,
+ right: grid.AppDesktop.paneCloseInset,
+ ),
+ child: Row(
+ children: [
+ Expanded(
+ child: Row(
+ children: [
+ Flexible(
+ child: Tooltip(
+ message:
+ '${widget.agent.displayName}\n${widget.agent.cloud?.place ?? ''}',
+ waitDuration: const Duration(milliseconds: 500),
+ // Renamed as a terminal pane's title is: a double click.
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onDoubleTap: () => unawaited(
+ showAgentRenameDialog(
+ context,
+ widget.notifier,
+ widget.machineId,
+ widget.agent.id,
+ widget.agent.displayName,
+ ),
+ ),
+ child: Text(
+ widget.agent.displayName,
+ key: const ValueKey('cloud-pane-title'),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: workspaceBarTextStyle(color: ink),
+ ),
+ ),
+ ),
+ ),
+ HarnessActivityMark(
+ app: widget.notifier,
+ machineId: widget.machineId,
+ agentId: widget.agent.id,
+ visible: widget.visible,
+ ),
+ ],
+ ),
+ ),
+ const SizedBox(width: 8),
+ // Its agent, in the ink a pane's agent rests in, and no picker: a
+ // cloud harness is not moved to another agent.
+ PaneHeaderActions(
+ agentPicker: Semantics(
+ label: 'Agent: $_agentLabel',
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 8),
+ child: Text(
+ _agentLabel,
+ key: const ValueKey('pane-agent-control'),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: workspaceBarTextStyle(
+ color: ink.withValues(alpha: .75),
+ ),
+ ),
+ ),
+ ),
+ ),
+ if (widget.onClose != null)
+ PaneCloseButton(onPressed: widget.onClose!),
+ ],
+ ),
+ ),
+ );
+
+ Widget _conversation(Color ink) {
+ final style = workspaceBarTextStyle(color: ink);
+ final muted = workspaceBarTextStyle(color: AppColors.mutedStrong);
+ final cloud = widget.agent.cloud;
+ final question = widget.notifier.questionFor(
+ widget.machineId,
+ widget.agent.id,
+ );
+ final senderWidth = _senderWidth(style);
+ final rows = <Widget>[
+ for (final message in _messages)
+ _row(
+ message.from == 'person' ? 'you' : _speaker,
+ message.text,
+ message.from == 'person' ? muted : style,
+ muted,
+ senderWidth,
+ key: ValueKey('cloud-message-${message.id}'),
+ ),
+ if (cloud != null && cloud.working && question == null)
+ _row(
+ _speaker,
+ '${cloud.activity ?? 'Working'}…',
+ muted,
+ muted,
+ senderWidth,
+ key: const ValueKey('cloud-activity'),
+ ),
+ if (cloud != null &&
+ !cloud.working &&
+ cloud.activity != null &&
+ question == null)
+ _row(
+ '',
+ cloud.activity!,
+ muted,
+ muted,
+ senderWidth,
+ key: const ValueKey('cloud-note'),
+ ),
+ if (question != null) _choices(question, style, senderWidth),
+ if (_error != null)
+ _row(
+ '',
+ _error!,
+ workspaceBarTextStyle(color: AppColors.danger),
+ muted,
+ senderWidth,
+ key: const ValueKey('cloud-error'),
+ ),
+ ];
+ if (!_loaded && rows.isEmpty) {
+ return Center(child: Text('Reading the conversation…', style: muted));
+ }
+ // Newest at the bottom, kept in view as messages arrive.
+ return ListView(
+ key: const ValueKey('cloud-conversation'),
+ controller: _scroll,
+ reverse: true,
+ padding: const EdgeInsets.fromLTRB(14, 10, 14, 6),
+ children: rows.reversed.toList(),
+ );
+ }
+
+ double _senderWidth(TextStyle style) {
+ final painter = TextPainter(
+ text: TextSpan(text: '$_speaker ', style: style),
+ textDirection: TextDirection.ltr,
+ maxLines: 1,
+ )..layout();
+ final width = painter.width;
+ painter.dispose();
+ return width < 40 ? 40 : width;
+ }
+
+ Widget _row(
+ String sender,
+ String text,
+ TextStyle style,
+ TextStyle muted,
+ double senderWidth, {
+ Key? key,
+ }) => Padding(
+ key: key,
+ padding: const EdgeInsets.only(bottom: 6),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ SizedBox(
+ width: senderWidth,
+ child: Text(sender, style: muted),
+ ),
+ Expanded(child: SelectableText(text, style: style)),
+ ],
+ ),
+ );
+
+ /// Its question's choices, each a button that answers with it; with none, the
+ /// prompt below takes the answer in words.
+ Widget _choices(
+ PendingQuestion question,
+ TextStyle style,
+ double senderWidth,
+ ) => Padding(
+ key: const ValueKey('cloud-question'),
+ padding: const EdgeInsets.only(bottom: 6),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ SizedBox(width: senderWidth),
+ Expanded(
+ child: question.options.isEmpty
+ ? Text(
+ 'Waiting for your answer',
+ style: workspaceBarTextStyle(color: AppColors.warning),
+ )
+ : Wrap(
+ spacing: 14,
+ runSpacing: 4,
+ children: [
+ for (final (index, option) in question.options.indexed)
+ TextButton(
+ key: ValueKey('cloud-choice-$index'),
+ onPressed: _sending
+ ? null
+ : () => unawaited(_send(option)),
+ style: TextButton.styleFrom(
+ foregroundColor: AppColors.warning,
+ padding: const EdgeInsets.symmetric(
+ horizontal: 4,
+ vertical: 2,
+ ),
+ minimumSize: Size.zero,
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ ),
+ child: Text(
+ '${index + 1}) $option',
+ style: workspaceBarTextStyle(
+ color: AppColors.warning,
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ );
+
+ Widget _prompter(Color ink) {
+ final stopped = widget.agent.cloud?.state == 'stopped';
+ return Padding(
+ padding: const EdgeInsets.fromLTRB(14, 4, 14, 10),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Padding(
+ padding: EdgeInsets.zero,
+ child: Text(
+ '❯ ',
+ style: workspaceBarTextStyle(color: AppColors.mutedStrong),
+ ),
+ ),
+ Expanded(
+ child: CallbackShortcuts(
+ // Enter sends; Shift-Enter breaks the line, as the composer does.
+ bindings: {
+ const SingleActivator(LogicalKeyboardKey.enter): () =>
+ unawaited(_send()),
+ },
+ child: TextField(
+ key: const ValueKey('cloud-prompt'),
+ controller: _prompt,
+ focusNode: _promptFocus,
+ enabled: !_sending,
+ minLines: 1,
+ maxLines: 6,
+ style: workspaceBarTextStyle(color: ink),
+ cursorColor: ink,
+ // No box: the prompt is a line, as a terminal's is.
+ decoration: InputDecoration(
+ isCollapsed: true,
+ isDense: true,
+ contentPadding: EdgeInsets.zero,
+ filled: false,
+ border: InputBorder.none,
+ enabledBorder: InputBorder.none,
+ focusedBorder: InputBorder.none,
+ disabledBorder: InputBorder.none,
+ hintText: stopped ? 'Write to wake it' : 'Write to $_speaker',
+ hintStyle: workspaceBarTextStyle(
+ color: AppColors.mutedStrong,
+ ),
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/widgets/delete_agent_dialog.dart b/desktop/lib/widgets/delete_agent_dialog.dart
index 02b06b463..56241232f 100644
--- a/desktop/lib/widgets/delete_agent_dialog.dart
+++ b/desktop/lib/widgets/delete_agent_dialog.dart
@@ -2,6 +2,7 @@ import 'dart:async';
import 'package:flutter/material.dart';
+import '../core/models.dart';
import '../shortcuts/app_keymap.dart';
import '../state/app_state.dart';
import '../shared/theme/app_theme.dart' as grid;
@@ -49,6 +50,14 @@ class _StopAgentPrompt extends StatefulWidget {
}
class _StopAgentPromptState extends State<_StopAgentPrompt> {
+ Agent? get _agent => widget.notifier
+ .stateOf(widget.machineId)
+ ?.agents
+ .where((agent) => agent.id == widget.agentId)
+ .firstOrNull;
+ AgentCloud? get _cloud => _agent?.cloud;
+ String? get _engine => _agent?.engine;
+
final _cancel = FocusNode(debugLabel: 'Cancel stop');
final _promptFocus = FocusNode(debugLabel: 'Pending stop');
final _body = ScrollController();
@@ -160,7 +169,11 @@ class _StopAgentPromptState extends State<_StopAgentPrompt> {
widget.name,
style: DesktopChrome.text(size: 14, medium: true),
),
- if (widget.notifier.stateOf(widget.machineId)?.machine.displayName
+ if (_cloud?.place ??
+ widget.notifier
+ .stateOf(widget.machineId)
+ ?.machine
+ .displayName
case final machine?) ...[
const SizedBox(height: 4),
Text(machine, style: DesktopChrome.metadata()),
@@ -169,6 +182,12 @@ class _StopAgentPromptState extends State<_StopAgentPrompt> {
Text(
widget.terminal
? 'End this shell and anything running in it? Files are kept.'
+ // A cloud agent stops where its maker lets it: Devin Cloud
+ // and Cursor Cloud sleep; Fo keeps working on its own.
+ : _cloud != null
+ ? (_engine == 'fo'
+ ? 'Stop following this harness here? Fo keeps working on its own, and its conversation is kept.'
+ : 'Stop this harness? Its session goes to sleep and stops spending; its conversation is kept, and a message wakes it.')
: 'Stop this harness? Project files and saved conversation history are kept.',
style: DesktopChrome.text(size: 13),
),
diff --git a/desktop/lib/widgets/engine_identity.dart b/desktop/lib/widgets/engine_identity.dart
index 0418bdb3a..867fa4508 100644
--- a/desktop/lib/widgets/engine_identity.dart
+++ b/desktop/lib/widgets/engine_identity.dart
@@ -861,6 +861,65 @@ const EngineIdentity _terminal = EngineIdentity(
color: Color(0xffa8b0b8),
);
+/// The cloud agents (CLI lib/cloudAgents.ts): agents that run on their maker's
+/// servers, reached through its API, with no terminal here. A SEPARATE map from
+/// [_engines] for the reason [_harnesses] is one: never probed as an engine
+/// (`engines_probe`), never given a launch flag. Named by the Naming System's
+/// rule: a CLI agent keeps its name, its maker's cloud agent adds "Cloud".
+const _cloudAgents = <String, EngineIdentity>{
+ 'fo': EngineIdentity(
+ id: 'fo',
+ label: 'Fo',
+ category: 'Errands',
+ tagline: 'Calls, emails and books things for you',
+ creator: 'Wajo',
+ color: Color(0xffffb86c),
+ homepage: 'https://wajo.ai',
+ blurb: "Wajo's Fo, which runs errands from its own servers.",
+ ),
+ 'devin-cloud': EngineIdentity(
+ id: 'devin-cloud',
+ label: 'Devin Cloud',
+ category: 'Code',
+ tagline: 'Devin in its own cloud machine',
+ creator: 'Cognition',
+ color: Color(0xff8fb8ff),
+ asset: 'assets/engine-icons/devin.png',
+ homepage: 'https://devin.ai',
+ blurb: "Cognition's Devin, working in its own cloud machine.",
+ ),
+ 'cursor-cloud': EngineIdentity(
+ id: 'cursor-cloud',
+ label: 'Cursor Cloud',
+ category: 'Code',
+ tagline: "Cursor's agent in its own cloud machine",
+ creator: 'Anysphere',
+ color: Color(0xffd5d5d5),
+ asset: 'assets/engine-icons/cursor.png',
+ homepage: 'https://cursor.com',
+ blurb: "Cursor's cloud agent, working on a GitHub repository.",
+ ),
+};
+
+/// The cloud agents, in declaration order — for New Harness's agent list.
+List<EngineIdentity> get cloudAgents =>
+ _cloudAgents.values.toList(growable: false);
+
+/// Where a cloud agent runs, said where a computer's name goes.
+String cloudPlaceOf(String? id) => switch (id) {
+ 'fo' => "Fo's cloud",
+ 'devin-cloud' => "Devin's cloud",
+ 'cursor-cloud' => "Cursor's cloud",
+ _ => 'The cloud',
+};
+
+/// Whether [id] names a cloud agent rather than an engine on a computer.
+bool isCloudAgentId(String? id) => id != null && _cloudAgents.containsKey(id);
+
+/// The cloud agents that work on a GitHub repository (the others take none).
+bool cloudAgentTakesRepository(String? id) =>
+ id == 'devin-cloud' || id == 'cursor-cloud';
+
/// The terminal's face, for the one list that offers it: New Harness.
EngineIdentity get terminalIdentity => _terminal;
@@ -882,6 +941,7 @@ EngineIdentity engineIdentity(String? engine, {String? displayName}) {
final id = engine?.trim().toLowerCase() ?? '';
final known =
_engines[id] ??
+ _cloudAgents[id] ??
_harnesses[canonicalHarnessId(id)] ??
_linkedHarnesses[id] ??
(id == kTerminalEngine ? _terminal : null);
@@ -983,9 +1043,11 @@ class EngineMark extends StatelessWidget {
// but sit bare on a dark palette as they always have; only a light one
// needs the tile.
final needsDarkTile =
- const {'cursor', 'opencode', 'autonomous/kicad'}.contains(
- identity.id,
- ) ||
+ const {
+ 'cursor',
+ 'opencode',
+ 'autonomous/kicad',
+ }.contains(identity.id) ||
(!dark && const {'grok', 'copilot'}.contains(identity.id));
return Opacity(
opacity: enabled ? 1 : 0.45,
diff --git a/desktop/lib/widgets/new_harness_form.dart b/desktop/lib/widgets/new_harness_form.dart
index 152c74aba..af901e9f8 100644
--- a/desktop/lib/widgets/new_harness_form.dart
+++ b/desktop/lib/widgets/new_harness_form.dart
@@ -1766,43 +1766,84 @@ class NewHarnessFormState extends State<NewHarnessForm> {
capsule: true,
),
),
- _desktopField(
- order: 2,
- anchor: _headerMachineAnchor,
- child: _desktopMachineAnchor(
+ // A cloud agent runs in its maker's cloud, never on a computer:
+ // the place is said where the computer is, and does not change.
+ if (box.isCloud)
+ _desktopField(
+ order: 2,
+ anchor: _headerMachineAnchor,
child: DesktopPill(
key: const ValueKey('new-harness-field-machine'),
focusNode: _headerMachineFocus,
- label: _repoMachineLabel(box.machineId),
- semanticLabel:
- 'Computer, ${_repoMachineLabel(box.machineId)}',
- icon: box.app.stateOf(box.machineId)?.isLocalMachine == true
- ? AppIcons.laptop
- : AppIcons.monitor,
- menu: true,
+ label: cloudPlaceOf(box.engine),
+ semanticLabel: 'Runs in ${cloudPlaceOf(box.engine)}',
+ icon: AppIcons.monitor,
capsule: true,
- tooltip: 'Choose computer',
+ tooltip: '${box.agentLabel} runs on its maker\'s servers',
textSize: 13,
surfaceColor: DesktopChrome.surface,
- onPressed: box.locked
- ? null
- : () => _headerMachineMenu.isOpen
- ? _headerMachineMenu.close()
- : _headerMachineMenu.open(),
+ onPressed: null,
+ ),
+ )
+ else
+ _desktopField(
+ order: 2,
+ anchor: _headerMachineAnchor,
+ child: _desktopMachineAnchor(
+ child: DesktopPill(
+ key: const ValueKey('new-harness-field-machine'),
+ focusNode: _headerMachineFocus,
+ label: _repoMachineLabel(box.machineId),
+ semanticLabel:
+ 'Computer, ${_repoMachineLabel(box.machineId)}',
+ icon:
+ box.app.stateOf(box.machineId)?.isLocalMachine == true
+ ? AppIcons.laptop
+ : AppIcons.monitor,
+ menu: true,
+ capsule: true,
+ tooltip: 'Choose computer',
+ textSize: 13,
+ surfaceColor: DesktopChrome.surface,
+ onPressed: box.locked
+ ? null
+ : () => _headerMachineMenu.isOpen
+ ? _headerMachineMenu.close()
+ : _headerMachineMenu.open(),
+ ),
),
),
- ),
- _desktopField(
- order: 3,
- anchor: _desktopAnchors[_Row.project]!,
- maxWidth: 340,
- child: _desktopChoiceButton(
- _Row.project,
- AppIcons.folder,
- label: projectName,
- capsule: true,
+ // Fo takes no repository; a cloud coding agent works on the chosen
+ // repository's GitHub copy, never on this computer's folder.
+ if (!box.isCloud || cloudAgentTakesRepository(box.engine))
+ _desktopField(
+ order: 3,
+ anchor: _desktopAnchors[_Row.project]!,
+ maxWidth: 340,
+ child: Tooltip(
+ message: box.isCloud
+ ? (box.cloudRepository == null
+ ? 'Choose a repository on GitHub, or a folder whose remote is on GitHub'
+ : 'Works on ${box.cloudRepository}. Changes not pushed stay on this computer.')
+ : '',
+ child: _desktopChoiceButton(
+ _Row.project,
+ AppIcons.folder,
+ label: box.isCloud
+ ? box.cloudRepository
+ ?.replaceFirst(
+ RegExp(
+ r'^(https://github\.com/|git@github\.com:)',
+ ),
+ '',
+ )
+ .replaceFirst(RegExp(r'\.git$'), '') ??
+ projectName
+ : projectName,
+ capsule: true,
+ ),
+ ),
),
- ),
],
),
),
@@ -1974,12 +2015,40 @@ class NewHarnessFormState extends State<NewHarnessForm> {
mainAxisSize: MainAxisSize.min,
spacing: 2,
children: [
- if (!box.isTerminal)
+ if (!box.isTerminal && !box.isCloud)
_desktopField(
order: 5,
anchor: _desktopAnchors[_Row.model]!,
child: _desktopChoiceButton(_Row.model, AppIcons.brain),
),
+ // Devin Cloud bills while it works: the session's limit, low by
+ // default, stepped through on each press.
+ if (box.isCloud && box.engine == 'devin-cloud')
+ _desktopField(
+ order: 5,
+ anchor: _desktopAnchors[_Row.model]!,
+ child: DesktopPill(
+ key: const ValueKey('new-harness-field-acu'),
+ label: 'Up to ${box.acuLimit} ACUs',
+ semanticLabel: 'ACU limit, ${box.acuLimit}',
+ icon: AppIcons.gauge,
+ quiet: true,
+ compact: true,
+ textSize: 12,
+ foregroundColor: DesktopChrome.muted,
+ tooltip:
+ 'The most this session may spend. Press for another limit.',
+ onPressed: box.locked
+ ? null
+ : () {
+ const limits = NewHarnessController.acuLimits;
+ box.setAcuLimit(
+ limits[(limits.indexOf(box.acuLimit) + 1) %
+ limits.length],
+ );
+ },
+ ),
+ ),
if (box.hasModes)
_desktopField(
order: 6,
@@ -2023,7 +2092,8 @@ class NewHarnessFormState extends State<NewHarnessForm> {
),
),
),
- if (box.isGitProject || box.checkingGit || box.gitError != null)
+ if (!box.isCloud &&
+ (box.isGitProject || box.checkingGit || box.gitError != null))
_desktopField(
order: 9,
anchor: _desktopAnchors[_Row.branch]!,
diff --git a/desktop/lib/widgets/pane_grid.dart b/desktop/lib/widgets/pane_grid.dart
index e45ebd62f..9bfc0e63a 100644
--- a/desktop/lib/widgets/pane_grid.dart
+++ b/desktop/lib/widgets/pane_grid.dart
@@ -30,6 +30,7 @@ import '../terminal/terminal_text.dart';
import '../terminal/terminal_session.dart';
import '../theme/app_theme.dart';
import 'agent_drag.dart';
+import 'cloud_chat_pane.dart';
import 'harness_join_guide_screen.dart';
import 'link_machine_screen.dart';
import 'new_agent_dialog.dart';
@@ -1620,6 +1621,19 @@ class _PaneContent extends StatelessWidget {
.where((agent) => agent.id == wantedAgentId)
.firstOrNull;
final agentName = agent?.displayName;
+ // A cloud harness has no terminal to attach: its pane is a conversation
+ // (widgets/cloud_chat_pane.dart), and every other pane stays a terminal.
+ if (agent != null && agent.isCloud) {
+ return CloudChatPane(
+ key: ValueKey('cloud-pane-${pane.id}'),
+ notifier: notifier,
+ machineId: pane.machineId,
+ agent: agent,
+ visible: visible,
+ compactHeader: swarmMode,
+ onClose: close,
+ );
+ }
final needsLink =
machine != null &&
machine.isRemote &&
diff --git a/desktop/test/cloud_agents_test.dart b/desktop/test/cloud_agents_test.dart
new file mode 100644
index 000000000..17df14ec9
--- /dev/null
+++ b/desktop/test/cloud_agents_test.dart
@@ -0,0 +1,511 @@
+// Cloud agents on the desktop (docs/design/2026-10-11-cloud-agents.md): a cloud
+// harness's frame, its chat pane with every pane's header, its question's
+// choices answered as the dial answers one, the person's words sent to it, and
+// the footer saying where it runs.
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/state/workspace_status.dart';
+import 'package:harness/widgets/cloud_chat_pane.dart';
+import 'package:harness/widgets/engine_identity.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'support/rename_connection.dart';
+import 'swarm_screen_test.dart' show mount;
+import 'swarm_state_test.dart' show createApp;
+
+/// A connection that answers the cloud requests as the CLI's cloud service does.
+class CloudConnection extends RenameConnection {
+ final sent = <Map<String, dynamic>>[];
+ final raw = <(String, Map<String, dynamic>)>[];
+ Map<String, dynamic> sendReply = {'ok': true};
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ if (type == 'cloud_send') {
+ sent.add(Map.of(payload));
+ return sendReply;
+ }
+ if (type == 'cloud_transcript') {
+ return {
+ 'messages': [
+ {
+ 'id': 'p1',
+ 'from': 'person',
+ 'text': 'book a haircut saturday morning near me',
+ },
+ {
+ 'id': 'a1',
+ 'from': 'agent',
+ 'text': 'They have 9:30 or 11:00. Which one?',
+ },
+ ],
+ 'total': 2,
+ };
+ }
+ return super.request(type, payload: payload, timeout: timeout);
+ }
+
+ @override
+ void sendRaw(String type, Map<String, dynamic> payload) =>
+ raw.add((type, payload));
+}
+
+Map<String, dynamic> cloudFrame({
+ String id = 'cloud_1',
+ String engine = 'fo',
+ String state = 'needs_input',
+ String? activity,
+ int messages = 2,
+ List<Map<String, String>> links = const [],
+ Map<String, dynamic>? project,
+}) => {
+ 'id': id,
+ 'name': 'haircut Saturday',
+ 'engine': engine,
+ 'status': state == 'stopped' ? 'stopped' : 'active',
+ 'location': 'cloud',
+ 'terminal': {'available': false, 'primary': '', 'runtimes': []},
+ 'project': ?project,
+ 'cloud': {
+ 'place': cloudPlaceOf(engine),
+ 'state': state,
+ 'activity': activity,
+ 'links': links,
+ 'messages': messages,
+ },
+};
+
+void main() {
+ test(
+ 'a cloud harness\'s frame reads as one, and a terminal agent\'s never does',
+ () {
+ final agent = Agent.fromJson(
+ cloudFrame(
+ engine: 'devin-cloud',
+ state: 'working',
+ activity: 'Reading code',
+ links: [
+ {'label': 'Session', 'url': 'https://app.devin.ai/sessions/1'},
+ {
+ 'label': 'Pull request #42',
+ 'url': 'https://github.com/acme/api/pull/42',
+ },
+ {'label': 'Bad', 'url': 'http://not-https'},
+ ],
+ ),
+ );
+ expect(agent.isCloud, isTrue);
+ expect(agent.terminalAvailable, isFalse);
+ expect(agent.cloud!.place, "Devin's cloud");
+ expect(agent.cloud!.working, isTrue);
+ expect(agent.cloud!.activity, 'Reading code');
+ expect(agent.cloud!.links.map((link) => link.label), [
+ 'Session',
+ 'Pull request #42',
+ ]);
+ expect(
+ agent.cloud!.pullRequest?.url,
+ 'https://github.com/acme/api/pull/42',
+ );
+ expect(agent.copyWith(name: 'renamed').cloud, same(agent.cloud));
+ expect(
+ Agent.fromJson({
+ 'id': 'a1',
+ 'name': 'x',
+ 'engine': 'claude',
+ 'cloud': {'place': 'x'},
+ }).isCloud,
+ isFalse,
+ );
+ final odd = AgentCloud.fromJson({
+ 'state': 'dancing',
+ 'messages': -3,
+ 'links': 'x',
+ });
+ expect(
+ [odd.place, odd.state, odd.messages, odd.links],
+ ['The cloud', 'idle', 0, isEmpty],
+ );
+ expect(AgentCloud.fromJson(null).pullRequest, isNull);
+ },
+ );
+
+ test('cloud agents are named by the Naming System\'s rule and never probed as engines', () {
+ expect(cloudAgents.map((agent) => agent.label), [
+ 'Fo',
+ 'Devin Cloud',
+ 'Cursor Cloud',
+ ]);
+ expect(engineIdentity('devin-cloud').label, 'Devin Cloud');
+ expect(engineIdentity('devin').label, 'Devin');
+ expect(
+ allEngines.map((engine) => engine.id),
+ isNot(contains('devin-cloud')),
+ );
+ expect(isCloudAgentId('fo'), isTrue);
+ expect(isCloudAgentId('claude'), isFalse);
+ expect(cloudAgentTakesRepository('fo'), isFalse);
+ expect(cloudAgentTakesRepository('cursor-cloud'), isTrue);
+ expect(cloudPlaceOf('cursor-cloud'), "Cursor's cloud");
+ expect(cloudPlaceOf('other'), 'The cloud');
+ });
+
+ Future<(AppNotifier, CloudConnection)> setUp(
+ WidgetTester tester,
+ Map<String, dynamic> frame,
+ ) async {
+ final connection = CloudConnection();
+ final app = createApp(
+ connectionForTest: (_) => connection,
+ connected: true,
+ );
+ addTearDown(app.dispose);
+ await app.handleEventForTest('m', {
+ 'type': 'agent_synced',
+ 'payload': {'agent': frame},
+ });
+ return (app, connection);
+ }
+
+ Agent agentOf(AppNotifier app, [String id = 'cloud_1']) =>
+ app.stateOf('m')!.agents.firstWhere((agent) => agent.id == id);
+
+ Future<void> mountPane(
+ WidgetTester tester,
+ AppNotifier app, {
+ VoidCallback? onClose,
+ }) async {
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: ListenableBuilder(
+ listenable: app,
+ builder: (context, _) => CloudChatPane(
+ notifier: app,
+ machineId: 'm',
+ agent: agentOf(app),
+ onClose: onClose,
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ }
+
+ testWidgets(
+ 'the chat pane: every pane\'s header, the conversation, and its question\'s choices answered as the dial does',
+ (tester) async {
+ final (app, connection) = await setUp(tester, cloudFrame());
+ await app.handleEventForTest('m', {
+ 'type': 'commander_question',
+ 'agentId': 'cloud_1',
+ 'payload': {
+ 'requestId': 'cloud_q_1',
+ 'questions': [
+ {
+ 'key': 'answer',
+ 'q': 'Which one?',
+ 'options': ['9:30', '11:00'],
+ 'multi': false,
+ 'canText': true,
+ },
+ ],
+ },
+ });
+ var closed = 0;
+ await mountPane(tester, app, onClose: () => closed++);
+ expect(find.byKey(const ValueKey('cloud-pane-title')), findsOneWidget);
+ expect(find.text('haircut Saturday'), findsOneWidget);
+ // The agent on the right, plainly: no picker to move a cloud harness elsewhere.
+ expect(find.byKey(const ValueKey('pane-agent-control')), findsOneWidget);
+ expect(find.text('Fo'), findsWidgets);
+ expect(
+ find.text("Fo's cloud"),
+ findsNothing,
+ reason: 'the place is said in the footer, never in the header',
+ );
+ expect(
+ find.text('book a haircut saturday morning near me'),
+ findsOneWidget,
+ );
+ expect(find.text('They have 9:30 or 11:00. Which one?'), findsOneWidget);
+ expect(find.text('1) 9:30'), findsOneWidget);
+ await tester.tap(find.byKey(const ValueKey('cloud-choice-0')));
+ await tester.pumpAndSettle();
+ // Answered as words for it, so a refusal can be said: the service takes them as the answer.
+ expect(connection.sent, [
+ {'agentId': 'cloud_1', 'text': '9:30'},
+ ]);
+ expect(connection.raw, isEmpty);
+ await tester.tap(find.byTooltip('Close Pane'));
+ expect(closed, 1);
+ },
+ );
+
+ testWidgets('its title is renamed as a terminal pane\'s is: a double click', (
+ tester,
+ ) async {
+ final (app, connection) = await setUp(tester, cloudFrame());
+ await mountPane(tester, app);
+ final title = find.byKey(const ValueKey('cloud-pane-title'));
+ await tester.tap(title);
+ await tester.pump(const Duration(milliseconds: 50));
+ await tester.tap(title);
+ await tester.pumpAndSettle();
+ final field = find.byKey(const Key('agent-rename-input'));
+ expect(field, findsOneWidget);
+ tester.testTextInput.enterText('Trip planning');
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.pump();
+ expect(connection.renames.single, {
+ 'agentId': 'cloud_1',
+ 'name': 'Trip planning',
+ });
+ connection.replies.single.complete({
+ 'agent': {'id': 'cloud_1', 'name': 'Trip planning'},
+ });
+ await tester.pumpAndSettle();
+ expect(find.text('Trip planning'), findsOneWidget);
+ });
+
+ testWidgets('words for it are sent, and a refusal is said in the pane', (
+ tester,
+ ) async {
+ final (app, connection) = await setUp(
+ tester,
+ cloudFrame(state: 'working', activity: 'Calling Hair Lab'),
+ );
+ await mountPane(tester, app);
+ expect(find.text('Calling Hair Lab…'), findsOneWidget);
+ await tester.enterText(
+ find.byKey(const ValueKey('cloud-prompt')),
+ 'make it 10',
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(connection.sent, [
+ {'agentId': 'cloud_1', 'text': 'make it 10'},
+ ]);
+ expect(
+ find.text('make it 10'),
+ findsNothing,
+ reason: 'the prompt empties once its maker has the words',
+ );
+ connection.sendReply = {
+ 'error': 'BUSY',
+ 'detail': 'Fo is still working. Send it again once it stops.',
+ };
+ await tester.enterText(find.byKey(const ValueKey('cloud-prompt')), 'again');
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(
+ find.text('Fo is still working. Send it again once it stops.'),
+ findsOneWidget,
+ );
+ expect(
+ find.text('again'),
+ findsOneWidget,
+ reason: 'refused words stay in the prompt',
+ );
+ });
+
+ testWidgets('the conversation is read again when its frame says it moved', (
+ tester,
+ ) async {
+ final (app, _) = await setUp(tester, cloudFrame(messages: 2));
+ var reads = 0;
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: ListenableBuilder(
+ listenable: app,
+ builder: (context, _) => CloudChatPane(
+ notifier: app,
+ machineId: 'm',
+ agent: agentOf(app),
+ read: (machineId, agentId) async {
+ reads++;
+ return {
+ 'messages': [
+ {'id': 'x', 'from': 'agent', 'text': 'read $reads'},
+ ],
+ 'total': 1,
+ };
+ },
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('read 1'), findsOneWidget);
+ await app.handleEventForTest('m', {
+ 'type': 'agent_synced',
+ 'payload': {
+ 'agent': cloudFrame(
+ messages: 3,
+ state: 'stopped',
+ activity: 'Fo keeps working on its own.',
+ ),
+ },
+ });
+ await tester.pumpAndSettle();
+ expect(find.text('read 2'), findsOneWidget);
+ expect(find.text('Fo keeps working on its own.'), findsOneWidget);
+ });
+
+ test('New Harness offers the cloud agents, asks a coding one for a GitHub repository, and makes one with its task', () async {
+ final connection = CreateConnection();
+ final app = createApp(
+ connectionForTest: (_) => connection,
+ connected: true,
+ );
+ addTearDown(app.dispose);
+ final devin = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'devin-cloud',
+ folder: '/work/no-remote',
+ );
+ addTearDown(devin.dispose);
+ expect(devin.isCloud, isTrue);
+ expect(devin.takesTask, isTrue);
+ expect(devin.hasModes, isFalse);
+ expect(devin.isGitProject, isFalse);
+ expect(devin.cloudRepository, isNull);
+ expect(
+ devin.requiredChoice?.message,
+ 'Choose a GitHub repository for Devin Cloud.',
+ );
+ expect(devin.acuLimit, 5);
+ devin.setAcuLimit(10);
+ expect(devin.acuLimit, 10);
+
+ final fo = NewHarnessController(app, machineId: 'm', engine: 'fo');
+ addTearDown(fo.dispose);
+ expect(fo.requiredChoice?.message, 'Tell Fo what to do.');
+ fo.setTask('book a haircut saturday morning near me');
+ expect(fo.requiredChoice, isNull);
+ expect(await fo.create(), NewHarnessOutcome.created);
+ expect(connection.creates.single, containsPair('engine', 'fo'));
+ expect(
+ connection.creates.single,
+ containsPair('prompt', 'book a haircut saturday morning near me'),
+ );
+ expect(connection.creates.single.containsKey('repositoryUrl'), isFalse);
+ expect(connection.creates.single.containsKey('cwd'), isFalse);
+
+ // Refused by the cloud service: its own words, never "not confirmed".
+ connection.refuse = {
+ 'error': 'NOT_CONNECTED',
+ 'detail':
+ 'Connect Fo in Connections (Add custom, https://mcp.api.wajo.ai/fo).',
+ };
+ final again = NewHarnessController(app, machineId: 'm', engine: 'fo');
+ addTearDown(again.dispose);
+ again.setTask('book a haircut');
+ expect(await again.create(), NewHarnessOutcome.failed);
+ expect(
+ again.error,
+ 'Connect Fo in Connections (Add custom, https://mcp.api.wajo.ai/fo).',
+ );
+ });
+
+ testWidgets(
+ 'in the workspace, a cloud harness\'s pane is its conversation, not a terminal waiting for one',
+ (tester) async {
+ final (app, _) = await setUp(
+ tester,
+ cloudFrame(state: 'working', activity: 'Calling Hair Lab'),
+ );
+ await app.addAgentToSwarm('m', 'cloud_1');
+ await mount(tester, app);
+ await tester.pump(const Duration(milliseconds: 50));
+ expect(find.byType(CloudChatPane), findsOneWidget);
+ expect(
+ find.text('This harness has no available terminal.'),
+ findsNothing,
+ );
+ expect(
+ find.text('book a haircut saturday morning near me'),
+ findsOneWidget,
+ );
+ },
+ );
+
+ test(
+ 'the footer says where a cloud harness runs, where a computer\'s name goes',
+ () async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ await app.handleEventForTest('m', {
+ 'type': 'agent_synced',
+ 'payload': {
+ 'agent': cloudFrame(
+ engine: 'devin-cloud',
+ project: {
+ 'kind': 'git',
+ 'name': 'api',
+ 'cwd': '',
+ 'root': null,
+ 'remote': 'https://github.com/acme/api',
+ 'branch': 'devin/fix',
+ },
+ ),
+ },
+ });
+ await app.addAgentToSwarm('m', 'cloud_1');
+ app.focusPane(app.panes.single.id);
+ final context = WorkspacePaneContext.focused(app)!;
+ expect(context.machineName, "Devin's cloud");
+ expect(context.agent!.isCloud, isTrue);
+ },
+ );
+}
+
+/// A connection that makes the cloud harness New Harness asks for.
+class CreateConnection extends CloudConnection {
+ final creates = <Map<String, dynamic>>[];
+ Map<String, dynamic>? refuse;
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ if (type == 'agent_create') {
+ creates.add(Map.of(payload));
+ // As the real connection does: an error reply is thrown, not returned.
+ if (refuse case final refusal?) {
+ throw WsRequestFailure(
+ responseType: 'agent_create_result',
+ code: refusal['error'] as String,
+ detail: refusal['detail'] as String?,
+ payload: refusal,
+ );
+ }
+ return {
+ 'agent': cloudFrame(
+ id: 'cloud_9',
+ engine: payload['engine'] as String,
+ state: 'working',
+ messages: 1,
+ ),
+ };
+ }
+ if (type == 'engines_probe') return {'engines': []};
+ if (type == 'dsh_list') return {'dsh': []};
+ return super.request(type, payload: payload, timeout: timeout);
+ }
+}
diff --git a/desktop/test/cloud_chat_pane_capture_test.dart b/desktop/test/cloud_chat_pane_capture_test.dart
new file mode 100644
index 000000000..73e8745ee
--- /dev/null
+++ b/desktop/test/cloud_chat_pane_capture_test.dart
@@ -0,0 +1,181 @@
+// The cloud agents' design image (docs/design/images/cloud-chat-pane.png): a
+// Fo harness's chat pane beside a terminal pane, so its header can be held to
+// every pane's. Rendered only when HARNESS_CLOUD_CAPTURE_DIR names a folder;
+// otherwise it checks the same scene renders.
+
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/terminal/terminal_binary.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/widgets/cloud_chat_pane.dart';
+import 'package:harness/widgets/new_harness_form.dart';
+
+import 'cloud_agents_test.dart'
+ show CloudConnection, CreateConnection, cloudFrame;
+import 'swarm_screen_test.dart' show mount, terminal;
+import 'swarm_state_test.dart' show createApp;
+import 'support/real_fonts.dart';
+
+void main() {
+ final capture = Platform.environment['HARNESS_CLOUD_CAPTURE_DIR'];
+
+ setUpAll(() async {
+ if (capture != null && Platform.isMacOS) {
+ for (final (family, path) in [
+ ('SF Mono', '/System/Library/Fonts/SFNSMono.ttf'),
+ ('.AppleSystemUIFontMonospaced', '/System/Library/Fonts/SFNSMono.ttf'),
+ ('Menlo', '/System/Library/Fonts/Menlo.ttc'),
+ ('Apple Symbols', '/System/Library/Fonts/Apple Symbols.ttf'),
+ ('.AppleSystemUIFont', '/System/Library/Fonts/SFNS.ttf'),
+ ('Roboto', '/System/Library/Fonts/Supplemental/Arial.ttf'),
+ ]) {
+ final bytes = ByteData.sublistView(await File(path).readAsBytes());
+ await (FontLoader(family)..addFont(Future.value(bytes))).load();
+ }
+ } else {
+ await loadRealFonts();
+ }
+ await (FontLoader('packages/lucide_icons_flutter/Lucide400')..addFont(
+ rootBundle.load(
+ 'packages/lucide_icons_flutter/assets/build_font/LucideVariable-w400.ttf',
+ ),
+ ))
+ .load();
+ });
+
+ testWidgets(
+ 'a Fo harness beside a terminal: the same header, a conversation in place of a terminal',
+ (tester) async {
+ final connection = CloudConnection();
+ final app = createApp(
+ connectionForTest: (_) => connection,
+ connected: true,
+ );
+ addTearDown(app.dispose);
+ app.adoptSessionForTest(terminal('a0', <TerminalBinaryFrame>[]));
+ await app.handleEventForTest('m', {
+ 'type': 'agent_synced',
+ 'payload': {'agent': cloudFrame()},
+ });
+ await app.handleEventForTest('m', {
+ 'type': 'commander_question',
+ 'agentId': 'cloud_1',
+ 'payload': {
+ 'requestId': 'cloud_q_1',
+ 'questions': [
+ {
+ 'key': 'answer',
+ 'q': 'Which one?',
+ 'options': ['9:30', '11:00', 'neither'],
+ 'multi': false,
+ 'canText': true,
+ },
+ ],
+ },
+ });
+ await app.addAgentToSwarm('m', 'cloud_1');
+ await mount(tester, app);
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(find.byType(CloudChatPane), findsOneWidget);
+ if (capture == null) return;
+ await tester.runAsync(() async {
+ final view = tester.binding.renderViews.first;
+ final image = await (view.debugLayer! as OffsetLayer).toImage(
+ Offset.zero & view.size,
+ pixelRatio: 2,
+ );
+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
+ await File('$capture/cloud-chat-pane.png')
+ .writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ });
+ },
+ );
+
+ testWidgets(
+ 'New Harness with Devin Cloud: its cloud for a computer, a GitHub repository, an ACU limit',
+ (tester) async {
+ final app = createApp(
+ connectionForTest: (_) => CreateConnection(),
+ connected: true,
+ );
+ addTearDown(app.dispose);
+ // A folder this computer already works in, whose remote is on GitHub.
+ await app.handleEventForTest('m', {
+ 'type': 'agent_synced',
+ 'payload': {
+ 'agent': {
+ 'id': 'a-api',
+ 'name': 'api',
+ 'engine': 'claude',
+ 'terminal': {
+ 'available': true,
+ 'runtimes': [
+ {'backend': 'tmux', 'paneId': '%1'},
+ ],
+ },
+ 'project': {
+ 'kind': 'git',
+ 'name': 'api',
+ 'cwd': '/work/api',
+ 'root': '/work/api',
+ 'remote': 'https://github.com/acme/api',
+ 'branch': 'main',
+ },
+ },
+ },
+ });
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'devin-cloud',
+ folder: '/work/api',
+ task: 'fix the flaky login test',
+ );
+ addTearDown(box.dispose);
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(820, 360);
+ addTearDown(tester.view.resetPhysicalSize);
+ addTearDown(tester.view.resetDevicePixelRatio);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: ThemeData.dark(),
+ debugShowCheckedModeBanner: false,
+ home: Scaffold(
+ body: NewHarnessForm(
+ controller: box,
+ desktop: true,
+ onClose: () {},
+ onCreated: () {},
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ // No caret or selection handle in the picture.
+ FocusManager.instance.primaryFocus?.unfocus();
+ await tester.pumpAndSettle();
+ expect(box.cloudRepository, 'https://github.com/acme/api');
+ expect(find.text("Devin's cloud"), findsOneWidget);
+ expect(find.text('acme/api'), findsOneWidget);
+ if (capture != null)
+ await tester.runAsync(() async {
+ final view = tester.binding.renderViews.first;
+ final image = await (view.debugLayer! as OffsetLayer).toImage(
+ Offset.zero & view.size,
+ pixelRatio: 2,
+ );
+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
+ await File('$capture/cloud-new-harness.png')
+ .writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ });
+ expect(find.text('Up to 5 ACUs'), findsOneWidget);
+ },
+ );
+}
diff --git a/desktop/test/launch_preferences_test.dart b/desktop/test/launch_preferences_test.dart
index 5bdfe29c5..194008be8 100644
--- a/desktop/test/launch_preferences_test.dart
+++ b/desktop/test/launch_preferences_test.dart
@@ -591,7 +591,11 @@ void main() {
'grok',
'opencode',
];
- final engines = allEngines.map((engine) => engine.id).toSet();
+ // Every agent, the cloud agents among them (Devin Cloud beside Devin).
+ final engines = {
+ ...allEngines.map((engine) => engine.id),
+ ...cloudAgents.map((agent) => agent.id),
+ };
final initial = box.options.map((option) => option.id).toList();
expect(initial.take(leading.length), leading);
expect(initial.take(engines.length).toSet(), engines);
diff --git a/docs/design/2026-10-11-cloud-agents.md b/docs/design/2026-10-11-cloud-agents.md
index 9088ad48c..57a1c1108 100644
--- a/docs/design/2026-10-11-cloud-agents.md
+++ b/docs/design/2026-10-11-cloud-agents.md
@@ -35,6 +35,11 @@ started from New Harness. They are not a second product beside the panes.
Fo's cloud
```
+ As built (rendered by `desktop/test/cloud_chat_pane_capture_test.dart` with
+ `HARNESS_CLOUD_CAPTURE_DIR`), beside a terminal pane:
+
+ ![A Fo harness's chat pane beside a terminal pane, rendered with synthetic data](images/cloud-chat-pane.png)
+
- **Devin and Devin Cloud** are two agents, as Cognition presents them; Cursor and Cursor Cloud the same.
Devin is today's terminal pane on a computer. Devin Cloud asks for a GitHub repository Devin can reach
rather than a folder (a local folder carries its GitHub remote over; its tooltip says uncommitted
@@ -49,6 +54,10 @@ started from New Harness. They are not a second product beside the panes.
Up to 5 ACUs New Harness
```
+ As built:
+
+ ![New Harness with Devin Cloud: its cloud for a computer, a GitHub repository, an ACU limit](images/cloud-new-harness.png)
+
Its chat pane's footer carries the session's branch and pull request like any pane's:
```
diff --git a/docs/design/images/cloud-chat-pane.png b/docs/design/images/cloud-chat-pane.png
new file mode 100644
index 000000000..9cb1eb80b
Binary files /dev/null and b/docs/design/images/cloud-chat-pane.png differ
diff --git a/docs/design/images/cloud-new-harness.png b/docs/design/images/cloud-new-harness.png
new file mode 100644
index 000000000..7f3796b75
Binary files /dev/null and b/docs/design/images/cloud-new-harness.png differ
diff --git a/mobile/lib/e2ee/envelope.dart b/mobile/lib/e2ee/envelope.dart
index 2c7a96ea1..0a648a630 100644
--- a/mobile/lib/e2ee/envelope.dart
+++ b/mobile/lib/e2ee/envelope.dart
@@ -53,6 +53,10 @@ const Set<String> encryptedDownTypes = {
'memory_snapshot',
'memory_about_put',
'memory_deliver',
+ // Cloud agents (CLI services/cloud.ts): a cloud harness's conversation and the person's words for it.
+ 'cloud_transcript',
+ 'cloud_send',
+ 'cloud_agents',
// The trust-group roster swap (`viewer/group_sync.dart`): the keys every member trusts.
'group_sync',
'codex_profiles_list',