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.

Keep usage readers in the usage service (#1078)

Deeab26595e14f3
diff --git a/cli/e2e/usageProcess.e2e.ts b/cli/e2e/usageProcess.e2e.ts
new file mode 100644
index 000000000..840eaa48d
--- /dev/null
+++ b/cli/e2e/usageProcess.e2e.ts
@@ -0,0 +1,104 @@
+/** Aggregate reads never own readiness, turns or stopped work. Every process/file is a private fixture. */
+import { appendFileSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs'
+import { join, relative } from 'node:path'
+import { afterEach, expect, it, onTestFailed } from 'vitest'
+import { IsolatedDaemon, until } from './harness/daemon.js'
+import { LocalClient } from './harness/client.js'
+
+let daemon: IsolatedDaemon | undefined
+afterEach(async () => { await daemon?.close(); daemon = undefined })
+const row = async (client: LocalClient, id: string) =>
+ (await client.request('agents_list', { includeStopped: true }, 30_000)).agents.find((a: any) => a.id === id)
+const turn = async (client: LocalClient, id: string, content: string) => {
+ const ended = client.next(f => f.type === 'turn_ended' && f.agentId === id, 45_000, content)
+ client.send('message', { agentId: id, content }); await ended
+}
+const fresh = async (mode = 'usage', hold = false) => {
+ const d = daemon = await IsolatedDaemon.create({ env: { HARNESSD_SERVICES: mode,
+ HARNESSD_SERVICE_INITIAL_BACKOFF_MS: '200', HARNESSD_SERVICE_MAX_BACKOFF_MS: '1000' } })
+ const gate = join(d.root, 'usage-connect-hold')
+ d.env.HARNESSD_TEST_HOLD_CONNECT = `usage:${gate}`
+ if (hold) writeFileSync(gate, '')
+ onTestFailed(() => console.log(d.log().split('\n').slice(-150).join('\n')))
+ await d.start()
+ return { d, gate, client: await LocalClient.connect(d) }
+}
+const create = async (d: IsolatedDaemon, client: LocalClient, engine: 'claude' | 'codex') => {
+ const cwd = join(d.projectsDir, engine); mkdirSync(cwd)
+ const result = await client.request('agent_create', { engine, cwd, bypassPermission: true }, 60_000)
+ expect(result.error).toBeUndefined()
+ return until(`${engine} bound`, async () => {
+ const a = await row(client, result.agent.id)
+ return a?.sessionId && a.status === 'active' ? a : null
+ }, 60_000, 250)
+}
+const usage = async (d: IsolatedDaemon, agent: any, n = 1) => {
+ const path = await until('private transcript path attached', () => {
+ const registered = JSON.parse(readFileSync(join(d.dataDir, 'registry.json'), 'utf8')).find((r: any) => r.agentId === agent.id)
+ return typeof registered?.transcriptPath === 'string' ? registered.transcriptPath as string : null
+ }, 30_000, 100)
+ expect(typeof path).toBe('string')
+ expect(relative(d.root, path).startsWith('..')).toBe(false)
+ const timestamp = new Date().toISOString()
+ const entry = agent.engine === 'claude'
+ ? { type: 'assistant', timestamp, sessionId: agent.sessionId, message: { id: `usage-${n}`, role: 'assistant', content: [], usage: { input_tokens: 100, output_tokens: 20 } } }
+ : { type: 'event_msg', timestamp, payload: { type: 'token_count', info: { total_token_usage: { input_tokens: 100 * n, output_tokens: 20 * n, cached_input_tokens: 0 } } } }
+ appendFileSync(path, JSON.stringify(entry) + '\n')
+}
+const totals = async (client: LocalClient, id: string, expected: number) => until(`usage ${expected}`, async () =>
+ (await row(client, id))?.tokenUsage?.totalTokens === expected || null, 45_000, 250)
+const edge = (d: IsolatedDaemon) => Number([...d.log().matchAll(/\[harnessd\] service edge started \(pid (\d+)\)/g)].at(-1)![1])
+
+it('usage unavailable at boot never delays readiness or binding; recovery updates both engines and stopped work', async () => {
+ const { d, gate, client } = await fresh('usage', true)
+ const agents = [await create(d, client, 'claude'), await create(d, client, 'codex')]
+ for (const a of agents) {
+ await usage(d, a); await turn(client, a.id, 'usage can wait')
+ expect((await row(client, a.id)).tokenUsage).toBeNull()
+ }
+ expect(d.coresStarted()).toBe(1)
+ unlinkSync(gate)
+ for (const a of agents) await totals(client, a.id, 120)
+ writeFileSync(gate, '')
+ process.kill(edge(d), 'SIGKILL')
+ await until('usage disconnected', () => d.log().includes('[services] usage disconnected') || null, 20_000, 200)
+ for (const a of agents) {
+ await usage(d, a, 2); await turn(client, a.id, 'usage is gone again')
+ expect((await row(client, a.id)).tokenUsage?.totalTokens).toBe(120)
+ const stopped = await client.request('agent_delete', { agentId: a.id }, 30_000)
+ expect(stopped.error).toBeUndefined()
+ expect((await row(client, a.id)).status).toBe('stopped')
+ }
+ unlinkSync(gate)
+ for (const a of agents) {
+ await totals(client, a.id, 240)
+ expect((await row(client, a.id)).status).toBe('stopped')
+ }
+ expect(d.coresStarted()).toBe(1)
+ client.close()
+})
+
+it('a new core receives an unchanged warm worker snapshot', async () => {
+ const { d, client } = await fresh()
+ const a = await create(d, client, 'claude')
+ await usage(d, a); await totals(client, a.id, 120)
+ const worker = edge(d), before = d.corePid()!
+ const ready = [...d.log().matchAll(/\[cli\] ready/g)].length
+ client.close(); process.kill(before, 'SIGKILL')
+ await until('new core', () => d.corePid() !== before && d.coresStarted() >= 2 || null, 30_000, 250)
+ await until('new core ready', () => [...d.log().matchAll(/\[cli\] ready/g)].length > ready || null, 60_000, 250)
+ const next = await LocalClient.connect(d)
+ await totals(next, a.id, 120)
+ expect(edge(d)).toBe(worker)
+ await turn(next, a.id, 'after core restart')
+ next.close()
+})
+
+it('explicit inline usage follows the same aggregate boundary', async () => {
+ const { d, client } = await fresh('none')
+ const a = await create(d, client, 'codex')
+ await usage(d, a); await totals(client, a.id, 120)
+ await turn(client, a.id, 'inline remains usable')
+ expect(d.coresStarted()).toBe(1)
+ client.close()
+})
diff --git a/cli/scripts/handoff-2026-10-08/mutate-usage.py b/cli/scripts/handoff-2026-10-08/mutate-usage.py
new file mode 100644
index 000000000..eb99c33fd
--- /dev/null
+++ b/cli/scripts/handoff-2026-10-08/mutate-usage.py
@@ -0,0 +1,34 @@
+"""Break real usage contributions; the unchanged former-code golden must reject each by assertion."""
+import os
+from pathlib import Path
+import subprocess
+import sys
+
+cli = Path(sys.argv[1]).resolve()
+mutations = [
+ ('service result', 'src/services/agentUsage.ts', 'value: usageSnapshot(value)', 'value: null'),
+ ('session target', 'src/services/agentUsage.ts', 'cache.read(target)', "cache.read({ ...target, sessionId: 'miswired-conversation' })"),
+ ('fork cutoff', 'src/lib/agentUsageWire.ts', 'forkedFrom: s.forkedFrom ?', 'forkedFrom: false && s.forkedFrom ?'),
+ ('output snapshot', 'src/lib/agentUsageWire.ts', '...(v.output ? { output:', '...(false && v.output ? { output:'),
+ ('work snapshot', 'src/lib/agentUsageWire.ts', '...(v.work ? { work:', '...(false && v.work ? { work:'),
+ ('token snapshot', 'src/lib/agentUsageWire.ts', 'totalTokens: v.totalTokens, updatedAt:', 'totalTokens: null, updatedAt:'),
+]
+env = {**os.environ, 'TZ': 'UTC', 'TMPDIR': '/tmp'}
+env.pop('RECORD_USAGE_SHAPES', None)
+env.pop('TMUX', None)
+env.pop('TMUX_PANE', None)
+for name, file, before, after in mutations:
+ path = cli / file
+ original = path.read_text()
+ assert original.count(before) == 1, name
+ path.write_text(original.replace(before, after))
+ try:
+ result = subprocess.run(['node', 'node_modules/vitest/vitest.mjs', 'run', 'src/lib/usageShapes.golden.spec.ts', '--maxWorkers=1'],
+ cwd=cli, env=env, text=True, capture_output=True, timeout=90)
+ output = result.stdout + result.stderr
+ if result.returncode == 0 or 'AssertionError:' not in output or 'usageShapes.golden.spec.ts:' not in output:
+ print(output[-6000:])
+ raise SystemExit(f'{name}: not rejected by the golden assertion')
+ print(f'{name}: caught by unchanged golden', flush=True)
+ finally:
+ path.write_text(original)
diff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.ts
index a22917775..8b78f67e1 100644
--- a/cli/src/architecture.spec.ts
+++ b/cli/src/architecture.spec.ts
@@ -199,6 +199,8 @@ const EDGE: RegExp[] = [
/^lib\/(gridLaunch|gridWebMcp|apiModels|gridAssignment|apiConnections)\.ts$/,
// The change-agent handoff reads and redacts history and runs git: the edge host owns that work.
/^lib\/agentHandoff\.ts$/,
+ // Usage owns all aggregate readers and ledgers. Core reads validated wire snapshots only.
+ /^lib\/(agentTokenUsage|agentOutputStats|sessionWork)\.ts$/,
// The relay's own parts, the gateway's alone: the windows' sessions to other machines, P2P and STUN, the
// remote viewers' proxy, and the shaping of what goes up the link.
/^lib\/(remoteRelay|terminalP2p|stunSelect|remoteViewerProxy|deviceRecentTrim|commanderReplay)\.ts$/,
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index 8c195f6e0..338cf6aa7 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -1,3 +1,4 @@
+import { USAGE_FALLBACKS } from './core/api.js'
import * as gitPullRequest from './lib/gitPullRequest.js'
import * as sessionGitPullRequest from './lib/sessionGitPullRequest.js'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
@@ -1287,7 +1288,7 @@ describe('BackendSocket outbound queue', () => {
body: { seven_day: { utilization: 42 } },
},
]
- serveOn(socket, (host) => host.serve('usage', (core) => startUsage(core, { read: async () => readings }), fakeCore(), USAGE_REQUESTS))
+ serveOn(socket, (host) => host.start('usage', (core, ports) => { ports.usage = { read: async () => ({}), stop: () => {} }; return startUsage(core, { read: async () => readings }) }, fakeCore(), USAGE_FALLBACKS, USAGE_REQUESTS))
socket.connect()
const ws = wsMock.instances[0]
ws.open()
@@ -3473,7 +3474,7 @@ describe('the connect burst with no network', () => {
bindAgentList(socket)
// A grid name that never comes, as a grid read that never lands; and a vendor that never answers, asked
// of the usage service beside models.
- serveModels(socket, { account: { privateGridName: () => new Promise<null>(() => {}) } }).serve('usage', (core) => startUsage(core, { read: () => new Promise(() => {}) }), fakeCore(), USAGE_REQUESTS)
+ serveModels(socket, { account: { privateGridName: () => new Promise<null>(() => {}) } }).start('usage', (core, ports) => { ports.usage = { read: async () => ({}), stop: () => {} }; return startUsage(core, { read: () => new Promise(() => {}) }) }, fakeCore(), USAGE_FALLBACKS, 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.ts
index 9c9c4a597..057a87615 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -31,7 +31,7 @@ import type { ScmLaunchRecord } from './scm/types.js'
import { probeEngines } from './lib/engineProbe.js'
import { engineInstallRecipe } from './lib/engineInstall.js'
import { agentFrame, type AgentDshContext, type AgentFrame } from './lib/agentFrame.js'
-import { agentTokenUsage } from './lib/agentTokenUsage.js'
+import type { AgentTokenUsage } from './lib/agentUsageWire.js'
import { terminalHandoffRequest } from './lib/terminalHandoff.js'
import { OwnerCommands, OWNER_COMMAND_TYPES, ROUTE_COMMAND_TYPES } from './lib/ownerCommands.js'
import { VIEWER_DOWN_TYPES } from './lib/viewerFrames.js'
@@ -268,6 +268,7 @@ export class BackendSocket {
/** Answers `theme_set` with the whole reply: the desktop's pane colours, to become this machine's tmux
* `window-style` (cli.ts binds core/terminals/requests.ts). Null answers UNSUPPORTED. */
themeProvider: ((payload: Record<string, unknown>) => Record<string, unknown>) | null = null
+ tokenUsageProvider: ((session: RegisteredSession) => AgentTokenUsage | null) | null = null
runtimeProfileProvider: ((session: RegisteredSession) => string | null) | null = null
/** Backend-resolved machine id, persisted by the SSO login preflight. */
readonly machineId: string
@@ -1155,7 +1156,7 @@ export class BackendSocket {
/** A stopped agent's frame: no pane, no terminal, nothing to fork. */
async toStoppedProject(s: RegisteredSession): Promise<AgentFrame> {
const frame = await agentFrame(s, { selectedModel: s.model, terminalAvailable: false, dsh: this.dshFrameProvider?.(s) ?? null,
- tokenUsage: agentTokenUsage.get(s), gridAnnotation: this.gridAnnotation })
+ tokenUsage: this.tokenUsageProvider?.(s) ?? null, gridAnnotation: this.gridAnnotation })
return {
...frame,
status: 'stopped',
@@ -1169,7 +1170,7 @@ export class BackendSocket {
/** Map a registered tmux session onto the web's Project shape (tabs in ProjectTabs). */
toProject(s: RegisteredSession): Promise<AgentFrame> {
return agentFrame(s, {
- tokenUsage: agentTokenUsage.get(s),
+ tokenUsage: this.tokenUsageProvider?.(s) ?? null,
selectedModel: this.runtimeProfileProvider?.(s) ?? null,
terminalAvailable: registry.terminalAvailable(s.agentId),
dsh: this.dshFrameProvider?.(s) ?? null,
diff --git a/cli/src/core/agentQueries.spec.ts b/cli/src/core/agentQueries.spec.ts
index 74e9c85ab..387a40e61 100644
--- a/cli/src/core/agentQueries.spec.ts
+++ b/cli/src/core/agentQueries.spec.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest'
import type { RegisteredSession } from '../lib/registry.js'
import { fakeCore } from '../testing/fakeCore.js'
import { answerAgentQuery } from './agentQueries.js'
+import { usageTarget } from '../lib/agentUsageWire.js'
const agent = (agentId: string, over: Partial<RegisteredSession> = {}) => ({ agentId, sessionId: `s-${agentId}`, engine: 'claude', cwd: `/work/${agentId}`, ...over }) as RegisteredSession
@@ -22,4 +23,15 @@ describe('what a service in its own process may ask the core of the agents', ()
it('nothing else', () => {
expect(answerAgentQuery(core, 'credentials')).toEqual({ error: 'UNKNOWN_QUERY' })
})
+
+ it('returns usage only for the exact live or stopped read target', async () => {
+ const saved = agent('a', { transcriptPath: '/fixture/session', registeredAt: 1 })
+ const target = usageTarget(saved)
+ const core = fakeCore({ agents: { all: () => [saved] } })
+ expect(await answerAgentQuery(core, 'agentUsage')).toEqual({ error: 'STALE_USAGE_TARGET' })
+ expect(await answerAgentQuery(core, 'agentUsage', { target: { ...target, cwd: '/different' } })).toEqual({ error: 'STALE_USAGE_TARGET' })
+ expect(await answerAgentQuery(core, 'agentUsage', { target })).toEqual({ target, value: null })
+ core.usage = async () => ({ totalTokens: 4, updatedAt: '2026-10-01T00:00:00Z' })
+ expect(await answerAgentQuery(core, 'agentUsage', { target })).toMatchObject({ value: { totalTokens: 4 } })
+ })
})
diff --git a/cli/src/core/agentQueries.ts b/cli/src/core/agentQueries.ts
index 99c45bb74..db373ec51 100644
--- a/cli/src/core/agentQueries.ts
+++ b/cli/src/core/agentQueries.ts
@@ -1,3 +1,4 @@
+import { usageTargetKey, usageTarget, validUsageTarget } from '../lib/agentUsageWire.js'
/**
* What a service in its own process may ask the core of the agents (`service_query`, core/serviceLinks.ts)
* when it has no link module of its own to answer it (the viewers, workspaces and the teams do):
@@ -8,7 +9,12 @@
*/
import type { CoreApi } from './api.js'
-export function answerAgentQuery(core: Pick<CoreApi, 'agents'>, query: string): Record<string, unknown> {
+export function answerAgentQuery(core: Pick<CoreApi, 'agents' | 'usage'>, query: string, payload: Record<string, unknown> = {}): Record<string, unknown> | Promise<Record<string, unknown>> {
+ if (query === 'agentUsage') {
+ const target = payload.target
+ if (!validUsageTarget(target) || !core.agents.all().some(row => usageTargetKey(row) === usageTargetKey(target))) return { error: 'STALE_USAGE_TARGET' }
+ return Promise.resolve(core.usage?.(target) ?? null).then(value => ({ target: usageTarget(target), value }))
+ }
if (query === 'agents') return { agents: core.agents.all().map((session) => ({ ...session, displayName: core.agents.displayName(session) })) }
if (query === 'live') return { agents: core.agents.live() }
if (query === 'advertised') return { agents: core.agents.advertised() }
diff --git a/cli/src/core/agents/events.spec.ts b/cli/src/core/agents/events.spec.ts
index cc762d9e7..599289da3 100644
--- a/cli/src/core/agents/events.spec.ts
+++ b/cli/src/core/agents/events.spec.ts
@@ -4,7 +4,7 @@ import type { RegisteredSession } from '../../lib/registry.js'
import { createAgentEvents, type AgentEventDeps, type AnnounceSink } from './events.js'
const agent = (over: Partial<RegisteredSession> = {}): RegisteredSession =>
- ({ agentId: 'a1', sessionId: 's1', engine: 'claude', cwd: '/work/app', ...over }) as RegisteredSession
+ ({ agentId: 'a1', sessionId: 's1', engine: 'claude', cwd: '/work/app', transcriptPath: '/work/session.jsonl', registeredAt: 1, ...over }) as RegisteredSession
function sink() {
const app: Array<{ type: string; payload: Record<string, unknown> }> = []
@@ -83,7 +83,7 @@ describe('agent events', () => {
it('refreshes a live agent on the app alone when its token usage moves', async () => {
const out = sink()
- events({}, out.socket).onTokenUsageChanged({ agentId: 'a1', sessionId: 's1', engine: 'claude' })
+ events({}, out.socket).onTokenUsageChanged(agent({ agentId: 'a1', sessionId: 's1', engine: 'claude' }))
await settle()
expect(out.app.map((frame) => frame.type)).toEqual(['agent_synced'])
expect(out.dial).toEqual([])
@@ -91,7 +91,16 @@ describe('agent events', () => {
it('leaves a live agent whose pane is not available yet alone', async () => {
const out = sink()
- events({ terminalAvailable: () => false }, out.socket).onTokenUsageChanged({ agentId: 'a1', sessionId: 's1', engine: 'claude' })
+ events({ terminalAvailable: () => false }, out.socket).onTokenUsageChanged(agent({ agentId: 'a1', sessionId: 's1', engine: 'claude' }))
+ await settle()
+ expect(out.app).toEqual([])
+ })
+
+ it('does not publish an old usage target after a path, profile, fork or registration change', async () => {
+ const out = sink()
+ const announce = events({}, out.socket)
+ for (const old of [{ transcriptPath: '/older' }, { cwd: '/older' }, { codexHome: '/older' },
+ { registeredAt: 0 }, { forkedFrom: { agentId: 'parent', name: 'Parent' } }]) announce.onTokenUsageChanged(agent(old))
await settle()
expect(out.app).toEqual([])
})
@@ -100,12 +109,12 @@ describe('agent events', () => {
const out = sink()
const saved = agent({ agentId: 'a2', sessionId: 's2' })
const announce = events({ stopped: (agentId) => agentId === 'a2' ? saved : null }, out.socket)
- announce.onTokenUsageChanged({ agentId: 'a2', sessionId: 's2', engine: 'claude' })
+ announce.onTokenUsageChanged(agent({ agentId: 'a2', sessionId: 's2', engine: 'claude' }))
// Another session of the same agent, or an engine it no longer runs: not this record.
- announce.onTokenUsageChanged({ agentId: 'a2', sessionId: 'older', engine: 'claude' })
- announce.onTokenUsageChanged({ agentId: 'a2', sessionId: 's2', engine: 'codex' })
+ announce.onTokenUsageChanged(agent({ agentId: 'a2', sessionId: 'older', engine: 'claude' }))
+ announce.onTokenUsageChanged(agent({ agentId: 'a2', sessionId: 's2', engine: 'codex' }))
// The live agent's earlier session: not live, and not archived either.
- announce.onTokenUsageChanged({ agentId: 'a1', sessionId: 'older', engine: 'claude' })
+ announce.onTokenUsageChanged(agent({ agentId: 'a1', sessionId: 'older', engine: 'claude' }))
await settle()
expect(out.published).toEqual(['a2'])
expect(out.app).toEqual([])
@@ -114,11 +123,11 @@ describe('agent events', () => {
it('shrugs off a stopped record that is being removed, or a publish that fails', async () => {
const out = sink()
events({ stopped: () => { throw new Error('archive moved') } }, out.socket)
- .onTokenUsageChanged({ agentId: 'a2', sessionId: 's2', engine: 'claude' })
+ .onTokenUsageChanged(agent({ agentId: 'a2', sessionId: 's2', engine: 'claude' }))
out.failPublish()
const saved = agent({ agentId: 'a2', sessionId: 's2' })
- events({ stopped: () => saved }, out.socket).onTokenUsageChanged({ agentId: 'a2', sessionId: 's2', engine: 'claude' })
- events({ stopped: () => saved }).onTokenUsageChanged({ agentId: 'a2', sessionId: 's2', engine: 'claude' })
+ events({ stopped: () => saved }, out.socket).onTokenUsageChanged(agent({ agentId: 'a2', sessionId: 's2', engine: 'claude' }))
+ events({ stopped: () => saved }).onTokenUsageChanged(agent({ agentId: 'a2', sessionId: 's2', engine: 'claude' }))
await settle()
expect(out.published).toEqual(['a2'])
})
diff --git a/cli/src/core/agents/events.ts b/cli/src/core/agents/events.ts
index f0894822a..c74ecf27e 100644
--- a/cli/src/core/agents/events.ts
+++ b/cli/src/core/agents/events.ts
@@ -1,3 +1,4 @@
+import { usageTargetKey, type AgentUsageTarget } from '../../lib/agentUsageWire.js'
/**
* Telling the app and the dial about an agent: its frame (sync), its name (rename), both at once
* (announce), and a fresh frame when its token usage moves, for a live agent or a stopped one.
@@ -20,7 +21,7 @@ export interface AnnounceSink {
}
/** The agent whose token usage changed, as the usage cache names it. */
-export type TokenUsageTarget = Pick<RegisteredSession, 'agentId' | 'sessionId' | 'engine'>
+export type TokenUsageTarget = AgentUsageTarget
export interface AgentEventDeps {
/** The socket, read as each frame goes out; undefined until it exists. */
@@ -48,13 +49,13 @@ export function createAgentEvents({ sink, terminalAvailable, resolve, stopped, p
}
const onTokenUsageChanged = (target: TokenUsageTarget): void => {
const current = resolve(target.agentId)
- if (current?.sessionId === target.sessionId && current.engine === target.engine) {
+ if (current && usageTargetKey(current) === usageTargetKey(target)) {
if (terminalAvailable(current.agentId)) syncSession(current, { device: false })
return
}
try {
const saved = stopped(target.agentId)
- if (saved?.sessionId === target.sessionId && saved.engine === target.engine) {
+ if (saved && usageTargetKey(saved) === usageTargetKey(target)) {
void sink()?.publishStoppedAgent(saved).catch(() => {})
}
} catch { /* A concurrently removed archive has nothing to update. */ }
diff --git a/cli/src/core/api.spec.ts b/cli/src/core/api.spec.ts
index c93c8d987..34a7c5bd3 100644
--- a/cli/src/core/api.spec.ts
+++ b/cli/src/core/api.spec.ts
@@ -252,7 +252,7 @@ describe('the core API services stand on', () => {
})
it('starts with every port empty: a service fills its own when it starts', () => {
- expect(emptyPorts()).toEqual({ store: null, search: null, viewers: null, models: null, workspaces: null, teams: null, devices: null, wifi: null, monitor: null, orchestrator: null, sharing: null, recaps: null })
+ expect(emptyPorts()).toEqual({ usage: null, store: null, search: null, viewers: null, models: null, workspaces: null, teams: null, devices: null, wifi: null, monitor: null, orchestrator: null, sharing: null, recaps: null })
expect(emptyPorts()).not.toBe(emptyPorts())
})
diff --git a/cli/src/core/api.ts b/cli/src/core/api.ts
index 8d5b7aff6..3cb781f96 100644
--- a/cli/src/core/api.ts
+++ b/cli/src/core/api.ts
@@ -1,3 +1,4 @@
+import type { AgentTokenUsage, AgentUsageTarget } from '../lib/agentUsageWire.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"):
@@ -107,7 +108,15 @@ export const CONVERSATIONS_OFF: ConversationReads = {
transcriptOk: async () => false,
}
+export interface UsagePort {
+ read(target: AgentUsageTarget): Promise<Record<string, unknown>>
+ stop(): void
+}
+export const USAGE_FALLBACKS: PortFallbacks<UsagePort> = { read: later(FAIL), stop: undefined }
+
export interface CoreApi {
+ /** Last aggregate observation, never a transcript read. Optional for services that do not ask. */
+ usage?: (target: AgentUsageTarget) => Promise<AgentTokenUsage | null>
/** The daemon's data folder; a service keeps its own files in it. */
dataDir: string
terminals: TerminalsPort
@@ -1301,6 +1310,7 @@ export const STORE_OFF: StorePort = {
/** Each port is filled by the service that owns it when that service starts, and is null while the
* service is off: the core never waits on one. */
export interface CorePorts {
+ usage: UsagePort | null
store: StorePort | null
search: SearchPort | null
viewers: ViewersPort | null
@@ -1316,7 +1326,7 @@ export interface CorePorts {
}
export function emptyPorts(): CorePorts {
- return { store: null, search: null, viewers: null, models: null, workspaces: null, teams: null, devices: null, wifi: null, monitor: null, orchestrator: null, sharing: null, recaps: null }
+ return { usage: null, store: null, search: null, viewers: null, models: null, workspaces: null, teams: null, devices: null, wifi: null, monitor: null, orchestrator: null, sharing: null, recaps: null }
}
export interface CoreApiDeps {
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index 22541d7a4..f44f8fe80 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -146,7 +146,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 { COMMAND_BAR_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, TEAMS_FALLBACKS, TEAMS_REQUESTS, USAGE_REQUESTS, VIEWERS_FALLBACKS, WIFI_FALLBACKS, WINDOW_NAMES_REQUESTS, WORKSPACES_FALLBACKS, type GatewayAccount, type GatewayOps, type GatewayStatus, type RouteAnswer, type TeamsPort, type WindowFocus } from './api.js'
+import { COMMAND_BAR_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, TEAMS_FALLBACKS, TEAMS_REQUESTS, USAGE_FALLBACKS, USAGE_REQUESTS, VIEWERS_FALLBACKS, WIFI_FALLBACKS, WINDOW_NAMES_REQUESTS, WORKSPACES_FALLBACKS, type GatewayAccount, type GatewayOps, type GatewayStatus, type RouteAnswer, type TeamsPort, type WindowFocus } from './api.js'
import { createServiceHost, testFaults } from './serviceHost.js'
import { startStalls } from './stall.js'
import { createServiceLinks, type ServiceLinks } from './serviceLinks.js'
@@ -194,7 +194,9 @@ import { TranscriptPager } from '../lib/transcriptPages.js'
import { AgentCreationReceipts } from '../lib/agentCreationReceipt.js'
import { agentFrame, lastActivityAt, type AgentFrame } from '../lib/agentFrame.js'
import { forgetAgentProject } from '../lib/agentProject.js'
-import { agentTokenUsage } from '../lib/agentTokenUsage.js'
+import { createUsageLink } from './usageLink.js'
+import type { UsageSnapshots } from './usageLink.js'
+import type { AgentUsageTarget } from '../lib/agentUsageWire.js'
import { LegacyRuntimeProfileManager, type RuntimeModelOption } from '../lib/runtimeProfileManager.js'
import { createRuntimeProfiles } from './engines/runtimeProfiles.js'
import { createRuntimeTransport } from './engines/runtimeTransport.js'
@@ -352,12 +354,15 @@ let activityFrameContextRef: ((s: RegisteredSession) => ActivityFrame | null) |
let dshFrameContextRef: ((s: RegisteredSession) => AgentDshContext | null) | null = null
+/** Aggregate snapshots only; populated after the optional usage port is composed. */
+let usagePortRef: UsageSnapshots | null = null
+
/** Set by runForeground once models can be asked: what an agent's frame says of its grid. */
let gridAnnotationRef: ((grid: AgentGridTarget) => GridAnnotation | null) | null = null
function projectFrame(s: RegisteredSession, selectedModel: string | null): Promise<AgentFrame> {
return agentFrame(s, {
- tokenUsage: agentTokenUsage.get(s),
+ tokenUsage: usagePortRef?.get(s) ?? null,
selectedModel,
terminalAvailable: registry.terminalAvailable(s.agentId),
dsh: dshFrameContextRef?.(s) ?? null,
@@ -653,7 +658,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {
})
const syncSession = agentEvents.syncSession
const announceRename = agentEvents.announceRename
- agentTokenUsage.onChanged = agentEvents.onTokenUsageChanged
const announceSession = agentEvents.announceSession
// Conversations on this machine that Harness did not start, found where each engine keeps them so
@@ -1252,6 +1256,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// What the core tells the recaps in their own process, and reads back from what they said (core/recapsLink.ts).
const recapsLink = createRecapsLink({ notify: (frame, opts) => serviceLinks.notify('recaps', frame, opts), buffered: () => serviceLinks.buffered('recaps'),
call: (type, payload) => serviceLinks.call('recaps', type, payload), clients: coreApi.clients, lastTurn: coreApi.transcripts.lastTurn })
+ const usageLink = createUsageLink({ call: payload => ports.usage?.read(payload.target as AgentUsageTarget) ?? Promise.resolve({}), changed: agentEvents.onTokenUsageChanged })
const serviceLinks = createServiceLinks({
token: serviceToken,
owned: Object.fromEntries([...outOfProcess].map((name) => [name, requestsOf[name] ?? []])),
@@ -1275,7 +1280,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
: service === 'wifi' ? wifiLink.answer(query, payload)
: service === 'handoff' ? answerConversationQuery(coreApi, query, payload)
: service === 'shell' ? answerShellQuery(coreApi, query, payload)
- : service === 'recaps' ? recapsLink.answer(query, payload) : answerAgentQuery(coreApi, query)),
+ : service === 'recaps' ? recapsLink.answer(query, payload) : answerAgentQuery(coreApi, query, payload)),
// The gateway's own traffic: its remote clients and what they sent, and its comings and goings; and what
// the devices tell the core (a turn, a frame for the windows, a dial on the wire); a viewer stream's answers.
notice: (service, payload) => { if (service === 'gateway') gatewayLink?.notice(payload); else if (service === 'devices') devicesLink.notice(payload); else if (service === 'wifi') wifiLink.notice(payload); else if (service === 'viewers') viewersLink.notice(payload); else if (service === 'recaps') recapsLink.notice(payload) },
@@ -1290,6 +1295,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
engineLinks.connected(service)
modelControls.connected(service)
questionControls.connected(service)
+ if (service === 'usage') usageLink.connected()
if (service === 'gateway') gatewayLink?.connected()
if (service === 'teams') teamsLink.on()
if (service === 'devices') devicesLink.connected()
@@ -1299,6 +1305,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
void heldLaunches.restoreHeld(service)
},
disconnected: (service) => {
+ if (service === 'usage') usageLink.disconnected()
engineReaders.disconnected(service)
liveTransport.disconnected(service)
runtimeTransport.disconnected(service)
@@ -1361,7 +1368,12 @@ async function runForeground(session: AuthSession | null): Promise<void> {
else serviceHost.start('store', (core, installedPorts) => inline!.startStoreInCore(core, installedPorts, () => { void heldLaunches.restoreHeld('store') }), coreApi, STORE_FALLBACKS, STORE_REQUESTS)
// This machine's Claude and Codex rate limits, read with its own credentials (services/usage.ts): in this
// process, or in the edge host (services/usageProcess.ts).
- if (!outOfProcess.has('usage')) serviceHost.serve('usage', inline!.startUsage, coreApi, USAGE_REQUESTS)
+ if (outOfProcess.has('usage')) ports.usage = { read: target => serviceLinks.call('usage', 'agentUsage', { target }), stop: () => {} }
+ else serviceHost.start('usage', inline!.startUsageInCore, coreApi, USAGE_FALLBACKS, USAGE_REQUESTS)
+ usagePortRef = usageLink.port
+ backend.tokenUsageProvider = target => usageLink.port.get(target)
+ coreApi.usage = target => usageLink.readSnapshot(target, coreApi.agents.all())
+
// This machine's and each agent's resources, for the Monitor and the list's readings (services/monitor.ts):
// in this process, or in the edge host (services/monitorProcess.ts), asked through its port (core/monitorLink.ts).
if (outOfProcess.has('monitor')) ports.monitor = createMonitorLink((type, payload) => serviceLinks.call('monitor', type, payload))
@@ -1439,7 +1451,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// Everything the funnel feeds exists now: install it, and deliver what waited.
funnel.arm({
bySession: (sessionId) => registry.bySession(sessionId),
- tokenUsage: agentTokenUsage,
+ tokenUsage: { changed: target => usageLink.port.changed(target) },
agentIdFor,
turnActivity,
isSubagentSession,
@@ -1897,7 +1909,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
liveFor,
has: (sessionId) => registry.has(sessionId),
bySession: (sessionId) => registry.bySession(sessionId),
- tokenUsage: agentTokenUsage,
+ tokenUsage: { changed: target => usageLink.port.changed(target) },
device: () => wifiCore.feed,
runtimeProfiles,
normalizers,
@@ -2449,6 +2461,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// next daemon's dial, and esptool, fail as if the hardware had died.
['the devices', () => ports.devices?.stop()],
// The successor starts its own viewers for the agents it restores; ours must not hold the ports.
+ ['usage observations', () => { usageLink.port.stop(); ports.usage?.stop() }],
['the viewers', () => ports.viewers?.stop()], ['the gateway', () => gateway.stop()],
// A graceful close releases the backend's one-machine claim, given a moment before the reclaim.
['the backend', () => backend.stop()], ['a grace', () => new Promise((r) => setTimeout(r, 1000))],
@@ -2498,6 +2511,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
await localWsServer.close()
hookServer.close()
nativeControls.close()
+ usageLink.port.stop(); ports.usage?.stop()
await ports.viewers?.stop()
await gateway.stop()
await backend.stop()
diff --git a/cli/src/core/usageLink.spec.ts b/cli/src/core/usageLink.spec.ts
new file mode 100644
index 000000000..d8f9647e8
--- /dev/null
+++ b/cli/src/core/usageLink.spec.ts
@@ -0,0 +1,153 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { createUsageLink } from './usageLink.js'
+import { usageTarget, type AgentUsageTarget } from '../lib/agentUsageWire.js'
+
+const target = usageTarget({ agentId: 'a', sessionId: 's', engine: 'claude', transcriptPath: '/fixture/a.jsonl', registeredAt: 1, cwd: '/fixture' })
+const value = { totalTokens: 12, updatedAt: '2026-10-01T00:00:00Z' }
+const deferred = <T>() => { let resolve!: (v: T) => void; const promise = new Promise<T>(r => { resolve = r }); return { promise, resolve } }
+
+describe('usage snapshots across the optional service', () => {
+ afterEach(() => vi.useRealTimers())
+
+ it('publishes progress throughout continuous transcript changes instead of starving the reading', async () => {
+ vi.useFakeTimers()
+ let now = 0
+ const pending: Array<ReturnType<typeof deferred<Record<string, unknown>>>> = []
+ const link = createUsageLink({ call: () => { const task = deferred<Record<string, unknown>>(); pending.push(task); return task.promise }, changed: vi.fn(), now: () => now })
+ link.port.changed(target)
+ for (let round = 0; round < 4; round++) {
+ await Promise.resolve()
+ for (let second = 0; second < 16; second++) {
+ now += 1000; link.port.changed(target); await vi.advanceTimersByTimeAsync(1000)
+ }
+ pending[round].resolve({ target, value: { ...value, totalTokens: round + 1 } })
+ await Promise.resolve(); await Promise.resolve()
+ expect(link.port.get(target)?.totalTokens).toBe(round + 1)
+ await Promise.resolve(); await Promise.resolve()
+ }
+ link.port.stop()
+ for (const task of pending) task.resolve({ target, value })
+ await link.settled()
+ })
+
+ it('serves copied snapshots to inline services for exact rows with omitted optional fields', async () => {
+ const raw: AgentUsageTarget = { agentId: 'a', sessionId: 's', engine: 'claude', transcriptPath: '/fixture/a.jsonl', registeredAt: 1, cwd: '/fixture' }
+ const link = createUsageLink({ call: async payload => ({ ...payload, value }), changed: vi.fn() })
+ expect(await link.readSnapshot(raw, [raw])).toBeNull()
+ await link.settled()
+ const copy = await link.readSnapshot(raw, [raw])
+ expect(copy).toEqual(value)
+ copy!.totalTokens = 99
+ expect(link.port.get(raw)).toEqual(value)
+ expect(await link.readSnapshot(raw, [{ ...raw, registeredAt: 2 }])).toBeNull()
+ link.port.stop()
+ })
+
+ it('reads memory on a cold frame, validates replies, keeps outages from changing a warm value, and never polls', async () => {
+ const changed = vi.fn(), call = vi.fn(async (payload: Record<string, unknown>) => ({ ...payload, value }))
+ let now = 0
+ const link = createUsageLink({ call, changed, now: () => now })
+ expect(link.port.get(target)).toBeNull()
+ await link.settled()
+ expect(link.port.get(target)).toEqual(value)
+ expect(changed).toHaveBeenCalledWith(target)
+ for (let i = 0; i < 100; i++) link.port.get(target)
+ expect(call).toHaveBeenCalledOnce()
+ const bad = [{ error: 'SERVICE_UNAVAILABLE' }, { target, value: { totalTokens: -1 } }, { target: { ...target, cwd: '/other' }, value }]
+ for (const answer of bad) {
+ call.mockResolvedValueOnce(answer as never)
+ now += 20_000; link.port.changed(target); await link.settled()
+ expect(link.port.get(target)).toEqual(value)
+ }
+ call.mockRejectedValueOnce(new Error('worker crashed'))
+ now += 20_000; link.port.changed(target); await link.settled()
+ expect(link.port.get(target)).toEqual(value)
+ now += 20_000; link.port.changed(target); await link.settled()
+ expect(changed).toHaveBeenCalledOnce()
+ call.mockResolvedValueOnce({ target, value: null } as never)
+ now += 20_000; link.port.changed(target); await link.settled()
+ expect(link.port.get(target)).toBeNull()
+ expect(changed).toHaveBeenCalledTimes(2)
+ link.port.stop()
+ expect(link.port.get(target)).toBeNull()
+ link.port.changed(target); link.connected()
+ })
+
+ it('refreshes warm workers after reconnect and drops old connections, rebinds, and retains progress when newer transcript events arrive', async () => {
+ const pending: Array<{ payload: Record<string, unknown>; done: ReturnType<typeof deferred<Record<string, unknown>>> }> = []
+ const link = createUsageLink({ call: payload => { const done = deferred<Record<string, unknown>>(); pending.push({ payload, done }); return done.promise }, changed: vi.fn(), now: () => 0 })
+ const tick = async () => { await Promise.resolve(); await Promise.resolve() }
+ link.port.get(target); await tick()
+ link.connected(); await tick()
+ pending[0].done.resolve({ target, value }); await tick()
+ expect(link.port.get(target)).toBeNull()
+ pending[1].done.resolve({ target, value }); await link.settled()
+ expect(link.port.get(target)).toEqual(value)
+ const rebound = { ...target, transcriptPath: '/fixture/other.jsonl', codexHome: '/fixture/profile', registeredAt: 2 }
+ expect(link.port.get(rebound)).toBeNull(); await tick()
+ const newer = { ...rebound, sessionId: 'new' }
+ expect(link.port.get(newer)).toBeNull(); await tick()
+ pending[2].done.resolve({ target: rebound, value }); await tick()
+ expect(link.port.get(newer)).toBeNull()
+ vi.useFakeTimers()
+ link.port.changed(newer)
+ pending[3].done.resolve({ target: newer, value }); await tick()
+ expect(link.port.get(newer)).toEqual(value)
+ await vi.advanceTimersByTimeAsync(15_000)
+ expect(pending).toHaveLength(5)
+ pending[4].done.resolve({ target: newer, value }); await link.settled()
+ expect(link.port.get(newer)).toEqual(value)
+ link.port.changed(newer)
+ link.disconnected()
+ expect(vi.getTimerCount()).toBe(0)
+ expect(link.port.get(newer)).toEqual(value)
+ link.connected(); await tick()
+ link.port.stop()
+ pending[5].done.resolve({ target: newer, value: null }); await link.settled()
+ })
+
+ it('coalesces bursts into one bounded delayed read, copies inputs, and cancels timers on replacement and stop', async () => {
+ vi.useFakeTimers()
+ let now = 0
+ const call = vi.fn(async (payload: Record<string, unknown>) => ({ ...payload, value }))
+ const link = createUsageLink({ call, changed: vi.fn(), now: () => now })
+ link.port.changed(target); await link.settled()
+ for (let i = 0; i < 50; i++) link.port.changed(target)
+ expect(vi.getTimerCount()).toBe(1)
+ now = 15_000; await vi.advanceTimersByTimeAsync(15_000); await link.settled()
+ expect(call).toHaveBeenCalledTimes(2)
+ now = 29_900; link.port.changed(target)
+ now = 30_400; await vi.advanceTimersByTimeAsync(500); await link.settled()
+ expect(call).toHaveBeenCalledTimes(3)
+ link.port.changed(target)
+ link.port.get({ ...target, cwd: '/fixture/rebound' }); await link.settled()
+ expect(vi.getTimerCount()).toBe(0)
+ link.port.changed({ ...target, cwd: '/fixture/rebound' })
+ link.port.stop()
+ expect(vi.getTimerCount()).toBe(0)
+ expect(link.port.get({ ...target, engine: 'hermes' })).toBeNull()
+ })
+
+ it('bounds interests and concurrent reads, evicting old identities without accepting their replies', async () => {
+ const release = deferred<void>()
+ let running = 0, maximum = 0
+ const call = vi.fn(async (payload: Record<string, unknown>) => {
+ running++; maximum = Math.max(maximum, running)
+ await release.promise
+ running--
+ return { ...payload, value }
+ })
+ const link = createUsageLink({ call, changed: vi.fn() })
+ expect(link.port.get({ ...target, sessionId: '' })).toBeNull()
+ link.port.changed({ ...target, engine: 'hermes' })
+ for (let i = 0; i < 520; i++) link.port.get({ ...target, agentId: `agent-${i}` })
+ await Promise.resolve()
+ expect(call).toHaveBeenCalledTimes(4)
+ release.resolve(); await link.settled()
+ expect(maximum).toBe(4)
+ expect(link.port.get({ ...target, agentId: 'agent-519' })).toEqual(value)
+ expect(link.port.get({ ...target, agentId: 'agent-0' })).toBeNull()
+ await link.settled()
+ link.port.stop()
+ })
+})
diff --git a/cli/src/core/usageLink.ts b/cli/src/core/usageLink.ts
new file mode 100644
index 000000000..298f50527
--- /dev/null
+++ b/cli/src/core/usageLink.ts
@@ -0,0 +1,116 @@
+/** Usage is observational: frames read memory, and bounded requests refresh it off the control path. */
+import { usageSnapshot, usageTarget, usageTargetKey, validUsage, validUsageTarget, USAGE_LIMIT, USAGE_REFRESH_MS,
+ type AgentTokenUsage, type AgentUsageTarget } from '../lib/agentUsageWire.js'
+export interface UsageSnapshots {
+ get(target: AgentUsageTarget): AgentTokenUsage | null
+ changed(target: AgentUsageTarget): void
+ stop(): void
+}
+
+interface Entry {
+ target: AgentUsageTarget
+ value: AgentTokenUsage | null
+ checked: number
+ dirty: boolean
+ pending: boolean
+ timer?: ReturnType<typeof setTimeout>
+}
+
+export function createUsageLink(options: {
+ call(payload: Record<string, unknown>): Promise<Record<string, unknown>>
+ changed(target: AgentUsageTarget): void
+ now?: () => number
+}) {
+ const entries = new Map<string, Entry>()
+ const tasks = new Set<Promise<void>>()
+ let epoch = 0, running = 0, stopped = false
+ const now = options.now ?? Date.now
+ const signal = (v: AgentTokenUsage | null) => JSON.stringify(v && [v.totalTokens, v.output, v.work])
+ const remove = (id: string, entry: Entry) => {
+ if (entry.timer) clearTimeout(entry.timer)
+ entries.delete(id)
+ }
+ const drain = () => {
+ if (stopped) return
+ for (const [id, entry] of entries) {
+ if (running >= 4) break
+ if (!entry.dirty || entry.pending) continue
+ entry.dirty = false; entry.pending = true; entry.checked = now()
+ const generation = epoch, target = usageTarget(entry.target)
+ running++
+ const task = Promise.resolve().then((): Record<string, unknown> | Promise<Record<string, unknown>> => stopped ? {} : options.call({ target })).then(answer => {
+ if (stopped || generation !== epoch || entries.get(id) !== entry
+ || !validUsageTarget(answer.target) || usageTargetKey(answer.target) !== usageTargetKey(target) || !validUsage(answer.value)) return
+ const value = usageSnapshot(answer.value)
+ const changed = signal(entry.value) !== signal(value)
+ entry.value = value
+ if (changed) options.changed(target)
+ }).catch(() => { /* A failed observation changes no session state or last good value. */ }).finally(() => {
+ tasks.delete(task)
+ if (generation !== epoch) return
+ running--; entry.pending = false
+ drain()
+ })
+ tasks.add(task)
+ }
+ }
+ const interest = (source: AgentUsageTarget): Entry | null => {
+ if (stopped) return null
+ const target = usageTarget(source)
+ if (!validUsageTarget(target)) return null
+ const previous = entries.get(target.agentId)
+ if (previous && usageTargetKey(previous.target) === usageTargetKey(target)) return previous
+ if (previous) remove(target.agentId, previous)
+ if (entries.size >= USAGE_LIMIT) {
+ const oldest = entries.entries().next().value!
+ remove(...oldest)
+ }
+ const entry: Entry = { target, value: null, checked: -Infinity, pending: false, dirty: true }
+ entries.set(target.agentId, entry)
+ drain()
+ return entry
+ }
+ const refresh = (entry: Entry) => { entry.dirty = true; drain() }
+ const port: UsageSnapshots = {
+ get: target => interest(target)?.value ?? null,
+ changed: target => {
+ const previous = entries.get(target.agentId)
+ const entry = interest(target)
+ if (!entry || entry !== previous || entry.timer) return
+ // One request per immutable target preserves order. New transcript events schedule a later
+ // refresh, never discard useful progress from a read already in flight.
+ if (now() - entry.checked >= USAGE_REFRESH_MS) { refresh(entry); return }
+ entry.timer = setTimeout(() => {
+ entry.timer = undefined
+ entry.dirty = true
+ drain()
+ }, Math.max(500, USAGE_REFRESH_MS - (now() - entry.checked)))
+ entry.timer.unref()
+ },
+ stop: () => {
+ stopped = true; epoch++
+ for (const [id, entry] of entries) remove(id, entry)
+ },
+ }
+ const disconnected = () => {
+ epoch++; running = 0
+ for (const entry of entries.values()) {
+ if (entry.timer) clearTimeout(entry.timer)
+ entry.timer = undefined; entry.pending = false; entry.dirty = false
+ }
+ }
+ return {
+ port,
+ disconnected,
+ /** Services receive only a copy for a current owned target. Raw registry rows may omit nullable fields. */
+ readSnapshot: async (target: AgentUsageTarget, current: readonly AgentUsageTarget[]) =>
+ current.some(row => usageTargetKey(row) === usageTargetKey(target)) ? usageSnapshot(port.get(target)) : null,
+ connected: () => {
+ disconnected()
+ for (const entry of entries.values()) entry.dirty = true
+ drain()
+ },
+ /** Deterministic observation tests only. Frames and readiness never await this. */
+ settled: async () => { while (tasks.size) await Promise.all(tasks) },
+ }
+}
diff --git a/cli/src/lib/__fixtures__/usage-shapes.golden.json b/cli/src/lib/__fixtures__/usage-shapes.golden.json
new file mode 100644
index 000000000..c9d9f40ae
--- /dev/null
+++ b/cli/src/lib/__fixtures__/usage-shapes.golden.json
@@ -0,0 +1,518 @@
+{
+ "darwin": {
+ "cold": null,
+ "missing": null,
+ "streaming-and-foreign": {
+ "totalTokens": 420,
+ "updatedAt": "2026-10-01T00:01:00.000Z",
+ "inputTokens": 380,
+ "outputTokens": 40,
+ "cachedTokens": 160
+ },
+ "partial": {
+ "totalTokens": 420,
+ "updatedAt": "2026-10-01T00:01:30.000Z",
+ "inputTokens": 380,
+ "outputTokens": 40,
+ "cachedTokens": 160
+ },
+ "completed": {
+ "totalTokens": 630,
+ "updatedAt": "2026-10-01T00:02:00.000Z",
+ "inputTokens": 570,
+ "outputTokens": 60,
+ "cachedTokens": 240
+ },
+ "output-and-work": {
+ "totalTokens": 630,
+ "updatedAt": "2026-10-01T00:02:30.000Z",
+ "inputTokens": 570,
+ "outputTokens": 60,
+ "cachedTokens": 240,
+ "output": {
+ "linesAdded": 2,
+ "linesRemoved": 0,
+ "pullRequestsCreated": 1
+ },
+ "work": {
+ "current": [
+ {
+ "cwd": "/fixture/work",
+ "at": "2026-10-01T00:00:00.000Z"
+ }
+ ],
+ "locations": [
+ {
+ "cwd": "/fixture/work",
+ "at": "2026-10-01T00:00:00.000Z"
+ }
+ ],
+ "pullRequests": [
+ {
+ "url": "https://github.com/example/project/pull/42",
+ "cwd": "/fixture/work",
+ "at": "2026-10-01T00:00:00.000Z"
+ }
+ ],
+ "uncertain": false,
+ "truncated": false
+ }
+ },
+ "unreadable-keeps-last": {
+ "totalTokens": 630,
+ "updatedAt": "2026-10-01T00:02:30.000Z",
+ "inputTokens": 570,
+ "outputTokens": 60,
+ "cachedTokens": 240,
+ "output": {
+ "linesAdded": 2,
+ "linesRemoved": 0,
+ "pullRequestsCreated": 1
+ },
+ "work": {
+ "current": [
+ {
+ "cwd": "/fixture/work",
+ "at": "2026-10-01T00:00:00.000Z"
+ }
+ ],
+ "locations": [
+ {
+ "cwd": "/fixture/work",
+ "at": "2026-10-01T00:00:00.000Z"
+ }
+ ],
+ "pullRequests": [
+ {
+ "url": "https://github.com/example/project/pull/42",
+ "cwd": "/fixture/work",
+ "at": "2026-10-01T00:00:00.000Z"
+ }
+ ],
+ "uncertain": false,
+ "truncated": false
+ }
+ },
+ "rewritten-keeps-history": {
+ "totalTokens": 410,
+ "updatedAt": "2026-10-01T00:03:30.000Z",
+ "inputTokens": 390,
+ "outputTokens": 20,
+ "cachedTokens": 80,
+ "work": {
+ "current": [],
+ "locations": [
+ {
+ "cwd": "/fixture/work",
+ "at": "2026-10-01T00:00:00.000Z"
+ }
+ ],
+ "pullRequests": [
+ {
+ "url": "https://github.com/example/project/pull/42",
+ "cwd": "/fixture/work",
+ "at": "2026-10-01T00:00:00.000Z"
+ }
+ ],
+ "uncertain": true,
+ "truncated": false
+ }
+ },
+ "rebound-does-not-borrow": null,
+ "unsupported": null,
+ "fork": {
+ "totalTokens": 330,
+ "updatedAt": "2026-10-01T00:05:00.000Z",
+ "inputTokens": 290,
+ "outputTokens": 40,
+ "cachedTokens": 80
+ },
+ "codex-deltas": {
+ "totalTokens": 250,
+ "updatedAt": "2026-10-01T00:05:30.000Z",
+ "inputTokens": 200,
+ "outputTokens": 50,
+ "cachedTokens": 100
+ },
+ "codex-append": {
+ "totalTokens": 380,
+ "updatedAt": "2026-10-01T00:06:00.000Z",
+ "inputTokens": 300,
+ "outputTokens": 80,
+ "cachedTokens": 150
+ },
+ "codex-other-conversation": null,
+ "notifications": [
+ "agent/conversation",
+ "agent/conversation",
+ "agent/conversation",
+ "agent/conversation",
+ "agent/conversation",
+ "agent/conversation",
+ "agent/conversation",
+ "agent/conversation"
+ ],
+ "restart-from-checkpoint": {
+ "totalTokens": 540,
+ "updatedAt": "2026-10-01T00:07:00.000Z",
+ "inputTokens": 480,
+ "outputTokens": 60,
+ "cachedTokens": 160,
+ "work": {
+ "current": [],
+ "locations": [
+ {
+ "cwd": "/fixture/work",
+ "at": "2026-10-01T00:00:00.000Z"
+ }
+ ],
+ "pullRequests": [
+ {
+ "url": "https://github.com/example/project/pull/42",
+ "cwd": "/fixture/work",
+ "at": "2026-10-01T00:00:00.000Z"
+ }
+ ],
+ "uncertain": true,
+ "truncated": false
+ }
+ },
+ "corrupt-checkpoint-rebuilt": {
+ "totalTokens": 540,
+ "updatedAt": "2026-10-01T00:07:30.000Z",
+ "inputTokens": 480,
+ "outputTokens": 60,
+ "cachedTokens": 160
+ },
+ "opencode/valid/cold": null,
+ "opencode/valid": {
+ "value": {
+ "totalTokens": 215,
+ "updatedAt": "2026-10-01T00:07:30.000Z",
+ "inputTokens": 190,
+ "outputTokens": 25,
+ "cachedTokens": 80
+ },
+ "queries": [
+ {
+ "sql": "SELECT tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write FROM session WHERE id = ?",
+ "args": [
+ "conversation"
+ ]
+ }
+ ]
+ },
+ "opencode/fallback/cold": null,
+ "opencode/fallback": {
+ "value": {
+ "totalTokens": 215,
+ "updatedAt": "2026-10-01T00:07:30.000Z",
+ "inputTokens": 190,
+ "outputTokens": 25,
+ "cachedTokens": 80
+ },
+ "queries": [
+ {
+ "sql": "SELECT tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write FROM session WHERE id = ?",
+ "args": [
+ "conversation"
+ ]
+ },
+ {
+ "sql": "SELECT tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, 0 AS tokens_cache_write FROM session WHERE id = ?",
+ "args": [
+ "conversation"
+ ]
+ }
+ ]
+ },
+ "opencode/unreadable/cold": null,
+ "opencode/unreadable": {
+ "value": null,
+ "queries": [
+ {
+ "sql": "SELECT tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write FROM session WHERE id = ?",
+ "args": [
+ "conversation"
+ ]
+ },
+ {
+ "sql": "SELECT tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, 0 AS tokens_cache_write FROM session WHERE id = ?",
+ "args": [
+ "conversation"
+ ]
+ }
+ ]
+ },
+ "opencode/malformed/cold": null,
+ "opencode/malformed": {
+ "value": null,
+ "queries": [
+ {
+ "sql": "SELECT tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write FROM session WHERE id = ?",
+ "args": [
+ "conversation"
+ ]
+ }
+ ]
+ }
+ },
+ "linux": {
+ "cold": null,
+ "missing": null,
+ "streaming-and-foreign": {
+ "totalTokens": 420,
+ "updatedAt": "2026-10-01T00:01:00.000Z",
+ "inputTokens": 380,
+ "outputTokens": 40,
+ "cachedTokens": 160
+ },
+ "partial": {
+ "totalTokens": 420,
+ "updatedAt": "2026-10-01T00:01:30.000Z",
+ "inputTokens": 380,
+ "outputTokens": 40,
+ "cachedTokens": 160
+ },
+ "completed": {
+ "totalTokens": 630,
+ "updatedAt": "2026-10-01T00:02:00.000Z",
+ "inputTokens": 570,
+ "outputTokens": 60,
+ "cachedTokens": 240
+ },
+ "output-and-work": {
+ "totalTokens": 630,
+ "updatedAt": "2026-10-01T00:02:30.000Z",
+ "inputTokens": 570,
+ "outputTokens": 60,
+ "cachedTokens": 240,
+ "output": {
+ "linesAdded": 2,
+ "linesRemoved": 0,
+ "pullRequestsCreated": 1
+ },
+ "work": {
+ "current": [
+ {
+ "cwd": "/fixture/work",
+ "at": "2026-10-01T00:00:00.000Z"
+ }
+ ],
+ "locations": [
+ {
+ "cwd": "/fixture/work",
+ "at": "2026-10-01T00:00:00.000Z"
+ }
+ ],
+ "pullRequests": [
+ {
+ "url": "https://github.com/example/project/pull/42",
+ "cwd": "/fixture/work",
+ "at": "2026-10-01T00:00:00.000Z"
+ }
+ ],
+ "uncertain": false,
+ "truncated": false
+ }
+ },
+ "unreadable-keeps-last": {
+ "totalTokens": 630,
+ "updatedAt": "2026-10-01T00:02:30.000Z",
+ "inputTokens": 570,
+ "outputTokens": 60,
+ "cachedTokens": 240,
+ "output": {
+ "linesAdded": 2,
+ "linesRemoved": 0,
+ "pullRequestsCreated": 1
+ },
+ "work": {
+ "current": [
+ {
+ "cwd": "/fixture/work",
+ "at": "2026-10-01T00:00:00.000Z"
+ }
+ ],
+ "locations": [
+ {
+ "cwd": "/fixture/work",
+ "at": "2026-10-01T00:00:00.000Z"
+ }
+ ],
+ "pullRequests": [
+ {
+ "url": "https://github.com/example/project/pull/42",
+ "cwd": "/fixture/work",
+ "at": "2026-10-01T00:00:00.000Z"
+ }
+ ],
+ "uncertain": false,
+ "truncated": false
+ }
+ },
+ "rewritten-keeps-history": {
+ "totalTokens": 410,
+ "updatedAt": "2026-10-01T00:03:30.000Z",
+ "inputTokens": 390,
+ "outputTokens": 20,
+ "cachedTokens": 80,
+ "work": {
+ "current": [],
+ "locations": [
+ {
+ "cwd": "/fixture/work",
+ "at": "2026-10-01T00:00:00.000Z"
+ }
+ ],
+ "pullRequests": [
+ {
+ "url": "https://github.com/example/project/pull/42",
+ "cwd": "/fixture/work",
+ "at": "2026-10-01T00:00:00.000Z"
+ }
+ ],
+ "uncertain": true,
+ "truncated": false
+ }
+ },
+ "rebound-does-not-borrow": null,
+ "unsupported": null,
+ "fork": {
+ "totalTokens": 330,
+ "updatedAt": "2026-10-01T00:05:00.000Z",
+ "inputTokens": 290,
+ "outputTokens": 40,
+ "cachedTokens": 80
+ },
+ "codex-deltas": {
+ "totalTokens": 250,
+ "updatedAt": "2026-10-01T00:05:30.000Z",
+ "inputTokens": 200,
+ "outputTokens": 50,
+ "cachedTokens": 100
+ },
+ "codex-append": {
+ "totalTokens": 380,
+ "updatedAt": "2026-10-01T00:06:00.000Z",
+ "inputTokens": 300,
+ "outputTokens": 80,
+ "cachedTokens": 150
+ },
+ "codex-other-conversation": null,
+ "notifications": [
+ "agent/conversation",
+ "agent/conversation",
+ "agent/conversation",
+ "agent/conversation",
+ "agent/conversation",
+ "agent/conversation",
+ "agent/conversation",
+ "agent/conversation"
+ ],
+ "restart-from-checkpoint": {
+ "totalTokens": 540,
+ "updatedAt": "2026-10-01T00:07:00.000Z",
+ "inputTokens": 480,
+ "outputTokens": 60,
+ "cachedTokens": 160,
+ "work": {
+ "current": [],
+ "locations": [
+ {
+ "cwd": "/fixture/work",
+ "at": "2026-10-01T00:00:00.000Z"
+ }
+ ],
+ "pullRequests": [
+ {
+ "url": "https://github.com/example/project/pull/42",
+ "cwd": "/fixture/work",
+ "at": "2026-10-01T00:00:00.000Z"
+ }
+ ],
+ "uncertain": true,
+ "truncated": false
+ }
+ },
+ "corrupt-checkpoint-rebuilt": {
+ "totalTokens": 540,
+ "updatedAt": "2026-10-01T00:07:30.000Z",
+ "inputTokens": 480,
+ "outputTokens": 60,
+ "cachedTokens": 160
+ },
+ "opencode/valid/cold": null,
+ "opencode/valid": {
+ "value": {
+ "totalTokens": 215,
+ "updatedAt": "2026-10-01T00:07:30.000Z",
+ "inputTokens": 190,
+ "outputTokens": 25,
+ "cachedTokens": 80
+ },
+ "queries": [
+ {
+ "sql": "SELECT tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write FROM session WHERE id = ?",
+ "args": [
+ "conversation"
+ ]
+ }
+ ]
+ },
+ "opencode/fallback/cold": null,
+ "opencode/fallback": {
+ "value": {
+ "totalTokens": 215,
+ "updatedAt": "2026-10-01T00:07:30.000Z",
+ "inputTokens": 190,
+ "outputTokens": 25,
+ "cachedTokens": 80
+ },
+ "queries": [
+ {
+ "sql": "SELECT tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write FROM session WHERE id = ?",
+ "args": [
+ "conversation"
+ ]
+ },
+ {
+ "sql": "SELECT tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, 0 AS tokens_cache_write FROM session WHERE id = ?",
+ "args": [
+ "conversation"
+ ]
+ }
+ ]
+ },
+ "opencode/unreadable/cold": null,
+ "opencode/unreadable": {
+ "value": null,
+ "queries": [
+ {
+ "sql": "SELECT tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write FROM session WHERE id = ?",
+ "args": [
+ "conversation"
+ ]
+ },
+ {
+ "sql": "SELECT tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, 0 AS tokens_cache_write FROM session WHERE id = ?",
+ "args": [
+ "conversation"
+ ]
+ }
+ ]
+ },
+ "opencode/malformed/cold": null,
+ "opencode/malformed": {
+ "value": null,
+ "queries": [
+ {
+ "sql": "SELECT tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write FROM session WHERE id = ?",
+ "args": [
+ "conversation"
+ ]
+ }
+ ]
+ }
+ }
+}
diff --git a/cli/src/lib/agentFrame.ts b/cli/src/lib/agentFrame.ts
index 6c7db818b..9a3e37b86 100644
--- a/cli/src/lib/agentFrame.ts
+++ b/cli/src/lib/agentFrame.ts
@@ -25,7 +25,7 @@ import type { ScmDescription } from '../scm/types.js'
import { sessionGitContext, SessionGitContextReader, type SessionGitContext } from './sessionGitContext.js'
import { sessionGitHistory } from './sessionGitHistory.js'
import { transcriptActivityAt } from './transcriptActivity.js'
-import type { AgentTokenUsage } from './agentTokenUsage.js'
+import type { AgentTokenUsage } from './agentUsageWire.js'
import type { AgentOutputStats } from './agentOutputStats.js'
import type { GridAssignment } from './gridAssignment.js'
import type { GridWebSearchStatus } from './gridLaunchWire.js'
diff --git a/cli/src/lib/agentTokenUsage.spec.ts b/cli/src/lib/agentTokenUsage.spec.ts
index 487b44f2f..ac3760bf4 100644
--- a/cli/src/lib/agentTokenUsage.spec.ts
+++ b/cli/src/lib/agentTokenUsage.spec.ts
@@ -34,6 +34,17 @@ describe('owning-machine token cache', () => {
})
afterEach(async () => { store.dispose(); await store.settled(); vi.useRealTimers(); await rm(dir, { recursive: true, force: true }) })
+ it('reports unavailable instead of null when a worker is full or disposed', async () => {
+ let release!: () => void
+ const held = new Promise<void>(done => { release = done })
+ const worker = new AgentTokenUsageCache(join(dir, 'bounded-worker'), { readSqlite: async () => { await held; return { ok: false, reason: 'unavailable' } as never } })
+ const database = { ...target, engine: 'opencode' as const, transcriptPath: null }
+ for (let i = 0; i < 512; i++) worker.get({ ...database, agentId: `agent-${i}`, sessionId: `session-${i}` })
+ await expect(worker.read(database)).rejects.toThrow('unavailable')
+ worker.dispose(); release(); await worker.settled()
+ await expect(worker.read({ ...database, agentId: 'agent-0', sessionId: 'session-0' })).rejects.toThrow('disposed')
+ })
+
it('coalesces activity bursts, captures their final usage, and does not poll idle harnesses', async () => {
await writeFile(target.transcriptPath!, claude('one'))
await read()
diff --git a/cli/src/lib/agentTokenUsage.ts b/cli/src/lib/agentTokenUsage.ts
index 77c0a2470..f62362dfe 100644
--- a/cli/src/lib/agentTokenUsage.ts
+++ b/cli/src/lib/agentTokenUsage.ts
@@ -5,14 +5,12 @@ import { createHash, randomUUID } from 'node:crypto'
import { mkdir, open, readFile, rename, stat, unlink, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { env } from '../config/env.js'
-import type { RegisteredSession } from './registry.js'
import { sqliteReadAll } from './sqliteRead.js'
import { emptyOutputLedger, ingestOutput, outputSnapshot, validOutputLedger, type AgentOutputStats, type OutputLedger } from './agentOutputStats.js'
import { emptySessionWork, ingestSessionWork, sessionWorkSnapshot, validSessionWork, type SessionWork, type SessionWorkLedger } from './sessionWork.js'
-export type AgentTokenUsage = { totalTokens: number | null; updatedAt: string; inputTokens?: number; outputTokens?: number; cachedTokens?: number; output?: AgentOutputStats; work?: SessionWork }
-type Target = Pick<RegisteredSession, 'engine' | 'sessionId' | 'transcriptPath' | 'codexHome' | 'agentId' | 'forkedFrom' | 'registeredAt'>
- & Partial<Pick<RegisteredSession, 'cwd'>>
+import { usageTargetKey, type AgentTokenUsage, type AgentUsageTarget as Target } from './agentUsageWire.js'
+export type { AgentTokenUsage } from './agentUsageWire.js'
type Buckets = [number, number, number, number]
type CodexTotals = [number, number, number, number]
type Checkpoint = {
@@ -26,6 +24,7 @@ type Checkpoint = {
type Entry = {
target: Target; value: AgentTokenUsage | null; checked: number; pending: Promise<void> | null;
fingerprint?: string;
+ readable?: boolean;
dirty?: boolean;
timer?: NodeJS.Timeout;
}
@@ -46,6 +45,9 @@ function keyFor(s: Target): string | null {
return hash(JSON.stringify([s.engine, s.codexHome ?? '', s.sessionId, s.transcriptPath,
s.forkedFrom ? s.registeredAt : null]))
}
+function cacheKeyFor(s: Target): string | null {
+ return keyFor(s) ? usageTargetKey(s) : null
+}
function targetSnapshot(s: Target): Target {
return { agentId: s.agentId, sessionId: s.sessionId, engine: s.engine, transcriptPath: s.transcriptPath,
codexHome: s.codexHome, cwd: s.cwd, registeredAt: s.registeredAt, forkedFrom: s.forkedFrom ? { ...s.forkedFrom } : null }
@@ -147,7 +149,7 @@ export class AgentTokenUsageCache {
/** Synchronous cache lookup. A cold or unsupported count is unknown, never invented as zero. */
get(target: Target): AgentTokenUsage | null {
if (this.disposed) return null
- const key = keyFor(target)
+ const key = cacheKeyFor(target)
if (!key) return null
let entry = this.entries.get(key)
if (!entry) {
@@ -158,7 +160,7 @@ export class AgentTokenUsageCache {
}
entry = { target: targetSnapshot(target), value: null, checked: -Infinity, pending: null }
this.entries.set(key, entry)
- this.schedule(key, entry)
+ this.schedule(keyFor(target)!, entry)
}
entry.target = targetSnapshot(target)
// Once hydrated, frames only read memory. Existing transcript events drive refreshes;
@@ -171,21 +173,35 @@ export class AgentTokenUsageCache {
changed(target: Target): void {
if (this.disposed) return
this.get(target)
- const key = keyFor(target)
+ const key = cacheKeyFor(target)
const entry = key && this.entries.get(key)
if (!entry || entry.timer) return
if (this.now() - entry.checked >= (this.options.refreshMs ?? REFRESH_MS)) {
- this.schedule(key!, entry)
+ this.schedule(keyFor(target)!, entry)
return
}
const delay = Math.max(500, (this.options.refreshMs ?? REFRESH_MS) - (this.now() - entry.checked))
entry.timer = setTimeout(() => {
entry.timer = undefined
- this.schedule(key!, entry)
+ this.schedule(keyFor(entry.target)!, entry)
}, delay)
entry.timer.unref()
}
+ /** A bounded service request. The caller coalesces events; this refreshes even a warm worker
+ * after core reconnect, and returns the exact requested target's current aggregate. */
+ async read(target: Target): Promise<AgentTokenUsage | null> {
+ if (this.disposed) throw new Error('Usage reader is disposed')
+ this.get(target)
+ const key = cacheKeyFor(target)
+ const entry = key && this.entries.get(key)
+ if (!entry) throw new Error('Usage reader is unavailable')
+ if (!entry.pending) this.schedule(keyFor(target)!, entry)
+ await this.settled()
+ if (!entry.readable) throw new Error('Usage source is unavailable')
+ return entry.value
+ }
+
/** Useful for a clean shutdown and isolated integration tests. Never awaited by a list frame. */
async settled(): Promise<void> { await this.queue }
dispose(): void {
@@ -201,7 +217,8 @@ export class AgentTokenUsageCache {
if (this.disposed) return
entry.dirty = false
entry.checked = this.now()
- try { await this.refresh(key, entry) } catch { /* An unreadable usage file must never affect a harness. */ }
+ entry.readable = false
+ try { entry.readable = await this.refresh(key, entry) } catch { /* An unreadable usage file must never affect a harness. */ }
})
entry.pending = task
this.queue = task.finally(() => {
@@ -271,12 +288,12 @@ export class AgentTokenUsageCache {
await rename(temporary, file)
} finally { await unlink(temporary).catch(() => {}) }
}
- private async refresh(key: string, entry: Entry): Promise<void> {
+ private async refresh(key: string, entry: Entry): Promise<boolean> {
let nextFingerprint: string | undefined
// Warm, unchanged transcripts need one stat, no checkpoint or transcript reads.
if (entry.fingerprint && entry.target.transcriptPath) {
const info = await stat(entry.target.transcriptPath).catch(() => null)
- if (info && entry.fingerprint === `${info.dev}:${info.ino}:${info.size}:${info.mtimeMs}:${info.ctimeMs}`) return
+ if (info && entry.fingerprint === `${info.dev}:${info.ino}:${info.size}:${info.mtimeMs}:${info.ctimeMs}`) return true
}
let state = await this.load(key)
this.publish(entry, state)
@@ -290,10 +307,10 @@ export class AgentTokenUsageCache {
if (!result.ok) result = await read(database,
'SELECT tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, 0 AS tokens_cache_write FROM session WHERE id = ?',
[entry.target.sessionId], limits)
- if (!result.ok || result.rows.length !== 1) return
+ if (!result.ok || result.rows.length !== 1) return false
const row = result.rows[0]
if (!['tokens_input', 'tokens_output', 'tokens_reasoning', 'tokens_cache_read', 'tokens_cache_write']
- .every(key => typeof row[key] === 'number' && Number.isSafeInteger(row[key]) && Number(row[key]) >= 0)) return
+ .every(key => typeof row[key] === 'number' && Number.isSafeInteger(row[key]) && Number(row[key]) >= 0)) return false
state.total = sum(Object.values(row).map(tokens))
state.usage = [tokens(row.tokens_input) + tokens(row.tokens_cache_read) + tokens(row.tokens_cache_write),
tokens(row.tokens_output) + tokens(row.tokens_reasoning), tokens(row.tokens_cache_read)]
@@ -303,12 +320,12 @@ export class AgentTokenUsageCache {
const file = await open(path, 'r')
try {
const info = await file.stat()
- if (!info.isFile() || info.size > MAX_TRANSCRIPT_BYTES) return
+ if (!info.isFile() || info.size > MAX_TRANSCRIPT_BYTES) return false
const inode = `${info.dev}:${info.ino}`
const fingerprint = `${inode}:${info.size}:${info.mtimeMs}:${info.ctimeMs}`
if (state.inode === inode && state.size === info.size && state.mtime === info.mtimeMs) {
entry.fingerprint = fingerprint
- return
+ return true
}
const boundary = async (offset: number) => {
const length = Math.min(256, offset)
@@ -355,11 +372,12 @@ export class AgentTokenUsageCache {
nextFingerprint = fingerprint
} finally { await file.close() }
}
- if (!Number.isSafeInteger(state.total)) return
+ if (!Number.isSafeInteger(state.total)) return false
state.updatedAt = new Date(this.now()).toISOString()
await this.save(key, state)
entry.fingerprint = nextFingerprint
this.publish(entry, state)
+ return true
}
}
@@ -367,5 +385,3 @@ function validBuckets(value: unknown): value is Buckets {
return Array.isArray(value) && value.length === 4
&& value.every(n => typeof n === 'number' && Number.isSafeInteger(n) && n >= 0)
}
-
-export const agentTokenUsage = new AgentTokenUsageCache(join(env.ADAPTER_DATA_DIR, 'agent-token-usage'))
diff --git a/cli/src/lib/agentUsageWire.spec.ts b/cli/src/lib/agentUsageWire.spec.ts
new file mode 100644
index 000000000..6ace060ce
--- /dev/null
+++ b/cli/src/lib/agentUsageWire.spec.ts
@@ -0,0 +1,40 @@
+import { expect, it } from 'vitest'
+import { usageSnapshot, usageTarget, usageTargetKey, validUsage, validUsageTarget } from './agentUsageWire.js'
+
+const target = usageTarget({ agentId: 'a', sessionId: 's', engine: 'claude', transcriptPath: '/fixture/a', registeredAt: 1 })
+const at = '2026-10-01T00:00:00Z'
+it('accepts only bounded full read identities', () => {
+ expect(validUsageTarget(target)).toBe(true)
+ expect(validUsageTarget({ ...target, engine: 'opencode', transcriptPath: null })).toBe(true)
+ expect(validUsageTarget({ ...target, forkedFrom: { agentId: 'parent', name: 'Parent' }, codexHome: '/profile', cwd: '/cwd' })).toBe(true)
+ for (const value of [null, [], {}, ...Object.entries({ agentId: '', sessionId: '', engine: 'hermes', transcriptPath: 'relative', cwd: 'relative',
+ codexHome: 'relative', registeredAt: -1, forkedFrom: { agentId: 4 } }).map(([key, value]) => ({ ...target, [key]: value })),
+ { ...target, transcriptPath: null }, { ...target, agentId: 'x'.repeat(4097) }, { ...target, cwd: '/bad\0path' }]) expect(validUsageTarget(value), JSON.stringify(value)).toBe(false)
+ for (const changed of [{ agentId: 'b' }, { sessionId: 'new' }, { engine: 'codex' }, { transcriptPath: '/other' }, { cwd: '/other' },
+ { codexHome: '/profile' }, { registeredAt: 2 }, { forkedFrom: { agentId: 'parent', name: 'Parent' } }]) {
+ expect(usageTargetKey({ ...target, ...changed } as typeof target)).not.toBe(usageTargetKey(target))
+ }
+})
+
+it('copies aggregates only and rejects malformed or oversized values', () => {
+ const value = { totalTokens: 42, updatedAt: at, inputTokens: 20, outputTokens: 22, cachedTokens: 10,
+ output: { linesAdded: 3, linesRemoved: null, pullRequestsCreated: 1 },
+ work: { current: [{ cwd: '/fixture', at }], locations: [{ cwd: '/fixture', at }],
+ pullRequests: [{ url: 'https://github.com/example/project/pull/4', cwd: null, at }], uncertain: true, truncated: false } }
+ expect(validUsage(null)).toBe(true)
+ expect(usageSnapshot(null)).toBeNull()
+ expect(validUsage(value)).toBe(true)
+ expect(usageSnapshot(value)).toEqual(value)
+ expect(usageSnapshot(value)?.work?.current).not.toBe(value.work.current)
+ expect(usageSnapshot({ totalTokens: null, updatedAt: at })).toEqual({ totalTokens: null, updatedAt: at })
+ expect(usageSnapshot({ ...value, ledger: 'private' } as typeof value)).not.toHaveProperty('ledger')
+ for (const bad of [[], {}, { ...value, totalTokens: -1 }, { ...value, inputTokens: Infinity }, { ...value, updatedAt: 'invalid' },
+ { ...value, output: { ...value.output, linesAdded: -1 } }, { ...value, output: null }, { ...value, work: null },
+ { ...value, work: { ...value.work, current: new Array(129).fill(value.work.current[0]) } },
+ { ...value, work: { ...value.work, locations: [{ cwd: 'relative', at }] } },
+ { ...value, work: { ...value.work, uncertain: 1 } }, { ...value, work: { ...value.work, truncated: 1 } },
+ { ...value, work: { ...value.work, locations: Array.from({ length: 128 }, () => ({ cwd: '/' + 'x'.repeat(4095), at })) } },
+ { ...value, work: { ...value.work, pullRequests: [{ url: 'https://github.com/' + 'x'.repeat(4096) + '/project/pull/1', cwd: null, at }] } },
+ { ...value, work: { ...value.work, pullRequests: [{ url: 'file:///secret', cwd: null, at }] } },
+ { ...value, work: { ...value.work, pullRequests: [{ url: value.work.pullRequests[0].url, cwd: 'relative', at }] } }]) expect(validUsage(bad)).toBe(false)
+})
diff --git a/cli/src/lib/agentUsageWire.ts b/cli/src/lib/agentUsageWire.ts
new file mode 100644
index 000000000..122e18204
--- /dev/null
+++ b/cli/src/lib/agentUsageWire.ts
@@ -0,0 +1,60 @@
+/** Aggregate usage observations. No transcript readers, parsers, SQLite or live state. */
+import { validWorkPath as path, validPullRequestUrl } from './sessionWorkWire.js'
+import type { RegisteredSession } from './registry.js'
+import type { AgentOutputStats } from './agentOutputStats.js'
+import type { SessionWork } from './sessionWork.js'
+
+export type AgentTokenUsage = { totalTokens: number | null; updatedAt: string; inputTokens?: number; outputTokens?: number; cachedTokens?: number; output?: AgentOutputStats; work?: SessionWork }
+export type AgentUsageTarget = Pick<RegisteredSession, 'engine' | 'sessionId' | 'transcriptPath' | 'codexHome' | 'agentId' | 'forkedFrom' | 'registeredAt'>
+ & Partial<Pick<RegisteredSession, 'cwd'>>
+export const USAGE_LIMIT = 512
+export const USAGE_REFRESH_MS = 15_000
+const object = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v)
+const text = (v: unknown): v is string => typeof v === 'string' && v.length <= 4096 && !/[\x00-\x1f\x7f]/.test(v)
+const count = (v: unknown): v is number => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0
+const stamp = (v: unknown): v is string => text(v) && Number.isFinite(Date.parse(v))
+
+export function usageTarget(s: AgentUsageTarget): AgentUsageTarget {
+ return { agentId: s.agentId, sessionId: s.sessionId, engine: s.engine, transcriptPath: s.transcriptPath,
+ codexHome: s.codexHome ?? null, cwd: s.cwd ?? null, registeredAt: s.registeredAt,
+ forkedFrom: s.forkedFrom ? { agentId: s.forkedFrom.agentId, name: s.forkedFrom.name } : null }
+}
+
+/** Every input that can affect the reading, including the owner that will display it. */
+export const usageTargetKey = (s: AgentUsageTarget): string => JSON.stringify(usageTarget(s))
+
+export function validUsageTarget(v: unknown): v is AgentUsageTarget {
+ return object(v) && text(v.agentId) && !!v.agentId && text(v.sessionId) && !!v.sessionId
+ && ['claude', 'codex', 'opencode'].includes(String(v.engine))
+ && (v.transcriptPath === null || path(v.transcriptPath)) && (v.engine === 'opencode' || !!v.transcriptPath)
+ && (v.codexHome === null || path(v.codexHome)) && (v.cwd === null || path(v.cwd)) && count(v.registeredAt)
+ && (v.forkedFrom === null || object(v.forkedFrom) && text(v.forkedFrom.agentId) && text(v.forkedFrom.name))
+}
+
+export function validUsage(v: unknown): v is AgentTokenUsage | null {
+ if (v === null) return true
+ if (!object(v) || !(v.totalTokens === null || count(v.totalTokens)) || !stamp(v.updatedAt)
+ || !['inputTokens', 'outputTokens', 'cachedTokens'].every(k => v[k] === undefined || count(v[k]))) return false
+ if (v.output !== undefined && (!object(v.output) || !['linesAdded', 'linesRemoved', 'pullRequestsCreated']
+ .every(k => (v.output as Record<string, unknown>)[k] === null || count((v.output as Record<string, unknown>)[k])))) return false
+ if (v.work !== undefined) {
+ const w = v.work
+ const locations = (a: unknown) => Array.isArray(a) && a.length <= 128 && a.every(x => object(x) && path(x.cwd) && stamp(x.at))
+ if (!object(w) || !locations(w.current) || !locations(w.locations) || typeof w.uncertain !== 'boolean' || typeof w.truncated !== 'boolean'
+ || !Array.isArray(w.pullRequests) || w.pullRequests.length > 128 || !w.pullRequests.every(p => object(p)
+ && text(p.url) && validPullRequestUrl(p.url) && (p.cwd === null || path(p.cwd)) && stamp(p.at))) return false
+ }
+ return Buffer.byteLength(JSON.stringify(usageSnapshot(v as AgentTokenUsage))) <= 256 * 1024
+}
+
+/** Copy only aggregate fields; a worker can never smuggle a ledger or transcript into core memory. */
+export function usageSnapshot(v: AgentTokenUsage | null): AgentTokenUsage | null {
+ if (!v) return null
+ return { totalTokens: v.totalTokens, updatedAt: v.updatedAt,
+ ...(v.inputTokens === undefined ? {} : { inputTokens: v.inputTokens }),
+ ...(v.outputTokens === undefined ? {} : { outputTokens: v.outputTokens }),
+ ...(v.cachedTokens === undefined ? {} : { cachedTokens: v.cachedTokens }),
+ ...(v.output ? { output: { linesAdded: v.output.linesAdded, linesRemoved: v.output.linesRemoved, pullRequestsCreated: v.output.pullRequestsCreated } } : {}),
+ ...(v.work ? { work: { current: v.work.current.map(p => ({ cwd: p.cwd, at: p.at })), locations: v.work.locations.map(p => ({ cwd: p.cwd, at: p.at })),
+ pullRequests: v.work.pullRequests.map(p => ({ url: p.url, cwd: p.cwd, at: p.at })), uncertain: v.work.uncertain, truncated: v.work.truncated } } : {}) }
+}
diff --git a/cli/src/lib/gitPullRequest.ts b/cli/src/lib/gitPullRequest.ts
index 7e0eb2640..268ae2517 100644
--- a/cli/src/lib/gitPullRequest.ts
+++ b/cli/src/lib/gitPullRequest.ts
@@ -2,7 +2,7 @@ import { execFile } from 'node:child_process'
import { promisify } from 'node:util'
import { insideGitCheckout, validGitPath } from './gitProject.js'
import { canonicalRepository } from './agentProject.js'
-import { validPullRequestUrl } from './sessionWork.js'
+import { validPullRequestUrl } from './sessionWorkWire.js'
import { tmpdir } from 'node:os'
const exec = promisify(execFile)
diff --git a/cli/src/lib/sessionGitHistory.ts b/cli/src/lib/sessionGitHistory.ts
index 15a40ecd3..1cdb1f5bf 100644
--- a/cli/src/lib/sessionGitHistory.ts
+++ b/cli/src/lib/sessionGitHistory.ts
@@ -5,7 +5,8 @@ import { join } from 'node:path'
import { env } from '../config/env.js'
import type { RegisteredSession } from './registry.js'
import type { SessionGitContext } from './sessionGitContext.js'
-import { validPullRequestUrl, validWorkPath, type WorkPullRequest } from './sessionWork.js'
+import { validPullRequestUrl, validWorkPath } from './sessionWorkWire.js'
+import type { WorkPullRequest } from './sessionWork.js'
import type { PullRequestResult } from './gitPullRequest.js'
export type WorkBranch = { cwd: string; remote: string | null; branch: string; at: string }
diff --git a/cli/src/lib/sessionGitPullRequest.spec.ts b/cli/src/lib/sessionGitPullRequest.spec.ts
index 07d262fc7..b39796bc9 100644
--- a/cli/src/lib/sessionGitPullRequest.spec.ts
+++ b/cli/src/lib/sessionGitPullRequest.spec.ts
@@ -3,7 +3,7 @@ import { appendFile, mkdir, mkdtemp, readFile, realpath, rm, writeFile } from 'n
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { AgentTokenUsageCache, agentTokenUsage } from './agentTokenUsage.js'
+import { AgentTokenUsageCache } from './agentTokenUsage.js'
import { agentFrame } from './agentFrame.js'
import { forgetAgentProject } from './agentProject.js'
import { SessionGitHistoryStore, sessionGitHistory } from './sessionGitHistory.js'
@@ -61,7 +61,6 @@ describe('session work from transcript through Git and PR history', () => {
now = Date.parse('2026-09-27T13:00:00Z')
usage = new AgentTokenUsageCache(join(directory, 'usage'), { now: () => now })
history = new SessionGitHistoryStore(join(directory, 'history'))
- vi.spyOn(agentTokenUsage, 'get').mockImplementation(target => usage.get(target))
vi.spyOn(sessionGitHistory, 'get').mockImplementation(target => history.get(target))
vi.spyOn(sessionGitHistory, 'observe').mockImplementation((target, context) => history.observe(target, context))
vi.spyOn(sessionGitHistory, 'recordPullRequest').mockImplementation((...args) => history.recordPullRequest(...args))
@@ -82,7 +81,7 @@ describe('session work from transcript through Git and PR history', () => {
const first = await frame()
expect(first.gitContext).toMatchObject({ state: 'workspace', current: { branch: 'hn/nfc' },
history: { branches: [{ branch: 'hn/nfc' }] } })
- expect(await readSessionGitPullRequest(agent, { history: true })).toMatchObject({
+ expect(await readSessionGitPullRequest(agent, { usage: async () => usage.get(agent), history: true })).toMatchObject({
history: { pullRequests: [{ result: { number: 12, state: 'Open' } }] },
})
git(ship, 'switch', '-c', 'hn/preview')
@@ -92,7 +91,7 @@ describe('session work from transcript through Git and PR history', () => {
expect(next.gitContext.history?.branches.map(b => b.branch).sort()).toEqual(['hn/nfc', 'hn/preview'])
rows[0] = pr(12, 'hn/nfc', true)
now += 61_000
- const refreshed = await readSessionGitPullRequest(agent, { history: true })
+ const refreshed = await readSessionGitPullRequest(agent, { usage: async () => usage.get(agent), history: true })
expect('history' in refreshed && refreshed.history.pullRequests.map(p => p.result?.status === 'found' && [p.result.number, p.result.state]))
.toEqual([[13, 'Open'], [12, 'Merged']])
// Another session's branch exists in the same repository, but has no association here.
@@ -106,7 +105,7 @@ describe('session work from transcript through Git and PR history', () => {
git(ship, 'branch', '-D', 'hn/nfc')
forgetAgentProject(ship)
rows[0] = pr(12, 'hn/nfc', true)
- const result = await readSessionGitPullRequest(agent, { history: true })
+ const result = await readSessionGitPullRequest(agent, { usage: async () => usage.get(agent), history: true })
expect('history' in result && result.history.pullRequests.map(p => p.result?.status === 'found' && [p.result.number, p.result.state]))
.toEqual([[13, 'Open'], [12, 'Merged']])
})
@@ -114,7 +113,7 @@ describe('session work from transcript through Git and PR history', () => {
it('keeps completed PRs when the same branch also has open work', async () => {
agent.cwd = ship; agent.transcriptPath = null
rows = [pr(12, 'hn/nfc', true), pr(14, 'hn/nfc')]
- const result = await readSessionGitPullRequest(agent, { history: true })
+ const result = await readSessionGitPullRequest(agent, { usage: async () => usage.get(agent), history: true })
expect('history' in result && result.history.pullRequests.map(p => p.result?.status === 'found' && [p.result.number, p.result.state]))
.toEqual([[14, 'Open'], [12, 'Merged']])
})
@@ -126,21 +125,21 @@ describe('session work from transcript through Git and PR history', () => {
expect(first.project?.branch).toBe('hn/nfc')
expect(first.gitContext.current).toMatchObject({ cwd: ship, branch: 'hn/nfc', worktree: true })
const expected = { cwd: ship, branch: 'hn/nfc', remote: 'github.com/acme/app' }
- expect(await readSessionGitPullRequest(agent, { expected })).toMatchObject({ status: 'found', number: 12, context: expected })
+ expect(await readSessionGitPullRequest(agent, { usage: async () => usage.get(agent), expected })).toMatchObject({ status: 'found', number: 12, context: expected })
git(ship, 'switch', '-c', 'hn/preview')
await receipt('preview', join(ship, 'tui'), 13)
const second = await frame()
expect(second.gitContext.current?.branch).toBe('hn/preview')
expect(second.gitContext.version!.revision).toBeGreaterThan(first.gitContext.version!.revision)
- expect((await readSessionGitPullRequest(agent, { expected })).status).toBe('unavailable')
- expect(await readSessionGitPullRequest(agent)).toMatchObject({ status: 'found', number: 13 })
+ expect((await readSessionGitPullRequest(agent, { usage: async () => usage.get(agent), expected })).status).toBe('unavailable')
+ expect(await readSessionGitPullRequest(agent, { usage: async () => usage.get(agent) })).toMatchObject({ status: 'found', number: 13 })
expect(agent.cwd).toBe(ship)
git(home, 'worktree', 'remove', '--force', ship)
git(home, 'branch', '-D', 'hn/nfc', 'hn/preview')
rows = rows.map(p => pr(p.number, p.head.ref, true))
- const removed = await readSessionGitPullRequest(agent, { history: true })
+ const removed = await readSessionGitPullRequest(agent, { usage: async () => usage.get(agent), history: true })
expect(removed).toMatchObject({ status: 'unavailable', gitContext: { checkouts: [] } })
expect('history' in removed && removed.history.pullRequests.map(p => p.result?.status === 'found' && p.result.state)).toEqual(['Merged', 'Merged'])
await history.settled()
@@ -148,7 +147,7 @@ describe('session work from transcript through Git and PR history', () => {
expect(restarted.branches.map(b => b.branch).sort()).toEqual(['hn/nfc', 'hn/preview'])
expect(restarted.pullRequests).toHaveLength(2)
vi.mocked(github.readPullRequestUrl).mockResolvedValue({ status: 'unavailable' })
- const offline = await readSessionGitPullRequest(agent, { history: true })
+ const offline = await readSessionGitPullRequest(agent, { usage: async () => usage.get(agent), history: true })
expect('history' in offline && offline.history.pullRequests).toEqual(restarted.pullRequests)
})
@@ -167,7 +166,7 @@ describe('session work from transcript through Git and PR history', () => {
history: { pullRequests: [{ url: 'https://github.com/acme/app/pull/397' }] } })
expect(value.gitContext.checkouts?.map(p => p.branch)).toEqual(['original', 'hn/nfc'])
expect(value.gitContext.history?.branches.map(p => p.branch).sort()).toEqual(['hn/nfc', 'original'])
- const result = await readSessionGitPullRequest(agent, { history: true })
+ const result = await readSessionGitPullRequest(agent, { usage: async () => usage.get(agent), history: true })
expect(result).toMatchObject({ history: { pullRequests: [{ result: { status: 'found', number: 397, state: 'Merged' } }] } })
expect(agent.cwd).toBe(home)
})
@@ -179,7 +178,7 @@ describe('session work from transcript through Git and PR history', () => {
await receipt('elsewhere', home)
return { status: 'found', number: 12, state: 'Open', url: rows[0].html_url }
})
- expect(await readSessionGitPullRequest(agent, {
+ expect(await readSessionGitPullRequest(agent, { usage: async () => usage.get(agent),
expected: { cwd: ship, branch: 'hn/nfc', remote: 'github.com/acme/app' },
})).toMatchObject({ status: 'unavailable', context: { cwd: home, branch: 'original', remote: 'github.com/acme/app' } })
})
@@ -191,21 +190,21 @@ describe('session work from transcript through Git and PR history', () => {
expect(value.gitContext).toMatchObject({ state: 'multiple', current: null,
recentWork: { project: { cwd: ship, branch: 'hn/nfc' } } })
const expected = { cwd: ship, branch: 'hn/nfc', remote: 'github.com/acme/app' }
- expect(await readSessionGitPullRequest(agent, { expected })).toMatchObject({ status: 'found', number: 12, context: expected })
- expect((await readSessionGitPullRequest(agent, { expected: { ...expected, cwd: home, branch: 'original' } })).status).toBe('unavailable')
+ expect(await readSessionGitPullRequest(agent, { usage: async () => usage.get(agent), expected })).toMatchObject({ status: 'found', number: 12, context: expected })
+ expect((await readSessionGitPullRequest(agent, { usage: async () => usage.get(agent), expected: { ...expected, cwd: home, branch: 'original' } })).status).toBe('unavailable')
expect(agent.cwd).toBe(home)
})
it('refreshes the visible open-first page, including multiple PRs for one branch', async () => {
await receipt('nfc', ship)
rows = [pr(12, 'hn/nfc'), pr(14, 'hn/nfc')]
- await readSessionGitPullRequest(agent)
+ await readSessionGitPullRequest(agent, { usage: async () => usage.get(agent) })
for (const number of [20, 21, 22, 23]) {
const item = pr(number, 'old', true); rows.push(item)
await history.recordPullRequest(agent, { url: item.html_url, cwd: ship, at: '2026-09-27T16:00:00Z' },
{ status: 'found', number, url: item.html_url, state: 'Merged' }, '2026-09-27T16:00:00Z')
}
- const result = await readSessionGitPullRequest(agent, { history: true })
+ const result = await readSessionGitPullRequest(agent, { usage: async () => usage.get(agent), history: true })
expect('lookups' in result && result.lookups.map(p => p.url)).toEqual([12, 14, 20, 21].map(n => `https://github.com/acme/app/pull/${n}`))
})
})
diff --git a/cli/src/lib/sessionGitPullRequest.ts b/cli/src/lib/sessionGitPullRequest.ts
index 968b9f6f0..de8e92b28 100644
--- a/cli/src/lib/sessionGitPullRequest.ts
+++ b/cli/src/lib/sessionGitPullRequest.ts
@@ -1,6 +1,6 @@
import type { RegisteredSession } from './registry.js'
import { agentProject, forgetAgentProject } from './agentProject.js'
-import { agentTokenUsage } from './agentTokenUsage.js'
+import type { AgentTokenUsage } from './agentUsageWire.js'
import { sessionGitContext } from './sessionGitContext.js'
import { sessionGitHistory } from './sessionGitHistory.js'
import { readBranchPullRequest, readGitPullRequest, readPullRequestUrl } from './gitPullRequest.js'
@@ -9,9 +9,10 @@ export type ExpectedGitContext = { cwd: string; branch: string; remote: string |
/** The branch badge and session history share the same resolved checkout. Existing callers may
* omit expected context; new clients bind their reply to the branch they displayed when asking. */
export async function readSessionGitPullRequest(agent: RegisteredSession, options: {
+ usage?: () => Promise<AgentTokenUsage | null>;
expected?: ExpectedGitContext; history?: boolean; offset?: number;
} = {}) {
- const work = agentTokenUsage.get(agent)?.work
+ const work = (await options.usage?.())?.work
const resolve = async (observed = work) => {
const saved = await sessionGitHistory.get(agent)
if (options.history) for (const cwd of [agent.cwd, ...saved.branches.map(b => b.cwd), ...(observed?.current.map(b => b.cwd) ?? [])]) {
@@ -35,7 +36,7 @@ export async function readSessionGitPullRequest(agent: RegisteredSession, option
{ url: pr.url, cwd: current!.cwd, at: context.observedAt ?? checkedAt }, recorded, pr.checkedAt ?? checkedAt)
}
const refreshMovedWork = async () => {
- const latest = agentTokenUsage.get(agent)?.work
+ const latest = (await options.usage?.())?.work
if (JSON.stringify(latest) === JSON.stringify(work)) return
context = await resolve(latest)
await sessionGitHistory.observe(agent, context)
diff --git a/cli/src/lib/sessionSearch/__fixtures__/external-shapes.golden.json b/cli/src/lib/sessionSearch/__fixtures__/external-shapes.golden.json
new file mode 100644
index 000000000..bf7124ed5
--- /dev/null
+++ b/cli/src/lib/sessionSearch/__fixtures__/external-shapes.golden.json
@@ -0,0 +1,1222 @@
+{
+ "darwin": {
+ "cold": {},
+ "scan": [
+ {
+ "sessionId": "tip",
+ "engine": "hermes",
+ "cwd": "<fixture>/darwin/work",
+ "origin": "terminal",
+ "title": "",
+ "mtime": 400,
+ "transcriptPath": "<fixture>/darwin/work/tip.jsonl",
+ "aliases": [
+ "root",
+ "first"
+ ],
+ "launchArgs": [
+ "-p",
+ "work"
+ ]
+ },
+ {
+ "sessionId": "duplicate",
+ "engine": "hermes",
+ "cwd": "<fixture>/darwin/work",
+ "origin": "terminal",
+ "title": "",
+ "mtime": 200,
+ "transcriptPath": "<fixture>/darwin/work/duplicate.jsonl"
+ },
+ {
+ "sessionId": "first",
+ "engine": "claude",
+ "cwd": "<fixture>/darwin/work",
+ "origin": "terminal",
+ "title": "true",
+ "mtime": 100,
+ "transcriptPath": "<fixture>/darwin/work/first.jsonl"
+ }
+ ],
+ "alias": {
+ "sessionId": "tip",
+ "engine": "hermes",
+ "cwd": "<fixture>/darwin/work",
+ "origin": "terminal",
+ "title": "",
+ "mtime": 400,
+ "transcriptPath": "<fixture>/darwin/work/tip.jsonl",
+ "aliases": [
+ "root",
+ "first"
+ ],
+ "launchArgs": [
+ "-p",
+ "work"
+ ]
+ },
+ "collision": {
+ "sessionId": "first",
+ "engine": "claude",
+ "cwd": "<fixture>/darwin/work",
+ "origin": "terminal",
+ "title": "true",
+ "mtime": 100,
+ "transcriptPath": "<fixture>/darwin/work/first.jsonl"
+ },
+ "lastGood": [
+ {
+ "sessionId": "tip",
+ "engine": "hermes",
+ "cwd": "<fixture>/darwin/work",
+ "origin": "terminal",
+ "title": "",
+ "mtime": 400,
+ "transcriptPath": "<fixture>/darwin/work/tip.jsonl",
+ "aliases": [
+ "root",
+ "first"
+ ],
+ "launchArgs": [
+ "-p",
+ "work"
+ ]
+ },
+ {
+ "sessionId": "duplicate",
+ "engine": "hermes",
+ "cwd": "<fixture>/darwin/work",
+ "origin": "terminal",
+ "title": "",
+ "mtime": 200,
+ "transcriptPath": "<fixture>/darwin/work/duplicate.jsonl"
+ },
+ {
+ "sessionId": "first",
+ "engine": "claude",
+ "cwd": "<fixture>/darwin/work",
+ "origin": "terminal",
+ "title": "true",
+ "mtime": 100,
+ "transcriptPath": "<fixture>/darwin/work/first.jsonl"
+ }
+ ],
+ "logs": [
+ "[search] hermes sessions not read: store unavailable",
+ "[search] hermes sessions not read: store unavailable",
+ "[search] hermes sessions not read: store unavailable"
+ ],
+ "missing": null,
+ "busy/claude": false,
+ "busy/codex": true,
+ "busy/grok": true,
+ "busy/pi": true,
+ "free/open": {},
+ "free/owner": null,
+ "free/working": false,
+ "free/null": {
+ "ok": true,
+ "cwd": "<fixture>/darwin/work",
+ "title": "Indexed title",
+ "owner": null,
+ "busy": false,
+ "launchArgs": []
+ },
+ "free/idle": {
+ "ok": true,
+ "cwd": "<fixture>/darwin/work",
+ "title": "Indexed title",
+ "owner": null,
+ "busy": false,
+ "launchArgs": []
+ },
+ "free/now": {
+ "ok": true,
+ "cwd": "<fixture>/darwin/work",
+ "title": "Indexed title",
+ "owner": null,
+ "busy": false,
+ "launchArgs": []
+ },
+ "free/wait": {
+ "ok": true,
+ "cwd": "<fixture>/darwin/work",
+ "title": "Indexed title",
+ "owner": null,
+ "busy": false,
+ "launchArgs": []
+ },
+ "free/heldBy": "free",
+ "terminal/open": {
+ "conversation": "terminal"
+ },
+ "terminal/owner": {
+ "pid": 7,
+ "engine": "claude",
+ "tty": "/dev/fixture-terminal",
+ "record": "/fixture/record"
+ },
+ "terminal/working": false,
+ "terminal/null": {
+ "ok": false,
+ "error": "SESSION_OPEN_IN_TERMINAL",
+ "detail": "It is open in Claude in a terminal. Moving it here quits it there."
+ },
+ "terminal/idle": {
+ "ok": true,
+ "cwd": "<fixture>/darwin/work",
+ "title": "Indexed title",
+ "owner": {
+ "pid": 7,
+ "engine": "claude",
+ "tty": "/dev/fixture-terminal",
+ "record": "/fixture/record"
+ },
+ "busy": false,
+ "launchArgs": []
+ },
+ "terminal/now": {
+ "ok": true,
+ "cwd": "<fixture>/darwin/work",
+ "title": "Indexed title",
+ "owner": {
+ "pid": 7,
+ "engine": "claude",
+ "tty": "/dev/fixture-terminal",
+ "record": "/fixture/record"
+ },
+ "busy": false,
+ "launchArgs": []
+ },
+ "terminal/wait": {
+ "ok": true,
+ "cwd": "<fixture>/darwin/work",
+ "title": "Indexed title",
+ "owner": {
+ "pid": 7,
+ "engine": "claude",
+ "tty": "/dev/fixture-terminal",
+ "record": "/fixture/record"
+ },
+ "busy": false,
+ "launchArgs": []
+ },
+ "terminal/heldBy": "same",
+ "busy/open": {
+ "conversation": "terminal"
+ },
+ "busy/owner": {
+ "pid": 7,
+ "engine": "claude",
+ "tty": "/dev/fixture-terminal",
+ "record": "/fixture/record"
+ },
+ "busy/working": true,
+ "busy/null": {
+ "ok": false,
+ "error": "SESSION_BUSY_IN_TERMINAL",
+ "detail": "Claude is working on it in a terminal."
+ },
+ "busy/idle": {
+ "ok": false,
+ "error": "SESSION_BUSY_IN_TERMINAL",
+ "detail": "Claude is working on it in a terminal."
+ },
+ "busy/now": {
+ "ok": true,
+ "cwd": "<fixture>/darwin/work",
+ "title": "Indexed title",
+ "owner": {
+ "pid": 7,
+ "engine": "claude",
+ "tty": "/dev/fixture-terminal",
+ "record": "/fixture/record"
+ },
+ "busy": true,
+ "launchArgs": []
+ },
+ "busy/wait": {
+ "ok": true,
+ "cwd": "<fixture>/darwin/work",
+ "title": "Indexed title",
+ "owner": {
+ "pid": 7,
+ "engine": "claude",
+ "tty": "/dev/fixture-terminal",
+ "record": "/fixture/record"
+ },
+ "busy": true,
+ "launchArgs": []
+ },
+ "busy/heldBy": "same",
+ "unknown-busy/open": {
+ "conversation": "terminal"
+ },
+ "unknown-busy/owner": {
+ "pid": 7,
+ "engine": "claude",
+ "tty": "/dev/fixture-terminal",
+ "record": "/fixture/record"
+ },
+ "unknown-busy/working": null,
+ "unknown-busy/null": {
+ "ok": false,
+ "error": "SESSION_BUSY_IN_TERMINAL",
+ "detail": "Claude is working on it in a terminal."
+ },
+ "unknown-busy/idle": {
+ "ok": false,
+ "error": "SESSION_BUSY_IN_TERMINAL",
+ "detail": "Claude is working on it in a terminal."
+ },
+ "unknown-busy/now": {
+ "ok": true,
+ "cwd": "<fixture>/darwin/work",
+ "title": "Indexed title",
+ "owner": {
+ "pid": 7,
+ "engine": "claude",
+ "tty": "/dev/fixture-terminal",
+ "record": "/fixture/record"
+ },
+ "busy": true,
+ "launchArgs": []
+ },
+ "unknown-busy/wait": {
+ "ok": true,
+ "cwd": "<fixture>/darwin/work",
+ "title": "Indexed title",
+ "owner": {
+ "pid": 7,
+ "engine": "claude",
+ "tty": "/dev/fixture-terminal",
+ "record": "/fixture/record"
+ },
+ "busy": true,
+ "launchArgs": []
+ },
+ "unknown-busy/heldBy": "same",
+ "app/open": {
+ "conversation": "app"
+ },
+ "app/owner": {
+ "pid": 7,
+ "engine": "claude",
+ "tty": null,
+ "record": "/fixture/record"
+ },
+ "app/working": null,
+ "app/null": {
+ "ok": false,
+ "error": "SESSION_OPEN_ELSEWHERE",
+ "detail": "It is open in Claude's app or an editor. Close it there, then open it here."
+ },
+ "app/idle": {
+ "ok": false,
+ "error": "SESSION_OPEN_ELSEWHERE",
+ "detail": "It is open in Claude's app or an editor. Close it there, then open it here."
+ },
+ "app/now": {
+ "ok": false,
+ "error": "SESSION_OPEN_ELSEWHERE",
+ "detail": "It is open in Claude's app or an editor. Close it there, then open it here."
+ },
+ "app/wait": {
+ "ok": false,
+ "error": "SESSION_OPEN_ELSEWHERE",
+ "detail": "It is open in Claude's app or an editor. Close it there, then open it here."
+ },
+ "app/heldBy": "other",
+ "args-only/open": {
+ "conversation": "maybe"
+ },
+ "args-only/owner": {
+ "pid": 7,
+ "engine": "claude",
+ "tty": "/dev/fixture-terminal",
+ "record": "/fixture/record",
+ "fromArgs": true
+ },
+ "args-only/working": null,
+ "args-only/null": {
+ "ok": false,
+ "error": "SESSION_OPEN_ELSEWHERE",
+ "detail": "It may be open in Claude in a terminal. Close it there, then open it here."
+ },
+ "args-only/idle": {
+ "ok": false,
+ "error": "SESSION_OPEN_ELSEWHERE",
+ "detail": "It may be open in Claude in a terminal. Close it there, then open it here."
+ },
+ "args-only/now": {
+ "ok": false,
+ "error": "SESSION_OPEN_ELSEWHERE",
+ "detail": "It may be open in Claude in a terminal. Close it there, then open it here."
+ },
+ "args-only/wait": {
+ "ok": false,
+ "error": "SESSION_OPEN_ELSEWHERE",
+ "detail": "It may be open in Claude in a terminal. Close it there, then open it here."
+ },
+ "args-only/heldBy": "other",
+ "harness/open": {
+ "conversation": "harness"
+ },
+ "harness/owner": {
+ "pid": 7,
+ "engine": "claude",
+ "tty": "/dev/fixture-terminal",
+ "record": "/fixture/record",
+ "harness": true
+ },
+ "harness/working": null,
+ "harness/null": {
+ "ok": false,
+ "error": "SESSION_IN_HARNESS",
+ "detail": "This conversation is already a harness here."
+ },
+ "harness/idle": {
+ "ok": false,
+ "error": "SESSION_IN_HARNESS",
+ "detail": "This conversation is already a harness here."
+ },
+ "harness/now": {
+ "ok": false,
+ "error": "SESSION_IN_HARNESS",
+ "detail": "This conversation is already a harness here."
+ },
+ "harness/wait": {
+ "ok": false,
+ "error": "SESSION_IN_HARNESS",
+ "detail": "This conversation is already a harness here."
+ },
+ "harness/heldBy": "other",
+ "unverified/open": {
+ "conversation": "maybe"
+ },
+ "unverified/owner": {
+ "pid": 7,
+ "engine": "claude",
+ "tty": "/dev/fixture-terminal",
+ "record": "/fixture/record",
+ "unverified": true
+ },
+ "unverified/working": null,
+ "unverified/null": {
+ "ok": false,
+ "error": "SESSION_OPEN_ELSEWHERE",
+ "detail": "It may be open in Claude in a terminal. Close it there, then open it here."
+ },
+ "unverified/idle": {
+ "ok": false,
+ "error": "SESSION_OPEN_ELSEWHERE",
+ "detail": "It may be open in Claude in a terminal. Close it there, then open it here."
+ },
+ "unverified/now": {
+ "ok": false,
+ "error": "SESSION_OPEN_ELSEWHERE",
+ "detail": "It may be open in Claude in a terminal. Close it there, then open it here."
+ },
+ "unverified/wait": {
+ "ok": false,
+ "error": "SESSION_OPEN_ELSEWHERE",
+ "detail": "It may be open in Claude in a terminal. Close it there, then open it here."
+ },
+ "unverified/heldBy": "other",
+ "no-tty/open": {
+ "conversation": "app"
+ },
+ "no-tty/owner": {
+ "pid": 7,
+ "engine": "claude",
+ "tty": null,
+ "record": "/fixture/record"
+ },
+ "no-tty/working": null,
+ "no-tty/null": {
+ "ok": false,
+ "error": "SESSION_OPEN_ELSEWHERE",
+ "detail": "It is open in Claude's app or an editor. Close it there, then open it here."
+ },
+ "no-tty/idle": {
+ "ok": false,
+ "error": "SESSION_OPEN_ELSEWHERE",
+ "detail": "It is open in Claude's app or an editor. Close it there, then open it here."
+ },
+ "no-tty/now": {
+ "ok": false,
+ "error": "SESSION_OPEN_ELSEWHERE",
+ "detail": "It is open in Claude's app or an editor. Close it there, then open it here."
+ },
+ "no-tty/wait": {
+ "ok": false,
+ "error": "SESSION_OPEN_ELSEWHERE",
+ "detail": "It is open in Claude's app or an editor. Close it there, then open it here."
+ },
+ "no-tty/heldBy": "other",
+ "archived/open": {},
+ "archived/owner": null,
+ "archived/working": false,
+ "archived/null": {
+ "ok": false,
+ "error": "SESSION_ARCHIVED",
+ "detail": "Codex archived this conversation. Run `codex unarchive conversation` in a terminal, then open it here."
+ },
+ "archived/idle": {
+ "ok": false,
+ "error": "SESSION_ARCHIVED",
+ "detail": "Codex archived this conversation. Run `codex unarchive conversation` in a terminal, then open it here."
+ },
+ "archived/now": {
+ "ok": false,
+ "error": "SESSION_ARCHIVED",
+ "detail": "Codex archived this conversation. Run `codex unarchive conversation` in a terminal, then open it here."
+ },
+ "archived/wait": {
+ "ok": false,
+ "error": "SESSION_ARCHIVED",
+ "detail": "Codex archived this conversation. Run `codex unarchive conversation` in a terminal, then open it here."
+ },
+ "archived/heldBy": "free",
+ "gone-folder/open": {},
+ "gone-folder/owner": null,
+ "gone-folder/working": false,
+ "gone-folder/null": {
+ "ok": false,
+ "error": "SESSION_FOLDER_GONE",
+ "detail": "The folder it ran in is gone: <fixture>/missing"
+ },
+ "gone-folder/idle": {
+ "ok": false,
+ "error": "SESSION_FOLDER_GONE",
+ "detail": "The folder it ran in is gone: <fixture>/missing"
+ },
+ "gone-folder/now": {
+ "ok": false,
+ "error": "SESSION_FOLDER_GONE",
+ "detail": "The folder it ran in is gone: <fixture>/missing"
+ },
+ "gone-folder/wait": {
+ "ok": false,
+ "error": "SESSION_FOLDER_GONE",
+ "detail": "The folder it ran in is gone: <fixture>/missing"
+ },
+ "gone-folder/heldBy": "free",
+ "owned/open": {},
+ "owned/owner": null,
+ "owned/working": false,
+ "owned/null": {
+ "ok": false,
+ "error": "SESSION_IN_HARNESS",
+ "detail": "This conversation is already a harness here."
+ },
+ "owned/idle": {
+ "ok": false,
+ "error": "SESSION_IN_HARNESS",
+ "detail": "This conversation is already a harness here."
+ },
+ "owned/now": {
+ "ok": false,
+ "error": "SESSION_IN_HARNESS",
+ "detail": "This conversation is already a harness here."
+ },
+ "owned/wait": {
+ "ok": false,
+ "error": "SESSION_IN_HARNESS",
+ "detail": "This conversation is already a harness here."
+ },
+ "owned/heldBy": "free",
+ "saved-alias/open": {},
+ "saved-alias/owner": null,
+ "saved-alias/working": false,
+ "saved-alias/null": {
+ "ok": false,
+ "error": "SESSION_IN_HARNESS",
+ "detail": "This conversation is already a harness here."
+ },
+ "saved-alias/idle": {
+ "ok": false,
+ "error": "SESSION_IN_HARNESS",
+ "detail": "This conversation is already a harness here."
+ },
+ "saved-alias/now": {
+ "ok": false,
+ "error": "SESSION_IN_HARNESS",
+ "detail": "This conversation is already a harness here."
+ },
+ "saved-alias/wait": {
+ "ok": false,
+ "error": "SESSION_IN_HARNESS",
+ "detail": "This conversation is already a harness here."
+ },
+ "saved-alias/heldBy": "free",
+ "profile/open": {},
+ "profile/owner": null,
+ "profile/working": false,
+ "profile/null": {
+ "ok": true,
+ "cwd": "<fixture>/darwin/work",
+ "title": "Named conversation",
+ "owner": null,
+ "busy": false,
+ "launchArgs": [
+ "-p",
+ "work"
+ ]
+ },
+ "profile/idle": {
+ "ok": true,
+ "cwd": "<fixture>/darwin/work",
+ "title": "Named conversation",
+ "owner": null,
+ "busy": false,
+ "launchArgs": [
+ "-p",
+ "work"
+ ]
+ },
+ "profile/now": {
+ "ok": true,
+ "cwd": "<fixture>/darwin/work",
+ "title": "Named conversation",
+ "owner": null,
+ "busy": false,
+ "launchArgs": [
+ "-p",
+ "work"
+ ]
+ },
+ "profile/wait": {
+ "ok": true,
+ "cwd": "<fixture>/darwin/work",
+ "title": "Named conversation",
+ "owner": null,
+ "busy": false,
+ "launchArgs": [
+ "-p",
+ "work"
+ ]
+ },
+ "profile/heldBy": "free",
+ "wrongEngine": {
+ "ok": false,
+ "error": "INVALID_ENGINE",
+ "detail": "This is a claude conversation."
+ },
+ "notFound": {
+ "ok": false,
+ "error": "SESSION_NOT_FOUND",
+ "detail": "This conversation is no longer on this machine."
+ }
+ },
+ "linux": {
+ "cold": {},
+ "scan": [
+ {
+ "sessionId": "tip",
+ "engine": "hermes",
+ "cwd": "<fixture>/linux/work",
+ "origin": "terminal",
+ "title": "",
+ "mtime": 400,
+ "transcriptPath": "<fixture>/linux/work/tip.jsonl",
+ "aliases": [
+ "root",
+ "first"
+ ],
+ "launchArgs": [
+ "-p",
+ "work"
+ ]
+ },
+ {
+ "sessionId": "duplicate",
+ "engine": "hermes",
+ "cwd": "<fixture>/linux/work",
+ "origin": "terminal",
+ "title": "",
+ "mtime": 200,
+ "transcriptPath": "<fixture>/linux/work/duplicate.jsonl"
+ },
+ {
+ "sessionId": "first",
+ "engine": "claude",
+ "cwd": "<fixture>/linux/work",
+ "origin": "terminal",
+ "title": "true",
+ "mtime": 100,
+ "transcriptPath": "<fixture>/linux/work/first.jsonl"
+ }
+ ],
+ "alias": {
+ "sessionId": "tip",
+ "engine": "hermes",
+ "cwd": "<fixture>/linux/work",
+ "origin": "terminal",
+ "title": "",
+ "mtime": 400,
+ "transcriptPath": "<fixture>/linux/work/tip.jsonl",
+ "aliases": [
+ "root",
+ "first"
+ ],
+ "launchArgs": [
+ "-p",
+ "work"
+ ]
+ },
+ "collision": {
+ "sessionId": "first",
+ "engine": "claude",
+ "cwd": "<fixture>/linux/work",
+ "origin": "terminal",
+ "title": "true",
+ "mtime": 100,
+ "transcriptPath": "<fixture>/linux/work/first.jsonl"
+ },
+ "lastGood": [
+ {
+ "sessionId": "tip",
+ "engine": "hermes",
+ "cwd": "<fixture>/linux/work",
+ "origin": "terminal",
+ "title": "",
+ "mtime": 400,
+ "transcriptPath": "<fixture>/linux/work/tip.jsonl",
+ "aliases": [
+ "root",
+ "first"
+ ],
+ "launchArgs": [
+ "-p",
+ "work"
+ ]
+ },
+ {
+ "sessionId": "duplicate",
+ "engine": "hermes",
+ "cwd": "<fixture>/linux/work",
+ "origin": "terminal",
+ "title": "",
+ "mtime": 200,
+ "transcriptPath": "<fixture>/linux/work/duplicate.jsonl"
+ },
+ {
+ "sessionId": "first",
+ "engine": "claude",
+ "cwd": "<fixture>/linux/work",
+ "origin": "terminal",
+ "title": "true",
+ "mtime": 100,
+ "transcriptPath": "<fixture>/linux/work/first.jsonl"
+ }
+ ],
+ "logs": [
+ "[search] hermes sessions not read: store unavailable",
+ "[search] hermes sessions not read: store unavailable",
+ "[search] hermes sessions not read: store unavailable"
+ ],
+ "missing": null,
+ "busy/claude": false,
+ "busy/codex": true,
+ "busy/grok": true,
+ "busy/pi": true,
+ "free/open": {},
+ "free/owner": null,
+ "free/working": false,
+ "free/null": {
+ "ok": true,
+ "cwd": "<fixture>/linux/work",
+ "title": "Indexed title",
+ "owner": null,
+ "busy": false,
+ "launchArgs": []
+ },
+ "free/idle": {
+ "ok": true,
+ "cwd": "<fixture>/linux/work",
+ "title": "Indexed title",
+ "owner": null,
+ "busy": false,
+ "launchArgs": []
+ },
+ "free/now": {
+ "ok": true,
+ "cwd": "<fixture>/linux/work",
+ "title": "Indexed title",
+ "owner": null,
+ "busy": false,
+ "launchArgs": []
+ },
+ "free/wait": {
+ "ok": true,
+ "cwd": "<fixture>/linux/work",
+ "title": "Indexed title",
+ "owner": null,
+ "busy": false,
+ "launchArgs": []
+ },
+ "free/heldBy": "free",
+ "terminal/open": {
+ "conversation": "terminal"
+ },
+ "terminal/owner": {
+ "pid": 7,
+ "engine": "claude",
+ "tty": "/dev/fixture-terminal",
+ "record": "/fixture/record"
+ },
+ "terminal/working": false,
+ "terminal/null": {
+ "ok": false,
+ "error": "SESSION_OPEN_IN_TERMINAL",
+ "detail": "It is open in Claude in a terminal. Moving it here quits it there."
+ },
+ "terminal/idle": {
+ "ok": true,
+ "cwd": "<fixture>/linux/work",
+ "title": "Indexed title",
+ "owner": {
+ "pid": 7,
+ "engine": "claude",
+ "tty": "/dev/fixture-terminal",
+ "record": "/fixture/record"
+ },
+ "busy": false,
+ "launchArgs": []
+ },
+ "terminal/now": {
+ "ok": true,
+ "cwd": "<fixture>/linux/work",
+ "title": "Indexed title",
+ "owner": {
+ "pid": 7,
+ "engine": "claude",
+ "tty": "/dev/fixture-terminal",
+ "record": "/fixture/record"
+ },
+ "busy": false,
+ "launchArgs": []
+ },
+ "terminal/wait": {
+ "ok": true,
+ "cwd": "<fixture>/linux/work",
+ "title": "Indexed title",
+ "owner": {
+ "pid": 7,
+ "engine": "claude",
+ "tty": "/dev/fixture-terminal",
+ "record": "/fixture/record"
+ },
+ "busy": false,
+ "launchArgs": []
+ },
+ "terminal/heldBy": "same",
+ "busy/open": {
+ "conversation": "terminal"
+ },
+ "busy/owner": {
+ "pid": 7,
+ "engine": "claude",
+ "tty": "/dev/fixture-terminal",
+ "record": "/fixture/record"
+ },
+ "busy/working": true,
+ "busy/null": {
+ "ok": false,
+ "error": "SESSION_BUSY_IN_TERMINAL",
+ "detail": "Claude is working on it in a terminal."
+ },
+ "busy/idle": {
+ "ok": false,
+ "error": "SESSION_BUSY_IN_TERMINAL",
+ "detail": "Claude is working on it in a terminal."
+ },
+ "busy/now": {
+ "ok": true,
+ "cwd": "<fixture>/linux/work",
+ "title": "Indexed title",
+ "owner": {
+ "pid": 7,
+ "engine": "claude",
+ "tty": "/dev/fixture-terminal",
+ "record": "/fixture/record"
+ },
+ "busy": true,
+ "launchArgs": []
+ },
+ "busy/wait": {
+ "ok": true,
+ "cwd": "<fixture>/linux/work",
+ "title": "Indexed title",
+ "owner": {
+ "pid": 7,
+ "engine": "claude",
+ "tty": "/dev/fixture-terminal",
+ "record": "/fixture/record"
+ },
+ "busy": true,
+ "launchArgs": []
+ },
+ "busy/heldBy": "same",
+ "unknown-busy/open": {
+ "conversation": "terminal"
+ },
+ "unknown-busy/owner": {
+ "pid": 7,
+ "engine": "claude",
+ "tty": "/dev/fixture-terminal",
+ "record": "/fixture/record"
+ },
+ "unknown-busy/working": null,
+ "unknown-busy/null": {
+ "ok": false,
+ "error": "SESSION_BUSY_IN_TERMINAL",
+ "detail": "Claude is working on it in a terminal."
+ },
+ "unknown-busy/idle": {
+ "ok": false,
+ "error": "SESSION_BUSY_IN_TERMINAL",
+ "detail": "Claude is working on it in a terminal."
+ },
+ "unknown-busy/now": {
+ "ok": true,
+ "cwd": "<fixture>/linux/work",
+ "title": "Indexed title",
+ "owner": {
+ "pid": 7,
+ "engine": "claude",
+ "tty": "/dev/fixture-terminal",
+ "record": "/fixture/record"
+ },
+ "busy": true,
+ "launchArgs": []
+ },
+ "unknown-busy/wait": {
+ "ok": true,
+ "cwd": "<fixture>/linux/work",
+ "title": "Indexed title",
+ "owner": {
+ "pid": 7,
+ "engine": "claude",
+ "tty": "/dev/fixture-terminal",
+ "record": "/fixture/record"
+ },
+ "busy": true,
+ "launchArgs": []
+ },
+ "unknown-busy/heldBy": "same",
+ "app/open": {
+ "conversation": "app"
+ },
+ "app/owner": {
+ "pid": 7,
+ "engine": "claude",
+ "tty": null,
+ "record": "/fixture/record"
+ },
+ "app/working": null,
+ "app/null": {
+ "ok": false,
+ "error": "SESSION_OPEN_ELSEWHERE",
+ "detail": "It is open in Claude's app or an editor. Close it there, then open it here."
+ },
+ "app/idle": {
+ "ok": false,
+ "error": "SESSION_OPEN_ELSEWHERE",
+ "detail": "It is open in Claude's app or an editor. Close it there, then open it here."
+ },
+ "app/now": {
+ "ok": false,
+ "error": "SESSION_OPEN_ELSEWHERE",
+ "detail": "It is open in Claude's app or an editor. Close it there, then open it here."
+ },
+ "app/wait": {
+ "ok": false,
+ "error": "SESSION_OPEN_ELSEWHERE",
+ "detail": "It is open in Claude's app or an editor. Close it there, then open it here."
+ },
+ "app/heldBy": "other",
+ "args-only/open": {
+ "conversation": "maybe"
+ },
+ "args-only/owner": {
+ "pid": 7,
+ "engine": "claude",
+ "tty": "/dev/fixture-terminal",
+ "record": "/fixture/record",
+ "fromArgs": true
+ },
+ "args-only/working": null,
+ "args-only/null": {
+ "ok": false,
+ "error": "SESSION_OPEN_ELSEWHERE",
+ "detail": "It may be open in Claude in a terminal. Close it there, then open it here."
+ },
+ "args-only/idle": {
+ "ok": false,
+ "error": "SESSION_OPEN_ELSEWHERE",
+ "detail": "It may be open in Claude in a terminal. Close it there, then open it here."
+ },
+ "args-only/now": {
+ "ok": false,
+ "error": "SESSION_OPEN_ELSEWHERE",
+ "detail": "It may be open in Claude in a terminal. Close it there, then open it here."
+ },
+ "args-only/wait": {
+ "ok": false,
+ "error": "SESSION_OPEN_ELSEWHERE",
+ "detail": "It may be open in Claude in a terminal. Close it there, then open it here."
+ },
+ "args-only/heldBy": "other",
+ "harness/open": {
+ "conversation": "harness"
+ },
+ "harness/owner": {
+ "pid": 7,
+ "engine": "claude",
+ "tty": "/dev/fixture-terminal",
+ "record": "/fixture/record",
+ "harness": true
+ },
+ "harness/working": null,
+ "harness/null": {
+ "ok": false,
+ "error": "SESSION_IN_HARNESS",
+ "detail": "This conversation is already a harness here."
+ },
+ "harness/idle": {
+ "ok": false,
+ "error": "SESSION_IN_HARNESS",
+ "detail": "This conversation is already a harness here."
+ },
+ "harness/now": {
+ "ok": false,
+ "error": "SESSION_IN_HARNESS",
+ "detail": "This conversation is already a harness here."
+ },
+ "harness/wait": {
+ "ok": false,
+ "error": "SESSION_IN_HARNESS",
+ "detail": "This conversation is already a harness here."
+ },
+ "harness/heldBy": "other",
+ "unverified/open": {
+ "conversation": "maybe"
+ },
+ "unverified/owner": {
+ "pid": 7,
+ "engine": "claude",
+ "tty": "/dev/fixture-terminal",
+ "record": "/fixture/record",
+ "unverified": true
+ },
+ "unverified/working": null,
+ "unverified/null": {
+ "ok": false,
+ "error": "SESSION_OPEN_ELSEWHERE",
+ "detail": "It may be open in Claude in a terminal. Close it there, then open it here."
+ },
+ "unverified/idle": {
+ "ok": false,
+ "error": "SESSION_OPEN_ELSEWHERE",
+ "detail": "It may be open in Claude in a terminal. Close it there, then open it here."
+ },
+ "unverified/now": {
+ "ok": false,
+ "error": "SESSION_OPEN_ELSEWHERE",
+ "detail": "It may be open in Claude in a terminal. Close it there, then open it here."
+ },
+ "unverified/wait": {
+ "ok": false,
+ "error": "SESSION_OPEN_ELSEWHERE",
+ "detail": "It may be open in Claude in a terminal. Close it there, then open it here."
+ },
+ "unverified/heldBy": "other",
+ "no-tty/open": {
+ "conversation": "app"
+ },
+ "no-tty/owner": {
+ "pid": 7,
+ "engine": "claude",
+ "tty": null,
+ "record": "/fixture/record"
+ },
+ "no-tty/working": null,
+ "no-tty/null": {
+ "ok": false,
+ "error": "SESSION_OPEN_ELSEWHERE",
+ "detail": "It is open in Claude's app or an editor. Close it there, then open it here."
+ },
+ "no-tty/idle": {
+ "ok": false,
+ "error": "SESSION_OPEN_ELSEWHERE",
+ "detail": "It is open in Claude's app or an editor. Close it there, then open it here."
+ },
+ "no-tty/now": {
+ "ok": false,
+ "error": "SESSION_OPEN_ELSEWHERE",
+ "detail": "It is open in Claude's app or an editor. Close it there, then open it here."
+ },
+ "no-tty/wait": {
+ "ok": false,
+ "error": "SESSION_OPEN_ELSEWHERE",
+ "detail": "It is open in Claude's app or an editor. Close it there, then open it here."
+ },
+ "no-tty/heldBy": "other",
+ "archived/open": {},
+ "archived/owner": null,
+ "archived/working": false,
+ "archived/null": {
+ "ok": false,
+ "error": "SESSION_ARCHIVED",
+ "detail": "Codex archived this conversation. Run `codex unarchive conversation` in a terminal, then open it here."
+ },
+ "archived/idle": {
+ "ok": false,
+ "error": "SESSION_ARCHIVED",
+ "detail": "Codex archived this conversation. Run `codex unarchive conversation` in a terminal, then open it here."
+ },
+ "archived/now": {
+ "ok": false,
+ "error": "SESSION_ARCHIVED",
+ "detail": "Codex archived this conversation. Run `codex unarchive conversation` in a terminal, then open it here."
+ },
+ "archived/wait": {
+ "ok": false,
+ "error": "SESSION_ARCHIVED",
+ "detail": "Codex archived this conversation. Run `codex unarchive conversation` in a terminal, then open it here."
+ },
+ "archived/heldBy": "free",
+ "gone-folder/open": {},
+ "gone-folder/owner": null,
+ "gone-folder/working": false,
+ "gone-folder/null": {
+ "ok": false,
+ "error": "SESSION_FOLDER_GONE",
+ "detail": "The folder it ran in is gone: <fixture>/missing"
+ },
+ "gone-folder/idle": {
+ "ok": false,
+ "error": "SESSION_FOLDER_GONE",
+ "detail": "The folder it ran in is gone: <fixture>/missing"
+ },
+ "gone-folder/now": {
+ "ok": false,
+ "error": "SESSION_FOLDER_GONE",
+ "detail": "The folder it ran in is gone: <fixture>/missing"
+ },
+ "gone-folder/wait": {
+ "ok": false,
+ "error": "SESSION_FOLDER_GONE",
+ "detail": "The folder it ran in is gone: <fixture>/missing"
+ },
+ "gone-folder/heldBy": "free",
+ "owned/open": {},
+ "owned/owner": null,
+ "owned/working": false,
+ "owned/null": {
+ "ok": false,
+ "error": "SESSION_IN_HARNESS",
+ "detail": "This conversation is already a harness here."
+ },
+ "owned/idle": {
+ "ok": false,
+ "error": "SESSION_IN_HARNESS",
+ "detail": "This conversation is already a harness here."
+ },
+ "owned/now": {
+ "ok": false,
+ "error": "SESSION_IN_HARNESS",
+ "detail": "This conversation is already a harness here."
+ },
+ "owned/wait": {
+ "ok": false,
+ "error": "SESSION_IN_HARNESS",
+ "detail": "This conversation is already a harness here."
+ },
+ "owned/heldBy": "free",
+ "saved-alias/open": {},
+ "saved-alias/owner": null,
+ "saved-alias/working": false,
+ "saved-alias/null": {
+ "ok": false,
+ "error": "SESSION_IN_HARNESS",
+ "detail": "This conversation is already a harness here."
+ },
+ "saved-alias/idle": {
+ "ok": false,
+ "error": "SESSION_IN_HARNESS",
+ "detail": "This conversation is already a harness here."
+ },
+ "saved-alias/now": {
+ "ok": false,
+ "error": "SESSION_IN_HARNESS",
+ "detail": "This conversation is already a harness here."
+ },
+ "saved-alias/wait": {
+ "ok": false,
+ "error": "SESSION_IN_HARNESS",
+ "detail": "This conversation is already a harness here."
+ },
+ "saved-alias/heldBy": "free",
+ "profile/open": {},
+ "profile/owner": null,
+ "profile/working": false,
+ "profile/null": {
+ "ok": true,
+ "cwd": "<fixture>/linux/work",
+ "title": "Named conversation",
+ "owner": null,
+ "busy": false,
+ "launchArgs": [
+ "-p",
+ "work"
+ ]
+ },
+ "profile/idle": {
+ "ok": true,
+ "cwd": "<fixture>/linux/work",
+ "title": "Named conversation",
+ "owner": null,
+ "busy": false,
+ "launchArgs": [
+ "-p",
+ "work"
+ ]
+ },
+ "profile/now": {
+ "ok": true,
+ "cwd": "<fixture>/linux/work",
+ "title": "Named conversation",
+ "owner": null,
+ "busy": false,
+ "launchArgs": [
+ "-p",
+ "work"
+ ]
+ },
+ "profile/wait": {
+ "ok": true,
+ "cwd": "<fixture>/linux/work",
+ "title": "Named conversation",
+ "owner": null,
+ "busy": false,
+ "launchArgs": [
+ "-p",
+ "work"
+ ]
+ },
+ "profile/heldBy": "free",
+ "wrongEngine": {
+ "ok": false,
+ "error": "INVALID_ENGINE",
+ "detail": "This is a claude conversation."
+ },
+ "notFound": {
+ "ok": false,
+ "error": "SESSION_NOT_FOUND",
+ "detail": "This conversation is no longer on this machine."
+ }
+ }
+}
diff --git a/cli/src/lib/sessionSearch/externalShapes.golden.spec.ts b/cli/src/lib/sessionSearch/externalShapes.golden.spec.ts
new file mode 100644
index 000000000..b7555be6e
--- /dev/null
+++ b/cli/src/lib/sessionSearch/externalShapes.golden.spec.ts
@@ -0,0 +1,89 @@
+/** Former-code record: optional readers provide facts; core alone admits or stops a conversation. */
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { expect, it, vi } from 'vitest'
+import type { ExternalProvider, ExternalSession, OwnerClaim, ProcessView } from './externals/types.js'
+
+process.env.TZ = 'UTC'
+const golden = fileURLToPath(new URL('./__fixtures__/external-shapes.golden.json', import.meta.url))
+const quiet: ProcessView = { list: async () => [], openFiles: async () => new Map(), openFilesOf: async () => new Map(), alive: () => true }
+
+it('preserves external lists, exact ownership, conservative busy answers and core admission on both platforms', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'external-shapes-'))
+ const platform = Object.getOwnPropertyDescriptor(process, 'platform')!
+ const result: Record<string, unknown> = {}
+ try {
+ for (const os of ['darwin', 'linux']) {
+ Object.defineProperty(process, 'platform', { value: os })
+ vi.resetModules()
+ const { externalShapes } = await import('../../testing/observerShapes.js')
+ const work = join(root, os, 'work')
+ mkdirSync(work, { recursive: true })
+ const session = (id: string, extra: Partial<ExternalSession> = {}): ExternalSession => ({
+ sessionId: id, engine: 'claude', cwd: work, origin: 'terminal', title: '', mtime: 100,
+ transcriptPath: join(work, id + '.jsonl'), ...extra,
+ })
+ let broken = false
+ const logs: string[] = []
+ const providers: ExternalProvider[] = [
+ { engine: 'claude', scan: async ctx => [session('first', { title: String(ctx.excluded(join(work, 'private'))) }), session('duplicate')] },
+ { engine: 'hermes', scan: async () => { if (broken) throw new Error('store unavailable'); return [
+ session('tip', { engine: 'hermes', mtime: 400, aliases: ['root', 'first'], launchArgs: ['-p', 'work'] }),
+ session('duplicate', { engine: 'hermes', mtime: 200 }),
+ ] } },
+ ]
+ const own = { bySession: () => undefined, byAgent: () => undefined, stoppedAgents: { list: () => [] }, search: { session: () => ({ title: 'Indexed title' }) } }
+ const openOptions = { providers, view: () => quiet, ttys: async () => new Map<number, string | null>(), harnessTtys: async () => new Set<string>(), now: () => 1000 }
+ const shapes = externalShapes({ providers, excluded: [work], log: line => logs.push(line) }, openOptions, own)
+ const out: Record<string, unknown> = { cold: shapes.known(), scan: await shapes.scan(), alias: await shapes.lookup('root'), collision: await shapes.lookup('first') }
+ broken = true
+ out.lastGood = await shapes.scan()
+ out.logs = logs
+ out.missing = await shapes.lookup('missing') ?? null
+ for (const engine of ['claude', 'codex', 'grok', 'pi'] as const) {
+ const p: ExternalProvider = { engine, scan: async () => [], busy: engine === 'claude' ? async () => false
+ : engine === 'codex' ? async () => true : engine === 'grok' ? async () => { throw new Error('unreadable') } : undefined }
+ const one = externalShapes({ providers: [p] }, { ...openOptions, providers: [p] }, own)
+ out[`busy/${engine}`] = await one.busy({ engine, pid: 7, record: '/fixture/record' })
+ }
+ const cases: Array<{ name: string; claim?: Partial<OwnerClaim>; tty?: string | null; harness?: boolean | null; busy?: boolean | null; extra?: Partial<ExternalSession>; owned?: boolean; saved?: boolean }> = [
+ { name: 'free' }, { name: 'terminal', claim: {}, tty: '/dev/fixture-terminal', busy: false },
+ { name: 'busy', claim: {}, tty: '/dev/fixture-terminal', busy: true },
+ { name: 'unknown-busy', claim: {}, tty: '/dev/fixture-terminal', busy: null },
+ { name: 'app', claim: { app: true }, tty: '/dev/fixture-terminal' },
+ { name: 'args-only', claim: { fromArgs: true }, tty: '/dev/fixture-terminal' },
+ { name: 'harness', claim: {}, tty: '/dev/fixture-terminal', harness: true },
+ { name: 'unverified', claim: {}, tty: '/dev/fixture-terminal', harness: null },
+ { name: 'no-tty', claim: {}, tty: null }, { name: 'archived', extra: { engine: 'codex', archived: true } },
+ { name: 'gone-folder', extra: { cwd: join(root, 'missing') } }, { name: 'owned', owned: true },
+ { name: 'saved-alias', saved: true, extra: { aliases: ['held'] } },
+ { name: 'profile', extra: { engine: 'hermes', launchArgs: ['-p', 'work'], title: 'Named conversation' } },
+ ]
+ for (const test of cases) {
+ const found = session('conversation', test.extra)
+ const p: ExternalProvider = { engine: found.engine, scan: async () => [found],
+ owners: async () => test.claim ? [{ sessionId: found.sessionId, pid: 7, record: '/fixture/record', ...test.claim }] : [],
+ busy: async () => test.busy ?? null }
+ const one = externalShapes({ providers: [p] }, { ...openOptions, providers: [p],
+ ttys: async () => new Map([[7, test.tty ?? null]]), harnessTtys: async () => test.harness === null ? null : new Set(test.harness ? [test.tty!] : []) },
+ { ...own, bySession: () => test.owned ? {} as never : undefined, stoppedAgents: { list: () => test.saved ? [{ sessionId: 'held' } as never] : [] } })
+ out[`${test.name}/open`] = await one.fresh()
+ out[`${test.name}/owner`] = await one.owner('conversation')
+ out[`${test.name}/working`] = await one.working('conversation')
+ for (const takeOver of [null, 'idle', 'now', 'wait'] as const) {
+ out[`${test.name}/${takeOver}`] = await one.adoption.adoptableSession('conversation', found.engine, takeOver)
+ }
+ out[`${test.name}/heldBy`] = await one.adoption.heldBy('conversation', { pid: 7, engine: found.engine, tty: test.tty ?? null, record: '/fixture/record' })
+ }
+ out.wrongEngine = await shapes.adoption.adoptableSession('first', 'codex', null)
+ out.notFound = await shapes.adoption.adoptableSession('missing', 'claude', null)
+ result[os] = JSON.parse(JSON.stringify(out).split(root).join('<fixture>'))
+ }
+ const text = JSON.stringify(result, null, 2) + '\n'
+ expect(text).not.toContain(root)
+ if (process.env.RECORD_EXTERNAL_SHAPES === '1') { mkdirSync(join(golden, '..'), { recursive: true }); writeFileSync(golden, text) }
+ expect(result).toEqual(JSON.parse(readFileSync(golden, 'utf8')))
+ } finally { Object.defineProperty(process, 'platform', platform); vi.resetModules(); rmSync(root, { recursive: true, force: true }) }
+})
diff --git a/cli/src/lib/sessionWork.ts b/cli/src/lib/sessionWork.ts
index 59437bca2..d4add3fde 100644
--- a/cli/src/lib/sessionWork.ts
+++ b/cli/src/lib/sessionWork.ts
@@ -20,11 +20,8 @@ const object = (v: unknown): Record<string, unknown> | null =>
v !== null && typeof v === 'object' && !Array.isArray(v) ? v as Record<string, unknown> : null
const hash = (s: string) => createHash('sha256').update(s).digest('hex')
const stamp = (v: unknown): v is string => typeof v === 'string' && Number.isFinite(Date.parse(v))
-export const validWorkPath = (v: unknown): v is string =>
- typeof v === 'string' && isAbsolute(v) && v.length <= 4096 && !/[\x00-\x1f\x7f]/.test(v)
-export const validPullRequestUrl = (v: unknown): v is string => typeof v === 'string'
- && /^https:\/\/github\.com\/[\w-]+\/[\w.-]+\/pull\/[1-9]\d*$/.test(v)
- && new URL(v).href === v && Number.isSafeInteger(Number(v.split('/').at(-1)))
+export { validWorkPath, validPullRequestUrl } from './sessionWorkWire.js'
+import { validWorkPath, validPullRequestUrl } from './sessionWorkWire.js'
export const emptySessionWork = (): SessionWorkLedger => ({ context: null, sequence: 0, latest: 0, currentOrder: 0, failedOrder: 0,
current: [], locations: [], pullRequests: [], pending: {}, running: {}, completed: [], uncertain: false, truncated: false })
diff --git a/cli/src/lib/sessionWorkWire.ts b/cli/src/lib/sessionWorkWire.ts
new file mode 100644
index 000000000..be6dd7f79
--- /dev/null
+++ b/cli/src/lib/sessionWorkWire.ts
@@ -0,0 +1,7 @@
+/** Small validators shared by aggregate readers and frame projections. */
+import { isAbsolute } from 'node:path'
+export const validWorkPath = (v: unknown): v is string =>
+ typeof v === 'string' && isAbsolute(v) && v.length <= 4096 && !/[\x00-\x1f\x7f]/.test(v)
+export const validPullRequestUrl = (v: unknown): v is string => typeof v === 'string'
+ && /^https:\/\/github\.com\/[\w-]+\/[\w.-]+\/pull\/[1-9]\d*$/.test(v)
+ && new URL(v).href === v && Number.isSafeInteger(Number(v.split('/').at(-1)))
diff --git a/cli/src/lib/usageShapes.golden.spec.ts b/cli/src/lib/usageShapes.golden.spec.ts
new file mode 100644
index 000000000..403f6fc3b
--- /dev/null
+++ b/cli/src/lib/usageShapes.golden.spec.ts
@@ -0,0 +1,112 @@
+/** Former-code record for the optional usage reader and the facts delivered to agent frames. */
+import { appendFileSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, utimesSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { expect, it, vi } from 'vitest'
+import type { RegisteredSession } from './registry.js'
+
+process.env.TZ = 'UTC'
+const golden = fileURLToPath(new URL('./__fixtures__/usage-shapes.golden.json', import.meta.url))
+const at = '2026-10-01T00:00:00Z'
+const lines = (...rows: unknown[]) => rows.map(row => JSON.stringify(row) + '\n').join('')
+const claude = (id: string, input = 100, output = 20, extra: Record<string, unknown> = {}) => ({
+ type: 'assistant', timestamp: at, sessionId: 'conversation', requestId: `request-${id}`,
+ message: { id, usage: { input_tokens: input, output_tokens: output, cache_read_input_tokens: 80, cache_creation_input_tokens: 10 } }, ...extra,
+})
+const codex = (input: number, output: number, last?: [number, number], timestamp = at) => ({
+ type: 'event_msg', timestamp, payload: { type: 'token_count', info: {
+ total_token_usage: { input_tokens: input, cached_input_tokens: input / 2, output_tokens: output, reasoning_output_tokens: output / 2 },
+ ...(last ? { last_token_usage: { input_tokens: last[0], cached_input_tokens: last[0] / 2, output_tokens: last[1], reasoning_output_tokens: last[1] / 2 } } : {}),
+ } },
+})
+
+it('preserves unknown, incremental, fork, rewrite, output, work and database usage facts on both platforms', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'usage-shapes-'))
+ const platform = Object.getOwnPropertyDescriptor(process, 'platform')!
+ const result: Record<string, unknown> = {}
+ try {
+ for (const os of ['darwin', 'linux']) {
+ Object.defineProperty(process, 'platform', { value: os })
+ vi.resetModules()
+ const { usageShapes } = await import('../testing/observerShapes.js')
+ const dir = join(root, os)
+ mkdirSync(dir)
+ let now = Date.parse(at)
+ const target = { agentId: 'agent', sessionId: 'conversation', engine: 'claude' as const, transcriptPath: join(dir, 'claude.jsonl'), registeredAt: 1, cwd: '/fixture/work' }
+ const changed: string[] = []
+ const options = { now: () => now }
+ let store = usageShapes(join(dir, 'cache'), options)
+ store.onChanged = s => changed.push(`${s.agentId}/${s.sessionId}`)
+ const out: Record<string, unknown> = {}
+ const read = async (name: string, s: Parameters<typeof store.get>[0] = target) => {
+ now += 30_000
+ store.changed(s)
+ await store.settled()
+ out[name] = store.get(s)
+ }
+ try {
+ out.cold = store.get(target)
+ await store.settled()
+ await read('missing')
+ writeFileSync(target.transcriptPath, lines(claude('one', 100, 10), claude('one'), claude('two'), claude('foreign', 999, 999, { sessionId: 'another' })))
+ await read('streaming-and-foreign')
+ const partial = lines(claude('three'))
+ appendFileSync(target.transcriptPath, partial.slice(0, 90))
+ await read('partial')
+ appendFileSync(target.transcriptPath, partial.slice(90))
+ await read('completed')
+ appendFileSync(target.transcriptPath, lines(
+ { type: 'assistant', timestamp: at, sessionId: 'conversation', message: { content: [{ type: 'tool_use', id: 'pr', name: 'Bash', input: { command: 'gh pr create --body-file /tmp/fixture-body' } }] } },
+ { type: 'user', timestamp: at, sessionId: 'conversation', message: { content: [{ type: 'tool_result', tool_use_id: 'pr', content: 'https://github.com/example/project/pull/42' }] } },
+ { type: 'assistant', timestamp: at, sessionId: 'conversation', message: { content: [{ type: 'tool_use', id: 'edit', name: 'Write', input: { file_path: '/fixture/work/new.ts' } }] } },
+ { type: 'user', timestamp: at, sessionId: 'conversation', toolUseResult: { type: 'create', content: 'one\ntwo\n' }, message: { content: [{ type: 'tool_result', tool_use_id: 'edit', content: 'Created' }] } },
+ ))
+ await read('output-and-work')
+ renameSync(target.transcriptPath, target.transcriptPath + '.away')
+ await read('unreadable-keeps-last')
+ writeFileSync(target.transcriptPath, lines(claude('replacement', 300)))
+ utimesSync(target.transcriptPath, now / 1000, now / 1000)
+ await read('rewritten-keeps-history')
+ await read('rebound-does-not-borrow', { ...target, sessionId: 'different' })
+ await read('unsupported', { ...target, engine: 'hermes' })
+ writeFileSync(target.transcriptPath, lines(claude('old'), claude('new', 200, 40, { timestamp: '2026-10-01T01:00:00Z' })))
+ await read('fork', { ...target, forkedFrom: { agentId: 'parent', name: 'Parent' }, registeredAt: Date.parse(at) + 1000 })
+ const cx = { ...target, engine: 'codex' as const, codexHome: '/fixture/profile', transcriptPath: join(dir, 'codex.jsonl') }
+ writeFileSync(cx.transcriptPath, lines({ type: 'session_meta', payload: { id: 'conversation' } }, codex(100, 20), codex(200, 50, [100, 30]), codex(200, 50, [100, 30]),
+ { type: 'event_msg', payload: { type: 'token_count', info: null } }))
+ await read('codex-deltas', cx)
+ appendFileSync(cx.transcriptPath, lines(codex(300, 80, [100, 30], '2026-10-01T00:02:00Z')))
+ await read('codex-append', cx)
+ writeFileSync(cx.transcriptPath, lines({ type: 'session_meta', payload: { id: 'elsewhere' } }, codex(900, 80)))
+ await read('codex-other-conversation', cx)
+ out.notifications = [...changed]
+ store.dispose(); await store.settled()
+ store = usageShapes(join(dir, 'cache'), options)
+ await read('restart-from-checkpoint')
+ store.dispose(); await store.settled()
+ for (const name of readdirSync(join(dir, 'cache'))) writeFileSync(join(dir, 'cache', name), '{broken')
+ store = usageShapes(join(dir, 'cache'), options)
+ await read('corrupt-checkpoint-rebuilt')
+ for (const mode of ['valid', 'fallback', 'unreadable', 'malformed'] as const) {
+ const queries: unknown[] = []
+ const db = usageShapes(join(dir, 'db-' + mode), { ...options, opencodeDb: '/fixture/opencode.db', readSqlite: async (_path, sql, args) => {
+ queries.push({ sql, args })
+ if (mode === 'unreadable' || mode === 'fallback' && queries.length === 1) return { ok: false, reason: 'unavailable' } as never
+ return { ok: true, via: 'builtin', rows: [{ tokens_input: 100, tokens_output: 20, tokens_reasoning: 5, tokens_cache_read: 80, tokens_cache_write: mode === 'malformed' ? -1 : 10 }] }
+ } })
+ const s = { ...target, engine: 'opencode' as const, transcriptPath: null }
+ out[`opencode/${mode}/cold`] = db.get(s)
+ await db.settled()
+ out[`opencode/${mode}`] = { value: db.get(s), queries }
+ db.dispose()
+ }
+ } finally { store.dispose(); await store.settled() }
+ result[os] = JSON.parse(JSON.stringify(out).split(root).join('<fixture>'))
+ }
+ const text = JSON.stringify(result, null, 2) + '\n'
+ expect(text).not.toContain(root)
+ if (process.env.RECORD_USAGE_SHAPES === '1') writeFileSync(golden, text)
+ expect(result).toEqual(JSON.parse(readFileSync(golden, 'utf8')))
+ } finally { Object.defineProperty(process, 'platform', platform); vi.resetModules(); rmSync(root, { recursive: true, force: true }) }
+})
diff --git a/cli/src/services/agentUsage.spec.ts b/cli/src/services/agentUsage.spec.ts
new file mode 100644
index 000000000..419d28639
--- /dev/null
+++ b/cli/src/services/agentUsage.spec.ts
@@ -0,0 +1,25 @@
+import { afterEach, expect, it, vi } from 'vitest'
+import { AgentTokenUsageCache } from '../lib/agentTokenUsage.js'
+import { usageTarget } from '../lib/agentUsageWire.js'
+import { createAgentUsage } from './agentUsage.js'
+
+const target = usageTarget({ agentId: 'a', sessionId: 's', engine: 'claude', transcriptPath: '/fixture/transcript', registeredAt: 1 })
+afterEach(() => vi.restoreAllMocks())
+
+it('accepts only complete targets and aggregate snapshots; disposal stops its reader', async () => {
+ const read = vi.spyOn(AgentTokenUsageCache.prototype, 'read').mockResolvedValue(null)
+ const dispose = vi.spyOn(AgentTokenUsageCache.prototype, 'dispose')
+ const service = createAgentUsage('/unused-fixture')
+ expect(await service.read({ target: {} })).toEqual({ error: 'INVALID_USAGE_TARGET' })
+ expect(read).not.toHaveBeenCalled()
+ expect(await service.read({ target })).toEqual({ target, value: null })
+ read.mockResolvedValueOnce({ totalTokens: -1, updatedAt: '' })
+ expect(await service.read({ target })).toEqual({ error: 'INVALID_USAGE_READING' })
+ read.mockRejectedValueOnce(new Error('unreadable'))
+ expect(await service.read({ target })).toEqual({ error: 'USAGE_UNAVAILABLE' })
+ const value = { totalTokens: 4, updatedAt: '2026-10-01T00:00:00Z', rawTranscript: 'must not cross' }
+ read.mockResolvedValueOnce(value)
+ expect(await service.read({ target })).toEqual({ target, value: { totalTokens: 4, updatedAt: value.updatedAt } })
+ service.stop()
+ expect(dispose).toHaveBeenCalledOnce()
+})
diff --git a/cli/src/services/agentUsage.ts b/cli/src/services/agentUsage.ts
new file mode 100644
index 000000000..a48b77f14
--- /dev/null
+++ b/cli/src/services/agentUsage.ts
@@ -0,0 +1,18 @@
+/** The usage service alone owns transcript/SQLite reads and private checkpoints. */
+import { AgentTokenUsageCache } from '../lib/agentTokenUsage.js'
+import { usageSnapshot, usageTarget, validUsage, validUsageTarget } from '../lib/agentUsageWire.js'
+
+export function createAgentUsage(...args: ConstructorParameters<typeof AgentTokenUsageCache>) {
+ const cache = new AgentTokenUsageCache(...args)
+ return {
+ async read(payload: Record<string, unknown>): Promise<Record<string, unknown>> {
+ if (!validUsageTarget(payload.target)) return { error: 'INVALID_USAGE_TARGET' }
+ const target = usageTarget(payload.target)
+ const reading = await cache.read(target).then(value => ({ value }), () => null)
+ if (!reading) return { error: 'USAGE_UNAVAILABLE' }
+ const { value } = reading
+ return validUsage(value) ? { target, value: usageSnapshot(value) } : { error: 'INVALID_USAGE_READING' }
+ },
+ stop: () => cache.dispose(),
+ }
+}
diff --git a/cli/src/services/inline.spec.ts b/cli/src/services/inline.spec.ts
index 2074e8660..9b7ff484f 100644
--- a/cli/src/services/inline.spec.ts
+++ b/cli/src/services/inline.spec.ts
@@ -22,7 +22,7 @@ import { startSearch } from './search.js'
import { startShell } from './shell.js'
import { startSharing } from './sharing.js'
import { startStoreInCore } from './store.js'
-import { startUsage } from './usage.js'
+import { startUsageInCore } from './usage.js'
import { startViewers } from './viewers.js'
import { startWifi } from './wifi.js'
import { startWindowNames } from './windowNames.js'
@@ -30,6 +30,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, startCommandBar, startDevices, startHandoff, startGateway, startModels, startMonitor, startOrchestrator, startProjects, startRecaps, startSearch, startSharing, startShell, startStoreInCore, startTeamsInCore, startUsage, startViewers, startWifi, startWindowNames, startWorkspaces })
+ expect({ ...inline }).toEqual({ engineTranscriptFor, liveFor, runtimeFor, screenFor, submissionFor, nativeControlFor, modelControlFor, questionControlFor, startCommandBar, startDevices, startHandoff, startGateway, startModels, startMonitor, startOrchestrator, startProjects, startRecaps, startSearch, startSharing, startShell, startStoreInCore, startTeamsInCore, startUsageInCore, startViewers, startWifi, startWindowNames, startWorkspaces })
})
})
diff --git a/cli/src/services/inline.ts b/cli/src/services/inline.ts
index c6abb70b8..700b42dea 100644
--- a/cli/src/services/inline.ts
+++ b/cli/src/services/inline.ts
@@ -34,7 +34,7 @@ export { startSearch } from './search.js'
export { startShell } from './shell.js'
export { startSharing } from './sharing.js'
export { startStoreInCore } from './store.js'
-export { startUsage } from './usage.js'
+export { startUsageInCore } from './usage.js'
export { startViewers } from './viewers.js'
export { startWifi } from './wifi.js'
export { startWindowNames } from './windowNames.js'
diff --git a/cli/src/services/processCoreApi.spec.ts b/cli/src/services/processCoreApi.spec.ts
index 0092d1cb3..a85cde70b 100644
--- a/cli/src/services/processCoreApi.spec.ts
+++ b/cli/src/services/processCoreApi.spec.ts
@@ -2,10 +2,24 @@ import { describe, expect, it, vi } from 'vitest'
import type { RegisteredSession } from '../lib/registry.js'
import { agentsIn, daemonIn, isSession, processCoreApi, type ShownAgent } from './processCoreApi.js'
import { turnsLink } from './turnsLink.js'
+import { usageTarget } from '../lib/agentUsageWire.js'
const agent = (agentId: string, over: Partial<RegisteredSession> = {}) => ({ agentId, sessionId: `s-${agentId}`, engine: 'claude', cwd: `/work/${agentId}`, ...over }) as RegisteredSession
describe('the core API a light service runs on in its own process', () => {
+ it('reads only an exact validated usage snapshot, without reading a transcript', async () => {
+ const target = usageTarget(agent('a', { transcriptPath: '/fixture/session', registeredAt: 1 }))
+ expect(await processCoreApi('/data', 'projects').usage!(target)).toBeNull()
+ const ask = vi.fn(async () => ({ target, value: { totalTokens: 4, updatedAt: '2026-10-01T00:00:00Z' } }))
+ const api = processCoreApi('/data', 'projects', { ask })
+ expect(await api.usage!(target)).toMatchObject({ totalTokens: 4 })
+ for (const answer of [{}, { target: { ...target, sessionId: 'other' }, value: null }, { target, value: { totalTokens: -1 } }]) {
+ ask.mockResolvedValueOnce(answer as never)
+ expect(await api.usage!(target)).toBeNull()
+ }
+ ask.mockRejectedValueOnce(new Error('offline'))
+ expect(await api.usage!(target)).toBeNull()
+ })
it('answers the agents from what the core last said, by agent id or session id', () => {
const live = [agent('a1'), agent('a2')]
const api = processCoreApi('/data', 'projects', { live: () => live, advertised: () => [live[1]] })
diff --git a/cli/src/services/processCoreApi.ts b/cli/src/services/processCoreApi.ts
index 079310a6b..ca82369a7 100644
--- a/cli/src/services/processCoreApi.ts
+++ b/cli/src/services/processCoreApi.ts
@@ -1,3 +1,4 @@
+import { usageTarget, usageTargetKey, usageSnapshot, validUsage, validUsageTarget } from '../lib/agentUsageWire.js'
/**
* The core API a light service runs on in its own process (the edge host: usage, the monitor, the project
* readers): the agents the core last said, and nothing else. Each process asks the core for what it reads
@@ -89,6 +90,10 @@ export function processCoreApi(dataDir: string, service: string, view: AgentsVie
const daemon = (): DaemonAddress => view.daemon?.() ?? DAEMON_UNKNOWN
return {
dataDir,
+ usage: async target => {
+ const answer = await ask?.('agentUsage', { target: usageTarget(target) }).catch(() => null)
+ return validUsageTarget(answer?.target) && usageTargetKey(answer.target) === usageTargetKey(target) && validUsage(answer?.value) ? usageSnapshot(answer.value) : null
+ },
conversations: CONVERSATIONS_OFF,
// Terminals are launched by the core alone (the shell service, #893): a service in its own process
// is refused, never handed a way to start a process outside the core.
diff --git a/cli/src/services/projects.spec.ts b/cli/src/services/projects.spec.ts
index 0acb8d1bd..dd334a2b6 100644
--- a/cli/src/services/projects.spec.ts
+++ b/cli/src/services/projects.spec.ts
@@ -30,6 +30,14 @@ function setup() {
}
describe('the project and folder readers', () => {
+ it('asks core for aggregate work evidence, and falls back to unknown', async () => {
+ const { core, ask } = setup()
+ await ask('git_pull_request', { agentId: 'a1' })
+ const options = vi.mocked(readSessionGitPullRequest).mock.calls.at(-1)![1]!
+ expect(await options.usage!()).toBeNull()
+ core.usage = async () => ({ totalTokens: 1, updatedAt: '2026-10-01T00:00:00Z' })
+ expect(await options.usage!()).toMatchObject({ totalTokens: 1 })
+ })
afterEach(() => { vi.clearAllMocks() })
it('answer exactly the requests they declare', () => {
@@ -39,10 +47,10 @@ describe('the project and folder readers', () => {
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 })
+ expect(readSessionGitPullRequest).toHaveBeenLastCalledWith(row('a1', '/work/app'), { usage: expect.any(Function), 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 })
+ expect(readSessionGitPullRequest).toHaveBeenLastCalledWith(row('a1', '/work/app'), { usage: expect.any(Function), expected: context, history: false, offset: undefined })
await ask('git_pull_request', { agentId: 'a1', context: { cwd: '/w', branch: 'b', remote: 'origin' } })
expect(readSessionGitPullRequest).toHaveBeenCalledTimes(3)
})
diff --git a/cli/src/services/projects.ts b/cli/src/services/projects.ts
index 20c69b22c..459cd63ac 100644
--- a/cli/src/services/projects.ts
+++ b/cli/src/services/projects.ts
@@ -33,6 +33,7 @@ export function startProjects(core: CoreApi): ServiceRequests {
return { status: 'unavailable' }
}
return readSessionGitPullRequest(agent, {
+ usage: () => core.usage?.(agent) ?? Promise.resolve(null),
expected: requested as ExpectedGitContext | undefined,
history: payload.history === true, offset: typeof payload.offset === 'number' ? payload.offset : undefined,
}).then((result) => result, () => ({ status: 'unavailable' }))
diff --git a/cli/src/services/projectsProcess.spec.ts b/cli/src/services/projectsProcess.spec.ts
index d7a05fccc..6de005986 100644
--- a/cli/src/services/projectsProcess.spec.ts
+++ b/cli/src/services/projectsProcess.spec.ts
@@ -35,6 +35,7 @@ describe('the project readers in their own process', () => {
expect(options).toMatchObject({ name: 'projects', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't' })
// Before a core has connected: the agents it last said, which is none.
expect(await options.requests.git_project_info!({ path: '/work' }, ASKER)).toEqual({ path: '/work', owner: true })
+ expect(await api.usage!(agent('a1'))).toBeNull()
let answer: Record<string, unknown> = { agents: [agent('a1')] }
const query = vi.fn(async (_name: string) => answer)
options.onConnected!({ query } satisfies CoreConnection)
@@ -49,6 +50,8 @@ describe('the project readers in their own process', () => {
await options.requests.git_project_info!({ path: '/work' }, ASKER)
expect(seen).toEqual([[], ['a1'], ['a1', 'a2'], ['a1', 'a2'], ['a1', 'a2']])
expect(api.agents.resolve('s-a2')).toEqual(agent('a2'))
+ expect(await api.usage!(agent('a1'))).toBeNull()
+ expect(query).toHaveBeenLastCalledWith('agentUsage', expect.any(Object))
})
it('runs as a real service by default, answering every request the core routes to the readers', () => {
diff --git a/cli/src/services/projectsProcess.ts b/cli/src/services/projectsProcess.ts
index 75930a3ab..c8804ea2a 100644
--- a/cli/src/services/projectsProcess.ts
+++ b/cli/src/services/projectsProcess.ts
@@ -29,7 +29,7 @@ export function runProjectsService(options: ProjectsServiceOptions): ServiceProc
const refresh = async (): Promise<void> => {
live = agentsIn(await core?.query('live').catch(() => null)) ?? live
}
- const answers = (options.start ?? startProjects)(processCoreApi(options.dataDir, 'projects', { live: () => live }))
+ const answers = (options.start ?? startProjects)(processCoreApi(options.dataDir, 'projects', { live: () => live, ask: (query, payload) => core?.query(query, payload) ?? Promise.resolve({ error: 'SERVICE_UNAVAILABLE' }) }))
// Each request reads the agents as they are when it is asked, as the core's registry would answer it:
// an agent stopped a moment ago is no longer one whose folder this reads.
const requests: ServiceRequests = Object.fromEntries(Object.entries(answers).map(([type, handle]) =>
diff --git a/cli/src/services/usage.spec.ts b/cli/src/services/usage.spec.ts
index f42393f1f..ed6ad53dd 100644
--- a/cli/src/services/usage.spec.ts
+++ b/cli/src/services/usage.spec.ts
@@ -1,10 +1,19 @@
import { describe, expect, it, vi } from 'vitest'
import { fakeCore } from '../testing/fakeCore.js'
-import { startUsage, USAGE_REQUESTS } from './usage.js'
+import { startUsage, startUsageInCore, USAGE_REQUESTS } from './usage.js'
+import { emptyPorts } from '../core/api.js'
+import { usageTarget } from '../lib/agentUsageWire.js'
const ASKER = { local: false, owner: true }
describe('the usage service', () => {
+ it('composes an explicit inline reader on the same bounded wire', async () => {
+ const ports = emptyPorts()
+ expect(Object.keys(startUsageInCore(fakeCore(), ports))).toEqual(['usage_read'])
+ expect(await ports.usage!.read(usageTarget({ agentId: 'a', sessionId: '', engine: 'claude', transcriptPath: null, registeredAt: 1 })))
+ .toEqual({ error: 'INVALID_USAGE_TARGET' })
+ ports.usage!.stop()
+ })
it('answers exactly the request it declares', () => {
expect(Object.keys(startUsage(fakeCore())).sort()).toEqual([...USAGE_REQUESTS].sort())
})
diff --git a/cli/src/services/usage.ts b/cli/src/services/usage.ts
index 1eb68cce9..9242e4d50 100644
--- a/cli/src/services/usage.ts
+++ b/cli/src/services/usage.ts
@@ -1,3 +1,6 @@
+import { join } from 'node:path'
+import { createAgentUsage } from './agentUsage.js'
+import type { CorePorts } from '../core/api.js'
/**
* 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
@@ -27,3 +30,10 @@ export function startUsage(_core: CoreApi, deps: UsageDeps = { read: readAccount
)),
}
}
+
+/** Explicit inline compatibility uses the same port and validators as the worker. */
+export function startUsageInCore(core: CoreApi, ports: CorePorts): ServiceRequests {
+ const reader = createAgentUsage(join(core.dataDir, 'agent-token-usage'))
+ ports.usage = { read: target => reader.read({ target }), stop: reader.stop }
+ return startUsage(core)
+}
diff --git a/cli/src/services/usageProcess.spec.ts b/cli/src/services/usageProcess.spec.ts
index fc3999292..5832ceeba 100644
--- a/cli/src/services/usageProcess.spec.ts
+++ b/cli/src/services/usageProcess.spec.ts
@@ -18,14 +18,16 @@ describe('account usage in its own process', () => {
run: (given) => { options = given; return service },
start: (core) => { api = core; return { usage_read: async () => ({ providers: [] }) } },
})
- expect(handle).toBe(service)
+ handle.stop()
+ expect(service.stop).toHaveBeenCalledOnce()
expect(options).toMatchObject({ name: 'usage', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't' })
expect(await options!.requests.usage_read!({}, { local: true, owner: true })).toEqual({ providers: [] })
+ expect(await options!.requests.agentUsage!({}, { local: true, owner: true })).toEqual({ error: 'INVALID_USAGE_TARGET' })
await expect(api!.account.accessToken()).rejects.toThrow('usage holds no credential')
})
it('runs as a real service by default', () => {
runUsageService({ dataDir: '/data', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't' })
- expect(runServiceProcess).toHaveBeenCalledWith(expect.objectContaining({ name: 'usage', requests: { usage_read: expect.any(Function) } }))
+ expect(runServiceProcess).toHaveBeenCalledWith(expect.objectContaining({ name: 'usage', requests: { usage_read: expect.any(Function), agentUsage: expect.any(Function) } }))
})
})
diff --git a/cli/src/services/usageProcess.ts b/cli/src/services/usageProcess.ts
index 36cd159f8..c5a581e5b 100644
--- a/cli/src/services/usageProcess.ts
+++ b/cli/src/services/usageProcess.ts
@@ -1,3 +1,5 @@
+import { join } from 'node:path'
+import { createAgentUsage } from './agentUsage.js'
/**
* Account usage in its own process (`harness __service usage`, in the edge host): `usage_read`, the same
* handler as in the core's process (services/usage.ts). It asks the core nothing. Its two vendor round
@@ -19,11 +21,13 @@ export interface UsageServiceOptions {
}
export function runUsageService(options: UsageServiceOptions): ServiceProcess {
- return (options.run ?? runServiceProcess)({
+ const reader = createAgentUsage(join(options.dataDir, 'agent-token-usage'))
+ const service = (options.run ?? runServiceProcess)({
name: 'usage',
socketPath: options.socketPath,
machineId: options.machineId,
token: options.token,
- requests: (options.start ?? startUsage)(processCoreApi(options.dataDir, 'usage')),
+ requests: { ...(options.start ?? startUsage)(processCoreApi(options.dataDir, 'usage')), agentUsage: payload => reader.read(payload) },
})
+ return { stop: () => { service.stop(); reader.stop() } }
}
diff --git a/cli/src/testing/observerShapes.ts b/cli/src/testing/observerShapes.ts
new file mode 100644
index 000000000..48988e2b7
--- /dev/null
+++ b/cli/src/testing/observerShapes.ts
@@ -0,0 +1,33 @@
+import { createAgentUsage } from '../services/agentUsage.js'
+import { createUsageLink } from '../core/usageLink.js'
+import type { AgentUsageTarget } from '../lib/agentUsageWire.js'
+/** Former-code composition for moving optional search and usage observations out of core. */
+import type { AgentTokenUsageCache } from '../lib/agentTokenUsage.js'
+import { ExternalSessions, OpenSessions, type ExternalSessionsOptions, type OpenSessionsOptions } from '../lib/sessionSearch/external.js'
+import { createAdoption, type AdoptDeps } from '../core/agents/adopt.js'
+
+export function externalShapes(sessionsOptions: ExternalSessionsOptions, openOptions: OpenSessionsOptions,
+ own: Pick<AdoptDeps, 'bySession' | 'byAgent' | 'stoppedAgents' | 'search'>) {
+ const sessions = new ExternalSessions(sessionsOptions)
+ const open = new OpenSessions(openOptions)
+ const adoption = createAdoption({ ...own, externalSessions: sessions, openSessions: open })
+ return {
+ scan: () => sessions.scan(),
+ lookup: async (id: string) => sessions.get(id) ?? (await sessions.scan(), sessions.get(id)),
+ owner: (id: string) => open.owner(id),
+ busy: (owner: Parameters<OpenSessions['busy']>[0]) => open.busy(owner),
+ known: () => Object.fromEntries(open.known()),
+ fresh: async () => Object.fromEntries(await open.fresh()),
+ working: (id: string) => open.working(id),
+ adoption,
+ }
+}
+
+export function usageShapes(...args: ConstructorParameters<typeof AgentTokenUsageCache>) {
+ let onChanged: ((target: AgentUsageTarget) => void) | undefined
+ const reader = createAgentUsage(...args)
+ const link = createUsageLink({ call: payload => reader.read(JSON.parse(JSON.stringify(payload))), now: args[1]?.now,
+ changed: target => onChanged?.(target) })
+ return { ...link.port, settled: link.settled, dispose: () => { link.port.stop(); reader.stop() },
+ get onChanged() { return onChanged }, set onChanged(value) { onChanged = value } }
+}
diff --git a/docs/research/2026-10-09-daemon-separation-progress.md b/docs/research/2026-10-09-daemon-separation-progress.md
index 85615db2b..d8783fb2e 100644
--- a/docs/research/2026-10-09-daemon-separation-progress.md
+++ b/docs/research/2026-10-09-daemon-separation-progress.md
@@ -57,3 +57,19 @@ L2 timing: golden recording and implementation began after the L3 merge at 01:22
L2 integrated main `d364ca98e` before final gates; its CLI launch/account/retention changes were reviewed with the assignment move. Receipt `20261009T015141.373083Z-17943` passed typecheck, 1,704 core tests at per-file 100% coverage, 265 harnessd tests with one existing skip, and 477 affected tests in 17 files. Receipt `20261009T015303.584859Z-32741` passed 292 resume tests, 1,050 portability tests with nine skips at their 100% gates, and 57 real-tmux tests with 15 unavailable-engine skips. The e2e receipt passed all 16 core/lifecycle and six machine tests, plus three models cases, but failed the new assignment-recovery case and remains failed evidence.
That remaining failure was traced to the fake engine's `process.title` rewrite: macOS `ps eww` returned its title with no environment, although the fixture inherited both endpoint and model. Core correctly treated that as unknown. The evidence test now opts into retaining the interpreter and real engine entrypoint, which discovery recognizes on both platforms. It does not weaken the production unknown-read rule. Independent review's final startup finding was also corrected: the exit listener is installed immediately after registry ownership/load, before startup yields, covering a staged update before full teardown exists. The new startup-order regression fails on the former placement and passes after the move. Final validation follows these narrow corrections; publication remains zero.
+
+L2 completed at 02:17:24 UTC as merge `67c2e52b7` ([#1076](https://github.com/autonomous-ai/openharness/pull/1076)). Final head `2e28b47d3` and base `d364ca98e` received independent approval. Automatic CI [37873262697](https://github.com/autonomous-ai/openharness/actions/runs/37873262697) passed all Linux shards, typecheck, process checks and `ci/required`. The merge receipt verified both the reviewed target and full tested tree. Final local receipts passed 1,704 core tests at per-file 100%, 265 harnessd tests with one existing skip at 100%, 489 affected tests, 292 resume tests, 1,050 portability tests with nine skips at 100%, and 57 real-tmux tests with 15 unavailable-engine skips. All four selected models outage/held-boot cases passed. The earlier failed e2e receipt is not passing evidence; its core/lifecycle and machine lanes passed on identical production source, with only the models fixture corrected afterward.
+
+L2 implementation and diagnosis ended at 02:09:44; final review finished at 02:10. Final local validation occupied 02:09:44–02:13:54, CI waiting ended at 02:14:51, measurement ran 02:15:25–02:16:36, and the merge helper ran 02:17:11–02:17:24. L2 elapsed time was 54 minutes 28 seconds; the whole request through that merge took 2 hours 50 minutes 43 seconds. These overlapping phases are not added. Publication remains zero.
+
+The matched L2 measurement used the L3 machine, toolchain and four-agent workload above. Empty/idle/active core CPU was 0.69/1.12/7.66%, RSS 80.4/101.0/97.4 MiB, and event-loop p95 about 12.1 ms. Two-turn p95 was 6.986 seconds versus L3's 6.980 seconds. The short sample supports no latency or long-term memory claim.
+
+## Item 5: usage observations
+
+Former-code commit `12d6b640b` records external session/adoption and usage goldens before either move. Both pin Darwin and Linux, UTC and private `/tmp` fixtures. The usage golden stays unchanged while its composition now crosses the real service reader, JSON serialization and both wire validators. External-session implementation remains unchanged for the next PR; its admission move also needs durable holds and precise process ownership.
+
+Usage transcript, SQLite and private checkpoint reads belong to the usage service. Core frames read a bounded aggregate mirror with no I/O or service wait. The mirror allows four requests at once and 512 targets, coalesces transcript events, and has no recurring idle poll. Replies belong to the full immutable read target and connection epoch; one pending request per target preserves order. Rebinding starts unknown. Service loss, unreadable sources, capacity exhaustion and invalid replies preserve the last same-identity value. Reconnect refreshes even an unchanged warm worker. Aggregate values are copied, URLs and paths are bounded, and each snapshot is limited to 256 KiB. Services receive copies for current owned targets, including rows whose nullable fields are omitted.
+
+Independent review identified starvation when continuous same-target events invalidated pending reads, omitted-field rejection in inline project readers, unbounded PR URLs, and a reader-capacity refusal that looked like a valid null. Each is corrected with a regression. Same-target progress is published while a later refresh is pending; identity changes still discard old replies. Checkpoint filenames remain compatible. In-memory reader entries additionally include the complete read target so concurrent target changes cannot mutate an in-flight read.
+
+Validation selected before execution: typecheck, architecture, unchanged goldens and mutations, core/harnessd 100% gates, affected frame/usage/Git/backend specs, and isolated usage, edge and services e2e. Initial core validation passed 1,713 tests at 100%; affected validation failed two old backend fixtures that still composed usage as a service without a port. Initial usage e2e failed fixture assumptions: Stop's RPC is `agent_delete`, and transcript attachment can follow session binding. The existing five edge and fourteen services cases passed. Failed receipts remain failed; final evidence follows the corrections. No release is authorized or attempted.