The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat(cli): add Kilo as the eleventh engine
0xken15a67e082b6e29
diff --git a/.github/assets/engines/README.md b/.github/assets/engines/README.mdindex b36225b91..07f478143 100644--- a/.github/assets/engines/README.md+++ b/.github/assets/engines/README.md@@ -28,6 +28,7 @@ a retina display.| `codex.png` | The transparent Codex product mark bundled as `codex-app-ga-logo--UgmJjKM.png` in the official `com.openai.codex` macOS app v`26.602.30954` | 104 | `8e82b26c98a10e45798ce48124515720657f7735fb8d0853b3f087eaa8a6b74e` || `muse.png` | The Meta mark from the official lockup SVG at `static.xx.fbcdn.net/rsrc.php/y3/r/y6QsbGgc866.svg` — wordmark paths dropped, glyph rasterised to 104×104, gradient kept | 104 | `d7c4568f992e60f6d42a7a819a5a782d479cbfd9ad2bc11e69c82b35b8a5d8fe` || `amp.png` | Amp's official app icon — the `apple-touch-icon` the site itself declares, <https://ampcode.com/app-icon.png?v=3>, fetched 2026-08-07 | 512 | `e5fc0d1178674b80c0dcbbf9811787b44df91f865fac9cd3ef44bb13ef728018` |+| `kilo.png` | Kilo's official app icon — the 512px `icon` the site itself declares, <https://kilo.ai/favicon/android-chrome-512x512.png?v=2>, fetched 2026-08-10 | 512 | `01d05e48efb03321468e1af0110d05de4550806f653b95adb93ad93a546fee7b` |Open items, recorded rather than left implicit:diff --git a/.github/assets/engines/kilo.png b/.github/assets/engines/kilo.pngnew file mode 100644index 000000000..d52f06c19Binary files /dev/null and b/.github/assets/engines/kilo.png differdiff --git a/README.md b/README.mdindex 7efdbedba..d449c5f58 100644--- a/README.md+++ b/README.md@@ -37,6 +37,8 @@ It drives the agents you already use:<img src=".github/assets/engines/muse.png" height="72" alt="Muse Code" title="Muse Code"> <img src=".github/assets/engines/amp.png" height="72" alt="Amp" title="Amp">+ + <img src=".github/assets/engines/kilo.png" height="72" alt="Kilo" title="Kilo"></p>## Add your agent to Harness@@ -84,7 +86,7 @@ Your agents stay your processes, on your hardware, with your credentials.`harness join` `harness join` your HTTP API│ │ │claude · codex hermes · muse agents running on- cursor · amp · … opencode · … your own servers+ cursor · amp · … opencode · kilo · … your own servers└───────── CLI ─────────┘ └─────── API ───────┘```diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 17af11abc..2bf118e16 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -28,6 +28,7 @@ import { codexMessagesToEvents, windowCodexLines } from './engines/codex/normaliimport { cursorMessagesToEvents, windowCursorLines } from './engines/cursor/normalizer.js'import { loadCursorReplayTaskLinks } from './engines/cursor/subagent.js'import { opencodeMessagesToEvents, windowOpencodeMessages } from './engines/opencode/normalizer.js'+import { kiloMessagesToEvents, windowKiloMessages } from './engines/kilo/normalizer.js'import { museMessagesToEvents } from './engines/muse/normalizer.js'import { ampMessagesToEvents } from './engines/amp/normalizer.js'import { ampThreadToEvents, readAmpThread } from './engines/amp/threadExport.js'@@ -38,6 +39,7 @@ import { devinMessagesToEvents, windowDevinMessages } from './engines/devin/normimport { readHermesMessages } from './engines/hermes/reader.js'import { readDevinMessages } from './engines/devin/reader.js'import { readOpencodeMessages } from './engines/opencode/reader.js'+import { readKiloMessages } from './engines/kilo/reader.js'import { E2eeManager, type PairResult } from './lib/e2ee/manager.js'import { ENCRYPTED_RPC_RESULT_TYPES, isEncryptedDownType, isWrapped } from './lib/e2ee/core.js'import { DEVICE_RECENT_SAFE_FRAME_BYTES, fitRecentReplyPayloadForDevice } from './lib/deviceRecentTrim.js'@@ -48,6 +50,8 @@ import { sid, preview } from './lib/log.js'// OpenCode has no per-session transcript file — its history is read from this SQLite store.const OPENCODE_DB = join(env.OPENCODE_DATA_DIR, 'opencode.db')+// Kilo keeps history the same way opencode does, in its own store.+const KILO_DB = join(env.KILO_DATA_DIR, 'kilo.db')const DEVIN_DB = join(env.DEVIN_HOME, 'sessions.db')// Hermes history likewise comes from a SQLite store, not a per-session file.const HERMES_DB = join(env.HERMES_HOME, 'state.db')@@ -121,11 +125,11 @@ async function ampHistory(sessionId: string, lines: string[]): Promise<SessionEvexport function deviceAgentListItem(raw: unknown,-): { id: unknown; name?: string; engine?: 'claude' | 'codex' | 'cursor' | 'opencode' | 'pi' | 'hermes' | 'commandcode' | 'devin' | 'muse' | 'amp'; selectedModel?: string | null } {+): { id: unknown; name?: string; engine?: 'claude' | 'codex' | 'cursor' | 'opencode' | 'pi' | 'hermes' | 'commandcode' | 'devin' | 'muse' | 'amp' | 'kilo'; selectedModel?: string | null } {const o = (raw ?? {}) as Record<string, unknown>- const item: { id: unknown; name?: string; engine?: 'claude' | 'codex' | 'cursor' | 'opencode' | 'pi' | 'hermes' | 'commandcode' | 'devin' | 'muse' | 'amp'; selectedModel?: string | null } = { id: o.id }+ const item: { id: unknown; name?: string; engine?: 'claude' | 'codex' | 'cursor' | 'opencode' | 'pi' | 'hermes' | 'commandcode' | 'devin' | 'muse' | 'amp' | 'kilo'; selectedModel?: string | null } = { id: o.id }if (typeof o.name === 'string') item.name = clipDeviceAgentName(o.name)- if (o.engine === 'claude' || o.engine === 'codex' || o.engine === 'cursor' || o.engine === 'opencode' || o.engine === 'pi' || o.engine === 'hermes' || o.engine === 'commandcode' || o.engine === 'devin' || o.engine === 'muse' || o.engine === 'amp') item.engine = o.engine+ if (o.engine === 'claude' || o.engine === 'codex' || o.engine === 'cursor' || o.engine === 'opencode' || o.engine === 'pi' || o.engine === 'hermes' || o.engine === 'commandcode' || o.engine === 'devin' || o.engine === 'muse' || o.engine === 'amp' || o.engine === 'kilo') item.engine = o.engine// Runtime model/effort profile (opaque runtime-v1:...) — lets the device render + change model/effort.if (typeof o.selectedModel === 'string' || o.selectedModel === null) item.selectedModel = o.selectedModelreturn item@@ -744,6 +748,31 @@ export class BackendSocket {reply(type, requestId, { id: sessionId, title: projectDisplayName(s), events, timestamp, engine: s.engine, hasMore: w.hasMore, oldestCursor: w.oldestCursor })return}+ if (s.engine === 'kilo') {+ // Kilo history likewise comes from its SQLite DB. BOTH branches below are load-bearing: the+ // web client always sends a `limit`, so handling only the full-transcript one opens an empty+ // pane — the exact half-dispatch this file has been caught on before. Cursors are namespaced+ // `kilo:<index>` by `windowKiloMessages`, so a cursor from another engine reads as stale+ // rather than silently indexing into the wrong conversation.+ const rawLimit = payload.limit+ const limit = typeof rawLimit === 'number' && rawLimit > 0 ? Math.min(Math.floor(rawLimit), 500) : undefined+ const before = typeof payload.before === 'string' ? payload.before : undefined+ const messages = await readKiloMessages(KILO_DB, sessionId)+ const timestamp = new Date(s.updatedAt).toISOString()+ if (!limit) {+ reply(type, requestId, { id: sessionId, title: projectDisplayName(s), events: kiloMessagesToEvents(messages), timestamp, engine: s.engine })+ return+ }+ const w = windowKiloMessages(messages, { limit, before })+ if (w.staleCursor) {+ reply(type, requestId, { id: sessionId, title: projectDisplayName(s), events: [], timestamp, engine: s.engine, hasMore: false, oldestCursor: null, staleCursor: true })+ return+ }+ const events = kiloMessagesToEvents(w.window)+ if (before && events[events.length - 1]?.type === 'done') events.pop()+ reply(type, requestId, { id: sessionId, title: projectDisplayName(s), events, timestamp, engine: s.engine, hasMore: w.hasMore, oldestCursor: w.oldestCursor })+ return+ }if (!s.transcriptPath) {reply(type, requestId, {id: sessionId,diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 6883bad73..7005250f9 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -24,7 +24,7 @@ import { homedir } from 'os'import { env } from './config/env.js'import { VERSION } from './version.js'import { registry, projectDisplayName, type RegisteredSession } from './lib/registry.js'-import { installAmpPlugin, installCodexHooks, installCommandCodeHooks, installCursorHooks, installDevinHooks, installHermesHooks, installOpencodePlugin, installPiExtension, installSessionHooks } from './lib/hooks.js'+import { installAmpPlugin, installCodexHooks, installCommandCodeHooks, installCursorHooks, installDevinHooks, installHermesHooks, installKiloPlugin, installOpencodePlugin, installPiExtension, installSessionHooks } from './lib/hooks.js'import { PID_FILE, TOKEN_FILE, daemonPort, isAlive, readPid } from './lib/daemonState.js'import { ENGINES, aliasesFor, engineBin, engineCommand, resolveEngine } from './lib/engineBin.js'import { refuseDuplicateAgent } from './lib/duplicateAgent.js'@@ -73,6 +73,8 @@ import { CursorTaskHookQueue } from './engines/cursor/taskHookQueue.js'import { loadCursorPendingTasks, removeCursorPendingTasks } from './engines/cursor/pendingTasks.js'import { OpencodeReader, readOpencodeMessages } from './engines/opencode/reader.js'import { lastOpencodeTurnText } from './engines/opencode/normalizer.js'+import { KiloReader, readKiloMessages } from './engines/kilo/reader.js'+import { lastKiloTurnText } from './engines/kilo/normalizer.js'import { MuseNormalizer, lastMuseTurnText, museMessagesToEvents } from './engines/muse/normalizer.js'import { AmpNormalizer, lastAmpTurnText, ampMessagesToEvents } from './engines/amp/normalizer.js'import { PiNormalizer, lastPiTurnText } from './engines/pi/normalizer.js'@@ -118,6 +120,8 @@ const COMPUTER_ID_FILE = join(env.ADAPTER_DATA_DIR, 'computer-id')const MACHINE_NAME_FILE = join(env.ADAPTER_DATA_DIR, 'machine-name')// OpenCode's SQLite store — polled per session by OpencodeReader (no per-session transcript file).const OPENCODE_DB = join(env.OPENCODE_DATA_DIR, 'opencode.db')+// Kilo's SQLite store — same shape, its own file and its own reader (see engines/kilo/).+const KILO_DB = join(env.KILO_DATA_DIR, 'kilo.db')// Hermes keeps every surface's history in one SQLite store — polled per session by HermesReader.const HERMES_DB = join(env.HERMES_HOME, 'state.db')// Devin likewise keeps all history in one SQLite store (WAL) — polled per session by DevinReader.@@ -153,6 +157,10 @@ ${ENGINES.map((e) => { const a = aliasesFor(e); return ` harness ${engineCommanTwo CLIs keep directory trust in their config rather than a flag — codex and devin ask "do you trustthis directory?" the first time you run one in a new directory. Answer it in the pane; harness willnot edit your config to skip it.+ Kilo is the exception with no bypass at all: it offers one on 'kilo run', but its interactive TUI —+ the thing harness starts — rejects the flag, so a kilo agent still stops at its own permission prompt.+ You can answer that prompt remotely from the web or the device; it arrives as a question, not as a+ tool card.Machine:harness join <token> connect this computer to an existing machine using the token from its machine page@@ -581,6 +589,7 @@ async function runForeground(token: string): Promise<void> {const codexNormalizers = new Map<string, CodexNormalizer>()const cursorNormalizers = new Map<string, CursorNormalizer>()const opencodeReaders = new Map<string, OpencodeReader>()+ const kiloReaders = new Map<string, KiloReader>()const piNormalizers = new Map<string, PiNormalizer>()const museNormalizers = new Map<string, MuseNormalizer>()const ampNormalizers = new Map<string, AmpNormalizer>()@@ -670,6 +679,7 @@ async function runForeground(token: string): Promise<void> {|| codexNormalizers.has(session.sessionId)|| cursorNormalizers.has(session.sessionId)|| opencodeReaders.has(session.sessionId)+ || kiloReaders.has(session.sessionId)|| piNormalizers.has(session.sessionId)|| museNormalizers.has(session.sessionId)|| ampNormalizers.has(session.sessionId)@@ -725,6 +735,17 @@ async function runForeground(token: string): Promise<void> {})opencodeReaders.set(session.sessionId, reader)await reader.start()+ } else if (session.engine === 'kilo') {+ // Kilo is opencode's fork and keeps the same store shape, so it is polled the same way — but from+ // its OWN db and through its own reader, so the two can diverge without one breaking the other.+ const reader = new KiloReader({+ dbPath: KILO_DB,+ sessionId: session.sessionId,+ onEvents: (events) => emitSessionEvents(session.sessionId, events),+ onFatal: (err) => console.warn(`[kilo] ${sid(session.sessionId)} ${err.message}`),+ })+ kiloReaders.set(session.sessionId, reader)+ await reader.start()} else if (session.engine === 'muse') {// Same JSONL tail as claude/pi; only the record shape differs.const normalizer = new MuseNormalizer()@@ -875,6 +896,7 @@ async function runForeground(token: string): Promise<void> {const s = registry.bySession(sessionId)if (!s) return nullif (s.engine === 'opencode') return lastOpencodeTurnText(await readOpencodeMessages(OPENCODE_DB, sessionId))+ if (s.engine === 'kilo') return lastKiloTurnText(await readKiloMessages(KILO_DB, sessionId))if (s.engine === 'hermes') return lastHermesTurnText(await readHermesMessages(HERMES_DB, sessionId))if (s.engine === 'devin') return lastDevinTurnText(await readDevinMessages(DEVIN_DB, sessionId))if (!s.transcriptPath) return null@@ -961,6 +983,7 @@ async function runForeground(token: string): Promise<void> {?? codexNormalizers.get(sessionId)?.turnOpen?? cursorNormalizers.get(sessionId)?.turnOpen?? opencodeReaders.get(sessionId)?.turnOpen+ ?? kiloReaders.get(sessionId)?.turnOpen?? piNormalizers.get(sessionId)?.turnOpen?? museNormalizers.get(sessionId)?.turnOpen?? ampNormalizers.get(sessionId)?.turnOpen@@ -1068,6 +1091,8 @@ async function runForeground(token: string): Promise<void> {cursorNormalizers.delete(sessionId)opencodeReaders.get(sessionId)?.stop()opencodeReaders.delete(sessionId)+ kiloReaders.get(sessionId)?.stop()+ kiloReaders.delete(sessionId)piNormalizers.delete(sessionId)museNormalizers.delete(sessionId)ampNormalizers.delete(sessionId)@@ -1497,6 +1522,7 @@ async function runForeground(token: string): Promise<void> {installCodexHooks(hookPort)installCursorHooks(hookPort)installOpencodePlugin(hookPort)+ installKiloPlugin(hookPort)installPiExtension(hookPort)// Amp belongs here with the other plugin-based engines, and it was missed. It matters most after a// SELF-UPDATE: the daemon restarts, and this is what puts the new plugin on disk immediately rather@@ -1583,6 +1609,7 @@ async function runForeground(token: string): Promise<void> {?? codexNormalizers.get(session.sessionId)?.turnOpen?? cursorNormalizers.get(session.sessionId)?.turnOpen?? opencodeReaders.get(session.sessionId)?.turnOpen+ ?? kiloReaders.get(session.sessionId)?.turnOpen?? piNormalizers.get(session.sessionId)?.turnOpen?? museNormalizers.get(session.sessionId)?.turnOpen?? ampNormalizers.get(session.sessionId)?.turnOpendiff --git a/cli/src/config/env.ts b/cli/src/config/env.tsindex f2fefc864..da4becdd2 100644--- a/cli/src/config/env.ts+++ b/cli/src/config/env.ts@@ -112,6 +112,18 @@ const envSchema = z.object({OPENCODE_PLUGIN_DIR: z.string().default(join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'opencode', 'plugin')),+ // Kilo state root — the SQLite store lives at <KILO_DATA_DIR>/kilo.db. Kilo is an opencode fork and+ // keeps the same layout, but NOT the same overrides: measured on 7.4.20 via `kilo debug paths`, it+ // honours XDG_DATA_HOME and ignores both `KILO_DATA_DIR` and `OPENCODE_DATA_DIR`. So this variable+ // steers the ADAPTER's reads only; anything that has to move KILO's own writes (the recap one-shot)+ // must set XDG_DATA_HOME on the child instead — see `KiloWorker` in lib/oneshot.ts.+ KILO_DATA_DIR: z+ .string()+ .default(join(process.env.XDG_DATA_HOME || join(homedir(), '.local', 'share'), 'kilo')),+ // Kilo plugin dir the adapter drops its discovery plugin into (honors XDG_CONFIG_HOME — measured).+ KILO_PLUGIN_DIR: z+ .string()+ .default(join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'kilo', 'plugin')),// Pi state root. Session transcripts live under <PI_HOME>/agent/sessions/--<mangled-cwd>--/*.jsonl and// the adapter's discovery extension is installed into <PI_HOME>/agent/extensions.PI_HOME: z.string().default(join(homedir(), '.pi')),@@ -176,6 +188,9 @@ const envSchema = z.object({MUSE_PATH: z.string().optional(),// Path to the `amp` CLI for Amp recap one-shots (else `amp` is resolved from PATH).AMP_PATH: z.string().optional(),+ // 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(),// 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.@@ -184,6 +199,8 @@ const envSchema = z.object({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(''),// 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).diff --git a/cli/src/engines/README.md b/cli/src/engines/README.mdindex 0dbe5c4c2..8f1a46e7d 100644--- a/cli/src/engines/README.md+++ b/cli/src/engines/README.md@@ -56,6 +56,45 @@ first. Everything else follows from the recording.---+## When your agent is a FORK of one already here++Kilo is opencode's fork: same commands, same `~/.local/share/<name>/<name>.db`, same+`{type:'text'|'reasoning'|'step-start'|'step-finish'}` parts, and its own log lines still say+`opencode`. That looks like the cheapest integration possible, and mostly it is — but it is also the+one where the one rule above is easiest to skip, because everything *seems* already known.++Copy the module, then re-measure it. `engines/kilo/` is a deliberate duplicate of `engines/opencode/`+rather than a shared abstraction: the forks are free to drift, and the duplication is where that drift+is allowed to land. Every place the two already differ was found by measuring, and every one of them+fails silently if inherited unchanged:++- **The model-catalog regex.** Opencode's character class has neither `~` nor `:`. On kilo's real+ catalog that silently dropped 23 of 299 ids — every floating `~vendor/model-latest` alias and every+ `:free` / `:discounted` variant — including the model the live session was actually running. The+ picker would simply not have listed the user's own model.+- **The pane footer.** Opencode's resolver anchors on its `Build`/`Plan` agent names. Kilo's agent is+ `code`, so the inherited function matched nothing and returned null forever: a blank model chip, no+ error anywhere. It had to be rewritten, not renamed.+- **The permission flag.** Opencode takes `--auto`. Kilo documents `--auto` on its `run` subcommand+ but its TUI *rejects* it — so inheriting the flag would not have loosened permissions, it would have+ stopped the agent from starting. Note that a non-TTY check cannot tell you this: with stdin closed,+ a real flag and an invented one both print the same usage block. Test permission flags on a real TTY+ inside tmux, with a control run.+- **The ask-the-user dialog.** Opencode draws Claude's numbered dialog inside a box. Kilo draws an+ unnumbered row of options laid out *horizontally*, sharing its line with the key hints, and walked+ with `Right` rather than `Down`. Same product lineage, completely different parser.+- **The turn boundary.** Kilo ends a refused turn with no `step-finish reason:'stop'` at all. Read+ only by opencode's stop rule, that turn never closes: the device tile spins forever and no recap+ runs. The refusal itself had to become a boundary.++Two of those (the catalog and the footer) would have shipped as "working" under any test written from+the parent engine's fixtures. So: inherit the *structure*, measure the *values*. And where a fork's+directory layout matches, check the ENV OVERRIDES separately — kilo honours `XDG_DATA_HOME` and+ignores the `<ENGINE>_DATA_DIR` variable its parent uses, which is the difference between a recap+running in a scratch directory and a recap writing into the user's real store.++---+## When your agent writes nothing to diskThis page assumes Harness can read a transcript your agent already writes. Amp is the case wherediff --git a/cli/src/engines/kilo/askQuestion.spec.ts b/cli/src/engines/kilo/askQuestion.spec.tsnew file mode 100644index 000000000..ecb7b7b6b--- /dev/null+++ b/cli/src/engines/kilo/askQuestion.spec.ts@@ -0,0 +1,59 @@+import { describe, expect, it } from 'vitest'+import { readFileSync } from 'fs'+import { fileURLToPath } from 'url'+import { kiloSelectionKeys, parseKiloQuestionPane } from './askQuestion.js'+import type { QuestionView } from '../../lib/askQuestion.js'++/**+ * A REAL kilo 7.4.20 permission prompt, captured with `tmux capture-pane -p` from a live pane and scrubbed+ * of the home directory. It was triggered the way a web-driven agent triggers it by accident: asking kilo+ * to read a path outside the project, which its default `external_directory: ask` rule blocks.+ */+function pane(): string {+ return readFileSync(fileURLToPath(new URL('../../lib/__fixtures__/question-kilo.txt', import.meta.url)), 'utf-8')+}++describe('kilo permission dialog', () => {+ it('reads the prompt as a question, not as a tool card', () => {+ const view = parseKiloQuestionPane(pane()) as QuestionView+ expect(view?.kind).toBe('question')+ // The question is the request itself — not the box heading above it, and not the `Patterns` list below.+ expect(view.question).toBe('Access external directory /private/etc')+ })++ it('reads the options off the line they SHARE with the key hints', () => {+ const view = parseKiloQuestionPane(pane()) as QuestionView+ expect(view.rows.map((r) => r.label)).toEqual(['Allow once', 'Allow always', 'Reject'])+ // `ctrl+f fullscreen`, `⇆ select` and `enter confirm` sit on the same line; offering any of them as an+ // answer would put a keybinding on the device's question screen.+ expect(view.rows.some((r) => /ctrl|select|confirm|fullscreen/i.test(r.label))).toBe(false)+ })++ it('keeps a way to say no', () => {+ const view = parseKiloQuestionPane(pane()) as QuestionView+ expect(view.rows.map((r) => r.label)).toContain('Reject')+ // Single-select, and no free-text row: every option is chosen, none is typed into.+ expect(view.multi).toBe(false)+ expect(view.typeRow).toBeNull()+ })++ /**+ * The walk is HORIZONTAL. Verified against the live pane: pressing `Right` twice moved kilo's amber+ * highlight from `Allow once` onto `Reject`, and `Enter` then dismissed the dialog and let the turn+ * finish. `Down` does nothing here — the rows are side by side, not stacked.+ */+ it('turns a row into the keystrokes that reach it', () => {+ const view = parseKiloQuestionPane(pane()) as QuestionView+ expect(kiloSelectionKeys(view.rows[0])).toEqual(['Enter'])+ expect(kiloSelectionKeys(view.rows[1])).toEqual(['Right', 'Enter'])+ expect(kiloSelectionKeys(view.rows[2])).toEqual(['Right', 'Right', 'Enter'])+ })++ it('reports no dialog when there is none', () => {+ expect(parseKiloQuestionPane('just some output\n$ ')).toBeNull()+ // A box that explains its own keys but is not a permission prompt must not be answered blindly.+ expect(parseKiloQuestionPane('┃ △ Something Else\n┃ Yes No enter confirm')).toBeNull()+ // The title alone is not enough either — without options there is nothing to answer with.+ expect(parseKiloQuestionPane('┃ △ Permission required\n┃ Access external directory /tmp')).toBeNull()+ })+})diff --git a/cli/src/engines/kilo/askQuestion.ts b/cli/src/engines/kilo/askQuestion.tsnew file mode 100644index 000000000..cd9869f03--- /dev/null+++ b/cli/src/engines/kilo/askQuestion.ts@@ -0,0 +1,126 @@+/**+ * Kilo's ask-the-user dialog — which, like amp's, is a PERMISSION prompt rather than a question tool.+ *+ * This is the one place kilo's pane diverges hardest from the opencode it forked. OpenCode draws Claude's+ * numbered dialog inside a box, so the shared parser fits once the border is peeled. Kilo does not: it+ * lays its options out HORIZONTALLY on a single line, unnumbered, sharing that line with the key hints.+ * Captured live from a real pane (an `external_directory` rule set to `ask`, which is kilo's default for+ * anything outside the project — so this prompt is not an edge case, it is what a web-driven agent hits+ * the first time it reads a path outside its own directory):+ *+ * ┃ △ Permission required+ * ┃ ← Access external directory /private/etc+ * ┃+ * ┃ Patterns+ * ┃+ * ┃ - /private/etc/*+ * ┃+ * ┃ Allow once Allow always Reject ctrl+f fullscreen ⇆ select enter confirm+ *+ * Four measured properties drive everything below:+ *+ * - **Options and footer share one line**, separated from each other by runs of spaces. Splitting on+ * whitespace alone would hand the device `ctrl+f fullscreen` as a selectable answer, so the hint+ * segments are removed by name before the labels are read.+ * - **The options are not numbered**, so nothing can be answered by pressing a digit. `number` carries+ * the row's INDEX and `kiloSelectionKeys` turns it into a walk — with `Right`, not `Down`: the footer+ * says `⇆ select`, and the layout is horizontal.+ * - **The selected row is marked only in ANSI.** Verified against the raw capture: `Allow once` is drawn+ * on the amber accent background (`48;2;204;167;0`) while the others sit on grey. A plain+ * `capture-pane -p` keeps none of that, so the walk assumes the dialog opens on the FIRST row — the+ * same assumption amp's parser makes, and the reason a walk is computed rather than a jump.+ * - **The box has a left rail only** (`┃`), not a full border, so peeling is one-sided.+ *+ * `Reject` is kept for the same reason amp's `Reject with feedback` is: dropping it would leave a device+ * user two ways to say yes and none to say no. Neither of the "allow" rows is preferred here — choosing+ * between "once" and "always" is a policy decision that belongs to the person, not to this parser.+ */++import type { PaneView, QuestionRow } from '../../lib/askQuestion.js'++/** `enter confirm` is the stable half of the footer; `⇆ select` is dropped first on a narrow pane. */+const FOOTER_RE = /enter\s+confirm/i+/** The title is what proves this is a permission prompt and not another box explaining its own keys. */+const TITLE_RE = /permission required/i+/** Key hints living on the options line. Matched as whole segments so a real label is never eaten. */+const HINT_RE = /^(ctrl\+\w+|esc|tab|enter|⇆|↑|↓|←|→|shift)\b/i+/** An option label: a short capitalised phrase. `Allow once` / `Allow always` / `Reject`, measured. */+const LABEL_RE = /^[A-Z][\w][\w ]{0,38}$/++function stripAnsi(text: string): string {+ // eslint-disable-next-line no-control-regex+ return text.replace(/\x1b?\[[0-9;?]*[A-Za-z]/g, '')+}++/** Peel kilo's left rail and any trailing rail/scrollbar glyphs. */+function unbox(line: string): string {+ return line+ .replace(/^[^│┃|]*[│┃|]/, '')+ .replace(/[│┃|█▌▐▁▂▃▄▅▆▇]+\s*$/, '')+ .trimEnd()+}++/** Split the options line into segments and keep only the ones that are actually options. */+function labelsFrom(line: string): string[] {+ return line+ .split(/\s{2,}/)+ .map((segment) => segment.trim())+ .filter((segment) => segment && !HINT_RE.test(segment) && LABEL_RE.test(segment))+}++/**+ * The keystrokes that select one row: walk right to it, then commit.+ *+ * Returned as a list because `sendKey` sends exactly one tmux key name per call.+ */+export function kiloSelectionKeys(row: QuestionRow): string[] {+ const index = Number(row.number)+ const steps = Number.isFinite(index) && index > 0 ? index : 0+ return [...Array(steps).fill('Right'), 'Enter']+}++export function parseKiloQuestionPane(capture: string): PaneView {+ const raw = stripAnsi(capture).split('\n')+ // Anchor on the LAST dialog: a prompt already answered stays in the scrollback above the live one.+ let footer = -1+ for (let i = raw.length - 1; i >= 0; i--) {+ if (FOOTER_RE.test(raw[i])) { footer = i; break }+ }+ if (footer < 0) return null+ let title = -1+ for (let i = footer; i >= 0 && footer - i < 40; i--) {+ if (TITLE_RE.test(raw[i])) { title = i; break }+ }+ if (title < 0) return null++ // Options normally share the footer line. On a pane too narrow to fit both, the hints wrap away and the+ // labels are the last content line above — so fall back to that rather than reporting no dialog.+ let labels = labelsFrom(unbox(raw[footer]))+ if (labels.length < 2) {+ for (let i = footer - 1; i > title; i--) {+ const line = unbox(raw[i])+ if (!line.trim()) continue+ labels = labelsFrom(line)+ break+ }+ }+ if (labels.length < 2) return null++ const rows: QuestionRow[] = labels.map((label, index) => ({+ number: String(index),+ label,+ checked: false,+ }))++ // What is being permitted: the first content line under the title, minus the `←` bullet kilo draws on+ // it. Best-effort — the row list is what the answer actually depends on.+ let question = ''+ for (let i = title + 1; i < footer; i++) {+ const line = unbox(raw[i]).trim().replace(/^[←→‣>•-]\s*/, '').trim()+ if (!line) continue+ question = line+ break+ }++ return { kind: 'question', question: question || 'Permission required', rows, multi: false, typeRow: null }+}diff --git a/cli/src/engines/kilo/normalizer.spec.ts b/cli/src/engines/kilo/normalizer.spec.tsnew file mode 100644index 000000000..29d29a047--- /dev/null+++ b/cli/src/engines/kilo/normalizer.spec.ts@@ -0,0 +1,150 @@+import { describe, expect, it } from 'vitest'+import { readFileSync } from 'fs'+import { fileURLToPath } from 'url'+import {+ isPermissionRejection,+ kiloMessagesToEvents,+ kiloToolName,+ lastKiloTurnText,+ windowKiloMessages,+ type KiloMessage,+} from './normalizer.js'++/**+ * A REAL kilo 7.4.20 session, exported from this machine's own `kilo.db` with the home directory+ * scrubbed. Two turns were driven by hand in a tmux pane: one that read a file and wrote a todo list,+ * and one whose file read was REFUSED at kilo's permission prompt. Nothing here is hand-written, which+ * is the point — every tool id and field name below is what kilo actually stored.+ */+function session(): KiloMessage[] {+ const p = fileURLToPath(new URL('../../lib/__fixtures__/kilo-session.json', import.meta.url))+ return JSON.parse(readFileSync(p, 'utf-8')) as KiloMessage[]+}++describe('kilo normalizer — replay', () => {+ it('renders the measured session as a conversation', () => {+ const events = kiloMessagesToEvents(session())+ expect(events.map((e) => e.type)).toEqual([+ 'user_message',+ 'thinking_delta', 'tool_start', 'tool_end',+ 'thinking_delta', 'tool_start', 'tool_end',+ 'thinking_delta', 'text_delta',+ 'user_message',+ 'thinking_delta', 'tool_start', 'tool_end',+ 'done',+ ])+ expect(events[0]).toMatchObject({ payload: { content: expect.stringContaining('read notes.txt') } })+ })++ /**+ * ONE user message produced THREE assistant messages here. Replay must not invent a turn boundary+ * between them — the conversation is one exchange, and the reader (not this path) owns turn frames.+ */+ it('replays as a conversation, not as a turn lifecycle', () => {+ // ONE user message produced THREE assistant messages here, and replay must not invent boundaries+ // between them. The replay type has no turn frames at all — that asserting one does not even+ // typecheck is the real guarantee; this checks the count the surfaces actually render.+ const events = kiloMessagesToEvents(session())+ expect(events.filter((e) => e.type === 'user_message')).toHaveLength(2)+ expect(events[events.length - 1]).toMatchObject({ type: 'done' })+ })++ it('maps the measured tool ids onto the shared vocabulary', () => {+ const events = kiloMessagesToEvents(session())+ const tools = events.filter((e) => e.type === 'tool_start')+ .map((e) => (e as { payload: { tool: string } }).payload.tool)+ // `read` and `todowrite` are what kilo actually called — not names borrowed from another engine.+ expect(tools).toEqual(['Read', 'TodoWrite', 'Read'])+ })++ /**+ * The device checklist reads `input.todos[].content` literally. Kilo already speaks that shape, so the+ * assertion here is that nothing reshapes it away — a rename would empty the checklist with no error.+ */+ it("hands the checklist kilo's todos under the field the device reads", () => {+ const start = kiloMessagesToEvents(session())+ .find((e) => e.type === 'tool_start' && (e as { payload: { tool: string } }).payload.tool === 'TodoWrite')+ const input = (start as { payload: { input: { todos: Array<{ content: string; status: string }> } } }).payload.input+ expect(input.todos).toHaveLength(3)+ expect(input.todos[0].content).toBe('Review and organize files in /private/tmp/kilo-probe')+ expect(input.todos[0].status).toBe('pending')+ })++ it('marks the refused tool as an error rather than a silent success', () => {+ const ends = kiloMessagesToEvents(session()).filter((e) => e.type === 'tool_end')+ const last = ends[ends.length - 1] as { payload: { isError: boolean; output: string } }+ expect(last.payload.isError).toBe(true)+ expect(last.payload.output).toContain('rejected permission')+ })+})++/**+ * The refusal is a turn BOUNDARY, and it is the one kilo never writes a `step-finish reason:'stop'` for.+ * These two cases are what stop a refused turn from spinning the device tile forever.+ */+describe('kilo permission refusal', () => {+ it('recognises the refusal kilo actually wrote', () => {+ const refused = session()[5].parts.find((p) => p.type === 'tool')!+ expect(isPermissionRejection(refused)).toBe(true)+ })++ it('does NOT treat an ordinary tool failure as the end of a turn', () => {+ // A failing command is handed back to the model and it carries on; closing here would cut turns off+ // mid-flight. Only a refusal stops kilo.+ expect(isPermissionRejection({+ id: 'prt_x',+ type: 'tool',+ data: { type: 'tool', tool: 'bash', state: { status: 'error', error: 'command not found: frobnicate' } },+ })).toBe(false)+ expect(isPermissionRejection({+ id: 'prt_y', type: 'text', data: { type: 'text', text: 'rejected permission' },+ })).toBe(false)+ })+})++describe('kilo recap source', () => {+ it('reads the last prompt and the answer that followed it', () => {+ // Drop the refused exchange: this is the last turn that actually answered.+ const answered = session().slice(0, 4)+ const last = lastKiloTurnText(answered)+ expect(last?.userMessage).toContain('read notes.txt')+ expect(last?.assistantText).toContain('alpha')+ })++ /**+ * Measured, and deliberate: the refused turn produced no assistant text, and the recap reports NOTHING+ * rather than re-summarising the previous turn. A recap sourced from the wrong turn is the classic+ * symptom of a last-turn tracker resetting on the wrong record, so an empty answer is the honest one.+ */+ it('reports nothing when the last turn was refused and said nothing', () => {+ expect(lastKiloTurnText(session())).toBeNull()+ })++ it('reports nothing for a session with no assistant text at all', () => {+ expect(lastKiloTurnText([])).toBeNull()+ })+})++describe('kilo history window', () => {+ it('namespaces its cursor so another engine cannot index into it', () => {+ const w = windowKiloMessages(session(), { limit: 2 })+ expect(w.oldestCursor).toMatch(/^kilo:\d+$/)+ expect(w.hasMore).toBe(true)+ // An opencode cursor is not a kilo cursor, even though the two stores are shaped the same.+ expect(windowKiloMessages(session(), { limit: 2, before: 'opencode:3' }).staleCursor).toBe(true)+ })++ it('snaps the window back to a user message so a turn is never split', () => {+ const w = windowKiloMessages(session(), { limit: 2 })+ expect(w.window[0].role).toBe('user')+ })+})++describe('kilo tool names', () => {+ it('title-cases an id it has never seen instead of guessing at it', () => {+ // The measured ids are asserted above. An unmeasured one must render plainly rather than land on+ // some other engine's card by accident.+ expect(kiloToolName('frobnicate')).toBe('Frobnicate')+ expect(kiloToolName('')).toBe('tool')+ })+})diff --git a/cli/src/engines/kilo/normalizer.ts b/cli/src/engines/kilo/normalizer.tsnew file mode 100644index 000000000..3ed06b0a6--- /dev/null+++ b/cli/src/engines/kilo/normalizer.ts@@ -0,0 +1,323 @@+/**+ * Kilo → web ServerEvent conversion.+ *+ * Unlike claude/codex/cursor, Kilo does NOT write a per-session transcript file — it persists+ * `session`/`message`/`part` rows in a SQLite DB (`~/.local/share/kilo/kilo.db`). The live+ * tailer is `KiloReader` (polls the DB); this module holds the pure row→event mapping it shares+ * with the replay / recap paths (`session_get`, device recap).+ *+ * Kilo is a FORK of opencode (`kilo --help` still logs `opencode`, and the two CLIs' command sets match),+ * so this module is a sibling of `engines/opencode/` rather than a shared abstraction: the forks are free+ * to drift and the duplication is where that drift is allowed to land. Where the two already differ is+ * recorded at the point of difference, not assumed away.+ *+ * On-disk shapes, read off a REAL kilo 7.4.20 session in this machine's own `kilo.db`:+ * session.id = `ses_024a007fdffe11yG68JPxsHJly` (the `ses_` prefix is what `RESUME_ARGS` matches)+ * message.data = { role:'user'|'assistant', parentID?, agent:'code', mode:'code', variant?:'medium',+ * model:{providerID:'kilo',modelID}, path:{cwd,root}, tokens{…},+ * time:{created,completed}, finish:'stop' }+ * part.data = discriminated by `type`:+ * text{text} · reasoning{text,time,metadata.openrouter.reasoning_details} · step-start{time} ·+ * step-finish{reason, time, model, tokens, cost} ·+ * tool{tool, state:{status:'completed', input, output}}+ *+ * ONE user message can produce SEVERAL assistant messages — measured: a two-tool turn wrote three, each+ * with its own step-start/step-finish pair. Only the LAST carries `reason:'stop'`; the intermediate ones+ * carry `reason:'tool-calls'` (mirrored by `message.data.finish`). That is what makes `reason === 'stop'`+ * the correct turn boundary and why counting `step-finish` parts would close the turn two steps early.+ *+ * Both stores carry the legacy `message`/`part` tables AND the newer `session_message` table; measured on+ * kilo 7.4.20, the conversation is in `message`/`part` (4 messages, 10 parts) and `session_message` held+ * only a single `model-switched` row. So `message`/`part` stay the cursor, as they are for opencode.+ */++import type { LastTurnText, SessionEvent, SubagentSummary } from '../../lib/normalize.js'++export const MAX_OUTPUT = 2_000+export const MAX_THINKING = 500++export interface KiloPart {+ id: string+ type: string+ data: Record<string, unknown>+}++export interface KiloMessage {+ id: string+ role: string+ timeCreated: number+ data: Record<string, unknown>+ parts: KiloPart[]+}++export function object(value: unknown): Record<string, unknown> | null {+ return value !== null && typeof value === 'object' && !Array.isArray(value)+ ? value as Record<string, unknown>+ : null+}++export function str(value: unknown): string {+ return typeof value === 'string' ? value : ''+}++export function clip(value: string, limit: number): string {+ return value.length > limit ? `${value.slice(0, limit)}\n…[truncated]` : value+}++/**+ * Kilo tool ids → the Claude vocabulary the UI renders.+ *+ * CONFIRMED on a real kilo 7.4.20 turn: `read` and `todowrite` fired with exactly these ids, and+ * `todowrite`'s arguments are `{todos:[{content, status, priority}]}` — `content` is already the field+ * the device checklist reads, so the tool NAME is the only translation kilo needs and no argument+ * reshape belongs here. Tool output arrives as a plain string (`read` returns an XML-ish+ * `<path>…</path><content>…</content>` blob, `todowrite` a JSON array), which `toolOutputText` passes+ * through unchanged.+ *+ * The REMAINING ids are inherited from opencode and are not individually confirmed on kilo. The two that+ * were checked both matched, which is decent evidence for a fork — but rule zero is that a tool named by+ * analogy fails SILENTLY, so treat a surface that renders nothing as a wrong id here rather than a bug in+ * the surface. The unknown-id fall-through title-cases instead of guessing, keeping a mismatch plain+ * rather than confidently wrong.+ */+const TOOL_NAMES: Record<string, string> = {+ bash: 'Bash',+ edit: 'Edit',+ multiedit: 'Edit',+ patch: 'Edit',+ write: 'Write',+ read: 'Read',+ grep: 'Grep',+ glob: 'Glob',+ list: 'LS',+ ls: 'LS',+ webfetch: 'WebFetch',+ websearch: 'WebSearch',+ todowrite: 'TodoWrite',+ todoread: 'TodoRead',+ task: 'Task',+ // On opencode this is `question`, whose arguments already arrive in the claude shape+ // (`{questions:[{question, header, options:[{label, description}]}]}`) so the NAME is the only+ // translation needed. Whether kilo kept the id, the argument shape, or the tool at all is unmeasured —+ // and this is the entry that matters most, because a question that renders as a tool card is a dialog+ // nobody can answer, i.e. an agent that looks hung.+ question: 'AskUserQuestion',+}++export function kiloToolName(name: string): string {+ const key = name.toLowerCase()+ if (TOOL_NAMES[key]) return TOOL_NAMES[key]+ return name ? name.charAt(0).toUpperCase() + name.slice(1) : 'tool'+}++export function toolOutputText(value: unknown): string {+ if (typeof value === 'string') return value+ if (value == null) return ''+ const o = object(value)+ if (o && typeof o.text === 'string') return o.text+ try { return JSON.stringify(value) ?? '' } catch { return String(value) }+}++/**+ * The text a finished tool card shows.+ *+ * Kilo puts a FAILURE's explanation in `state.error` and leaves `state.output` empty — measured on a+ * refused permission, where reading `output` alone drew a red card with nothing written on it. Prefer the+ * output, fall back to the error, so a failure always says why.+ */+export function toolResultText(state: Record<string, unknown>): string {+ return toolOutputText(state.output) || str(state.error)+}++export function toolSummary(name: string, output: string, isError: boolean): string {+ const first = output.split('\n').map((line) => line.trim()).find(Boolean) ?? ''+ if (isError) return first ? `${name} failed: ${first}` : `${name} failed`+ return first || `${name} completed`+}++/** The plain text of a user message (its `text` parts joined). */+export function userMessageText(msg: KiloMessage): string {+ return msg.parts+ .filter((p) => p.type === 'text')+ .map((p) => str(p.data.text))+ .filter(Boolean)+ .join('\n')+ .trim()+}++/** Assistant text (its `text` parts joined) — for recap. */+export function assistantMessageText(msg: KiloMessage): string {+ return msg.parts+ .filter((p) => p.type === 'text')+ .map((p) => str(p.data.text))+ .filter(Boolean)+ .join('')+ .trim()+}++/** A completed assistant message has a `step-finish` part with reason `stop`. */+export function isAssistantDone(msg: KiloMessage): boolean {+ return msg.parts.some((p) => p.type === 'step-finish' && str(p.data.reason) === 'stop')+}++/** Aggregates read from a sub-agent's OWN (child) kilo session. */+export interface ChildStats { totalToolUseCount: number; totalTokens?: number }++/**+ * A tool part that failed because the person said no.+ *+ * This is a turn BOUNDARY on kilo, which is why it needs naming. Measured on a live pane: refusing a+ * permission prompt leaves the tool part `status:'error'` with this message, the enclosing step finishes+ * with `reason:'tool-calls'`, the agent goes idle — and NO `step-finish reason:'stop'` is ever written.+ * Read only by the `stop` rule, that turn stays open forever: the device tile spins on `processing`, no+ * recap runs, and the store looks identical to a turn that is still thinking. Confirmed by re-reading the+ * store minutes later with the composer back at idle.+ *+ * Deliberately narrower than "the tool errored". An ordinary tool failure (missing file, bad command) is+ * handed back to the model and it carries on, so closing on any error would end turns mid-flight. Only a+ * refusal stops kilo, which is also what the headless path reports in its own words: `run ended with an+ * auto-rejected permission`.+ */+const PERMISSION_REJECTED_RE = /rejected permission|permission (?:was )?denied|auto-rejected permission/i++export function isPermissionRejection(part: KiloPart): boolean {+ if (part.type !== 'tool') return false+ const state = object(part.data.state) ?? {}+ if (str(state.status) !== 'error') return false+ return PERMISSION_REJECTED_RE.test(str(state.error))+}++export function isTaskPart(part: KiloPart): boolean {+ return part.type === 'tool' && str(part.data.tool).toLowerCase() === 'task'+}++/** The `<task_result>…</task_result>` body of a Task tool's output, else the raw text. */+export function extractTaskResult(output: string): string {+ const m = /<task_result>\s*([\s\S]*?)\s*<\/task_result>/.exec(output)+ return (m ? m[1] : output).trim()+}++/** Kilo's `task` tool spawns a sub-agent (a child session). Render it like Claude/Codex Task cards. */+export function taskStartEvent(part: KiloPart): SessionEvent {+ const input = object((object(part.data.state) ?? {}).input) ?? {}+ const description = str(input.description) || str(input.prompt).slice(0, 80) || 'Delegated task'+ const subagentType = str(input.subagent_type) || 'agent'+ return { type: 'tool_start', payload: { id: part.id, tool: 'Task', input: { subagent_type: subagentType, description } } }+}++export function taskEndEvent(part: KiloPart, childStats?: ChildStats): SessionEvent {+ const state = object(part.data.state) ?? {}+ const input = object(state.input) ?? {}+ const meta = object(state.metadata) ?? {}+ const time = object(state.time) ?? {}+ const durationMs = (Number(time.end) || 0) - (Number(time.start) || 0)+ const output = extractTaskResult(toolOutputText(state.output))+ const isError = str(state.status) === 'error'+ const subagent: SubagentSummary = {+ agentId: str(meta.sessionId) || undefined,+ agentType: str(input.subagent_type) || 'agent',+ totalToolUseCount: childStats?.totalToolUseCount ?? 0,+ totalTokens: childStats?.totalTokens ?? 0,+ totalDurationMs: durationMs > 0 ? durationMs : 0,+ }+ return {+ type: 'tool_end',+ payload: { id: part.id, tool: 'Task', output: clip(output, MAX_OUTPUT), isError, summary: toolSummary('Task', output, isError), subagent },+ }+}++/** Replay events for one assistant `tool` part. In-flight tools emit only `tool_start`. */+export function toolPartEvents(part: KiloPart): SessionEvent[] {+ const state = object(part.data.state) ?? {}+ const status = str(state.status)+ const done = status === 'completed' || status === 'error'+ if (isTaskPart(part)) return done ? [taskStartEvent(part), taskEndEvent(part)] : [taskStartEvent(part)]+ const name = kiloToolName(str(part.data.tool))+ const id = part.id+ const start: SessionEvent = {+ type: 'tool_start',+ payload: { id, tool: name, input: state.input ?? {} },+ }+ if (!done) return [start]+ const output = toolResultText(state)+ const isError = status === 'error'+ return [start, {+ type: 'tool_end',+ payload: { id, tool: name, output: clip(output, MAX_OUTPUT), isError, summary: toolSummary(name, output, isError) },+ }]+}++/** Replay events for one part (assistant blocks only). */+function partReplayEvents(part: KiloPart, thinking: { n: number }): SessionEvent[] {+ if (part.type === 'text') {+ const text = str(part.data.text)+ return text ? [{ type: 'text_delta', payload: { content: text } }] : []+ }+ if (part.type === 'reasoning') {+ const text = str(part.data.text)+ return text+ ? [{ type: 'thinking_delta', payload: { content: clip(text, MAX_THINKING), thinkingId: `thinking-kilo-${thinking.n++}` } }]+ : []+ }+ if (part.type === 'tool') return toolPartEvents(part)+ return []+}++/** Full-session replay (session_get) — same render path as the live stream. */+export function kiloMessagesToEvents(messages: KiloMessage[]): SessionEvent[] {+ const events: SessionEvent[] = []+ const thinking = { n: 0 }+ for (const msg of messages) {+ if (msg.role === 'user') {+ const text = userMessageText(msg)+ if (text) events.push({ type: 'user_message', payload: { content: text } })+ continue+ }+ for (const part of msg.parts) events.push(...partReplayEvents(part, thinking))+ }+ events.push({ type: 'done', payload: { result: 'success' } })+ return events+}++/** Last user prompt + the assistant text that followed it — the recap source of truth. */+export function lastKiloTurnText(messages: KiloMessage[]): LastTurnText | null {+ let userMessage = ''+ let assistantText = ''+ for (const msg of messages) {+ if (msg.role === 'user') {+ const text = userMessageText(msg)+ if (text) { userMessage = text; assistantText = '' }+ continue+ }+ const text = assistantMessageText(msg)+ if (text) assistantText += `${assistantText ? '\n\n' : ''}${text}`+ }+ return assistantText ? { userMessage, assistantText } : null+}++/**+ * Turn-snapped pagination window over the message list, for `session_get {limit, before}`.+ * `before` = `kilo:<index>` (exclusive upper bound = message index the client already holds).+ * The window start snaps back to a user message so a turn is never split.+ */+export function windowKiloMessages(+ messages: KiloMessage[],+ opts: { limit: number; before?: string },+): { window: KiloMessage[]; hasMore: boolean; oldestCursor: string | null; staleCursor?: boolean } {+ let endIndex = messages.length+ if (opts.before) {+ const match = /^kilo:(\d+)$/.exec(opts.before)+ if (!match) return { window: [], hasMore: false, oldestCursor: null, staleCursor: true }+ endIndex = Number(match[1])+ if (!Number.isSafeInteger(endIndex) || endIndex < 0 || endIndex > messages.length) {+ return { window: [], hasMore: false, oldestCursor: null, staleCursor: true }+ }+ }+ let start = Math.max(0, endIndex - opts.limit)+ while (start > 0 && messages[start].role !== 'user') start--+ return {+ window: messages.slice(start, endIndex),+ hasMore: start > 0,+ oldestCursor: `kilo:${start}`,+ }+}diff --git a/cli/src/engines/kilo/reader.ts b/cli/src/engines/kilo/reader.tsnew file mode 100644index 000000000..c61771678--- /dev/null+++ b/cli/src/engines/kilo/reader.ts@@ -0,0 +1,311 @@+/**+ * Kilo live tailer.+ *+ * Kilo has no per-session transcript file — it writes `message`/`part` rows to a SQLite DB. We+ * cannot byte-offset-tail it, so this reader **polls** the DB every ~1s via the `sqlite3` CLI (shelled+ * out, like tmux/git — keeps the adapter's single pure-JS bundle intact; no native SQLite dependency)+ * and diffs against per-part state to emit incremental `LiveEvent`s into the same+ * `emitSessionEvents` funnel the file-based engines use.+ *+ * Measured on kilo 7.4.20: the conversation is written to the legacy `message`/`part` tables, so those+ * are the primary cursor. Unlike opencode's store, kilo's `session_message` table is NOT empty — it held+ * one `model-switched` row — but it carries session METADATA, not turns, so the cursor does not move to+ * it. Its `seq` column is also nullable here where opencode's is `NOT NULL`, which is the reason not to+ * reach for it as an ordering key if that ever looks tempting.+ */++import { execFile } from 'child_process'+import { promisify } from 'util'+import type { LiveEvent } from '../../lib/normalize.js'+import {+ MAX_OUTPUT, MAX_THINKING, clip, object, str,+ kiloToolName, toolOutputText, toolResultText, toolSummary, userMessageText,+ isTaskPart, isPermissionRejection, taskStartEvent, taskEndEvent,+ type KiloMessage, type KiloPart, type ChildStats,+} from './normalizer.js'++const execFileAsync = promisify(execFile)++const ID_RE = /^[A-Za-z0-9_]+$/+const POLL_MS = 1_000+const MAX_BUFFER = 32 * 1024 * 1024++function parseJson(text: unknown): Record<string, unknown> {+ if (typeof text !== 'string') return object(text) ?? {}+ try { return object(JSON.parse(text)) ?? {} } catch { return {} }+}++interface Cursor { tc: number; id: string }++/**+ * Read messages (+ their parts) for one session from kilo.db via the `sqlite3` CLI.+ * `after` restricts to messages strictly after that boundary (for incremental polling).+ * Opens the DB with `query_only` + a busy timeout so it never contends with kilo's writer.+ * Throws `KiloSqliteMissing` if the `sqlite3` binary is absent.+ */+export async function readKiloMessages(+ dbPath: string,+ sessionId: string,+ after?: Cursor | null,+): Promise<KiloMessage[]> {+ if (!ID_RE.test(sessionId)) return []+ const cond = after && ID_RE.test(after.id) && Number.isFinite(after.tc)+ ? `AND (m.time_created > ${Math.trunc(after.tc)} OR (m.time_created = ${Math.trunc(after.tc)} AND m.id > '${after.id}'))`+ : ''+ const sql =+ `SELECT m.id AS mid, m.time_created AS mtc, m.data AS mdata, p.id AS pid, p.data AS pdata ` ++ `FROM message m LEFT JOIN part p ON p.message_id = m.id ` ++ `WHERE m.session_id = '${sessionId}' ${cond} ` ++ `ORDER BY m.time_created, m.id, p.time_created, p.id;`++ let stdout: string+ try {+ // `.timeout` is the silent dot-command form (the `PRAGMA busy_timeout=…` form prints a JSON row+ // under -json, which would corrupt the single-array parse below). query_only guards against writes.+ ({ stdout } = await execFileAsync(+ 'sqlite3',+ ['-json', '-cmd', '.timeout 3000', '-cmd', 'PRAGMA query_only=1', dbPath, sql],+ { maxBuffer: MAX_BUFFER },+ ))+ } catch (err) {+ if ((err as NodeJS.ErrnoException)?.code === 'ENOENT') throw new KiloSqliteMissing()+ return [] // db locked / transient — retry next tick+ }++ const trimmed = stdout.trim()+ if (!trimmed) return []+ let rows: Array<Record<string, unknown>>+ try { rows = JSON.parse(trimmed) } catch { return [] }++ const byId = new Map<string, KiloMessage>()+ const order: string[] = []+ for (const row of rows) {+ const mid = str(row.mid)+ if (!mid) continue+ let msg = byId.get(mid)+ if (!msg) {+ const mdata = parseJson(row.mdata)+ msg = { id: mid, role: str(mdata.role), timeCreated: Number(row.mtc) || 0, data: mdata, parts: [] }+ byId.set(mid, msg)+ order.push(mid)+ }+ const pid = str(row.pid)+ if (pid) {+ const pdata = parseJson(row.pdata)+ msg.parts.push({ id: pid, type: str(pdata.type), data: pdata })+ }+ }+ return order.map((id) => byId.get(id)!)+}++export class KiloSqliteMissing extends Error {+ constructor() { super('sqlite3 CLI not found on PATH — Kilo sessions cannot be mirrored') }+}++export interface KiloReaderDeps {+ dbPath: string+ sessionId: string+ onEvents: (events: LiveEvent[]) => void+ /** Reports the one-time fatal "sqlite3 missing" so the caller can warn + stop the reader. */+ onFatal?: (err: Error) => void+ pollMs?: number+}++/**+ * Is a message a closed boundary? user messages always are; assistants when `step-finish reason:stop` —+ * OR when a permission was refused, which is the other way a kilo turn ends and the only one that leaves+ * no `stop` behind (see `isPermissionRejection`). Without the second clause the cursor never advances+ * past a refused turn and the reader re-reads it on every poll.+ */+function isDone(msg: KiloMessage): boolean {+ if (msg.role !== 'assistant') return true+ if (msg.parts.some(isPermissionRejection)) return true+ return msg.parts.some((p) => p.type === 'step-finish' && str(p.data.reason) === 'stop')+}++export class KiloReader {+ private timer: NodeJS.Timeout | null = null+ private polling = false+ private open = false+ private thinking = 0+ private cursor: Cursor | null = null+ private readonly emittedText = new Map<string, number>() // partId → chars already emitted+ private readonly thinkingIds = new Map<string, string>() // reasoning partId → stable thinkingId+ private readonly toolStarted = new Set<string>()+ private readonly toolEnded = new Set<string>()+ private readonly seenUser = new Set<string>()++ constructor(private readonly deps: KiloReaderDeps) {}++ get turnOpen(): boolean { return this.open }+ closeTurn(): void { this.open = false }++ /** Hydrate silently (no replay), then start polling. */+ async start(): Promise<void> {+ try {+ const all = await readKiloMessages(this.deps.dbPath, this.deps.sessionId, null)+ this.hydrate(all)+ } catch (err) {+ if (err instanceof KiloSqliteMissing) { this.deps.onFatal?.(err); return }+ }+ this.timer = setInterval(() => { void this.tick() }, this.deps.pollMs ?? POLL_MS)+ }++ stop(): void {+ if (this.timer) { clearInterval(this.timer); this.timer = null }+ }++ /** Seed state from existing rows without emitting, so we only stream NEW activity after attach. */+ private hydrate(messages: KiloMessage[]): void {+ if (messages.length === 0) return+ // Find the last closed boundary; everything up to it is "already seen".+ let boundary = -1+ for (let i = messages.length - 1; i >= 0; i--) { if (isDone(messages[i])) { boundary = i; break } }+ const done = boundary >= 0 ? messages[boundary] : null+ this.cursor = done ? { tc: done.timeCreated, id: done.id } : null+ for (const msg of messages) {+ if (msg.role === 'user') this.seenUser.add(msg.id)+ for (const part of msg.parts) this.seedPart(part)+ }+ // A trailing in-flight assistant means a turn is open (attached mid-turn).+ const tail = messages[messages.length - 1]+ this.open = tail.role === 'assistant' && !isDone(tail)+ }++ private seedPart(part: KiloPart): void {+ if (part.type === 'text' || part.type === 'reasoning') {+ this.emittedText.set(part.id, str(part.data.text).length)+ } else if (part.type === 'tool') {+ this.toolStarted.add(part.id)+ const status = str((object(part.data.state) ?? {}).status)+ if (status === 'completed' || status === 'error') this.toolEnded.add(part.id)+ }+ }++ private async tick(): Promise<void> {+ if (this.polling) return+ this.polling = true+ try {+ const batch = await readKiloMessages(this.deps.dbPath, this.deps.sessionId, this.cursor)+ if (batch.length === 0) return+ const events: LiveEvent[] = []+ for (const msg of batch) events.push(...await this.processMessage(msg))+ // Advance the cursor past the trailing run of closed messages; keep an in-flight tail for re-read.+ for (let i = batch.length - 1; i >= 0; i--) {+ if (isDone(batch[i])) { this.cursor = { tc: batch[i].timeCreated, id: batch[i].id }; break }+ }+ if (events.length) this.deps.onEvents(events)+ } catch (err) {+ if (err instanceof KiloSqliteMissing) { this.stop(); this.deps.onFatal?.(err) }+ } finally {+ this.polling = false+ }+ }++ private async processMessage(msg: KiloMessage): Promise<LiveEvent[]> {+ if (msg.role === 'user') {+ if (this.seenUser.has(msg.id)) return []+ this.seenUser.add(msg.id)+ const events: LiveEvent[] = []+ if (this.open) events.push({ type: 'turn_ended', payload: {} })+ this.open = true+ events.push({ type: 'turn_started', payload: { userMessage: userMessageText(msg) } })+ return events+ }+ const events: LiveEvent[] = []+ for (const part of msg.parts) {+ if (isTaskPart(part)) events.push(...await this.processTaskPart(part))+ else events.push(...this.processPart(part))+ }+ return events+ }++ /** A `task` tool part spawns a sub-agent child session — emit Task start/end, reading the child+ * session for its tool-call count so the device/web Task card shows "N toolcalls" like the others. */+ private async processTaskPart(part: KiloPart): Promise<LiveEvent[]> {+ const state = object(part.data.state) ?? {}+ const events: LiveEvent[] = []+ const status = str(state.status)+ // kilo writes the part as soon as the tool call starts streaming, BEFORE its arguments are+ // filled in — so announcing on first sight labelled every sub-agent with the `Delegated task`+ // fallback (measured live: two parallel sub-agents, two identical rows). Wait for the input; the row+ // is worth nothing without its description, and it lands within the same poll or the next.+ const described = Object.keys(object(state.input) ?? {}).length > 0+ const settled = status === 'completed' || status === 'error'+ if (!this.toolStarted.has(part.id) && (described || settled)) {+ this.toolStarted.add(part.id)+ events.push(taskStartEvent(part))+ }+ if (settled && !this.toolEnded.has(part.id)) {+ this.toolEnded.add(part.id)+ const childId = str((object(state.metadata) ?? {}).sessionId)+ const childStats = childId ? await this.childStats(childId) : undefined+ events.push(taskEndEvent(part, childStats))+ }+ return events+ }++ private async childStats(childId: string): Promise<ChildStats> {+ try {+ const msgs = await readKiloMessages(this.deps.dbPath, childId)+ let tools = 0+ let tokens = 0+ for (const m of msgs) {+ for (const p of m.parts) if (p.type === 'tool' && !isTaskPart(p)) tools+++ const t = object(m.data.tokens) ?? {}+ tokens += (Number(t.input) || 0) + (Number(t.output) || 0)+ }+ return { totalToolUseCount: tools, totalTokens: tokens || undefined }+ } catch { return { totalToolUseCount: 0 } }+ }++ private processPart(part: KiloPart): LiveEvent[] {+ if (part.type === 'text') {+ const full = str(part.data.text)+ const seen = this.emittedText.get(part.id) ?? 0+ if (full.length <= seen) return []+ this.emittedText.set(part.id, full.length)+ return [{ type: 'text_delta', payload: { content: full.slice(seen) } }]+ }+ if (part.type === 'reasoning') {+ const full = str(part.data.text)+ const seen = this.emittedText.get(part.id) ?? 0+ if (full.length <= seen) return []+ this.emittedText.set(part.id, full.length)+ let thinkingId = this.thinkingIds.get(part.id)+ if (!thinkingId) { thinkingId = `thinking-kilo-${this.thinking++}`; this.thinkingIds.set(part.id, thinkingId) }+ return [{ type: 'thinking_delta', payload: { content: clip(full.slice(seen), MAX_THINKING), thinkingId } }]+ }+ if (part.type === 'tool') {+ const events: LiveEvent[] = []+ const state = object(part.data.state) ?? {}+ const name = kiloToolName(str(part.data.tool))+ if (!this.toolStarted.has(part.id)) {+ this.toolStarted.add(part.id)+ events.push({ type: 'tool_start', payload: { id: part.id, tool: name, input: state.input ?? {} } })+ }+ const status = str(state.status)+ if ((status === 'completed' || status === 'error') && !this.toolEnded.has(part.id)) {+ this.toolEnded.add(part.id)+ const output = toolResultText(state)+ const isError = status === 'error'+ events.push({+ type: 'tool_end',+ payload: { id: part.id, tool: name, output: clip(output, MAX_OUTPUT), isError, summary: toolSummary(name, output, isError) },+ })+ // A refusal ends the turn, and kilo writes no `stop` to say so — close it here or the tile spins.+ if (this.open && isPermissionRejection(part)) {+ this.open = false+ events.push({ type: 'turn_ended', payload: {} })+ }+ }+ return events+ }+ if (part.type === 'step-finish' && str(part.data.reason) === 'stop') {+ if (!this.open) return []+ this.open = false+ return [{ type: 'turn_ended', payload: {} }]+ }+ return []+ }+}diff --git a/cli/src/engines/kilo/runtimeProfile.spec.ts b/cli/src/engines/kilo/runtimeProfile.spec.tsnew file mode 100644index 000000000..ab9802dc1--- /dev/null+++ b/cli/src/engines/kilo/runtimeProfile.spec.ts@@ -0,0 +1,72 @@+import { describe, expect, it } from 'vitest'+import { kiloFooterModelId, parseKiloModelsOutput } from './runtimeProfile.js'++/** Ids exactly as `kilo models` printed them on kilo 7.4.20 — including the two shapes opencode's parser drops. */+const CATALOG = [+ 'kilo/~anthropic/claude-opus-latest',+ 'kilo/~openai/gpt-latest',+ 'kilo/ai21/jamba-large-1.7',+ 'kilo/kilo-auto/free',+ 'kilo/kilo-auto/frontier',+ 'kilo/stepfun/step-3.7-flash',+ 'kilo/stepfun/step-3.7-flash:free',+].join('\n')++describe('kilo model catalog', () => {+ /**+ * The regression this parser exists for. Opencode's character class has neither `~` nor `:`, and on the+ * real catalog that silently dropped 23 of 299 ids — the floating `~vendor/model-latest` aliases and+ * every `:free` / `:discounted` / `:thinking` variant. One of the casualties was the model the live+ * session was actually running, so the picker would have omitted the user's own current model.+ */+ it('keeps the ids that carry a ~ alias or a : variant', () => {+ const ids = parseKiloModelsOutput(CATALOG).map((t) => t.id)+ expect(ids).toHaveLength(7)+ expect(ids).toContain('kilo/~anthropic/claude-opus-latest')+ expect(ids).toContain('kilo/stepfun/step-3.7-flash:free')+ })++ it('splits provider from model at the FIRST slash, leaving the vendor in the model', () => {+ const entry = parseKiloModelsOutput(CATALOG).find((t) => t.id === 'kilo/stepfun/step-3.7-flash')!+ expect(entry.provider).toBe('kilo')+ expect(entry.model).toBe('stepfun/step-3.7-flash')+ })++ it('ignores anything that is not a provider/model line', () => {+ expect(parseKiloModelsOutput('loading…\n\nnot-a-model\n')).toEqual([])+ })+})++describe('kilo footer → model', () => {+ const catalog = parseKiloModelsOutput(CATALOG)++ /**+ * Measured composer footer. Note the trailing working directory: the footer is a full-width status bar,+ * so the model name has to be read as the span BETWEEN the agent separator and the provider label —+ * stripping the label alone leaves the path attached and matches nothing.+ */+ it('resolves the model kilo shows in its composer footer', () => {+ const footer = ' ┃ Code · Auto Free Kilo Gateway /private/tmp/kilo-probe'+ expect(kiloFooterModelId(footer, catalog)).toBe('kilo/kilo-auto/free')+ })++ it('resolves a plain vendor model by its leaf', () => {+ expect(kiloFooterModelId('┃ Code · Step 3.7 Flash Kilo Gateway /tmp/x', catalog))+ .toBe('kilo/stepfun/step-3.7-flash')+ })++ /**+ * The TURN footer (`▣ Code · Auto Free · Step 3.7 Flash · 17.9s`) names the model the router resolved+ * to, not the one the user selected — and those differ whenever a `kilo-auto/*` alias is in play. It+ * carries no provider label, which is exactly what keeps it out.+ */+ it('ignores the turn footer, which names the resolved model rather than the selected one', () => {+ expect(kiloFooterModelId('▣ Code · Auto Free · Step 3.7 Flash · 17.9s', catalog)).toBeNull()+ })++ it('answers null rather than guessing when nothing matches', () => {+ expect(kiloFooterModelId('┃ Code · Nonsense Model Kilo Gateway /tmp/x', catalog)).toBeNull()+ expect(kiloFooterModelId('┃ Code · Auto Free Kilo Gateway /tmp/x', [])).toBeNull()+ expect(kiloFooterModelId('no footer here', catalog)).toBeNull()+ })+})diff --git a/cli/src/engines/kilo/runtimeProfile.ts b/cli/src/engines/kilo/runtimeProfile.tsnew file mode 100644index 000000000..c51ef8999--- /dev/null+++ b/cli/src/engines/kilo/runtimeProfile.ts@@ -0,0 +1,179 @@+/**+ * Kilo model catalog → runtime-profile options.+ *+ * `kilo models` prints one `provider/model` per line on stdout and that is the whole catalog. Measured on+ * kilo 7.4.20 (299 lines, and it runs WITHOUT being logged in, unlike `kilo profile`):+ *+ * kilo/~anthropic/claude-opus-latest ← floating alias; note the `~`+ * kilo/stepfun/step-3.7-flash:free ← variant suffix; note the `:`+ * kilo/ai21/jamba-large-1.7+ *+ * Every id measured here begins with the single provider `kilo` and carries the vendor as the first+ * segment of the MODEL, so the leaf-plus-provider filter below reduces to the leaf in practice.+ *+ * Kilo has no separate effort axis in the catalog — every option is `@auto`. It does expose a reasoning+ * `--variant` (`high`, `max`, `minimal`) on `kilo run`, and the real session on this machine recorded+ * `variant: 'medium'` on its message rows, so an effort axis DOES exist somewhere in the product; it is+ * simply not in this catalog and is not wired here.+ *+ * INHERITED, NOT MEASURED ON KILO: everything below about the interactive picker — that it is `/models`,+ * that its header reads `Select model`, that it ends at a `Connect provider` hint, that `●` marks the+ * running model, and that typing filters it. All of that was read off an opencode pane. Driving a picker+ * on unverified anchors is how the Command Code revert (2026-07-30) happened, so the rule that made it+ * safe there holds doubly here: type a filter and act only once exactly ONE row remains, never arrow+ * blindly. Confirm the anchors on a real kilo pane before trusting the switch path.+ */++export interface KiloModelTarget {+ /** `<provider>/<model>` exactly as `kilo models` prints it. */+ id: string+ provider: string+ model: string+ /** What the picker filter is fed: model words, then provider words to disambiguate. */+ filter: string+}++export interface KiloPickerRow {+ display: string+ provider: string+ /** Kilo marks the running model with `●`. */+ current: boolean+}++function words(value: string): string {+ return value.replace(/[^a-z0-9.]+/gi, ' ').trim().toLowerCase()+}++function squash(value: string): string {+ return value.replace(/[^a-z0-9]+/gi, '').toLowerCase()+}++/**+ * Parse `kilo models`; anything that is not a `provider/model` line is ignored.+ *+ * The character class carries `~` and `:`, which opencode's does not. Measured on kilo 7.4.20:+ * `kilo models` prints 299 ids and opencode's class matches only 276 of them. The 23 it drops are the+ * 11 `kilo/~vendor/model-latest` aliases (the floating "latest" pointers — the ones a person is most+ * likely to pick by name) and 12 `…:free` / `:discounted` / `:thinking` variants. Among the dropped was+ * `kilo/stepfun/step-3.7-flash:free`, the model the real session on this machine was actually running —+ * so with opencode's class the picker would have silently omitted the user's own current model, which is+ * exactly the no-error-no-log failure the model-picker site is known for.+ */+export function parseKiloModelsOutput(output: string): KiloModelTarget[] {+ const targets: KiloModelTarget[] = []+ const seen = new Set<string>()+ for (const rawLine of output.split('\n')) {+ const id = rawLine.trim()+ if (!/^[a-z0-9][\w.-]*\/[\w.~:/-]+$/i.test(id) || seen.has(id)) continue+ seen.add(id)+ const slash = id.indexOf('/')+ const provider = id.slice(0, slash)+ const model = id.slice(slash + 1)+ // The picker shows the model's LAST segment (`minimax/minimax-m3` renders as "MiniMax M3"), so the+ // filter is built from that plus the provider.+ const leaf = model.slice(model.lastIndexOf('/') + 1)+ targets.push({ id, provider, model, filter: `${words(leaf)} ${words(provider)}`.trim() })+ }+ return targets+}++/**+ * Rows currently listed by the `/models` picker. The list is bounded above by its own header and below by+ * the "Connect provider" hint; reading only between them keeps the composer and the banner out.+ */+export function parseKiloPickerRows(capture: string): KiloPickerRow[] | null {+ const lines = capture.split('\n').map((line) => line.replace(/\s+$/, ''))+ // LAST header, not the first: a capture carries scrollback, so an earlier opening of the same picker is+ // usually still up there — reading from it parsed a stale, differently-filtered row set.+ const header = lines.findLastIndex((line) => /\bSelect model\b/.test(line))+ if (header < 0) return null+ const end = lines.findIndex((line, index) => index > header && /Connect provider/i.test(line))+ const rows: KiloPickerRow[] = []+ for (const line of lines.slice(header + 1, end < 0 ? lines.length : end)) {+ const text = line.trim()+ if (!text) continue+ const current = text.startsWith('●')+ const cells = text.replace(/^●\s*/, '').split(/\s{3,}/).map((cell) => cell.trim()).filter(Boolean)+ // A model row is TWO cells — model and provider. Counting by position instead put the filter box+ // (one cell, the text just typed) in the row set, so a list narrowed to one model read as two rows+ // and every switch was refused. Provider group headings are single-cell too, and drop out here.+ if (cells.length < 2) continue+ rows.push({ display: cells[0], provider: cells[1], current })+ }+ return rows+}++/**+ * How many times the `/models` picker appears in a capture. A tmux capture includes scrollback, so the+ * only way to tell "the picker I just opened" from "a picker I opened a minute ago" is that the count went+ * up — see setKilo.+ */+export function countKiloPickers(capture: string): number {+ return capture.split('\n').filter((line) => /\bSelect model\b/.test(line)).length+}++/** True when a picker row is the catalog entry we are trying to select. */+export function kiloRowMatches(target: KiloModelTarget, row: KiloPickerRow): boolean {+ const leaf = target.model.slice(target.model.lastIndexOf('/') + 1)+ return squash(row.display).startsWith(squash(leaf))+ && squash(`${row.display} ${row.provider}`).includes(squash(target.provider))+}++/**+ * Resolve kilo's composer footer back to a catalog id.+ *+ * This is a REWRITE of the opencode function it was copied from, not a rename. Opencode anchors on its+ * `Build`/`Plan` agent names; kilo's default agent is `code`, so the inherited version matched nothing on+ * every kilo pane and returned null forever — a blank model chip with no error, which is precisely how+ * this site is known to fail.+ *+ * Measured on a live pane, the composer footer is:+ *+ * ┃ Code · Auto Free Kilo Gateway+ * ^agent ^model display ^provider display+ *+ * so the anchor here is the PROVIDER label rather than the agent: `Kilo Gateway` is stable across agents,+ * while the agent name is user-configurable. The turn footer (`▣ Code · Auto Free · Step 3.7 Flash · 17.9s`)+ * is deliberately NOT used — it names the model the router RESOLVED to, whereas the chip has to report the+ * one the user selected, and those differ exactly when an `kilo-auto/*` alias is in play.+ *+ * Matching allows two spellings of the same entry, both measured:+ * - the full model path with kilo's own prefix dropped — `kilo-auto/free` renders as "Auto Free";+ * - the leaf alone — `stepfun/step-3.7-flash` renders as "Step 3.7 Flash".+ * Longest match wins, so a leaf that is a prefix of another cannot claim the row.+ *+ * A user on a different provider gets a footer this does not recognise, and the answer is null — a blank+ * chip, which is the correct way to say "not observed" rather than reporting a model that is not running.+ */+export function kiloFooterModelId(capture: string, catalog: KiloModelTarget[]): string | null {+ const line = capture.split('\n').map((l) => l.trim()).reverse()+ .find((l) => /·/.test(l) && PROVIDER_LABEL_RE.test(l))+ if (!line) return null+ // The model name is the span BETWEEN the agent separator and the provider label — not "the line with+ // the label removed". The footer is a full-width status bar and right-aligns the working directory onto+ // the same line, so stripping only the label leaves `Auto Free /private/tmp/kilo-probe` and matches+ // nothing. Measured on a live pane; it is why this reads a span rather than doing a replace.+ const providerAt = line.search(PROVIDER_LABEL_RE)+ const display = squash(line.slice(line.indexOf('·') + 1, providerAt))+ if (!display) return null++ let best: { id: string; length: number } | null = null+ for (const entry of catalog) {+ for (const candidate of spellings(entry)) {+ if (candidate.length < 3 || candidate !== display) continue+ if (!best || candidate.length > best.length) best = { id: entry.id, length: candidate.length }+ }+ }+ return best?.id ?? null+}++/** The provider as the footer spells it, which is also what proves the line IS the composer footer. */+const PROVIDER_LABEL_RE = /kilo gateway/i++/** How one catalog entry can appear in the footer. See kiloFooterModelId for the measured examples. */+function spellings(entry: KiloModelTarget): string[] {+ const path = squash(entry.model)+ const leaf = squash(entry.model.slice(entry.model.lastIndexOf('/') + 1))+ const unprefixed = path.startsWith(squash(entry.provider)) ? path.slice(squash(entry.provider).length) : ''+ return [path, leaf, unprefixed].filter(Boolean)+}diff --git a/cli/src/engines/types.ts b/cli/src/engines/types.tsindex cd262f179..ab1af6fe4 100644--- a/cli/src/engines/types.ts+++ b/cli/src/engines/types.ts@@ -1,7 +1,7 @@import type { LiveEvent } from '../lib/normalize.js'import type { RegisteredSession } from '../lib/registry.js'-export type AgentEngine = 'claude' | 'codex' | 'cursor' | 'opencode' | 'pi' | 'hermes' | 'commandcode' | 'devin' | 'muse' | 'amp'+export type AgentEngine = 'claude' | 'codex' | 'cursor' | 'opencode' | 'pi' | 'hermes' | 'commandcode' | 'devin' | 'muse' | 'amp' | 'kilo'export interface EngineNormalizer {ingest(line: string): LiveEvent[]diff --git a/cli/src/lib/__fixtures__/kilo-session.json b/cli/src/lib/__fixtures__/kilo-session.jsonnew file mode 100644index 000000000..dd5994831--- /dev/null+++ b/cli/src/lib/__fixtures__/kilo-session.json@@ -0,0 +1,673 @@+[+ {+ "id": "msg_fe9de3de4001VJVnZBj6LnGaTq",+ "role": "user",+ "timeCreated": 1786335084004,+ "data": {+ "role": "user",+ "time": {+ "created": 1786335084004+ },+ "tools": {},+ "agent": "code",+ "model": {+ "providerID": "kilo",+ "modelID": "kilo-auto/free"+ },+ "summary": {+ "diffs": []+ }+ },+ "parts": [+ {+ "id": "prt_fe9de3def0013XoUegX7iJMNci",+ "type": "text",+ "data": {+ "type": "text",+ "text": "Use your tools: read notes.txt, then make a todo list of 3 items for tidying this folder."+ }+ }+ ]+ },+ {+ "id": "msg_fe9de3e0d001uOueadsR5aquHp",+ "role": "assistant",+ "timeCreated": 1786335084045,+ "data": {+ "parentID": "msg_fe9de3de4001VJVnZBj6LnGaTq",+ "role": "assistant",+ "mode": "code",+ "agent": "code",+ "path": {+ "cwd": "/private/tmp/kilo-probe",+ "root": "/"+ },+ "cost": 0,+ "tokens": {+ "total": 11609,+ "input": 9493,+ "output": 34,+ "reasoning": 34,+ "cache": {+ "write": 0,+ "read": 2048+ }+ },+ "modelID": "kilo-auto/free",+ "providerID": "kilo",+ "time": {+ "created": 1786335084045,+ "completed": 1786335090803+ },+ "finish": "tool-calls"+ },+ "parts": [+ {+ "id": "prt_fe9de5653001yrvxQpa6iqZAYu",+ "type": "step-start",+ "data": {+ "type": "step-start",+ "time": {+ "start": 1786335090255+ }+ }+ },+ {+ "id": "prt_fe9de565800115H1XdbfAAWQ2N",+ "type": "reasoning",+ "data": {+ "type": "reasoning",+ "text": "The user wants me to read notes.txt and then make a todo list of 3 items for tidying the folder. Let me first read the notes.txt file.",+ "time": {+ "start": 1786335090264,+ "end": 1786335090768+ },+ "metadata": {+ "openrouter": {+ "reasoning_details": [+ {+ "type": "reasoning.text",+ "text": "The user wants me to read notes.txt and then make a todo list of 3 items for tidying the folder. Let me first read the notes.txt file.",+ "format": "unknown",+ "index": 0+ }+ ]+ }+ }+ }+ },+ {+ "id": "prt_fe9de5845001k860flku4f7ERu",+ "type": "tool",+ "data": {+ "type": "tool",+ "tool": "read",+ "callID": "chatcmpl-tool-9c6a98e9f3dc7c8b",+ "state": {+ "status": "completed",+ "input": {+ "filePath": "/private/tmp/kilo-probe/notes.txt"+ },+ "output": "<path>/private/tmp/kilo-probe/notes.txt</path>\n<type>file</type>\n<content>\n1: alpha\n2: beta\n3: gamma\n\n(End of file - total 3 lines)\n</content>",+ "metadata": {+ "preview": "alpha\nbeta\ngamma",+ "truncated": false,+ "loaded": [],+ "display": {+ "type": "file",+ "path": "/private/tmp/kilo-probe/notes.txt",+ "text": "alpha\nbeta\ngamma",+ "lineStart": 1,+ "lineEnd": 3,+ "totalLines": 3,+ "truncated": false+ },+ "approval": {+ "source": "agent",+ "agent": "code",+ "rule": {+ "permission": "read",+ "pattern": "*",+ "action": "allow"+ }+ }+ },+ "title": "private/tmp/kilo-probe/notes.txt",+ "time": {+ "start": 1786335090765,+ "end": 1786335090787+ }+ },+ "metadata": {+ "openrouter": {+ "reasoning_details": [+ {+ "type": "reasoning.text",+ "text": "The user wants me to read notes.txt and then make a todo list of 3 items for tidying the folder. Let me first read the notes.txt file.",+ "format": "unknown",+ "index": 0+ }+ ]+ }+ }+ }+ },+ {+ "id": "prt_fe9de5870001DNm2AY7VHh0P2L",+ "type": "step-finish",+ "data": {+ "reason": "tool-calls",+ "type": "step-finish",+ "time": {+ "start": 1786335090255,+ "end": 1786335090799,+ "elapsed": 544+ },+ "model": {+ "providerID": "kilo",+ "modelID": "stepfun/step-3.7-flash"+ },+ "vercelID": "sin1:sin1:sin1::fra1::sr6d9-1786335084575-c94e0a2a3418",+ "metrics": {+ "generation": 125,+ "source": "computed"+ },+ "tokens": {+ "total": 11609,+ "input": 9493,+ "output": 34,+ "reasoning": 34,+ "cache": {+ "write": 0,+ "read": 2048+ }+ },+ "cost": 0+ }+ }+ ]+ },+ {+ "id": "msg_fe9de5879001DQX0l2R9eWos8x",+ "role": "assistant",+ "timeCreated": 1786335090809,+ "data": {+ "parentID": "msg_fe9de3de4001VJVnZBj6LnGaTq",+ "role": "assistant",+ "mode": "code",+ "agent": "code",+ "path": {+ "cwd": "/private/tmp/kilo-probe",+ "root": "/"+ },+ "cost": 0,+ "tokens": {+ "total": 11926,+ "input": 411,+ "output": 98,+ "reasoning": 153,+ "cache": {+ "write": 0,+ "read": 11264+ }+ },+ "modelID": "kilo-auto/free",+ "providerID": "kilo",+ "time": {+ "created": 1786335090809,+ "completed": 1786335095711+ },+ "finish": "tool-calls"+ },+ "parts": [+ {+ "id": "prt_fe9de6500001gFH4SgUdqMBQZw",+ "type": "step-start",+ "data": {+ "type": "step-start",+ "time": {+ "start": 1786335094014+ }+ }+ },+ {+ "id": "prt_fe9de65010017bhynLA1EPOlex",+ "type": "reasoning",+ "data": {+ "type": "reasoning",+ "text": "The notes.txt file contains three items: alpha, beta, gamma. Now I need to create a todo list of 3 items for tidying this folder. Based on the notes.txt content, I should create meaningful tidying tasks related to the folder /private/tmp/kilo-probe. Let me think about what would be appropriate:\n\n1. Clean up temporary or unused files in the folder\n2. Organize files by type or purpose\n3. Remove redundant or outdated notes\n\nActually, looking at the notes.txt content, it seems like it's just a simple list. The user wants a todo list of 3 items for tidying this folder. I should create practical tidying tasks.",+ "time": {+ "start": 1786335094017,+ "end": 1786335095696+ },+ "metadata": {+ "openrouter": {+ "reasoning_details": [+ {+ "type": "reasoning.text",+ "text": "The notes.txt file contains three items: alpha, beta, gamma. Now I need to create a todo list of 3 items for tidying this folder. Based on the notes.txt content, I should create meaningful tidying tasks related to the folder /private/tmp/kilo-probe. Let me think about what would be appropriate:\n\n1. Clean up temporary or unused files in the folder\n2. Organize files by type or purpose\n3. Remove redundant or outdated notes\n\nActually, looking at the notes.txt content, it seems like it's just a simple list. The user wants a todo list of 3 items for tidying this folder. I should create practical tidying tasks.",+ "format": "unknown",+ "index": 0+ }+ ]+ }+ }+ }+ },+ {+ "id": "prt_fe9de6b8b001YCcTiTjwqK1ViP",+ "type": "tool",+ "data": {+ "type": "tool",+ "tool": "todowrite",+ "callID": "chatcmpl-tool-9f673b8effe0c6b6",+ "state": {+ "status": "completed",+ "input": {+ "todos": [+ {+ "content": "Review and organize files in /private/tmp/kilo-probe",+ "priority": "high",+ "status": "pending"+ },+ {+ "content": "Remove any redundant or outdated notes from notes.txt",+ "priority": "medium",+ "status": "pending"+ },+ {+ "content": "Create a clear folder structure or naming convention for the workspace",+ "priority": "medium",+ "status": "pending"+ }+ ]+ },+ "output": "[\n {\n \"content\": \"Review and organize files in /private/tmp/kilo-probe\",\n \"status\": \"pending\",\n \"priority\": \"high\"\n },\n {\n \"content\": \"Remove any redundant or outdated notes from notes.txt\",\n \"status\": \"pending\",\n \"priority\": \"medium\"\n },\n {\n \"content\": \"Create a clear folder structure or naming convention for the workspace\",\n \"status\": \"pending\",\n \"priority\": \"medium\"\n }\n]",+ "metadata": {+ "todos": [+ {+ "content": "Review and organize files in /private/tmp/kilo-probe",+ "status": "pending",+ "priority": "high"+ },+ {+ "content": "Remove any redundant or outdated notes from notes.txt",+ "status": "pending",+ "priority": "medium"+ },+ {+ "content": "Create a clear folder structure or naming convention for the workspace",+ "status": "pending",+ "priority": "medium"+ }+ ],+ "view": {+ "mode": "full",+ "todos": [+ {+ "content": "Review and organize files in /private/tmp/kilo-probe",+ "status": "pending",+ "priority": "high"+ },+ {+ "content": "Remove any redundant or outdated notes from notes.txt",+ "status": "pending",+ "priority": "medium"+ },+ {+ "content": "Create a clear folder structure or naming convention for the workspace",+ "status": "pending",+ "priority": "medium"+ }+ ],+ "hiddenBefore": 0,+ "hiddenAfter": 0,+ "changed": 3+ },+ "truncated": false,+ "approval": {+ "source": "agent",+ "agent": "code",+ "rule": {+ "permission": "*",+ "pattern": "*",+ "action": "allow"+ }+ }+ },+ "title": "3 todos",+ "time": {+ "start": 1786335095695,+ "end": 1786335095702+ }+ },+ "metadata": {+ "openrouter": {+ "reasoning_details": [+ {+ "type": "reasoning.text",+ "text": "The notes.txt file contains three items: alpha, beta, gamma. Now I need to create a todo list of 3 items for tidying this folder. Based on the notes.txt content, I should create meaningful tidying tasks related to the folder /private/tmp/kilo-probe. Let me think about what would be appropriate:\n\n1. Clean up temporary or unused files in the folder\n2. Organize files by type or purpose\n3. Remove redundant or outdated notes\n\nActually, looking at the notes.txt content, it seems like it's just a simple list. The user wants a todo list of 3 items for tidying this folder. I should create practical tidying tasks.",+ "format": "unknown",+ "index": 0+ }+ ]+ }+ }+ }+ },+ {+ "id": "prt_fe9de6b9a001PVO6x6WvhpEA3a",+ "type": "step-finish",+ "data": {+ "reason": "tool-calls",+ "type": "step-finish",+ "time": {+ "start": 1786335094014,+ "end": 1786335095706,+ "elapsed": 1692+ },+ "model": {+ "providerID": "kilo",+ "modelID": "stepfun/step-3.7-flash"+ },+ "vercelID": "sin1:sin1:sin1::fra1::lbnxg-1786335090915-4954d88b8dec",+ "metrics": {+ "generation": 148.34515366430261,+ "source": "computed"+ },+ "tokens": {+ "total": 11926,+ "input": 411,+ "output": 98,+ "reasoning": 153,+ "cache": {+ "write": 0,+ "read": 11264+ }+ },+ "cost": 0+ }+ }+ ]+ },+ {+ "id": "msg_fe9de6ba2001V6rJktGt0KxRL4",+ "role": "assistant",+ "timeCreated": 1786335095714,+ "data": {+ "parentID": "msg_fe9de3de4001VJVnZBj6LnGaTq",+ "role": "assistant",+ "mode": "code",+ "agent": "code",+ "path": {+ "cwd": "/private/tmp/kilo-probe",+ "root": "/"+ },+ "cost": 0,+ "tokens": {+ "total": 12135,+ "input": 364,+ "output": 86,+ "reasoning": 37,+ "cache": {+ "write": 0,+ "read": 11648+ }+ },+ "modelID": "kilo-auto/free",+ "providerID": "kilo",+ "time": {+ "created": 1786335095714,+ "completed": 1786335101920+ },+ "finish": "stop"+ },+ "parts": [+ {+ "id": "prt_fe9de813d001gUVsnwCYhDJpr1",+ "type": "step-start",+ "data": {+ "type": "step-start",+ "time": {+ "start": 1786335101243+ }+ }+ },+ {+ "id": "prt_fe9de81410012IqhgPVlGdOh1E",+ "type": "reasoning",+ "data": {+ "type": "reasoning",+ "text": "The user asked me to read notes.txt and make a todo list of 3 items for tidying this folder. I've done both. Let me present the result concisely.",+ "time": {+ "start": 1786335101249,+ "end": 1786335101458+ },+ "metadata": {+ "openrouter": {+ "reasoning_details": [+ {+ "type": "reasoning.text",+ "text": "The user asked me to read notes.txt and make a todo list of 3 items for tidying this folder. I've done both. Let me present the result concisely.",+ "format": "unknown",+ "index": 0+ }+ ]+ }+ }+ }+ },+ {+ "id": "prt_fe9de82140016WnQ34pUX64gmw",+ "type": "text",+ "data": {+ "type": "text",+ "text": "Done. I've read `notes.txt` (contains `alpha`, `beta`, `gamma`) and created a 3-item todo list for tidying `/private/tmp/kilo-probe`:\n\n1. Review and organize files in `/private/tmp/kilo-probe`\n2. Remove any redundant or outdated notes from `notes.txt`\n3. Create a clear folder structure or naming convention for the workspace",+ "time": {+ "start": 1786335101460,+ "end": 1786335101904+ }+ }+ },+ {+ "id": "prt_fe9de83d6001OiUN3YYGtjjnHn",+ "type": "step-finish",+ "data": {+ "reason": "stop",+ "type": "step-finish",+ "time": {+ "start": 1786335101243,+ "end": 1786335101909,+ "elapsed": 667+ },+ "model": {+ "providerID": "kilo",+ "modelID": "stepfun/step-3.7-flash"+ },+ "vercelID": "sin1:sin1:sin1::fra1::j65s2-1786335095814-f894895644cd",+ "metrics": {+ "generation": 184.40779610194903,+ "source": "computed"+ },+ "tokens": {+ "total": 12135,+ "input": 364,+ "output": 86,+ "reasoning": 37,+ "cache": {+ "write": 0,+ "read": 11648+ }+ },+ "cost": 0+ }+ }+ ]+ },+ {+ "id": "msg_fe9e6e340001jy4EkeJHjR8bxQ",+ "role": "user",+ "timeCreated": 1786335650624,+ "data": {+ "role": "user",+ "time": {+ "created": 1786335650624+ },+ "tools": {},+ "agent": "code",+ "model": {+ "providerID": "kilo",+ "modelID": "kilo-auto/free"+ },+ "summary": {+ "diffs": []+ }+ },+ "parts": [+ {+ "id": "prt_fe9e6e342001YnSlpgCADgZ2eN",+ "type": "text",+ "data": {+ "type": "text",+ "text": "Read the file /etc/hosts and tell me its first line."+ }+ }+ ]+ },+ {+ "id": "msg_fe9e6e362001ISZ7CY73gs3k82",+ "role": "assistant",+ "timeCreated": 1786335650659,+ "data": {+ "parentID": "msg_fe9e6e340001jy4EkeJHjR8bxQ",+ "role": "assistant",+ "mode": "code",+ "agent": "code",+ "path": {+ "cwd": "/private/tmp/kilo-probe",+ "root": "/"+ },+ "cost": 0,+ "tokens": {+ "total": 12002,+ "input": 9890,+ "output": 47,+ "reasoning": 17,+ "cache": {+ "write": 0,+ "read": 2048+ }+ },+ "modelID": "kilo-auto/free",+ "providerID": "kilo",+ "time": {+ "created": 1786335650659,+ "completed": 1786335831992+ },+ "finish": "tool-calls"+ },+ "parts": [+ {+ "id": "prt_fe9e6fc6f001oDXsOFhsPujVzy",+ "type": "step-start",+ "data": {+ "type": "step-start",+ "time": {+ "start": 1786335657068+ }+ }+ },+ {+ "id": "prt_fe9e6fc72001kIopoc3gWdX5Cd",+ "type": "reasoning",+ "data": {+ "type": "reasoning",+ "text": "The user wants me to read /etc/hosts and tell them its first line.",+ "time": {+ "start": 1786335657074,+ "end": 1786335658281+ },+ "metadata": {+ "openrouter": {+ "reasoning_details": [+ {+ "type": "reasoning.text",+ "text": "The user wants me to read /etc/hosts and tell them its first line.",+ "format": "unknown",+ "index": 0+ }+ ]+ }+ }+ }+ },+ {+ "id": "prt_fe9e700a3001eoxDRR6dxvgC1w",+ "type": "tool",+ "data": {+ "type": "tool",+ "tool": "read",+ "callID": "chatcmpl-tool-b0ae647755dcf927",+ "state": {+ "status": "error",+ "input": {+ "filePath": "/etc/hosts",+ "limit": 1,+ "offset": 1+ },+ "error": "The user rejected permission to use this specific tool call.",+ "time": {+ "start": 1786335658151,+ "end": 1786335831963+ }+ },+ "metadata": {+ "openrouter": {+ "reasoning_details": [+ {+ "type": "reasoning.text",+ "text": "The user wants me to read /etc/hosts and tell them its first line.",+ "format": "unknown",+ "index": 0+ }+ ]+ }+ }+ }+ },+ {+ "id": "prt_fe9e9a7aa001w2oI2zpAwyVFpK",+ "type": "step-finish",+ "data": {+ "reason": "tool-calls",+ "type": "step-finish",+ "time": {+ "start": 1786335657068,+ "end": 1786335831976,+ "elapsed": 174909+ },+ "model": {+ "providerID": "kilo",+ "modelID": "stepfun/step-3.7-flash"+ },+ "vercelID": "sin1:sin1:sin1::fra1::rqj2s-1786335650892-32000d77a838",+ "metrics": {+ "generation": 0.36590455608344913,+ "source": "computed"+ },+ "tokens": {+ "total": 12002,+ "input": 9890,+ "output": 47,+ "reasoning": 17,+ "cache": {+ "write": 0,+ "read": 2048+ }+ },+ "cost": 0+ }+ }+ ]+ }+]diff --git a/cli/src/lib/__fixtures__/question-kilo.txt b/cli/src/lib/__fixtures__/question-kilo.txtnew file mode 100644index 000000000..0c9ea77e7--- /dev/null+++ b/cli/src/lib/__fixtures__/question-kilo.txt@@ -0,0 +1,50 @@+ ┃+ ┃ Use your tools: read notes.txt, then make a todo list of 3 items for tidying this folder. Todo list from notes.txt █+ ┃ █+ █+ + Thought: 504ms ▼ Context █+ 12,135 tokens █+ → Read notes.txt · auto-approved by the code agent (matched read `*`) 5% used █+ $0.00 spent █+ + Thought: 1.7s █+ ▼ Token Usage █+ ┃ Input 10,268 █+ ┃ # Todos · Step 3.7 Flash Output 218 █+ ┃ Reasoning 224 █+ ┃ [ ] Review and organize files in /private/tmp/kilo-probe Cache read 24,960 █+ ┃ [ ] Remove any redundant or outdated notes from notes.txt Cache write 0 █+ ┃ [ ] Create a clear folder structure or naming convention for the workspace Cache rate 70.9% █+ ┃ Generation speed 152.3 t/s █+ Cost $0.00 █+ + Thought: 209ms · Step 3.7 Flash █+ ▼ Models (1) █+ Done. I've read notes.txt (contains alpha, beta, gamma) and created a 3-item todo list for tidying /private/tmp/kilo-probe: █+ Kilo Gateway ▀+ 1. Review and organize files in /private/tmp/kilo-probe+ 2. Remove any redundant or outdated notes from notes.txt Model Steps Cost+ 3. Create a clear folder structure or naming convention for the workspace ▶ Step 3.7 Flash 3 $0.00++ ▣ Code · Auto Free · Step 3.7 Flash · 17.9s Code Indexing+ • Disabled+ ┃+ ┃ Read the file /etc/hosts and tell me its first line. LSP+ ┃ LSPs are disabled++ + Thought: 1.2s ▼ Todo+ [ ] Review and organize files in /+ ⠋ Read /etc/hosts [limit=1, offset=1] private/tmp/kilo-probe+ [ ] Remove any redundant or outdated+ ▣ Code · Auto Free notes from notes.txt+ [ ] Create a clear folder structure+ ┃ or naming convention for the+ ┃ △ Permission required workspace+ ┃ ← Access external directory /private/etc+ ┃ Memory+ ┃ Patterns+ ┃ Balance+ ┃ - /private/etc/* • Personal credits $0.00+ ┃+ ┃ /private/tmp/kilo-probe+ ┃ Allow once Allow always Reject ctrl+f fullscreen ⇆ select enter confirm+ ┃ • Kilo 7.4.20+diff --git a/cli/src/lib/askQuestion.ts b/cli/src/lib/askQuestion.tsindex b20c258d6..b17d6c4ce 100644--- a/cli/src/lib/askQuestion.ts+++ b/cli/src/lib/askQuestion.ts@@ -25,6 +25,7 @@ import type { RegisteredSession } from './registry.js'import type { AgentEngine } from '../engines/types.js'import { parseMuseQuestionPane } from '../engines/muse/askQuestion.js'import { ampSelectionKeys, parseAmpQuestionPane } from '../engines/amp/askQuestion.js'+import { kiloSelectionKeys, parseKiloQuestionPane } from '../engines/kilo/askQuestion.js'import { parseDevinQuestionPane } from '../engines/devin/askQuestion.js'/** Device-facing question shape — byte-for-byte the hosted runtime’s `commanderQuestions()` output. */@@ -121,6 +122,9 @@ export function parseEngineQuestionPane(engine: AgentEngine, capture: string): Pif (engine === 'muse') return parseMuseQuestionPane(capture)// Amp's is a permission prompt with unnumbered rows — nothing the shared parser can anchor on.if (engine === 'amp') return parseAmpQuestionPane(capture)+ // Kilo's is the same kind of prompt but laid out HORIZONTALLY, sharing its line with the key hints —+ // it is a fork of opencode that did not keep opencode's dialog.+ if (engine === 'kilo') return parseKiloQuestionPane(capture)// Hermes and OpenCode paint Claude's dialog inside a box; peel the border and the shared parser fits.if (engine === 'hermes') return parseQuestionPane(unframe(capture))if (engine === 'opencode') {@@ -323,7 +327,10 @@ export function parseQuestionPane(capture: string): PaneView {* walking down to them.*/function rowKeys(engine: AgentEngine, row: QuestionRow): string[] {- return engine === 'amp' ? ampSelectionKeys(row) : [row.number]+ if (engine === 'amp') return ampSelectionKeys(row)+ // Kilo's rows sit side by side, so its walk is horizontal — see engines/kilo/askQuestion.ts.+ if (engine === 'kilo') return kiloSelectionKeys(row)+ return [row.number]}export function matchRow(rows: QuestionRow[], answer: string): QuestionRow | null {@@ -506,7 +513,7 @@ export interface QuestionWatcherDeps {const POLL_MS = 1500// Amp is here for its PERMISSION prompt, not a question tool — it has none. That prompt is drawn only in// the pane and recorded nowhere, so polling the pane is the only way it is ever seen.-const QUESTION_ENGINES = new Set<AgentEngine>(['claude', 'commandcode', 'devin', 'hermes', 'opencode', 'muse', 'amp'])+const QUESTION_ENGINES = new Set<AgentEngine>(['claude', 'commandcode', 'devin', 'hermes', 'opencode', 'muse', 'amp', 'kilo'])/** Does this engine ever paint a question dialog? Callers use it to decide whether to watch its pane. */export function pollsQuestions(engine: AgentEngine): boolean {diff --git a/cli/src/lib/disposableOneShotPool.spec.ts b/cli/src/lib/disposableOneShotPool.spec.tsindex 45033b62a..194178819 100644--- a/cli/src/lib/disposableOneShotPool.spec.ts+++ b/cli/src/lib/disposableOneShotPool.spec.ts@@ -51,7 +51,7 @@ describe('DisposableOneShotPool', () => {return worker}, 300_000, () => {})- pool.setActiveCounts({ claude: 4, codex: 1, cursor: 2, opencode: 0, pi: 0, commandcode: 0 })+ pool.setActiveCounts({ claude: 4, codex: 1, cursor: 2, opencode: 0, pi: 0, commandcode: 0, kilo: 0 })pool.setDeviceConnected(true)await settle()expect(pool.snapshot()).toMatchObject({@@ -83,7 +83,7 @@ describe('DisposableOneShotPool', () => {return Promise.resolve(new FakeWorker(engine, calls))}, 300_000, () => {})- pool.setActiveCounts({ claude: 1, codex: 0, cursor: 0, opencode: 0, pi: 0, commandcode: 0 })+ pool.setActiveCounts({ claude: 1, codex: 0, cursor: 0, opencode: 0, pi: 0, commandcode: 0, kilo: 0 })pool.setDeviceConnected(true)expect(pool.snapshot().claude.starting).toBe(1)@@ -103,7 +103,7 @@ describe('DisposableOneShotPool', () => {5 * 60_000,() => {},)- pool.setActiveCounts({ claude: 1, codex: 0, cursor: 0, opencode: 0, pi: 0, commandcode: 0 })+ pool.setActiveCounts({ claude: 1, codex: 0, cursor: 0, opencode: 0, pi: 0, commandcode: 0, kilo: 0 })pool.setDeviceConnected(true)await settle()@@ -129,7 +129,7 @@ describe('DisposableOneShotPool', () => {created.push(worker)return worker}, 300_000, () => {})- pool.setActiveCounts({ claude: 1, codex: 0, cursor: 0, opencode: 0, pi: 0, commandcode: 0 })+ pool.setActiveCounts({ claude: 1, codex: 0, cursor: 0, opencode: 0, pi: 0, commandcode: 0, kilo: 0 })pool.setDeviceConnected(true)await settle()expect(created).toHaveLength(1)@@ -160,7 +160,7 @@ describe('DisposableOneShotPool', () => {60_000, // idle ceiling)- pool.setActiveCounts({ claude: 1, codex: 0, cursor: 0, opencode: 0, pi: 0, commandcode: 0 })+ pool.setActiveCounts({ claude: 1, codex: 0, cursor: 0, opencode: 0, pi: 0, commandcode: 0, kilo: 0 })pool.setDeviceConnected(true)await settle()expect(pool.snapshot()).toMatchObject({ claude: { ready: 1 } })@@ -192,7 +192,7 @@ describe('DisposableOneShotPool', () => {60_000,)- pool.setActiveCounts({ claude: 1, codex: 0, cursor: 0, opencode: 0, pi: 0, commandcode: 0 })+ pool.setActiveCounts({ claude: 1, codex: 0, cursor: 0, opencode: 0, pi: 0, commandcode: 0, kilo: 0 })pool.setDeviceConnected(true)await settle()const first = created[0]diff --git a/cli/src/lib/disposableOneShotPool.ts b/cli/src/lib/disposableOneShotPool.tsindex 9ab718f89..9abe6edf6 100644--- a/cli/src/lib/disposableOneShotPool.ts+++ b/cli/src/lib/disposableOneShotPool.ts@@ -1,6 +1,6 @@-export type OneShotEngine = 'claude' | 'codex' | 'cursor' | 'opencode' | 'pi' | 'commandcode'+export type OneShotEngine = 'claude' | 'codex' | 'cursor' | 'opencode' | 'pi' | 'commandcode' | 'kilo'-const ONE_SHOT_ENGINES: readonly OneShotEngine[] = ['claude', 'codex', 'cursor', 'opencode', 'pi', 'commandcode']+const ONE_SHOT_ENGINES: readonly OneShotEngine[] = ['claude', 'codex', 'cursor', 'opencode', 'pi', 'commandcode', 'kilo']export interface DisposableWorker<Options, Result> {readonly engine: OneShotEngine@@ -35,6 +35,7 @@ export interface PoolSnapshot {opencode: { active: number; target: number; starting: number; ready: number }pi: { active: number; target: number; starting: number; ready: number }commandcode: { active: number; target: number; starting: number; ready: number }+ kilo: { active: number; target: number; starting: number; ready: number }}/** Maintains disposable, pre-spawned workers. A checked-out worker is never returned to the pool. */@@ -46,6 +47,7 @@ export class DisposableOneShotPool<Options, Result> {opencode: { active: 0, target: 0, starting: 0, ready: new Set(), retryTimer: null },pi: { active: 0, target: 0, starting: 0, ready: new Set(), retryTimer: null },commandcode: { active: 0, target: 0, starting: 0, ready: new Set(), retryTimer: null },+ kilo: { active: 0, target: 0, starting: 0, ready: new Set(), retryTimer: null },}private readonly all = new Set<DisposableWorker<Options, Result>>()private connected = false@@ -168,6 +170,7 @@ export class DisposableOneShotPool<Options, Result> {opencode: item('opencode'),pi: item('pi'),commandcode: item('commandcode'),+ kilo: item('kilo'),}}diff --git a/cli/src/lib/engineBin.ts b/cli/src/lib/engineBin.tsindex 0e5aa52a4..bef0fa520 100644--- a/cli/src/lib/engineBin.ts+++ b/cli/src/lib/engineBin.ts@@ -12,14 +12,15 @@ import type { AgentEngine } from '../engines/types.js'/** Every engine the adapter can drive — also the set of `harness <engine>` launch subcommands. */export const ENGINES: readonly AgentEngine[] = [- 'claude', 'codex', 'cursor', 'opencode', 'pi', 'hermes', 'commandcode', 'devin', 'muse', 'amp',+ 'claude', 'codex', 'cursor', 'opencode', 'pi', 'hermes', 'commandcode', 'devin', 'muse', 'amp', 'kilo',] as const/*** Names users actually type. Several CLIs install more than one binary for the same product, and people* reach for whichever one they know — `harness cmd` must mean Command Code, not "unknown command".- * Verified on disk: command-code ships `commandcode`/`command-code`/`cmd`/`cmdc` (all the same file), and- * Cursor's CLI is installed as `agent` / `cursor-agent`.+ * Verified on disk: command-code ships `commandcode`/`command-code`/`cmd`/`cmdc` (all the same file),+ * Cursor's CLI is installed as `agent` / `cursor-agent`, and `@kilocode/cli` declares+ * `bin: { kilo, kilocode }` — two names for one file, with `kilo` first and used throughout its help.*/const ENGINE_ALIASES: Readonly<Record<string, AgentEngine>> = {cmd: 'commandcode',@@ -27,6 +28,7 @@ const ENGINE_ALIASES: Readonly<Record<string, AgentEngine>> = {'command-code': 'commandcode',agent: 'cursor','cursor-agent': 'cursor',+ kilocode: 'kilo',}/**@@ -83,5 +85,6 @@ export function engineBin(engine: AgentEngine): string {case 'devin': return env.DEVIN_PATH || 'devin'case 'muse': return env.MUSE_PATH || 'muse'case 'amp': return env.AMP_PATH || 'amp'+ case 'kilo': return env.KILO_PATH || 'kilo'}}diff --git a/cli/src/lib/enginePermissions.spec.ts b/cli/src/lib/enginePermissions.spec.tsindex bab04fa8e..673b34c32 100644--- a/cli/src/lib/enginePermissions.spec.ts+++ b/cli/src/lib/enginePermissions.spec.ts@@ -31,6 +31,12 @@ describe('default permission flags', () => {// 0.0.1786064749: an unknown flag is rejected while this one is accepted, an `ask` rule blocks the// tool without it ("blocked by a permissions rule"), and the same command runs with it.amp: ['--dangerously-allow-all'],+ // Kilo adds NOTHING, and the empty array is the assertion — it is a measurement, not an omission.+ // `kilo run` documents `--auto` and `--dangerously-skip-permissions`, but the launcher starts the+ // TUI, and on a real TTY (with a control: bare `kilo` starts, `kilo --auto` prints usage and exits)+ // the root command rejects both. Adding either would stop the agent starting at all. The recap+ // one-shot DOES pass `--auto`, because it invokes the `run` subcommand — see lib/oneshot.ts.+ kilo: [],})})diff --git a/cli/src/lib/enginePermissions.ts b/cli/src/lib/enginePermissions.tsindex babcde9d1..84c8dd670 100644--- a/cli/src/lib/enginePermissions.ts+++ b/cli/src/lib/enginePermissions.ts@@ -74,6 +74,26 @@ const PERMISSIONS: Readonly<Record<AgentEngine, EnginePermissions>> = {add: [{ axis: 'permission', args: ['--auto'] }],owned: { permission: ['--auto'] },},+ /**+ * Kilo adds NOTHING, and this is the one place it diverges hardest from the opencode it forked.+ *+ * `kilo run` documents BOTH `--auto` and `--dangerously-skip-permissions`, so the flags exist on the+ * binary — but they belong to the `run` subcommand, and the launcher starts the TUI (`kilo`), not `run`.+ * Measured on a real TTY inside tmux, with a control: bare `kilo` starts the TUI, while `kilo --auto`+ * prints the usage block and exits. Adding the flag anyway would not loosen permissions, it would stop+ * the agent from starting at all.+ *+ * Note the non-TTY form cannot answer this question: with stdin closed, `kilo --auto`,+ * `kilo --dangerously-skip-permissions` and an invented flag all print byte-identical usage, so the+ * usual unknown-flag test reads as "rejected" for real flags too. The TTY is the only place it shows.+ *+ * `owned` still lists both spellings: a user who types one has chosen the axis, and nothing should be+ * appended on top of that if this table ever gains an `add`.+ */+ kilo: {+ add: [],+ owned: { permission: ['--auto', '--dangerously-skip-permissions'] },+ },// Pi has NO permission bypass: its model is tool allow/deny lists (`--tools`, `--exclude-tools`) with no// "approve everything" switch, so only the trust axis is set. Inventing a flag would just fail to start.pi: {diff --git a/cli/src/lib/hooks.ts b/cli/src/lib/hooks.tsindex 6acbe3095..357014cfd 100644--- a/cli/src/lib/hooks.ts+++ b/cli/src/lib/hooks.ts@@ -222,19 +222,30 @@ export function installCursorHooks(port: number): void {}const OPENCODE_PLUGIN_PATH = join(env.OPENCODE_PLUGIN_DIR, 'launcher-register.js')+const KILO_PLUGIN_PATH = join(env.KILO_PLUGIN_DIR, 'launcher-register.js')-/** OpenCode has no shell hooks — discovery is a global plugin that POSTs each session to the daemon.- * The plugin runs INSIDE every interactive `opencode` process (so it sees `$TMUX_PANE` + the cwd) and- * fires on session.created/updated. The recap worker runs `opencode run --pure`, which skips external- * plugins, so it never self-registers. */-function opencodePluginSource(port: number): string {- return `// launcher-register — auto-installed by the machine adapter. Registers this OpenCode session with the+/**+ * Discovery plugin for the opencode-family engines — opencode itself and `kilo`, which is its fork.+ *+ * Neither has shell hooks; discovery is a global plugin that POSTs each session to the daemon. The plugin+ * runs INSIDE every interactive process (so it sees `$TMUX_PANE` + the cwd) and fires on+ * session.created/updated. The recap workers run with `--pure`, which skips external plugins, so an+ * ephemeral summary session never self-registers.+ *+ * ONE template, two installers: the engine name is the only difference in the emitted source, and the two+ * install to different directories with their own log lines. The engine modules are deliberately+ * duplicated so the forks can drift apart, but this template holds no engine behaviour to drift — if+ * kilo's plugin API ever diverges from opencode's, that is the moment to split this, not before.+ */+function forkPluginSource(engine: 'opencode' | 'kilo', port: number): string {+ const product = engine === 'kilo' ? 'Kilo' : 'OpenCode'+ return `// launcher-register — auto-installed by the machine adapter. Registers this ${product} session with the// local machine daemon (127.0.0.1:${port}) so it can be mirrored to web/device. No-op if machine isn't running.export const MachineRegister = async ({ directory, worktree, project }) => {const seen = new Set()const post = async (sessionID) => {const pane = process.env.TMUX_PANE- // The launcher (\`harness opencode\`) mints a UUID per launch and exports it as MACHINE_ID; the daemon+ // The launcher (\`harness ${engine}\`) mints a UUID per launch and exports it as MACHINE_ID; the daemon// binds a session's lifetime to that launcher and REFUSES a registration without one. This plugin runs// inside the engine, so it inherits the variable — and an engine started outside the launcher has none,// which is exactly when it should not register. Same rule notify.mjs applies for every other engine.@@ -246,7 +257,7 @@ export const MachineRegister = async ({ directory, worktree, project }) => {method: "POST",headers: { "content-type": "application/json" },body: JSON.stringify({- engine: "opencode",+ engine: "${engine}",pluginVersion: ${JSON.stringify(VERSION)},launcherId,sessionId: sessionID,@@ -813,22 +824,38 @@ export function installAmpPlugin(port: number): void {/** Idempotently drop the OpenCode discovery plugin into ~/.config/opencode/plugin/. */export function installOpencodePlugin(port: number): void {- const source = opencodePluginSource(port)+ installForkPlugin('opencode', OPENCODE_PLUGIN_PATH, 'OpenCode', port)+}++/**+ * Idempotently drop the Kilo discovery plugin into ~/.config/kilo/plugin/.+ *+ * Measured: kilo resolves its config root from XDG_CONFIG_HOME (`kilo debug paths` reports+ * `~/.config/kilo`), and that directory is already scaffolded with the same `package.json` ++ * `node_modules` layout opencode's has — the plugin dir itself is simply absent until something creates+ * it, which `mkdirSync` below does.+ */+export function installKiloPlugin(port: number): void {+ installForkPlugin('kilo', KILO_PLUGIN_PATH, 'Kilo', port)+}++function installForkPlugin(engine: 'opencode' | 'kilo', path: string, product: string, port: number): void {+ const source = forkPluginSource(engine, port)try {- if (existsSync(OPENCODE_PLUGIN_PATH) && readFileSync(OPENCODE_PLUGIN_PATH, 'utf-8') === source) {- console.log('[hooks] OpenCode discovery plugin already installed')+ if (existsSync(path) && readFileSync(path, 'utf-8') === source) {+ console.log(`[hooks] ${product} discovery plugin already installed`)return}} catch { /* unreadable — rewrite it */ }try {- mkdirSync(dirname(OPENCODE_PLUGIN_PATH), { recursive: true })- const tmp = `${OPENCODE_PLUGIN_PATH}.${process.pid}.tmp`+ mkdirSync(dirname(path), { recursive: true })+ const tmp = `${path}.${process.pid}.tmp`writeFileSync(tmp, source)- renameSync(tmp, OPENCODE_PLUGIN_PATH)- console.log(`[hooks] installed OpenCode discovery plugin → ${OPENCODE_PLUGIN_PATH}`)- console.log('[hooks] (takes effect on the next opencode session start)')+ renameSync(tmp, path)+ console.log(`[hooks] installed ${product} discovery plugin → ${path}`)+ console.log(`[hooks] (takes effect on the next ${engine} session start)`)} catch (err) {- console.error('[hooks] failed to write OpenCode plugin:', err)+ console.error(`[hooks] failed to write ${product} plugin:`, err)}}@@ -849,6 +876,7 @@ export function installHooksFor(engine: AgentEngine, port: number): void {case 'codex': installCodexHooks(port); breakcase 'cursor': installCursorHooks(port); breakcase 'opencode': installOpencodePlugin(port); break+ case 'kilo': installKiloPlugin(port); breakcase 'pi': installPiExtension(port); breakcase 'hermes': installHermesHooks(port); breakcase 'commandcode': installCommandCodeHooks(port); breakdiff --git a/cli/src/lib/kiloOneShot.spec.ts b/cli/src/lib/kiloOneShot.spec.tsnew file mode 100644index 000000000..a5d0908a0--- /dev/null+++ b/cli/src/lib/kiloOneShot.spec.ts@@ -0,0 +1,62 @@+import { describe, expect, it } from 'vitest'+import { kiloOneShotSpawn } from './oneshot.js'++/**+ * A production failure, pinned.+ *+ * The kilo recap worker escaped its scratch directory and ran against the user's real repository. The+ * daemon spawns it with `cwd: <scratch>`, which is not enough: kilo resolves its project from `$PWD`, and+ * `spawn({cwd})` does not rewrite that variable, so the child inherited the DAEMON's working directory.+ * Measured in the daemon log — the worker announced+ * `kilocode-indexing workspacePath=<the daemon's launch directory> initializing project indexing` the+ * moment a prompt reached it — and reproduced by hand by setting a hostile `PWD` with the correct `cwd`.+ *+ * The consequence was not a crash. The recap sat indexing a real repository until the 60s timeout, so no+ * `turn_summary` was ever produced: no recap, and a device tile that showed "Summarizing…" for a minute+ * on every single turn. Nothing about that is visible in a unit test of the parser, which is why the+ * containment rules are asserted here instead.+ */+describe('kilo recap worker containment', () => {+ const SCRATCH = '/tmp/adapter/kilo-recap'+ const HOSTILE = { PWD: '/Users/someone/Work/a-real-repo', TMUX: '/tmp/tmux-501/default', TMUX_PANE: '%3' }++ it('pins the workspace with --dir rather than trusting the spawn cwd', () => {+ const { args } = kiloOneShotSpawn(undefined, {}, SCRATCH)+ expect(args).toContain('--dir')+ expect(args[args.indexOf('--dir') + 1]).toBe(SCRATCH)+ })++ it('overrides an inherited PWD, which is what actually leaked', () => {+ const { env } = kiloOneShotSpawn(undefined, { ...HOSTILE }, SCRATCH)+ expect(env.PWD).toBe(SCRATCH)+ })++ it('keeps kilo\'s own store in the scratch dir', () => {+ // Kilo ignores KILO_DATA_DIR and OPENCODE_DATA_DIR; XDG_DATA_HOME is the only override that moves it.+ const { env } = kiloOneShotSpawn(undefined, {}, SCRATCH)+ expect(env.XDG_DATA_HOME).toBe(SCRATCH)+ })++ it('scrubs tmux so an ephemeral recap can never look like a pane agent', () => {+ const { env } = kiloOneShotSpawn(undefined, { ...HOSTILE }, SCRATCH)+ expect(env.TMUX).toBeUndefined()+ expect(env.TMUX_PANE).toBeUndefined()+ })++ /**+ * `--auto` is required: without it a recap whose model reaches for any tool dies on kilo's own+ * auto-rejection ("run ended with an auto-rejected permission") and returns no text at all. It is valid+ * on the `run` SUBCOMMAND only — the interactive TUI rejects it, which is why `enginePermissions` adds+ * nothing for kilo.+ */+ it('runs autonomously and asks for machine-readable output', () => {+ const { args } = kiloOneShotSpawn(undefined, {}, SCRATCH)+ expect(args.slice(0, 5)).toEqual(['run', '--pure', '--auto', '--format', 'json'])+ })++ 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 ''".+ expect(kiloOneShotSpawn('', {}, SCRATCH).args).not.toContain('--model')+ })+})diff --git a/cli/src/lib/oneshot.ts b/cli/src/lib/oneshot.tsindex b9332fb90..56724428f 100644--- a/cli/src/lib/oneshot.ts+++ b/cli/src/lib/oneshot.ts@@ -578,6 +578,158 @@ class OpencodeWorker extends ProcessWorker {}}+function kiloBin(): string {+ return env.KILO_PATH || 'kilo'+}++/**+ * Recap runs in an isolated Kilo data dir so ephemeral summary sessions never land in the user's real+ * kilo.db, while still reading their ~/.config/kilo provider/model config.+ *+ * The isolation mechanism is where kilo parts company with the opencode it forked. Opencode honours+ * `OPENCODE_DATA_DIR`; kilo has no equivalent — measured with `kilo debug paths`, it ignores both+ * `KILO_DATA_DIR` and `OPENCODE_DATA_DIR` and moves its store only for `XDG_DATA_HOME`. So the child is+ * given that instead, and because kilo appends its own name, the store lands at `<dir>/kilo/kilo.db`.+ *+ * `XDG_CONFIG_HOME` is deliberately NOT set: it would move the config root too and the recap would lose+ * the user's provider and model, which is the one thing this worker has to inherit.+ *+ * First spawn into a fresh dir prints `Performing one time database migration` and pays for it; the pool+ * pre-warms workers, so that cost lands before a recap is ever asked for.+ */+const KILO_RECAP_DATA_DIR = join(env.ADAPTER_DATA_DIR, 'kilo-recap')++/**+ * The argv + env for one kilo recap worker. Exported so the containment rules below are testable — a+ * spawn is not, and both of these have already failed in production once.+ */+export function kiloOneShotSpawn(+ model: string | undefined,+ parentEnv: NodeJS.ProcessEnv,+ dataDir: string = KILO_RECAP_DATA_DIR,+): { args: string[]; env: NodeJS.ProcessEnv } {+ const args = [+ 'run', '--pure', '--auto', '--format', 'json', '--dir', dataDir,+ ...(model ? ['--model', model] : []),+ ]+ const childEnv = { ...parentEnv }+ delete childEnv.TMUX+ delete childEnv.TMUX_PANE+ childEnv.XDG_DATA_HOME = dataDir+ // Belt and braces with `--dir`. `spawn({cwd})` does NOT rewrite `PWD`, and kilo resolves its project+ // from that variable, so without this the child inherits the DAEMON's directory.+ childEnv.PWD = dataDir+ return { args, env: childEnv }+}++class KiloWorker extends ProcessWorker {+ readonly engine = 'kilo' as const+ private buffer = ''+ private stderr = ''+ private readonly assistantParts: string[] = []+ private pending: {+ resolve: (result: OneShotResult) => void+ reject: (err: unknown) => void+ timer: NodeJS.Timeout+ signal?: AbortSignal+ onAbort: () => void+ } | null = null++ constructor(model?: string) {+ // `kilo run` reads the prompt from stdin (pipe → EOF), so the worker can be pre-warmed and fed the+ // prompt later. `--pure` skips external plugins (so the discovery plugin never self-registers this+ // ephemeral recap session). `--format json` streams one JSON envelope per line.+ //+ // `--auto` is REQUIRED here and is not the same question as the launcher's permission table. Measured:+ // without it a recap run whose model reaches for any tool dies outright — kilo auto-rejects the+ // permission and ends the run (`run ended with an auto-rejected permission; pass --auto for+ // autonomous use`), emitting an `error` envelope and NO text. A summariser has no user to ask, and a+ // recap that returns nothing is the failure this flag prevents. Note the asymmetry that makes this+ // easy to get wrong: `--auto` is a valid flag of the `run` SUBCOMMAND, while the bare TUI rejects it+ // — see `enginePermissions.ts`, where kilo therefore adds nothing.+ mkdirSync(KILO_RECAP_DATA_DIR, { recursive: true })+ // `--dir` pins the workspace explicitly. Do NOT rely on the spawn `cwd` alone: kilo resolves its+ // project from `$PWD`, and `spawn({cwd})` does not rewrite that variable — the child inherits the+ // DAEMON's `PWD`. Measured in production: the worker logged+ // `kilocode-indexing workspacePath=<the daemon's launch directory> initializing project indexing`+ // the moment a prompt arrived, i.e. every recap ran against the user's real repository instead of an+ // empty scratch dir. It then hung indexing and gathering context until the 60s timeout, so no+ // `turn_summary` was ever emitted and the device tile stayed on `processing` forever.+ const { args, env: processEnv } = kiloOneShotSpawn(model, process.env)+ const child = spawn(kiloBin(), args, {+ cwd: KILO_RECAP_DATA_DIR, env: processEnv, detached: true, stdio: ['pipe', 'pipe', 'pipe'],+ })+ super(child)+ child.stdout?.on('data', (chunk: Buffer) => this.onStdout(chunk.toString()))+ child.stderr?.on('data', (chunk: Buffer) => { this.stderr += chunk.toString() })+ child.stdin?.on('error', (err) => this.fail(err))+ child.on('error', (err) => this.fail(err))+ child.on('close', (code) => {+ if (this.buffer.trim()) this.handleLine(this.buffer)+ if (!this.pending) return+ const text = this.assistantParts.join('').trim()+ if (!text && code !== 0) this.fail(new Error(`kilo one-shot exited ${code}: ${this.stderr.slice(0, 500)}`))+ else this.complete(text)+ })+ }++ run(options: OneShotOptions): Promise<OneShotResult> {+ if (this.assigned) return Promise.reject(new Error('kilo recap worker already consumed'))+ this.assigned = true+ if (options.signal?.aborted) return Promise.reject(abortError(this.engine))+ const timeoutMs = options.timeoutMs ?? 60_000+ return new Promise((resolve, reject) => {+ const onAbort = (): void => { this.fail(abortError(this.engine)); this.dispose() }+ const timer = setTimeout(() => {+ this.fail(new Error(`kilo one-shot timed out after ${timeoutMs}ms`))+ this.dispose()+ }, timeoutMs)+ this.pending = { resolve, reject, timer, signal: options.signal, onAbort }+ options.signal?.addEventListener('abort', onAbort)+ if (!this.child.stdin || this.child.stdin.destroyed || !this.isAlive()) {+ this.fail(new Error('kilo recap worker is not writable'))+ return+ }+ try { this.child.stdin.end(options.prompt) } catch (err) { this.fail(err) }+ })+ }++ private onStdout(chunk: string): void {+ this.buffer += chunk+ const lines = this.buffer.split('\n')+ this.buffer = lines.pop() ?? ''+ for (const line of lines) this.handleLine(line)+ }++ private handleLine(line: string): void {+ const trimmed = line.trim()+ if (!trimmed) return+ let evt: Record<string, unknown>+ try { evt = JSON.parse(trimmed) } catch { return }+ if (evt.type === 'text') {+ const part = evt.part as { text?: string } | undefined+ if (part && typeof part.text === 'string') this.assistantParts.push(part.text)+ }+ }++ private cleanupPending(): typeof this.pending {+ const pending = this.pending+ if (!pending) return null+ this.pending = null+ clearTimeout(pending.timer)+ pending.signal?.removeEventListener('abort', pending.onAbort)+ return pending+ }++ private complete(text: string): void {+ this.cleanupPending()?.resolve({ text, sessionId: null })+ }++ private fail(err: unknown): void {+ this.cleanupPending()?.reject(err)+ }+}+function piBin(): string {return env.PI_PATH || 'pi'}@@ -743,6 +895,7 @@ let config: {codexModel?: stringcursorModel?: stringopencodeModel?: string+ kiloModel?: stringpiModel?: stringcommandcodeModel?: stringeffort?: OneShotOptions['effort']@@ -754,6 +907,7 @@ const pool = new DisposableOneShotPool<OneShotOptions, OneShotResult>(async (engif (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()})@@ -763,6 +917,7 @@ export function configureOneShotPool(next: {codexModel?: stringcursorModel?: stringopencodeModel?: string+ kiloModel?: stringpiModel?: stringcommandcodeModel?: stringeffort?: OneShotOptions['effort']@@ -770,7 +925,8 @@ export function configureOneShotPool(next: {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.piModel !== next.piModel ||+ config.opencodeModel !== next.opencodeModel || config.kiloModel !== next.kiloModel ||+ config.piModel !== next.piModel ||config.commandcodeModel !== next.commandcodeModel || config.effort !== next.effort)config = next@@ -807,7 +963,9 @@ function createOneShotWorker(? new PiWorker(cwd, model).ready(): engine === 'commandcode'? new CommandCodeWorker(cwd, model).ready()- : new OpencodeWorker(model).ready()+ : engine === 'kilo'+ ? new KiloWorker(model).ready()+ : new OpencodeWorker(model).ready()}async function runDirect(engine: OneShotEngine, opts: OneShotOptions): Promise<OneShotResult> {@@ -1141,6 +1299,14 @@ export function runOpencodeOneShot(opts: OneShotOptions): Promise<OneShotResult>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".diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.tsindex 129571524..04eab8926 100644--- a/cli/src/lib/registry.ts+++ b/cli/src/lib/registry.ts@@ -199,7 +199,7 @@ class Registry {}let changed = falsefor (const raw of Array.isArray(arr) ? arr : []) {- const engine: AgentEngine = raw?.engine === 'codex' || raw?.engine === 'cursor' || raw?.engine === 'opencode' || raw?.engine === 'pi' || raw?.engine === 'hermes' || raw?.engine === 'commandcode' || raw?.engine === 'devin' || raw?.engine === 'muse' || raw?.engine === 'amp' ? raw.engine : 'claude'+ const engine: AgentEngine = raw?.engine === 'codex' || raw?.engine === 'cursor' || raw?.engine === 'opencode' || raw?.engine === 'pi' || raw?.engine === 'hermes' || raw?.engine === 'commandcode' || raw?.engine === 'devin' || raw?.engine === 'muse' || raw?.engine === 'amp' || raw?.engine === 'kilo' ? raw.engine : 'claude'const pane = typeof raw?.tmuxPane === 'string' && PANE_RE.test(raw.tmuxPane) ? raw.tmuxPane : ''let transcriptPath =typeof raw?.transcriptPath === 'string' && raw.transcriptPath@@ -229,7 +229,7 @@ class Registry {if (!bound) transcriptPath = nullif (!pane- || (bound && engine !== 'cursor' && engine !== 'opencode' && engine !== 'pi' && engine !== 'hermes' && engine !== 'commandcode' && engine !== 'devin' && !transcriptPath)+ || (bound && engine !== 'cursor' && engine !== 'opencode' && engine !== 'kilo' && engine !== 'pi' && engine !== 'hermes' && engine !== 'commandcode' && engine !== 'devin' && !transcriptPath)|| (bound && transcriptPath !== null && !validTranscriptPath(engine, transcriptPath))) {changed = true@@ -366,7 +366,7 @@ class Registry {const sessionId =input.sessionId || (transcriptPath ? basename(transcriptPath).replace(/\.jsonl$/, '') : '')const engine: AgentEngine =- input.engine === 'codex' || input.engine === 'cursor' || input.engine === 'opencode' || input.engine === 'pi' || input.engine === 'hermes' || input.engine === 'commandcode' || input.engine === 'devin' || input.engine === 'muse' || input.engine === 'amp' ? input.engine : 'claude'+ input.engine === 'codex' || input.engine === 'cursor' || input.engine === 'opencode' || input.engine === 'pi' || input.engine === 'hermes' || input.engine === 'commandcode' || input.engine === 'devin' || input.engine === 'muse' || input.engine === 'amp' || input.engine === 'kilo' ? input.engine : 'claude'const pane = input.tmuxPane// The machine id may be omitted only when re-registering a session we already know (the catch hook// fires on every prompt and older payloads carried no id) — a NEW session always needs one, because@@ -377,7 +377,7 @@ class Registry {|| !agentId|| !pane|| !PANE_RE.test(pane)- || (engine !== 'cursor' && engine !== 'opencode' && engine !== 'pi' && engine !== 'hermes' && engine !== 'commandcode' && engine !== 'devin' && !transcriptPath)+ || (engine !== 'cursor' && engine !== 'opencode' && engine !== 'kilo' && engine !== 'pi' && engine !== 'hermes' && engine !== 'commandcode' && engine !== 'devin' && !transcriptPath)|| (transcriptPath && !validTranscriptPath(engine, transcriptPath))) return nullif (engine === 'codex' && transcriptPath && readCodexRolloutMeta(transcriptPath)?.isSubagent) return nulldiff --git a/cli/src/lib/runtimeProfile.ts b/cli/src/lib/runtimeProfile.tsindex 15f459413..b87999555 100644--- a/cli/src/lib/runtimeProfile.ts+++ b/cli/src/lib/runtimeProfile.ts@@ -32,6 +32,11 @@ import {parseOpencodeModelsOutput,type OpencodeModelTarget,} from '../engines/opencode/runtimeProfile.js'+import {+ kiloFooterModelId,+ parseKiloModelsOutput,+ type KiloModelTarget,+} from '../engines/kilo/runtimeProfile.js'import {PI_EFFORTS,PI_THINKING_LEVELS,@@ -102,7 +107,7 @@ interface CodexCache {models?: CodexCacheModel[]}-const PROFILE_RE = /^runtime-v1:([^:]+):(claude|codex|cursor|commandcode|pi|devin|opencode|hermes|muse|amp):([^@]+)@([a-z0-9_-]+)$/i+const PROFILE_RE = /^runtime-v1:([^:]+):(claude|codex|cursor|commandcode|pi|devin|opencode|hermes|muse|amp|kilo):([^@]+)@([a-z0-9_-]+)$/iconst CODEX_EFFORTS = new Set(['auto', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'])const CLAUDE_EFFORTS = new Set(['auto', 'low', 'medium', 'high', 'xhigh', 'max', 'ultracode'])const CURSOR_EFFORTS = new Set(['auto', 'none', 'low', 'medium', 'high', 'xhigh', 'max'])@@ -597,6 +602,7 @@ export class RuntimeProfileManager {private devinCatalogCache: { key: string; expiresAt: number; entries: DevinModelTarget[] } | null = nullprivate piCatalogCache: { key: string; expiresAt: number; entries: ReturnType<typeof parsePiModelsOutput> } | null = nullprivate opencodeCatalogCache: { key: string; expiresAt: number; entries: OpencodeModelTarget[] } | null = null+ private kiloCatalogCache: { key: string; expiresAt: number; entries: KiloModelTarget[] } | null = nullprivate commandcodeCatalogCache: { key: string; expiresAt: number; entries: CommandcodeModelTarget[] } | null = null/** profile id → the full `/model` argument (the profile carries the SHORT name the device labels by). */private readonly commandcodeTargets = new Map<string, Map<string, CommandcodeModelTarget>>()@@ -699,6 +705,12 @@ export class RuntimeProfileManager {await this.opencodeCatalog()return false}+ if (session.engine === 'kilo') {+ // Same reason as opencode: kilo names its model only in the composer footer, which resolves only+ // against the catalog, and `ingestPane` is synchronous.+ await this.kiloCatalog()+ return false+ }if (session.engine === 'devin') {// Same shape: devin's model exists only as a DISPLAY name in its pane footer, and only the catalog// maps that back to a model key + effort. Warm it on attach so the first pane read resolves.@@ -823,6 +835,16 @@ export class RuntimeProfileManager {state.observedAt = Date.now()this.confirmObserved(session.sessionId, id, 'auto')}+ } else if (session.engine === 'kilo') {+ // Kilo names the model in its composer footer too, but the line is shaped differently enough that+ // its resolver had to be rewritten rather than renamed — see engines/kilo/runtimeProfile.ts.+ const id = kiloFooterModelId(paneText, this.kiloCatalogCache?.entries ?? [])+ if (id) {+ state.model = id+ state.effort = 'auto'+ state.observedAt = Date.now()+ this.confirmObserved(session.sessionId, id, 'auto')+ }} else if (session.engine === 'pi') {// Pi puts both axes in one footer cell: `minimax/minimax-m3 • high`.const footer = parsePiFooterProfile(paneText)@@ -1472,6 +1494,43 @@ export class RuntimeProfileManager {return entries}+ /** Kilo has no effort axis either, so every model is one `auto` row. */+ private async kiloModels(session: RegisteredSession): Promise<RuntimeModelOption[]> {+ const entries = await this.kiloCatalog()+ const output: RuntimeModelOption[] = []+ const seen = new Set<string>()+ for (const entry of entries) {+ const id = encodeRuntimeProfile({+ sessionId: session.agentId, engine: 'kilo', model: entry.id, effort: 'auto',+ })+ if (seen.has(id)) continue+ seen.add(id)+ output.push({ id, displayName: entry.id })+ }+ return output+ }++ async kiloCatalog(): Promise<KiloModelTarget[]> {+ const key = env.KILO_DATA_DIR+ if (this.kiloCatalogCache?.key === key && this.kiloCatalogCache.expiresAt > Date.now()) {+ return this.kiloCatalogCache.entries+ }+ let entries: KiloModelTarget[] = []+ try {+ // Measured: `kilo models` answers WITHOUT the user being logged in (unlike `kilo profile`), and+ // prints 299 ids on this machine — so an empty catalog here means the binary is missing, not that+ // the account is signed out.+ const result = await execFileAsync(env.KILO_PATH || 'kilo', ['models'], {+ env: process.env, timeout: 10_000, maxBuffer: 1024 * 1024,+ })+ entries = parseKiloModelsOutput(result.stdout)+ } catch (err) {+ console.warn('[runtime-profile] Kilo model catalog failed:', err instanceof Error ? err.message : err)+ }+ this.kiloCatalogCache = { key, entries, expiresAt: Date.now() + CATALOG_TTL_MS }+ return entries+ }+private async piCatalog(): Promise<ReturnType<typeof parsePiModelsOutput>> {const key = env.PI_HOMEif (this.piCatalogCache?.key === key && this.piCatalogCache.expiresAt > Date.now()) {diff --git a/cli/src/lib/sessionInput.ts b/cli/src/lib/sessionInput.tsindex e6e49581d..fb4b9fcc8 100644--- a/cli/src/lib/sessionInput.ts+++ b/cli/src/lib/sessionInput.ts@@ -10,6 +10,10 @@ const CLAUDE_SUBMIT_VERIFY_MS = 3_000// OpenCode's accept signal is the reader's DB poll (~1s) surfacing a new user row → turn_started, so// give it a slightly longer window than the file-based engines before a retry-Enter.const OPENCODE_SUBMIT_VERIFY_MS = 2_500+// Kilo is opencode's fork and its user row lands on Enter the same way, read by the same 1s DB poll, so+// it gets the same window. Measured on a live pane: the row is written as the turn opens, not when the+// model replies — so this covers the poll, not model latency (which is Command Code's problem, not this).+const KILO_SUBMIT_VERIFY_MS = 2_500// Pi has no composer glyph either, and its JSONL is written per completed message — give the derived// turn_started a comparable window before re-pressing Enter.const PI_SUBMIT_VERIFY_MS = 2_500@@ -284,7 +288,9 @@ export class SessionInputController {? MUSE_SUBMIT_VERIFY_MS: session.engine === 'amp'? AMP_SUBMIT_VERIFY_MS- : SUBMIT_VERIFY_MS)+ : session.engine === 'kilo'+ ? KILO_SUBMIT_VERIFY_MS+ : SUBMIT_VERIFY_MS)}private async retrySubmit(sessionId: string, session: RegisteredSession, state: InputState): Promise<void> {@@ -304,7 +310,7 @@ export class SessionInputController {this.deps.onError(sessionId, 'The agent did not accept the message. Please try again.')return}- } else if (session.engine === 'opencode' || session.engine === 'pi' || session.engine === 'hermes' || session.engine === 'muse'+ } else if (session.engine === 'opencode' || session.engine === 'kilo' || session.engine === 'pi' || session.engine === 'hermes' || session.engine === 'muse'|| session.engine === 'amp') {// OpenCode has no composer glyph, and the submitted text stays visible in the message area, so a// pane scrape can't tell "still in the composer" from "already sent". Rely purely on the reader-diff --git a/cli/src/lib/sessionRepair.ts b/cli/src/lib/sessionRepair.tsindex d7d7290dc..b4bd01ad3 100644--- a/cli/src/lib/sessionRepair.ts+++ b/cli/src/lib/sessionRepair.ts@@ -273,6 +273,15 @@ export async function findLiveSession(+ ` AND (time_created >= ${Math.trunc(sinceMs)} OR time_updated >= ${Math.trunc(sinceMs)})`+ ` ORDER BY time_updated DESC LIMIT 2;`,)+ case 'kilo':+ // Same store shape as opencode (measured: `session` is byte-identical between the two DBs), and+ // time_created is epoch MILLISECONDS here too — the real row on this machine reads 1786091927554.+ return dbEngineSession(+ join(env.KILO_DATA_DIR, 'kilo.db'),+ `SELECT id FROM session WHERE directory IN (${dirList}) AND parent_id IS NULL`+ + ` AND (time_created >= ${Math.trunc(sinceMs)} OR time_updated >= ${Math.trunc(sinceMs)})`+ + ` ORDER BY time_updated DESC LIMIT 2;`,+ )case 'hermes':// started_at is epoch SECONDS (fractional).return dbEngineSession(diff --git a/cli/src/lib/summarize.spec.ts b/cli/src/lib/summarize.spec.tsindex e93492bba..9055b9e8a 100644--- a/cli/src/lib/summarize.spec.ts+++ b/cli/src/lib/summarize.spec.ts@@ -68,20 +68,23 @@ describe('Cursor recap', () => {expect(mocks.cleanupCursor).toHaveBeenCalledWith('cursor-recap-session')})- it('includes Cursor, OpenCode and Pi sessions when sizing recap workers', () => {+ 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, pi: 1, commandcode: 1 })+ expect(mocks.setCounts).toHaveBeenCalledWith({ claude: 1, codex: 1, cursor: 2, opencode: 1, kilo: 1, pi: 1, commandcode: 1 })})})diff --git a/cli/src/lib/summarize.ts b/cli/src/lib/summarize.tsindex 168b5be5a..f93437286 100644--- a/cli/src/lib/summarize.ts+++ b/cli/src/lib/summarize.ts@@ -19,6 +19,7 @@ import {runCodexOneShot,runCursorOneShot,runOpencodeOneShot,+ runKiloOneShot,runPiOneShot,runHermesOneShot,runCommandCodeOneShot,@@ -46,13 +47,14 @@ configureOneShotPool({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, pi: 0, commandcode: 0 }+ 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.@@ -305,7 +307,9 @@ export async function summarizeTurnText(// Amp's is an agent MODE (low|medium|high|ultra), not a model name — it exposes no models.: engine === 'amp'? env.AMP_SUMMARY_MODE- : env.OPENCODE_SUMMARY_MODEL+ : engine === 'kilo'+ ? env.KILO_SUMMARY_MODEL+ : env.OPENCODE_SUMMARY_MODELconst effort = engine === 'cursor' ? 'model-defined' : env.SUMMARY_EFFORTconsole.log(`[recap] one-shot ${engine} · model=${model} · effort=${effort} · inputChars=${last.length}${ask ? ' · withAsk' : ''}`)const run = engine === 'claude'@@ -326,7 +330,9 @@ export async function summarizeTurnText(? runMuseOneShot: engine === 'amp'? runAmpOneShot- : runOpencodeOneShot+ : engine === 'kilo'+ ? runKiloOneShot+ : runOpencodeOneShotlet r = await run({ prompt, model, effort: env.SUMMARY_EFFORT, cwd: scratch, signal })console.log(`[recap] one-shot returned in ${Date.now() - t0}ms · rawLen=${(r.text || '').length}`)await cleanupRecapSession(engine, scratch, r.sessionId)diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.tsindex 6a9b11254..7999451c5 100644--- a/cli/src/lib/tmux.ts+++ b/cli/src/lib/tmux.ts@@ -169,6 +169,13 @@ export function engineProcessMatchScore(if (executable === 'opencode') return 3return /(^|[\/\s])opencode(?:[\s]|$)/.test(haystack) ? 1 : 0}+ if (engine === 'kilo') {+ // `@kilocode/cli` installs the same file under both names, and kilo's own installer puts a second+ // copy at ~/.kilo/bin/kilo — so match either spelling as the executable, and fall back to the argv+ // scan for the wrapper form. `kilocode` is listed first so the weak regex below cannot claim it.+ if (executable === 'kilo' || executable === 'kilocode') return 3+ return /(^|[\/\s])kilocode?(?:[\s]|$)/.test(haystack) ? 1 : 0+ }if (engine === 'commandcode') {// The TUI overwrites its own argv within the first second — `ps` shows `⌘ Command Code · <dir>` and// then `⌘ <session title>`, with no trace of the node entrypoint. So the ⌘ (U+2318) prefix is the@@ -259,6 +266,10 @@ function selectEngineProcess(const RESUME_ARGS: Partial<Record<RegisteredSession['engine'], { flags: string[]; id: RegExp }>> = {cursor: { flags: ['--resume'], id: /^[0-9a-f-]{16,}$/i },opencode: { flags: ['--session', '-s'], id: /^ses_[A-Za-z0-9]+$/ },+ // Kilo inherits opencode's resume flags and its `ses_` id prefix — measured on this machine's kilo.db:+ // `ses_024a007fdffe11yG68JPxsHJly`. `--fork` is deliberately NOT here: it CONTINUES from an id but+ // writes a NEW session, so the id in argv is the parent's and would bind the agent to the wrong row.+ kilo: { flags: ['--session', '-s'], id: /^ses_[A-Za-z0-9]+$/ },pi: { flags: ['--session', '--session-id'], id: /^[0-9a-f][0-9a-f-]{7,}$/i },// Hermes ids are timestamps: 20260728_115628_f2c86a.hermes: { flags: ['--resume'], id: /^\d{8}_\d{6}_[0-9a-z]+$/i },diff --git a/cli/src/lib/voiceRouter.ts b/cli/src/lib/voiceRouter.tsindex f98c4a088..7fb00bf23 100644--- a/cli/src/lib/voiceRouter.ts+++ b/cli/src/lib/voiceRouter.ts@@ -30,7 +30,7 @@ const ROUTE_SCRATCH = join(env.ADAPTER_DATA_DIR, 'voice-route-scratch')/** Engines that can serve the router, best first. Hermes and Devin are absent on purpose: they take the* prompt as argv so they cannot be pre-warmed — the same exclusion the recap pool makes. */-const ROUTER_ENGINE_PRIORITY = ['claude', 'codex', 'commandcode', 'cursor', 'pi', 'opencode'] as const+const ROUTER_ENGINE_PRIORITY = ['claude', 'codex', 'commandcode', 'cursor', 'pi', 'opencode', 'kilo'] as constexport type RouterEngine = (typeof ROUTER_ENGINE_PRIORITY)[number]/**