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.

cli: the recap is the answer's excerpt; the model that rewrote it is gone (#714)

Dee2de7b2a03d2e
diff --git a/cli/README.md b/cli/README.md
index 930b51128..24c99ad66 100644
--- a/cli/README.md
+++ b/cli/README.md
@@ -287,9 +287,7 @@ report all fields.
| `ADAPTER_CLI_DIR` | `~/.harness/cli` | install dir holding the `cli.js`/`notify.mjs` the updater swaps |
| `LOG_FRAMES` | `false` | one log line per backend frame — type, audience and opaque ids, never a payload body. Every content-bearing frame is encrypted before it reaches the socket, so this is the only way to see what the daemon actually sent |
| `HARNESS_HOOK_DEADLINE_MS` | `4500` | wall-clock budget a hook gives itself before abandoning optional work. Raise it on a slow or heavily loaded machine, where the budget is spent on load rather than on the hook and the offline registry fallback silently does nothing. Clamped, never below the default |
-| `SUMMARY_MODE` | `local` | who writes the recap HEADLINE. `local`: no model — the answer's first sentence is excerpted, instantly; the dial shows what the terminal shows. `model`: a one-shot of the session's own engine, fed the previous recap, the user's ask and the answer — reads better across turns, at ~9s of latency per turn. The `text` under the headline is the answer's own excerpt in both modes |
-| `ORI_SUMMARY_MODEL` | `deepseek/deepseek-v4-flash` | recap model for agents routed through an OpenRouter gateway (`ori claude`), which have no vendor credential to spend |
-| `ORI_VOICE_ROUTE_MODEL` | `deepseek/deepseek-v4-flash` | same, for the voice router's classification |
+| `ORI_VOICE_ROUTE_MODEL` | `deepseek/deepseek-v4-flash` | the voice router's classification model for agents routed through an OpenRouter gateway (`ori claude`), which have no vendor credential to spend |
| `ORI_CREDENTIALS_PATH` | `~/.ori/credentials.json` | where `ori login` stores its key; read only when neither the daemon env nor the agent's own process supplies one |
## Device (hardware commander)
@@ -302,22 +300,12 @@ turns arrive as an injected `message` → `sendToTmux`. A device that joins **mi
a client-count signal (`__clients`) — the adapter re-emits the open turn's live state on join (no
periodic heartbeat).
-The per-turn **summary/recap** matches the hosted runtime: on turn end, *only while a device is
-connected*, the adapter runs a disposable one-shot from the session's own CLI engine
-(`SUMMARY_MODEL`, `CODEX_SUMMARY_MODEL`, or `CURSOR_SUMMARY_MODEL`) → a one-line `recap ≤15 words`,
-shows a `Summarizing…` indicator while it runs, persists `recap\n\ntext` per session
-(`${ADAPTER_DATA_DIR}/summaries.json`), and returns it on `project_recent` at device boot. A newer
-turn aborts a stale recap. The `text` under the headline is NOT model-written: it is the answer
-itself, flattened to one line and clipped to 250 characters (`deriveTurnBody`) — the dial shows only
-the headline, the device protocol defines `text` as an excerpt, and a paraphrase nobody reads cost
-output tokens on every turn.
-
-The one-shot is `recap = llm(instruct, previous recap, the user's ask, the answer)`. The previous
-recap is the session's last stored summary, quoted as *continuity only* — it lets a turn whose
-answer is "done, same change in the other file" recap as what was done instead of a fragment — and
-the prompt forbids repeating it or reporting it as this turn's news. `SUMMARY_MODE=local` drops the
-model: the answer's first prose sentence becomes the headline in the same tick (no `Summarizing…`),
-which is the right trade when the dial sits next to a window already showing the full text.
+The per-turn **recap** is cut from the answer the moment a turn ends, with no model in the loop: the
+answer's first prose sentence is the headline, and the `text` under it is the answer itself,
+flattened to one line and clipped to 250 characters (`deriveTurnBody`). It is persisted as
+`recap\n\ntext` per session (`${ADAPTER_DATA_DIR}/summaries.json`) and returned on
+`project_recent` at device boot. The window, the phone and the dial each show it beside the full
+answer, so the model rewrite the daemon once offered (about 9 s of every turn) is gone.
## Pair an Autonomous device directly
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 329bf2804..8860078df 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -194,13 +194,7 @@ import { teamWriteHold } from './teams/preflight.js'
import { TeamError } from './teams/model.js'
import { CommanderMirror, SUBAGENT_IDLE_MS, type CommanderMirrorOpts } from './lib/commander.js'
import { AgentNotifications } from './lib/agentNotifications.js'
-import {
- setSummaryPoolDeviceConnected,
- shutdownSummaryPool,
- deriveTurnSummary,
- summarizeTurnText,
- syncSummaryPoolSessions,
-} from './lib/summarize.js'
+import { deriveTurnSummary } from './lib/deviceRecap.js'
import type { CableAgent } from './cable/cableSession.js'
import { routeVoiceTask, setVoiceRouterDeviceConnected, setVoiceRouterSessions, shutdownVoiceRouter, type RouterAgent } from './lib/voiceRouter.js'
import { tailFile } from './lib/sessions.js'
@@ -1881,12 +1875,10 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// Persisted records are not trusted blindly. The process reconciler below adopts a matching live
// runtime, replaces it immediately when PID/start-marker changed, and requires two successful misses
// before removing it. Probe errors leave the registry untouched.
- // Recap pool AND voice router share one sync: both need to know which engines the machine actually
- // runs, and a router warmed for an engine no agent uses is exactly the bug this rides along to fix.
+ // The voice router needs to know which engines the machine actually runs: a router warmed for an
+ // engine no agent uses is a worker nobody asked for.
const syncRecapPool = (): void => {
- const sessions = registry.active()
- syncSummaryPoolSessions(sessions)
- setVoiceRouterSessions(sessions)
+ setVoiceRouterSessions(registry.active())
}
syncRecapPool()
const runtimeProfiles = new RuntimeProfileManager()
@@ -2932,27 +2924,13 @@ async function runForeground(session: AuthSession | null): Promise<void> {
})
- // SUMMARY_MODE picks the recap writer.
- // model — recap = llm(instruct, previous recap, the user's ask, the answer): a disposable
- // one-shot of the session's own engine. The previous recap is what lets "same fix, other file"
- // recap as what was done rather than as a fragment. Costs the one-shot's latency on every turn.
- // local (default) — NO MODEL IN THE LOOP. The dial is cabled to the Mac whose window already shows this text
- // in full, so the recap is a glance and the detail is one turn of the head away; the one-shot cost
- // ~9s of the user's turn to say something they were already looking at. Instant, but every recap
- // stands alone.
- const summarizer: Pick<CommanderMirrorOpts, 'summarize' | 'summarizeIsLocal'> = env.SUMMARY_MODE === 'local'
- ? { summarize: async (text) => deriveTurnSummary(text), summarizeIsLocal: true }
- : {
- summarize: async (text, signal, userMessage, sessionId, previousRecap) => {
- 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, previousRecap)
- },
- }
+ // The recap is an excerpt of the answer, cut the moment the turn ends — no model in the loop. The
+ // window, the phone and the dial show it beside the whole answer, so a model's rewrite (which cost
+ // about 9 s of every turn) said again what the screen already showed.
+ const summarizer: Pick<CommanderMirrorOpts, 'summarize' | 'summarizeIsLocal'> = {
+ summarize: async (text) => deriveTurnSummary(text),
+ summarizeIsLocal: true,
+ }
/**
* A turn that belongs to a SUB-AGENT: an Orchestrator specialist, or its Director while specialists
* are still out.
@@ -5296,9 +5274,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {
}, PANE_TITLE_SYNC_MS)
// A device joined mid-turn (count rise or join generation; no adapter heartbeat) → replay live state.
- backend.onCommanderJoin = () => { setSummaryPoolDeviceConnected(deviceIsWatching()); mirror.replayAll(); questionWatcher.reset() } // re-announce an open question
+ backend.onCommanderJoin = () => { mirror.replayAll(); questionWatcher.reset() } // re-announce an open question
backend.onCommanderPresenceChanged = (connected) => {
- setSummaryPoolDeviceConnected(connected || backend.autonomousDeviceConnected())
// Warm the voice-router worker while a device is connected.
setVoiceRouterDeviceConnected(connected)
}
@@ -6456,7 +6433,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {
hookServer.close()
await localSocket?.close()
codexActivity.close()
- shutdownSummaryPool()
shutdownVoiceRouter()
// The new daemon starts its own viewers for the agents it restores; ours must not hold the ports.
await dshViewers.stopAll()
@@ -6564,7 +6540,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {
hookServer.close()
await localSocket?.close()
codexActivity.close()
- shutdownSummaryPool()
shutdownVoiceRouter()
await dshViewers.stopAll()
await dshVerdicts.stop()
@@ -6575,7 +6550,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
}
process.on('SIGINT', () => void shutdown('SIGINT'))
process.on('SIGTERM', () => void shutdown('SIGTERM'))
- process.on('exit', () => { shutdownSummaryPool(); shutdownVoiceRouter() })
+ process.on('exit', () => { shutdownVoiceRouter() })
// A machine revocation or invalid SSO refresh ends this adapter session permanently.
backend.onRevoked = () => {
diff --git a/cli/src/config/env.ts b/cli/src/config/env.ts
index 00d4706cd..6083c68ec 100644
--- a/cli/src/config/env.ts
+++ b/cli/src/config/env.ts
@@ -294,7 +294,7 @@ const envSchema = z.object({
// Path to the `kilo` CLI for Kilo recap one-shots (else `kilo` is resolved from PATH). `@kilocode/cli`
// also installs it as `kilocode`; both are the same file.
KILO_PATH: z.string().optional(),
- // Path to the xAI Grok CLI for interactive sessions and recap one-shots.
+ // Path to the xAI Grok CLI for interactive sessions and voice-router one-shots.
GROK_PATH: z.string().optional(),
// Path to the GitHub Copilot CLI. Two builds answer to `copilot` on a typical machine — a compiled
// binary and the npm loader script — so an override is worth having.
@@ -302,46 +302,6 @@ const envSchema = z.object({
// Path to the Antigravity CLI. Two binaries answer to `agy` on a typical PATH — the CLI itself and
// the Antigravity IDE launcher — so an override is worth having.
AGY_PATH: z.string().optional(),
- // Model for the device turn-recap one-shot.
- SUMMARY_MODEL: z.string().default('sonnet'),
- // Balanced Codex counterpart used only for recap workers; never inherits the interactive CLI model.
- CODEX_SUMMARY_MODEL: z.string().default('gpt-5.5'),
- // Cursor's Auto model keeps recap availability aligned with the user's Cursor account.
- CURSOR_SUMMARY_MODEL: z.string().default('auto'),
- // OpenCode recap model (`provider/model`). Empty → use the user's opencode config default model.
- OPENCODE_SUMMARY_MODEL: z.string().default(''),
- // Kilo recap model (`provider/model` as `kilo models` prints it). Empty → the user's kilo default.
- KILO_SUMMARY_MODEL: z.string().default(''),
- // Grok recap model. Empty → use the user's Grok CLI default model.
- GROK_SUMMARY_MODEL: z.string().default(''),
- // Copilot recap model. Empty -> `auto`, which lets Copilot pick and keeps the user's credit policy.
- COPILOT_SUMMARY_MODEL: z.string().default(''),
- // Antigravity recap model (a slug from `agy models`). Flash at low effort: a recap is a short
- // summarisation of text already in hand, so the cheapest tier in the catalog is the right one.
- AGY_SUMMARY_MODEL: z.string().default('gemini-3.7-flash-low'),
- // Pi recap model (`provider/model` or a model pattern). Empty → use the user's pi config default.
- PI_SUMMARY_MODEL: z.string().default(''),
- // Hermes recap model. Empty → use the user's ~/.hermes/config.yaml default (keeps their provider).
- HERMES_SUMMARY_MODEL: z.string().default(''),
- // Command Code recap model. Empty → use the user's own account default.
- COMMANDCODE_SUMMARY_MODEL: z.string().default(''),
- // Devin recap model. Empty → use the user's own account default (their plan decides what is available).
- DEVIN_SUMMARY_MODEL: z.string().default(''),
- MUSE_SUMMARY_MODEL: z.string().default(''),
- // Amp recap agent mode. Amp exposes no model list — `-m` picks a MODE (low|medium|high|ultra) and the
- // mode picks the model. `medium` on the project owner's call: `low` was the cheaper default but is no
- // more reliable on this path (both modes hit Amp's ~30s network timeout at similar rates, measured),
- // so the better answer wins over the cheaper one.
- AMP_SUMMARY_MODE: z.string().default('medium'),
- // Shared recap reasoning level for Claude and Codex. Cursor effort is part of its model identifier.
- SUMMARY_EFFORT: z.enum(['low', 'medium', 'high']).default('low'),
- // Who writes the device recap's headline. `local` (default since 2026-09-15): no model in the loop —
- // the answer's first sentence is excerpted, instantly; the dial shows what the terminal shows, as it
- // shows it. `model`: a disposable one-shot of the session's own engine, fed the previous recap, the
- // user's ask and the answer — reads better across turns, but measured at ~9s of the user's turn to
- // rephrase "Blue selected." as "Blue selected as the colour choice" (owner: the dial is cabled to the
- // window already showing the answer in full; the recap is a glance, not prose).
- SUMMARY_MODE: z.enum(['model', 'local']).default('local'),
RECAP_WITHOUT_DEVICE: z.string().default('true').transform((v) => v !== 'false'),
// Model for the voice router one-shot classifier (Overview voice → pick the agent). Small/fast by default.
VOICE_ROUTE_MODEL: z.string().default('haiku'),
@@ -358,12 +318,10 @@ const envSchema = z.object({
TERMINAL_P2P_FORCE_RELAY: 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'),
+ // An agent whose CLI is pointed at OpenRouter has no vendor credential to spend, so its voice route
+ // is served by ONE direct chat/completions call instead of a vendor one-shot: spawning a whole coding
+ // agent for it would bill an account the user may not even have. A cheap, fast model by default; ''
+ // disables that call (the VOICE_ROUTE_MODEL convention) and falls back to the engine path.
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.
diff --git a/cli/src/engines/codex/lastTurn.spec.ts b/cli/src/engines/codex/lastTurn.spec.ts
index 86d60b787..fc8f0fe48 100644
--- a/cli/src/engines/codex/lastTurn.spec.ts
+++ b/cli/src/engines/codex/lastTurn.spec.ts
@@ -6,7 +6,7 @@ import { CodexNormalizer, lastCodexTurnText, selectCodexRecapLine } from './norm
import { readLastCodexTurnText } from './lastTurn.js'
import { tailFile } from '../../lib/transcriptTail.js'
import { CommanderMirror, type CommanderFrame } from '../../lib/commander.js'
-import { deriveTurnSummary } from '../../lib/summarize.js'
+import { deriveTurnSummary } from '../../lib/deviceRecap.js'
const event = (payload: unknown) => JSON.stringify({ type: 'event_msg', payload })
const ask = (message: string) => event({ type: 'user_message', message })
diff --git a/cli/src/lib/commander.spec.ts b/cli/src/lib/commander.spec.ts
index 92d9c676d..3d8629c07 100644
--- a/cli/src/lib/commander.spec.ts
+++ b/cli/src/lib/commander.spec.ts
@@ -4,7 +4,7 @@ import { tmpdir } from 'os'
import { join } from 'path'
import { CommanderMirror, type CommanderFrame } from './commander.js'
import type { LiveEvent } from './normalize.js'
-import { BODY_MAX_CHARS, RECAP_MAX_CHARS, deriveTurnSummary } from './summarize.js'
+import { BODY_MAX_CHARS, RECAP_MAX_CHARS, deriveTurnSummary } from './deviceRecap.js'
let dataDir = ''
diff --git a/cli/src/lib/commander.ts b/cli/src/lib/commander.ts
index 52c6129fd..14d9dcfe0 100644
--- a/cli/src/lib/commander.ts
+++ b/cli/src/lib/commander.ts
@@ -14,7 +14,7 @@
* turn_ended (empty text) → {kind:'done'} (clear busy)
*
* Every frame carries top-level `agentId` + `dbSessionId` (= the tmux session id). The recap
- * (`summarizeTurnText`) is injected so it's unit-testable with a stub. Mirrors the hosted runtime's
+ * writer (`summarize`) is injected so it's unit-testable with a stub; the daemon's is an excerpt. Mirrors the hosted runtime's
* device-gated recap (recap.ts / manager.ts triggerTurnRecap / websocket.ts handleBrainSummaryEvent).
*/
@@ -638,8 +638,7 @@ export class CommanderMirror {
// nothing rides the wire to an absent device. This is the fix for the back-fill gap — a device
// that pairs LATER restores real tiles from what was persisted here, instead of blank ones,
// because replayAll() only re-emits stored recaps and never regenerates a past turn.
- // Cost: with SUMMARY_MODE=model this is one engine one-shot per turn, per agent, forever — the very
- // cost the device gate used to avoid. SUMMARY_MODE=local makes it free (no model, same-tick excerpt).
+ // Free: the recap is an excerpt cut the moment the turn ends, with no model in the loop.
const alwaysGenerate = typeof this.opts.alwaysGenerate === 'function' ? this.opts.alwaysGenerate() : this.opts.alwaysGenerate
const localOnly = !device && !this.opts.recapForce && !alwaysGenerate
if (localOnly && !this.opts.notifyWithoutDevice) {
diff --git a/cli/src/lib/companionOneShot.spec.ts b/cli/src/lib/companionOneShot.spec.ts
deleted file mode 100644
index 38334c1e3..000000000
--- a/cli/src/lib/companionOneShot.spec.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { afterEach, describe, expect, it, vi } from 'vitest'
-import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
-import { join } from 'node:path'
-import { tmpdir } from 'node:os'
-import { runCodexOneShot } from './oneshot.js'
-
-let directory: string | null = null
-afterEach(() => { vi.unstubAllEnvs(); if (directory) rmSync(directory, { recursive: true, force: true }) })
-
-describe('the companion Codex review worker', () => {
- it('keeps its selected login, model and effort and cannot be discovered as a terminal agent', async () => {
- directory = mkdtempSync(join(tmpdir(), 'companion-worker-'))
- const binary = join(directory, 'codex-fixture')
- const capture = join(directory, 'launch.json')
- writeFileSync(binary, `#!${process.execPath}
-const fs = require('node:fs');
-let prompt = '';
-process.stdin.on('data', data => prompt += data);
-process.stdin.on('end', () => {
- fs.writeFileSync(${JSON.stringify(capture)}, JSON.stringify({args: process.argv.slice(2), prompt,
- codexHome: process.env.CODEX_HOME, tmux: process.env.TMUX, pane: process.env.TMUX_PANE}));
- fs.writeFileSync(process.argv[process.argv.indexOf('--output-last-message') + 1], '{"lesson":null}');
-});
-`, { mode: 0o700 })
- vi.stubEnv('CODEX_PATH', binary)
- vi.stubEnv('TMUX', 'a-real-terminal')
- vi.stubEnv('TMUX_PANE', '%42')
- const profile = join(directory, 'selected-login')
- expect(await runCodexOneShot({ prompt: 'review only this evidence', cwd: directory,
- codexHome: profile, model: 'selected-model', effort: 'xhigh', timeoutMs: 3000 })).toEqual({ text: '{"lesson":null}', sessionId: null })
- const launch = JSON.parse(readFileSync(capture, 'utf8'))
- expect(launch.codexHome).toBe(profile)
- expect(launch.args).toEqual(expect.arrayContaining(['--model', 'selected-model', 'model_reasoning_effort="xhigh"',
- '--ephemeral', '--sandbox', 'read-only', '--ignore-user-config', '--ignore-rules']))
- expect(launch.tmux).toBeUndefined()
- expect(launch.pane).toBeUndefined()
- expect(launch.prompt.trim()).toBe('review only this evidence')
- })
-})
diff --git a/cli/src/lib/deriveTurnSummary.spec.ts b/cli/src/lib/deriveTurnSummary.spec.ts
index 3ea9eac76..4833ce153 100644
--- a/cli/src/lib/deriveTurnSummary.spec.ts
+++ b/cli/src/lib/deriveTurnSummary.spec.ts
@@ -4,7 +4,7 @@
// `slice(0, 60)` of markdown is a heading and a severed word. What is asserted here is that the cut
// lands on words a person can read.
import { describe, expect, it } from 'vitest'
-import { BODY_MAX_CHARS, RECAP_MAX_CHARS, deriveTurnSummary } from './summarize.js'
+import { BODY_MAX_CHARS, RECAP_MAX_CHARS, deriveTurnSummary } from './deviceRecap.js'
const parts = (text: string) => {
const out = deriveTurnSummary(text)
diff --git a/cli/src/lib/devinTrust.spec.ts b/cli/src/lib/devinTrust.spec.ts
deleted file mode 100644
index 98ef17d19..000000000
--- a/cli/src/lib/devinTrust.spec.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-import { afterEach, describe, expect, it, vi } from 'vitest'
-import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'
-import { tmpdir } from 'os'
-import { join } from 'path'
-
-/**
- * Devin 3000.3.22 refuses to run in a directory it has not been trusted in, and the recap runs in a
- * throwaway scratch dir — so every devin recap failed until the dir is added to its trust list. The list
- * is the USER's file: other entries and any unrelated keys must survive.
- */
-const dirs: string[] = []
-afterEach(() => {
- for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
- vi.resetModules()
-})
-
-async function loadOneShot(devinHome: string) {
- vi.resetModules()
- process.env.DEVIN_HOME = devinHome
- return import('./oneshot.js')
-}
-
-function devinHome(seed?: unknown): { home: string; file: string } {
- const home = mkdtempSync(join(tmpdir(), 'adapter-devin-trust-'))
- dirs.push(home)
- const file = join(home, 'trusted_workspaces.json')
- if (seed !== undefined) writeFileSync(file, JSON.stringify(seed))
- return { home, file }
-}
-
-const read = (file: string): Record<string, unknown> =>
- JSON.parse(readFileSync(file, 'utf-8')) as Record<string, unknown>
-
-describe('devin scratch-dir trust', () => {
- it('appends the scratch dir, keeping the paths and keys already there', async () => {
- const { home, file } = devinHome({ trusted_paths: ['/Users/me/project'], other_setting: true })
- const { runDevinOneShot } = await loadOneShot(home)
-
- // The spawn fails (no `devin` on PATH under this test) — the trust write happens first, by design.
- await runDevinOneShot({ prompt: 'x', cwd: '/tmp/scratch-a', timeoutMs: 200 }).catch(() => {})
-
- expect(read(file)).toEqual({
- trusted_paths: ['/Users/me/project', '/tmp/scratch-a'],
- other_setting: true,
- })
- })
-
- it('is idempotent and starts a list when the file is absent or junk', async () => {
- const { home, file } = devinHome({ trusted_paths: ['/tmp/scratch-a'] })
- const { runDevinOneShot } = await loadOneShot(home)
- await runDevinOneShot({ prompt: 'x', cwd: '/tmp/scratch-a', timeoutMs: 200 }).catch(() => {})
- expect(read(file).trusted_paths).toEqual(['/tmp/scratch-a'])
-
- const fresh = devinHome()
- const one = await loadOneShot(fresh.home)
- await one.runDevinOneShot({ prompt: 'x', cwd: '/tmp/scratch-b', timeoutMs: 200 }).catch(() => {})
- expect(read(fresh.file).trusted_paths).toEqual(['/tmp/scratch-b'])
-
- const junk = devinHome('not an object')
- const two = await loadOneShot(junk.home)
- await two.runDevinOneShot({ prompt: 'x', cwd: '/tmp/scratch-c', timeoutMs: 200 }).catch(() => {})
- expect(read(junk.file).trusted_paths).toEqual(['/tmp/scratch-c'])
- })
-})
diff --git a/cli/src/lib/disposableOneShotPool.ts b/cli/src/lib/disposableOneShotPool.ts
index 4ac6dd25a..77fc00711 100644
--- a/cli/src/lib/disposableOneShotPool.ts
+++ b/cli/src/lib/disposableOneShotPool.ts
@@ -111,7 +111,7 @@ export class DisposableOneShotPool<Options, Result> {
if (this.connected || this.closed) return
this.enabled = false
this.reconcileAll()
- this.log('[recap-pool] device grace expired · unwarmed')
+ this.log('[one-shot-pool] device grace expired · unwarmed')
}, this.graceMs)
}
@@ -121,7 +121,7 @@ export class DisposableOneShotPool<Options, Result> {
for (const candidate of state.ready) {
state.ready.delete(candidate)
if (candidate.isAlive() && !this.expired(candidate)) { worker = candidate; break }
- if (candidate.isAlive()) this.log(`[recap-pool] ${engine} dropped a stale warm worker · age=${Date.now() - candidate.createdAt}ms`)
+ if (candidate.isAlive()) this.log(`[one-shot-pool] ${engine} dropped a stale warm worker · age=${Date.now() - candidate.createdAt}ms`)
candidate.dispose()
this.all.delete(candidate)
}
@@ -133,7 +133,7 @@ export class DisposableOneShotPool<Options, Result> {
const selected = worker ?? await this.createWorker(engine)
const age = Date.now() - selected.createdAt
- this.log(`[recap-pool] ${engine} ${hit ? 'hit' : 'miss'} · workerAge=${age}ms · ready=${state.ready.size}/${state.target}`)
+ this.log(`[one-shot-pool] ${engine} ${hit ? 'hit' : 'miss'} · workerAge=${age}ms · ready=${state.ready.size}/${state.target}`)
try {
return await selected.run(options)
} finally {
@@ -204,7 +204,7 @@ export class DisposableOneShotPool<Options, Result> {
state.ready.delete(worker)
worker.dispose()
this.all.delete(worker)
- this.log(`[recap-pool] ${engine} retired an idle warm worker · age=${Date.now() - worker.createdAt}ms`)
+ this.log(`[one-shot-pool] ${engine} retired an idle warm worker · age=${Date.now() - worker.createdAt}ms`)
}
}
this.reconcileAll()
@@ -227,7 +227,7 @@ export class DisposableOneShotPool<Options, Result> {
const previousTarget = state.target
state.target = this.enabled ? poolTargetForActiveSessions(state.active) : 0
if (state.target !== previousTarget) {
- this.log(`[recap-pool] ${engine} target ${previousTarget}→${state.target} · active=${state.active}`)
+ this.log(`[one-shot-pool] ${engine} target ${previousTarget}→${state.target} · active=${state.active}`)
}
if (state.target === 0 && state.retryTimer) {
@@ -263,7 +263,7 @@ export class DisposableOneShotPool<Options, Result> {
} else {
state.ready.add(worker)
state.failures = 0
- this.log(`[recap-pool] ${engine} warm ready=${state.ready.size}/${state.target}`)
+ this.log(`[one-shot-pool] ${engine} warm ready=${state.ready.size}/${state.target}`)
this.reconcile(engine)
}
})
@@ -276,7 +276,7 @@ export class DisposableOneShotPool<Options, Result> {
// not narrate the same sentence every second until the log is 9MB.
if (delay < RETRY_CAP_MS || state.failures === CAP_ANNOUNCE_AT) {
this.log(
- `[recap-pool] ${engine} warm spawn failed (${state.failures}): ${err instanceof Error ? err.message : String(err)}`
+ `[one-shot-pool] ${engine} warm spawn failed (${state.failures}): ${err instanceof Error ? err.message : String(err)}`
+ (delay >= RETRY_CAP_MS ? ` · backing off to ${RETRY_CAP_MS / 1000}s and staying quiet` : ` · retry in ${delay}ms`),
)
}
@@ -295,7 +295,7 @@ export class DisposableOneShotPool<Options, Result> {
if (this.closed) {
worker.dispose()
this.all.delete(worker)
- throw new Error('recap pool shut down while worker was starting')
+ throw new Error('one-shot pool shut down while worker was starting')
}
return worker
}
diff --git a/cli/src/lib/kiloOneShot.spec.ts b/cli/src/lib/kiloOneShot.spec.ts
index 568106685..003bead76 100644
--- a/cli/src/lib/kiloOneShot.spec.ts
+++ b/cli/src/lib/kiloOneShot.spec.ts
@@ -55,7 +55,7 @@ describe('kilo recap worker containment', () => {
it('passes a model only when one is configured', () => {
expect(kiloOneShotSpawn('kilo/stepfun/step-3.7-flash', {}, SCRATCH).args).toContain('--model')
- // KILO_SUMMARY_MODEL defaults to empty, meaning "use the user's own default" — not "--model ''".
+ // No model given means "use the user's own default" — not "--model ''".
expect(kiloOneShotSpawn('', {}, SCRATCH).args).not.toContain('--model')
})
})
diff --git a/cli/src/lib/oneshot.ts b/cli/src/lib/oneshot.ts
index f774ab171..82fac5279 100644
--- a/cli/src/lib/oneshot.ts
+++ b/cli/src/lib/oneshot.ts
@@ -23,41 +23,6 @@ function claudeBin(): string {
return env.CLAUDE_PATH || 'claude'
}
-/**
- * Add one directory to devin's trusted-workspace list, if it is not already there.
- *
- * Devin 3000.3.22 refuses to run anywhere it has not been trusted interactively:
- *
- * Error: Refusing to run in an untrusted workspace: <dir>
- * Start `devin` interactively in this directory to trust it, or set
- * `respect_workspace_trust: false` in your config to restore the previous behavior.
- *
- * The recap is headless and runs in a scratch dir machine just created, so there is no prompt for anyone
- * to answer and no session that survives it — hence this narrow exception to "harness edits no config":
- * ONE path is appended, the one being created here. The config-wide `respect_workspace_trust: false`
- * would switch the check off for the user's real projects too; every other entry, and the setting
- * itself, is left alone. The interactive vendor CLI does NOT use this — its pane can ask.
- */
-export function trustDevinWorkspace(dir: string, onError?: (message: string) => void): void {
- const file = join(env.DEVIN_HOME, 'trusted_workspaces.json')
- let config: { trusted_paths?: unknown } = {}
- try {
- const parsed: unknown = JSON.parse(readFileSync(file, 'utf-8'))
- if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) config = parsed
- } catch { /* absent or unreadable — a fresh list below is the right answer either way */ }
- const paths = Array.isArray(config.trusted_paths)
- ? config.trusted_paths.filter((p): p is string => typeof p === 'string')
- : []
- if (paths.includes(dir)) return
- try {
- mkdirSync(dirname(file), { recursive: true })
- writeFileSync(file, `${JSON.stringify({ ...config, trusted_paths: [...paths, dir] }, null, 2)}\n`)
- } catch (err) {
- // Never fatal: devin then refuses with its own message, which is clearer than anything said here.
- onError?.(err instanceof Error ? err.message : String(err))
- }
-}
-
function cursorBin(): string {
const bin = cursorRuntimeBin()
if (bin) return bin
@@ -478,7 +443,6 @@ class CursorWorker extends ProcessWorker {
}
}
-
// Isolate session storage while retaining the user's provider config and auth.json location.
const OPENCODE_RECAP_DATA_DIR = join(env.ADAPTER_DATA_DIR, 'opencode-recap')
@@ -891,62 +855,6 @@ class CommandCodeWorker extends ProcessWorker {
}
}
-let config: {
- cwd: string
- claudeModel?: string
- codexModel?: string
- cursorModel?: string
- opencodeModel?: string
- kiloModel?: string
- piModel?: string
- commandcodeModel?: string
- effort?: OneShotOptions['effort']
-} | null = null
-const pool = new DisposableOneShotPool<OneShotOptions, OneShotResult>(async (engine) => {
- if (!config) throw new Error('recap pool is not configured')
- if (engine === 'claude') return new ClaudeWorker(config.cwd, config.claudeModel, config.effort).ready()
- if (engine === 'codex') return new CodexWorker(config.cwd, config.codexModel, config.effort).ready()
- if (engine === 'cursor') return new CursorWorker(config.cwd, config.cursorModel).ready()
- if (engine === 'pi') return new PiWorker(config.cwd, config.piModel).ready()
- if (engine === 'commandcode') return new CommandCodeWorker(config.cwd, config.commandcodeModel).ready()
- if (engine === 'kilo') return new KiloWorker(config.kiloModel).ready()
- return new OpencodeWorker(config.opencodeModel).ready()
-})
-
-export function configureOneShotPool(next: {
- cwd: string
- claudeModel?: string
- codexModel?: string
- cursorModel?: string
- opencodeModel?: string
- kiloModel?: string
- piModel?: string
- commandcodeModel?: string
- effort?: OneShotOptions['effort']
-}): void {
- const changed = config != null && (
- config.cwd !== next.cwd || config.claudeModel !== next.claudeModel ||
- config.codexModel !== next.codexModel || config.cursorModel !== next.cursorModel ||
- config.opencodeModel !== next.opencodeModel || config.kiloModel !== next.kiloModel ||
- config.piModel !== next.piModel ||
- config.commandcodeModel !== next.commandcodeModel || config.effort !== next.effort
- )
- config = next
- if (changed) pool.recycleReady()
-}
-
-export function setOneShotPoolActiveCounts(counts: ActiveEngineCounts): void {
- pool.setActiveCounts(counts)
-}
-
-export function setOneShotPoolDeviceConnected(connected: boolean): void {
- pool.setDeviceConnected(connected)
-}
-
-export function shutdownOneShotPool(): void {
- pool.shutdown()
-}
-
/** Spawn ONE worker for an engine. Shared by the cold path and both warm pools so a pooled worker can
* never be started differently from a direct one. */
function createOneShotWorker(
@@ -971,35 +879,6 @@ function createOneShotWorker(
: new OpencodeWorker(model).ready()
}
-async function runDirect(engine: OneShotEngine, opts: OneShotOptions): Promise<OneShotResult> {
- const worker = await createOneShotWorker(engine, opts.cwd, opts.model, opts.effort, opts.codexHome)
- try { return await worker.run(opts) } finally { worker.dispose() }
-}
-
-export function runClaudeOneShot(opts: OneShotOptions): Promise<OneShotResult> {
- if (opts.signal?.aborted) return Promise.reject(abortError('claude'))
- if (!config || config.cwd !== opts.cwd || config.claudeModel !== opts.model || config.effort !== opts.effort) {
- return runDirect('claude', opts)
- }
- return pool.run('claude', opts)
-}
-
-export function runCodexOneShot(opts: OneShotOptions): Promise<{ text: string; sessionId: null }> {
- if (opts.signal?.aborted) return Promise.reject(abortError('codex'))
- const run = opts.codexHome || !config || config.cwd !== opts.cwd || config.codexModel !== opts.model || config.effort !== opts.effort
- ? runDirect('codex', opts)
- : pool.run('codex', opts)
- return run.then((result) => ({ text: result.text, sessionId: null }))
-}
-
-export function runCursorOneShot(opts: OneShotOptions): Promise<OneShotResult> {
- if (opts.signal?.aborted) return Promise.reject(abortError('cursor'))
- if (!config || config.cwd !== opts.cwd || config.cursorModel !== opts.model) {
- return runDirect('cursor', opts)
- }
- return pool.run('cursor', opts)
-}
-
/** The measured Grok 1.0.0 headless invocation. A fresh GROK_HOME contains every persisted session. */
export function grokOneShotSpawn(
opts: Pick<OneShotOptions, 'prompt' | 'model' | 'effort' | 'cwd'>,
@@ -1090,526 +969,11 @@ export async function runGrokOneShot(opts: OneShotOptions): Promise<OneShotResul
}
}
-/**
- * The measured Antigravity 1.1.14 headless invocation.
- *
- * `-p` takes the prompt on argv, so this cannot be pre-warmed into the worker pool.
- *
- * Two deliberate omissions:
- * - **No scratch data dir.** `ANTIGRAVITY_EXECUTABLE_DATA_DIR` looks like the override and is not one
- * (measured: the run still wrote to the real `~/.gemini/antigravity-cli`), and a scratch `HOME` DOES
- * isolate the store but takes the credentials with it — the re-auth prompt makes it unusable for a
- * background worker. So the run lands in the user's store and is deleted afterwards by id.
- * - **No workspace.** `-p` opens none, and agy refuses every tool without one ("no active workspace"),
- * which is exactly the confinement a recap wants: it cannot read or write the user's files at all.
- */
-export function agyOneShotSpawn(
- opts: Pick<OneShotOptions, 'prompt' | 'model' | 'effort'>,
- parentEnv: NodeJS.ProcessEnv = oneShotParentEnv(),
-): { args: string[]; env: NodeJS.ProcessEnv } {
- const args = [
- '--output-format', 'json',
- // A recap prompt is user text; without this a leading `/` would be expanded as a slash command.
- '--disable-slash-commands',
- ...(opts.model ? ['--model', opts.model] : []),
- ...(opts.effort ? ['--effort', opts.effort] : []),
- '-p', opts.prompt,
- ]
- const childEnv = scrubTerminalContext({ ...parentEnv })
- delete childEnv.MACHINE_ID
- return { args, env: childEnv }
-}
-
-interface AgyOneShotOutput {
- text: string
- conversationId: string
-}
-
-/** agy prints one JSON object: `{conversation_id, status, response, duration_seconds, usage}`. */
-export function agyOutputText(stdout: string): AgyOneShotOutput {
- const raw = stdout.trim()
- // The id is needed for cleanup even when the envelope does not parse, so read it directly too.
- const idMatch = /"conversation_id"\s*:\s*"([0-9a-f-]{16,})"/i.exec(raw)
- const conversationId = idMatch ? idMatch[1] : ''
- for (const candidate of [raw, ...raw.split('\n').reverse()]) {
- if (!candidate) continue
- try {
- const parsed = JSON.parse(candidate) as { response?: unknown; conversation_id?: unknown }
- if (typeof parsed.response === 'string') {
- return { text: parsed.response.trim(), conversationId: typeof parsed.conversation_id === 'string' ? parsed.conversation_id : conversationId }
- }
- } catch { /* try the next complete JSON value */ }
- }
- return { text: '', conversationId }
-}
-
-/**
- * Remove the conversation a recap created.
- *
- * One `-p` run leaves exactly five artifacts, all named by the conversation id (measured):
- * `brain/<id>/`, `conversations/<id>.db` plus its `-wal`/`-shm`, and `presence/<id>.lock`. Deleting by
- * id touches nothing else, so a concurrent interactive agy session is never at risk.
- */
-async function removeAgyConversation(conversationId: string): Promise<void> {
- if (!/^[0-9a-f-]{16,}$/i.test(conversationId)) return
- const targets = [
- join(env.AGY_HOME, 'brain', conversationId),
- join(env.AGY_HOME, 'conversations', `${conversationId}.db`),
- join(env.AGY_HOME, 'conversations', `${conversationId}.db-wal`),
- join(env.AGY_HOME, 'conversations', `${conversationId}.db-shm`),
- join(env.AGY_HOME, 'presence', `${conversationId}.lock`),
- ]
- for (const target of targets) await rm(target, { recursive: true, force: true }).catch(() => {})
-}
-
-export async function runAgyOneShot(opts: OneShotOptions): Promise<OneShotResult> {
- if (opts.signal?.aborted) throw Object.assign(new Error('agy one-shot aborted'), { name: 'AbortError' })
- const { args, env: processEnv } = agyOneShotSpawn(opts)
- const timeoutMs = opts.timeoutMs ?? 60_000
- let created = ''
- try {
- return await new Promise<OneShotResult>((resolve, reject) => {
- const child = spawn(env.AGY_PATH || 'agy', args, {
- cwd: opts.cwd, env: processEnv, detached: true, stdio: ['ignore', 'pipe', 'pipe'],
- })
- let stdout = ''
- let stderr = ''
- let settled = false
- const finish = (fn: () => void): void => {
- if (settled) return
- settled = true
- clearTimeout(timer)
- opts.signal?.removeEventListener('abort', onAbort)
- fn()
- }
- const kill = (): void => killGroup(child)
- const onAbort = (): void => {
- created = created || agyOutputText(stdout).conversationId
- finish(() => reject(Object.assign(new Error('agy one-shot aborted'), { name: 'AbortError' })))
- kill()
- }
- const timer = setTimeout(() => {
- created = created || agyOutputText(stdout).conversationId
- finish(() => reject(new Error(`agy one-shot timed out after ${timeoutMs}ms`)))
- kill()
- }, timeoutMs)
- opts.signal?.addEventListener('abort', onAbort)
- child.stdout?.on('data', (chunk: Buffer) => { stdout += chunk.toString() })
- child.stderr?.on('data', (chunk: Buffer) => { stderr += chunk.toString() })
- child.on('error', (err) => finish(() => reject(err)))
- child.on('close', (code) => {
- const { text, conversationId } = agyOutputText(stdout)
- created = conversationId
- finish(() => {
- if (!text) reject(new Error(`agy one-shot exited ${code}: ${stderr.slice(0, 500)}`))
- else resolve({ text, sessionId: null })
- })
- })
- })
- } finally {
- // An aborted run may still have created the conversation before it died, so this runs either way.
- if (created) await removeAgyConversation(created)
- }
-}
-
-/**
- * The measured Copilot CLI 1.0.80 headless invocation.
- *
- * Three things settled by running it:
- *
- * - **`--no-color` makes stdout the answer and nothing else.** The "Changes / AI Credits / Tokens /
- * Resume" block goes to stderr, so the recap needs no parsing at all — 12 bytes of stdout for a
- * 12-byte reply.
- * - **`--available-tools` with no values leaves the model no tools.** `-p` demands
- * `--allow-all-tools`, which on its own would let a recap run shell commands; pairing the two gives
- * a run that can answer but cannot touch anything.
- * - **`--session-id` accepts a UUID we choose for a NEW session**, so the state this leaves behind is
- * known before it exists and can be removed by name rather than by scraping stderr.
- */
-export function copilotOneShotSpawn(
- opts: Pick<OneShotOptions, 'prompt' | 'model'>,
- sessionId: string,
- parentEnv: NodeJS.ProcessEnv = oneShotParentEnv(),
-): { args: string[]; env: NodeJS.ProcessEnv } {
- const args = [
- '-p', opts.prompt,
- '--allow-all-tools',
- '--available-tools',
- '--no-color',
- '--session-id', sessionId,
- ...(opts.model ? ['--model', opts.model] : []),
- ]
- const childEnv = scrubTerminalContext({ ...parentEnv })
- delete childEnv.MACHINE_ID
- return { args, env: childEnv }
-}
-
-/**
- * Remove the session a recap created.
- *
- * The event stream lives in a directory named by the id, so it goes cleanly. The row Copilot also
- * writes into `session-store.db` is deliberately left alone: that database belongs to the user's
- * running CLI, and deleting from it to tidy a recap is not worth writing into a live vendor store.
- * The cost is an unnamed entry in `copilot --resume`.
- */
-async function removeCopilotSession(sessionId: string): Promise<void> {
- if (!/^[0-9a-f-]{16,}$/i.test(sessionId)) return
- await rm(join(env.COPILOT_HOME, 'session-state', sessionId), { recursive: true, force: true }).catch(() => {})
-}
-
-export async function runCopilotOneShot(opts: OneShotOptions): Promise<OneShotResult> {
- if (opts.signal?.aborted) throw Object.assign(new Error('copilot one-shot aborted'), { name: 'AbortError' })
- const sessionId = randomUUID()
- const { args, env: processEnv } = copilotOneShotSpawn(opts, sessionId)
- const timeoutMs = opts.timeoutMs ?? 60_000
- try {
- return await new Promise<OneShotResult>((resolve, reject) => {
- const child = spawn(env.COPILOT_PATH || 'copilot', args, {
- cwd: opts.cwd, env: processEnv, detached: true, stdio: ['ignore', 'pipe', 'pipe'],
- })
- let stdout = ''
- let stderr = ''
- let settled = false
- const finish = (fn: () => void): void => {
- if (settled) return
- settled = true
- clearTimeout(timer)
- opts.signal?.removeEventListener('abort', onAbort)
- fn()
- }
- const kill = (): void => killGroup(child)
- const onAbort = (): void => {
- finish(() => reject(Object.assign(new Error('copilot one-shot aborted'), { name: 'AbortError' })))
- kill()
- }
- const timer = setTimeout(() => {
- finish(() => reject(new Error(`copilot one-shot timed out after ${timeoutMs}ms`)))
- kill()
- }, timeoutMs)
- opts.signal?.addEventListener('abort', onAbort)
- child.stdout?.on('data', (chunk: Buffer) => { stdout += chunk.toString() })
- child.stderr?.on('data', (chunk: Buffer) => { stderr += chunk.toString() })
- child.on('error', (err) => finish(() => reject(err)))
- child.on('close', (code) => {
- const text = stdout.trim()
- finish(() => {
- if (!text) reject(new Error(`copilot one-shot exited ${code}: ${stderr.slice(0, 500)}`))
- else resolve({ text, sessionId: null })
- })
- })
- })
- } finally {
- await removeCopilotSession(sessionId)
- }
-}
-
-function hermesBin(): string {
- return env.HERMES_PATH || 'hermes'
-}
-
-/**
- * Hermes recap. Unlike every other engine, `hermes chat -q` takes the prompt as **argv, not stdin**, so
- * a worker cannot be pre-warmed — each recap spawns a fresh process (Hermes is deliberately absent from
- * `OneShotEngine`/the warm pool).
- *
- * Notably we do NOT pass `--safe-mode`: it implies `--ignore-user-config`, which would discard the
- * user's model/provider (their whole reason for a working recap). Self-registration is prevented the
- * same way every other worker does it: every terminal location variable is scrubbed. `--source tool`
- * keeps it out of the user's session list.
- */
-function museBin(): string {
- return env.MUSE_PATH || 'muse'
-}
-
-/**
- * One-shot recap through `muse exec`.
- *
- * Prompt goes as ARGV (muse has no stdin mode), so this worker cannot be pre-warmed the way a stdin-fed
- * CLI can — it is deliberately outside the pool. `--json` is not used: the recap wants the answer, not
- * the event stream. Terminal context is stripped so the worker cannot register itself as an agent, and
- * MUSE_NO_AUTO_UPDATE keeps a background self-update from swapping the binary mid-run.
- */
-export function runMuseOneShot(opts: OneShotOptions): Promise<OneShotResult> {
- if (opts.signal?.aborted) return Promise.reject(Object.assign(new Error('muse one-shot aborted'), { name: 'AbortError' }))
- const args = ['exec', opts.prompt, ...(opts.model ? ['--model', opts.model] : [])]
- const processEnv: NodeJS.ProcessEnv = scrubTerminalContext({ ...oneShotParentEnv(), MUSE_NO_AUTO_UPDATE: '1' })
- const timeoutMs = opts.timeoutMs ?? 60_000
-
- return new Promise<OneShotResult>((resolve, reject) => {
- const child = spawn(museBin(), args, {
- cwd: opts.cwd, env: processEnv, detached: true, stdio: ['ignore', 'pipe', 'pipe'],
- })
- let stdout = ''
- let stderr = ''
- let settled = false
- const finish = (fn: () => void): void => {
- if (settled) return
- settled = true
- clearTimeout(timer)
- opts.signal?.removeEventListener('abort', onAbort)
- fn()
- }
- const kill = (): void => {
- if (child.pid == null || child.exitCode != null) return
- try { process.kill(-child.pid, 'SIGKILL') } catch { try { child.kill('SIGKILL') } catch { /* gone */ } }
- }
- const onAbort = (): void => {
- finish(() => reject(Object.assign(new Error('muse one-shot aborted'), { name: 'AbortError' })))
- kill()
- }
- const timer = setTimeout(() => {
- finish(() => reject(new Error(`muse one-shot timed out after ${timeoutMs}ms`)))
- kill()
- }, timeoutMs)
- opts.signal?.addEventListener('abort', onAbort)
-
- child.stdout?.on('data', (chunk: Buffer) => { stdout += chunk.toString() })
- child.stderr?.on('data', (chunk: Buffer) => { stderr += chunk.toString() })
- child.on('error', (err) => finish(() => reject(err)))
- child.on('close', (code) => {
- // muse prints a `muse: workspace root: …` preamble before the answer — drop it.
- const text = stdout.split('\n').filter((line) => !/^\s*muse:\s/.test(line)).join('\n').trim()
- finish(() => {
- if (!text && code !== 0) reject(new Error(`muse one-shot exited ${code}: ${stderr.slice(0, 500)}`))
- else resolve({ text, sessionId: null })
- })
- })
- })
-}
-
-/**
- * One-shot recap through `amp -x`.
- *
- * The prompt goes as ARGV, so like muse this worker cannot be pre-warmed and stays outside the pool.
- *
- * `model` here is an agent MODE, not a model name: Amp exposes no model list and `-m low|medium|high|ultra`
- * is what chooses one. `low` is both the cheapest and plenty for a one-sentence recap.
- *
- * Self-registration is prevented twice over. The adapter's Amp plugin already refuses to do anything
- * without machine and terminal context, and both are scrubbed here; `AMP_DISABLE_PLUGINS` then stops it
- * loading at all, which also keeps a user's own plugins out of a recap. `-x` archives the thread it
- * creates once it finishes, so recaps do not accumulate in the user's thread list.
- */
-/**
- * One attempt at `amp -x`. Resolves with the text, or null when Amp gave up on its own.
- *
- * The prompt goes on STDIN, not argv. Measured, and the difference is not subtle: with a real ~1KB
- * recap prompt as an argument, 1 run in 10 produced output — the other nine died at a flat ~32s on
- * Amp's own `Error: Network timeout. Check your connection or proxy settings and retry.` The same
- * prompt through stdin succeeded 2 in 3. (A trivial "reply OK" prompt succeeds either way, which is
- * exactly why the first round of testing missed this.)
- */
-function ampOneShotAttempt(opts: OneShotOptions, timeoutMs: number): Promise<OneShotResult | null> {
- const args = ['-x', '--no-notifications', '-m', opts.model || env.AMP_SUMMARY_MODE]
- const processEnv: NodeJS.ProcessEnv = scrubTerminalContext({ ...oneShotParentEnv(), AMP_DISABLE_PLUGINS: '1' })
- delete processEnv.MACHINE_ID
-
- return new Promise<OneShotResult | null>((resolve, reject) => {
- const child = spawn(env.AMP_PATH || 'amp', args, {
- cwd: opts.cwd, env: processEnv, detached: true, stdio: ['pipe', 'pipe', 'pipe'],
- })
- let stdout = ''
- let stderr = ''
- let settled = false
- const finish = (fn: () => void): void => {
- if (settled) return
- settled = true
- clearTimeout(timer)
- opts.signal?.removeEventListener('abort', onAbort)
- fn()
- }
- const kill = (): void => {
- if (child.pid == null || child.exitCode != null) return
- try { process.kill(-child.pid, 'SIGKILL') } catch { try { child.kill('SIGKILL') } catch { /* gone */ } }
- }
- const onAbort = (): void => {
- finish(() => reject(Object.assign(new Error('amp one-shot aborted'), { name: 'AbortError' })))
- kill()
- }
- const timer = setTimeout(() => { finish(() => resolve(null)); kill() }, timeoutMs)
- opts.signal?.addEventListener('abort', onAbort)
-
- child.stdout?.on('data', (chunk: Buffer) => { stdout += chunk.toString() })
- child.stderr?.on('data', (chunk: Buffer) => { stderr += chunk.toString() })
- child.on('error', (err) => finish(() => reject(err)))
- child.on('close', () => {
- const text = stdout.trim()
- // Amp exits non-zero even on runs that DID answer (seen repeatedly), so the output is the verdict,
- // not the exit code. Empty output means this attempt failed, whatever the code says.
- if (!text && stderr) console.warn(`[amp] one-shot attempt failed: ${stderr.replace(/\s+/g, ' ').slice(0, 120)}`)
- finish(() => resolve(text ? { text, sessionId: null } : null))
- })
- try { child.stdin?.end(opts.prompt) } catch { /* the close handler reports it */ }
- })
-}
-
-/**
- * One-shot recap through `amp -x`, retried.
- *
- * Amp is the only engine here that needs retrying, and it asks for it in its own error text. Its client
- * gives up on the network at a flat ~30s and exits with nothing; the very next run of the identical
- * prompt often succeeds. Three attempts turn the common transient failure into an answer, and a genuine
- * outage still ends in the same "no recap" it would have reached anyway.
- */
-export async function runAmpOneShot(opts: OneShotOptions): Promise<OneShotResult> {
- if (opts.signal?.aborted) throw Object.assign(new Error('amp one-shot aborted'), { name: 'AbortError' })
- const perAttemptMs = opts.timeoutMs ?? 90_000
- for (let attempt = 1; attempt <= 3; attempt++) {
- const result = await ampOneShotAttempt(opts, perAttemptMs)
- if (result) return result
- if (opts.signal?.aborted) throw Object.assign(new Error('amp one-shot aborted'), { name: 'AbortError' })
- if (attempt < 3) console.warn(`[amp] one-shot produced nothing — retrying (${attempt + 1}/3)`)
- }
- throw new Error('amp one-shot produced no output after 3 attempts')
-}
-
-export function runHermesOneShot(opts: OneShotOptions): Promise<OneShotResult> {
- if (opts.signal?.aborted) return Promise.reject(Object.assign(new Error('hermes one-shot aborted'), { name: 'AbortError' }))
- const args = ['chat', '-q', opts.prompt, '-Q', '--source', 'tool', ...(opts.model ? ['-m', opts.model] : [])]
- const processEnv = scrubTerminalContext({ ...oneShotParentEnv() })
- const timeoutMs = opts.timeoutMs ?? 60_000
-
- return new Promise<OneShotResult>((resolve, reject) => {
- const child = spawn(hermesBin(), args, {
- cwd: opts.cwd, env: processEnv, detached: true, stdio: ['ignore', 'pipe', 'pipe'],
- })
- let stdout = ''
- let stderr = ''
- let settled = false
- const finish = (fn: () => void): void => {
- if (settled) return
- settled = true
- clearTimeout(timer)
- opts.signal?.removeEventListener('abort', onAbort)
- fn()
- }
- const kill = (): void => {
- if (child.pid == null || child.exitCode != null) return
- try { process.kill(-child.pid, 'SIGKILL') } catch { try { child.kill('SIGKILL') } catch { /* gone */ } }
- }
- const onAbort = (): void => {
- finish(() => reject(Object.assign(new Error('hermes one-shot aborted'), { name: 'AbortError' })))
- kill()
- }
- const timer = setTimeout(() => {
- finish(() => reject(new Error(`hermes one-shot timed out after ${timeoutMs}ms`)))
- kill()
- }, timeoutMs)
- opts.signal?.addEventListener('abort', onAbort)
-
- child.stdout?.on('data', (chunk: Buffer) => { stdout += chunk.toString() })
- child.stderr?.on('data', (chunk: Buffer) => { stderr += chunk.toString() })
- child.on('error', (err) => finish(() => reject(err)))
- child.on('close', (code) => {
- // `-Q` still prints a `session_id: …` line before the answer — drop it.
- const text = stdout.split('\n').filter((line) => !/^\s*session_id:\s/.test(line)).join('\n').trim()
- finish(() => {
- if (!text && code !== 0) reject(new Error(`hermes one-shot exited ${code}: ${stderr.slice(0, 500)}`))
- else resolve({ text, sessionId: null })
- })
- })
- })
-}
-
-function devinBin(): string {
- return env.DEVIN_PATH || 'devin'
-}
-
-
-/**
- * Devin recap. Like Hermes — and unlike every pooled engine — the prompt must be **argv**: piping it to
- * `devin -p` panics the CLI outright (`called Result::unwrap() on an Err value`, verified on 3000.2.17),
- * so a worker cannot be pre-warmed and Devin is deliberately absent from `OneShotEngine`/the warm pool.
- *
- * `devin -p "<prompt>"` prints just the answer and exits 0. There is no `--no-session` equivalent, so the
- * recap does leave a row in `sessions.db`; it cannot register as an agent because every terminal
- * location variable is scrubbed.
- */
-export function runDevinOneShot(opts: OneShotOptions): Promise<OneShotResult> {
- if (opts.signal?.aborted) return Promise.reject(Object.assign(new Error('devin one-shot aborted'), { name: 'AbortError' }))
- if (opts.cwd) trustDevinWorkspace(opts.cwd, (m) => console.warn('[recap] could not trust the devin scratch dir:', m))
- const args = ['-p', opts.prompt, ...(opts.model ? ['--model', opts.model] : [])]
- const processEnv = scrubTerminalContext({ ...oneShotParentEnv() })
- const timeoutMs = opts.timeoutMs ?? 60_000
-
- return new Promise<OneShotResult>((resolve, reject) => {
- const child = spawn(devinBin(), args, {
- cwd: opts.cwd, env: processEnv, detached: true, stdio: ['ignore', 'pipe', 'pipe'],
- })
- let stdout = ''
- let stderr = ''
- let settled = false
- const finish = (fn: () => void): void => {
- if (settled) return
- settled = true
- clearTimeout(timer)
- opts.signal?.removeEventListener('abort', onAbort)
- fn()
- }
- const kill = (): void => {
- if (child.pid == null || child.exitCode != null) return
- try { process.kill(-child.pid, 'SIGKILL') } catch { try { child.kill('SIGKILL') } catch { /* gone */ } }
- }
- const onAbort = (): void => {
- finish(() => reject(Object.assign(new Error('devin one-shot aborted'), { name: 'AbortError' })))
- kill()
- }
- const timer = setTimeout(() => {
- finish(() => reject(new Error(`devin one-shot timed out after ${timeoutMs}ms`)))
- kill()
- }, timeoutMs)
- opts.signal?.addEventListener('abort', onAbort)
-
- child.stdout?.on('data', (chunk: Buffer) => { stdout += chunk.toString() })
- child.stderr?.on('data', (chunk: Buffer) => { stderr += chunk.toString() })
- child.on('error', (err) => finish(() => reject(err)))
- child.on('close', (code) => {
- const text = stdout.trim()
- finish(() => {
- if (!text && code !== 0) reject(new Error(`devin one-shot exited ${code}: ${stderr.slice(0, 500)}`))
- else resolve({ text, sessionId: null })
- })
- })
- })
-}
-
-export function runCommandCodeOneShot(opts: OneShotOptions): Promise<OneShotResult> {
- if (opts.signal?.aborted) return Promise.reject(abortError('commandcode'))
- if (!config || config.cwd !== opts.cwd || config.commandcodeModel !== opts.model) {
- return runDirect('commandcode', opts)
- }
- return pool.run('commandcode', opts)
-}
-
-export function runPiOneShot(opts: OneShotOptions): Promise<OneShotResult> {
- if (opts.signal?.aborted) return Promise.reject(abortError('pi'))
- if (!config || config.cwd !== opts.cwd || config.piModel !== opts.model) {
- return runDirect('pi', opts)
- }
- return pool.run('pi', opts)
-}
-
-export function runOpencodeOneShot(opts: OneShotOptions): Promise<OneShotResult> {
- if (opts.signal?.aborted) return Promise.reject(abortError('opencode'))
- if (!config || config.cwd !== opts.cwd || config.opencodeModel !== opts.model) {
- return runDirect('opencode', opts)
- }
- return pool.run('opencode', opts)
-}
-
-export function runKiloOneShot(opts: OneShotOptions): Promise<OneShotResult> {
- if (opts.signal?.aborted) return Promise.reject(abortError('kilo'))
- if (!config || config.cwd !== opts.cwd || config.kiloModel !== opts.model) {
- return runDirect('kilo', opts)
- }
- return pool.run('kilo', opts)
-}
-
// ── Voice-router warm worker ─────────────────────────────────────────────────────────────────────────
// The Overview voice router runs a tiny classifier on EVERY voice turn. Spawning the CLI each time paid a
// cold start (Node boot + CLI init + auth) that occasionally blew the 12s budget → "voice_route timed out".
-// Keep ONE router worker warm (device-gated, like the recap pool) so the classify skips the spawn. Separate
-// from the recap `pool` because the router uses its own small model, and only ever needs one worker.
+// Keep ONE router worker warm (device-gated) so the classify skips the spawn. The router uses its own
+// small model, and only ever needs one worker.
//
// The ENGINE is chosen by the caller from the machine's live agents (see voiceRouter.chooseRouterEngine).
// It used to be pinned to claude here, which meant a machine with no Claude CLI never routed at all: the
@@ -1622,7 +986,7 @@ const routerPool = new DisposableOneShotPool<OneShotOptions, OneShotResult>(
return createOneShotWorker(routerConfig.engine, routerConfig.cwd, routerConfig.model, routerConfig.effort)
},
5 * 60_000,
- (line) => console.log(line.replace('[recap-pool]', '[router-pool]')),
+ (line) => console.log(line.replace('[one-shot-pool]', '[router-pool]')),
)
/** Routing needs exactly ONE warm worker, of the configured engine — active=1 there, 0 everywhere else. */
@@ -1651,8 +1015,14 @@ export function shutdownRouterOneShot(): void {
routerPool.shutdown()
}
-/** Like runClaudeOneShot but served from the dedicated warm router worker (a cold spawn only if the pool
- * isn't configured for this exact cwd/model/effort). */
+/** One worker started and gone after one run: what the router uses when its warm worker does not match. */
+async function runDirect(engine: OneShotEngine, opts: OneShotOptions): Promise<OneShotResult> {
+ const worker = await createOneShotWorker(engine, opts.cwd, opts.model, opts.effort, opts.codexHome)
+ try { return await worker.run(opts) } finally { worker.dispose() }
+}
+
+/** A one-shot served from the dedicated warm router worker (a cold spawn only if the pool isn't
+ * configured for this exact engine, cwd, model and effort). */
export function runRouterOneShot(engine: OneShotEngine, opts: OneShotOptions): Promise<OneShotResult> {
if (opts.signal?.aborted) return Promise.reject(abortError(engine))
if (!routerConfig || routerConfig.engine !== engine || routerConfig.cwd !== opts.cwd ||
diff --git a/cli/src/lib/summarize.spec.ts b/cli/src/lib/summarize.spec.ts
deleted file mode 100644
index c4c89df04..000000000
--- a/cli/src/lib/summarize.spec.ts
+++ /dev/null
@@ -1,422 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest'
-
-const mocks = vi.hoisted(() => ({
- configure: vi.fn(),
- runClaude: vi.fn(),
- runCodex: vi.fn(),
- runCursor: vi.fn(),
- runGrok: vi.fn(),
- cleanupCursor: vi.fn(),
- setCounts: vi.fn(),
- resolveKey: vi.fn(),
- complete: vi.fn(),
-}))
-
-vi.mock('../config/env.js', () => ({
- env: {
- ADAPTER_DATA_DIR: '/tmp/machine-adapter-summarize-spec',
- CURSOR_HOME: '/tmp/machine-adapter-summarize-spec/cursor',
- SUMMARY_MODEL: 'sonnet',
- CODEX_SUMMARY_MODEL: 'gpt-5.5',
- 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,
- runClaudeOneShot: mocks.runClaude,
- runCodexOneShot: mocks.runCodex,
- runCursorOneShot: mocks.runCursor,
- runGrokOneShot: mocks.runGrok,
- setOneShotPoolActiveCounts: mocks.setCounts,
- setOneShotPoolDeviceConnected: vi.fn(),
- shutdownOneShotPool: vi.fn(),
-}))
-
-import { deriveTurnBody, summarizeTurnText, syncSummaryPoolSessions, deriveTurnSummary, RECAP_MAX_CHARS } from './summarize.js'
-
-beforeEach(() => {
- mocks.runClaude.mockReset()
- mocks.runCodex.mockReset()
- mocks.runCursor.mockReset()
- mocks.runGrok.mockReset()
- 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.')
-
- await expect(summarizeTurnText(
- 'Wired the gateway recap path.',
- undefined,
- 'Does the gateway recap work?',
- 'claude',
- gateway,
- )).resolves.toBe('Recap works through the gateway.\n\nWired the gateway recap path.')
-
- expect(mocks.complete).toHaveBeenCalledTimes(1)
- expect(mocks.complete.mock.calls[0][0]).toMatchObject({
- model: 'deepseek/deepseek-v4-flash',
- apiKey: 'sk-or-v1-process',
- // A headline in any script, not a paragraph.
- maxTokens: 160,
- })
- 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.', sessionId: null })
-
- await expect(summarizeTurnText('Did the work.', undefined, 'Status?', 'claude', gateway))
- .resolves.toBe('Engine recap.\n\nDid the work.')
-
- 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('previous recap', () => {
- it('quotes the previous turn\'s recap as continuity context, fenced off from the content', async () => {
- mocks.runClaude.mockResolvedValue({ text: 'Applied the same change to server.ts.\n\nDone.', sessionId: null })
-
- await summarizeTurnText(
- 'Done, applied the same change to server.ts.',
- undefined,
- 'same fix in the other file',
- 'claude',
- undefined,
- 'Fixed the retry path in client.ts.\n\nThe retry now backs off\nand caps at five attempts.',
- )
-
- const prompt = mocks.runClaude.mock.calls[0][0].prompt as string
- // Flattened — the stored body's line breaks must not read as structure to preserve.
- expect(prompt).toContain('«Fixed the retry path in client.ts. The retry now backs off and caps at five attempts.»')
- expect(prompt).toContain('PREVIOUS turn')
- // Context, not content: the block sits BEFORE the turn's own message, and the message is unchanged.
- expect(prompt.indexOf('PREVIOUS turn')).toBeLessThan(prompt.indexOf('---\nDone, applied the same change'))
- })
-
- it('says nothing about a previous turn when there is none', async () => {
- mocks.runClaude.mockResolvedValue({ text: 'Fixed the retry path.\n\nDone.', sessionId: null })
-
- await summarizeTurnText('Fixed the retry path in client.ts.', undefined, 'fix the retry path', 'claude')
-
- const prompt = mocks.runClaude.mock.calls[0][0].prompt as string
- expect(prompt).not.toContain('PREVIOUS turn')
- })
-
- it('does not let the previous recap\'s language trigger the drift retry', async () => {
- // The language check compares the OUTPUT against the ask + answer only. A previous recap in another
- // script is context the model was told to ignore for language, so it must not count as a mismatch.
- mocks.runClaude.mockResolvedValue({ text: 'Deploy finished.\n\nThe service is healthy.', sessionId: null })
-
- await summarizeTurnText('Deploy finished; service healthy.', undefined, 'deploy status?', 'claude', undefined,
- 'Đã sửa đường retry.\n\nRetry giờ lùi dần và dừng ở năm lần.')
-
- expect(mocks.runClaude).toHaveBeenCalledTimes(1)
- })
-})
-
-describe('Cursor recap', () => {
- it('uses a Cursor one-shot with the configured Cursor model', async () => {
- mocks.runCursor.mockResolvedValue({
- text: 'Cursor recap works.',
- sessionId: 'cursor-recap-session',
- })
-
- await expect(summarizeTurnText(
- 'Implemented Cursor recap support.',
- undefined,
- 'Does Cursor recap work?',
- 'cursor',
- )).resolves.toBe(
- 'Cursor recap works.\n\nImplemented Cursor recap support.',
- )
-
- expect(mocks.runCursor).toHaveBeenCalledOnce()
- expect(mocks.runCursor.mock.calls[0][0]).toMatchObject({
- model: 'auto',
- effort: 'low',
- })
- expect(mocks.runClaude).not.toHaveBeenCalled()
- expect(mocks.runCodex).not.toHaveBeenCalled()
- expect(mocks.cleanupCursor).toHaveBeenCalledWith('cursor-recap-session')
- })
-
- it('includes Cursor, OpenCode, Kilo and Pi sessions when sizing recap workers', () => {
- syncSummaryPoolSessions([
- { engine: 'claude' },
- { engine: 'codex' },
- { engine: 'cursor' },
- { engine: 'cursor' },
- { engine: 'opencode' },
- // Kilo IS poolable: `kilo run` takes its prompt on stdin and ends at EOF, so a worker can be warmed
- // before the prompt exists — the property hermes and devin lack.
- { engine: 'kilo' },
- { engine: 'pi' },
- { engine: 'commandcode' },
- { engine: 'hermes' }, // not poolable (prompt is argv) — must NOT be counted
- { engine: 'devin' }, // likewise: piping a prompt to `devin -p` panics the CLI
- ])
-
- expect(mocks.setCounts).toHaveBeenCalledWith({ claude: 1, codex: 1, cursor: 2, opencode: 1, kilo: 1, pi: 1, commandcode: 1 })
- })
-})
-
-describe('Grok recap', () => {
- it('uses an isolated direct Grok one-shot with the configured model', async () => {
- mocks.runGrok.mockResolvedValue({
- text: 'Grok recap works.',
- sessionId: 'grok-recap-session',
- })
-
- await expect(summarizeTurnText(
- 'Implemented Grok recap support.',
- undefined,
- 'Does Grok recap work?',
- 'grok',
- )).resolves.toBe('Grok recap works.\n\nImplemented Grok recap support.')
-
- expect(mocks.runGrok).toHaveBeenCalledOnce()
- expect(mocks.runGrok.mock.calls[0][0]).toMatchObject({ model: 'grok-4.5', effort: 'low' })
- expect(mocks.runClaude).not.toHaveBeenCalled()
- expect(mocks.runCodex).not.toHaveBeenCalled()
- expect(mocks.runCursor).not.toHaveBeenCalled()
- })
-})
-
-describe('language fidelity', () => {
- const VI_SOURCE = 'Đội tuyển Việt Nam đã thắng trận chung kết với tỉ số hai một trước Thái Lan tối qua tại sân Mỹ Đình.'
- const VI_ASK = 'Trận đấu tối qua kết quả thế nào?'
-
- it('retries when the recap comes back in another language than the source', async () => {
- // The old check only fired for "should be English, came back Vietnamese"; this is the reverse, which
- // is what users actually hit — talking Vietnamese and getting an English recap.
- mocks.runClaude
- .mockResolvedValueOnce({ text: 'Vietnam won the final two one.\n\nVietnam beat Thailand two one last night.', sessionId: 's1' })
- .mockResolvedValueOnce({ text: 'Việt Nam thắng chung kết 2-1.\n\nViệt Nam hạ Thái Lan 2-1 tối qua tại Mỹ Đình.', sessionId: 's2' })
-
- const out = await summarizeTurnText(VI_SOURCE, undefined, VI_ASK, 'claude')
-
- expect(mocks.runClaude).toHaveBeenCalledTimes(2)
- expect(mocks.runClaude.mock.calls[1][0].prompt).toContain('RETRY')
- expect(out).toContain('Việt Nam thắng chung kết')
- })
-
- it('does not retry when the recap keeps the source language', async () => {
- mocks.runClaude.mockResolvedValue({
- text: 'Việt Nam thắng chung kết 2-1.\n\nViệt Nam hạ Thái Lan 2-1 tối qua tại sân Mỹ Đình.',
- sessionId: 's1',
- })
-
- await summarizeTurnText(VI_SOURCE, undefined, VI_ASK, 'claude')
- expect(mocks.runClaude).toHaveBeenCalledOnce()
- })
-
- it('does not retry an English turn answered in English', async () => {
- mocks.runClaude.mockResolvedValue({
- text: 'Vietnam won the final two one.\n\nVietnam beat Thailand two one last night at My Dinh stadium.',
- sessionId: 's1',
- })
-
- await summarizeTurnText(
- 'Vietnam won the final against Thailand two one last night at the My Dinh stadium.',
- undefined,
- 'How did the match go last night?',
- 'claude',
- )
- expect(mocks.runClaude).toHaveBeenCalledOnce()
- })
-
- it('tolerates a technical term in another script inside a matching recap', async () => {
- // A quoted identifier or product name must not read as a language switch.
- mocks.runClaude.mockResolvedValue({
- text: 'Đã sửa lỗi ở hàm parseConfig.\n\nMình đã sửa hàm parseConfig trong module loader và thêm kiểm tra đầu vào.',
- sessionId: 's1',
- })
-
- await summarizeTurnText(
- 'Mình đã sửa hàm parseConfig trong module loader và thêm kiểm tra đầu vào cho tham số.',
- undefined,
- 'Sửa xong chưa?',
- 'claude',
- )
- expect(mocks.runClaude).toHaveBeenCalledOnce()
- })
-})
-
-describe('the body under the headline', () => {
- // The dial shows the headline and nothing else; the device protocol defines `text` as the answer
- // flattened and clipped. So the model writes ONE line, and the body is excerpted from the answer
- // itself — never a paraphrase that costs tokens on every turn and is shown nowhere.
- const answer = '## Result\n\n- **Deploy**: finished\n- Service is healthy and serving traffic.\n\nNothing else changed.'
-
- it('is the answer\'s own excerpt, never the model\'s', async () => {
- mocks.runClaude.mockResolvedValue({ text: 'Deploy finished, service healthy.\n\nSome invented paraphrase.', sessionId: 's1' })
- const out = await summarizeTurnText(answer, undefined, 'Done?', 'claude')
- const [recap, body] = out!.split('\n\n')
- expect(recap).toBe('Deploy finished, service healthy.')
- expect(body).toBe(deriveTurnBody(answer))
- expect(body).toBe('Result Deploy: finished Service is healthy and serving traffic. Nothing else changed.')
- expect(out).not.toContain('invented paraphrase')
- })
-
- it('takes the first non-empty line as the headline when the model still writes more', async () => {
- mocks.runClaude.mockResolvedValue({ text: '\n\nAll good.\nAnd a second line.\n\nA third paragraph…', sessionId: 's1' })
- const out = await summarizeTurnText(answer, undefined, 'Done?', 'claude')
- expect(out!.split('\n\n')[0]).toBe('All good.')
- })
-
- it('excerpts the whole answer, not the tail the prompt was fed', async () => {
- const opening = 'The opening sentence is what the excerpt should show.'
- const huge = `${opening} ${'filler '.repeat(20_000)}the very end.`
- mocks.runClaude.mockResolvedValue({ text: 'Long answer done.', sessionId: 's1' })
- const out = await summarizeTurnText(huge, undefined, 'Done?', 'claude')
- expect(out!.split('\n\n')[1].startsWith(opening)).toBe(true)
- // The prompt itself still carries only the tail.
- expect((mocks.runClaude.mock.calls[0][0].prompt as string)).not.toContain(opening)
- })
-
- it('judges language drift on the headline alone', async () => {
- mocks.runClaude.mockResolvedValue({ text: 'All done.\n\nĐoạn thứ hai lạc ngôn ngữ hoàn toàn nhé.', sessionId: 's1' })
- const out = await summarizeTurnText('The deploy finished and the service is healthy.', undefined, 'Done?', 'claude')
- expect(out!.split('\n\n')[0]).toBe('All done.')
- expect(mocks.runClaude).toHaveBeenCalledTimes(1)
- })
-
- it('never lets an ellipsis into the headline', async () => {
- mocks.runClaude.mockResolvedValue({ text: 'Work is done and then it trails off…', sessionId: 's1' })
- const out = await summarizeTurnText(answer, undefined, 'Status?', 'claude')
- expect(out!.split('\n\n')[0]).not.toContain('…')
- })
-
- it('asks the model for the headline only', async () => {
- mocks.runClaude.mockResolvedValue({ text: 'Done.', sessionId: 's1' })
- await summarizeTurnText(answer, undefined, 'Done?', 'claude')
- const prompt = mocks.runClaude.mock.calls[0][0].prompt as string
- expect(prompt).toContain('Output ONLY the one line')
- expect(prompt).not.toContain('Part 2')
- expect(prompt).not.toContain('LAY PART 2')
- expect(prompt).not.toContain('two parts')
- })
-})
-
-describe('deriveTurnSummary (the local recap)', () => {
- it('keeps complete opening sentences across paragraph boundaries', () => {
- const text = 'Blue selected.\n\nAnything else?'
- expect(deriveTurnSummary(text)?.split('\n')[0]).toBe('Blue selected. Anything else?')
- })
-
- it('skips a label at the top', () => {
- const text = 'Kết quả:\nĐã sửa xong file cấu hình.'
- expect(deriveTurnSummary(text)?.split('\n')[0]).toBe('Đã sửa xong file cấu hình.')
- })
-
- it.each([
- ['Yes. The fix is installed.', 'Yes. The fix is installed.'],
- ['No.\n\nThe list only decides who is allowed in.', 'No. The list only decides who is allowed in.'],
- ['## Result\n\n**No.** It does not send your data to a model.', 'No. It does not send your data to a model.'],
- ['OK! The checks pass. Here are all the details.', 'OK! The checks pass. Here are all the details.'],
- ['No\nThe device has no network connection.', 'No The device has no network connection.'],
- ['Yes. Correct. The fix is installed. More details follow.', 'Yes. Correct. The fix is installed. More details follow.'],
- ['No.', 'No.'],
- ])('preserves the opening and its explanation: %s', (text, expected) => {
- expect(deriveTurnSummary(text)?.split('\n')[0]).toBe(expected)
- })
-
- it('includes the explanation instead of stranding a bare acknowledgment', () => {
- const text = 'Yes. The fix is installed and the device has reconnected successfully to the desktop application.'
- const result = deriveTurnSummary(text)!
- expect(result.split('\n\n')[0]).toBe(text)
- expect(result.split('\n\n')[0].length).toBeLessThanOrEqual(RECAP_MAX_CHARS)
- expect(result.split('\n\n')[1]).toBe(text)
- })
-
- it.each([
- ["It isn't external. The label is a branch name.", "It isn't external. The label is a branch name."],
- ['Tests pass. All the details are in the terminal.', 'Tests pass. All the details are in the terminal.'],
- ['Not approved. The write would overwrite your changes.', 'Not approved. The write would overwrite your changes.'],
- ['No files changed. This was only a review.', 'No files changed. This was only a review.'],
- ])('keeps useful short sentences without a word-count threshold: %s', (text, expected) => {
- expect(deriveTurnSummary(text)?.split('\n')[0]).toBe(expected)
- })
-
- it('keeps a sentence exactly at the current budget without a continuation marker', () => {
- const text = 'A'.repeat(RECAP_MAX_CHARS - 1) + '.'
- expect(text.length).toBe(RECAP_MAX_CHARS)
- expect(deriveTurnSummary(`${text} Another sentence.`)?.split('\n')[0]).toBe(text)
- })
-
- it('uses the additional room for three complete sentences', () => {
- const text = 'Fixed the parser. All tests pass. Voice input now sends to the selected agent.'
- expect(text.length).toBeGreaterThan(60)
- expect(deriveTurnSummary(`${text} More details follow.`)?.split('\n')[0]).toBe(`${text} More details follow.`)
- })
-
- it('keeps the body excerpt unchanged when the headline is shorter', () => {
- const text = `Tests pass. ${'The details stay in the body. '.repeat(15)}`
- const [recap, body] = deriveTurnSummary(text)!.split('\n\n')
- expect(recap).toBe('Tests pass. The details stay in the body. The details stay in the body. The details stay in the body. The details stay in the body. The details stay in the body.')
- expect(body).toBe(deriveTurnBody(text))
- expect(body.length).toBeLessThanOrEqual(250)
- expect(body.endsWith('…')).toBe(true)
- expect(mocks.runClaude).not.toHaveBeenCalled()
- expect(mocks.runCodex).not.toHaveBeenCalled()
- expect(mocks.complete).not.toHaveBeenCalled()
- })
-
- it('stops after two complete sentences when the next sentence would overflow', () => {
- const text = `Fixed the parser. All tests pass. The remaining details include ${'additional verification notes '.repeat(6)}in the terminal.`
- expect(deriveTurnSummary(text)?.split('\n')[0]).toBe('Fixed the parser. All tests pass.')
- })
-
- it('extends a short sentence to at least 20 characters even when the next sentence cannot fit', () => {
- const text = `Tests pass. The full explanation includes ${'individual test results and measurements '.repeat(6)}in the terminal.`
- const recap = deriveTurnSummary(text)!.split('\n')[0]
- expect(recap.length).toBeGreaterThanOrEqual(20)
- expect(recap.startsWith('Tests pass. The full explanation')).toBe(true)
- expect(recap.endsWith(' +')).toBe(true)
- })
-
- it('keeps following text when a complete opening is shorter than 20 characters', () => {
- const text = 'It is fixed. The remaining details are'
- expect(deriveTurnSummary(text)?.split('\n')[0]).toBe(text)
- })
-
- it('uses a marked word-boundary excerpt when no complete sentence fits', () => {
- const text = 'The fix is installed and the device has reconnected successfully to the desktop application and verified the selected agent before sending the complete transcript from the microphone to its terminal pane'
- const recap = deriveTurnSummary(text)!.split('\n')[0]
- expect(recap).toBe('The fix is installed and the device has reconnected successfully to the desktop application and verified the selected agent before sending the complete transcript from the +')
- expect(recap.length).toBeLessThanOrEqual(RECAP_MAX_CHARS)
- })
-})
diff --git a/cli/src/lib/summarize.ts b/cli/src/lib/summarize.ts
deleted file mode 100644
index ce8300c83..000000000
--- a/cli/src/lib/summarize.ts
+++ /dev/null
@@ -1,401 +0,0 @@
-/**
- * Device turn-recap summarizer — self-contained port of the brain's `summarizeTurnText`.
- *
- * Produces the device's `recap\n\ntext` shape for one turn. Only the RECAP — a one-line headline,
- * ≤15 words — comes from a model (a disposable one-shot of the same CLI engine as the interactive
- * session). The `text` under it is the answer itself, flattened and clipped locally
- * (`deriveTurnBody`), the same excerpt `SUMMARY_MODE=local` shows: nothing on the dial reads a
- * model-written body any more (the tile shows the headline, the reader is off), the device protocol
- * defines `text` as an excerpt, and a paraphrase nobody sees cost output tokens on every turn.
- * Honors an AbortSignal so a newer turn can supersede a stale recap.
- */
-
-import { deriveTurnBody } from './deviceRecap.js'
-export { deriveTurnSummary, deriveTurnBody, RECAP_MAX_CHARS, RECAP_MIN_CHARS, BODY_MAX_CHARS } from './deviceRecap.js'
-
-import { existsSync, mkdirSync } from 'fs'
-import { unlink } from 'fs/promises'
-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,
- runClaudeOneShot,
- runCodexOneShot,
- runCursorOneShot,
- runOpencodeOneShot,
- runKiloOneShot,
- runPiOneShot,
- runHermesOneShot,
- runCommandCodeOneShot,
- runDevinOneShot,
- runMuseOneShot,
- runAmpOneShot,
- runGrokOneShot,
- runAgyOneShot,
- runCopilotOneShot,
- setOneShotPoolActiveCounts,
- setOneShotPoolDeviceConnected,
- shutdownOneShotPool,
- type OneShotOptions,
-} from './oneshot.js'
-
-const RECAP_MAX_WORDS = 15 // ~12-15 words; ONE complete sentence (20 overflowed the device tile).
-const MAX_INPUT_CHARS = 50_000
-// The previous turn's `recap\n\ntext` is a ≤15-word headline over a ≤250-char excerpt by construction;
-// this is a guard against a stored summary from an older build, not a budget anyone is expected to hit.
-const PREVIOUS_RECAP_MAX_CHARS = 1_000
-const SUMMARY_SCRATCH = join(env.ADAPTER_DATA_DIR, 'summary-scratch')
-
-function ensureSummaryScratch(): string {
- if (!existsSync(SUMMARY_SCRATCH)) mkdirSync(SUMMARY_SCRATCH, { recursive: true, mode: 0o700 })
- return SUMMARY_SCRATCH
-}
-
-configureOneShotPool({
- cwd: ensureSummaryScratch(),
- claudeModel: env.SUMMARY_MODEL,
- codexModel: env.CODEX_SUMMARY_MODEL,
- cursorModel: env.CURSOR_SUMMARY_MODEL,
- opencodeModel: env.OPENCODE_SUMMARY_MODEL,
- kiloModel: env.KILO_SUMMARY_MODEL,
- piModel: env.PI_SUMMARY_MODEL,
- commandcodeModel: env.COMMANDCODE_SUMMARY_MODEL,
- effort: env.SUMMARY_EFFORT,
-})
-
-export function syncSummaryPoolSessions(sessions: Array<{ engine: AgentEngine }>): void {
- const counts = { claude: 0, codex: 0, cursor: 0, opencode: 0, kilo: 0, pi: 0, commandcode: 0 }
- for (const session of sessions) {
- // Hermes, Devin, Muse and Amp take their recap prompt as argv (`muse exec <prompt>`, `amp -x <prompt>`),
- // so they cannot be pre-warmed the way a stdin-fed CLI can — no pooled worker for them.
- if (session.engine === 'hermes' || session.engine === 'devin' || session.engine === 'muse'
- || session.engine === 'amp' || session.engine === 'grok' || session.engine === 'agy' || session.engine === 'copilot'
- || session.engine === 'terminal') continue
- counts[session.engine]++
- }
- setOneShotPoolActiveCounts(counts)
-}
-
-export function setSummaryPoolDeviceConnected(connected: boolean): void {
- setOneShotPoolDeviceConnected(connected)
-}
-
-export function shutdownSummaryPool(): void {
- shutdownOneShotPool()
-}
-
-/**
- * A coarse WRITING-SYSTEM fingerprint — deliberately not a language identifier. Naming languages meant a
- * hand-maintained word list per language and a drift check that only ever ran in one direction (it caught
- * "should be English, came back Vietnamese" but never the reverse). Comparing which scripts a text uses,
- * and how accented its Latin part is, catches "answered in a different language" for any pair of languages
- * with nothing to maintain.
- */
-interface ScriptProfile {
- /** Share of letters per writing system, e.g. { Latin: 0.9, Han: 0.1 }. */
- shares: Record<string, number>
- /** Share of Latin letters carrying a diacritic — what separates Vietnamese/Polish/Turkish from English. */
- accented: number
- letters: number
-}
-
-const SCRIPTS: Array<[string, RegExp]> = [
- ['Han', /\p{Script=Han}/u],
- ['Hiragana', /\p{Script=Hiragana}/u],
- ['Katakana', /\p{Script=Katakana}/u],
- ['Hangul', /\p{Script=Hangul}/u],
- ['Cyrillic', /\p{Script=Cyrillic}/u],
- ['Arabic', /\p{Script=Arabic}/u],
- ['Hebrew', /\p{Script=Hebrew}/u],
- ['Thai', /\p{Script=Thai}/u],
- ['Devanagari', /\p{Script=Devanagari}/u],
- ['Greek', /\p{Script=Greek}/u],
- ['Latin', /\p{Script=Latin}/u],
-]
-
-function scriptProfile(text: string): ScriptProfile {
- const counts: Record<string, number> = {}
- let letters = 0
- let accented = 0
- for (const ch of text || '') {
- if (!/\p{L}/u.test(ch)) continue
- const hit = SCRIPTS.find(([, re]) => re.test(ch))
- if (!hit) continue
- letters++
- counts[hit[0]] = (counts[hit[0]] || 0) + 1
- // NFD splits an accented letter into base + combining mark(s); a bare ASCII letter never does.
- if (hit[0] === 'Latin' && /\p{M}/u.test(ch.normalize('NFD'))) accented++
- }
- const shares: Record<string, number> = {}
- if (letters) for (const [k, v] of Object.entries(counts)) shares[k] = v / letters
- const latin = counts.Latin || 0
- return { shares, accented: latin ? accented / latin : 0, letters }
-}
-
-/**
- * True when `out` reads as a DIFFERENT language than `src`: it dropped (or invented) a writing system the
- * other side relies on, or its Latin text lost (or gained) diacritics wholesale. Thresholds are loose on
- * purpose — quoting a product name or a code identifier in another script must not trip it.
- */
-function languageDrifted(src: string, out: string): boolean {
- const a = scriptProfile(src)
- const b = scriptProfile(out)
- if (a.letters < 12 || b.letters < 12) return false // too little signal to judge
- for (const [name] of SCRIPTS) {
- if (name === 'Latin') continue
- const sa = a.shares[name] || 0
- const sb = b.shares[name] || 0
- if (sa >= 0.15 && sb <= 0.02) return true // the source is written in it, the output is not
- if (sb >= 0.15 && sa <= 0.02) return true // the output switched into a script the source never used
- }
- const latinBoth = (a.shares.Latin || 0) >= 0.5 && (b.shares.Latin || 0) >= 0.5
- if (latinBoth && a.accented >= 0.08 && b.accented <= 0.02) return true
- if (latinBoth && b.accented >= 0.08 && a.accented <= 0.02) return true
- return false
-}
-
-// Trailing connectors (VN + EN) a recap must never END on — cutting here would leave it dangling
-// ("…2-1, nhờ"). Stripped from the tail if a hard cut lands on one. Prefix with a separator rather
-// than \b: JS \b is ASCII-only, so it fails on a Vietnamese word ending in a diacritic (e.g. "nhờ").
-const DANGLING_TAIL =
- /[\s,;:–—-]+(nhờ|vì|do|bởi|để|và|hoặc|nhưng|mà|với|của|cho|khi|nếu|thì|theo|cùng|rằng|là|nên|and|or|but|with|because|since|so|to|for|of|in|on|at|the|a|an)[\s,;:–—-]*$/i
-
-/**
- * Cap the RECAP to a clean newspaper-style headline: ONE line, ≤ max words, and NEVER any "…". The model is
- * told to write a complete headline within budget; this is the hard guard. If it overshoots we cut at the
- * last clause boundary and strip any dangling connector so it still ends on a complete point — but we do
- * NOT append an ellipsis (a headline reads as finished, not truncated).
- */
-function capRecap(text: string, max: number): string {
- // Drop any ellipsis the model emitted (leading/trailing/mid) — headlines never carry "…".
- let t = text.replace(/…|\.{2,}/g, ' ').replace(/\s+/g, ' ').trim()
- const words = t.split(/\s+/)
- if (words.length > max) {
- let head = words.slice(0, max).join(' ')
- const b = Math.max(head.lastIndexOf(','), head.lastIndexOf(';'), head.lastIndexOf('. '))
- if (b > head.length * 0.5) head = head.slice(0, b)
- t = head
- }
- // Strip a dangling connector / trailing punctuation so the headline ends on a complete point. No "…".
- let prev: string
- do { prev = t; t = t.replace(DANGLING_TAIL, '').replace(/[\s,;:–—-]+$/, '').trim() } while (t !== prev)
- return t
-}
-
-// The CLI mangles a cwd into its projects-dir name (every non-alphanumeric → '-'); used to delete
-// the throwaway one-shot transcript so it never lingers under the watched projects root.
-function scratchTranscript(scratch: string, id: string): string {
- const mangled = scratch.replace(/[^a-zA-Z0-9]/g, '-')
- return join(homedir(), '.claude', 'projects', mangled, `${id}.jsonl`)
-}
-
-async function cleanupRecapSession(engine: AgentEngine, scratch: string, sessionId: string | null): Promise<void> {
- if (!sessionId) return
- if (engine === 'claude') {
- await unlink(scratchTranscript(scratch, sessionId)).catch(() => {})
- return
- }
- if (engine === 'cursor') await cleanupCursorOneShotSession(sessionId)
-}
-
-/** The headline in a one-shot's output: its first non-empty line. A model that still writes a second
- * paragraph is tolerated, not concatenated — and not judged for language drift either. */
-function headlineOf(output: string): string {
- return output.split('\n').map((line) => line.trim()).find(Boolean) ?? ''
-}
-
-
-/**
- * `recap = llm(instruct, previousRecap, userMessage, text)`.
- *
- * `previousRecap` is the stored summary of this agent's LAST turn. It is context, not content: it lets
- * a turn whose answer is "Done — same change in the other two files" recap as what was done, instead of
- * a fragment that names nothing. The prompt fences it off so it can only resolve references, never be
- * reported as this turn's news. Absent on a session's first turn.
- */
-export async function summarizeTurnText(
- text: string,
- signal?: AbortSignal,
- userMessage?: string,
- engine: AgentEngine = 'claude',
- gateway?: GatewayRuntime,
- previousRecap?: string,
-): Promise<string | null> {
- let last = (text || '').trim()
- if (!last) return null
- if (last.length > MAX_INPUT_CHARS) last = last.slice(-MAX_INPUT_CHARS)
-
- // Continuity only. Flattened — the stored body carries line breaks the model would otherwise
- // read as structure to preserve — and capped so an odd stored value cannot crowd out the turn.
- const prev = (previousRecap || '').replace(/\s+/g, ' ').trim().slice(0, PREVIOUS_RECAP_MAX_CHARS)
- const prevBlock = prev
- ? `For continuity ONLY, the recap of this assistant's PREVIOUS turn was: «${prev}». Use it to ` +
- `resolve references in this turn ("it", "that one", "the same fix", "as before", "the other file") ` +
- `and to keep names and terms consistent — nothing more. Your recap describes THIS turn's message ` +
- `alone: do NOT repeat, restate or merge in the previous recap, and do NOT report anything from it ` +
- `as if it happened now. If this turn's message is complete on its own, ignore the previous recap ` +
- `entirely.\n\n`
- : ''
-
- // If we know the user's request for this turn, tell the recap to LEAD with the direct answer to it
- // (asked a price → give the price), not a generic characterization of the topic — the answer text
- // still comes from the assistant's message. Whitespace-flattened + capped so a long paste can't
- // dominate the prompt.
- const ask = (userMessage || '').replace(/\s+/g, ' ').trim().slice(0, 400)
- const askBlock = ask
- ? `The user's request this turn was: «${ask}». Use this request as the turn's language signal ` +
- `and context, but take all facts from the assistant message below. Your recap MUST lead with the DIRECT answer to that ` +
- `exact request — the specific fact, number, decision or result they asked for (asked a price → the ` +
- `price; asked yes/no → the verdict; asked "how" → the key step), taken from the assistant's message ` +
- `below, then a few words of context. Do NOT lead with a generic characterization of the topic, and ` +
- `do NOT invent anything not in the message.\n\n`
- : ''
-
- // Kept in sync with the hosted runtime’s recap. Guards two failure
- // modes: (1) META-TASK LEAK — the summarizer writing its own intent ("I need to convert…") into the
- // recap instead of re-voicing the content; (2) WRONG LANGUAGE — the recap drifting away from the
- // source message's language.
- const prompt =
- `LANGUAGE RULE (most important): choose the output language ONLY from the user's request for this ` +
- `turn and the assistant message between the --- markers below. If both are in English, output English. ` +
- `If they use another language, output that language. If they mix languages, preserve that mix naturally. ` +
- `Never switch to a language that does not appear in the user's request or the assistant message. Ignore ` +
- `previous conversation (including the previous recap, if one is quoted below), account locale, ` +
- `environment locale, and the language of these instructions.\n\n` +
- prevBlock +
- askBlock +
- `Between the --- markers below is a message the assistant already sent to the user. Re-voice its ` +
- `CONTENT back to the user, in the FIRST PERSON as that same assistant (its own "I"). You are ONLY ` +
- `restating what the message says — you are NOT performing any task and NOT describing this ` +
- `summarizing job. NEVER write a meta or intent sentence such as "I need to…", "I will ` +
- `summarize/convert/translate…", "let me…", or "the message is about…". Output ONLY the one line ` +
- `described below — nothing before it, nothing after it, no headings, labels or preamble:\n` +
- `A NEWSPAPER HEADLINE for this turn: ONE punchy, self-contained line of at most ` +
- `${RECAP_MAX_WORDS} words. State the SINGLE most important thing the user needs from this turn — the ` +
- `direct answer, decision, result or recommendation to their request (what was said or done, NOT a plan ` +
- `of what you will do next, NOT a description of the topic) — and FRONT-LOAD it so the first few words ` +
- `alone carry the point (only the opening may be shown). Headline voice: active, specific, punchy; NO ` +
- `hedging or throat-clearing (never open with "I think…", "This is a close one…", "It is about…", ` +
- `"Regarding…") — conclusion first, then at most a few words of why; if the source hedges, still commit ` +
- `to its leaning up front. It MUST be COMPLETE within ${RECAP_MAX_WORDS} words: never cut off mid-idea, ` +
- `never end on a connector/preposition/unfinished clause, and NEVER use "…", "..." or any ellipsis or ` +
- `trailing dots. If you would run long, TIGHTEN the wording into a shorter headline — do not truncate. ` +
- `Do NOT enumerate long lists — give the gist (use counts like "4 forwards" instead of naming everyone). ` +
- `PLAIN TEXT ONLY: no emoji, markdown, tables, bullets or URLs. Restate the substance itself; do NOT ` +
- `narrate the process (avoid "I wrote/did…").\n\n---\n${last}\n\n---\n` +
- `IMPORTANT: before you answer, re-check the user's request and source message. Write the headline ` +
- `in their language and register. Do NOT translate or switch to any language absent from those two ` +
- `inputs. Keep technical terms, code, and product names as-is.`
-
- const scratch = ensureSummaryScratch()
-
- const t0 = Date.now()
- // 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
- : engine === 'cursor'
- ? env.CURSOR_SUMMARY_MODEL
- : engine === 'pi'
- ? env.PI_SUMMARY_MODEL
- : engine === 'hermes'
- ? env.HERMES_SUMMARY_MODEL
- : engine === 'commandcode'
- ? env.COMMANDCODE_SUMMARY_MODEL
- : engine === 'devin'
- ? env.DEVIN_SUMMARY_MODEL
- : engine === 'muse'
- ? env.MUSE_SUMMARY_MODEL
- // Amp's is an agent MODE (low|medium|high|ultra), not a model name — it exposes no models.
- : engine === 'amp'
- ? env.AMP_SUMMARY_MODE
- : engine === 'kilo'
- ? env.KILO_SUMMARY_MODEL
- : engine === 'grok'
- ? env.GROK_SUMMARY_MODEL
- : engine === 'agy'
- ? env.AGY_SUMMARY_MODEL
- : engine === 'copilot'
- ? env.COPILOT_SUMMARY_MODEL
- : env.OPENCODE_SUMMARY_MODEL
- const effort = engine === 'cursor' ? 'model-defined' : env.SUMMARY_EFFORT
- console.log(
- gatewayKey
- ? `[recap] openrouter ${engine} · model=${model} · inputChars=${last.length}${ask ? ' · withAsk' : ''}${prev ? ' · withPrev' : ''}`
- : `[recap] one-shot ${engine} · model=${model} · effort=${effort} · inputChars=${last.length}${ask ? ' · withAsk' : ''}${prev ? ' · withPrev' : ''}`,
- )
- const runEngine = engine === 'claude'
- ? runClaudeOneShot
- : engine === 'codex'
- ? runCodexOneShot
- : engine === 'cursor'
- ? runCursorOneShot
- : engine === 'pi'
- ? runPiOneShot
- : engine === 'hermes'
- ? runHermesOneShot
- : engine === 'commandcode'
- ? runCommandCodeOneShot
- : engine === 'devin'
- ? runDevinOneShot
- : engine === 'muse'
- ? runMuseOneShot
- : engine === 'amp'
- ? runAmpOneShot
- : engine === 'kilo'
- ? runKiloOneShot
- : engine === 'grok'
- ? runGrokOneShot
- : engine === 'agy'
- ? runAgyOneShot
- : engine === 'copilot'
- ? runCopilotOneShot
- : runOpencodeOneShot
- // One shape for both paths so the language-drift retry and the headline cap 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: 160,
- }) ?? '',
- sessionId: null,
- })
- : runEngine
- let r = await run({ prompt, model, effort: env.SUMMARY_EFFORT, cwd: scratch, signal })
- 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.
- if (languageDrifted(`${ask} ${last}`, headlineOf(r.text || ''))) {
- console.warn('[recap] one-shot language drift detected · retrying')
- r = await run({
- prompt: prompt + `\n\nRETRY: your previous output was NOT in the same language as the user's request ` +
- `and the assistant message. Rewrite it in exactly that language — same script and same diacritics — ` +
- `as one line.`,
- model,
- effort: env.SUMMARY_EFFORT,
- cwd: scratch,
- signal,
- })
- await cleanupRecapSession(engine, scratch, r.sessionId)
- }
-
- const recap = capRecap(headlineOf(r.text || ''), RECAP_MAX_WORDS)
- if (!recap) { console.warn('[recap] one-shot produced no usable recap (empty after cap)'); return null }
- // The body is the answer's own excerpt, never the model's — and of the whole answer (`text`), not
- // the tail the prompt was fed (`last`), so a very long answer excerpts from its start like local mode.
- const body = deriveTurnBody(text)
- return body ? `${recap}\n\n${body}` : recap
-}
diff --git a/cli/src/lib/voiceRouter.ts b/cli/src/lib/voiceRouter.ts
index 0d5603c6e..620b3718d 100644
--- a/cli/src/lib/voiceRouter.ts
+++ b/cli/src/lib/voiceRouter.ts
@@ -110,7 +110,7 @@ function ensureRouterConfigured(engine: RouterEngine): void {
}
/**
- * Tell the router which agents exist. Called from the same place the recap pool is synced, so the warm
+ * Tell the router which agents exist. Called whenever the active agents change, so the warm
* worker always belongs to an engine the machine really runs.
*/
export function setVoiceRouterSessions(sessions: Array<{ engine: string }>): void {