The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat(cli): usage_read — a machine reads its own agent accounts for a client that cannot
Dev jacobac967e30678c
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.tsindex bbf5af05b..98d5e3dbc 100644--- a/cli/src/backendSocket.spec.ts+++ b/cli/src/backendSocket.spec.ts@@ -177,6 +177,42 @@ describe('BackendSocket outbound queue', () => {await socket.stop()})+ it('answers usage_read with this machine\'s own readings, wrapped for the requester', async () => {+ // What goes back names what the person spends and on whose account, so it must leave encrypted.+ // The reader is the socket's own field: this never touches a real home, Keychain or network.+ const socket = new BackendSocket('token')+ const readings = [+ {+ provider: 'claude' as const,+ account: 'k1',+ outcome: 'answered' as const,+ httpStatus: 200,+ body: { seven_day: { utilization: 42 } },+ },+ ]+ socket.accountUsageReader = async () => readings+ socket.connect()+ const ws = wsMock.instances[0]+ ws.open()+ vi.spyOn(socket.e2ee, 'unwrapDown').mockReturnValue({+ type: 'usage_read', payload: { requestId: 'usage-1' },+ })+ vi.spyOn(socket.e2ee, 'hasSession').mockReturnValue(true)+ const wrapReply = vi.spyOn(socket.e2ee, 'wrapRpcReply').mockReturnValue({+ type: 'usage_read_result', payload: { __e2e: { v: 1, k: 's', n: 1, ct: 'ciphertext' } },+ })+ ws.message({+ t: 'down',+ connId: 'web-1',+ frame: { type: 'usage_read', payload: { __e2e: { v: 1, k: 's', n: 1, ct: 'ciphertext' } } },+ })++ await vi.waitFor(() => {+ expect(wrapReply).toHaveBeenCalledWith('web-1', 'usage_read_result', 'usage-1', { providers: readings })+ })+ await socket.stop()+ })+it('includes engine session correlation in the web agent list', async () => {const session: RegisteredSession = {schemaVersion: 2,diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex ea911bf74..18401bd4f 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -26,6 +26,7 @@ import { ENGINES, type AgentEngine } from './engines/types.js'import { listDir } from './lib/fsBrowse.js'import { linkCodexProfile, listCodexProfiles } from './lib/codexProfiles.js'import { parseGridLaunchOverride, type GridLaunchOverride } from './lib/gridLaunch.js'+import { readAccountUsage, type AccountUsageReading } from './lib/accountUsage.js'import { probeEngines } from './lib/engineProbe.js'import { engineInstallRecipe } from './lib/engineInstall.js'import { agentFrame, type AgentFrame } from './lib/agentFrame.js'@@ -365,6 +366,9 @@ export class BackendSocket {recentProvider: RecentProvider | null = null/** Runtime Model/Effort integration, wired by cli.ts for registered tmux sessions. */runtimeModelsProvider: ((sessionId?: string) => Promise<RuntimeModelOption[]>) | null = null+ /** Answers `usage_read` — this machine's own agent-account usage (lib/accountUsage.ts). A field+ * rather than a direct call so a spec answers it without a real home, Keychain or network. */+ accountUsageReader: () => Promise<AccountUsageReading[]> = readAccountUsageruntimeProfileProvider: ((session: RegisteredSession) => string | null) | null = nullonRuntimeProfileUpdate: ((sessionId: string, selectedModel: string) => Promise<void>) | null = null/** Web↔adapter E2EE: group-encrypts user events, runs the CPace pairing, holds per-conn sessions. */@@ -1719,6 +1723,15 @@ export class BackendSocket {return}+ // This machine's Claude/Codex rate limits, read with ITS OWN credentials. The desktop reads the+ // account on the computer it runs on directly; this is how it reads one on a machine it does+ // not — which may be signed in to a different subscription entirely. The vendor's answer goes+ // back as it came: see lib/accountUsage.ts for why the parsing stays on the client.+ case 'usage_read': {+ reply(type, requestId, { providers: await this.accountUsageReader() })+ return+ }+// v1 no-ops: no programmatic session control over an interactive tmux claude.case 'new_chat':case 'compact':diff --git a/cli/src/lib/accountUsage.spec.ts b/cli/src/lib/accountUsage.spec.tsnew file mode 100644index 000000000..3138313a8--- /dev/null+++ b/cli/src/lib/accountUsage.spec.ts@@ -0,0 +1,180 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { dirname, join } from 'node:path'+import {+ accountKey,+ CLAUDE_USAGE_URL,+ CODEX_USAGE_URL,+ readAccountUsage,+ type AccountUsageDeps,+} from './accountUsage.js'++let home: string++beforeEach(() => {+ home = mkdtempSync(join(tmpdir(), 'account-usage-'))+})++afterEach(() => {+ rmSync(home, { recursive: true, force: true })+})++function write(relative: string, value: unknown): void {+ const path = join(home, relative)+ mkdirSync(dirname(path), { recursive: true })+ writeFileSync(path, typeof value === 'string' ? value : JSON.stringify(value))+}++interface Call {+ url: string+ headers: Record<string, string>+}++/** A vendor that answers every request with [status] and [body], and remembers what it was asked. */+function vendor(status = 200, body: unknown = { five_hour: { utilization: 12 } }) {+ const calls: Call[] = []+ const fetchImpl = (async (url: string | URL | Request, init?: RequestInit) => {+ calls.push({ url: String(url), headers: { ...(init?.headers as Record<string, string>) } })+ return new Response(JSON.stringify(body), { status })+ }) as typeof fetch+ return { calls, fetchImpl }+}++/** Never the real Keychain: every spec here runs on whatever machine runs the suite. */+function deps(extra: AccountUsageDeps = {}): AccountUsageDeps {+ return { home, readKeychain: async () => null, ...extra }+}++const CLAUDE_TOKEN = 'sk-ant-oat01-secret'+const CODEX_TOKEN = 'codex-access-secret'++describe('accountKey', () => {+ it('matches the vector the desktop pins', () => {+ // ⚠️ A cross-language contract: `test/usage_account_key_test.dart` in autonomous-harness-desktop+ // asserts these same two strings. If they drift, every remote reading looks like a different+ // account and the strip shows the same subscription twice.+ expect(accountKey('claude', 'acct-123')).toBe('85d2541574c31caa')+ expect(accountKey('codex', 'acct-123')).toBe('d9921dd1861038f4')+ })++ it('keeps the same id on two vendors apart', () => {+ expect(accountKey('claude', 'same')).not.toBe(accountKey('codex', 'same'))+ })+})++describe('readAccountUsage', () => {+ it('a machine signed in to nothing asks nobody', async () => {+ const { calls, fetchImpl } = vendor()+ const readings = await readAccountUsage(deps({ fetchImpl }))+ expect(readings).toEqual([+ { provider: 'claude', account: null, outcome: 'signedOut' },+ { provider: 'codex', account: null, outcome: 'signedOut' },+ ])+ expect(calls).toHaveLength(0)+ })++ it('asks Claude the way Claude Code does, and names the account without sending it', async () => {+ write('.claude/.credentials.json', { claudeAiOauth: { accessToken: CLAUDE_TOKEN } })+ write('.claude.json', { oauthAccount: { accountUuid: 'uuid-1', emailAddress: '[email protected]' } })+ const { calls, fetchImpl } = vendor(200, { seven_day: { utilization: 42 } })++ const [claude] = await readAccountUsage(deps({ fetchImpl }))++ expect(claude).toEqual({+ provider: 'claude',+ account: accountKey('claude', 'uuid-1'),+ outcome: 'answered',+ httpStatus: 200,+ body: { seven_day: { utilization: 42 } },+ })+ const call = calls.find((c) => c.url === CLAUDE_USAGE_URL)+ expect(call?.headers).toEqual({+ Authorization: `Bearer ${CLAUDE_TOKEN}`,+ 'anthropic-beta': 'oauth-2025-04-20',+ 'User-Agent': 'claude-code/2.1.0',+ })+ })++ it('never puts a token, an id or an email in what goes back', async () => {+ // The reply crosses the relay and the desktop logs it. Only the hashed key may name the account.+ write('.claude/.credentials.json', { claudeAiOauth: { accessToken: CLAUDE_TOKEN } })+ write('.claude.json', { oauthAccount: { accountUuid: 'uuid-1', emailAddress: '[email protected]' } })+ write('.codex/auth.json', { tokens: { access_token: CODEX_TOKEN, account_id: 'codex-acct' } })+ const { fetchImpl } = vendor()++ const wire = JSON.stringify(await readAccountUsage(deps({ fetchImpl })))++ for (const secret of [CLAUDE_TOKEN, CODEX_TOKEN, 'uuid-1', '[email protected]', 'codex-acct']) {+ expect(wire).not.toContain(secret)+ }+ })++ it('an expired Claude token is a sign-in, not a round trip', async () => {+ write('.claude/.credentials.json', { claudeAiOauth: { accessToken: CLAUDE_TOKEN, expiresAt: 1_000 } })+ const { calls, fetchImpl } = vendor()++ const [claude] = await readAccountUsage(deps({ fetchImpl, now: () => 2_000 }))++ expect(claude).toMatchObject({ outcome: 'signedOut', message: expect.stringContaining('expired') })+ expect(calls.some((c) => c.url === CLAUDE_USAGE_URL)).toBe(false)+ })++ it('reads the Keychain before the file, as the desktop does on macOS', async () => {+ write('.claude/.credentials.json', { claudeAiOauth: { accessToken: 'from-file' } })+ const { calls, fetchImpl } = vendor()++ await readAccountUsage(deps({+ fetchImpl,+ readKeychain: async () => JSON.stringify({ claudeAiOauth: { accessToken: 'from-keychain' } }),+ }))++ const call = calls.find((c) => c.url === CLAUDE_USAGE_URL)+ expect(call?.headers.Authorization).toBe('Bearer from-keychain')+ })++ it('scopes the Codex reading to its account', async () => {+ write('.codex/auth.json', { tokens: { access_token: CODEX_TOKEN, account_id: 'codex-acct' } })+ const { calls, fetchImpl } = vendor()++ const [, codex] = await readAccountUsage(deps({ fetchImpl }))++ expect(codex).toMatchObject({ outcome: 'answered', account: accountKey('codex', 'codex-acct') })+ const call = calls.find((c) => c.url === CODEX_USAGE_URL)+ expect(call?.headers).toEqual({+ Authorization: `Bearer ${CODEX_TOKEN}`,+ 'ChatGPT-Account-Id': 'codex-acct',+ })+ })++ it('hands a refusal back as an answer, for the client to read', async () => {+ // The desktop already turns a 401 into "sign in" for its own reading; deciding it again here+ // would be a second opinion about the same status code.+ write('.codex/auth.json', { tokens: { access_token: CODEX_TOKEN } })+ const { fetchImpl } = vendor(401, { error: 'unauthorized' })++ const [, codex] = await readAccountUsage(deps({ fetchImpl }))++ expect(codex).toMatchObject({ outcome: 'answered', httpStatus: 401, account: null })+ })++ it('a vendor that cannot be reached is an outcome, not a throw', async () => {+ write('.codex/auth.json', { tokens: { access_token: CODEX_TOKEN } })+ const fetchImpl = (async () => {+ throw new TypeError('fetch failed')+ }) as typeof fetch++ const [, codex] = await readAccountUsage(deps({ fetchImpl }))++ expect(codex).toEqual({ provider: 'codex', account: null, outcome: 'unreachable' })+ })++ it('a half-written credentials file reads as signed out', async () => {+ write('.claude/.credentials.json', '{"claudeAiOauth": {"accessTo')+ write('.codex/auth.json', 'not json at all')++ const readings = await readAccountUsage(deps({ fetchImpl: vendor().fetchImpl }))++ expect(readings.map((r) => r.outcome)).toEqual(['signedOut', 'signedOut'])+ })+})diff --git a/cli/src/lib/accountUsage.ts b/cli/src/lib/accountUsage.tsnew file mode 100644index 000000000..6421ef93c--- /dev/null+++ b/cli/src/lib/accountUsage.ts@@ -0,0 +1,204 @@+/**+ * This machine's agent-account usage — Claude's and Codex's rate limits — read with THIS machine's+ * own credentials, for a client that cannot read them itself.+ *+ * The desktop app reads the account on the computer it runs on directly. A remote machine may be+ * signed in to a DIFFERENT account, and a rate limit belongs to an account rather than to a+ * computer, so the only honest way to show that one is to ask the machine that holds it. This is the+ * answer to `usage_read`.+ *+ * **The credential never leaves this machine.** The vendor is called from here, and what goes back+ * over the relay is the vendor's answer — its HTTP status and body — plus an opaque account key.+ * Never the token, never the account's email or id.+ *+ * **Deliberately a thin proxy, not a parser.** The body is returned as the vendor sent it, and the+ * client interprets it with the SAME code that interprets its own local reading+ * (`autonomous-harness-desktop/lib/usage/*_usage_source.dart`). Parsing it here would put the+ * window-naming rules — "five_hour" is "Session", Codex derives its labels from+ * `limit_window_seconds`, Fable has been spelled three ways — in two languages, and the two copies+ * would drift the first time either vendor renamed a field.+ *+ * ⚠️ **Both endpoints are undocumented**, on exactly the terms the desktop app uses them: they are+ * what `claude /usage` and the Codex CLI ask, the Claude one answers only a token minted for Claude+ * Code (hence the beta header and the CLI's own user agent), and either can change without notice.+ * Every failure here is an `outcome`, never a throw — the reply must go back either way.+ */+import { createHash } from 'node:crypto'+import { execFile } from 'node:child_process'+import { readFile } from 'node:fs/promises'+import { homedir } from 'node:os'+import { join } from 'node:path'+import { promisify } from 'node:util'++const execFileAsync = promisify(execFile)++export type UsageProviderId = 'claude' | 'codex'++/**+ * How far the question got. `answered` means the vendor was asked and replied — WHATEVER it+ * replied, a 401 included; the client decides what a status means, because it already does for+ * its own reading.+ */+export type UsageOutcome = 'answered' | 'signedOut' | 'unreachable'++export interface AccountUsageReading {+ provider: UsageProviderId+ /**+ * `accountKey(provider, id)`, or null when this machine cannot name the account it is signed in+ * as. The client compares these to show one figure per ACCOUNT rather than one per machine.+ */+ account: string | null+ outcome: UsageOutcome+ httpStatus?: number+ body?: unknown+ /** Why there is no answer, when this side knows better than a status code can say. */+ message?: string+}++export const CLAUDE_USAGE_URL = 'https://api.anthropic.com/api/oauth/usage'+export const CODEX_USAGE_URL = 'https://chatgpt.com/backend-api/wham/usage'++/** Under the client's own 10s request timeout, so a slow vendor still produces a reply. */+const FETCH_TIMEOUT_MS = 8_000++/**+ * An account, as the wire names it: the first 16 hex characters of sha256(`<provider>:<id>`).+ *+ * Hashed rather than sent raw because the reply is LOGGED — the desktop writes every RPC answer to+ * `~/.harness/logs` — and an account id or email has no business there. Equality survives hashing,+ * which is all the client needs.+ *+ * ⚠️ **A cross-language contract.** The desktop computes the same key for its own account+ * (`lib/usage/usage_account_key.dart`) and the two must agree byte for byte, or every remote reading+ * would look like a different account. Both test suites pin the same vector for that reason.+ */+export function accountKey(provider: UsageProviderId, accountId: string): string {+ return createHash('sha256').update(`${provider}:${accountId}`).digest('hex').slice(0, 16)+}++/** Everything that reaches outside this function, so a spec never touches a real home, keychain or+ * network. Production passes nothing. */+export interface AccountUsageDeps {+ home?: string+ platform?: NodeJS.Platform+ fetchImpl?: typeof fetch+ readKeychain?: () => Promise<string | null>+ now?: () => number+}++/** Both accounts, asked at once — one being slow says nothing about the other. */+export async function readAccountUsage(deps: AccountUsageDeps = {}): Promise<AccountUsageReading[]> {+ return Promise.all([readClaude(deps), readCodex(deps)])+}++async function readClaude(deps: AccountUsageDeps): Promise<AccountUsageReading> {+ const home = deps.home ?? homedir()+ // The Keychain first and the file second, as the desktop reads its own: macOS keeps the token in+ // the login Keychain and Linux in a file, and a Keychain that will not answer is a state, not the+ // end of the road.+ const stored = (await readKeychain(deps)) ?? (await readText(join(home, '.claude', '.credentials.json')))+ const oauth = asRecord(asRecord(parseJson(stored))?.claudeAiOauth)+ const token = stringField(oauth?.accessToken)+ // The account lives beside the token rather than in it: `~/.claude.json` is where Claude Code+ // records who it is signed in as, on every platform.+ const profile = asRecord(asRecord(parseJson(await readText(join(home, '.claude.json'))))?.oauthAccount)+ const accountId = stringField(profile?.accountUuid)+ const account = accountId ? accountKey('claude', accountId) : null+ if (!token) return { provider: 'claude', account, outcome: 'signedOut' }++ // Spent as a sign-in rather than as a round trip: nothing here refreshes a token Claude Code owns,+ // so the request could only fail. The sentence is the desktop's own, word for word.+ const expiresAt = typeof oauth?.expiresAt === 'number' ? oauth.expiresAt : null+ if (expiresAt !== null && expiresAt < (deps.now ?? Date.now)()) {+ return {+ provider: 'claude',+ account,+ outcome: 'signedOut',+ message: 'Claude session expired — run claude to sign in again',+ }+ }+ return ask('claude', account, CLAUDE_USAGE_URL, {+ Authorization: `Bearer ${token}`,+ 'anthropic-beta': 'oauth-2025-04-20',+ 'User-Agent': 'claude-code/2.1.0',+ }, deps)+}++async function readCodex(deps: AccountUsageDeps): Promise<AccountUsageReading> {+ const home = deps.home ?? homedir()+ const tokens = asRecord(asRecord(parseJson(await readText(join(home, '.codex', 'auth.json'))))?.tokens)+ const token = stringField(tokens?.access_token)+ const accountId = stringField(tokens?.account_id)+ const account = accountId ? accountKey('codex', accountId) : null+ if (!token) return { provider: 'codex', account, outcome: 'signedOut' }+ const headers: Record<string, string> = { Authorization: `Bearer ${token}` }+ // The account the backend scopes the reading to — the same id the key above is made from.+ if (accountId) headers['ChatGPT-Account-Id'] = accountId+ return ask('codex', account, CODEX_USAGE_URL, headers, deps)+}++async function ask(+ provider: UsageProviderId,+ account: string | null,+ url: string,+ headers: Record<string, string>,+ deps: AccountUsageDeps,+): Promise<AccountUsageReading> {+ const fetchImpl = deps.fetchImpl ?? fetch+ try {+ const response = await fetchImpl(url, { headers, signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) })+ const text = await response.text()+ return { provider, account, outcome: 'answered', httpStatus: response.status, body: parseJson(text) }+ } catch {+ // No detail on purpose: a network error's message can carry the URL, and the client already+ // knows which vendor it asked.+ return { provider, account, outcome: 'unreachable' }+ }+}++/** The macOS Keychain item Claude Code writes — `security` rather than a native module, for one+ * read of one generic password. */+async function readKeychain(deps: AccountUsageDeps): Promise<string | null> {+ if (deps.readKeychain) return deps.readKeychain()+ if ((deps.platform ?? process.platform) !== 'darwin') return null+ try {+ const { stdout } = await execFileAsync(+ 'security',+ ['find-generic-password', '-s', 'Claude Code-credentials', '-w'],+ { timeout: 5_000 },+ )+ const out = stdout.trim()+ return out.length > 0 ? out : null+ } catch {+ return null+ }+}++async function readText(path: string): Promise<string | null> {+ try {+ return await readFile(path, 'utf8')+ } catch {+ return null+ }+}++/** A half-written credentials file is not news — the CLI that owns it is mid-refresh, and the next+ * poll a minute from now reads it whole. */+function parseJson(raw: string | null): unknown {+ if (raw === null) return null+ try {+ return JSON.parse(raw) as unknown+ } catch {+ return null+ }+}++function asRecord(value: unknown): Record<string, unknown> | null {+ return typeof value === 'object' && value !== null && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : null+}++function stringField(value: unknown): string | null {+ return typeof value === 'string' && value.length > 0 ? value : null+}diff --git a/cli/src/lib/e2ee/core.test.ts b/cli/src/lib/e2ee/core.test.tsindex 43ad56d0b..3450c5cc8 100644--- a/cli/src/lib/e2ee/core.test.ts+++ b/cli/src/lib/e2ee/core.test.ts@@ -132,6 +132,10 @@ describe('e2ee core — codes + fingerprint + classification', () => {expect(C.isEncryptedUpType('node_status')).toBe(false)expect(C.isEncryptedDownType('agents_list')).toBe(true)expect(C.isEncryptedDownType('agent_update')).toBe(true)+ // A machine's account usage names what the person spends and on whose subscription. Missing from+ // either list the request would not fail — it would time out, which is harder to find.+ expect(C.isEncryptedDownType('usage_read')).toBe(true)+ expect(C.isEncryptedRpcResultType('usage_read_result')).toBe(true)expect(C.ENCRYPTED_RPC_RESULT_TYPES.has('session_get_result')).toBe(true)expect(C.ENCRYPTED_RPC_RESULT_TYPES.has('agents_list_result')).toBe(true)expect(C.ENCRYPTED_RPC_RESULT_TYPES.has('agent_update_result')).toBe(true)@@ -197,6 +201,6 @@ describe('e2ee core — interop keystone', () => {it('core.ts still hashes to the pinned value shared with the other implementations', () => {const here = dirname(fileURLToPath(import.meta.url))const actual = createHash('sha256').update(readFileSync(join(here, 'core.ts'))).digest('hex')- expect(actual).toBe('e21ceb78f3cf8ca56d09bc52daf336f89a75d05dd84ee6882c7b736cfd5bb415')+ expect(actual).toBe('76b0171f0dd53a1a00e5e321f376ae956faacf3db85cd95b644ef3dd9f91e78c')})})diff --git a/cli/src/lib/e2ee/core.ts b/cli/src/lib/e2ee/core.tsindex 6c7d8a894..b333ed27c 100644--- a/cli/src/lib/e2ee/core.ts+++ b/cli/src/lib/e2ee/core.ts@@ -354,6 +354,9 @@ export const ENCRYPTED_RPC_RESULT_TYPES = new Set<string>(['fs_list_dir_result',// Same reasoning as fs_list_dir_result: reveals Codex profile folder names/paths on this machine.'codex_profiles_list_result', 'codex_profile_link_result',+ // This machine's Claude/Codex rate limits and a key naming the account — what the person is+ // spending, and on whose subscription. The relay has no business reading either.+ 'usage_read_result',])/** Client→adapter frames that carry or can trigger adapter-local user data. */export const ENCRYPTED_DOWN_TYPES = new Set<string>([@@ -366,6 +369,11 @@ export const ENCRYPTED_DOWN_TYPES = new Set<string>(['agents_list', 'sessions_list', 'session_get', 'models_list','agent_create', 'agent_delete', 'agent_restart', 'agent_recent', 'agent_update', 'agent_files', 'agent_read_file','fs_list_dir', 'codex_profiles_list', 'codex_profile_link',+ // Asks this machine to read its own agent accounts' usage (lib/accountUsage.ts). ⚠️ Missing here it+ // would not fail loudly — the same trap `question_response` once fell into: the payload would stay+ // an {__e2e} envelope, requestId would read back undefined, and the requester would wait out its+ // timeout on a reply that was never going to be sent.+ 'usage_read','device_e2ee_pair', 'e2ee_pairings_list', 'e2ee_pairing_unpair','e2ee_pairings_unpair_all', 'e2ee_browser_link_create',// Remote terminal control is always pairwise E2EE. The relay may route by outer type/connId but must