Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

41.6 KB
Raw Blame
/** Disposable one-shot processes used by device recaps and voice routing. */

import { spawn, type ChildProcess } from 'child_process'
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs'
import { chmod, copyFile, mkdtemp, readFile, readdir, rm, unlink } from 'fs/promises'
import { dirname, join } from 'path'
import { randomUUID } from 'crypto'
import { homedir, tmpdir, userInfo } from 'os'
import { env } from '../config/env.js'
import { findCursorTranscript } from '../engines/cursor/discovery.js'
import { cursorConfigDir, cursorDataDir } from '../engines/cursor/home.js'
import { cursorRuntimeBin, opencodeBin } from './engineBin.js'
import {
  DisposableOneShotPool,
  type ActiveEngineCounts,
  type DisposableWorker,
  type OneShotEngine,
} from './disposableOneShotPool.js'
import { oneShotParentEnv } from './loginShellEnv.js'
import { scrubTerminalContext } from './terminalEnvironment.js'
import { ownProcessGroup } from './windows/noWindow.js'

function claudeBin(): string {
  return env.CLAUDE_PATH || 'claude'
}

function cursorBin(): string {
  const bin = cursorRuntimeBin()
  if (bin) return bin
  throw new Error('Cursor CLI command is ambiguous or unavailable; install cursor-agent or set CURSOR_PATH to its absolute path')
}

function buildEnv(): NodeJS.ProcessEnv {
  return {
    PATH: process.env.PATH || '',
    HOME: process.env.HOME || homedir(),
    USER: process.env.USER || userInfo().username,
    LOGNAME: process.env.LOGNAME || process.env.USER || userInfo().username,
    TMPDIR: tmpdir(),
    LANG: process.env.LANG || 'en_US.UTF-8',
    TERM: process.env.TERM || 'xterm-256color',
    NODE_ENV: process.env.NODE_ENV || 'production',
    ...(process.env.ANTHROPIC_BASE_URL && { ANTHROPIC_BASE_URL: process.env.ANTHROPIC_BASE_URL }),
    ...(process.env.ANTHROPIC_AUTH_TOKEN && { ANTHROPIC_AUTH_TOKEN: process.env.ANTHROPIC_AUTH_TOKEN }),
  }
}

export interface OneShotOptions {
  prompt: string
  model?: string
  effort?: 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'ultra' | 'ultracode'
  /** The collection agent's own Codex login profile, when it has one. */
  codexHome?: string
  cwd: string
  timeoutMs?: number
  signal?: AbortSignal
}

type OneShotResult = { text: string; sessionId: string | null }

function abortError(engine: OneShotEngine): Error {
  return Object.assign(new Error(`${engine} one-shot aborted`), { name: 'AbortError' })
}

function killGroup(child: ChildProcess, signal: NodeJS.Signals = 'SIGKILL'): void {
  if (child.pid == null || child.exitCode != null) return
  try { process.kill(-child.pid, signal) } catch {
    try { child.kill(signal) } catch { /* already gone */ }
  }
}

export async function cleanupCursorOneShotSession(sessionId: string): Promise<void> {
  const transcript = await findCursorTranscript(cursorDataDir(), sessionId)
  if (transcript) await rm(dirname(transcript), { recursive: true, force: true }).catch(() => {})

  const chatsRoot = join(cursorConfigDir(), 'chats')
  const workspaces = await readdir(chatsRoot, { withFileTypes: true }).catch(() => [])
  await Promise.all(workspaces
    .filter((entry) => entry.isDirectory())
    .map((entry) => rm(join(chatsRoot, entry.name, sessionId), { recursive: true, force: true }).catch(() => {})))
}

abstract class ProcessWorker implements DisposableWorker<OneShotOptions, OneShotResult> {
  readonly createdAt = Date.now()
  protected assigned = false
  protected readonly child: ChildProcess
  private readonly exitListeners = new Set<() => void>()
  private readonly spawned: Promise<void>

  abstract readonly engine: OneShotEngine
  abstract run(options: OneShotOptions): Promise<OneShotResult>

  constructor(child: ChildProcess) {
    this.child = child
    this.spawned = new Promise((resolve, reject) => {
      child.once('spawn', () => resolve())
      child.once('error', reject)
    })
    child.once('close', () => {
      for (const listener of this.exitListeners) listener()
      this.exitListeners.clear()
    })
  }

  ready(): Promise<this> {
    return this.spawned.then(() => this)
  }

  isAlive(): boolean {
    return this.child.exitCode == null && !this.child.killed
  }

  onExit(listener: () => void): void {
    this.exitListeners.add(listener)
  }

  dispose(): void {
    killGroup(this.child)
  }
}

class ClaudeWorker extends ProcessWorker {
  readonly engine = 'claude' as const
  private buffer = ''
  private stderr = ''
  private sessionId: string | null = null
  private resultText = ''
  private readonly assistantParts: string[] = []
  private pending: {
    resolve: (result: OneShotResult) => void
    reject: (err: unknown) => void
    timer: NodeJS.Timeout
    signal?: AbortSignal
    onAbort: () => void
  } | null = null

  constructor(cwd: string, model?: string, effort?: OneShotOptions['effort']) {
    const args = [
      '--print', '--verbose',
      '--input-format', 'stream-json',
      '--output-format', 'stream-json',
      '--no-session-persistence',
      // Recap is pure text condensation. Keep Claude from loading project/user customizations,
      // slash-command skills, MCP servers, or built-in tools.
      '--safe-mode',
      '--disable-slash-commands',
      '--tools', '',
      '--strict-mcp-config', '--mcp-config', '{"mcpServers":{}}',
      ...(model ? ['--model', model] : []),
      ...(effort ? ['--effort', effort] : []),
    ]
    const child = spawn(claudeBin(), args, {
      cwd, env: buildEnv(), ...ownProcessGroup(), 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.resultText || this.assistantParts.join('')).trim()
      if (!text && code !== 0) this.fail(new Error(`claude 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('claude 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(`claude 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('claude recap worker is not writable'))
        return
      }
      try {
        this.child.stdin.write(JSON.stringify({ type: 'user', message: { role: 'user', content: options.prompt } }) + '\n')
      } 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 (typeof evt.session_id === 'string' && !this.sessionId) this.sessionId = evt.session_id
    if (evt.type === 'assistant') {
      const content = (evt.message as { content?: Array<{ type?: string; text?: string }> } | undefined)?.content
      if (Array.isArray(content)) {
        const text = content.filter((part) => part?.type === 'text').map((part) => part.text ?? '').join('')
        if (text) this.assistantParts.push(text)
      }
    }
    if (evt.type === 'result') {
      if (typeof evt.result === 'string') this.resultText = evt.result
      this.complete((this.resultText || this.assistantParts.join('')).trim())
    }
  }

  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 {
    const pending = this.cleanupPending()
    pending?.resolve({ text, sessionId: this.sessionId })
  }

  private fail(err: unknown): void {
    this.cleanupPending()?.reject(err)
  }
}

class CodexWorker extends ProcessWorker {
  readonly engine = 'codex' as const
  private stderr = ''
  private readonly output: string
  private pending: {
    resolve: (result: OneShotResult) => void
    reject: (err: unknown) => void
    timer: NodeJS.Timeout
    signal?: AbortSignal
    onAbort: () => void
  } | null = null

  constructor(cwd: string, model?: string, effort?: OneShotOptions['effort'], codexHome?: string) {
    const output = join(cwd, `.codex-recap-${randomUUID()}.txt`)
    const args = [
      'exec', '--json', '--ephemeral', '--sandbox', 'read-only', '--skip-git-repo-check',
      '--ignore-user-config', '--ignore-rules', '--output-last-message', output,
      ...(model ? ['--model', model] : []),
      ...(effort ? ['-c', `model_reasoning_effort="${effort}"`] : []),
      '-',
    ]
    const processEnv = scrubTerminalContext({ ...oneShotParentEnv() })
    if (codexHome) processEnv.CODEX_HOME = codexHome
    const child = spawn(process.env.CODEX_PATH || 'codex', args, {
      cwd, env: processEnv, ...ownProcessGroup(), stdio: ['pipe', 'ignore', 'pipe'],
    })
    super(child)
    this.output = output
    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) => { void this.onClose(code) })
  }

  override dispose(): void {
    super.dispose()
    void unlink(this.output).catch(() => {})
  }

  run(options: OneShotOptions): Promise<OneShotResult> {
    if (this.assigned) return Promise.reject(new Error('codex 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(`codex 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('codex recap worker is not writable'))
        return
      }
      try { this.child.stdin.end(options.prompt) } catch (err) { this.fail(err) }
    })
  }

  private async onClose(code: number | null): Promise<void> {
    if (!this.pending) return
    const text = (await readFile(this.output, 'utf8').catch(() => '')).trim()
    await unlink(this.output).catch(() => {})
    if (!text && code !== 0) this.fail(new Error(`codex one-shot exited ${code}: ${this.stderr.slice(0, 500)}`))
    else this.complete(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)
  }
}

class CursorWorker extends ProcessWorker {
  readonly engine = 'cursor' as const
  private buffer = ''
  private stderr = ''
  private sessionId: string | null = null
  private resultText = ''
  private cleanupScheduled = false
  private readonly assistantParts: string[] = []
  private pending: {
    resolve: (result: OneShotResult) => void
    reject: (err: unknown) => void
    timer: NodeJS.Timeout
    signal?: AbortSignal
    onAbort: () => void
  } | null = null

  constructor(cwd: string, model?: string) {
    const args = [
      '--print',
      '--mode', 'ask',
      '--sandbox', 'enabled',
      '--trust',
      '--output-format', 'stream-json',
      ...(model ? ['--model', model] : []),
    ]
    const processEnv = scrubTerminalContext({ ...oneShotParentEnv() })
    const child = spawn(cursorBin(), args, {
      cwd, env: processEnv, ...ownProcessGroup(), 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.resultText || this.assistantParts.join('')).trim()
      if (!text && code !== 0) this.fail(new Error(`cursor 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('cursor 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(`cursor 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('cursor recap worker is not writable'))
        return
      }
      try { this.child.stdin.end(options.prompt) } catch (err) { this.fail(err) }
    })
  }

  override dispose(): void {
    super.dispose()
    if (this.cleanupScheduled) return
    this.cleanupScheduled = true
    const cleanup = (): void => {
      if (this.sessionId) void cleanupCursorOneShotSession(this.sessionId)
    }
    if (this.child.exitCode != null) cleanup()
    else this.child.once('close', cleanup)
  }

  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 (typeof evt.session_id === 'string' && !this.sessionId) this.sessionId = evt.session_id
    if (evt.type === 'assistant') {
      const content = (evt.message as { content?: Array<{ type?: string; text?: string }> } | undefined)?.content
      if (Array.isArray(content)) {
        const text = content.filter((part) => part?.type === 'text').map((part) => part.text ?? '').join('')
        if (text) this.assistantParts.push(text)
      }
    }
    if (evt.type !== 'result') return
    if (typeof evt.result === 'string') this.resultText = evt.result
    if (evt.is_error === true || evt.subtype === 'error') {
      this.fail(new Error(`cursor one-shot failed: ${(this.resultText || this.stderr).slice(0, 500)}`))
      return
    }
    this.complete((this.resultText || this.assistantParts.join('')).trim())
  }

  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: this.sessionId })
  }

  private fail(err: unknown): void {
    this.cleanupPending()?.reject(err)
  }
}

// Isolate session storage while retaining the user's provider config and auth.json location.
const OPENCODE_RECAP_DATA_DIR = join(env.ADAPTER_DATA_DIR, 'opencode-recap')

export function opencodeOneShotSpawn(model: string | undefined, parentEnv: NodeJS.ProcessEnv, dataDir: string) {
  const childEnv = scrubTerminalContext({ ...parentEnv })
  // OpenCode ignores OPENCODE_DATA_DIR. Its absolute OPENCODE_DB override selects the real store.
  childEnv.OPENCODE_DB = join(dataDir, 'opencode.db')
  childEnv.PWD = dataDir
  return {
    args: ['run', '--pure', '--format', 'json', ...(model ? ['--model', model] : [])],
    env: childEnv,
  }
}

class OpencodeWorker extends ProcessWorker {
  readonly engine = 'opencode' 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) {
    // `opencode 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 machine discovery plugin never
    // self-registers this ephemeral recap session). `--format json` streams `{type:'text',part:{text}}`.
    mkdirSync(OPENCODE_RECAP_DATA_DIR, { recursive: true, mode: 0o700 })
    const { args, env: processEnv } = opencodeOneShotSpawn(model, oneShotParentEnv(), OPENCODE_RECAP_DATA_DIR)
    const child = spawn(opencodeBin(), args, {
      cwd: OPENCODE_RECAP_DATA_DIR, env: processEnv, ...ownProcessGroup(), 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(`opencode 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('opencode 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(`opencode 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('opencode 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 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_DB`; this Kilo worker uses an isolated data root — 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 = scrubTerminalContext({ ...parentEnv })
  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 for this disposable worker only. 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
    // — the interactive TUI remains entirely under the user's own permission configuration.
    mkdirSync(KILO_RECAP_DATA_DIR, { recursive: true, mode: 0o700 })
    // `--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, oneShotParentEnv())
    const child = spawn(kiloBin(), args, {
      cwd: KILO_RECAP_DATA_DIR, env: processEnv, ...ownProcessGroup(), 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'
}

class PiWorker extends ProcessWorker {
  readonly engine = 'pi' as const
  private stdout = ''
  private stderr = ''
  private pending: {
    resolve: (result: OneShotResult) => void
    reject: (err: unknown) => void
    timer: NodeJS.Timeout
    signal?: AbortSignal
    onAbort: () => void
  } | null = null

  constructor(cwd: string, model?: string) {
    // `pi -p` reads the prompt from piped stdin (merged into the initial prompt) and prints the plain
    // answer, so the worker can be pre-warmed and fed later. `--no-session` keeps the recap out of the
    // user's session store; `--no-extensions` stops the machine discovery extension from registering it.
    const args = ['-p', '--no-session', '--no-extensions', ...(model ? ['--model', model] : [])]
    const processEnv = scrubTerminalContext({ ...oneShotParentEnv() })
    const child = spawn(piBin(), args, {
      cwd, env: processEnv, ...ownProcessGroup(), stdio: ['pipe', 'pipe', 'pipe'],
    })
    super(child)
    child.stdout?.on('data', (chunk: Buffer) => { this.stdout += 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.pending) return
      const text = this.stdout.trim()
      if (!text && code !== 0) this.fail(new Error(`pi 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('pi 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(`pi 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('pi recap worker is not writable'))
        return
      }
      try { this.child.stdin.end(options.prompt) } catch (err) { this.fail(err) }
    })
  }

  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 commandCodeBin(): string {
  return env.COMMANDCODE_PATH || 'commandcode'
}

class CommandCodeWorker extends ProcessWorker {
  readonly engine = 'commandcode' as const
  private stdout = ''
  private stderr = ''
  private pending: {
    resolve: (result: OneShotResult) => void
    reject: (err: unknown) => void
    timer: NodeJS.Timeout
    signal?: AbortSignal
    onAbort: () => void
  } | null = null

  constructor(cwd: string, model?: string) {
    // `commandcode -p` reads the prompt from piped stdin (verified), so the worker pre-warms and is fed
    // later. `--no-session` keeps the recap out of the user's project/session list — without it every
    // recap shows up as a session. There is no --no-hooks flag; the scrubbed terminal context below
    // stops our own SessionStart hook registering this process.
    const args = ['-p', '--no-session', ...(model ? ['-m', model] : [])]
    const processEnv = scrubTerminalContext({ ...oneShotParentEnv() })
    const child = spawn(commandCodeBin(), args, {
      cwd, env: processEnv, ...ownProcessGroup(), stdio: ['pipe', 'pipe', 'pipe'],
    })
    super(child)
    child.stdout?.on('data', (chunk: Buffer) => { this.stdout += 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.pending) return
      const text = this.stdout.trim()
      if (!text && code !== 0) this.fail(new Error(`commandcode 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('commandcode 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(`commandcode 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('commandcode recap worker is not writable'))
        return
      }
      try { this.child.stdin.end(options.prompt) } catch (err) { this.fail(err) }
    })
  }

  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)
  }
}

/** Spawn ONE worker for an engine. Shared by the cold path and both warm pools so a pooled worker can
 *  never be started differently from a direct one. */
function createOneShotWorker(
  engine: OneShotEngine,
  cwd: string,
  model?: string,
  effort?: OneShotOptions['effort'],
  codexHome?: string,
): Promise<DisposableWorker<OneShotOptions, OneShotResult>> {
  return engine === 'claude'
    ? new ClaudeWorker(cwd, model, effort).ready()
    : engine === 'codex'
      ? new CodexWorker(cwd, model, effort, codexHome).ready()
      : engine === 'cursor'
        ? new CursorWorker(cwd, model).ready()
        : engine === 'pi'
          ? new PiWorker(cwd, model).ready()
          : engine === 'commandcode'
            ? new CommandCodeWorker(cwd, model).ready()
            : engine === 'kilo'
              ? new KiloWorker(model).ready()
              : new OpencodeWorker(model).ready()
}

/** The measured Grok 1.0.0 headless invocation. A fresh GROK_HOME contains every persisted session. */
export function grokOneShotSpawn(
  opts: Pick<OneShotOptions, 'prompt' | 'model' | 'effort' | 'cwd'>,
  scratchHome: string,
  parentEnv: NodeJS.ProcessEnv = oneShotParentEnv(),
): { args: string[]; env: NodeJS.ProcessEnv } {
  const args = [
    '--cwd', opts.cwd,
    '--always-approve', '--no-memory', '--no-plan', '--max-turns', '1',
    '--output-format', 'json',
    ...(opts.model ? ['--model', opts.model] : []),
    ...(opts.effort ? ['--reasoning-effort', opts.effort] : []),
    '-p', opts.prompt,
  ]
  const childEnv: NodeJS.ProcessEnv = scrubTerminalContext({ ...parentEnv, GROK_HOME: scratchHome })
  delete childEnv.MACHINE_ID
  return { args, env: childEnv }
}

function grokOutputText(stdout: string): string {
  const candidates = [stdout.trim(), ...stdout.trim().split('\n').reverse()]
  for (const candidate of candidates) {
    if (!candidate) continue
    try {
      const parsed = JSON.parse(candidate) as { text?: unknown; result?: unknown }
      if (typeof parsed.text === 'string') return parsed.text.trim()
      if (typeof parsed.result === 'string') return parsed.result.trim()
    } catch { /* try the next complete JSON value */ }
  }
  return ''
}

/** Grok takes its print prompt on argv, so it cannot be pre-warmed. Its real CLI always persists a
 * session; isolating GROK_HOME and deleting it afterwards is the no-pollution equivalent. */
export async function runGrokOneShot(opts: OneShotOptions): Promise<OneShotResult> {
  if (opts.signal?.aborted) throw Object.assign(new Error('grok one-shot aborted'), { name: 'AbortError' })
  mkdirSync(opts.cwd, { recursive: true })
  const scratchHome = await mkdtemp(join(opts.cwd, '.grok-recap-'))
  try {
    // Copy auth/config into the short-lived home. A symlink would keep session writes isolated but still
    // let a token refresh or config migration mutate the user's real files through the link.
    for (const name of ['auth.json', 'config.toml']) {
      const source = join(env.GROK_HOME, name)
      if (!existsSync(source)) continue
      const target = join(scratchHome, name)
      await copyFile(source, target)
      await chmod(target, 0o600)
    }
    const { args, env: processEnv } = grokOneShotSpawn(opts, scratchHome)
    const timeoutMs = opts.timeoutMs ?? 60_000
    return await new Promise<OneShotResult>((resolve, reject) => {
      const child = spawn(env.GROK_PATH || 'grok', args, {
        cwd: opts.cwd, env: processEnv, ...ownProcessGroup(), stdio: ['ignore', 'pipe', 'pipe'],
      })
      let stdout = ''
      let stderr = ''
      let settled = false
      const finish = (fn: () => void): void => {
        if (settled) return
        settled = true
        clearTimeout(timer)
        opts.signal?.removeEventListener('abort', onAbort)
        fn()
      }
      const kill = (): void => killGroup(child)
      const onAbort = (): void => {
        finish(() => reject(Object.assign(new Error('grok one-shot aborted'), { name: 'AbortError' })))
        kill()
      }
      const timer = setTimeout(() => {
        finish(() => reject(new Error(`grok one-shot timed out after ${timeoutMs}ms`)))
        kill()
      }, timeoutMs)
      opts.signal?.addEventListener('abort', onAbort)
      child.stdout?.on('data', (chunk: Buffer) => { stdout += chunk.toString() })
      child.stderr?.on('data', (chunk: Buffer) => { stderr += chunk.toString() })
      child.on('error', (err) => finish(() => reject(err)))
      child.on('close', (code) => {
        const text = grokOutputText(stdout)
        finish(() => {
          if (!text) reject(new Error(`grok one-shot exited ${code}: ${stderr.slice(0, 500)}`))
          else resolve({ text, sessionId: null })
        })
      })
    })
  } finally {
    await rm(scratchHome, { recursive: true, force: true }).catch(() => {})
  }
}

// ── Voice-router warm worker ─────────────────────────────────────────────────────────────────────────
// The Overview voice router runs a tiny classifier on EVERY voice turn. Spawning the CLI each time paid a
// cold start (Node boot + CLI init + auth) that occasionally blew the 12s budget → "voice_route timed out".
// Keep ONE router worker warm (device-gated) so the classify skips the spawn. The router uses its own
// small model, and only ever needs one worker.
//
// The ENGINE is chosen by the caller from the machine's live agents (see voiceRouter.chooseRouterEngine).
// It used to be pinned to claude here, which meant a machine with no Claude CLI never routed at all: the
// warm spawn failed on a loop and every voice fell through to the name-matching heuristic, whose capped
// confidence can never clear the backend's auto-dispatch threshold.
let routerConfig: { engine: OneShotEngine; cwd: string; model?: string; effort?: OneShotOptions['effort'] } | null = null
const routerPool = new DisposableOneShotPool<OneShotOptions, OneShotResult>(
  async () => {
    if (!routerConfig) throw new Error('router pool is not configured')
    return createOneShotWorker(routerConfig.engine, routerConfig.cwd, routerConfig.model, routerConfig.effort)
  },
  5 * 60_000,
  (line) => console.log(line.replace('[one-shot-pool]', '[router-pool]')),
)

/** Routing needs exactly ONE warm worker, of the configured engine — active=1 there, 0 everywhere else. */
function pinRouterEngine(engine: OneShotEngine): void {
  routerPool.setActiveCounts({
    claude: 0, codex: 0, cursor: 0, opencode: 0, pi: 0, commandcode: 0, [engine]: 1,
  } as Parameters<typeof routerPool.setActiveCounts>[0])
}

export function configureRouterOneShot(next: { engine: OneShotEngine; cwd: string; model?: string; effort?: OneShotOptions['effort'] }): void {
  const changed = routerConfig != null && (
    routerConfig.engine !== next.engine || routerConfig.cwd !== next.cwd ||
    routerConfig.model !== next.model || routerConfig.effort !== next.effort
  )
  routerConfig = next
  pinRouterEngine(next.engine)
  // An engine change must drop the warm worker too — it is the wrong CLI now, not just the wrong model.
  if (changed) routerPool.recycleReady()
}

export function setRouterOneShotDeviceConnected(connected: boolean): void {
  routerPool.setDeviceConnected(connected)
}

export function shutdownRouterOneShot(): void {
  routerPool.shutdown()
}

/** One worker started and gone after one run: what the router uses when its warm worker does not match. */
async function runDirect(engine: OneShotEngine, opts: OneShotOptions): Promise<OneShotResult> {
  const worker = await createOneShotWorker(engine, opts.cwd, opts.model, opts.effort, opts.codexHome)
  try { return await worker.run(opts) } finally { worker.dispose() }
}

/** A one-shot served from the dedicated warm router worker (a cold spawn only if the pool isn't
 *  configured for this exact engine, cwd, model and effort). */
export function runRouterOneShot(engine: OneShotEngine, opts: OneShotOptions): Promise<OneShotResult> {
  if (opts.signal?.aborted) return Promise.reject(abortError(engine))
  if (!routerConfig || routerConfig.engine !== engine || routerConfig.cwd !== opts.cwd ||
      routerConfig.model !== opts.model || routerConfig.effort !== opts.effort) {
    return runDirect(engine, opts)
  }
  return routerPool.run(engine, opts)
}