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): support gateway-launched agents (`ori claude`, `ori codex`)
0xken15f357609b1c01
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 9bfcf712d..c827ba421 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -47,7 +47,7 @@ import { DEVICE_RECENT_SAFE_FRAME_BYTES, fitRecentReplyPayloadForDevice } from 'import { shouldReplayCommander } from './lib/commanderReplay.js'import { RuntimeProfileControlError, type RuntimeProfileErrorCode } from './lib/runtimeProfileController.js'import { parseRuntimeProfile, type RuntimeModelOption } from './lib/runtimeProfile.js'-import { sid, preview } from './lib/log.js'+import { sid, preview, logFrame } from './lib/log.js'// OpenCode has no per-session transcript file — its history is read from this SQLite store.const OPENCODE_DB = join(env.OPENCODE_DATA_DIR, 'opencode.db')@@ -448,6 +448,7 @@ export class BackendSocket {/** Send an up-frame (event or RPC reply) to the WEB audience. Queued while disconnected.* User-content events are group-encrypted (E2EE) here; system frames pass through as plaintext. */send(frame: Frame): void {+ if (env.LOG_FRAMES) logFrame('→', 'web', frame)this.enqueue({ t: 'up', frame: this.e2ee.wrapUp(frame) })}@@ -464,6 +465,7 @@ export class BackendSocket {/** Send a DEVICE-audience frame (commanderEligible, not web). User/data frames are group-encrypted* (E2EE) here so the backend relays only ciphertext; system/presence frames pass through. */sendCommander(frame: Frame): void {+ if (env.LOG_FRAMES) logFrame('→', 'device', frame)this.enqueue({ t: 'up', webEligible: false, commanderEligible: true, frame: this.e2ee.wrapCommander(frame) })}@@ -536,6 +538,8 @@ export class BackendSocket {* is never returned plaintext: even legacy backend nodeRequest (`connId === ''`) gets only an error. */private emitReply(connId: string, type: string, requestId: unknown, payload: Record<string, unknown>): void {const resultType = `${type}_result`+ // Before the E2EE wrap: an RPC reply is only readable here.+ if (env.LOG_FRAMES) logFrame('→', connId ? `conn:${sid(connId)}` : 'backend', { type: resultType, payload: { requestId, ...payload } })if (connId && this.e2ee.hasSession(connId) && ENCRYPTED_RPC_RESULT_TYPES.has(resultType)) {let replyPayload = payloadif (resultType === 'agent_recent_result') {@@ -585,6 +589,9 @@ export class BackendSocket {if (!dec) returnframe = dec}+ // Logged AFTER the unwrap above, so a down-frame reads as what the client actually asked for rather+ // than as an opaque __e2e envelope.+ if (env.LOG_FRAMES) logFrame('←', connId ? `conn:${sid(connId)}` : 'backend', frame)const reply = (t: string, rid: unknown, p: Record<string, unknown>): void => this.emitReply(connId, t, rid, p)// Cross-instance client snapshot. Generation detects leave/join cycles that coalesce to the same// count; count rise remains the compatibility fallback for older backends.@@ -946,7 +953,8 @@ export class BackendSocket {const recentSummary = recents.map((r) => r?.recap || r?.text || '').filter(Boolean).join(' · ')// engine: the router classifies with a CLI the machine actually runs (a live agent proves it is// installed and logged in), so it has to travel with the agent.- return { id: p.id, name: p.name, recentSummary, engine: registry.resolve(p.id)?.engine }+ const session = registry.resolve(p.id)+ return { id: p.id, name: p.name, recentSummary, engine: session?.engine, gateway: session?.gateway }})const decision = await routeVoiceTask(transcript, agents) // logs the task, candidates and pickconst chosen = projects.find((p) => p.id === decision.agentId)diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex d4b3b56b3..771246467 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -89,6 +89,7 @@ import {commandCodeRunErrorSummary,lastCommandCodeTurnText,} from './engines/commandcode/normalizer.js'+import { probeGatewayRuntime } from './lib/gatewayRuntime.js'import { SessionInputController } from './lib/sessionInput.js'import { adaptSlashCommand } from './lib/goalCommand.js'import { RuntimeProfileManager } from './lib/runtimeProfile.js'@@ -143,6 +144,7 @@ function usage(): never {Agents — after "harness join", run the vendor CLI directly inside tmux. Harness discovers supportedtop-level processes automatically; it does not launch them or change their permission flags:${ENGINES.map((engine) => ` ${ENGINE_CLI_COMMANDS[engine]}`).join('\n')}+A launcher that hands the pane to one of these works the same — "ori claude" is a Claude Code agent.Machine:harness join <token> connect this computer to an existing machine using the token from its machine page@@ -879,8 +881,15 @@ async function runForeground(token: string): Promise<void> {sendWeb: (frame) => backend.send(frame), // turn_summary_pending / turn_summary → web indicatorhasDevice: () => backend.hasCommander(), // device-gate the LLM recap (mirror node)active: () => backend.hasActiveCommander(), // stream live cards only to the actively-rendered machine- summarize: (text, signal, userMessage, sessionId) =>- summarizeTurnText(text, signal, userMessage, sessionId ? registry.bySession(sessionId)?.engine ?? 'claude' : 'claude'),+ summarize: async (text, signal, userMessage, sessionId) => {+ const session = sessionId ? registry.bySession(sessionId) : undefined+ // Gateway agents recap through OpenRouter directly (no vendor credential to spend). The probe is+ // cached per live process, so this resolves without touching the process table again.+ const gateway = session?.gateway === 'ori' && session.processIdentity+ ? await probeGatewayRuntime(session.processIdentity)+ : undefined+ return summarizeTurnText(text, signal, userMessage, session?.engine ?? 'claude', gateway)+ },nameFor: (sessionId) => { const s = registry.bySession(sessionId); return s ? projectDisplayName(s) : undefined },agentIdFor: (sessionId) => registry.bySession(sessionId)?.agentId,readLastTurn: async (sessionId) => {@@ -1230,6 +1239,7 @@ async function runForeground(token: string): Promise<void> {tmuxPane: observed.tmuxPane,cwd: observed.cwd,processIdentity: observed.processIdentity,+ gateway: observed.gateway,})if (!opened) returnif (opened.evicted) console.log(`[discovery] ${observed.tmuxPane} replaced ${sid(opened.evicted)}`)@@ -1240,7 +1250,7 @@ async function runForeground(token: string): Promise<void> {await bindObservedAgent(observed)},onObserved: async (observed, current) => {- registry.updateProcessIdentity(current.agentId, observed.processIdentity)+ registry.updateProcessIdentity(current.agentId, observed.processIdentity, observed.gateway)await bindObservedAgent(observed)},onRemoved: (agent, reason) => {diff --git a/cli/src/config/env.ts b/cli/src/config/env.tsindex 1a126cb59..aebd8e721 100644--- a/cli/src/config/env.ts+++ b/cli/src/config/env.ts@@ -235,6 +235,23 @@ const envSchema = z.object({VOICE_ROUTE_MODEL: z.string().default('haiku'),// Test override: run the recap even with no device connected (mirrors node isRecapForced()).RECAP_FORCE: z.string().default('false').transform((v) => v === 'true'),+ // Log one line per backend frame (type + audience + a few opaque ids). OFF by default: it is noisy,+ // and it is the only place frames are visible in the clear — every content-bearing frame is E2EE+ // encrypted on the wire, so a packet capture cannot answer "what did the adapter actually send".+ // Never prints message text, transcripts, tokens or payload bodies.+ LOG_FRAMES: z.string().default('false').transform((v) => v === 'true'),++ // ── OpenRouter gateway agents (`ori claude`, `ori codex`, …) ───────────────────────────────────+ // An agent whose CLI is pointed at OpenRouter has no vendor credential to spend, so its recap and+ // voice route are served by ONE direct chat/completions call instead of a vendor one-shot: a recap+ // is a 200-token condensation, and spawning a whole coding agent to do it would bill an account the+ // user may not even have. Both default to a cheap, fast model; '' disables that call (the+ // VOICE_ROUTE_MODEL convention) and falls back to the engine path.+ ORI_SUMMARY_MODEL: z.string().default('deepseek/deepseek-v4-flash'),+ ORI_VOICE_ROUTE_MODEL: z.string().default('deepseek/deepseek-v4-flash'),+ // Where `ori login` stores the key ({ createdAt, key, userId }). Only read when neither the daemon+ // env nor the agent's own process supplies one.+ ORI_CREDENTIALS_PATH: z.string().default(join(homedir(), '.ori', 'credentials.json')),// ── self-update (the daemon polls a GCS manifest and swaps its own bundle) ──────────────────────// Manifest URL (same GCS bucket + metadata.json shape as the device OTA; key = ADAPTER_UPDATE_KEY).diff --git a/cli/src/engines/README.md b/cli/src/engines/README.mdindex 82908cecb..71d4ed103 100644--- a/cli/src/engines/README.md+++ b/cli/src/engines/README.md@@ -22,6 +22,13 @@ order. Two engines were each added in a single commit — Muse Code (`b6c58e6`)and reading either alongside this page shows every item below in context. Read Amp's if your agentdoes not write a transcript at all; see "When your agent writes nothing to disk".+**Launchers are not engines.** A wrapper that configures an environment and then hands the pane to a+vendor CLI — `ori claude`, an `env`-prefixed alias, a shell function — produces an agent of the+*wrapped* engine, with that engine's name, icon and normalizer. Discovery reads through the wrapper+(and most wrappers, ori included, `exec` themselves away entirely), so there is nothing to add here+for one. What a gateway launcher does change is billing: see `lib/gatewayRuntime.ts`, which marks such+a session display-only for model/effort and routes the daemon's own recap through the gateway.+---## The one rulediff --git a/cli/src/lib/gatewayRuntime.spec.ts b/cli/src/lib/gatewayRuntime.spec.tsnew file mode 100644index 000000000..5c26f97b1--- /dev/null+++ b/cli/src/lib/gatewayRuntime.spec.ts@@ -0,0 +1,148 @@+import { describe, expect, it, vi } from 'vitest'+import {+ argvNamesOpenRouterProvider,+ classifyGatewayRuntime,+ clearGatewayRuntimeCache,+ gatewayRuntimeCacheKey,+ probeGatewayRuntime,+ parseEnviron,+ parsePsEnviron,+} from './gatewayRuntime.js'++// READ OFF A REAL PROCESS, not from ori's source: `ori claude` on 0.7.1, macOS, 2026-08-17, captured+// after the execve with `ps eww`. The surprise is the key layout — ANTHROPIC_AUTH_TOKEN is EMPTY and the+// `sk-or-…` value sits in OPENROUTER_API_KEY and ANTHROPIC_API_KEY, the reverse of what ori's own+// bundled launcher code says. Anything that reads a key must survive that, and a future ori flipping it+// back.+const ORI_CLAUDE_ENV = [+ 'OPENROUTER_API_KEY=sk-or-v1-abc123',+ 'ANTHROPIC_BASE_URL=https://openrouter.ai/api',+ 'ANTHROPIC_AUTH_TOKEN=',+ 'ANTHROPIC_API_KEY=sk-or-v1-abc123',+ 'CLAUDE_CODE_SKIP_FAST_MODE_ORG_CHECK=1',+ 'CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1',+ 'CLAUDE_CODE_SIMPLE_SYSTEM_PROMPT=1',+ 'ANTHROPIC_DEFAULT_SONNET_MODEL=anthropic/claude-sonnet-5[1m]',+]++// `ori codex` configures its provider through argv, not env — the pane process carries these verbatim.+const ORI_CODEX_ARGS = '/opt/homebrew/bin/codex -c model_provider=openrouter -c '+ + 'model_providers.openrouter.base_url="https://openrouter.ai/api/v1"'++describe('parseEnviron (linux /proc)', () => {+ it('reads NUL-separated pairs and keeps values containing =', () => {+ const env = parseEnviron('HOME=/home/u\0ANTHROPIC_BASE_URL=https://openrouter.ai/api\0X=a=b\0')+ expect(env.HOME).toBe('/home/u')+ expect(env.ANTHROPIC_BASE_URL).toBe('https://openrouter.ai/api')+ expect(env.X).toBe('a=b')+ })+})++describe('parsePsEnviron (macOS ps eww)', () => {+ it('skips the argv prefix and reads the variables that follow', () => {+ const env = parsePsEnviron(`/Users/u/.local/bin/claude --resume abc ${ORI_CLAUDE_ENV.join(' ')}`)+ expect(env.ANTHROPIC_BASE_URL).toBe('https://openrouter.ai/api')+ expect(env.OPENROUTER_API_KEY).toBe('sk-or-v1-abc123')+ })++ it('is not derailed by the JSON blob ori now passes as --settings', () => {+ // Measured: `ori claude` execs `claude --settings {"apiKeyHelper":…,"env":{…}} -p noop`. That JSON is+ // argv, contains spaces and colons, and mentions the same variable names as the real environment.+ const argv = '/Users/u/.local/bin/claude --settings {"apiKeyHelper":"printf %s \\"$OPENROUTER_API_KEY\\"",'+ + '"env":{"ANTHROPIC_BASE_URL":"https://openrouter.ai/api"}} -p noop'+ const env = parsePsEnviron(`${argv} ${ORI_CLAUDE_ENV.join(' ')}`)+ expect(env.ANTHROPIC_BASE_URL).toBe('https://openrouter.ai/api')+ expect(env.OPENROUTER_API_KEY).toBe('sk-or-v1-abc123')+ })++ it('rejoins a value that contains spaces, since ps quotes nothing', () => {+ const env = parsePsEnviron('claude LANG=en_US.UTF-8 SOME_TITLE=two words HOME=/Users/u')+ expect(env.SOME_TITLE).toBe('two words')+ expect(env.HOME).toBe('/Users/u')+ })+})++describe('argvNamesOpenRouterProvider', () => {+ it('recognizes the provider block ori codex injects', () => {+ expect(argvNamesOpenRouterProvider(ORI_CODEX_ARGS)).toBe(true)+ })++ it('does not fire on a plain codex, or on prompt text that mentions openrouter', () => {+ expect(argvNamesOpenRouterProvider('/opt/homebrew/bin/codex --full-auto')).toBe(false)+ expect(argvNamesOpenRouterProvider('claude -p "compare openrouter and anthropic pricing"')).toBe(false)+ })+})++describe('classifyGatewayRuntime', () => {+ it('marks an ori claude pane and lifts its key', () => {+ const runtime = classifyGatewayRuntime(parsePsEnviron(`claude ${ORI_CLAUDE_ENV.join(' ')}`))+ expect(runtime.kind).toBe('ori')+ expect(runtime.apiKey).toBe('sk-or-v1-abc123')+ })++ it('finds the key whichever variable this ori version put it in', () => {+ const base = { ANTHROPIC_BASE_URL: 'https://openrouter.ai/api' }+ // Measured layout: AUTH_TOKEN empty, key in ANTHROPIC_API_KEY.+ expect(classifyGatewayRuntime({ ...base, ANTHROPIC_AUTH_TOKEN: '', ANTHROPIC_API_KEY: 'sk-or-v1-a' }).apiKey).toBe('sk-or-v1-a')+ // Documented layout: key in AUTH_TOKEN, API_KEY blanked.+ expect(classifyGatewayRuntime({ ...base, ANTHROPIC_AUTH_TOKEN: 'sk-or-v1-b', ANTHROPIC_API_KEY: '' }).apiKey).toBe('sk-or-v1-b')+ })++ it('marks an ori codex pane from argv alone', () => {+ expect(classifyGatewayRuntime({ OPENROUTER_API_KEY: 'sk-or-v1-abc123' }, ORI_CODEX_ARGS).kind).toBe('ori')+ })++ it('leaves a normal vendor login alone, key or not', () => {+ expect(classifyGatewayRuntime({ ANTHROPIC_API_KEY: 'sk-ant-1' }).kind).toBeNull()+ expect(classifyGatewayRuntime({ ANTHROPIC_BASE_URL: 'https://api.anthropic.com' }).kind).toBeNull()+ expect(classifyGatewayRuntime({}).kind).toBeNull()+ })++ it('is not fooled by a host that merely ends in something similar', () => {+ expect(classifyGatewayRuntime({ ANTHROPIC_BASE_URL: 'https://notopenrouter.ai/api' }).kind).toBeNull()+ expect(classifyGatewayRuntime({ ANTHROPIC_BASE_URL: 'https://gw.openrouter.ai/api' }).kind).toBe('ori')+ })++ it('separates one live process image from another in the cache key', () => {+ const identity = { pid: 4242, startMarker: 'Sun Aug 17 10:36:00 2026', executable: 'ori' }+ expect(gatewayRuntimeCacheKey(identity))+ .not.toBe(gatewayRuntimeCacheKey({ ...identity, executable: 'codex' }))+ expect(gatewayRuntimeCacheKey({ ...identity, startMarker: 'Sun Aug 17 11:00:00 2026' }))+ .not.toBe(gatewayRuntimeCacheKey(identity))+ // A genuine re-scan of the same image shares one entry — that is what makes this a cache.+ expect(gatewayRuntimeCacheKey({ ...identity })).toBe(gatewayRuntimeCacheKey({ ...identity }))+ })++ it('re-probes a live process that was NOT a gateway, so a pre-exec read cannot pin it forever', async () => {+ // The live bug this pins: `ori codex` was scanned in the ~100ms before execve, read as `ori` (which+ // carries none of the routing it is about to install), and the null answer stuck for the agent's whole+ // life. Keying on the executable is not enough on its own — macOS truncates comm to 16 chars, so+ // `~/.local/bin/ori` and `~/.local/bin/claude` are indistinguishable — hence a TTL on negatives.+ clearGatewayRuntimeCache()+ const identity = { pid: process.pid, startMarker: 'Sun Aug 17 10:36:00 2026', executable: 'ori' }+ const first = await probeGatewayRuntime(identity) // this test process is not a gateway+ expect(first.kind).toBeNull()++ // Same identity, one minute later: the negative has expired and the probe runs again.+ const realNow = Date.now+ try {+ Date.now = () => realNow() + 61_000+ const spy = vi.spyOn(process, 'platform', 'get')+ spy.mockReturnValue('linux') // makes the re-probe read /proc, which fails here → still null…+ const second = await probeGatewayRuntime(identity)+ expect(second.kind).toBeNull()+ // …and a failed read is never cached, so the next pass tries once more rather than settling.+ expect(await probeGatewayRuntime(identity)).toEqual({ kind: null })+ } finally {+ Date.now = realNow+ vi.restoreAllMocks()+ clearGatewayRuntimeCache()+ }+ })++ it('still marks the session when the endpoint is routed but no key is readable', () => {+ const runtime = classifyGatewayRuntime({ ANTHROPIC_BASE_URL: 'https://openrouter.ai/api' })+ expect(runtime.kind).toBe('ori')+ expect(runtime.apiKey).toBeUndefined()+ })+})diff --git a/cli/src/lib/gatewayRuntime.ts b/cli/src/lib/gatewayRuntime.tsnew file mode 100644index 000000000..bc3359643--- /dev/null+++ b/cli/src/lib/gatewayRuntime.ts@@ -0,0 +1,161 @@+/**+ * Is this pane's engine talking to a GATEWAY instead of its vendor's own API?+ *+ * `ori claude` (OpenRouter's launcher) does not stay in the process tree: it resolves the vendor binary+ * and `execve`s itself away, so `ps` shows a plain `claude`/`codex` and discovery finds the agent with no+ * help from here. What survives the exec is the ROUTING — env for claude/opencode/hermes+ * (`ANTHROPIC_BASE_URL=https://openrouter.ai/api` + a `sk-or-…` token), argv for codex+ * (`-c model_provider=openrouter …`, which is how `ori codex` configures the provider at all).+ *+ * So the gateway is read off the live process rather than declared: a hand-rolled+ * `ANTHROPIC_BASE_URL=…openrouter…` alias is treated exactly like `ori claude`, and nothing about ori's+ * internals is hard-coded here. Two things follow from a positive read — the runtime profile becomes+ * display-only (nothing may type `/model` into a pane whose catalog we cannot enumerate), and the+ * daemon's own recap/route calls go straight to OpenRouter with the key below instead of spawning a+ * vendor CLI that has no credential to spend.+ *+ * The key is held in memory only: never written to the registry, never logged, never sent to the backend.+ */++import { execFile } from 'node:child_process'+import { readFile } from 'node:fs/promises'+import type { ProcessIdentity } from './registry.js'++export interface GatewayRuntime {+ /** 'ori' ⇔ an OpenRouter endpoint is in play. null = a normal vendor login, or we could not look. */+ kind: 'ori' | null+ /** The OpenRouter key as the pane itself received it, when the probe could read one. */+ apiKey?: string+}++const NONE: GatewayRuntime = { kind: null }++/**+ * Env vars worth reading. Everything else in the process env is the user's business, not ours.+ *+ * Which variable carries the key is version-dependent and must not be assumed: measured on ori 0.7.1,+ * `ori claude` sets OPENROUTER_API_KEY **and** ANTHROPIC_API_KEY to the same `sk-or-…` value while+ * leaving ANTHROPIC_AUTH_TOKEN empty — the exact opposite of the layout its own bundled launcher code+ * describes. So try all of them, in the order that is unambiguous first, and skip empty values. Reading+ * a key at all is already gated on the endpoint being OpenRouter, so nothing here can pick up a vendor+ * credential by mistake.+ */+const BASE_URL_VARS = ['ANTHROPIC_BASE_URL', 'OPENAI_BASE_URL', 'OPENAI_API_BASE'] as const+const KEY_VARS = ['OPENROUTER_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_API_KEY', 'OPENAI_API_KEY'] as const++const OPENROUTER_HOST = /(?:^|\.)openrouter\.ai$/i++/**+ * Cache the probe so it costs one read per agent, not one per 5s scan — but cache the two answers+ * differently, because only one of them is permanent.+ *+ * A POSITIVE is permanent: a process's environment cannot change under it, so an agent seen routed+ * through OpenRouter stays routed for its whole life.+ *+ * A NEGATIVE expires. A launcher is discoverable for the ~100ms before it replaces itself, and in that+ * window "not a gateway" is the honest answer — `ori` carries none of the routing it is about to install.+ * Measured, not theorised: `ori codex` was scanned as `ori`, cached null, and stayed a non-gateway agent+ * for the rest of its life while the codex it became ran `-c model_provider=openrouter`.+ *+ * Keying on the executable was the first fix and it is NOT sufficient: macOS truncates `comm` to 16+ * chars, so `~/.local/bin/ori` and `~/.local/bin/claude` are the SAME string and the exec is invisible.+ * A short TTL closes that hole and every other one like it (an engine that rewrites its own argv, a slow+ * launcher) for one extra `ps eww` per non-gateway agent per minute.+ */+const cache = new Map<string, { runtime: GatewayRuntime; at: number }>()+const CACHE_LIMIT = 256+const NEGATIVE_TTL_MS = 60_000++/** Exported only so a test can pin the key's shape — the bugs above are invisible otherwise. */+export function gatewayRuntimeCacheKey(identity: ProcessIdentity): string {+ return `${identity.pid}\u0000${identity.startMarker}\u0000${identity.executable}`+}++export function clearGatewayRuntimeCache(): void {+ cache.clear()+}++function isOpenRouterUrl(value: string | undefined): boolean {+ if (!value) return false+ try {+ return OPENROUTER_HOST.test(new URL(value).hostname)+ } catch {+ return false+ }+}++/** `ori codex` passes its provider as argv, so codex panes are recognized without reading any env. */+export function argvNamesOpenRouterProvider(args: string): boolean {+ return /(?:^|\s)-c\s+model_provider=openrouter(?:\s|$)/.test(args)+ || /model_providers\.openrouter\./.test(args)+}++/** NUL-separated `/proc/<pid>/environ`. */+export function parseEnviron(blob: string): Record<string, string> {+ const out: Record<string, string> = {}+ for (const entry of blob.split('\0')) {+ const eq = entry.indexOf('=')+ if (eq > 0) out[entry.slice(0, eq)] = entry.slice(eq + 1)+ }+ return out+}++/**+ * macOS `ps eww -p <pid> -o command=`: argv first, then `KEY=VALUE` pairs, all space-separated with no+ * quoting. A value containing spaces is therefore only recoverable by reading up to the next token that+ * starts a new variable — which is exactly what this does. Leading argv is skipped by the same rule+ * (`--flag=x` cannot start a variable), and the keys we care about never carry spaces anyway.+ */+export function parsePsEnviron(line: string): Record<string, string> {+ const out: Record<string, string> = {}+ let key: string | null = null+ for (const token of line.trim().split(/\s+/)) {+ const eq = token.indexOf('=')+ if (eq > 0 && /^[A-Za-z_][A-Za-z0-9_]*$/.test(token.slice(0, eq))) {+ key = token.slice(0, eq)+ out[key] = token.slice(eq + 1)+ } else if (key) {+ out[key] += ` ${token}`+ }+ }+ return out+}++function readProcessEnv(pid: number): Promise<Record<string, string> | null> {+ if (process.platform === 'linux') {+ return readFile(`/proc/${pid}/environ`, 'utf8').then(parseEnviron).catch(() => null)+ }+ return new Promise((resolve) => {+ execFile('ps', ['eww', '-p', String(pid), '-o', 'command='], { timeout: 2_000, maxBuffer: 4 << 20 }, (err, stdout) => {+ resolve(err && !stdout ? null : parsePsEnviron(stdout))+ })+ })+}++/** Classify an already-read env + argv. Exported for fixtures; the probe below adds I/O and caching. */+export function classifyGatewayRuntime(processEnv: Record<string, string>, args = ''): GatewayRuntime {+ const routed = BASE_URL_VARS.some((name) => isOpenRouterUrl(processEnv[name]))+ if (!routed && !argvNamesOpenRouterProvider(args)) return NONE+ const apiKey = KEY_VARS.map((name) => processEnv[name]?.trim()).find((value) => !!value)+ return apiKey ? { kind: 'ori', apiKey } : { kind: 'ori' }+}++/**+ * Read the routing of one live engine process.+ *+ * A failed read returns `{ kind: null }` and is NOT cached: "we could not look" is not "this is a normal+ * login", and it must never cost an agent its chip or its recap on the next pass.+ */+export async function probeGatewayRuntime(identity: ProcessIdentity, args = ''): Promise<GatewayRuntime> {+ const key = gatewayRuntimeCacheKey(identity)+ const hit = cache.get(key)+ if (hit && (hit.runtime.kind !== null || Date.now() - hit.at < NEGATIVE_TTL_MS)) return hit.runtime++ const processEnv = await readProcessEnv(identity.pid)+ if (!processEnv) return argvNamesOpenRouterProvider(args) ? { kind: 'ori' } : NONE++ const runtime = classifyGatewayRuntime(processEnv, args)+ if (cache.size >= CACHE_LIMIT) cache.clear()+ cache.set(key, { runtime, at: Date.now() })+ return runtime+}diff --git a/cli/src/lib/log.spec.ts b/cli/src/lib/log.spec.tsindex ae493c912..daf18dd83 100644--- a/cli/src/lib/log.spec.ts+++ b/cli/src/lib/log.spec.ts@@ -3,7 +3,7 @@ import { closeSync, existsSync, mkdtempSync, openSync, readFileSync, rmSync, staimport { tmpdir } from 'os'import { join } from 'path'import {- ts, sid, preview, installTimestampedConsole,+ ts, sid, preview, installTimestampedConsole, logFrame,adoptLegacyLog, prepareLogFile, trimLogFile, LOG_MAX_BYTES,} from './log.js'@@ -19,6 +19,52 @@ describe('log helpers', () => {expect(sid('69aaaa14-89e9-7e21-871a-ee6ea943fc95')).toBe('69aaaa14')})+ describe('logFrame', () => {+ const lastLine = (spy: ReturnType<typeof vi.spyOn>) => String(spy.mock.calls.at(-1)?.[0] ?? '')++ it('prints direction, audience, type and the opaque ids that make a frame identifiable', () => {+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {})+ logFrame('→', 'web', {+ type: 'agent_synced',+ payload: {+ agentId: '26f49435-71e8-4461-ac59-65c0e854b374',+ agent: { engine: 'claude', selectedModel: 'runtime-v1:x:claude:anthropic%2Fclaude-sonnet-5@xhigh' },+ },+ })+ const line = lastLine(spy)+ expect(line).toContain('[frame] → web agent_synced')+ expect(line).toContain('agentId=26f49435')+ expect(line).toContain('engine=claude')+ expect(line).toContain('agent.selectedModel=runtime-v1:x:claude:anthropic%2Fclaude-sonnet-5@xhigh')+ })++ it('never prints a payload body — this log is the one place frames are in the clear', () => {+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {})+ logFrame('←', 'conn:74dab280', {+ type: 'message',+ payload: {+ sessionId: '9e9f7954-1111-2222-3333-444455556666',+ text: 'my private prompt about the acquisition',+ token: 'sk-or-v1-secret',+ images: ['data:image/png;base64,AAAA'],+ },+ })+ const line = lastLine(spy)+ expect(line).toContain('sessionId=9e9f7954')+ expect(line).not.toContain('private prompt')+ expect(line).not.toContain('sk-or-v1-secret')+ expect(line).not.toContain('base64')+ })++ it('summarizes a catalog by size, not by contents', () => {+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {})+ logFrame('→', 'conn:1', { type: 'models_list_result', payload: { models: [{ id: 'a' }, { id: 'b' }] } })+ expect(lastLine(spy)).toContain('models=2')+ logFrame('→', 'conn:1', { type: 'models_list_result', payload: { models: [] } })+ expect(lastLine(spy)).toContain('models=0')+ })+ })+it('flattens whitespace and caps preview with an ellipsis', () => {expect(preview(' hello\n\n world ')).toBe('hello world')expect(preview('abcdef', 3)).toBe('abc…')diff --git a/cli/src/lib/log.ts b/cli/src/lib/log.tsindex 19d4d4bfb..a1507db6a 100644--- a/cli/src/lib/log.ts+++ b/cli/src/lib/log.ts@@ -109,3 +109,35 @@ export function preview(text: string, max = 60): string {const flat = (text || '').replace(/\s+/g, ' ').trim()return flat.length > max ? `${flat.slice(0, max)}…` : flat}++/**+ * One line per backend frame, when LOG_FRAMES is on.+ *+ * Every content-bearing frame is E2EE-encrypted before it reaches the socket, so there is no way to see+ * what the adapter actually said from the outside — not from a packet capture, not from the backend.+ * This is that view, taken on the plaintext side of the wrap.+ *+ * It prints the frame TYPE and a fixed set of opaque identifiers, never a payload body: no message text,+ * no transcript, no token, no model list. Keep it that way — the point is to see the shape of a+ * conversation between adapter and clients, not its contents.+ */+export function logFrame(direction: '→' | '←', audience: string, frame: { type?: unknown; payload?: unknown }): void {+ const type = typeof frame.type === 'string' ? frame.type : '?'+ const payload = (frame.payload ?? {}) as Record<string, unknown>+ const bits: string[] = []+ for (const key of ['agentId', 'sessionId', 'dbSessionId', 'requestId'] as const) {+ const value = payload[key]+ if (typeof value === 'string' && value) bits.push(`${key}=${sid(value)}`)+ }+ // The runtime profile is an opaque id by construction — printing it whole is what makes a model/effort+ // bug readable in one line, and it carries nothing private.+ if (typeof payload.selectedModel === 'string') bits.push(`selectedModel=${payload.selectedModel}`)+ const agent = payload.agent as Record<string, unknown> | undefined+ if (agent && typeof agent === 'object') {+ if (typeof agent.engine === 'string') bits.push(`engine=${agent.engine}`)+ if (typeof agent.selectedModel === 'string') bits.push(`agent.selectedModel=${agent.selectedModel}`)+ }+ if (Array.isArray(payload.models)) bits.push(`models=${payload.models.length}`)+ if (typeof payload.error === 'string') bits.push(`error=${payload.error}`)+ console.log(`[frame] ${direction} ${audience} ${type}${bits.length ? ` · ${bits.join(' · ')}` : ''}`)+}diff --git a/cli/src/lib/openrouter.spec.ts b/cli/src/lib/openrouter.spec.tsnew file mode 100644index 000000000..a4edbcf17--- /dev/null+++ b/cli/src/lib/openrouter.spec.ts@@ -0,0 +1,112 @@+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { env } from '../config/env.js'+import { openRouterComplete, redactKeys, resolveOpenRouterKey } from './openrouter.js'++const KEY = 'sk-or-v1-file-key'+const originalPath = env.ORI_CREDENTIALS_PATH+const originalEnvKey = process.env.OPENROUTER_API_KEY+const dirs: string[] = []++function credentialsFile(contents: string): string {+ const dir = mkdtempSync(join(tmpdir(), 'ori-cred-'))+ dirs.push(dir)+ const file = join(dir, 'credentials.json')+ writeFileSync(file, contents)+ return file+}++beforeEach(() => {+ delete process.env.OPENROUTER_API_KEY+ // A path that does not exist is the normal state on a machine without ori.+ env.ORI_CREDENTIALS_PATH = join(tmpdir(), 'ori-cred-absent', 'credentials.json')+})++afterEach(() => {+ env.ORI_CREDENTIALS_PATH = originalPath+ if (originalEnvKey === undefined) delete process.env.OPENROUTER_API_KEY+ else process.env.OPENROUTER_API_KEY = originalEnvKey+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })+ vi.unstubAllGlobals()+})++describe('resolveOpenRouterKey', () => {+ it('prefers the daemon env, then the agent process, then the credentials file', async () => {+ env.ORI_CREDENTIALS_PATH = credentialsFile(JSON.stringify({ key: KEY }))+ process.env.OPENROUTER_API_KEY = 'sk-or-v1-daemon'+ expect(await resolveOpenRouterKey({ kind: 'ori', apiKey: 'sk-or-v1-process' })).toBe('sk-or-v1-daemon')++ delete process.env.OPENROUTER_API_KEY+ expect(await resolveOpenRouterKey({ kind: 'ori', apiKey: 'sk-or-v1-process' })).toBe('sk-or-v1-process')++ expect(await resolveOpenRouterKey({ kind: 'ori' })).toBe(KEY)+ expect(await resolveOpenRouterKey()).toBe(KEY)+ })++ it('returns null — never throws — when the file is absent, corrupt or keyless', async () => {+ expect(await resolveOpenRouterKey()).toBeNull()+ env.ORI_CREDENTIALS_PATH = credentialsFile('{not json')+ expect(await resolveOpenRouterKey()).toBeNull()+ env.ORI_CREDENTIALS_PATH = credentialsFile(JSON.stringify({ userId: 'or_user_1' }))+ expect(await resolveOpenRouterKey()).toBeNull()+ })++ it('re-reads after the file changes, so `ori login` needs no daemon restart', async () => {+ const file = credentialsFile(JSON.stringify({ key: 'sk-or-v1-old' }))+ env.ORI_CREDENTIALS_PATH = file+ expect(await resolveOpenRouterKey()).toBe('sk-or-v1-old')+ writeFileSync(file, JSON.stringify({ key: 'sk-or-v1-new' }))+ expect(await resolveOpenRouterKey()).toBe('sk-or-v1-new')+ })+})++describe('openRouterComplete', () => {+ const options = { prompt: 'summarize this', model: 'deepseek/deepseek-v4-flash', apiKey: KEY }++ it('sends the prompt and returns the completion text', async () => {+ const fetchMock = vi.fn().mockResolvedValue({+ ok: true,+ json: async () => ({ choices: [{ message: { content: ' recap\n\nbody ' } }] }),+ })+ vi.stubGlobal('fetch', fetchMock)++ expect(await openRouterComplete(options)).toBe('recap\n\nbody')+ const [url, init] = fetchMock.mock.calls[0]+ expect(url).toBe('https://openrouter.ai/api/v1/chat/completions')+ expect((init.headers as Record<string, string>).Authorization).toBe(`Bearer ${KEY}`)+ expect(JSON.parse(init.body as string)).toMatchObject({+ model: options.model,+ messages: [{ role: 'user', content: options.prompt }],+ })+ })++ it('returns null on an HTTP error instead of failing the turn', async () => {+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false, status: 402, text: async () => 'no credits' }))+ expect(await openRouterComplete(options)).toBeNull()+ })++ it('returns null on a transport failure and on an empty completion', async () => {+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('ECONNRESET')))+ expect(await openRouterComplete(options)).toBeNull()+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => ({ choices: [] }) }))+ expect(await openRouterComplete(options)).toBeNull()+ })++ it("re-throws the CALLER's abort, so a superseded recap stays superseded", async () => {+ const controller = new AbortController()+ vi.stubGlobal('fetch', vi.fn().mockImplementation(() => {+ controller.abort()+ return Promise.reject(Object.assign(new Error('aborted'), { name: 'AbortError' }))+ }))+ await expect(openRouterComplete({ ...options, signal: controller.signal })).rejects.toThrow('aborted')+ })+})++describe('redactKeys', () => {+ it('keeps a key out of anything that can be logged', () => {+ expect(redactKeys(`bad request for ${KEY}`)).toBe('bad request for sk-…')+ expect(redactKeys('nothing secret here')).toBe('nothing secret here')+ })+})diff --git a/cli/src/lib/openrouter.ts b/cli/src/lib/openrouter.tsnew file mode 100644index 000000000..cd12231a2--- /dev/null+++ b/cli/src/lib/openrouter.ts@@ -0,0 +1,136 @@+/**+ * One direct OpenRouter call, for the daemon's OWN small LLM jobs (turn recap, voice routing) on agents+ * that run through the gateway.+ *+ * Every other engine path in this file's neighbourhood spawns the user's vendor CLI, which works because+ * that CLI is logged in. A `ori claude` user may have no Anthropic account at all — their credential is+ * an OpenRouter key — so the vendor one-shot has nothing to spend and the recap silently never arrives.+ * Both jobs are a couple of hundred tokens of text condensation, so the answer is not "spawn a different+ * agent" but "make the request ourselves": no process, no pool slot, no vendor login, one HTTPS call.+ *+ * The key never leaves this module except in an Authorization header to openrouter.ai, and is redacted+ * from every message this module can produce.+ */++import { readFile, stat } from 'node:fs/promises'+import { env } from '../config/env.js'+import type { GatewayRuntime } from './gatewayRuntime.js'++const ENDPOINT = 'https://openrouter.ai/api/v1/chat/completions'+/**+ * Matches the vendor one-shot's 60s (`oneshot.ts`), and for the same reason: this call REPLACES that+ * one, so a recap must not become less reliable by being routed through a gateway.+ *+ * It was 20s until a live run proved that wrong. OpenRouter spreads one model id across providers, and+ * the same `deepseek/deepseek-v4-flash` request measured 1.6s, 8.4s and >20s within ten minutes — the+ * 20s attempt aborted a recap that had already been paid for. A recap is asynchronous (the card arrives+ * when it arrives), so waiting is cheap and giving up early is not. Callers on a real deadline pass+ * their own: the voice router uses 12s, under the backend's 15s RPC budget.+ */+const DEFAULT_TIMEOUT_MS = 60_000+const DEFAULT_MAX_TOKENS = 512++/** `ori login` writes { createdAt, key: 'sk-or-…', userId }. */+interface OriCredentials {+ key?: unknown+}++let fileCache: { path: string; mtimeMs: number; key: string | null } | null = null++/** Strip anything that looks like a key from text that may be logged. */+export function redactKeys(text: string): string {+ return text.replace(/sk-[A-Za-z0-9_-]{8,}/g, 'sk-…')+}++async function keyFromCredentialsFile(): Promise<string | null> {+ const path = env.ORI_CREDENTIALS_PATH+ try {+ const { mtimeMs } = await stat(path)+ // Re-read on change so `ori login` (or a key rotation) is picked up without restarting the daemon.+ if (fileCache && fileCache.path === path && fileCache.mtimeMs === mtimeMs) return fileCache.key+ const parsed = JSON.parse(await readFile(path, 'utf8')) as OriCredentials+ const key = typeof parsed.key === 'string' && parsed.key.trim() ? parsed.key.trim() : null+ fileCache = { path, mtimeMs, key }+ return key+ } catch {+ // Absent, unreadable or corrupt is a normal state (no ori installed) — not an error worth logging.+ fileCache = null+ return null+ }+}++/**+ * First hit wins: the daemon's own env, then the key the AGENT's process was given, then `ori login`'s+ * file. The middle one matters most — it is per-agent, so a machine mixing gateway and vendor agents+ * bills each recap to whatever that agent already runs on.+ */+export async function resolveOpenRouterKey(gateway?: GatewayRuntime): Promise<string | null> {+ const fromEnv = process.env.OPENROUTER_API_KEY?.trim()+ if (fromEnv) return fromEnv+ const fromProcess = gateway?.apiKey?.trim()+ if (fromProcess) return fromProcess+ return keyFromCredentialsFile()+}++export interface OpenRouterCompletionOptions {+ prompt: string+ model: string+ apiKey: string+ signal?: AbortSignal+ timeoutMs?: number+ maxTokens?: number+ temperature?: number+}++/**+ * The completion text, or null when the call could not produce one.+ *+ * Null rather than throw: both callers already degrade gracefully (the recap logs and skips the card, the+ * router falls back to name matching), and a gateway hiccup must never fail the turn or the RPC. An+ * abort from the CALLER is re-thrown, so a superseded recap stays superseded.+ */+export async function openRouterComplete(options: OpenRouterCompletionOptions): Promise<string | null> {+ const controller = new AbortController()+ const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? DEFAULT_TIMEOUT_MS)+ const onCallerAbort = () => controller.abort()+ options.signal?.addEventListener('abort', onCallerAbort, { once: true })++ try {+ const res = await fetch(ENDPOINT, {+ method: 'POST',+ headers: {+ 'Authorization': `Bearer ${options.apiKey}`,+ 'Content-Type': 'application/json',+ // OpenRouter attributes usage in the user's activity export by these two.+ 'HTTP-Referer': 'https://harness.autonomous.ai',+ 'X-Title': 'Harness',+ },+ body: JSON.stringify({+ model: options.model,+ messages: [{ role: 'user', content: options.prompt }],+ max_tokens: options.maxTokens ?? DEFAULT_MAX_TOKENS,+ temperature: options.temperature ?? 0,+ }),+ signal: controller.signal,+ })++ if (!res.ok) {+ const body = redactKeys((await res.text().catch(() => '')).slice(0, 300))+ if (res.status === 402) console.warn('[openrouter] out of credits — top up at https://openrouter.ai/settings/credits')+ else console.warn(`[openrouter] ${options.model} failed with HTTP ${res.status}${body ? `: ${body}` : ''}`)+ return null+ }++ const payload = await res.json() as { choices?: Array<{ message?: { content?: unknown } }> }+ const content = payload.choices?.[0]?.message?.content+ const text = typeof content === 'string' ? content.trim() : ''+ return text || null+ } catch (err) {+ if (options.signal?.aborted) throw err // the caller cancelled: don't paper over it+ console.warn(`[openrouter] ${options.model} call failed: ${redactKeys(err instanceof Error ? err.message : String(err))}`)+ return null+ } finally {+ clearTimeout(timer)+ options.signal?.removeEventListener('abort', onCallerAbort)+ }+}diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.tsindex 93bd4c2e9..f8e8b9597 100644--- a/cli/src/lib/registry.ts+++ b/cli/src/lib/registry.ts@@ -54,6 +54,16 @@ export interface RegisteredSession {/** When the CURRENT sessionId was bound (vs `registeredAt`, which is when the agent appeared). */boundAt: number | nullengine: AgentEngine+ /**+ * Set when the engine process is pointed at an OpenRouter endpoint (`ori claude`, `ori codex`, …).+ *+ * It is NOT a second engine: the engine stays `claude`/`codex`/… and every badge, icon and wire field+ * keeps saying so. It only records HOW the pane's requests are billed, which decides two things — the+ * runtime profile becomes display-only, and the daemon's recap/route calls go direct to OpenRouter+ * instead of spawning a vendor CLI that has no credential. Re-derived from the live process on every+ * discovery, so a pane restarted without the wrapper drops it on the next scan.+ */+ gateway?: 'ori' | null/** Legacy launcher-owned snapshots may still contain this field. New records never write it. */launcherId?: stringtranscriptPath: string | null@@ -321,6 +331,7 @@ class Registry {tmuxPane: stringcwd?: string | nullprocessIdentity: ProcessIdentity+ gateway?: 'ori' | null}):{ entry: RegisteredSession; isNew: boolean; evicted: string | null } | null {const { engine, tmuxPane, processIdentity } = input@@ -336,6 +347,9 @@ class Registry {existing.tmuxPane = tmuxPaneexisting.cwd = input.cwd ?? existing.cwdexisting.processIdentity = processIdentity+ // Only a successful read speaks: an undefined probe (ps failed, /proc unreadable) keeps whatever+ // the last good one said rather than silently downgrading a gateway agent to a vendor one.+ if (input.gateway !== undefined) existing.gateway = input.gatewayexisting.updatedAt = Date.now()this.save()return { entry: existing, isNew: false, evicted: null }@@ -352,6 +366,7 @@ class Registry {sessionId: '',boundAt: null,engine,+ gateway: input.gateway ?? null,transcriptPath: null,projectDir: basename(input.cwd ?? '') || agentId,cwd: input.cwd ?? null,@@ -518,10 +533,13 @@ class Registry {return this.bySession(sessionId)}- updateProcessIdentity(sessionId: string, processIdentity: ProcessIdentity): boolean {+ updateProcessIdentity(sessionId: string, processIdentity: ProcessIdentity, gateway?: 'ori' | null): boolean {const session = this.resolve(sessionId)if (!session || !validProcessIdentity(processIdentity)) return falsesession.processIdentity = processIdentity+ // A record written before gateways existed, or by a pass whose probe failed, learns it here — the+ // env cannot change under a running process, so a successful read is always the truth for this pid.+ if (gateway !== undefined) session.gateway = gatewaysession.updatedAt = Date.now()this.save()return truediff --git a/cli/src/lib/runtimeProfile.spec.ts b/cli/src/lib/runtimeProfile.spec.tsindex 6fb11bd79..a37cc412b 100644--- a/cli/src/lib/runtimeProfile.spec.ts+++ b/cli/src/lib/runtimeProfile.spec.ts@@ -99,6 +99,33 @@ describe('RuntimeProfileManager', () => {}})+ it('is display-only through an OpenRouter gateway, but still names the model it runs', async () => {+ // `ori claude` runs the same CLI with gateway model discovery, so its picker holds the user's+ // OpenRouter catalog, not the native aliases this controller types. Both gates must hold — an empty+ // catalogue AND a refusal to control — or a stale profile id from an older client drives the pane.+ const manager = new RuntimeProfileManager()+ for (const engine of ['claude', 'codex'] as const) {+ const value = { ...session(engine), gateway: 'ori' as const }+ expect(supportsNativeRuntimeControl(value)).toBe(false)+ await expect(manager.modelsForSession(value)).resolves.toEqual([])+ }++ // Displaying it is the whole point of the flag being separate from `engine`: the chip still works.+ const value = { ...session('claude'), gateway: 'ori' as const }+ manager.hydrate(value, [])+ manager.ingest(value, JSON.stringify({ type: 'assistant', message: { model: 'anthropic/claude-sonnet-4.6' } }))+ expect(parseRuntimeProfile(manager.selectedModel(value))).toMatchObject({+ engine: 'claude', // NOT a new engine — the badge stays Claude Code+ model: 'anthropic/claude-sonnet-4.6', // the OpenRouter id, percent-encoded in the profile+ effort: 'auto',+ })++ // The same session without the flag keeps the native catalogue and native control.+ const native = session('claude')+ expect(supportsNativeRuntimeControl(native)).toBe(true)+ await expect(manager.modelsForSession(native)).resolves.not.toEqual([])+ })+it('supports both captured Codex picker generations', () => {const value = session('codex')expect(supportsNativeRuntimeControl(value)).toBe(true)diff --git a/cli/src/lib/runtimeProfile.ts b/cli/src/lib/runtimeProfile.tsindex b44e1c4a7..4f29a7d00 100644--- a/cli/src/lib/runtimeProfile.ts+++ b/cli/src/lib/runtimeProfile.ts@@ -229,6 +229,11 @@ function versionAtLeast(value: string | null, wanted: [number, number, number]):}export function supportsNativeRuntimeControl(session: RegisteredSession): boolean {+ // A gateway agent (`ori claude`, `ori codex`) is DISPLAY-ONLY (owner, 2026-08-17). Its CLI runs with+ // gateway model discovery, so the picker holds the user's OpenRouter catalog rather than the native+ // aliases this controller knows how to type — and a `/model opus` typed into that pane would be a+ // guess. The chip still names what it is running; nothing offers to change it.+ if (session.gateway) return false// Switching is Claude and Codex only (owner, 2026-07-31); everything else is view-only, so it never gets// here with anything to apply. This is the second gate rather than the only one — modelsForSession// already returns an empty catalogue for those engines — because a stale profile id from an older device@@ -1000,6 +1005,9 @@ export class RuntimeProfileManager {* because the catalogues they fetch are what the ingest paths resolve pane footers against.*/async modelsForSession(session: RegisteredSession): Promise<RuntimeModelOption[]> {+ // Display-only through a gateway: the empty catalogue IS the mechanism (see the note above), so web+ // renders a static chip and the device picker closes instead of offering a list we cannot enumerate.+ if (session.gateway) return []if (session.engine === 'codex') return this.codexModels(session)if (session.engine === 'claude') return this.claudeModels(session)return []diff --git a/cli/src/lib/summarize.spec.ts b/cli/src/lib/summarize.spec.tsindex 3a99833e5..9df327911 100644--- a/cli/src/lib/summarize.spec.ts+++ b/cli/src/lib/summarize.spec.ts@@ -8,6 +8,8 @@ const mocks = vi.hoisted(() => ({runGrok: vi.fn(),cleanupCursor: vi.fn(),setCounts: vi.fn(),+ resolveKey: vi.fn(),+ complete: vi.fn(),}))vi.mock('../config/env.js', () => ({@@ -19,9 +21,15 @@ vi.mock('../config/env.js', () => ({CURSOR_SUMMARY_MODEL: 'auto',GROK_SUMMARY_MODEL: 'grok-4.5',SUMMARY_EFFORT: 'low',+ ORI_SUMMARY_MODEL: 'deepseek/deepseek-v4-flash',},}))+vi.mock('./openrouter.js', () => ({+ resolveOpenRouterKey: mocks.resolveKey,+ openRouterComplete: mocks.complete,+}))+vi.mock('./oneshot.js', () => ({cleanupCursorOneShotSession: mocks.cleanupCursor,configureOneShotPool: mocks.configure,@@ -44,6 +52,55 @@ beforeEach(() => {mocks.cleanupCursor.mockReset()mocks.cleanupCursor.mockResolvedValue(undefined)mocks.setCounts.mockReset()+ mocks.resolveKey.mockReset()+ mocks.complete.mockReset()+})++describe('gateway recap', () => {+ const gateway = { kind: 'ori' as const, apiKey: 'sk-or-v1-process' }++ it('calls OpenRouter directly and never spawns a vendor one-shot', async () => {+ // The point of the whole path: an `ori claude` user may hold no Anthropic credential at all, so the+ // engine one-shot would spawn a CLI that cannot authenticate and the recap would never arrive.+ mocks.resolveKey.mockResolvedValue('sk-or-v1-process')+ mocks.complete.mockResolvedValue('Recap works through the gateway.\n\nThe turn recapped without a vendor login.')++ await expect(summarizeTurnText(+ 'Wired the gateway recap path.',+ undefined,+ 'Does the gateway recap work?',+ 'claude',+ gateway,+ )).resolves.toBe('Recap works through the gateway.\n\nThe turn recapped without a vendor login.')++ expect(mocks.complete).toHaveBeenCalledTimes(1)+ expect(mocks.complete.mock.calls[0][0]).toMatchObject({+ model: 'deepseek/deepseek-v4-flash',+ apiKey: 'sk-or-v1-process',+ })+ expect(mocks.runClaude).not.toHaveBeenCalled()+ })++ it('falls back to the engine one-shot when no key resolves', async () => {+ mocks.resolveKey.mockResolvedValue(null)+ mocks.runClaude.mockResolvedValue({ text: 'Engine recap.\n\nThe engine path still runs.', sessionId: null })++ await expect(summarizeTurnText('Did the work.', undefined, 'Status?', 'claude', gateway))+ .resolves.toBe('Engine recap.\n\nThe engine path still runs.')++ expect(mocks.complete).not.toHaveBeenCalled()+ expect(mocks.runClaude).toHaveBeenCalledTimes(1)+ expect(mocks.runClaude.mock.calls[0][0]).toMatchObject({ model: 'sonnet' })+ })++ it('leaves a normal vendor agent on its own engine one-shot', async () => {+ mocks.runClaude.mockResolvedValue({ text: 'Engine recap.\n\nNothing changed here.', sessionId: null })++ await expect(summarizeTurnText('Did the work.', undefined, 'Status?', 'claude')).resolves.toBeTruthy()++ expect(mocks.resolveKey).not.toHaveBeenCalled()+ expect(mocks.complete).not.toHaveBeenCalled()+ })})describe('Cursor recap', () => {diff --git a/cli/src/lib/summarize.ts b/cli/src/lib/summarize.tsindex 89beae3d3..2a12adbda 100644--- a/cli/src/lib/summarize.ts+++ b/cli/src/lib/summarize.ts@@ -12,6 +12,8 @@ import { homedir } from 'os'import { join } from 'path'import { env } from '../config/env.js'import type { AgentEngine } from '../engines/types.js'+import type { GatewayRuntime } from './gatewayRuntime.js'+import { openRouterComplete, resolveOpenRouterKey } from './openrouter.js'import {cleanupCursorOneShotSession,configureOneShotPool,@@ -30,6 +32,7 @@ import {setOneShotPoolActiveCounts,setOneShotPoolDeviceConnected,shutdownOneShotPool,+ type OneShotOptions,} from './oneshot.js'const SUMMARY_MAX_WORDS = 120@@ -215,6 +218,7 @@ export async function summarizeTurnText(signal?: AbortSignal,userMessage?: string,engine: AgentEngine = 'claude',+ gateway?: GatewayRuntime,): Promise<string | null> {let last = (text || '').trim()if (!last) return null@@ -289,7 +293,15 @@ export async function summarizeTurnText(const scratch = ensureSummaryScratch()const t0 = Date.now()- const model = engine === 'claude'+ // A gateway agent (`ori claude`, `ori codex`) bills an OpenRouter account, and its user may hold no+ // vendor credential at all — the engine one-shot would spawn a CLI that cannot authenticate and the+ // recap would silently never arrive. Same prompt, same output contract, one HTTPS call instead.+ const gatewayKey = gateway?.kind === 'ori' && env.ORI_SUMMARY_MODEL+ ? await resolveOpenRouterKey(gateway)+ : null+ const model = gatewayKey+ ? env.ORI_SUMMARY_MODEL+ : engine === 'claude'? env.SUMMARY_MODEL: engine === 'codex'? env.CODEX_SUMMARY_MODEL@@ -314,8 +326,12 @@ export async function summarizeTurnText(? env.GROK_SUMMARY_MODEL: env.OPENCODE_SUMMARY_MODELconst effort = engine === 'cursor' ? 'model-defined' : env.SUMMARY_EFFORT- console.log(`[recap] one-shot ${engine} · model=${model} · effort=${effort} · inputChars=${last.length}${ask ? ' · withAsk' : ''}`)- const run = engine === 'claude'+ console.log(+ gatewayKey+ ? `[recap] openrouter ${engine} · model=${model} · inputChars=${last.length}${ask ? ' · withAsk' : ''}`+ : `[recap] one-shot ${engine} · model=${model} · effort=${effort} · inputChars=${last.length}${ask ? ' · withAsk' : ''}`,+ )+ const runEngine = engine === 'claude'? runClaudeOneShot: engine === 'codex'? runCodexOneShot@@ -338,8 +354,17 @@ export async function summarizeTurnText(: engine === 'grok'? runGrokOneShot: runOpencodeOneShot+ // One shape for both paths so the language-drift retry and the two-part capping below stay single-source.+ const run: (options: OneShotOptions) => Promise<{ text: string; sessionId: string | null }> = gatewayKey+ ? async (options) => ({+ text: await openRouterComplete({+ prompt: options.prompt, model, apiKey: gatewayKey, signal: options.signal, maxTokens: 1_024,+ }) ?? '',+ sessionId: null,+ })+ : runEnginelet r = await run({ prompt, model, effort: env.SUMMARY_EFFORT, cwd: scratch, signal })- console.log(`[recap] one-shot returned in ${Date.now() - t0}ms · rawLen=${(r.text || '').length}`)+ console.log(`[recap] ${gatewayKey ? 'openrouter' : 'one-shot'} returned in ${Date.now() - t0}ms · rawLen=${(r.text || '').length}`)await cleanupRecapSession(engine, scratch, r.sessionId)// Language check without naming a language: compare the writing system of the output against the inputs// it was supposed to mirror. Works in both directions and for any language pair.diff --git a/cli/src/lib/tmux.spec.ts b/cli/src/lib/tmux.spec.tsindex be7767ec0..3cb03c9eb 100644--- a/cli/src/lib/tmux.spec.ts+++ b/cli/src/lib/tmux.spec.ts@@ -28,6 +28,21 @@ describe('tmux process primitives', () => {expect(engineProcessMatchScore({ executable: '/Users/demo/.grok/bin/grok', args: 'grok' }, 'grok')).toBe(3)})+ it('reads an engine through the ori launcher, before and after its exec', () => {+ // `ori claude` computes an environment and then execve's the vendor binary away, so for all but the+ // first ~100ms the pane row IS `claude` — that case must keep scoring exactly as a bare launch does.+ expect(engineProcessMatchScore({ executable: 'claude', args: '/Users/demo/.local/bin/claude --resume x' }, 'claude')).toBe(3)+ // The pre-exec window (and any future ori that spawns instead of exec'ing) resolves through the flags.+ expect(engineProcessMatchScore({ executable: 'ori', args: 'ori claude' }, 'claude')).toBe(3)+ expect(engineProcessMatchScore({ executable: 'ori', args: '/Users/demo/.local/bin/ori claude --model anthropic/claude-sonnet-4.6 -p hi' }, 'claude')).toBe(3)+ expect(engineProcessMatchScore({ executable: 'ori', args: 'ori --log-level debug codex --full-auto' }, 'codex')).toBe(3)+ expect(engineProcessMatchScore({ executable: 'ori', args: 'ori opencode' }, 'opencode')).toBe(3)+ // Wrapping does not make it a different engine, and ori's own subcommands are not engines.+ expect(engineProcessMatchScore({ executable: 'ori', args: 'ori claude' }, 'codex')).toBe(0)+ expect(engineProcessMatchScore({ executable: 'ori', args: 'ori eval' }, 'claude')).toBe(0)+ expect(engineProcessMatchScore({ executable: 'ori', args: 'ori login' }, 'claude')).toBe(0)+ })+it('assigns the colliding agent basename only from executable ownership', () => {const cursor = ownership(['cursor-file'], ['grok-file'])const grok = ownership(['cursor-file'], ['grok-file'])diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.tsindex dff2f52a9..bbff14382 100644--- a/cli/src/lib/tmux.ts+++ b/cli/src/lib/tmux.ts@@ -73,6 +73,18 @@ function processEntrypoint(args: string): string {while (index < tokens.length && (tokens[index].startsWith('-') || /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[index]))) index++command = basename(tokens[index] ?? '').toLowerCase()}+ // `ori <engine>` (OpenRouter's launcher) computes an environment and then `execve`s the vendor binary+ // away, so a pane running it looks exactly like a bare `claude`/`codex` for all but the ~100ms before+ // the exec. Reading through the wrapper covers that window — and keeps the pane resolvable if a future+ // ori ever spawns a child instead. Its own flags are skipped; everything after them is the engine.+ if (command === 'ori') {+ index+++ const oriFlagsWithValue = new Set(['--model', '--log-level', '--completions'])+ while (index < tokens.length && tokens[index].startsWith('-')) {+ index += oriFlagsWithValue.has(tokens[index]) && index + 1 < tokens.length ? 2 : 1+ }+ command = basename(tokens[index] ?? '').toLowerCase()+ }if (!/^(?:node|nodejs|bun|deno|python(?:\d+(?:\.\d+)*)?|bash|zsh|sh)$/.test(command)) return tokens[index] ?? ''index++diff --git a/cli/src/lib/tmuxAgentDiscovery.ts b/cli/src/lib/tmuxAgentDiscovery.tsindex 6aa89efcd..5c00e2534 100644--- a/cli/src/lib/tmuxAgentDiscovery.ts+++ b/cli/src/lib/tmuxAgentDiscovery.ts@@ -14,6 +14,7 @@ import {type AgentCommandOwnershipSnapshot,} from './engineBin.js'import type { AgentEngine } from '../engines/types.js'+import { probeGatewayRuntime } from './gatewayRuntime.js'import type { ProcessIdentity, RegisteredSession } from './registry.js'import {ambiguousAgentProcess,@@ -38,6 +39,11 @@ export interface DiscoveredTmuxAgent {/** The stable engine process argv, used only to bind an explicit `--resume <id>` after discovery. */args: stringresumeSessionId: string | null+ /**+ * 'ori' when this process is pointed at OpenRouter (`ori claude` and friends). undefined = the probe+ * could not read the process; the registry then keeps whatever it already knew.+ */+ gateway?: 'ori' | null}export type TmuxAgentProbe =@@ -195,13 +201,20 @@ export async function probeTmuxAgents(if (!ps.ok) return { ok: false, error: `process table failed: ${ps.error}` }const parsed = ps.stdout.split('\n').map(parseProcessRow).filter((row): row is ProcessRow => row !== null)const rows = await enrichProcessRows(parsed)- return discoverTmuxAgentsFromSnapshot(+ const probe = discoverTmuxAgentsFromSnapshot(parsePanes(tmux.stdout),rows,daemonPid,agentCommandOwnershipSnapshot(),hints,)+ // Which endpoint each agent is pointed at. Cached per live process, so this is one read per agent for+ // its whole life, not one per pass — and a failed read leaves `gateway` undefined rather than false.+ await Promise.all(probe.agents.map(async (agent) => {+ const runtime = await probeGatewayRuntime(agent.processIdentity, agent.args)+ agent.gateway = runtime.kind+ }))+ return probe}export function sameRuntime(diff --git a/cli/src/lib/voiceRouter.spec.ts b/cli/src/lib/voiceRouter.spec.tsindex d35298055..d50e6b4cf 100644--- a/cli/src/lib/voiceRouter.spec.ts+++ b/cli/src/lib/voiceRouter.spec.ts@@ -15,6 +15,14 @@ vi.mock('./oneshot.js', () => ({shutdownRouterOneShot: vi.fn(),}))+// The gateway path: a machine whose agents run through OpenRouter classifies with one direct call.+const resolveOpenRouterKey = vi.fn()+const openRouterComplete = vi.fn()+vi.mock('./openrouter.js', () => ({+ resolveOpenRouterKey: (...args: unknown[]) => resolveOpenRouterKey(...args),+ openRouterComplete: (...args: unknown[]) => openRouterComplete(...args),+}))+// Import AFTER the mock is registered.const { buildRouterPrompt, parseRouteOutput, routeVoiceTask, pickAgentHeuristic, chooseRouterEngine, routerModelFor } = await import('./voiceRouter.js')type RouterAgent = import('./voiceRouter.js').RouterAgent@@ -188,6 +196,50 @@ describe('chooseRouterEngine', () => {})})+describe('routeVoiceTask through an OpenRouter gateway', () => {+ const gatewayAgents: RouterAgent[] = [+ { id: '1', name: 'Frontend', engine: 'claude', gateway: 'ori' },+ { id: '2', name: 'Auth', engine: 'claude', gateway: 'ori' },+ ]++ beforeEach(() => {+ runRouterOneShot.mockReset(); runGrokOneShot.mockReset()+ routerImpl = async () => ({ text: '', sessionId: null })+ resolveOpenRouterKey.mockReset(); openRouterComplete.mockReset()+ })++ it('classifies with one direct call instead of warming a vendor one-shot', async () => {+ resolveOpenRouterKey.mockResolvedValue('sk-or-v1-test')+ openRouterComplete.mockResolvedValue('{"agentId":"2","confidence":0.9,"reason":"auth","needNewAgent":false}')++ const d = await routeVoiceTask('login broken', gatewayAgents)++ expect(d.agentId).toBe('2')+ expect(openRouterComplete).toHaveBeenCalledOnce()+ expect(runRouterOneShot).not.toHaveBeenCalled()+ })++ it('falls through to the engine one-shot when the gateway cannot answer', async () => {+ resolveOpenRouterKey.mockResolvedValue('sk-or-v1-test')+ openRouterComplete.mockResolvedValue(null)+ routerImpl = async () => ({ text: '{"agentId":"1","confidence":0.7,"reason":"ui"}', sessionId: null })++ const d = await routeVoiceTask('dark mode', gatewayAgents)++ expect(d.agentId).toBe('1')+ expect(runRouterOneShot).toHaveBeenCalledOnce()+ })++ it('leaves a machine with no gateway agent entirely alone', async () => {+ routerImpl = async () => ({ text: '{"agentId":"2","confidence":0.9,"reason":"auth"}', sessionId: null })++ await routeVoiceTask('login broken', AGENTS)++ expect(resolveOpenRouterKey).not.toHaveBeenCalled()+ expect(runRouterOneShot).toHaveBeenCalledOnce()+ })+})+describe('routeVoiceTask engine selection', () => {beforeEach(() => { runRouterOneShot.mockReset(); runGrokOneShot.mockReset(); routerImpl = async () => ({ text: '', sessionId: null }) })diff --git a/cli/src/lib/voiceRouter.ts b/cli/src/lib/voiceRouter.tsindex c40e47bba..1cd0d978c 100644--- a/cli/src/lib/voiceRouter.ts+++ b/cli/src/lib/voiceRouter.ts@@ -7,6 +7,7 @@ import { existsSync, mkdirSync } from 'fs'import { join } from 'path'import { env } from '../config/env.js'import { runGrokOneShot, runRouterOneShot, configureRouterOneShot, setRouterOneShotDeviceConnected, shutdownRouterOneShot } from './oneshot.js'+import { openRouterComplete, resolveOpenRouterKey } from './openrouter.js'export interface RouterAgent {id: string@@ -14,6 +15,8 @@ export interface RouterAgent {/** The CLI this agent runs on. It is what decides which engine classifies the route — see* chooseRouterEngine — so the decision is made from the very list being routed over. */engine?: string+ /** 'ori' when this agent's CLI is pointed at OpenRouter — see the direct-call path in routeVoiceTask. */+ gateway?: 'ori' | null/** Recaps of the agent's last few completed turns (up to 3), joined — a broader, less skewed picture* of what it's working on than a single turn. */recentSummary?: string@@ -222,6 +225,23 @@ export async function routeVoiceTask(transcript: string, agents: RouterAgent[],return logDecision('only-agent', agents, { agentId: agents[0].id, confidence: 1, reason: 'only agent in machine', needNewAgent: false })}+ const prompt = buildRouterPrompt(transcript, agents)++ // A machine running gateway agents (`ori claude`, …) classifies with ONE direct OpenRouter call: the+ // vendor one-shot it would otherwise warm has no credential to spend, and this is a 20-word+ // classification either way. Anything short of a usable answer falls through to the engine path below.+ if (env.ORI_VOICE_ROUTE_MODEL && agents.some((agent) => agent.gateway === 'ori')) {+ const apiKey = await resolveOpenRouterKey()+ if (apiKey) {+ console.log(`[voice-route] classifying with openrouter · model=${env.ORI_VOICE_ROUTE_MODEL}`)+ const text = await openRouterComplete({+ prompt, model: env.ORI_VOICE_ROUTE_MODEL, apiKey, signal, timeoutMs: 12_000, maxTokens: 256,+ })+ if (text) return logDecision('openrouter', agents, parseRouteOutput(text, agents))+ console.log('[voice-route] openrouter classification unavailable → engine one-shot')+ }+ }+// Decide from the agents in hand, falling back to whatever the registry sync last warmed (a caller that// does not label its agents). No usable engine → the heuristic, without burning a doomed spawn on every// voice.@@ -231,7 +251,6 @@ export async function routeVoiceTask(transcript: string, agents: RouterAgent[],return logDecision('heuristic (no engine)', agents, pickAgentHeuristic(transcript, agents))}const model = routerModelFor(engine)- const prompt = buildRouterPrompt(transcript, agents)ensureRouterConfigured(engine) // so runRouterOneShot matches the pool config and uses the warm worker// BEFORE the call: on a timeout this is the only record of which CLI was asked.console.log(`[voice-route] classifying with ${engine} · model=${model || '(engine default)'}`)