@dmrlzz/davecode 0.5.2 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/README.md +1 -0
  2. package/dist/{ChatApp-Z6PQIZ5J.js → ChatApp-RQZ2IZFQ.js} +6 -6
  3. package/dist/{account-RTPS2V6O.js → account-FY6THFLW.js} +3 -3
  4. package/dist/{accounts-IYQ4ZRL7.js → accounts-ZV3KMLC5.js} +5 -5
  5. package/dist/{budget-N2ZB66FF.js → budget-OUOEMMOM.js} +4 -4
  6. package/dist/{chat-6TX6JX45.js → chat-OHVP4BS3.js} +8 -8
  7. package/dist/{chunk-UEV5K3DH.js → chunk-2MM5WT5J.js} +3 -3
  8. package/dist/{chunk-UNK3EQD6.js → chunk-2P5DJWIJ.js} +4 -4
  9. package/dist/{chunk-QKY3OKVG.js → chunk-2XGDILCW.js} +1677 -133
  10. package/dist/chunk-2XGDILCW.js.map +1 -0
  11. package/dist/{chunk-LEU46DGH.js → chunk-FFB2QA5I.js} +2 -2
  12. package/dist/{goal-STLEU7C7.js → chunk-HL4RIXPM.js} +8 -8
  13. package/dist/chunk-HL4RIXPM.js.map +1 -0
  14. package/dist/{chunk-WAARDGCZ.js → chunk-L7NEDOA3.js} +2 -2
  15. package/dist/{chunk-BJTXMET2.js → chunk-NKRI6SYR.js} +2 -2
  16. package/dist/{chunk-KUY3QHGS.js → chunk-TP3ORSHY.js} +134 -4
  17. package/dist/chunk-TP3ORSHY.js.map +1 -0
  18. package/dist/{chunk-YNAMNQLW.js → chunk-U5CI774J.js} +3 -3
  19. package/dist/{config-YQKY2AA4.js → config-ZLO3YOUX.js} +3 -3
  20. package/dist/dashboard/assets/Accounts-CIhOt9FH.js +1 -0
  21. package/dist/dashboard/assets/{Callout-1E8Wsl9W.js → Callout-CqdcH6dC.js} +1 -1
  22. package/dist/dashboard/assets/Goals-CITP2GqG.js +1 -0
  23. package/dist/dashboard/assets/{Library-DZxBVUo_.js → Library-DnCIb76j.js} +1 -1
  24. package/dist/dashboard/assets/{Panes-C-TJekjs.js → Panes-DBqKYuaE.js} +3 -3
  25. package/dist/dashboard/assets/RoutesPage-BNVmKhyU.js +4 -0
  26. package/dist/dashboard/assets/Runner-KR35ZWUE.js +1 -0
  27. package/dist/dashboard/assets/Settings-B5qE-a5O.js +1 -0
  28. package/dist/dashboard/assets/Tasks-bJLfNJmS.js +2 -0
  29. package/dist/dashboard/assets/Traffic-CGfilrRx.js +1 -0
  30. package/dist/dashboard/assets/Workspace-Dc3cvct_.js +1 -0
  31. package/dist/dashboard/assets/format-328qIBHX.js +111 -0
  32. package/dist/dashboard/assets/index-C-bwzlsl.js +50 -0
  33. package/dist/dashboard/assets/index-D9FCfPmM.css +2 -0
  34. package/dist/dashboard/assets/task-errors-DK4-900l.js +1 -0
  35. package/dist/dashboard/index.html +3 -3
  36. package/dist/{dist-PIC255RX.js → dist-56V3DLJ4.js} +16 -2
  37. package/dist/{doctor-PQC7JQPP.js → doctor-DUOKUSJL.js} +3 -3
  38. package/dist/goal-WG37XHUY.js +26 -0
  39. package/dist/index.js +64 -31
  40. package/dist/index.js.map +1 -1
  41. package/dist/{init-NHU5LJSS.js → init-WW4XPFMM.js} +3 -3
  42. package/dist/orchestrate-7YQDBS3E.js +382 -0
  43. package/dist/orchestrate-7YQDBS3E.js.map +1 -0
  44. package/dist/{run-7HWSHMRJ.js → run-QB4SGPEC.js} +3 -3
  45. package/dist/runtime.js +6 -2
  46. package/dist/{start-WVAEAQWL.js → start-U4RL377T.js} +3 -3
  47. package/dist/{status-ZRHPFLFT.js → status-GHVMGZI5.js} +4 -4
  48. package/dist/status-GHVMGZI5.js.map +1 -0
  49. package/dist/{tasks-JVWXUNXN.js → tasks-VTBJ4B2G.js} +4 -4
  50. package/package.json +4 -4
  51. package/dist/chunk-KUY3QHGS.js.map +0 -1
  52. package/dist/chunk-QKY3OKVG.js.map +0 -1
  53. package/dist/dashboard/assets/Accounts-DXiGsutB.js +0 -1
  54. package/dist/dashboard/assets/Badge-DUGKlx3Z.js +0 -55
  55. package/dist/dashboard/assets/Goals-kL4VAxw3.js +0 -1
  56. package/dist/dashboard/assets/RoutesPage-DWYm9tW8.js +0 -4
  57. package/dist/dashboard/assets/Runner-CmHBjECR.js +0 -1
  58. package/dist/dashboard/assets/Settings-BANphxva.js +0 -1
  59. package/dist/dashboard/assets/Tasks-cSx1PKyQ.js +0 -2
  60. package/dist/dashboard/assets/Traffic-DEAuM6jq.js +0 -1
  61. package/dist/dashboard/assets/Workspace-BQFjc1jH.js +0 -1
  62. package/dist/dashboard/assets/index-B8kld9xo.js +0 -104
  63. package/dist/dashboard/assets/index-BEmBgsbP.css +0 -2
  64. package/dist/dashboard/assets/task-errors-r-WYZ_S3.js +0 -1
  65. package/dist/goal-STLEU7C7.js.map +0 -1
  66. /package/dist/{ChatApp-Z6PQIZ5J.js.map → ChatApp-RQZ2IZFQ.js.map} +0 -0
  67. /package/dist/{account-RTPS2V6O.js.map → account-FY6THFLW.js.map} +0 -0
  68. /package/dist/{accounts-IYQ4ZRL7.js.map → accounts-ZV3KMLC5.js.map} +0 -0
  69. /package/dist/{budget-N2ZB66FF.js.map → budget-OUOEMMOM.js.map} +0 -0
  70. /package/dist/{chat-6TX6JX45.js.map → chat-OHVP4BS3.js.map} +0 -0
  71. /package/dist/{chunk-UEV5K3DH.js.map → chunk-2MM5WT5J.js.map} +0 -0
  72. /package/dist/{chunk-UNK3EQD6.js.map → chunk-2P5DJWIJ.js.map} +0 -0
  73. /package/dist/{chunk-LEU46DGH.js.map → chunk-FFB2QA5I.js.map} +0 -0
  74. /package/dist/{chunk-WAARDGCZ.js.map → chunk-L7NEDOA3.js.map} +0 -0
  75. /package/dist/{chunk-BJTXMET2.js.map → chunk-NKRI6SYR.js.map} +0 -0
  76. /package/dist/{chunk-YNAMNQLW.js.map → chunk-U5CI774J.js.map} +0 -0
  77. /package/dist/{config-YQKY2AA4.js.map → config-ZLO3YOUX.js.map} +0 -0
  78. /package/dist/{dist-PIC255RX.js.map → dist-56V3DLJ4.js.map} +0 -0
  79. /package/dist/{doctor-PQC7JQPP.js.map → doctor-DUOKUSJL.js.map} +0 -0
  80. /package/dist/{status-ZRHPFLFT.js.map → goal-WG37XHUY.js.map} +0 -0
  81. /package/dist/{init-NHU5LJSS.js.map → init-WW4XPFMM.js.map} +0 -0
  82. /package/dist/{run-7HWSHMRJ.js.map → run-QB4SGPEC.js.map} +0 -0
  83. /package/dist/{start-WVAEAQWL.js.map → start-U4RL377T.js.map} +0 -0
  84. /package/dist/{tasks-JVWXUNXN.js.map → tasks-VTBJ4B2G.js.map} +0 -0
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/program.ts","../src/index.ts"],"sourcesContent":["import { Command, CommanderError, InvalidArgumentError, Option } from 'commander';\nimport { type CliContext, type CliIO, createContext, type GlobalOptions } from './context';\nimport { CliError, EXIT } from './errors';\n\n/**\n * Command tree. Keep this module light: it only declares commands and options. Every action\n * lazy-loads its implementation, so `davecode --help` never pays for SQLite, Fastify or Ink.\n */\n\nexport interface RunOptions {\n io: CliIO;\n env: NodeJS.ProcessEnv;\n cwd: string;\n}\n\n/** Result of an action: an exit code, or nothing for success. */\nexport type ActionResult = number | undefined;\n\ninterface ProgramState {\n ctx?: CliContext;\n exitCode: number;\n}\n\nexport function buildProgram(options: RunOptions, state: ProgramState = { exitCode: 0 }): Command {\n const { io } = options;\n const program = new Command('davecode');\n\n const context = (): CliContext => {\n if (!state.ctx) throw new Error('CLI context is not initialised');\n return state.ctx;\n };\n\n /** Wrap a lazily loaded action: `(ctx, ...args) => exit code`. */\n const run =\n <A extends unknown[]>(action: (ctx: CliContext, ...args: A) => Promise<ActionResult>) =>\n async (...args: A) => {\n const code = await action(context(), ...args);\n if (typeof code === 'number') state.exitCode = code;\n };\n\n program\n .description('Local-first AI gateway and autonomous coding engine.')\n .usage('[command] [options]')\n .option('--home <dir>', 'DaveCode home directory (sets DAVECODE_HOME)')\n .option('--json', 'machine-readable JSON output where supported')\n .option('--no-color', 'disable colours (NO_COLOR is honoured too)')\n .option('-V, --version', 'print the version and exit')\n .showSuggestionAfterError(true)\n .configureOutput({\n writeOut: (text) => io.stdout.write(text),\n writeErr: (text) => io.stderr.write(text),\n outputError: (text, write) => write(text),\n })\n .exitOverride()\n .hook('preAction', (_root, action) => {\n state.ctx = createContext(action.optsWithGlobals<GlobalOptions>(), io, options);\n })\n .addHelpText(\n 'after',\n `\nRun \\`davecode\\` with no command in a terminal to open the chat TUI.\nDocs: https://github.com/DMRLZZ/DaveCode#readme`,\n );\n\n program.action(\n run(async (ctx) => {\n const globals = program.opts<GlobalOptions & { version?: boolean }>();\n if (globals.version) {\n const { VERSION } = await import('@davecode/core');\n ctx.out(`davecode ${VERSION}`);\n return EXIT.ok;\n }\n if (ctx.interactive) {\n const { chatCommand } = await import('./commands/chat');\n return chatCommand(ctx, {});\n }\n program.outputHelp();\n return EXIT.ok;\n }),\n );\n\n registerCommands(program, run);\n return program;\n}\n\ntype Runner = <A extends unknown[]>(\n action: (ctx: CliContext, ...args: A) => Promise<ActionResult>,\n) => (...args: A) => Promise<void>;\n\n/** Parse a TCP port (0 = pick a free one). */\nexport function parsePort(value: string): number {\n const n = Number(value);\n if (!/^\\d+$/.test(value.trim()) || !Number.isInteger(n) || n < 0 || n > 65535) {\n throw new InvalidArgumentError('expected a port number between 0 and 65535');\n }\n return n;\n}\n\n/** Parse a non-negative integer (priorities, weights, limits). */\nexport function parseInteger(value: string): number {\n const n = Number(value);\n if (!/^-?\\d+$/.test(value.trim()) || !Number.isSafeInteger(n) || n < 0) {\n throw new InvalidArgumentError('expected a non-negative integer');\n }\n return n;\n}\n\n/** Repeatable option collector (`--model a --model b`, also accepts `a,b`). */\nexport function collect(value: string, previous: string[] = []): string[] {\n return [\n ...previous,\n ...value\n .split(',')\n .map((v) => v.trim())\n .filter(Boolean),\n ];\n}\n\n/** Subcommands. Each action dynamically imports its module. */\nfunction registerCommands(program: Command, run: Runner): void {\n program\n .command('app')\n .description('start your local workspace in a Chrome or Edge app window')\n .addOption(new Option('-p, --port <port>', 'port to listen on').argParser(parsePort))\n .option('--project <dir>', 'repository to open')\n .action(\n run(async (ctx, opts: import('./commands/start').StartOptions) => {\n const { startCommand } = await import('./commands/start');\n return startCommand(ctx, { ...opts, host: '127.0.0.1', app: true });\n }),\n );\n program\n .command('start')\n .description('start the gateway (OpenAI-compatible /v1, dashboard API and web dashboard)')\n .addOption(new Option('-p, --port <port>', 'port to listen on').argParser(parsePort))\n .option('--host <host>', 'interface to bind (default 127.0.0.1)')\n .option('--no-dashboard', 'do not serve the web dashboard')\n .option('--project <dir>', 'repository whose project brain to serve (default: detected)')\n .option('--verbose', 'print gateway request logs')\n .option('-q, --quiet', 'do not print the live activity log')\n .action(\n run(async (ctx, opts: import('./commands/start').StartOptions) => {\n const { startCommand } = await import('./commands/start');\n return startCommand(ctx, opts);\n }),\n );\n\n program\n .command('status')\n .description('gateway health, accounts and 1m/5h/24h quota usage')\n .action(\n run(async (ctx) => {\n const { statusCommand } = await import('./commands/status');\n return statusCommand(ctx);\n }),\n );\n\n program\n .command('chat')\n .description('chat TUI (also what bare `davecode` opens in a terminal)')\n .option('-m, --model <id>', 'model or route, e.g. davecode/auto or anthropic/claude-sonnet-5-5')\n .option('--project <dir>', 'repository whose brain an in-process gateway serves')\n .action(\n run(async (ctx, opts: { model?: string; project?: string }) => {\n const { chatCommand } = await import('./commands/chat');\n return chatCommand(ctx, opts);\n }),\n );\n\n program\n .command('login')\n .description('sign in to your DaveCode account in the browser')\n .action(\n run(async (ctx) => {\n const { loginCommand } = await import('./commands/account');\n return loginCommand(ctx);\n }),\n );\n program\n .command('logout')\n .description('sign out of your DaveCode account')\n .action(\n run(async (ctx) => {\n const { logoutCommand } = await import('./commands/account');\n return logoutCommand(ctx);\n }),\n );\n program\n .command('account')\n .description('show the signed-in DaveCode account')\n .action(\n run(async (ctx) => {\n const { accountCommand } = await import('./commands/account');\n return accountCommand(ctx);\n }),\n );\n\n registerAccounts(program, run);\n registerProject(program, run);\n\n program\n .command('budget')\n .description('plans, renewals and remaining quota per account (what agents are told)')\n .option('--context', 'print only the summary injected into agent prompts')\n .option('--local', 'read the local database even if a gateway is running')\n .action(\n run(async (ctx, opts: import('./commands/budget').BudgetFlags) => {\n const { budgetCommand } = await import('./commands/budget');\n return budgetCommand(ctx, opts);\n }),\n );\n\n program\n .command('doctor')\n .description('check the environment and print fixes')\n .action(\n run(async (ctx) => {\n const { doctorCommand } = await import('./commands/doctor');\n return doctorCommand(ctx);\n }),\n );\n\n program\n .command('run')\n .description('run the autonomous engine on the task graph (live view in a terminal)')\n .option('--once', 'implement at most one ready task, print the result and exit')\n .option(\n '--task <id>',\n \"run this task instead of the runner's pick (it must be PENDING and unblocked)\",\n )\n .option('--project <dir>', 'repository to work on (default: detected)')\n .addHelpText(\n 'after',\n `\nExit codes with --once: 0 success or nothing to do, 1 failed or error, 130 stopped.\nCtrl+C stops safely: partial work stays on the task branch and the task goes back to PENDING.`,\n )\n .action(\n run(async (ctx, opts: import('./commands/run').RunOptions) => {\n const { runCommand } = await import('./commands/run');\n return runCommand(ctx, opts);\n }),\n );\n\n registerGoals(program, run);\n}\n\nfunction registerGoals(program: Command, run: Runner): void {\n const limit = (flag: string, description: string) =>\n new Option(flag, description).argParser((value) => {\n const n = parseInteger(value);\n if (n < 1) throw new InvalidArgumentError('expected a positive integer');\n return n;\n });\n\n program\n .command('goal <objective...>')\n .description('pursue an objective with a team of agents (plan, execute, review, re-plan)')\n .addOption(\n limit('--max-rounds <n>', 'plan → execute → review rounds (capped by goal.maxRounds)'),\n )\n .addOption(limit('--max-tasks <n>', 'tasks across all rounds (capped by goal.maxTasks)'))\n .addOption(\n limit('--max-tokens <n>', 'token budget for the whole goal (capped by goal.maxTokens)'),\n )\n .option('--dry-run', 'plan only: print the task graph without executing it')\n .option('--project <dir>', 'repository to work in (default: detected)')\n .addHelpText(\n 'after',\n `\nAgents never send emails, post, pay or sign up for anything: such steps become drafts in\n.davecode/goals/<goal-id>/. Code tasks go through the autonomous runner (branch, checks, merge).\nCtrl+C cancels. Exit codes: 0 succeeded or planned, 1 failed or out of budget, 130 cancelled.\n\nExamples:\n davecode goal \"Write positioning and landing copy for this app\" --dry-run\n davecode goal \"Add a /health endpoint with tests\" --max-rounds 2`,\n )\n .action(\n run(async (ctx, words: string[], opts: import('./commands/goal').GoalOptions) => {\n const { goalCommand } = await import('./commands/goal');\n return goalCommand(ctx, words, opts);\n }),\n );\n\n const goals = program.command('goals').description('goals of this repository');\n goals\n .command('list', { isDefault: true })\n .alias('ls')\n .description('goals, newest first')\n .option('--project <dir>', 'repository (default: detected)')\n .action(\n run(async (ctx, opts: { project?: string }) => {\n const { goalsList } = await import('./commands/goal');\n return goalsList(ctx, opts);\n }),\n );\n goals\n .command('show <id>')\n .description('tasks, artifacts and summary of a goal')\n .option('--project <dir>', 'repository (default: detected)')\n .action(\n run(async (ctx, id: string, opts: { project?: string }) => {\n const { goalsShow } = await import('./commands/goal');\n return goalsShow(ctx, id, opts);\n }),\n );\n goals\n .command('cancel <id>')\n .description('cancel a running goal')\n .option('--project <dir>', 'repository (default: detected)')\n .action(\n run(async (ctx, id: string, opts: { project?: string }) => {\n const { goalsCancel } = await import('./commands/goal');\n return goalsCancel(ctx, id, opts);\n }),\n );\n}\n\nfunction registerProject(program: Command, run: Runner): void {\n program\n .command('init')\n .description('scaffold the project brain (.davecode/) in this repository')\n .option('--name <name>', 'project name used in STATE.md and ARCHITECTURE.md')\n .option('--config', 'write a starter .davecode/config.json without asking')\n .option('--no-config', 'do not write .davecode/config.json')\n .action(\n run(async (ctx, opts: { name?: string; config?: boolean }) => {\n const { initCommand } = await import('./commands/init');\n return initCommand(ctx, opts);\n }),\n );\n\n const tasks = program.command('tasks').description('show and edit the task graph');\n tasks\n .command('list', { isDefault: true })\n .alias('ls')\n .description('task tree with status and blocked reasons')\n .action(\n run(async (ctx) => {\n const { tasksList } = await import('./commands/tasks');\n return tasksList(ctx);\n }),\n );\n tasks\n .command('next')\n .description('the task the runner would pick next')\n .action(\n run(async (ctx) => {\n const { tasksNext } = await import('./commands/tasks');\n return tasksNext(ctx);\n }),\n );\n tasks\n .command('add <id> <title...>')\n .description('add a PENDING task')\n .option('-d, --depends <ids>', 'dependencies (repeatable or comma-separated)', collect)\n .addOption(new Option('-p, --priority <n>', 'higher runs first').argParser(parseInteger))\n .option('--description <text>', 'longer description')\n .option(\n '-a, --acceptance <criterion>',\n 'acceptance criterion (repeatable)',\n (v, prev: string[] = []) => [...prev, v],\n )\n .action(\n run(\n async (\n ctx,\n id: string,\n title: string[],\n opts: import('./commands/tasks').AddTaskOptions,\n ) => {\n const { tasksAdd } = await import('./commands/tasks');\n return tasksAdd(ctx, id, title, opts);\n },\n ),\n );\n tasks\n .command('status <id> <status>')\n .description('move a task to PENDING | IN_PROGRESS | SUCCESS | FAILED')\n .option('--notes <text>', 'note stored on the task')\n .action(\n run(async (ctx, id: string, status: string, opts: { notes?: string }) => {\n const { tasksStatus } = await import('./commands/tasks');\n return tasksStatus(ctx, id, status, opts);\n }),\n );\n\n const config = program.command('config').description('show the resolved configuration');\n config\n .command('show', { isDefault: true })\n .description('resolved config as JSON (secrets redacted)')\n .action(\n run(async (ctx) => {\n const { configShow } = await import('./commands/config');\n return configShow(ctx);\n }),\n );\n config\n .command('path')\n .description('where config, state and brains live')\n .action(\n run(async (ctx) => {\n const { configPath } = await import('./commands/config');\n return configPath(ctx);\n }),\n );\n config\n .command('get <key>')\n .description('one value by dotted key, e.g. server.port')\n .action(\n run(async (ctx, key: string) => {\n const { configGet } = await import('./commands/config');\n return configGet(ctx, key);\n }),\n );\n}\n\ntype AddOpts = import('./commands/accounts').AddCommandFlags;\n\nfunction addAccountOptions(command: Command, run: Runner): Command {\n return command\n .option(\n '--provider <kind>',\n 'anthropic | openai | gemini | openai-compatible | claude-cli | codex-cli | gemini-cli | gemini-web',\n )\n .option('--label <name>', 'human-friendly name')\n .addOption(\n new Option('--priority <n>', 'lower is tried first (default 100)').argParser(parseInteger),\n )\n .addOption(\n new Option('--weight <n>', 'traffic share among equal priorities').argParser(parseInteger),\n )\n .option('--secret-env <var>', 'read the API key from this environment variable')\n .option('--secret-stdin', 'read the API key from stdin')\n .option('--secret <value>', 'API key (discouraged: visible in shell history)')\n .option('--base-url <url>', 'endpoint for openai-compatible accounts')\n .option('--model <id>', 'advertised model (repeatable or comma-separated)', collect)\n .option('--default-model <id>', 'model used for davecode/auto without a route')\n .option('--binary-path <path>', 'CLI binary for claude-cli / codex-cli / gemini-cli')\n .option('--limit <key=value>', 'quota limit, e.g. tokens5h=500000 (repeatable)', collect)\n .option('--disabled', 'add the account disabled')\n .option('-y, --yes', 'never prompt: take everything from flags')\n .option('--no-login', 'do not offer to log in after adding a CLI account')\n .option('--local', 'write to the local database even if a gateway is running')\n .addHelpText(\n 'after',\n `\nExamples:\n davecode accounts add # interactive\n davecode accounts add --provider anthropic --label work --secret-env ANTHROPIC_API_KEY --yes\n echo \"$OPENROUTER_KEY\" | davecode accounts add --provider openai-compatible \\\\\n --base-url https://openrouter.ai/api/v1 --model openai/gpt-5.5 --secret-stdin\n davecode accounts add --provider claude-cli --label \"Claude Pro\" --yes`,\n )\n .action(\n run(async (ctx, opts: AddOpts) => {\n const { accountsAdd } = await import('./commands/accounts');\n return accountsAdd(ctx, opts);\n }),\n );\n}\n\nfunction registerAccounts(program: Command, run: Runner): void {\n const accounts = program.command('accounts').description('manage provider accounts');\n\n accounts\n .command('list', { isDefault: true })\n .alias('ls')\n .description('list accounts')\n .option('--local', 'read the local database even if a gateway is running')\n .action(\n run(async (ctx, opts: { local?: boolean }) => {\n const { accountsList } = await import('./commands/accounts');\n return accountsList(ctx, opts);\n }),\n );\n\n addAccountOptions(\n accounts.command('add').description('add an account (interactive in a terminal)'),\n run,\n );\n\n accounts\n .command('remove <id>')\n .alias('rm')\n .description('remove an account, its secret and its sandbox')\n .option('-y, --yes', 'do not ask for confirmation')\n .option('--local', 'write to the local database even if a gateway is running')\n .action(\n run(async (ctx, id: string, opts: { yes?: boolean; local?: boolean }) => {\n const { accountsRemove } = await import('./commands/accounts');\n return accountsRemove(ctx, id, opts);\n }),\n );\n\n for (const [name, enabled] of [\n ['enable', true],\n ['disable', false],\n ] as const) {\n accounts\n .command(`${name} <id>`)\n .description(`${name} an account${enabled ? ' (also clears error and cooldown state)' : ''}`)\n .option('--local', 'write to the local database even if a gateway is running')\n .action(\n run(async (ctx, id: string, opts: { local?: boolean }) => {\n const { accountsSetEnabled } = await import('./commands/accounts');\n return accountsSetEnabled(ctx, id, enabled, opts);\n }),\n );\n }\n\n accounts\n .command('plan <id>')\n .description('show or set what you pay for an account (plan, price, paid/renewal dates)')\n .option('--plan <name>', 'plan name, e.g. \"Claude Pro\" or \"API pay-as-you-go\"')\n .option('--price <amount>', 'price per period, e.g. 20')\n .option('--currency <code>', '3-letter currency code (default USD)')\n .option('--period <period>', 'month | year (default month)')\n .option('--paid <date>', 'last payment date (YYYY-MM-DD)')\n .option('--renews <date>', 'next renewal date (YYYY-MM-DD)')\n .option('--notes <text>', 'free-form note')\n .option('--clear', 'remove the recorded plan')\n .option('--local', 'write to the local database even if a gateway is running')\n .addHelpText(\n 'after',\n `\nEntered by hand: DaveCode never reads billing pages. Example:\n davecode accounts plan acc_123 --plan \"Claude Pro\" --price 20 --renews 2026-11-01`,\n )\n .action(\n run(async (ctx, id: string, opts: import('./commands/accounts').PlanFlags) => {\n const { accountsPlan } = await import('./commands/accounts');\n return accountsPlan(ctx, id, opts);\n }),\n );\n\n accounts\n .command('login <id> [args...]')\n .description(\n 'log a claude-cli / codex-cli / gemini-cli account in, inside its own isolated config dir',\n )\n .allowUnknownOption()\n .option('--local', 'read the local database even if a gateway is running')\n .option('--hold', 'wait for Enter before exiting (for windows opened by the dashboard)')\n .addHelpText(\n 'after',\n `\nRuns the vendor's official sign-in (claude auth login, codex login, Gemini CLI's\n\"Login with Google\") with CLAUDE_CONFIG_DIR / CODEX_HOME / GEMINI_CLI_HOME pointing at the\naccount's sandbox, so every account keeps a separate login. DaveCode never sees the password.\nExtra arguments after -- replace the default ones (e.g. -- login --device-auth for Codex).`,\n )\n .action(\n run(\n async (ctx, id: string, args: string[], opts: import('./commands/accounts').LoginFlags) => {\n const { accountsLogin } = await import('./commands/accounts');\n return accountsLogin(ctx, id, args, opts);\n },\n ),\n );\n\n accounts\n .command('connect <id>')\n .description('connect a subscription: check its login and run the official sign-in if needed')\n .option('--check', 'only report whether the account is connected')\n .option('--local', 'read the local database even if a gateway is running')\n .addHelpText(\n 'after',\n `\nAPI-key accounts are connected when a key is stored. CLI accounts (claude-cli, codex-cli,\ngemini-cli) ask the vendor CLI for its login status inside the account sandbox and, when not\nconnected, start the vendor's own sign-in. Example:\n davecode accounts connect acc_123 --check`,\n )\n .action(\n run(async (ctx, id: string, opts: import('./commands/accounts').ConnectFlags) => {\n const { accountsConnect } = await import('./commands/accounts');\n return accountsConnect(ctx, id, opts);\n }),\n );\n\n addAccountOptions(program.command('add-account').description('alias of `accounts add`'), run);\n}\n\n/** Render an error for humans: `error: …` plus an optional hint, without a stack trace. */\nexport function describeError(err: unknown): { message: string; hint?: string; exitCode: number } {\n if (err instanceof CliError) {\n return {\n message: err.message,\n exitCode: err.exitCode,\n ...(err.hint ? { hint: err.hint } : {}),\n };\n }\n if (err instanceof Error) {\n if (err.name === 'ConfigError') {\n return {\n message: err.message,\n hint: 'Fix the file above or run `davecode config path` to see where config is read from.',\n exitCode: EXIT.failure,\n };\n }\n return { message: err.message, exitCode: EXIT.failure };\n }\n return { message: String(err), exitCode: EXIT.failure };\n}\n\n/** Parse `argv` (user arguments only) and run the matching command. Resolves to an exit code. */\nexport async function runCli(argv: string[], options: RunOptions): Promise<number> {\n const state: ProgramState = { exitCode: 0 };\n const program = buildProgram(options, state);\n try {\n await program.parseAsync(argv, { from: 'user' });\n return state.exitCode;\n } catch (err) {\n if (err instanceof CommanderError) {\n // Help/version print and exit 0; usage errors were already written by commander.\n return err.exitCode;\n }\n const { message, hint, exitCode } = describeError(err);\n const theme = state.ctx?.errTheme;\n const label = theme ? theme.error('error') : 'error';\n options.io.stderr.write(`${label}: ${message}\\n`);\n if (hint) options.io.stderr.write(`${theme ? theme.dim(hint) : hint}\\n`);\n if (options.env.DAVECODE_DEBUG && err instanceof Error && err.stack) {\n options.io.stderr.write(`${err.stack}\\n`);\n }\n return exitCode;\n }\n}\n","import { runCli } from './program';\n\nconst code = await runCli(process.argv.slice(2), {\n io: { stdout: process.stdout, stderr: process.stderr, stdin: process.stdin },\n env: process.env,\n cwd: process.cwd(),\n});\nprocess.exitCode = code;\n"],"mappings":";;;;;;;;;;AAAA,SAAS,SAAS,gBAAgB,sBAAsB,cAAc;AAuB/D,SAAS,aAAa,SAAqB,QAAsB,EAAE,UAAU,EAAE,GAAY;AAChG,QAAM,EAAE,GAAG,IAAI;AACf,QAAM,UAAU,IAAI,QAAQ,UAAU;AAEtC,QAAM,UAAU,MAAkB;AAChC,QAAI,CAAC,MAAM,IAAK,OAAM,IAAI,MAAM,gCAAgC;AAChE,WAAO,MAAM;AAAA,EACf;AAGA,QAAM,MACJ,CAAsB,WACtB,UAAU,SAAY;AACpB,UAAMA,QAAO,MAAM,OAAO,QAAQ,GAAG,GAAG,IAAI;AAC5C,QAAI,OAAOA,UAAS,SAAU,OAAM,WAAWA;AAAA,EACjD;AAEF,UACG,YAAY,sDAAsD,EAClE,MAAM,qBAAqB,EAC3B,OAAO,gBAAgB,8CAA8C,EACrE,OAAO,UAAU,8CAA8C,EAC/D,OAAO,cAAc,4CAA4C,EACjE,OAAO,iBAAiB,4BAA4B,EACpD,yBAAyB,IAAI,EAC7B,gBAAgB;AAAA,IACf,UAAU,CAAC,SAAS,GAAG,OAAO,MAAM,IAAI;AAAA,IACxC,UAAU,CAAC,SAAS,GAAG,OAAO,MAAM,IAAI;AAAA,IACxC,aAAa,CAAC,MAAM,UAAU,MAAM,IAAI;AAAA,EAC1C,CAAC,EACA,a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ACD,QAAQ,WAAW;","names":["code"]}
1
+ {"version":3,"sources":["../src/program.ts","../src/index.ts"],"sourcesContent":["import { Command, CommanderError, InvalidArgumentError, Option } from 'commander';\nimport { type CliContext, type CliIO, createContext, type GlobalOptions } from './context';\nimport { CliError, EXIT } from './errors';\n\n/**\n * Command tree. Keep this module light: it only declares commands and options. Every action\n * lazy-loads its implementation, so `davecode --help` never pays for SQLite, Fastify or Ink.\n */\n\nexport interface RunOptions {\n io: CliIO;\n env: NodeJS.ProcessEnv;\n cwd: string;\n}\n\n/** Result of an action: an exit code, or nothing for success. */\nexport type ActionResult = number | undefined;\n\ninterface ProgramState {\n ctx?: CliContext;\n exitCode: number;\n}\n\nexport function buildProgram(options: RunOptions, state: ProgramState = { exitCode: 0 }): Command {\n const { io } = options;\n const program = new Command('davecode');\n\n const context = (): CliContext => {\n if (!state.ctx) throw new Error('CLI context is not initialised');\n return state.ctx;\n };\n\n /** Wrap a lazily loaded action: `(ctx, ...args) => exit code`. */\n const run =\n <A extends unknown[]>(action: (ctx: CliContext, ...args: A) => Promise<ActionResult>) =>\n async (...args: A) => {\n const code = await action(context(), ...args);\n if (typeof code === 'number') state.exitCode = code;\n };\n\n program\n .description('Local-first AI gateway and autonomous coding engine.')\n .usage('[command] [options]')\n .option('--home <dir>', 'DaveCode home directory (sets DAVECODE_HOME)')\n .option('--json', 'machine-readable JSON output where supported')\n .option('--no-color', 'disable colours (NO_COLOR is honoured too)')\n .option('-V, --version', 'print the version and exit')\n .showSuggestionAfterError(true)\n .configureOutput({\n writeOut: (text) => io.stdout.write(text),\n writeErr: (text) => io.stderr.write(text),\n outputError: (text, write) => write(text),\n })\n .exitOverride()\n .hook('preAction', (_root, action) => {\n state.ctx = createContext(action.optsWithGlobals<GlobalOptions>(), io, options);\n })\n .addHelpText(\n 'after',\n `\nRun \\`davecode\\` with no command in a terminal to open the chat TUI.\nDocs: https://github.com/DMRLZZ/DaveCode#readme`,\n );\n\n program.action(\n run(async (ctx) => {\n const globals = program.opts<GlobalOptions & { version?: boolean }>();\n if (globals.version) {\n const { VERSION } = await import('@davecode/core');\n ctx.out(`davecode ${VERSION}`);\n return EXIT.ok;\n }\n if (ctx.interactive) {\n const { chatCommand } = await import('./commands/chat');\n return chatCommand(ctx, {});\n }\n program.outputHelp();\n return EXIT.ok;\n }),\n );\n\n registerCommands(program, run);\n return program;\n}\n\ntype Runner = <A extends unknown[]>(\n action: (ctx: CliContext, ...args: A) => Promise<ActionResult>,\n) => (...args: A) => Promise<void>;\n\n/** Parse a TCP port (0 = pick a free one). */\nexport function parsePort(value: string): number {\n const n = Number(value);\n if (!/^\\d+$/.test(value.trim()) || !Number.isInteger(n) || n < 0 || n > 65535) {\n throw new InvalidArgumentError('expected a port number between 0 and 65535');\n }\n return n;\n}\n\n/** Parse a non-negative integer (priorities, weights, limits). */\nexport function parseInteger(value: string): number {\n const n = Number(value);\n if (!/^-?\\d+$/.test(value.trim()) || !Number.isSafeInteger(n) || n < 0) {\n throw new InvalidArgumentError('expected a non-negative integer');\n }\n return n;\n}\n\n/** Repeatable option collector (`--model a --model b`, also accepts `a,b`). */\nexport function collect(value: string, previous: string[] = []): string[] {\n return [\n ...previous,\n ...value\n .split(',')\n .map((v) => v.trim())\n .filter(Boolean),\n ];\n}\n\n/** Subcommands. Each action dynamically imports its module. */\nfunction registerCommands(program: Command, run: Runner): void {\n program\n .command('app')\n .description('start your local workspace in a Chrome or Edge app window')\n .addOption(new Option('-p, --port <port>', 'port to listen on').argParser(parsePort))\n .option('--project <dir>', 'repository to open')\n .action(\n run(async (ctx, opts: import('./commands/start').StartOptions) => {\n const { startCommand } = await import('./commands/start');\n return startCommand(ctx, { ...opts, host: '127.0.0.1', app: true });\n }),\n );\n program\n .command('start')\n .description('start the gateway (OpenAI-compatible /v1, dashboard API and web dashboard)')\n .addOption(new Option('-p, --port <port>', 'port to listen on').argParser(parsePort))\n .option('--host <host>', 'interface to bind (default 127.0.0.1)')\n .option('--no-dashboard', 'do not serve the web dashboard')\n .option('--project <dir>', 'repository whose project brain to serve (default: detected)')\n .option('--verbose', 'print gateway request logs')\n .option('-q, --quiet', 'do not print the live activity log')\n .action(\n run(async (ctx, opts: import('./commands/start').StartOptions) => {\n const { startCommand } = await import('./commands/start');\n return startCommand(ctx, opts);\n }),\n );\n\n program\n .command('status')\n .description('gateway health, accounts and 1m/5h/24h quota usage')\n .action(\n run(async (ctx) => {\n const { statusCommand } = await import('./commands/status');\n return statusCommand(ctx);\n }),\n );\n\n program\n .command('chat')\n .description('chat TUI (also what bare `davecode` opens in a terminal)')\n .option('-m, --model <id>', 'model or route, e.g. davecode/auto or anthropic/claude-sonnet-5-5')\n .option('--project <dir>', 'repository whose brain an in-process gateway serves')\n .action(\n run(async (ctx, opts: { model?: string; project?: string }) => {\n const { chatCommand } = await import('./commands/chat');\n return chatCommand(ctx, opts);\n }),\n );\n\n program\n .command('login')\n .description('sign in to your DaveCode account in the browser')\n .action(\n run(async (ctx) => {\n const { loginCommand } = await import('./commands/account');\n return loginCommand(ctx);\n }),\n );\n program\n .command('logout')\n .description('sign out of your DaveCode account')\n .action(\n run(async (ctx) => {\n const { logoutCommand } = await import('./commands/account');\n return logoutCommand(ctx);\n }),\n );\n program\n .command('account')\n .description('show the signed-in DaveCode account')\n .action(\n run(async (ctx) => {\n const { accountCommand } = await import('./commands/account');\n return accountCommand(ctx);\n }),\n );\n\n registerAccounts(program, run);\n registerProject(program, run);\n\n program\n .command('budget')\n .description('plans, renewals and remaining quota per account (what agents are told)')\n .option('--context', 'print only the summary injected into agent prompts')\n .option('--local', 'read the local database even if a gateway is running')\n .action(\n run(async (ctx, opts: import('./commands/budget').BudgetFlags) => {\n const { budgetCommand } = await import('./commands/budget');\n return budgetCommand(ctx, opts);\n }),\n );\n\n program\n .command('doctor')\n .description('check the environment and print fixes')\n .action(\n run(async (ctx) => {\n const { doctorCommand } = await import('./commands/doctor');\n return doctorCommand(ctx);\n }),\n );\n\n program\n .command('run')\n .description('run the autonomous engine on the task graph (live view in a terminal)')\n .option('--once', 'implement at most one ready task, print the result and exit')\n .option(\n '--task <id>',\n \"run this task instead of the runner's pick (it must be PENDING and unblocked)\",\n )\n .option('--project <dir>', 'repository to work on (default: detected)')\n .addHelpText(\n 'after',\n `\nExit codes with --once: 0 success or nothing to do, 1 failed or error, 130 stopped.\nCtrl+C stops safely: partial work stays on the task branch and the task goes back to PENDING.`,\n )\n .action(\n run(async (ctx, opts: import('./commands/run').RunOptions) => {\n const { runCommand } = await import('./commands/run');\n return runCommand(ctx, opts);\n }),\n );\n\n registerGoals(program, run);\n registerOrchestrate(program, run);\n}\n\nfunction registerOrchestrate(program: Command, run: Runner): void {\n program\n .command('orchestrate [objective...]')\n .description(\n 'split an objective across Claude Code, Codex and Antigravity, each in its own git worktree',\n )\n .option('--agents <list>', 'agents allowed to work, comma-separated: claude,codex,agy')\n .option('--planner <agent>', 'agent that splits the objective (default: claude, then codex)')\n .addOption(\n new Option('--max-tasks <n>', 'most subtasks in the plan (1-8, default 5)').argParser(\n (value) => {\n const n = parseInteger(value);\n if (n < 1) throw new InvalidArgumentError('expected a positive integer');\n return n;\n },\n ),\n )\n .option('--apply', 'merge the results into your branch when the run is done')\n .option('--list', 'recent runs of this repository')\n .option('--apply-run <id>', 'merge a finished run into the branch it started from')\n .option('--project <dir>', 'repository to work on (default: detected)')\n .addHelpText(\n 'after',\n `\nEach agent uses the CLI you already signed in to (claude, codex, agy) and works in its own\ngit worktree. Results are merged into the branch davecode/run-<id>; your working tree is not\ntouched until you apply, and nothing is ever pushed. Ctrl+C cancels the run.\nExit codes: 0 the run is done (and applied with --apply), 1 otherwise.\n\nExamples:\n davecode orchestrate \"Add a /health endpoint with tests\" --agents claude,codex\n davecode orchestrate --list\n davecode orchestrate --apply-run <id>`,\n )\n .action(\n run(\n async (ctx, words: string[], opts: import('./commands/orchestrate').OrchestrateOptions) => {\n const { orchestrateCommand } = await import('./commands/orchestrate');\n return orchestrateCommand(ctx, words, opts);\n },\n ),\n );\n}\n\nfunction registerGoals(program: Command, run: Runner): void {\n const limit = (flag: string, description: string) =>\n new Option(flag, description).argParser((value) => {\n const n = parseInteger(value);\n if (n < 1) throw new InvalidArgumentError('expected a positive integer');\n return n;\n });\n\n program\n .command('goal <objective...>')\n .description('pursue an objective with a team of agents (plan, execute, review, re-plan)')\n .addOption(\n limit('--max-rounds <n>', 'plan → execute → review rounds (capped by goal.maxRounds)'),\n )\n .addOption(limit('--max-tasks <n>', 'tasks across all rounds (capped by goal.maxTasks)'))\n .addOption(\n limit('--max-tokens <n>', 'token budget for the whole goal (capped by goal.maxTokens)'),\n )\n .option('--dry-run', 'plan only: print the task graph without executing it')\n .option('--project <dir>', 'repository to work in (default: detected)')\n .addHelpText(\n 'after',\n `\nAgents never send emails, post, pay or sign up for anything: such steps become drafts in\n.davecode/goals/<goal-id>/. Code tasks go through the autonomous runner (branch, checks, merge).\nCtrl+C cancels. Exit codes: 0 succeeded or planned, 1 failed or out of budget, 130 cancelled.\n\nExamples:\n davecode goal \"Write positioning and landing copy for this app\" --dry-run\n davecode goal \"Add a /health endpoint with tests\" --max-rounds 2`,\n )\n .action(\n run(async (ctx, words: string[], opts: import('./commands/goal').GoalOptions) => {\n const { goalCommand } = await import('./commands/goal');\n return goalCommand(ctx, words, opts);\n }),\n );\n\n const goals = program.command('goals').description('goals of this repository');\n goals\n .command('list', { isDefault: true })\n .alias('ls')\n .description('goals, newest first')\n .option('--project <dir>', 'repository (default: detected)')\n .action(\n run(async (ctx, opts: { project?: string }) => {\n const { goalsList } = await import('./commands/goal');\n return goalsList(ctx, opts);\n }),\n );\n goals\n .command('show <id>')\n .description('tasks, artifacts and summary of a goal')\n .option('--project <dir>', 'repository (default: detected)')\n .action(\n run(async (ctx, id: string, opts: { project?: string }) => {\n const { goalsShow } = await import('./commands/goal');\n return goalsShow(ctx, id, opts);\n }),\n );\n goals\n .command('cancel <id>')\n .description('cancel a running goal')\n .option('--project <dir>', 'repository (default: detected)')\n .action(\n run(async (ctx, id: string, opts: { project?: string }) => {\n const { goalsCancel } = await import('./commands/goal');\n return goalsCancel(ctx, id, opts);\n }),\n );\n}\n\nfunction registerProject(program: Command, run: Runner): void {\n program\n .command('init')\n .description('scaffold the project brain (.davecode/) in this repository')\n .option('--name <name>', 'project name used in STATE.md and ARCHITECTURE.md')\n .option('--config', 'write a starter .davecode/config.json without asking')\n .option('--no-config', 'do not write .davecode/config.json')\n .action(\n run(async (ctx, opts: { name?: string; config?: boolean }) => {\n const { initCommand } = await import('./commands/init');\n return initCommand(ctx, opts);\n }),\n );\n\n const tasks = program.command('tasks').description('show and edit the task graph');\n tasks\n .command('list', { isDefault: true })\n .alias('ls')\n .description('task tree with status and blocked reasons')\n .action(\n run(async (ctx) => {\n const { tasksList } = await import('./commands/tasks');\n return tasksList(ctx);\n }),\n );\n tasks\n .command('next')\n .description('the task the runner would pick next')\n .action(\n run(async (ctx) => {\n const { tasksNext } = await import('./commands/tasks');\n return tasksNext(ctx);\n }),\n );\n tasks\n .command('add <id> <title...>')\n .description('add a PENDING task')\n .option('-d, --depends <ids>', 'dependencies (repeatable or comma-separated)', collect)\n .addOption(new Option('-p, --priority <n>', 'higher runs first').argParser(parseInteger))\n .option('--description <text>', 'longer description')\n .option(\n '-a, --acceptance <criterion>',\n 'acceptance criterion (repeatable)',\n (v, prev: string[] = []) => [...prev, v],\n )\n .action(\n run(\n async (\n ctx,\n id: string,\n title: string[],\n opts: import('./commands/tasks').AddTaskOptions,\n ) => {\n const { tasksAdd } = await import('./commands/tasks');\n return tasksAdd(ctx, id, title, opts);\n },\n ),\n );\n tasks\n .command('status <id> <status>')\n .description('move a task to PENDING | IN_PROGRESS | SUCCESS | FAILED')\n .option('--notes <text>', 'note stored on the task')\n .action(\n run(async (ctx, id: string, status: string, opts: { notes?: string }) => {\n const { tasksStatus } = await import('./commands/tasks');\n return tasksStatus(ctx, id, status, opts);\n }),\n );\n\n const config = program.command('config').description('show the resolved configuration');\n config\n .command('show', { isDefault: true })\n .description('resolved config as JSON (secrets redacted)')\n .action(\n run(async (ctx) => {\n const { configShow } = await import('./commands/config');\n return configShow(ctx);\n }),\n );\n config\n .command('path')\n .description('where config, state and brains live')\n .action(\n run(async (ctx) => {\n const { configPath } = await import('./commands/config');\n return configPath(ctx);\n }),\n );\n config\n .command('get <key>')\n .description('one value by dotted key, e.g. server.port')\n .action(\n run(async (ctx, key: string) => {\n const { configGet } = await import('./commands/config');\n return configGet(ctx, key);\n }),\n );\n}\n\ntype AddOpts = import('./commands/accounts').AddCommandFlags;\n\nfunction addAccountOptions(command: Command, run: Runner): Command {\n return command\n .option(\n '--provider <kind>',\n 'anthropic | openai | gemini | openai-compatible | claude-cli | codex-cli | gemini-cli | gemini-web',\n )\n .option('--label <name>', 'human-friendly name')\n .addOption(\n new Option('--priority <n>', 'lower is tried first (default 100)').argParser(parseInteger),\n )\n .addOption(\n new Option('--weight <n>', 'traffic share among equal priorities').argParser(parseInteger),\n )\n .option('--secret-env <var>', 'read the API key from this environment variable')\n .option('--secret-stdin', 'read the API key from stdin')\n .option('--secret <value>', 'API key (discouraged: visible in shell history)')\n .option('--base-url <url>', 'endpoint for openai-compatible accounts')\n .option('--model <id>', 'advertised model (repeatable or comma-separated)', collect)\n .option('--default-model <id>', 'model used for davecode/auto without a route')\n .option('--binary-path <path>', 'CLI binary for claude-cli / codex-cli / gemini-cli')\n .option('--limit <key=value>', 'quota limit, e.g. tokens5h=500000 (repeatable)', collect)\n .option('--disabled', 'add the account disabled')\n .option('-y, --yes', 'never prompt: take everything from flags')\n .option('--no-login', 'do not offer to log in after adding a CLI account')\n .option('--local', 'write to the local database even if a gateway is running')\n .addHelpText(\n 'after',\n `\nExamples:\n davecode accounts add # interactive\n davecode accounts add --provider anthropic --label work --secret-env ANTHROPIC_API_KEY --yes\n echo \"$OPENROUTER_KEY\" | davecode accounts add --provider openai-compatible \\\\\n --base-url https://openrouter.ai/api/v1 --model openai/gpt-5.5 --secret-stdin\n davecode accounts add --provider claude-cli --label \"Claude Pro\" --yes`,\n )\n .action(\n run(async (ctx, opts: AddOpts) => {\n const { accountsAdd } = await import('./commands/accounts');\n return accountsAdd(ctx, opts);\n }),\n );\n}\n\nfunction registerAccounts(program: Command, run: Runner): void {\n const accounts = program.command('accounts').description('manage provider accounts');\n\n accounts\n .command('list', { isDefault: true })\n .alias('ls')\n .description('list accounts')\n .option('--local', 'read the local database even if a gateway is running')\n .action(\n run(async (ctx, opts: { local?: boolean }) => {\n const { accountsList } = await import('./commands/accounts');\n return accountsList(ctx, opts);\n }),\n );\n\n addAccountOptions(\n accounts.command('add').description('add an account (interactive in a terminal)'),\n run,\n );\n\n accounts\n .command('remove <id>')\n .alias('rm')\n .description('remove an account, its secret and its sandbox')\n .option('-y, --yes', 'do not ask for confirmation')\n .option('--local', 'write to the local database even if a gateway is running')\n .action(\n run(async (ctx, id: string, opts: { yes?: boolean; local?: boolean }) => {\n const { accountsRemove } = await import('./commands/accounts');\n return accountsRemove(ctx, id, opts);\n }),\n );\n\n for (const [name, enabled] of [\n ['enable', true],\n ['disable', false],\n ] as const) {\n accounts\n .command(`${name} <id>`)\n .description(`${name} an account${enabled ? ' (also clears error and cooldown state)' : ''}`)\n .option('--local', 'write to the local database even if a gateway is running')\n .action(\n run(async (ctx, id: string, opts: { local?: boolean }) => {\n const { accountsSetEnabled } = await import('./commands/accounts');\n return accountsSetEnabled(ctx, id, enabled, opts);\n }),\n );\n }\n\n accounts\n .command('plan <id>')\n .description('show or set what you pay for an account (plan, price, paid/renewal dates)')\n .option('--plan <name>', 'plan name, e.g. \"Claude Pro\" or \"API pay-as-you-go\"')\n .option('--price <amount>', 'price per period, e.g. 20')\n .option('--currency <code>', '3-letter currency code (default USD)')\n .option('--period <period>', 'month | year (default month)')\n .option('--paid <date>', 'last payment date (YYYY-MM-DD)')\n .option('--renews <date>', 'next renewal date (YYYY-MM-DD)')\n .option('--notes <text>', 'free-form note')\n .option('--clear', 'remove the recorded plan')\n .option('--local', 'write to the local database even if a gateway is running')\n .addHelpText(\n 'after',\n `\nEntered by hand: DaveCode never reads billing pages. Example:\n davecode accounts plan acc_123 --plan \"Claude Pro\" --price 20 --renews 2026-11-01`,\n )\n .action(\n run(async (ctx, id: string, opts: import('./commands/accounts').PlanFlags) => {\n const { accountsPlan } = await import('./commands/accounts');\n return accountsPlan(ctx, id, opts);\n }),\n );\n\n accounts\n .command('login <id> [args...]')\n .description(\n 'log a claude-cli / codex-cli / gemini-cli account in, inside its own isolated config dir',\n )\n .allowUnknownOption()\n .option('--local', 'read the local database even if a gateway is running')\n .option('--hold', 'wait for Enter before exiting (for windows opened by the dashboard)')\n .addHelpText(\n 'after',\n `\nRuns the vendor's official sign-in (claude auth login, codex login, Gemini CLI's\n\"Login with Google\") with CLAUDE_CONFIG_DIR / CODEX_HOME / GEMINI_CLI_HOME pointing at the\naccount's sandbox, so every account keeps a separate login. DaveCode never sees the password.\nExtra arguments after -- replace the default ones (e.g. -- login --device-auth for Codex).`,\n )\n .action(\n run(\n async (ctx, id: string, args: string[], opts: import('./commands/accounts').LoginFlags) => {\n const { accountsLogin } = await import('./commands/accounts');\n return accountsLogin(ctx, id, args, opts);\n },\n ),\n );\n\n accounts\n .command('connect <id>')\n .description('connect a subscription: check its login and run the official sign-in if needed')\n .option('--check', 'only report whether the account is connected')\n .option('--local', 'read the local database even if a gateway is running')\n .addHelpText(\n 'after',\n `\nAPI-key accounts are connected when a key is stored. CLI accounts (claude-cli, codex-cli,\ngemini-cli) ask the vendor CLI for its login status inside the account sandbox and, when not\nconnected, start the vendor's own sign-in. Example:\n davecode accounts connect acc_123 --check`,\n )\n .action(\n run(async (ctx, id: string, opts: import('./commands/accounts').ConnectFlags) => {\n const { accountsConnect } = await import('./commands/accounts');\n return accountsConnect(ctx, id, opts);\n }),\n );\n\n addAccountOptions(program.command('add-account').description('alias of `accounts add`'), run);\n}\n\n/** Render an error for humans: `error: …` plus an optional hint, without a stack trace. */\nexport function describeError(err: unknown): { message: string; hint?: string; exitCode: number } {\n if (err instanceof CliError) {\n return {\n message: err.message,\n exitCode: err.exitCode,\n ...(err.hint ? { hint: err.hint } : {}),\n };\n }\n if (err instanceof Error) {\n if (err.name === 'ConfigError') {\n return {\n message: err.message,\n hint: 'Fix the file above or run `davecode config path` to see where config is read from.',\n exitCode: EXIT.failure,\n };\n }\n return { message: err.message, exitCode: EXIT.failure };\n }\n return { message: String(err), exitCode: EXIT.failure };\n}\n\n/** Parse `argv` (user arguments only) and run the matching command. Resolves to an exit code. */\nexport async function runCli(argv: string[], options: RunOptions): Promise<number> {\n const state: ProgramState = { exitCode: 0 };\n const program = buildProgram(options, state);\n try {\n await program.parseAsync(argv, { from: 'user' });\n return state.exitCode;\n } catch (err) {\n if (err instanceof CommanderError) {\n // Help/version print and exit 0; usage errors were already written by commander.\n return err.exitCode;\n }\n const { message, hint, exitCode } = describeError(err);\n const theme = state.ctx?.errTheme;\n const label = theme ? theme.error('error') : 'error';\n options.io.stderr.write(`${label}: ${message}\\n`);\n if (hint) options.io.stderr.write(`${theme ? theme.dim(hint) : hint}\\n`);\n if (options.env.DAVECODE_DEBUG && err instanceof Error && err.stack) {\n options.io.stderr.write(`${err.stack}\\n`);\n }\n return exitCode;\n }\n}\n","import { runCli } from './program';\n\nconst code = await runCli(process.argv.slice(2), {\n io: { stdout: process.stdout, stderr: process.stderr, stdin: process.stdin },\n env: process.env,\n cwd: process.cwd(),\n});\nprocess.exitCode = code;\n"],"mappings":";;;;;;;;;;AAAA,SAAS,SAAS,gBAAgB,sBAAsB,cAAc;AAuB/D,SAAS,aAAa,SAAqB,QAAsB,EAAE,UAAU,EAAE,GAAY;AAChG,QAAM,EAAE,GAAG,IAAI;AACf,QAAM,UAAU,IAAI,QAAQ,UAAU;AAEtC,QAAM,UAAU,MAAkB;AAChC,QAAI,CAAC,MAAM,IAAK,OAAM,IAAI,MAAM,gCAAgC;AAChE,WAAO,MAAM;AAAA,EACf;AAGA,QAAM,MACJ,CAAsB,WACtB,UAAU,SAAY;AACpB,UAAMA,QAAO,MAAM,OAAO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AQ,WAAW;","names":["code"]}
@@ -6,7 +6,7 @@ import {
6
6
  } from "./chunk-QA3O6RA2.js";
7
7
  import {
8
8
  detectProjectRoot
9
- } from "./chunk-KUY3QHGS.js";
9
+ } from "./chunk-TP3ORSHY.js";
10
10
  import {
11
11
  CliError,
12
12
  EXIT
@@ -16,7 +16,7 @@ import {
16
16
  ProjectBrain,
17
17
  configSchema,
18
18
  projectPaths
19
- } from "./chunk-QKY3OKVG.js";
19
+ } from "./chunk-2XGDILCW.js";
20
20
  import "./chunk-MC7RIPL7.js";
21
21
 
22
22
  // src/commands/init.ts
@@ -192,4 +192,4 @@ export {
192
192
  ensureLockIgnored,
193
193
  initCommand
194
194
  };
195
- //# sourceMappingURL=init-NHU5LJSS.js.map
195
+ //# sourceMappingURL=init-WW4XPFMM.js.map
@@ -0,0 +1,382 @@
1
+ import {
2
+ interruptSignal
3
+ } from "./chunk-HL4RIXPM.js";
4
+ import {
5
+ formatDuration,
6
+ truncate
7
+ } from "./chunk-SF5ZEAP4.js";
8
+ import {
9
+ printJson
10
+ } from "./chunk-QA3O6RA2.js";
11
+ import {
12
+ createProjectOrchestrator,
13
+ detectProjectRoot
14
+ } from "./chunk-TP3ORSHY.js";
15
+ import {
16
+ CliError,
17
+ EXIT
18
+ } from "./chunk-7XVXEO7U.js";
19
+ import "./chunk-732GIHRQ.js";
20
+ import {
21
+ EventBus,
22
+ ORCHESTRATOR_AGENTS,
23
+ ORCHESTRATOR_LIMITS
24
+ } from "./chunk-2XGDILCW.js";
25
+ import "./chunk-MC7RIPL7.js";
26
+
27
+ // src/commands/orchestrate.ts
28
+ import { existsSync } from "fs";
29
+ import { resolve } from "path";
30
+ var AGENT_ALIASES = {
31
+ claude: "claude",
32
+ "claude-code": "claude",
33
+ codex: "codex",
34
+ agy: "agy",
35
+ antigravity: "agy"
36
+ };
37
+ function parseAgents(value) {
38
+ const agents = [];
39
+ for (const raw of value.split(",")) {
40
+ const name = raw.trim().toLowerCase();
41
+ if (!name) continue;
42
+ const agent = AGENT_ALIASES[name];
43
+ if (!agent) {
44
+ throw new CliError(`Unknown agent "${raw.trim()}"`, {
45
+ hint: `Use a comma-separated list of ${ORCHESTRATOR_AGENTS.join(", ")}.`
46
+ });
47
+ }
48
+ if (!agents.includes(agent)) agents.push(agent);
49
+ }
50
+ if (agents.length === 0) {
51
+ throw new CliError("No agents given", {
52
+ hint: `Use a comma-separated list of ${ORCHESTRATOR_AGENTS.join(", ")}.`
53
+ });
54
+ }
55
+ return agents;
56
+ }
57
+ function parsePlanner(value) {
58
+ const agents = parseAgents(value);
59
+ if (agents.length !== 1) throw new CliError("--planner takes exactly one agent");
60
+ return agents[0];
61
+ }
62
+ function startInput(words, opts) {
63
+ const objective = words.join(" ").trim();
64
+ if (!objective) {
65
+ throw new CliError("Describe the objective", {
66
+ hint: 'davecode orchestrate "Add a /health endpoint with tests"'
67
+ });
68
+ }
69
+ if (objective.length > ORCHESTRATOR_LIMITS.objectiveMaxLength) {
70
+ throw new CliError(
71
+ `The objective is too long (at most ${ORCHESTRATOR_LIMITS.objectiveMaxLength} characters)`
72
+ );
73
+ }
74
+ if (opts.maxTasks !== void 0 && (opts.maxTasks < 1 || opts.maxTasks > ORCHESTRATOR_LIMITS.maxTasks)) {
75
+ throw new CliError(`--max-tasks must be between 1 and ${ORCHESTRATOR_LIMITS.maxTasks}`);
76
+ }
77
+ return {
78
+ objective,
79
+ ...opts.agents !== void 0 ? { agents: parseAgents(opts.agents) } : {},
80
+ ...opts.maxTasks !== void 0 ? { maxTasks: opts.maxTasks } : {},
81
+ ...opts.planner !== void 0 ? { planner: parsePlanner(opts.planner) } : {}
82
+ };
83
+ }
84
+ function isRunOver(run) {
85
+ return run.status === "done" || run.status === "failed" || run.status === "cancelled";
86
+ }
87
+ function runExitCode(run) {
88
+ return run.status === "done" ? EXIT.ok : EXIT.failure;
89
+ }
90
+ function oneLine(text, width = 160) {
91
+ const flat = text.replace(/\u001b\[[0-9;?]*[ -/]*[@-~]/g, "").replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim();
92
+ return truncate(flat, width);
93
+ }
94
+ var TASK_GLYPH = {
95
+ pending: (t) => t.dim(t.glyph.pending),
96
+ running: (t) => t.accent(t.glyph.running),
97
+ done: (t) => t.ok(t.glyph.success),
98
+ failed: (t) => t.error(t.glyph.failed),
99
+ conflict: (t) => t.warn(t.glyph.warn),
100
+ cancelled: (t) => t.dim(t.glyph.fail),
101
+ skipped: (t) => t.dim(t.glyph.blocked)
102
+ };
103
+ var AGENT_WIDTH = Math.max(...ORCHESTRATOR_AGENTS.map((agent) => agent.length));
104
+ function agentLabel(theme, agent) {
105
+ return theme.dim(agent.padEnd(AGENT_WIDTH));
106
+ }
107
+ function runStatus(theme, run) {
108
+ if (run.status === "done") return theme.ok(run.status);
109
+ if (run.status === "failed") return theme.error(run.status);
110
+ if (run.status === "cancelled") return theme.warn(run.status);
111
+ return theme.accent(run.status);
112
+ }
113
+ function taskOutcome(theme, task) {
114
+ const files = task.changedFiles?.length;
115
+ if (task.status === "done") {
116
+ return files ? theme.dim(`${files} file${files === 1 ? "" : "s"} changed`) : "";
117
+ }
118
+ return task.error ? theme.dim(oneLine(task.error)) : "";
119
+ }
120
+ function taskLine(theme, task) {
121
+ const parts = [
122
+ TASK_GLYPH[task.status](theme),
123
+ theme.bold(task.id),
124
+ agentLabel(theme, task.agent),
125
+ task.status === "done" ? task.title : `${task.title} ${theme.dim(`(${task.status})`)}`
126
+ ];
127
+ const outcome = taskOutcome(theme, task);
128
+ return outcome ? `${parts.join(" ")} ${outcome}` : parts.join(" ");
129
+ }
130
+ function createProgress(theme, runId) {
131
+ const seen = /* @__PURE__ */ new Map();
132
+ const agents = /* @__PURE__ */ new Map();
133
+ let planned = false;
134
+ let status;
135
+ return (event) => {
136
+ const time = theme.dim(new Date(event.ts).toTimeString().slice(0, 8));
137
+ const lines = [];
138
+ if (event.type === "orchestrator.output") {
139
+ if (event.runId !== runId) return lines;
140
+ const { kind, text } = event.output;
141
+ if (kind !== "tool" && kind !== "error") return lines;
142
+ const body = oneLine(text);
143
+ if (!body) return lines;
144
+ const who = `${theme.dim(event.taskId)} ${agentLabel(theme, agents.get(event.taskId) ?? "")}`;
145
+ lines.push(`${time} ${who} ${kind === "error" ? theme.error(body) : theme.dim(body)}`);
146
+ return lines;
147
+ }
148
+ if (event.type !== "orchestrator.run" || event.run.id !== runId) return lines;
149
+ const { run } = event;
150
+ if (run.planner) agents.set("plan", run.planner);
151
+ if (run.status !== status) {
152
+ status = run.status;
153
+ if (run.status === "planning") {
154
+ const by = run.planner ? ` with ${run.planner}` : "";
155
+ lines.push(
156
+ `${time} ${theme.accent(theme.glyph.running)} Planning${by}${theme.glyph.ellipsis}`
157
+ );
158
+ }
159
+ }
160
+ if (!planned && run.tasks.length > 0) {
161
+ planned = true;
162
+ lines.push(
163
+ `${time} ${theme.bold("Plan")} ${theme.dim(`${run.tasks.length} task${run.tasks.length === 1 ? "" : "s"}`)}`
164
+ );
165
+ for (const task of run.tasks) {
166
+ const after = task.dependsOn.length > 0 ? theme.dim(` after ${task.dependsOn.join(", ")}`) : "";
167
+ lines.push(
168
+ `${time} ${theme.bold(task.id)} ${agentLabel(theme, task.agent)} ${task.title}${after}`
169
+ );
170
+ }
171
+ }
172
+ for (const task of run.tasks) {
173
+ agents.set(task.id, task.agent);
174
+ const previous = seen.get(task.id);
175
+ seen.set(task.id, task.status);
176
+ if (previous === task.status || task.status === "pending") continue;
177
+ if (task.status === "running") {
178
+ lines.push(
179
+ `${time} ${TASK_GLYPH.running(theme)} ${theme.bold(task.id)} ${agentLabel(theme, task.agent)} started`
180
+ );
181
+ continue;
182
+ }
183
+ const outcome = taskOutcome(theme, task);
184
+ lines.push(
185
+ `${time} ${TASK_GLYPH[task.status](theme)} ${theme.bold(task.id)} ${agentLabel(theme, task.agent)} ${task.status}${outcome ? ` ${outcome}` : ""}`
186
+ );
187
+ }
188
+ return lines;
189
+ };
190
+ }
191
+ function describeRun(theme, run) {
192
+ const lines = [];
193
+ const planner = run.planner ? theme.dim(` planned by ${run.planner}`) : "";
194
+ lines.push(`${theme.bold(run.id)} ${runStatus(theme, run)}${planner}`);
195
+ lines.push(` ${oneLine(run.objective, 200)}`);
196
+ if (run.tasks.length > 0) lines.push("");
197
+ for (const task of run.tasks) {
198
+ lines.push(taskLine(theme, task));
199
+ if (task.status === "done" && task.summary) {
200
+ lines.push(theme.dim(` ${oneLine(task.summary)}`));
201
+ }
202
+ }
203
+ if (run.summary) lines.push("", run.summary.trim());
204
+ if (run.error) lines.push("", theme.error(oneLine(run.error, 300)));
205
+ if (run.integrationBranch && run.status === "done") {
206
+ lines.push("");
207
+ if (run.appliedAt) {
208
+ lines.push(
209
+ theme.dim(` ${run.integrationBranch} applied to ${run.baseBranch ?? "the base branch"}`)
210
+ );
211
+ } else {
212
+ lines.push(theme.dim(` results on ${run.integrationBranch}, nothing changed in your tree`));
213
+ lines.push(theme.dim(` apply with: davecode orchestrate --apply-run ${run.id}`));
214
+ }
215
+ }
216
+ return lines;
217
+ }
218
+ function runListLine(theme, run) {
219
+ const done = run.tasks.filter((task) => task.status === "done").length;
220
+ const applied = run.appliedAt ? " \xB7 applied" : "";
221
+ const when = run.createdAt.slice(0, 16).replace("T", " ");
222
+ return `${theme.bold(run.id)} ${run.status.padEnd(9)} ${theme.dim(`${done}/${run.tasks.length} tasks \xB7 ${when}${applied}`)} ${oneLine(run.objective, 80)}`;
223
+ }
224
+ var HINTS = {
225
+ no_agents: "Install and sign in to Claude Code (claude), Codex (codex) or Antigravity (agy), or pick others with --agents.",
226
+ not_a_repository: "Run it inside a git repository with at least one commit.",
227
+ busy: "Another run is active in this project. Wait for it, or cancel it from the dashboard.",
228
+ not_appliable: "Only a finished run that was not applied yet can be applied, and your working tree must be clean.",
229
+ not_found: "See `davecode orchestrate --list` for the ids."
230
+ };
231
+ function explain(err) {
232
+ const { name, code } = err ?? {};
233
+ if (name === "OrchestratorError" && typeof code === "string" && err instanceof Error) {
234
+ const hint = HINTS[code];
235
+ return new CliError(err.message, hint ? { hint } : {});
236
+ }
237
+ return err;
238
+ }
239
+ async function projectRoot(ctx, project) {
240
+ const root = project ? resolve(ctx.cwd, project) : await detectProjectRoot(ctx.cwd, ctx.home);
241
+ if (!root || !existsSync(root)) {
242
+ throw new CliError("Not inside a git repository", {
243
+ hint: "Run `davecode orchestrate` inside the repository the agents should work on."
244
+ });
245
+ }
246
+ return root;
247
+ }
248
+ async function openService(ctx, opts, deps) {
249
+ const root = await projectRoot(ctx, opts.project);
250
+ const events = new EventBus();
251
+ try {
252
+ const service = deps.service ? deps.service(events, root) : createProjectOrchestrator({ projectDir: root, home: ctx.home, env: ctx.env, events });
253
+ return { service, events };
254
+ } catch {
255
+ throw new CliError("The pane orchestrator is not available in this build", {
256
+ exitCode: EXIT.unavailable
257
+ });
258
+ }
259
+ }
260
+ function waitForEnd(service, events, id) {
261
+ return new Promise((resolveRun) => {
262
+ let unsubscribe = () => {
263
+ };
264
+ const finish = (run) => {
265
+ unsubscribe();
266
+ resolveRun(run);
267
+ };
268
+ unsubscribe = events.subscribe((event) => {
269
+ if (event.type === "orchestrator.run" && event.run.id === id && isRunOver(event.run)) {
270
+ finish(event.run);
271
+ }
272
+ });
273
+ const current = service.get(id);
274
+ if (current && isRunOver(current)) finish(current);
275
+ });
276
+ }
277
+ async function orchestrateCommand(ctx, words, opts, deps = {}) {
278
+ if (opts.list) return listRuns(ctx, opts, deps);
279
+ if (opts.applyRun !== void 0) return applyRun(ctx, opts.applyRun, opts, deps);
280
+ const input = startInput(words, opts);
281
+ const { service, events } = await openService(ctx, opts, deps);
282
+ const interrupt = interruptSignal(deps);
283
+ const started = Date.now();
284
+ let runId;
285
+ let progress;
286
+ const unsubscribe = events.subscribe((event) => {
287
+ if (ctx.json || !progress) return;
288
+ for (const line of progress(event)) ctx.err(line);
289
+ });
290
+ try {
291
+ let run;
292
+ try {
293
+ run = await service.start(input);
294
+ } catch (err) {
295
+ throw explain(err);
296
+ }
297
+ runId = run.id;
298
+ progress = createProgress(ctx.errTheme, run.id);
299
+ if (!ctx.json) {
300
+ ctx.err(
301
+ ctx.errTheme.dim(`Run ${run.id} started with ${run.agents.join(", ")}. Ctrl+C cancels.`)
302
+ );
303
+ for (const line of progress({ type: "orchestrator.run", run, ts: Date.now() })) ctx.err(line);
304
+ }
305
+ let cancelled = false;
306
+ void interrupt.promise.then(() => {
307
+ cancelled = true;
308
+ if (!ctx.json) ctx.err(ctx.errTheme.dim(`Cancelling${ctx.errTheme.glyph.ellipsis}`));
309
+ if (runId) service.cancel(runId);
310
+ });
311
+ run = await waitForEnd(service, events, run.id);
312
+ let applyError;
313
+ if (opts.apply && run.status === "done" && !cancelled) {
314
+ try {
315
+ run = await service.apply(run.id);
316
+ } catch (err) {
317
+ const explained = explain(err);
318
+ applyError = explained instanceof CliError ? explained : new CliError("Could not apply the run");
319
+ }
320
+ }
321
+ if (ctx.json)
322
+ printJson(ctx, { run, ...applyError ? { applyError: applyError.message } : {} });
323
+ else {
324
+ ctx.out();
325
+ for (const line of describeRun(ctx.theme, run)) ctx.out(line);
326
+ ctx.out(ctx.theme.dim(` took ${formatDuration((Date.now() - started) / 1e3)}`));
327
+ if (applyError) {
328
+ ctx.err(`${ctx.errTheme.error("error")}: ${applyError.message}`);
329
+ if (applyError.hint) ctx.err(ctx.errTheme.dim(applyError.hint));
330
+ }
331
+ }
332
+ return applyError ? EXIT.failure : runExitCode(run);
333
+ } finally {
334
+ interrupt.dispose();
335
+ unsubscribe();
336
+ await service.close();
337
+ }
338
+ }
339
+ async function listRuns(ctx, opts, deps) {
340
+ const { service } = await openService(ctx, opts, deps);
341
+ try {
342
+ const runs = service.list();
343
+ if (ctx.json) printJson(ctx, { runs });
344
+ else if (runs.length === 0) {
345
+ ctx.out(ctx.theme.dim('No runs yet. Start one with `davecode orchestrate "<objective>"`.'));
346
+ } else {
347
+ for (const run of runs) ctx.out(runListLine(ctx.theme, run));
348
+ }
349
+ return EXIT.ok;
350
+ } finally {
351
+ await service.close();
352
+ }
353
+ }
354
+ async function applyRun(ctx, id, opts, deps) {
355
+ const { service } = await openService(ctx, opts, deps);
356
+ try {
357
+ let run;
358
+ try {
359
+ run = await service.apply(id);
360
+ } catch (err) {
361
+ throw explain(err);
362
+ }
363
+ if (ctx.json) printJson(ctx, { run });
364
+ else for (const line of describeRun(ctx.theme, run)) ctx.out(line);
365
+ return EXIT.ok;
366
+ } finally {
367
+ await service.close();
368
+ }
369
+ }
370
+ export {
371
+ createProgress,
372
+ describeRun,
373
+ isRunOver,
374
+ oneLine,
375
+ orchestrateCommand,
376
+ parseAgents,
377
+ parsePlanner,
378
+ runExitCode,
379
+ runListLine,
380
+ startInput
381
+ };
382
+ //# sourceMappingURL=orchestrate-7YQDBS3E.js.map