The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Requests leave the socket's switch for services in the core's process: models, usage, the monitor, the project readers (#851)
Dee1d8087bfc57f
diff --git a/cli/e2e/compat.e2e.ts b/cli/e2e/compat.e2e.tsindex 894cc2e51..e3d2f2fe0 100644--- a/cli/e2e/compat.e2e.ts+++ b/cli/e2e/compat.e2e.ts@@ -215,12 +215,14 @@ async function scenario(d: IsolatedDaemon): Promise<Answers> {await ask(`agent_recent ${engine}`, 'agent_recent', { agentId: agent[engine] })await ask(`terminal_info ${engine}`, 'terminal_info', { agentId: agent[engine] })await ask(`agent_read_file ${engine}`, 'agent_read_file', { agentId: agent[engine], path: 'README.md' })+ await ask(`git_pull_request ${engine}`, 'git_pull_request', { agentId: agent[engine] })}await ask('models_list', 'models_list')await ask('git_project_info', 'git_project_info', { path: cwd('claude') })await ask('fs_list_dir', 'fs_list_dir', { path: d.projectsDir })await ask('project_preview', 'project_preview', { path: cwd('claude') })await ask('codex_profiles_list', 'codex_profiles_list')+ await ask('api_connections', 'api_connections', { action: 'list' })await ask('claude_login_status', 'claude_login_status')await ask('agents_cleanup_preview', 'agents_cleanup_preview')await ask('harness_devices_list', 'harness_devices_list')@@ -233,7 +235,9 @@ async function scenario(d: IsolatedDaemon): Promise<Answers> {const malformed = ['session_get', 'sessions_list', 'agent_recent', 'terminal_info', 'agent_read_file', 'agent_update', 'agent_fork','agent_restart', 'agent_delete', 'agent_resume', 'agent_purge', 'agent_retarget', 'agent_close', 'cancel', 'question_response','git_project_info', 'fs_list_dir', 'project_preview', 'session_tail', 'dsh_remove', 'dsh_install', 'dsh_update', 'theme_set',- 'agent_create', 'agent_create_status', 'agent_handoff_prepare', 'agent_worktree_delete', 'message']+ 'agent_create', 'agent_create_status', 'agent_handoff_prepare', 'agent_worktree_delete', 'message',+ // Moved out of the socket's switch into services (docs/design/2026-10-06-core-boundary-next.md, step 4).+ 'git_pull_request', 'codex_profile_link', 'api_connections']for (const type of malformed) {// `cancel` and `message` are fire-and-forget: no build answers them, so waiting a minute shows nothing more.const ms = type === 'cancel' || type === 'message' ? 5_000 : 60_000diff --git a/cli/e2e/services.e2e.ts b/cli/e2e/services.e2e.tsindex b5469258c..b0c19f82a 100644--- a/cli/e2e/services.e2e.ts+++ b/cli/e2e/services.e2e.ts@@ -116,10 +116,10 @@ describe('a failing service never takes the core down', () => {})it('with every service in the core failing to start, the core starts, runs an agent through turns and a restart, and says each service is off', async () => {- daemon = await IsolatedDaemon.create({ env: { HARNESSD_TEST_FAULTS: 'search,viewers,models,workspaces,store', ...IN_THE_CORE } })+ daemon = await IsolatedDaemon.create({ env: { HARNESSD_TEST_FAULTS: 'search,viewers,models,workspaces,store,usage,monitor,projects', ...IN_THE_CORE } })onTestFailed(() => { console.log(`---- daemon log\n${daemon?.log().split('\n').slice(-80).join('\n')}`) })await daemon.start()- for (const service of ['search', 'viewers', 'models', 'workspaces', 'store']) {+ for (const service of ['search', 'viewers', 'models', 'workspaces', 'store', 'usage', 'monitor', 'projects']) {expect(daemon.log()).toContain(`[services] ${service} did not start · injected fault: ${service} · the core runs without it`)}const client = await LocalClient.connect(daemon)@@ -130,9 +130,20 @@ describe('a failing service never takes the core down', () => {for (const type of ['dsh_list', 'dsh_install', 'dsh_update', 'dsh_remove']) {expect(await client.request(type, { id: 'acme/thing' }), type).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'store', retryable: false })}- for (const type of ['grid_models_list', 'models_list', 'grid_fleet_models_list', 'grid_fleet_model_download', 'grid_fleet_model_start', 'grid_fleet_model_stop']) {+ for (const type of ['grid_models_list', 'models_list', 'grid_fleet_models_list', 'grid_fleet_model_download', 'grid_fleet_model_start', 'grid_fleet_model_stop',+ 'api_connections', 'codex_profiles_list', 'codex_profile_link']) {expect(await client.request(type, { modelId: 'org/Model-GGUF' }), type).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'models', retryable: false })}+ // The services that came out of the socket's switch (docs/design/2026-10-06-core-boundary-next.md, step 4).+ // usage_read is asked only here, with its service off: on, it reads the vendors' credentials.+ expect(await client.request('usage_read', {})).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'usage', retryable: false })+ expect(await client.request('machine_resources', {})).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'monitor', retryable: false })+ for (const type of ['git_pull_request', 'git_project_info', 'project_preview', 'fs_list_dir', 'agent_read_file']) {+ expect(await client.request(type, { agentId, path: daemon.projectsDir }), type).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'projects', retryable: false })+ }+ // With the monitor off, the Monitor's list is still the list: its rows, without readings.+ const monitored = (await client.request('agents_list', { monitor: true })).agents.find((agent: Record<string, any>) => agent.id === agentId)+ expect(monitored.monitor).toMatchObject({ rssBytes: null, cpu: null, processes: [] })// The Model Manager's grid commands are still the socket's, and so is their handshake: models being// off does not tell the Grid harness to update Harness.expect(await client.request('grid_fleet_capabilities', {})).toMatchObject({ protocol: 1, thinkingControl: true })@@ -225,6 +236,27 @@ describe('a failing service never takes the core down', () => {client.close()})+ it('the monitor\'s readings failing on every call leave the list its rows, then switch the monitor off; the core runs on', async () => {+ daemon = await IsolatedDaemon.create({ env: { HARNESSD_TEST_FAULTS: 'monitor.resources,projects.fs_list_dir' } })+ onTestFailed(() => { console.log(`---- daemon log\n${daemon?.log().split('\n').slice(-80).join('\n')}`) })+ await daemon.start()+ const client = await LocalClient.connect(daemon)+ const agentId = await boundAgent(daemon, client, 'monitor-failing')+ // Each failed sample is a row without readings, as a failed `ps` always was; five in a minute switch it off.+ for (let i = 0; i < 6; i++) {+ const listed = (await client.request('agents_list', { monitor: true })).agents.find((agent: Record<string, any>) => agent.id === agentId)+ expect(listed.monitor).toMatchObject({ rssBytes: null, cpu: null, processes: [] })+ }+ expect(daemon.log()).toContain('[services] monitor switched off after 5 failures')+ expect(await client.request('machine_resources', {})).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'monitor' })+ // One of the project readers failing leaves the others their own answers.+ expect(await client.request('fs_list_dir', {})).toMatchObject({ error: 'SERVICE_FAILED', service: 'projects' })+ expect(await client.request('project_preview', { path: '/no/such/folder' })).not.toHaveProperty('service')+ await turn(client, agentId, 'with the monitor off')+ expect(daemon.coresStarted()).toBe(1)+ client.close()+ })+it('models answers from its own service; one of its requests failing leaves its others and the core alone', async () => {daemon = await IsolatedDaemon.create({ env: { HARNESSD_TEST_FAULTS: 'models.grid_models_list' } })onTestFailed(() => { console.log(`---- daemon log\n${daemon?.log().split('\n').slice(-80).join('\n')}`) })diff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.tsindex 0bf3c12dc..c03d8a975 100644--- a/cli/src/architecture.spec.ts+++ b/cli/src/architecture.spec.ts@@ -66,7 +66,7 @@ function runForegroundLines(): number {* those moves, and runForeground gained 28.*/const RUN_FOREGROUND_BUDGET = 2_600-const BACKEND_SOCKET_BUDGET = 2_320+const BACKEND_SOCKET_BUDGET = 2_180/** Exceptions, each with its reason. Keep this short. */const SERVICE_MAY_IMPORT: Record<string, string> = {diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.tsindex aa3203e15..f27a528fb 100644--- a/cli/src/backendSocket.spec.ts+++ b/cli/src/backendSocket.spec.ts@@ -10,9 +10,14 @@ import { AGENT_OPENED_THROTTLE_MS } from './core/agents/update.js'import { deviceAgentListItem, deviceAgentRow } from './core/agents/list.js'import { grokHistoryPage } from './core/transcripts/history.js'import { bindAgentList, bindAgentUpdate, bindCancelRequest, bindLaunchRequests, bindCloseRequests, bindMessageRequest, bindPurgeRequest, bindQuestionResponse, bindStopRequest, bindTerminalRequests } from './testing/socketCore.js'-import { emptyPorts, MODELS_FALLBACKS } from './core/api.js'+import { emptyPorts, MODELS_FALLBACKS, MONITOR_FALLBACKS } from './core/api.js'import { createServiceHost, ServiceUnavailableError } from './core/serviceHost.js'import { MODELS_REQUESTS, startModels } from './services/models.js'+import { USAGE_REQUESTS, startUsage } from './services/usage.js'+import { MONITOR_REQUESTS, startMonitor, type MonitorDeps } from './services/monitor.js'+import { PROJECTS_REQUESTS, startProjects } from './services/projects.js'+import { createHarnessResourcesReader } from './lib/harnessResources.js'+import { createHarnessStorageReader } from './lib/harnessTelemetry.js'import { fakeCore } from './testing/fakeCore.js'import { AuthSessionError, type AuthSessionManager } from './lib/authSession.js'import { WS_IDLE_DEADLINE_MS as IDLE_DEADLINE_MS } from './lib/wsLiveness.js'@@ -595,6 +600,34 @@ function serveModels(socket: BackendSocket, over: Parameters<typeof fakeCore>[0]return host}+/** The machine monitor (services/monitor.ts) in `host`, reading this machine as the daemon does unless a+ * spec says otherwise; its totals through the module, so a spy on it is what answers. */+function serveMonitor(host: ReturnType<typeof createServiceHost>, over: Partial<MonitorDeps> = {}) {+ host.start('monitor', (core, ports) => startMonitor(core, ports, {+ machine: () => machineResources.readMachineResources(),+ resources: createHarnessResourcesReader(() => registry.advertised()),+ storage: createHarnessStorageReader(),+ ...over,+ }), fakeCore(), MONITOR_FALLBACKS, MONITOR_REQUESTS)+ return host+}++/** The project and folder readers (services/projects.ts) answering `socket`, over the registry as the+ * daemon's core API reads it, so a spec's spies on the registry are what they see. */+function serveProjects(socket: BackendSocket) {+ return serveOn(socket, (host) => host.serve('projects', startProjects, fakeCore({+ agents: { live: () => registry.list(), resolve: (id: string) => registry.resolve(id) },+ }), PROJECTS_REQUESTS))+}++/** A socket whose service requests go to the services `serve` starts in a host of their own. */+function serveOn(socket: BackendSocket, serve: (host: ReturnType<typeof createServiceHost>) => void) {+ const host = createServiceHost(emptyPorts(), { log: () => {} })+ serve(host)+ socket.serviceRouter = (type, payload, asker, reply) => host.route(type, payload, asker, reply)+ return host+}+/** The session a requester holds whenever its sealed request was opened. Replies of a sealed type go back* sealed to it; this stub seals them transparently, so a test reads the reply as the client does, opened. */function withSession(socket: BackendSocket, connId: string): void {@@ -1196,7 +1229,8 @@ describe('BackendSocket outbound queue', () => {it('answers usage_read with this machine\'s own readings, wrapped for the requester', async () => {// What goes back names what the person spends and on whose account, so it must leave encrypted.- // The reader is the socket's own field: this never touches a real home, Keychain or network.+ // The usage service answers it (services/usage.ts), with a reader that never touches a real home,+ // Keychain or network.const socket = new BackendSocket('token')const readings = [{@@ -1207,7 +1241,7 @@ describe('BackendSocket outbound queue', () => {body: { seven_day: { utilization: 42 } },},]- socket.accountUsageReader = async () => readings+ serveOn(socket, (host) => host.serve('usage', (core) => startUsage(core, { read: async () => readings }), fakeCore(), USAGE_REQUESTS))socket.connect()const ws = wsMock.instances[0]ws.open()@@ -1235,6 +1269,7 @@ describe('BackendSocket outbound queue', () => {const preview = { path: '/remote/workspace', readme: 'Private project README', branch: 'main', files: ['README.md'], contributors: [] }const read = vi.spyOn(projectPreview, 'projectPreview').mockResolvedValue(preview)const socket = new BackendSocket('token')+ serveProjects(socket)socket.connect()const ws = wsMock.instances[0]ws.open()@@ -1261,6 +1296,7 @@ describe('BackendSocket outbound queue', () => {const preview = { isGit: true, root: '/remote/workspace', branch: 'main', branches: [{ ref: 'refs/heads/private-branch', name: 'private-branch', remote: false }] }const read = vi.spyOn(gitProject, 'readGitProject').mockResolvedValue(preview)const socket = new BackendSocket('token')+ serveProjects(socket)socket.connect()const ws = wsMock.instances[0]ws.open()@@ -1289,6 +1325,7 @@ describe('BackendSocket outbound queue', () => {vi.spyOn(registry, 'resolve').mockReturnValue({ cwd: '/remote/workspace' } as RegisteredSession)const read = vi.spyOn(gitPullRequest, 'readGitPullRequest').mockResolvedValue(preview)const socket = new BackendSocket('token')+ serveProjects(socket)socket.connect()const ws = wsMock.instances[0]ws.open()@@ -1317,7 +1354,7 @@ describe('BackendSocket outbound queue', () => {}, history: { branches: [{ cwd: '/private/worktree', remote: null, branch: 'private-fix', at: '2026-09-27' }], pullRequests: [], truncated: false }, lookups: [], nextOffset: null }vi.spyOn(registry, 'resolve').mockReturnValue({ cwd: '/remote/workspace' } as RegisteredSession)vi.spyOn(sessionGitPullRequest, 'readSessionGitPullRequest').mockResolvedValue(history)- const socket = new BackendSocket('token'); socket.connect()+ const socket = new BackendSocket('token'); serveProjects(socket); socket.connect()const ws = wsMock.instances[0]; ws.open()vi.spyOn(socket.e2ee, 'unwrapDown').mockReturnValue({ type: 'git_pull_request', payload: {requestId: 'history-1', agentId: 'agent1', history: true,@@ -1334,6 +1371,7 @@ describe('BackendSocket outbound queue', () => {it('returns a correlated Git error when discovery rejects or the path is malformed', async () => {const read = vi.spyOn(gitProject, 'readGitProject').mockRejectedValue(new Error('unavailable'))const socket = new BackendSocket('token')+ serveProjects(socket)socket.connect()const ws = wsMock.instances[0]ws.open()@@ -1358,6 +1396,7 @@ describe('BackendSocket outbound queue', () => {revision: 'a'.repeat(64), contentBase64: 'AQID' }const read = vi.spyOn(mediaPreview, 'readMediaPreviewChunk').mockResolvedValue(media)const socket = new BackendSocket('token')+ serveProjects(socket)socket.connect()const ws = wsMock.instances[0]ws.open()@@ -1566,7 +1605,7 @@ describe('BackendSocket outbound queue', () => {() => new Promise(resolve => { finish = resolve }),)const socket = new BackendSocket('token')- serveModels(socket)+ serveMonitor(serveModels(socket))const frames: Array<Record<string, unknown>> = []socket.registerLocalClient('local:stats', {sendFrame: frame => { frames.push(frame); return true }, sendBinary: () => true,@@ -1596,6 +1635,7 @@ describe('BackendSocket outbound queue', () => {const reading = { cpuPercent: 18, memoryUsedBytes: 10, memoryTotalBytes: 32 }vi.spyOn(machineResources, 'readMachineResources').mockResolvedValue(reading)const socket = new BackendSocket('token')+ serveOn(socket, (host) => serveMonitor(host))socket.connect()const ws = wsMock.instances[0]ws.open()@@ -1619,8 +1659,7 @@ describe('BackendSocket outbound queue', () => {const system = vi.spyOn(machineResources, 'readMachineResources')const socket = new BackendSocket('token')let finish!: (value: { sampledAt: string; agents: [] }) => void- socket.harnessResourcesReader = vi.fn(() => new Promise<{ sampledAt: string; agents: [] }>(resolve => { finish = resolve }))- serveModels(socket)+ serveMonitor(serveModels(socket), { resources: vi.fn(() => new Promise<{ sampledAt: string; agents: [] }>(resolve => { finish = resolve })) })const frames: Array<Record<string, unknown>> = []socket.registerLocalClient('local:monitor', {sendFrame: frame => { frames.push(frame); return true }, sendBinary: () => true,@@ -2593,8 +2632,8 @@ describe('agent_restart RPC', () => {vi.spyOn(registry, 'advertised').mockReturnValue([BASE_SESSION])vi.spyOn(registry, 'list').mockReturnValue([BASE_SESSION])vi.spyOn(stoppedAgents, 'available').mockReturnValue([{ ...BASE_SESSION, agentId: 'stopped' }])- socket.harnessResourcesReader = vi.fn(async () => ({ sampledAt: new Date().toISOString(), agents: [{ agentId: 'agent-1', memoryBytes: 123, cpuPercent: 2, processCount: 1 }] }))- bindAgentList(socket, { monitorActivityProvider: sessionId => sessionId === BASE_SESSION.sessionId ? 'needsInput' : 'idle' })+ const resources = vi.fn(async () => ({ sampledAt: new Date().toISOString(), agents: [{ agentId: 'agent-1', memoryBytes: 123, cpuPercent: 2, processCount: 1 }] }))+ bindAgentList(socket, { harnessResourcesReader: resources, monitorActivityProvider: sessionId => sessionId === BASE_SESSION.sessionId ? 'needsInput' : 'idle' })for (const [requestId, monitor] of [['plain', false], ['monitor', true]] as const) {socket.handleLocalFrame('local:restart', { type: 'agents_list', payload: { requestId, monitor, includeStopped: true } })}@@ -2603,7 +2642,7 @@ describe('agent_restart RPC', () => {expect(response('plain').every((agent: any) => agent.monitor === undefined)).toBe(true)expect(response('monitor').find((a: any) => a.id === 'agent-1').monitor).toMatchObject({ activity: 'needsInput', activityKnown: true, rssBytes: 123, cpu: 2, pid: BASE_SESSION.processIdentity?.pid ?? null })expect(response('monitor').find((a: any) => a.id === 'stopped').monitor).toMatchObject({ rssBytes: 0, cpu: 0, pid: null })- expect(socket.harnessResourcesReader).toHaveBeenCalledOnce()+ expect(resources).toHaveBeenCalledOnce()await socket.unregisterLocalClient('local:restart'); await socket.stop()})@@ -3178,8 +3217,8 @@ describe('the connect burst with no network', () => {const socket = new BackendSocket('token')bindAgentList(socket)socket.deriveGridName = () => new Promise<null>(() => {}) // a grid read that never lands- socket.accountUsageReader = () => new Promise(() => {}) // a vendor that never answers- serveModels(socket)+ // A vendor that never answers, asked of the usage service beside models.+ serveModels(socket).serve('usage', (core) => startUsage(core, { read: () => new Promise(() => {}) }), fakeCore(), USAGE_REQUESTS)const frames: Array<Record<string, unknown>> = []socket.registerLocalClient('local:burst', { sendFrame: (frame) => { frames.push(frame); return true }, sendBinary: () => true })diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex ea7d754f1..923419f8f 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -2,7 +2,6 @@ import type { PurgeAgentService } from './lib/purgeAgentService.js'import type { Asker, PromptScopes } from './core/api.js'import { ServiceUnavailableError } from './core/serviceHost.js'import type { ActivityFrame } from './lib/turnActivity.js'-import { readSessionGitPullRequest } from './lib/sessionGitPullRequest.js'import { MonitorCompletions } from './lib/harnessMonitor.js'import type { HarnessShareOwner } from './sharing/owner.js'import { SHARE_REQUEST_TYPES } from './sharing/protocol.js'@@ -36,12 +35,10 @@ import { registry, projectDisplayName, type RegisteredSession } from './lib/regiimport type { CloseAgentService } from './lib/closeAgentService.js'import { isHiddenBuiltin } from './dsh/builtins.js'import { ENGINES, type AgentEngine } from './engines/types.js'-import { listDir } from './lib/fsBrowse.js'-import { linkCodexProfile, listCodexProfiles } from './lib/codexProfiles.js'import { gridCliPresence } from './lib/gridExec.js'import { GridFleetRpc, GRID_FLEET_PROTOCOL, GRID_FLEET_MAX_TIMEOUT_MS, parseGridFleetRequest } from './lib/gridFleetRpc.js'-import { ApiConnectionError, ApiConnections, apiConnectionsRequest } from './lib/apiConnections.js'-import { apiModelsRequest, rememberSavedApis, resolveApiTarget } from './lib/apiModels.js'+import { ApiConnectionError, ApiConnections } from './lib/apiConnections.js'+import { resolveApiTarget } from './lib/apiModels.js'import { isApiLaunch, parseGridLaunchOverride, type GridLaunchOverride } from './lib/gridLaunch.js'import { listAllGridModels, onGridModelsChanged, retargetPrewarm } from './lib/gridModels.js'import { gridModelsPayload } from './lib/gridModelsPayload.js'@@ -49,15 +46,9 @@ import { resolveGridTarget } from './lib/gridTarget.js'import type { GridAttachResult } from './lib/gridAttach.js'import { deriveHarnessGridName } from './lib/gridDerive.js'import { supportsFirstPrompt } from './lib/engineLaunch.js'-import { readAccountUsage, type AccountUsageReading } from './lib/accountUsage.js'import { probeEngines } from './lib/engineProbe.js'-import { readMachineResources } from './lib/machineResources.js'import { harnessDevicesRequest, type HarnessDevicesService } from './lib/harnessDevices.js'-import { createHarnessResourcesReader } from './lib/harnessResources.js'-import { createHarnessStorageReader } from './lib/harnessTelemetry.js'import { engineInstallRecipe } from './lib/engineInstall.js'-import { projectPreview } from './lib/projectPreview.js'-import { readGitProject } from './lib/gitProject.js'import { agentFrame, type AgentDshContext, type AgentFrame } from './lib/agentFrame.js'import { agentTokenUsage } from './lib/agentTokenUsage.js'import { listInstalledDsh } from './dsh/installed.js'@@ -74,7 +65,6 @@ import { Address, Id, OperationId, Receipt, TeamError, type MemberRuntime } fromimport { shellQuote } from './orchestrator/prompts.js'import type { SessionInputDelivery } from './lib/sessionInput.js'import { terminalHandoffRequest } from './lib/terminalHandoff.js'-import { MediaPreviewError, readMediaPreviewChunk } from './lib/mediaPreview.js'import { ViewerForwarder } from './lib/viewerForwarder.js'import { InteractiveViewers } from './lib/interactiveViewer.js'import { OwnerCommands, OWNER_COMMAND_TYPES } from './lib/ownerCommands.js'@@ -534,11 +524,6 @@ export class BackendSocket {/** How each agent's last turn ended, from the turn frames this socket sends: the monitor's activity* once a turn is over (`agents_list`, core/agents/list.ts). */readonly monitorCompletions = new MonitorCompletions()- /** Answers `usage_read` — this machine's own agent-account usage (lib/accountUsage.ts). A field- * rather than a direct call so a spec answers it without a real home, Keychain or network. */- accountUsageReader: () => Promise<AccountUsageReading[]> = readAccountUsage- harnessResourcesReader = createHarnessResourcesReader(() => registry.advertised())- harnessStorageReader = createHarnessStorageReader()/** The windows on this computer that draw row state (`grid_models_list` with `rowState: true`) and so* are pushed labels as `unavailable` rather than in the node text. Kept here, by connection: the* models service answers the list, and a request reaches it without its connection. */@@ -1757,17 +1742,6 @@ export class BackendSocket {return}- if (type === 'api_connections') {- if (!local && this.e2ee.sessionRole(connId) !== 'web') { reply(type, requestId, { error: 'OWNER_REQUIRED' }); return }- if (payload.action === 'models') {- reply(type, requestId, await apiModelsRequest(this.apiConnections, payload))- return- }- reply(type, requestId, apiConnectionsRequest(this.apiConnections, payload))- if (payload.action === 'save') rememberSavedApis(this.apiConnections)- return- }-// A paired owner can run the machine's orchestrator; observers and device sessions cannot.// Both requests and replies are encrypted, including project artifacts.if (OWNER_COMMAND_TYPES.has(type)) {@@ -1840,18 +1814,6 @@ export class BackendSocket {try {switch (type) {- case 'machine_resources':- // Sampling CPU must not hold up typing or other machine requests.- void (payload.harnesses === true- ? this.harnessResourcesReader().then(async harnesses => {- if (payload.storage !== true) return { harnesses }- const storage = await this.harnessStorageReader(registry.advertised())- return { harnesses: { ...harnesses, agents: harnesses.agents.map(row => ({ ...row, ...storage.get(row.agentId) })) } }- })- : readMachineResources())- .then(resources => reply(type, requestId, { ...resources }))- .catch(() => reply(type, requestId, { error: 'UNAVAILABLE' }))- return// The Model Manager's grid commands stay here while the rest of models answers from its service// (services/models.ts). A command is a job of the connection that started it, keyed by that// connection, and a cancel stops only that connection's own (lib/gridFleetRpc.ts); a request the@@ -2122,95 +2084,6 @@ export class BackendSocket {else reply(type, requestId, { error: 'UNSUPPORTED' })return- case 'git_pull_request': {- const id = payload.agentId- const agent = typeof id === 'string' ? registry.resolve(id) : undefined- if (!agent?.cwd) { reply(type, requestId, { status: 'unavailable' }); return }- const requested = payload.context- if (requested !== undefined && (!requested || typeof requested !== 'object'- || typeof (requested as Record<string, unknown>).cwd !== 'string'- || typeof (requested as Record<string, unknown>).branch !== 'string'- || (requested as Record<string, unknown>).remote !== null && typeof (requested as Record<string, unknown>).remote !== 'string')) {- reply(type, requestId, { status: 'unavailable' }); return- }- void readSessionGitPullRequest(agent, {- expected: requested as import('./lib/sessionGitPullRequest.js').ExpectedGitContext | undefined,- history: payload.history === true, offset: typeof payload.offset === 'number' ? payload.offset : undefined,- }).then(result => reply(type, requestId, result))- .catch(() => reply(type, requestId, { status: 'unavailable' }))- return- }-- case 'git_project_info': {- const path = typeof payload.path === 'string' ? payload.path : ''- // Same root set as project_preview below: the browsable home, widened by the workspaces- // agents are running in, so a repo outside both is not somewhere this daemon runs git.- void readGitProject(path, { refresh: payload.refresh === true,- knownRoots: registry.list().flatMap(agent => agent.cwd ? [agent.cwd] : []) })- .then(result => reply(type, requestId, result))- .catch(() => reply(type, requestId, { error: 'UNAVAILABLE' }))- return- }-- case 'project_preview': {- const path = typeof payload.path === 'string' ? payload.path : ''- // Preview work is detached so typing and other RPCs stay responsive.- void projectPreview(path, registry.list().flatMap(agent => agent.cwd ? [agent.cwd] : []))- .then(result => reply(type, requestId, result))- .catch(() => reply(type, requestId, { error: 'UNAVAILABLE' }))- return- }-- case 'fs_list_dir': {- // One-level remote directory listing for the New Agent folder browser.- const path = typeof payload.path === 'string' ? payload.path : ''- const result = listDir(path)- if ('error' in result) { reply(type, requestId, { error: result.error }); return }- reply(type, requestId, { ...result })- return- }-- case 'codex_profiles_list': {- // Which CODEX_HOME folders THIS machine can offer — answered here, on the machine in- // question, for the same reason `engines_probe` is: a Codex profile is a folder on disk,- // and a folder on a Mac means nothing on the Docker rig it was asked about instead.- const observed = Array.isArray(payload.observedPaths)- ? payload.observedPaths.filter((p): p is string => typeof p === 'string')- : []- try {- reply(type, requestId, { profiles: listCodexProfiles(observed) })- } catch {- reply(type, requestId, { error: 'CODEX_PROFILES_FAILED' })- }- return- }-- case 'codex_profile_link': {- const path = typeof payload.path === 'string' ? payload.path : ''- const result = linkCodexProfile(path)- if ('error' in result) { reply(type, requestId, { error: result.error }); return }- reply(type, requestId, { profile: result })- return- }-- case 'agent_read_file': {- // Media previews, in bounded binary chunks. The text mode this RPC also used to serve was- // read by nothing — every client has always asked with `media: true` — so it is gone rather- // than carrying a second, laxer file reader (lib/mediaPreview.ts).- const projectId = payload.agentId as string | undefined- const path = payload.path as string | undefined- if (!projectId || !path) { reply(type, requestId, { error: 'MISSING_AGENT_OR_PATH' }); return }- if (payload.media !== true) { reply(type, requestId, { error: 'UNSUPPORTED', detail: 'agent_read_file serves media previews only' }); return }- const s = registry.resolve(projectId)- if (!s?.cwd) { reply(type, requestId, { error: 'AGENT_NOT_FOUND' }); return }- try {- reply(type, requestId, { ...await readMediaPreviewChunk(s.cwd, path, payload.offset, payload.revision) })- } catch (error) {- reply(type, requestId, { error: error instanceof MediaPreviewError ? error.message : 'MEDIA_READ_FAILED' })- }- return- }-case 'claude_login_status':// Legacy RPC name; report the selected agent's actual engine when one was supplied.{@@ -2233,20 +2106,6 @@ export class BackendSocket {this.questionProvider?.(payload, answer)return- // This machine's Claude/Codex rate limits, read with ITS OWN credentials. The desktop reads the- // account on the computer it runs on directly; this is how it reads one on a machine it does- // not — which may be signed in to a different subscription entirely. The vendor's answer goes- // back as it came: see lib/accountUsage.ts for why the parsing stays on the client.- case 'usage_read': {- // Two vendor round trips (up to 8s each, lib/accountUsage.ts) — detached from the ordered- // chain for the same reason as `grid_models_list`: it is asked on connect beside the RPCs- // the terminal needs, and with no network it held them past the app's timeout.- void this.accountUsageReader()- .then((providers) => reply(type, requestId, { providers }))- .catch(() => reply(type, requestId, { error: 'USAGE_READ_FAILED' }))- return- }-// Physical devices belong to this machine; only its owner or loopback tools may manage them.case 'harness_devices_list':case 'harness_device_settings': {diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex dbe6827c9..d15f02d89 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -172,7 +172,7 @@ import { createAgentUpdate } from './core/agents/update.js'import { createEngineHooks, installEngineHooks } from './core/engines/hooks.js'import { createCursorTaskHooks } from './core/engines/cursorTasks.js'import { databaseHistory } from './core/transcripts/databaseHistory.js'-import { createCoreApi, emptyPorts, FLEET_FALLBACKS, MODELS_FALLBACKS, SEARCH_FALLBACKS, TEAMS_FALLBACKS, VIEWERS_FALLBACKS, WORKSPACES_FALLBACKS, type TeamsPort } from './core/api.js'+import { createCoreApi, emptyPorts, FLEET_FALLBACKS, MODELS_FALLBACKS, MONITOR_FALLBACKS, MONITOR_OFF, SEARCH_FALLBACKS, TEAMS_FALLBACKS, VIEWERS_FALLBACKS, WORKSPACES_FALLBACKS, type TeamsPort } from './core/api.js'import { createServiceHost, testFaults } from './core/serviceHost.js'import { startStalls } from './core/stall.js'import { createServiceLinks } from './core/serviceLinks.js'@@ -182,6 +182,9 @@ import { KNOWN_SERVICES, servicesTheMasterRuns } from './harnessd/services.js'import { createTeamsLink } from './core/teamsLink.js'import { SEARCH_REQUESTS, startSearch } from './services/search.js'import { STORE_REQUESTS, startStore } from './services/store.js'+import { USAGE_REQUESTS, startUsage } from './services/usage.js'+import { MONITOR_REQUESTS, startMonitor } from './services/monitor.js'+import { PROJECTS_REQUESTS, startProjects } from './services/projects.js'import { startViewers } from './services/viewers.js'import { MODELS_REQUESTS, startModels } from './services/models.js'import { startWorkspaces } from './services/workspaces.js'@@ -2253,7 +2256,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {backend.agentsProvider = createAgentList({registry, stoppedAgents, monitorActivityProvider: asking.monitorActivity, monitorCompletions: backend.monitorCompletions,toProject: (s) => backend.toProject(s), toStoppedProject: (s) => backend.toStoppedProject(s),- harnessResourcesReader: () => backend.harnessResourcesReader(), harnessStorageReader: (agents, invalidate) => backend.harnessStorageReader(agents, invalidate),+ // 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),}).agentsListconst agentNotifications = asking.agentNotificationsconst questionWatcher = asking.questionWatcher@@ -2360,6 +2364,13 @@ async function runForeground(session: AuthSession | null): Promise<void> {else serviceHost.start('teams', (_core, started) => { started.teams = backend.swarmPromptScopes }, coreApi, TEAMS_FALLBACKS)// The harnesses installed here, and installing, updating and removing one (services/store.ts).serviceHost.serve('store', startStore, coreApi, STORE_REQUESTS)+ // This machine's Claude and Codex rate limits, read with its own credentials (services/usage.ts).+ serviceHost.serve('usage', startUsage, coreApi, USAGE_REQUESTS)+ // This machine's and each agent's resources, for the Monitor and the list's readings (services/monitor.ts).+ serviceHost.start('monitor', startMonitor, coreApi, MONITOR_FALLBACKS, MONITOR_REQUESTS)+ // An agent's branch and pull request, a project's repository and preview, a folder's subfolders and a+ // media file from an agent's project (services/projects.ts).+ serviceHost.serve('projects', startProjects, coreApi, PROJECTS_REQUESTS)const runtimeController = new RuntimeProfileController({manager: runtimeProfiles,@@ -3690,7 +3701,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {const stopAgent = lifecycle.stopAgentbackend.stopProvider = createStopRequest({ byAgent: (id) => registry.byAgent(id), stop: stopAgent })backend.purgeAgentService = lifecycle.purgeAgentService- backend.purgeProvider = createPurgeRequest({ purgeAgentService: () => lifecycle.purgeAgentService, invalidateStorage: () => { void backend.harnessStorageReader([], true) } })+ 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).const closing = createAgentClosing({registry,diff --git a/cli/src/core/api.spec.ts b/cli/src/core/api.spec.tsindex 1936025b9..10a902822 100644--- a/cli/src/core/api.spec.ts+++ b/cli/src/core/api.spec.ts@@ -1,17 +1,26 @@import { describe, expect, it, vi } from 'vitest'import { projectDisplayName, type RegisteredSession } from '../lib/registry.js'-import { createCoreApi, emptyPorts, FLEET_FALLBACKS, TEAMS_FALLBACKS, type CoreApiDeps } from './api.js'+import { createCoreApi, emptyPorts, FLEET_FALLBACKS, MONITOR_OFF, resolveAgent, TEAMS_FALLBACKS, type CoreApiDeps } from './api.js'import { FAIL } from './serviceHost.js'const row = (agentId: string) => ({ agentId, sessionId: `s-${agentId}`, engine: 'claude', cwd: '/work/app' }) as RegisteredSessiondescribe('the core API services stand on', () => {+ it('resolves an agent in a service\'s own copy as the registry does: by agent id, then session id', () => {+ const agents = [{ ...row('a'), sessionId: '' }, row('b')]+ expect(resolveAgent(agents, 'b')?.agentId).toBe('b')+ expect(resolveAgent(agents, 's-b')?.agentId).toBe('b')+ expect(resolveAgent(agents, '')).toBeUndefined()+ expect(resolveAgent(agents, 'nobody')).toBeUndefined()+ })+it('lists every agent, live then stopped, and names them as the apps do', () => {const deps: CoreApiDeps = {dataDir: '/data',registry: {list: vi.fn(() => [row('live')]),byAgent: vi.fn((agentId: string) => (agentId === 'live' ? row('live') : undefined)),+ resolve: vi.fn((id: string) => (id === 'live' || id === 's-live' ? row('live') : undefined)),advertised: vi.fn(() => [row('live')]),terminalAvailable: vi.fn((agentId: string) => agentId === 'live'),} as unknown as CoreApiDeps['registry'],@@ -45,6 +54,8 @@ describe('the core API services stand on', () => {expect(core.external.open).toBe(deps.openSessions)expect(core.agents.byAgent('live')?.agentId).toBe('live')expect(core.agents.byAgent('gone')).toBeUndefined()+ expect(core.agents.resolve('s-live')?.agentId).toBe('live')+ expect(core.agents.resolve('gone')).toBeUndefined()expect(core.agents.terminalAvailable('live')).toBe(true)expect(core.agents.sync).toBe(deps.syncSession)expect(core.agents.runtimeModels).toBe(deps.runtimeModels)@@ -86,7 +97,12 @@ describe('the core API services stand on', () => {})it('starts with every port empty: a service fills its own when it starts', () => {- expect(emptyPorts()).toEqual({ search: null, viewers: null, models: null, workspaces: null, teams: null, fleet: null })+ expect(emptyPorts()).toEqual({ search: null, viewers: null, models: null, workspaces: null, teams: null, fleet: null, monitor: null })expect(emptyPorts()).not.toBe(emptyPorts())})++ it('answers the monitor\'s fallbacks while it is off: no readings, nothing measured to forget', async () => {+ await expect(MONITOR_OFF.resources()).rejects.toThrow('the monitor service is unavailable')+ expect(await MONITOR_OFF.storage([], true)).toEqual(new Map())+ })})diff --git a/cli/src/core/api.ts b/cli/src/core/api.tsindex 8fccc4762..264d4bf5d 100644--- a/cli/src/core/api.ts+++ b/cli/src/core/api.ts@@ -16,6 +16,8 @@ import type { FleetEvent } from '../cable/machineFleet.js'import type { AnswerReceipt, ReviewedAnswer } from '../cable/questionInbox.js'import type { AgentDshContext } from '../lib/agentFrame.js'import type { GridAccess } from '../lib/gridAttach.js'+import type { createHarnessResourcesReader } from '../lib/harnessResources.js'+import type { createHarnessStorageReader } from '../lib/harnessTelemetry.js'import type { AgentGridTarget } from '../lib/gridModels.js'import type { LiveEvent } from '../lib/normalize.js'import { projectDisplayName, type registry, type RegisteredSession } from '../lib/registry.js'@@ -26,7 +28,7 @@ import type { SessionSearchIndex } from '../lib/sessionSearch/indexer.js'import type { StoppedAgentStore } from '../lib/stoppedAgents.js'import type { RouteAnswer } from '../localWsServer.js'import type { SwarmPromptScopes } from '../teams/promptScope.js'-import { FAIL, later, type PortFallbacks } from './serviceHost.js'+import { FAIL, later, ServiceUnavailableError, type PortFallbacks } from './serviceHost.js'export type { RouteAnswer }@@ -42,6 +44,8 @@ export interface CoreApi {displayName(session: RegisteredSession): string/** A live agent, by its agent id. */byAgent(agentId: string): RegisteredSession | undefined+ /** A live agent, by its agent id or its engine session id: whichever the apps asked by. */+ resolve(id: string): RegisteredSession | undefined/** The live agents the apps are shown. */advertised(): RegisteredSession[]/** Whether the agent's terminal is attached: a frame without one reads to the apps as "agent gone". */@@ -113,6 +117,12 @@ export interface CoreApi {}}+/** `agents.resolve` over a service process's own copy of the agents, as the registry answers it: by agent+ * id, then by engine session id (an agent with none yet is never found by an empty one). */+export function resolveAgent(agents: readonly RegisteredSession[], id: string): RegisteredSession | undefined {+ return agents.find((agent) => agent.agentId === id) ?? (id ? agents.find((agent) => agent.sessionId === id) : undefined)+}+/** Who sent a request, as the core established it. A service trusts this, never a field of the* payload: a payload says whatever its sender wrote. */export interface Asker {@@ -180,6 +190,27 @@ export const MODELS_FALLBACKS: PortFallbacks<ModelsPort> = {ensure: later(FAIL), setUp: false, prewarm: undefined, signedOut: undefined,}+/** The core's calls into the machine monitor: the readings `agents_list` adds to its rows when a window+ * asks for the monitor, and forgetting what a purged agent's workspace held. The same readers answer the+ * monitor's own request (`machine_resources`), so the two share one sample and one cache. */+export interface MonitorPort {+ /** Each live agent's processes, and the shared ones (lib/harnessResources.ts). */+ resources: ReturnType<typeof createHarnessResourcesReader>+ /** What each agent's workspace and transcript hold on disk; `invalidate` drops what was measured+ * (lib/harnessTelemetry.ts). */+ storage: ReturnType<typeof createHarnessStorageReader>+}++/** What the core gets when the monitor fails: the list's rows without readings (core/agents/list.ts+ * answers a failed sample as none), and nothing measured to forget. */+export const MONITOR_FALLBACKS: PortFallbacks<MonitorPort> = { resources: later(FAIL), storage: later(new Map()) }++/** What the core calls while `ports.monitor` is null (the monitor is off): its fallbacks' answers. */+export const MONITOR_OFF: MonitorPort = {+ resources: () => Promise.reject(new ServiceUnavailableError('monitor')),+ storage: async () => new Map(),+}+/** The core's calls into workspaces: name made-up worktree branches after their sessions, on each* terminal-title pass, and sweep the worktrees nothing uses, when the core says it is time. */export interface WorkspacesPort {@@ -298,15 +329,16 @@ export interface CorePorts {workspaces: WorkspacesPort | nullteams: TeamsPort | nullfleet: FleetPort | null+ monitor: MonitorPort | null}export function emptyPorts(): CorePorts {- return { search: null, viewers: null, models: null, workspaces: null, teams: null, fleet: null }+ return { search: null, viewers: null, models: null, workspaces: null, teams: null, fleet: null, monitor: null }}export interface CoreApiDeps {dataDir: string- registry: Pick<typeof registry, 'list' | 'byAgent' | 'advertised' | 'terminalAvailable'>+ registry: Pick<typeof registry, 'list' | 'byAgent' | 'resolve' | 'advertised' | 'terminalAvailable'>stoppedAgents: Pick<StoppedAgentStore, 'list'>databaseHistory: CoreApi['transcripts']['databaseHistory']externalSessions: CoreApi['external']['sessions']@@ -340,6 +372,7 @@ export function createCoreApi({live: () => registry.list(),displayName: projectDisplayName,byAgent: (agentId) => registry.byAgent(agentId),+ resolve: (id) => registry.resolve(id),advertised: () => registry.advertised(),terminalAvailable: (agentId) => registry.terminalAvailable(agentId),sync: syncSession,diff --git a/cli/src/lib/apiConnectionsRpc.spec.ts b/cli/src/lib/apiConnectionsRpc.spec.tsindex 59de0ca55..50aa78b70 100644--- a/cli/src/lib/apiConnectionsRpc.spec.ts+++ b/cli/src/lib/apiConnectionsRpc.spec.ts@@ -1,11 +1,26 @@import { afterEach, describe, expect, it, vi } from 'vitest'import { BackendSocket } from '../backendSocket.js'+import { emptyPorts } from '../core/api.js'+import { createServiceHost } from '../core/serviceHost.js'+import { launchTargetRequests } from '../services/models.js'+import { fakeCore } from '../testing/fakeCore.js'import { ApiConnections } from './apiConnections.js'afterEach(() => vi.restoreAllMocks())++/** A socket whose `api_connections` goes where the daemon sends it: the models service+ * (services/models.ts), behind the socket's gates. */+function socketWithModels(): BackendSocket {+ const socket = new BackendSocket('fixture')+ const host = createServiceHost(emptyPorts())+ // Served alone, under a name of its own: `models` is a port's name, which `serve` keeps for `start`.+ host.serve('launch-targets', launchTargetRequests, fakeCore(), ['api_connections', 'codex_profiles_list', 'codex_profile_link'])+ socket.serviceRouter = host.route+ return socket+}describe('API connection RPC', () => {it.each(['list', 'save', 'remove'])('handles local %s and returns only public metadata', async action => {- const socket = new BackendSocket('fixture')+ const socket = socketWithModels()const frames: any[] = []socket.registerLocalClient('local:apis', { sendFrame: frame => { frames.push(frame); return true }, sendBinary: () => true })vi.spyOn(ApiConnections.prototype, 'list').mockReturnValue([])@@ -22,7 +37,7 @@ describe('API connection RPC', () => {})it('refuses unsealed remote access before touching the credential store', async () => {- const socket = new BackendSocket('fixture')+ const socket = socketWithModels()const list = vi.spyOn(ApiConnections.prototype, 'list')const save = vi.spyOn(ApiConnections.prototype, 'save')await (socket as any).dispatchDown({ type: 'api_connections', payload: { action: 'list', requestId: 'remote' } }, 'remote')@@ -33,7 +48,7 @@ describe('API connection RPC', () => {})it('refuses a sealed device session before touching the credential store', async () => {- const socket = new BackendSocket('fixture')+ const socket = socketWithModels()const save = vi.spyOn(ApiConnections.prototype, 'save')const reply = vi.spyOn(socket as any, 'emitReply').mockImplementation(() => {})vi.spyOn((socket as any).e2ee, 'sessionRole').mockReturnValue('device')@@ -41,13 +56,13 @@ describe('API connection RPC', () => {type: 'api_connections', payload: { action: 'save', requestId: 'remote', connection: { provider: 'fal', apiKey: 'must-stay-local' } },})await (socket as any).dispatchDown({ type: 'api_connections', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'fixture' } } }, 'remote')+ await vi.waitFor(() => expect(reply).toHaveBeenCalledWith('remote', 'api_connections', 'remote', { error: 'OWNER_REQUIRED' }))expect(save).not.toHaveBeenCalled()- expect(reply).toHaveBeenCalledWith('remote', 'api_connections', 'remote', { error: 'OWNER_REQUIRED' })await socket.stop()})it.each(['list', 'save', 'remove'])('allows sealed owner web %s with a sealed metadata-only reply', async action => {- const socket = new BackendSocket('fixture'), internals = socket as any+ const socket = socketWithModels(), internals = socket as anyvi.spyOn(ApiConnections.prototype, 'list').mockReturnValue([])const save = vi.spyOn(ApiConnections.prototype, 'save').mockReturnValue({ id: 'fixture' } as any)const remove = vi.spyOn(ApiConnections.prototype, 'remove').mockImplementation(() => {})@@ -58,7 +73,7 @@ describe('API connection RPC', () => {} })const sealedReply = vi.spyOn(internals.e2ee, 'wrapRpcReply').mockReturnValue({ type: 'api_connections_result', payload: { __e2e: 'sealed' } })await internals.dispatchDown({ type: 'api_connections', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'fixture' } } }, 'remote')- expect(sealedReply).toHaveBeenCalledWith('remote', 'api_connections_result', 'owner', expect.objectContaining({ connections: [] }))+ await vi.waitFor(() => expect(sealedReply).toHaveBeenCalledWith('remote', 'api_connections_result', 'owner', expect.objectContaining({ connections: [] })))expect(JSON.stringify(sealedReply.mock.calls)).not.toContain('fixture-private-key')if (action === 'save') expect(save).toHaveBeenCalledWith({ provider: 'fal', apiKey: 'fixture-private-key' })if (action === 'remove') expect(remove).toHaveBeenCalledWith('fixture')diff --git a/cli/src/services/models.spec.ts b/cli/src/services/models.spec.tsindex fc72e8b85..a654ca4a2 100644--- a/cli/src/services/models.spec.ts+++ b/cli/src/services/models.spec.ts@@ -19,6 +19,9 @@ import {import type { RegisteredSession } from '../lib/registry.js'import type { RuntimeModelOption } from '../lib/runtimeProfile.js'import { ensureManagedGrid } from '../lib/runtimeInstall.js'+import { apiConnectionsRequest } from '../lib/apiConnections.js'+import { apiModelsRequest, rememberSavedApis } from '../lib/apiModels.js'+import { linkCodexProfile, listCodexProfiles } from '../lib/codexProfiles.js'import { fakeCore } from '../testing/fakeCore.js'import { compactRuntimePickerModels, MODELS_REQUESTS, startModels } from './models.js'@@ -45,6 +48,20 @@ vi.mock('../lib/gridModels.js', () => ({warmGridModels: vi.fn(async () => {}),}))vi.mock('../lib/runtimeInstall.js', () => ({ ensureManagedGrid: vi.fn(async () => {}) }))+/** The saved APIs and the Codex profiles: their files and folders are the lib's, never this machine's here. */+const apis = vi.hoisted(() => ({ stores: [] as string[] }))+vi.mock('../lib/apiConnections.js', () => ({+ ApiConnections: class { constructor(dataDir: string) { apis.stores.push(dataDir) } },+ apiConnectionsRequest: vi.fn((_store: unknown, payload: Record<string, unknown>) => ({ connections: [], presets: [], action: payload.action })),+}))+vi.mock('../lib/apiModels.js', () => ({+ apiModelsRequest: vi.fn(async (_store: unknown, payload: Record<string, unknown>) => ({ id: payload.id, models: ['m1'] })),+ rememberSavedApis: vi.fn(),+}))+vi.mock('../lib/codexProfiles.js', () => ({+ listCodexProfiles: vi.fn((observed: string[]) => observed.map((path) => ({ path, label: 'Codex' }))),+ linkCodexProfile: vi.fn((path: string) => (path ? { path, label: 'Linked' } : { error: 'INVALID_PATH' })),+}))vi.mock('../lib/appModels.js', () => ({ appEngineOps: vi.fn(() => ({ engines: 'app' })), scanAppModels: vi.fn(async () => []) }))vi.mock('../dsh/installed.js', async (importOriginal) => ({...await importOriginal<typeof import('../dsh/installed.js')>(),@@ -491,6 +508,49 @@ describe('the models service', () => {expect(await ask('grid_fleet_models_list')).toMatchObject({ models: [] })})})++ describe('what an agent can be launched on besides a model: the saved APIs and the Codex profiles', () => {+ it('api_connections: only the owner manages the saved APIs, kept in the data folder', async () => {+ const { requests } = setup([], { dataDir: '/data/here' })+ expect(apis.stores.at(-1)).toBe('/data/here')+ // A device or an observer may not, whatever it asked.+ expect(await requests.api_connections!({ action: 'list' }, { local: false, owner: false })).toEqual({ error: 'OWNER_REQUIRED' })+ expect(apiConnectionsRequest).not.toHaveBeenCalled()+ })++ it('api_connections: lists, saves (and recognises agents already on the saved endpoints), removes, and reads an API\'s models', async () => {+ const { ask } = setup()+ expect(await ask('api_connections', { action: 'list' })).toEqual({ connections: [], presets: [], action: 'list' })+ expect(rememberSavedApis).not.toHaveBeenCalled()+ expect(await ask('api_connections', { action: 'save', connection: { name: 'x' } })).toEqual({ connections: [], presets: [], action: 'save' })+ expect(rememberSavedApis).toHaveBeenCalledOnce()+ expect(await ask('api_connections', { action: 'remove', id: 'a' })).toEqual({ connections: [], presets: [], action: 'remove' })+ expect(await ask('api_connections', { action: 'models', id: 'a' })).toEqual({ id: 'a', models: ['m1'] })+ expect(apiModelsRequest).toHaveBeenCalledOnce()+ expect(rememberSavedApis).toHaveBeenCalledOnce()+ })++ it('codex_profiles_list: the folders this machine offers, with the ones the asker has seen; a failed scan is said', async () => {+ const { ask } = setup()+ expect(await ask('codex_profiles_list', { observedPaths: ['/home/me/.codex-work', 7] })).toEqual({ profiles: [{ path: '/home/me/.codex-work', label: 'Codex' }] })+ expect(listCodexProfiles).toHaveBeenLastCalledWith(['/home/me/.codex-work'])+ expect(await ask('codex_profiles_list')).toEqual({ profiles: [] })+ vi.mocked(listCodexProfiles).mockImplementationOnce(() => { throw new Error('unreadable') })+ expect(await ask('codex_profiles_list')).toEqual({ error: 'CODEX_PROFILES_FAILED' })+ })++ it('codex_profile_link: links the folder and answers the profile, or why not; a failure to save answers INTERNAL, as the socket did', async () => {+ const { ask } = setup()+ expect(await ask('codex_profile_link', { path: '/home/me/.codex-work' })).toEqual({ profile: { path: '/home/me/.codex-work', label: 'Linked' } })+ expect(await ask('codex_profile_link', { path: 42 })).toEqual({ error: 'INVALID_PATH' })+ expect(linkCodexProfile).toHaveBeenLastCalledWith('')+ const log = vi.spyOn(console, 'error').mockImplementation(() => {})+ vi.mocked(linkCodexProfile).mockImplementationOnce(() => { throw new Error('disk full') })+ expect(await ask('codex_profile_link', { path: '/home/me/.codex-work' })).toEqual({ error: 'INTERNAL' })+ expect(log).toHaveBeenCalledWith('[backend] dispatch codex_profile_link failed:', expect.any(Error))+ log.mockRestore()+ })+ })})})diff --git a/cli/src/services/models.ts b/cli/src/services/models.tsindex 40a900995..6c6471e5d 100644--- a/cli/src/services/models.ts+++ b/cli/src/services/models.ts@@ -12,7 +12,10 @@ import { join } from 'node:path'import type { CoreApi, CorePorts, ModelsPort, ServiceRequest, ServiceRequests } from '../core/api.js'import { MODEL_MANAGER_ID } from '../dsh/builtins.js'import { installedDsh } from '../dsh/installed.js'+import { ApiConnections, apiConnectionsRequest } from '../lib/apiConnections.js'+import { apiModelsRequest, rememberSavedApis } from '../lib/apiModels.js'import { appEngineOps, scanAppModels } from '../lib/appModels.js'+import { linkCodexProfile, listCodexProfiles } from '../lib/codexProfiles.js'import { createGridAccess, gridNamesLocal, reconcileGridAttach } from '../lib/gridAttach.js'import { resetGridDeriveMemo, signedInGridEmail } from '../lib/gridDerive.js'import { ensureHarnessGrid } from '../lib/gridEnsure.js'@@ -27,6 +30,7 @@ import { gridModelsPayload } from '../lib/gridModelsPayload.js'import { LocalModels } from '../lib/localModels.js'import { parseRuntimeProfile, type RuntimeModelOption } from '../lib/runtimeProfile.js'import { ensureManagedGrid } from '../lib/runtimeInstall.js'+import { internalOnThrow } from './requestErrors.js'/*** The requests models answers for the apps.@@ -36,10 +40,12 @@ import { ensureManagedGrid } from '../lib/runtimeInstall.js'* (`lib/gridFleetRpc.ts`), while a request answered here knows who asked but not over which connection.* Their handshake, `grid_fleet_capabilities`, stays beside them: the Grid harness runs a command only* after it, and reads an answer without its protocol as "update Harness".+ * The saved APIs and the Codex profiles came out of the socket's switch (launchTargetRequests).*/export const MODELS_REQUESTS = ['grid_models_list', 'models_list','grid_fleet_models_list', 'grid_fleet_model_download', 'grid_fleet_model_start', 'grid_fleet_model_stop',+ 'api_connections', 'codex_profiles_list', 'codex_profile_link',] as constexport function startModels(core: CoreApi, ports: CorePorts): ServiceRequests {@@ -256,6 +262,49 @@ function modelsRequests(core: CoreApi, grid: Pick<ModelsPort, 'ensure' | 'setUp'grid_fleet_model_download: localModel('grid_fleet_model_download'),grid_fleet_model_start: localModel('grid_fleet_model_start'),grid_fleet_model_stop: localModel('grid_fleet_model_stop'),+ ...launchTargetRequests(core),+ }+}++/**+ * What an agent can be launched on besides a model: the saved APIs and the Codex profiles, moved out of the+ * socket's switch (docs/design/2026-10-06-core-boundary-next.md, step 4). Its own function so the socket's+ * specs can serve it alone behind the gates.+ */+export function launchTargetRequests(core: CoreApi): ServiceRequests {+ // The saved APIs, a file in the data folder (lib/apiConnections.ts): read afresh on every request.+ const apiConnections = new ApiConnections(core.dataDir)+ return {+ // The APIs saved on this machine (lib/apiConnections.ts): list, save and remove one, and one API's+ // models. Their keys stay here, so only the owner manages them: this machine's app, or its paired one.+ api_connections: internalOnThrow('api_connections', (payload, asker) => {+ if (!asker.owner) return { error: 'OWNER_REQUIRED' }+ if (payload.action === 'models') return apiModelsRequest(apiConnections, payload)+ const reply = apiConnectionsRequest(apiConnections, payload)+ if (payload.action === 'save') rememberSavedApis(apiConnections)+ return reply+ }),++ // Which CODEX_HOME folders THIS machine can offer — answered here, on the machine in question, for+ // the same reason `engines_probe` is: a Codex profile is a folder on disk, and a folder on a Mac means+ // nothing on the Docker rig it was asked about instead.+ codex_profiles_list: internalOnThrow('codex_profiles_list', (payload) => {+ const observed = Array.isArray(payload.observedPaths)+ ? payload.observedPaths.filter((p): p is string => typeof p === 'string')+ : []+ try {+ return { profiles: listCodexProfiles(observed) }+ } catch {+ return { error: 'CODEX_PROFILES_FAILED' }+ }+ }),++ codex_profile_link: internalOnThrow('codex_profile_link', (payload) => {+ const path = typeof payload.path === 'string' ? payload.path : ''+ const result = linkCodexProfile(path)+ if ('error' in result) return { error: result.error }+ return { profile: result }+ }),}}diff --git a/cli/src/services/monitor.spec.ts b/cli/src/services/monitor.spec.tsnew file mode 100644index 000000000..e25a81095--- /dev/null+++ b/cli/src/services/monitor.spec.ts@@ -0,0 +1,83 @@+import { describe, expect, it, vi } from 'vitest'+import { emptyPorts, MONITOR_FALLBACKS, type MonitorPort } from '../core/api.js'+import { createServiceHost } from '../core/serviceHost.js'+import type { RegisteredSession } from '../lib/registry.js'+import { fakeCore } from '../testing/fakeCore.js'+import { MONITOR_REQUESTS, startMonitor, type MonitorDeps } from './monitor.js'++/** This machine's readers, as the daemon builds them: which agents the process sample is taken of. */+const built = vi.hoisted(() => ({ agents: null as null | (() => unknown[]) }))+vi.mock('../lib/harnessResources.js', () => ({+ createHarnessResourcesReader: vi.fn((agents: () => unknown[]) => { built.agents = agents; return async () => ({ sampledAt: 'now', agents: [] }) }),+}))++const ASKER = { local: true, owner: true }+const agent = (agentId: string) => ({ agentId }) as RegisteredSession+const reading = { sampledAt: '2026-10-05T12:00:00.000Z', agents: [{ agentId: 'a1', memoryBytes: 1, cpuPercent: 2, processCount: 1, processes: [] }] }++function setup(over: Partial<MonitorDeps> = {}) {+ const deps: MonitorDeps = {+ machine: vi.fn(async () => ({ cpuPercent: 18, memoryUsedBytes: 10, memoryTotalBytes: 32 })),+ resources: vi.fn(async () => reading),+ storage: vi.fn(async () => new Map([['a1', { workspaceBytes: 5, transcriptBytes: 6 }]])) as unknown as MonitorDeps['storage'],+ ...over,+ }+ const core = fakeCore({ agents: { advertised: vi.fn(() => [agent('a1')]) } })+ const ports = emptyPorts()+ const requests = startMonitor(core, ports, deps)+ return { deps, core, port: ports.monitor as MonitorPort, requests, ask: (payload: Record<string, unknown> = {}) => requests.machine_resources!(payload, ASKER) }+}++describe('the machine monitor', () => {+ it('answers exactly the request it declares, and fills its port', () => {+ const { requests, port } = setup()+ expect(Object.keys(requests)).toEqual([...MONITOR_REQUESTS])+ expect(port).not.toBeNull()+ // Started as the daemon starts it, with this machine's own readers behind it.+ const ports = emptyPorts()+ const core = fakeCore({ agents: { advertised: vi.fn(() => [agent('a1')]) } })+ expect(Object.keys(startMonitor(core, ports))).toEqual([...MONITOR_REQUESTS])+ expect(ports.monitor).not.toBeNull()+ // The processes sampled are those of the agents the apps are shown.+ expect(built.agents!()).toEqual([agent('a1')])+ })++ it('machine_resources: the machine\'s totals, or each agent\'s readings, with their storage when asked', async () => {+ const { ask, deps } = setup()+ expect(await ask()).toEqual({ cpuPercent: 18, memoryUsedBytes: 10, memoryTotalBytes: 32 })+ expect(deps.resources).not.toHaveBeenCalled()+ expect(await ask({ harnesses: true })).toEqual({ harnesses: reading })+ expect(deps.storage).not.toHaveBeenCalled()+ expect(await ask({ harnesses: true, storage: true })).toEqual({+ harnesses: { ...reading, agents: [{ ...reading.agents[0], workspaceBytes: 5, transcriptBytes: 6 }] },+ })+ // The agents the apps are shown: the same ones the readings are taken of.+ expect(deps.storage).toHaveBeenCalledWith([agent('a1')])+ expect(deps.machine).toHaveBeenCalledOnce()+ })++ it('machine_resources: a sample that fails is UNAVAILABLE', async () => {+ expect(await setup({ machine: vi.fn(async () => { throw new Error('ps failed') }) }).ask()).toEqual({ error: 'UNAVAILABLE' })+ expect(await setup({ resources: vi.fn(async () => { throw new Error('ps failed') }) }).ask({ harnesses: true })).toEqual({ error: 'UNAVAILABLE' })+ })++ it('the core\'s list reads the same readers through the port, and a purge forgets through it', async () => {+ const { port, deps } = setup()+ expect(await port.resources()).toBe(reading)+ await port.storage([agent('a1')], true)+ expect(deps.storage).toHaveBeenCalledWith([agent('a1')], true)+ })++ it('through the host, a failing reader answers the port\'s fallbacks: no readings, nothing to forget', async () => {+ const ports = emptyPorts()+ const guarded = createServiceHost(ports, { log: () => {} })+ guarded.start('monitor', (core, staging) => startMonitor(core, staging, {+ machine: vi.fn(async () => ({})) as unknown as MonitorDeps['machine'],+ resources: vi.fn(async () => { throw new Error('ps failed') }),+ storage: vi.fn(async () => { throw new Error('du failed') }) as unknown as MonitorDeps['storage'],+ }), fakeCore(), MONITOR_FALLBACKS, MONITOR_REQUESTS)+ await expect(ports.monitor!.resources()).rejects.toThrow('the monitor service is unavailable')+ expect(await ports.monitor!.storage([], true)).toEqual(new Map())+ expect(guarded.isOff('monitor')).toBe(false)+ })+})diff --git a/cli/src/services/monitor.ts b/cli/src/services/monitor.tsnew file mode 100644index 000000000..da79c5fc6--- /dev/null+++ b/cli/src/services/monitor.ts@@ -0,0 +1,42 @@+/**+ * The machine monitor: this machine's totals, each agent's processes and what its workspace and transcript+ * hold (`machine_resources`), and the same readers for `agents_list`'s rows through `ports.monitor`: one+ * sample and one cache for both, as when the socket held them. Moved out of the socket's switch as it was+ * (docs/design/2026-10-06-core-boundary-next.md, step 4).+ */+import type { CoreApi, CorePorts, ServiceRequests } from '../core/api.js'+import { createHarnessResourcesReader } from '../lib/harnessResources.js'+import { createHarnessStorageReader } from '../lib/harnessTelemetry.js'+import { readMachineResources } from '../lib/machineResources.js'+import { internalOnThrow } from './requestErrors.js'++/** The request the monitor answers for the apps. */+export const MONITOR_REQUESTS = ['machine_resources'] as const++export interface MonitorDeps {+ /** The machine's own totals. */+ machine: () => ReturnType<typeof readMachineResources>+ /** Each live agent's processes. */+ resources: ReturnType<typeof createHarnessResourcesReader>+ /** What each agent's workspace and transcript hold. */+ storage: ReturnType<typeof createHarnessStorageReader>+}++export function startMonitor(core: CoreApi, ports: CorePorts, deps: MonitorDeps = {+ machine: readMachineResources,+ resources: createHarnessResourcesReader(() => core.agents.advertised()),+ storage: createHarnessStorageReader(),+}): ServiceRequests {+ ports.monitor = { resources: () => deps.resources(), storage: (agents, invalidate) => deps.storage(agents, invalidate) }+ return {+ // Sampling CPU must not hold up typing or other machine requests.+ machine_resources: internalOnThrow('machine_resources', (payload) => (payload.harnesses === true+ ? deps.resources().then(async (harnesses) => {+ if (payload.storage !== true) return { harnesses }+ const storage = await deps.storage(core.agents.advertised())+ return { harnesses: { ...harnesses, agents: harnesses.agents.map((row) => ({ ...row, ...storage.get(row.agentId) })) } }+ })+ : deps.machine())+ .then((resources) => ({ ...resources }), () => ({ error: 'UNAVAILABLE' }))),+ }+}diff --git a/cli/src/services/projects.spec.ts b/cli/src/services/projects.spec.tsnew file mode 100644index 000000000..84b1d6b52--- /dev/null+++ b/cli/src/services/projects.spec.ts@@ -0,0 +1,104 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import { listDir } from '../lib/fsBrowse.js'+import { readGitProject } from '../lib/gitProject.js'+import { MediaPreviewError, readMediaPreviewChunk } from '../lib/mediaPreview.js'+import { projectPreview } from '../lib/projectPreview.js'+import type { RegisteredSession } from '../lib/registry.js'+import { readSessionGitPullRequest } from '../lib/sessionGitPullRequest.js'+import { fakeCore } from '../testing/fakeCore.js'+import { PROJECTS_REQUESTS, startProjects } from './projects.js'++vi.mock('../lib/fsBrowse.js', () => ({ listDir: vi.fn(() => ({ path: '/home/me', entries: [], truncated: false })) }))+vi.mock('../lib/gitProject.js', () => ({ readGitProject: vi.fn(async () => ({ path: '/work/app', branch: 'main' })) }))+vi.mock('../lib/projectPreview.js', () => ({ projectPreview: vi.fn(async () => ({ path: '/work/app', readme: '# app' })) }))+vi.mock('../lib/sessionGitPullRequest.js', () => ({ readSessionGitPullRequest: vi.fn(async () => ({ status: 'found', number: 12 })) }))+vi.mock('../lib/mediaPreview.js', async (importOriginal) => ({+ MediaPreviewError: (await importOriginal<typeof import('../lib/mediaPreview.js')>()).MediaPreviewError,+ readMediaPreviewChunk: vi.fn(async () => ({ mime: 'image/png', data: 'AAAA', done: true })),+}))++const ASKER = { local: false, owner: false }+const row = (agentId: string, cwd: string | null) => ({ agentId, sessionId: `s-${agentId}`, cwd }) as RegisteredSession++function setup() {+ const agents = [row('a1', '/work/app'), row('a2', null)]+ const core = fakeCore({ agents: { live: vi.fn(() => agents), resolve: vi.fn((id: string) => agents.find((agent) => agent.agentId === id || agent.sessionId === id)) } })+ const requests = startProjects(core)+ return { core, ask: (type: string, payload: Record<string, unknown> = {}) => requests[type]!(payload, ASKER), requests }+}++describe('the project and folder readers', () => {+ afterEach(() => { vi.clearAllMocks() })++ it('answer exactly the requests they declare', () => {+ expect(Object.keys(setup().requests).sort()).toEqual([...PROJECTS_REQUESTS].sort())+ })++ it('git_pull_request: an agent\'s branch and pull request, asked by either id, with the context it was shown', async () => {+ const { ask } = setup()+ expect(await ask('git_pull_request', { agentId: 's-a1', history: true, offset: 20 })).toEqual({ status: 'found', number: 12 })+ expect(readSessionGitPullRequest).toHaveBeenLastCalledWith(row('a1', '/work/app'), { expected: undefined, history: true, offset: 20 })+ const context = { cwd: '/work/app', branch: 'feature', remote: null }+ await ask('git_pull_request', { agentId: 'a1', context, offset: 'later' })+ expect(readSessionGitPullRequest).toHaveBeenLastCalledWith(row('a1', '/work/app'), { expected: context, history: false, offset: undefined })+ await ask('git_pull_request', { agentId: 'a1', context: { cwd: '/w', branch: 'b', remote: 'origin' } })+ expect(readSessionGitPullRequest).toHaveBeenCalledTimes(3)+ })++ it('git_pull_request: unavailable for an agent with no folder, a malformed context, or a read that fails', async () => {+ const { ask } = setup()+ for (const payload of [{}, { agentId: 7 }, { agentId: 'nobody' }, { agentId: 'a2' }]) {+ expect(await ask('git_pull_request', payload)).toEqual({ status: 'unavailable' })+ }+ for (const context of [null, 'main', { cwd: 1, branch: 'b', remote: null }, { cwd: '/w', branch: 2, remote: null }, { cwd: '/w', branch: 'b', remote: 3 }]) {+ expect(await ask('git_pull_request', { agentId: 'a1', context })).toEqual({ status: 'unavailable' })+ }+ expect(readSessionGitPullRequest).not.toHaveBeenCalled()+ vi.mocked(readSessionGitPullRequest).mockRejectedValueOnce(new Error('gh missing'))+ expect(await ask('git_pull_request', { agentId: 'a1' })).toEqual({ status: 'unavailable' })+ })++ it('git_project_info and project_preview: read within the home and the folders agents run in', async () => {+ const { ask } = setup()+ expect(await ask('git_project_info', { path: '/work/app', refresh: true })).toEqual({ path: '/work/app', branch: 'main' })+ expect(readGitProject).toHaveBeenLastCalledWith('/work/app', { refresh: true, knownRoots: ['/work/app'] })+ await ask('git_project_info', { path: 9 })+ expect(readGitProject).toHaveBeenLastCalledWith('', { refresh: false, knownRoots: ['/work/app'] })+ expect(await ask('project_preview', { path: '/work/app' })).toEqual({ path: '/work/app', readme: '# app' })+ expect(projectPreview).toHaveBeenLastCalledWith('/work/app', ['/work/app'])+ await ask('project_preview')+ expect(projectPreview).toHaveBeenLastCalledWith('', ['/work/app'])+ })++ it('git_project_info and project_preview: a read that fails is UNAVAILABLE', async () => {+ const { ask } = setup()+ vi.mocked(readGitProject).mockRejectedValueOnce(new Error('git failed'))+ expect(await ask('git_project_info', { path: '/work/app' })).toEqual({ error: 'UNAVAILABLE' })+ vi.mocked(projectPreview).mockRejectedValueOnce(new Error('unreadable'))+ expect(await ask('project_preview', { path: '/work/app' })).toEqual({ error: 'UNAVAILABLE' })+ })++ it('fs_list_dir: one folder\'s subfolders, or why not', async () => {+ const { ask } = setup()+ expect(await ask('fs_list_dir', { path: '/home/me' })).toEqual({ path: '/home/me', entries: [], truncated: false })+ expect(listDir).toHaveBeenLastCalledWith('/home/me')+ vi.mocked(listDir).mockReturnValueOnce({ error: 'FORBIDDEN' })+ expect(await ask('fs_list_dir')).toEqual({ error: 'FORBIDDEN' })+ expect(listDir).toHaveBeenLastCalledWith('')+ })++ it('agent_read_file: a media chunk from the agent\'s project, or why not', async () => {+ const { ask } = setup()+ expect(await ask('agent_read_file', { agentId: 'a1', path: 'shot.png', media: true, offset: 0, revision: 'r1' }))+ .toEqual({ mime: 'image/png', data: 'AAAA', done: true })+ expect(readMediaPreviewChunk).toHaveBeenLastCalledWith('/work/app', 'shot.png', 0, 'r1')+ expect(await ask('agent_read_file', { path: 'shot.png', media: true })).toEqual({ error: 'MISSING_AGENT_OR_PATH' })+ expect(await ask('agent_read_file', { agentId: 'a1', media: true })).toEqual({ error: 'MISSING_AGENT_OR_PATH' })+ expect(await ask('agent_read_file', { agentId: 'a1', path: 'notes.md' })).toEqual({ error: 'UNSUPPORTED', detail: 'agent_read_file serves media previews only' })+ expect(await ask('agent_read_file', { agentId: 'a2', path: 'shot.png', media: true })).toEqual({ error: 'AGENT_NOT_FOUND' })+ vi.mocked(readMediaPreviewChunk).mockRejectedValueOnce(new MediaPreviewError('OUTSIDE_PROJECT'))+ expect(await ask('agent_read_file', { agentId: 'a1', path: '../x.png', media: true })).toEqual({ error: 'OUTSIDE_PROJECT' })+ vi.mocked(readMediaPreviewChunk).mockRejectedValueOnce(new Error('EIO'))+ expect(await ask('agent_read_file', { agentId: 'a1', path: 'shot.png', media: true })).toEqual({ error: 'MEDIA_READ_FAILED' })+ })+})diff --git a/cli/src/services/projects.ts b/cli/src/services/projects.tsnew file mode 100644index 000000000..26a9a5b90--- /dev/null+++ b/cli/src/services/projects.ts@@ -0,0 +1,76 @@+/**+ * The project and folder readers: an agent's branch and pull request, a project's repository and preview,+ * a folder's subfolders for the New Agent browser, and media from an agent's project. Each reads the disk+ * or runs git, so it is answered when it settles, never in the connection's line. Moved out of the+ * socket's switch as they were (docs/design/2026-10-06-core-boundary-next.md, step 4).+ */+import type { CoreApi, ServiceRequests } from '../core/api.js'+import { listDir } from '../lib/fsBrowse.js'+import { readGitProject } from '../lib/gitProject.js'+import { MediaPreviewError, readMediaPreviewChunk } from '../lib/mediaPreview.js'+import { projectPreview } from '../lib/projectPreview.js'+import { readSessionGitPullRequest, type ExpectedGitContext } from '../lib/sessionGitPullRequest.js'+import { internalOnThrow } from './requestErrors.js'++/** The requests the project readers answer for the apps. */+export const PROJECTS_REQUESTS = ['git_pull_request', 'git_project_info', 'project_preview', 'fs_list_dir', 'agent_read_file'] as const++export function startProjects(core: CoreApi): ServiceRequests {+ /** The browsable home, widened by the folders agents are running in: a repository outside both is not+ * somewhere this daemon runs git. */+ const knownRoots = (): string[] => core.agents.live().flatMap((agent) => agent.cwd ? [agent.cwd] : [])+ return {+ git_pull_request: internalOnThrow('git_pull_request', (payload) => {+ const id = payload.agentId+ const agent = typeof id === 'string' ? core.agents.resolve(id) : undefined+ if (!agent?.cwd) return { status: 'unavailable' }+ const requested = payload.context+ if (requested !== undefined && (!requested || typeof requested !== 'object'+ || typeof (requested as Record<string, unknown>).cwd !== 'string'+ || typeof (requested as Record<string, unknown>).branch !== 'string'+ || (requested as Record<string, unknown>).remote !== null && typeof (requested as Record<string, unknown>).remote !== 'string')) {+ return { status: 'unavailable' }+ }+ return readSessionGitPullRequest(agent, {+ expected: requested as ExpectedGitContext | undefined,+ history: payload.history === true, offset: typeof payload.offset === 'number' ? payload.offset : undefined,+ }).then((result) => result, () => ({ status: 'unavailable' }))+ }),++ git_project_info: internalOnThrow('git_project_info', (payload) => {+ const path = typeof payload.path === 'string' ? payload.path : ''+ return readGitProject(path, { refresh: payload.refresh === true, knownRoots: knownRoots() })+ .then((result) => result, () => ({ error: 'UNAVAILABLE' }))+ }),++ project_preview: internalOnThrow('project_preview', (payload) => {+ const path = typeof payload.path === 'string' ? payload.path : ''+ return projectPreview(path, knownRoots()).then((result) => result, () => ({ error: 'UNAVAILABLE' }))+ }),++ // One-level remote directory listing for the New Agent folder browser.+ fs_list_dir: internalOnThrow('fs_list_dir', (payload) => {+ const path = typeof payload.path === 'string' ? payload.path : ''+ const result = listDir(path)+ if ('error' in result) return { error: result.error }+ return { ...result }+ }),++ // Media previews, in bounded binary chunks. The text mode this request also used to serve was read by+ // nothing — every client has always asked with `media: true` — so it is gone rather than carrying a+ // second, laxer file reader (lib/mediaPreview.ts).+ agent_read_file: internalOnThrow('agent_read_file', async (payload) => {+ const projectId = payload.agentId as string | undefined+ const path = payload.path as string | undefined+ if (!projectId || !path) return { error: 'MISSING_AGENT_OR_PATH' }+ if (payload.media !== true) return { error: 'UNSUPPORTED', detail: 'agent_read_file serves media previews only' }+ const s = core.agents.resolve(projectId)+ if (!s?.cwd) return { error: 'AGENT_NOT_FOUND' }+ try {+ return { ...await readMediaPreviewChunk(s.cwd, path, payload.offset, payload.revision) }+ } catch (error) {+ return { error: error instanceof MediaPreviewError ? error.message : 'MEDIA_READ_FAILED' }+ }+ }),+ }+}diff --git a/cli/src/services/requestErrors.spec.ts b/cli/src/services/requestErrors.spec.tsnew file mode 100644index 000000000..58aa64dfa--- /dev/null+++ b/cli/src/services/requestErrors.spec.ts@@ -0,0 +1,24 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import { internalOnThrow } from './requestErrors.js'++const ASKER = { local: true, owner: true }++describe('a request moved out of the socket\'s switch', () => {+ afterEach(() => { vi.restoreAllMocks() })++ it('answers what its handler answers, sync or async, with the payload and asker it was given', async () => {+ const handler = vi.fn((payload: Record<string, unknown>) => ({ echoed: payload.n }))+ expect(await internalOnThrow('t', handler)({ n: 1 }, ASKER)).toEqual({ echoed: 1 })+ expect(handler).toHaveBeenCalledWith({ n: 1 }, ASKER)+ expect(await internalOnThrow('t', async () => ({ later: true }))({}, ASKER)).toEqual({ later: true })+ })++ it('answers a throw or a rejection INTERNAL, as the switch did, and logs it under its type', async () => {+ const log = vi.spyOn(console, 'error').mockImplementation(() => {})+ const boom = new Error('disk full')+ expect(await internalOnThrow('codex_profile_link', () => { throw boom })({}, ASKER)).toEqual({ error: 'INTERNAL' })+ expect(log).toHaveBeenCalledWith('[backend] dispatch codex_profile_link failed:', boom)+ expect(await internalOnThrow('fs_list_dir', async () => { throw boom })({}, ASKER)).toEqual({ error: 'INTERNAL' })+ expect(log).toHaveBeenCalledWith('[backend] dispatch fs_list_dir failed:', boom)+ })+})diff --git a/cli/src/services/requestErrors.ts b/cli/src/services/requestErrors.tsnew file mode 100644index 000000000..c7ce542de--- /dev/null+++ b/cli/src/services/requestErrors.ts@@ -0,0 +1,18 @@+/**+ * A request moved out of the socket's switch answers a throw as the switch did: INTERNAL, logged under its+ * type. The service host would answer SERVICE_FAILED and count it, switching the service off after five+ * in a minute (core/serviceHost.ts): a full disk under a profile link would take grid and the pickers+ * with it (docs/design/2026-10-06-core-boundary-next.md, step 4).+ */+import type { ServiceRequest } from '../core/api.js'++export function internalOnThrow(type: string, handler: ServiceRequest): ServiceRequest {+ return async (payload, asker) => {+ try {+ return await handler(payload, asker)+ } catch (error) {+ console.error(`[backend] dispatch ${type} failed:`, error)+ return { error: 'INTERNAL' }+ }+ }+}diff --git a/cli/src/services/searchProcess.spec.ts b/cli/src/services/searchProcess.spec.tsindex 4952c0f52..278af25a1 100644--- a/cli/src/services/searchProcess.spec.ts+++ b/cli/src/services/searchProcess.spec.ts@@ -116,6 +116,7 @@ describe('search in its own process', () => {expect(api.agents.all()).toEqual([live, stopped])expect(api.agents.live()).toEqual([live])expect(api.agents.byAgent('stopped')).toBe(stopped)+ expect(api.agents.resolve('stopped')).toBe(stopped)expect(api.agents.displayName(live as never)).toBe('Live one')expect(api.agents.displayName(stopped as never)).toBe('')expect(api.agents.advertised()).toEqual([])diff --git a/cli/src/services/searchProcess.ts b/cli/src/services/searchProcess.tsindex 08e95a079..eed622283 100644--- a/cli/src/services/searchProcess.ts+++ b/cli/src/services/searchProcess.ts@@ -8,7 +8,7 @@* process's alone: a crash or a leak in search costs search, and the master starts it again.*/import type { CoreApi } from '../core/api.js'-import { emptyPorts } from '../core/api.js'+import { emptyPorts, resolveAgent } from '../core/api.js'import { databaseHistory } from '../core/transcripts/databaseHistory.js'import { ExternalSessions, OpenSessions } from '../lib/sessionSearch/external.js'import { externalProviders } from '../lib/sessionSearch/externals/index.js'@@ -45,6 +45,7 @@ export function searchCoreApi(live: () => agents().filter((agent) => agent.active),displayName: (session) => (session as { displayName?: string }).displayName ?? '',byAgent: (agentId) => agents().find((agent) => agent.agentId === agentId),+ resolve: (id) => resolveAgent(agents(), id),advertised: () => [],terminalAvailable: () => false,sync: () => {},diff --git a/cli/src/services/usage.spec.ts b/cli/src/services/usage.spec.tsnew file mode 100644index 000000000..f42393f1f--- /dev/null+++ b/cli/src/services/usage.spec.ts@@ -0,0 +1,23 @@+import { describe, expect, it, vi } from 'vitest'+import { fakeCore } from '../testing/fakeCore.js'+import { startUsage, USAGE_REQUESTS } from './usage.js'++const ASKER = { local: false, owner: true }++describe('the usage service', () => {+ it('answers exactly the request it declares', () => {+ expect(Object.keys(startUsage(fakeCore())).sort()).toEqual([...USAGE_REQUESTS].sort())+ })++ it('usage_read: this machine\'s own readings, as the vendors gave them', async () => {+ const readings = [{ provider: 'claude' as const, account: 'k1', outcome: 'answered' as const, httpStatus: 200, body: { seven_day: { utilization: 42 } } }]+ const read = vi.fn(async () => readings)+ expect(await startUsage(fakeCore(), { read }).usage_read!({}, ASKER)).toEqual({ providers: readings })+ expect(read).toHaveBeenCalledOnce()+ })++ it('usage_read: a reading that fails is said, never thrown', async () => {+ const requests = startUsage(fakeCore(), { read: async () => { throw new Error('keychain locked') } })+ expect(await requests.usage_read!({}, ASKER)).toEqual({ error: 'USAGE_READ_FAILED' })+ })+})diff --git a/cli/src/services/usage.ts b/cli/src/services/usage.tsnew file mode 100644index 000000000..9ab65c3e2--- /dev/null+++ b/cli/src/services/usage.ts@@ -0,0 +1,29 @@+/**+ * This machine's Claude and Codex rate limits, read with its own credentials (`usage_read`): how the+ * desktop reads an account on a machine it does not run on, which may be signed in to another+ * subscription. The vendors' answers go back as they came (lib/accountUsage.ts says why). Moved out of+ * the socket's switch as it was (docs/design/2026-10-06-core-boundary-next.md, step 4).+ */+import type { CoreApi, ServiceRequests } from '../core/api.js'+import { readAccountUsage, type AccountUsageReading } from '../lib/accountUsage.js'+import { internalOnThrow } from './requestErrors.js'++/** The request usage answers for the apps. */+export const USAGE_REQUESTS = ['usage_read'] as const++export interface UsageDeps {+ /** The vendors' answers. Injected so a spec reads no real home, Keychain or network. */+ read: () => Promise<AccountUsageReading[]>+}++export function startUsage(_core: CoreApi, deps: UsageDeps = { read: readAccountUsage }): ServiceRequests {+ return {+ // Two vendor round trips (up to 8s each, lib/accountUsage.ts). Answered when they settle, never in the+ // connection's line: it is asked on connect beside the requests the terminal needs, and with no+ // network it held them past the app's timeout while it was the socket's.+ usage_read: internalOnThrow('usage_read', () => deps.read().then(+ (providers) => ({ providers }),+ () => ({ error: 'USAGE_READ_FAILED' }),+ )),+ }+}diff --git a/cli/src/services/viewersProcess.spec.ts b/cli/src/services/viewersProcess.spec.tsindex 8c6ae10ff..305a3e89b 100644--- a/cli/src/services/viewersProcess.spec.ts+++ b/cli/src/services/viewersProcess.spec.ts@@ -70,6 +70,7 @@ describe('the viewers in their own process', () => {options.onEvent!({ kind: 'attach', session: agent() })expect(viewers.port.attach).toHaveBeenCalledWith(agent())expect(api.agents.byAgent('a1')).toEqual(agent())+ expect(api.agents.resolve('a1')).toEqual(agent())expect(core.told()).toEqual([{ agentId: 'a1', context: viewers.contexts.get('a1'), forwardingUrl: null }])options.onEvent!({ kind: 'detach', agentId: 'a1' })expect(viewers.port.detach).toHaveBeenCalledWith('a1')diff --git a/cli/src/services/viewersProcess.ts b/cli/src/services/viewersProcess.tsindex ed6ecce18..52633b975 100644--- a/cli/src/services/viewersProcess.ts+++ b/cli/src/services/viewersProcess.ts@@ -18,7 +18,7 @@* no longer restarts every viewer: they stay up here, and the new core hears their URLs at once.*/import type { CoreApi } from '../core/api.js'-import { emptyPorts } from '../core/api.js'+import { emptyPorts, resolveAgent } from '../core/api.js'import type { RegisteredSession } from '../lib/registry.js'import { runServiceProcess, type CoreConnection, type ServiceProcess } from './process.js'import { startViewers } from './viewers.js'@@ -55,6 +55,7 @@ export function viewersCoreApi(dataDir: string, sessions: ReadonlyMap<string, Relive: attached,displayName: () => '',byAgent: (agentId) => sessions.get(agentId),+ resolve: (id) => resolveAgent(attached(), id),advertised: () => [],terminalAvailable: () => true,sync: (session) => tell(session.agentId),diff --git a/cli/src/services/workspacesProcess.spec.ts b/cli/src/services/workspacesProcess.spec.tsindex 26af06036..b605f07b6 100644--- a/cli/src/services/workspacesProcess.spec.ts+++ b/cli/src/services/workspacesProcess.spec.ts@@ -152,6 +152,7 @@ describe('workspaces in their own process', () => {expect(api.agents.all()).toEqual(everyone)expect(api.agents.byAgent('a1')).toEqual(agent('a1'))expect(api.agents.byAgent('old')).toBeUndefined()+ expect(api.agents.resolve('a1')).toEqual(agent('a1'))expect(api.agents.displayName(agent())).toBe('')expect(api.agents.advertised()).toEqual([])expect(api.agents.terminalAvailable('a1')).toBe(false)diff --git a/cli/src/services/workspacesProcess.ts b/cli/src/services/workspacesProcess.tsindex bc78125db..d8b03d231 100644--- a/cli/src/services/workspacesProcess.ts+++ b/cli/src/services/workspacesProcess.ts@@ -13,7 +13,7 @@* alone: a hang or a crash in it costs workspaces, and the master starts them again.*/import type { CoreApi } from '../core/api.js'-import { emptyPorts } from '../core/api.js'+import { emptyPorts, resolveAgent } from '../core/api.js'import type { RegisteredSession } from '../lib/registry.js'import { runServiceProcess, type CoreConnection, type ServiceProcess } from './process.js'import { startWorkspaces } from './workspaces.js'@@ -54,6 +54,7 @@ export function workspacesCoreApi(live: () => view.live(),displayName: () => '',byAgent: (agentId) => view.live().find((session) => session.agentId === agentId),+ resolve: (id) => resolveAgent(view.live(), id),advertised: () => [],terminalAvailable: () => false,sync: (session) => renamed(session.agentId),diff --git a/cli/src/testing/fakeCore.ts b/cli/src/testing/fakeCore.tsindex 6f5a324c3..f4d273f23 100644--- a/cli/src/testing/fakeCore.ts+++ b/cli/src/testing/fakeCore.ts@@ -16,6 +16,7 @@ export function fakeCore(over: Overrides = {}): CoreApi {live: vi.fn(() => []),displayName: vi.fn(() => ''),byAgent: vi.fn(() => undefined),+ resolve: vi.fn(() => undefined),advertised: vi.fn(() => []),terminalAvailable: vi.fn(() => false),sync: vi.fn(),diff --git a/cli/src/testing/socketCore.ts b/cli/src/testing/socketCore.tsindex 17b404a48..08c09ff89 100644--- a/cli/src/testing/socketCore.ts+++ b/cli/src/testing/socketCore.ts@@ -19,6 +19,8 @@ import { createHistory } from '../core/transcripts/history.js'import { createTerminalRequests, type TerminalRequestDeps } from '../core/terminals/requests.js'import { createCancelRequest } from '../core/turns/cancel.js'import { AgentCreationReceipts } from '../lib/agentCreationReceipt.js'+import { createHarnessResourcesReader } from '../lib/harnessResources.js'+import { createHarnessStorageReader } from '../lib/harnessTelemetry.js'import { hermesDbForSession } from '../lib/hermesHome.js'import { registry } from '../lib/registry.js'import { stoppedAgents } from '../lib/stoppedAgents.js'@@ -39,6 +41,18 @@ export function bindHistory(socket: BackendSocket): void {socket.sessionsProvider = history.sessionsList}+const monitors = new WeakMap<BackendSocket, Pick<AgentListDeps, 'harnessResourcesReader' | 'harnessStorageReader'>>()+/** The monitor's readers for a socket, one of each as the daemon's monitor service holds them+ * (services/monitor.ts): the list's readings and a purge's forgetting share them. */+function monitorOf(socket: BackendSocket): Pick<AgentListDeps, 'harnessResourcesReader' | 'harnessStorageReader'> {+ let monitor = monitors.get(socket)+ if (!monitor) {+ monitor = { harnessResourcesReader: createHarnessResourcesReader(() => registry.advertised()), harnessStorageReader: createHarnessStorageReader() }+ monitors.set(socket, monitor)+ }+ return monitor+}+/** `agents_list` (core/agents/list.ts). The daemon knows each agent's activity; a bare socket does not,* unless a spec says what it is. */export function bindAgentList(socket: BackendSocket, over: Partial<AgentListDeps> = {}): void {@@ -47,8 +61,7 @@ export function bindAgentList(socket: BackendSocket, over: Partial<AgentListDepsstoppedAgents,toProject: (s) => socket.toProject(s),toStoppedProject: (s) => socket.toStoppedProject(s),- harnessResourcesReader: () => socket.harnessResourcesReader(),- harnessStorageReader: (agents, invalidate) => socket.harnessStorageReader(agents, invalidate),+ ...monitorOf(socket),monitorActivityProvider: null,monitorCompletions: socket.monitorCompletions,...over,@@ -93,7 +106,7 @@ export function bindCloseRequests(socket: BackendSocket, cleanupPreview: () => P/** `agent_purge` and `agent_worktree_delete` (core/agents/lifecycle.ts), through the socket's own purge service. */export function bindPurgeRequest(socket: BackendSocket): void {- socket.purgeProvider = createPurgeRequest({ purgeAgentService: () => socket.purgeAgentService, invalidateStorage: () => { void socket.harnessStorageReader([], true) } })+ socket.purgeProvider = createPurgeRequest({ purgeAgentService: () => socket.purgeAgentService, invalidateStorage: () => { void monitorOf(socket).harnessStorageReader([], true) } })}/** `agent_update` (core/agents/update.ts). A bare socket moves no agent to another model and titles no pane. */