@dmrlzz/davecode 0.0.0-stage → 0.3.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 (101) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +33 -2
  3. package/bin/davecode.js +2 -0
  4. package/dist/ChatApp-FO5SABXB.js +893 -0
  5. package/dist/ChatApp-FO5SABXB.js.map +1 -0
  6. package/dist/RunnerView-DLVR7C22.js +18 -0
  7. package/dist/RunnerView-DLVR7C22.js.map +1 -0
  8. package/dist/accounts-MTMGYKEP.js +724 -0
  9. package/dist/accounts-MTMGYKEP.js.map +1 -0
  10. package/dist/budget-RBHCEDPP.js +115 -0
  11. package/dist/budget-RBHCEDPP.js.map +1 -0
  12. package/dist/chat-ZDXX3N6X.js +95 -0
  13. package/dist/chat-ZDXX3N6X.js.map +1 -0
  14. package/dist/chunk-23KTE7IK.js +114 -0
  15. package/dist/chunk-23KTE7IK.js.map +1 -0
  16. package/dist/chunk-7XVXEO7U.js +23 -0
  17. package/dist/chunk-7XVXEO7U.js.map +1 -0
  18. package/dist/chunk-BOLFK3BH.js +20 -0
  19. package/dist/chunk-BOLFK3BH.js.map +1 -0
  20. package/dist/chunk-C7FDRA3U.js +9087 -0
  21. package/dist/chunk-C7FDRA3U.js.map +1 -0
  22. package/dist/chunk-DYQ56FBT.js +47 -0
  23. package/dist/chunk-DYQ56FBT.js.map +1 -0
  24. package/dist/chunk-FRFSJMN4.js +79 -0
  25. package/dist/chunk-FRFSJMN4.js.map +1 -0
  26. package/dist/chunk-IC3TDONV.js +12 -0
  27. package/dist/chunk-IC3TDONV.js.map +1 -0
  28. package/dist/chunk-IVZHKUCD.js +180 -0
  29. package/dist/chunk-IVZHKUCD.js.map +1 -0
  30. package/dist/chunk-MSLLH5XP.js +213 -0
  31. package/dist/chunk-MSLLH5XP.js.map +1 -0
  32. package/dist/chunk-OXRMGR72.js +20 -0
  33. package/dist/chunk-OXRMGR72.js.map +1 -0
  34. package/dist/chunk-OYEYNDOO.js +200 -0
  35. package/dist/chunk-OYEYNDOO.js.map +1 -0
  36. package/dist/chunk-PIIJ3RSI.js +1610 -0
  37. package/dist/chunk-PIIJ3RSI.js.map +1 -0
  38. package/dist/chunk-SF5ZEAP4.js +105 -0
  39. package/dist/chunk-SF5ZEAP4.js.map +1 -0
  40. package/dist/chunk-VVCXGQMY.js +107 -0
  41. package/dist/chunk-VVCXGQMY.js.map +1 -0
  42. package/dist/config-FRMY5OHG.js +158 -0
  43. package/dist/config-FRMY5OHG.js.map +1 -0
  44. package/dist/dashboard/assets/Accounts-BR3ZfVk4.js +1 -0
  45. package/dist/dashboard/assets/Badge-B-qzNRrZ.js +55 -0
  46. package/dist/dashboard/assets/Callout-B9g_wPDi.js +1 -0
  47. package/dist/dashboard/assets/Field-BfabPEcY.js +1 -0
  48. package/dist/dashboard/assets/Goals-BsV-6m94.js +1 -0
  49. package/dist/dashboard/assets/Library-CEA9P1m-.js +1 -0
  50. package/dist/dashboard/assets/Markdown-ClRsddnB.js +69 -0
  51. package/dist/dashboard/assets/Panel-B9tSgX6l.js +1 -0
  52. package/dist/dashboard/assets/RoutesPage-Dh-BJ3ir.js +4 -0
  53. package/dist/dashboard/assets/Runner-C_e9l5l2.js +1 -0
  54. package/dist/dashboard/assets/Settings-C6Yc1Gjg.js +1 -0
  55. package/dist/dashboard/assets/Switch-CUpOJjUT.js +1 -0
  56. package/dist/dashboard/assets/Tasks-CTku0rR3.js +2 -0
  57. package/dist/dashboard/assets/Traffic-CE6wZSMr.js +1 -0
  58. package/dist/dashboard/assets/Workspace-CxFxvkA6.js +1 -0
  59. package/dist/dashboard/assets/arrow-up-DL3CuFOO.js +1 -0
  60. package/dist/dashboard/assets/forms-D6UIYgC5.js +1 -0
  61. package/dist/dashboard/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
  62. package/dist/dashboard/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
  63. package/dist/dashboard/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
  64. package/dist/dashboard/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
  65. package/dist/dashboard/assets/geist-mono-cyrillic-ext-wght-normal-X_5orZeX.woff2 +0 -0
  66. package/dist/dashboard/assets/geist-mono-cyrillic-wght-normal-DiZS0aHC.woff2 +0 -0
  67. package/dist/dashboard/assets/geist-mono-latin-ext-wght-normal-Bwz-egvJ.woff2 +0 -0
  68. package/dist/dashboard/assets/geist-mono-latin-wght-normal-XN7g48iV.woff2 +0 -0
  69. package/dist/dashboard/assets/geist-mono-symbols2-wght-normal-CO5SzqOn.woff2 +0 -0
  70. package/dist/dashboard/assets/geist-mono-vietnamese-wght-normal-DadHysG0.woff2 +0 -0
  71. package/dist/dashboard/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
  72. package/dist/dashboard/assets/index-1iH716Xy.css +2 -0
  73. package/dist/dashboard/assets/index-BMWr9EKo.js +104 -0
  74. package/dist/dashboard/assets/task-errors-CE4oEr8H.js +1 -0
  75. package/dist/dashboard/assets/trash-CWqeZ7eg.js +1 -0
  76. package/dist/dashboard/favicon.svg +7 -0
  77. package/dist/dashboard/github.svg +1 -0
  78. package/dist/dashboard/index.html +31 -0
  79. package/dist/dist-ZPXEVBEC.js +357 -0
  80. package/dist/dist-ZPXEVBEC.js.map +1 -0
  81. package/dist/doctor-7RUD4D3A.js +279 -0
  82. package/dist/doctor-7RUD4D3A.js.map +1 -0
  83. package/dist/goal-JFRNPBSD.js +302 -0
  84. package/dist/goal-JFRNPBSD.js.map +1 -0
  85. package/dist/index.js +381 -0
  86. package/dist/index.js.map +1 -0
  87. package/dist/init-NFYNO3A3.js +194 -0
  88. package/dist/init-NFYNO3A3.js.map +1 -0
  89. package/dist/prompts-L37J72YW.js +215 -0
  90. package/dist/prompts-L37J72YW.js.map +1 -0
  91. package/dist/run-ARUPXFFB.js +376 -0
  92. package/dist/run-ARUPXFFB.js.map +1 -0
  93. package/dist/runner-state-QFU3LJVJ.js +17 -0
  94. package/dist/runner-state-QFU3LJVJ.js.map +1 -0
  95. package/dist/start-CFPOVIAR.js +285 -0
  96. package/dist/start-CFPOVIAR.js.map +1 -0
  97. package/dist/status-E4EACVE2.js +25 -0
  98. package/dist/status-E4EACVE2.js.map +1 -0
  99. package/dist/tasks-ZIK6BVEX.js +184 -0
  100. package/dist/tasks-ZIK6BVEX.js.map +1 -0
  101. package/package.json +68 -4
package/dist/index.js ADDED
@@ -0,0 +1,381 @@
1
+ import {
2
+ createContext
3
+ } from "./chunk-DYQ56FBT.js";
4
+ import "./chunk-VVCXGQMY.js";
5
+ import {
6
+ CliError,
7
+ EXIT
8
+ } from "./chunk-7XVXEO7U.js";
9
+
10
+ // src/program.ts
11
+ import { Command, CommanderError, InvalidArgumentError, Option } from "commander";
12
+ function buildProgram(options, state = { exitCode: 0 }) {
13
+ const { io } = options;
14
+ const program = new Command("davecode");
15
+ const context = () => {
16
+ if (!state.ctx) throw new Error("CLI context is not initialised");
17
+ return state.ctx;
18
+ };
19
+ const run = (action) => async (...args) => {
20
+ const code2 = await action(context(), ...args);
21
+ if (typeof code2 === "number") state.exitCode = code2;
22
+ };
23
+ program.description("Local-first AI gateway and autonomous coding engine.").usage("[command] [options]").option("--home <dir>", "DaveCode home directory (sets DAVECODE_HOME)").option("--json", "machine-readable JSON output where supported").option("--no-color", "disable colours (NO_COLOR is honoured too)").option("-V, --version", "print the version and exit").showSuggestionAfterError(true).configureOutput({
24
+ writeOut: (text) => io.stdout.write(text),
25
+ writeErr: (text) => io.stderr.write(text),
26
+ outputError: (text, write) => write(text)
27
+ }).exitOverride().hook("preAction", (_root, action) => {
28
+ state.ctx = createContext(action.optsWithGlobals(), io, options);
29
+ }).addHelpText(
30
+ "after",
31
+ `
32
+ Run \`davecode\` with no command in a terminal to open the chat TUI.
33
+ Docs: https://github.com/DMRLZZ/DaveCode#readme`
34
+ );
35
+ program.action(
36
+ run(async (ctx) => {
37
+ const globals = program.opts();
38
+ if (globals.version) {
39
+ const { VERSION } = await import("./dist-ZPXEVBEC.js");
40
+ ctx.out(`davecode ${VERSION}`);
41
+ return EXIT.ok;
42
+ }
43
+ if (ctx.interactive) {
44
+ const { chatCommand } = await import("./chat-ZDXX3N6X.js");
45
+ return chatCommand(ctx, {});
46
+ }
47
+ program.outputHelp();
48
+ return EXIT.ok;
49
+ })
50
+ );
51
+ registerCommands(program, run);
52
+ return program;
53
+ }
54
+ function parsePort(value) {
55
+ const n = Number(value);
56
+ if (!/^\d+$/.test(value.trim()) || !Number.isInteger(n) || n < 0 || n > 65535) {
57
+ throw new InvalidArgumentError("expected a port number between 0 and 65535");
58
+ }
59
+ return n;
60
+ }
61
+ function parseInteger(value) {
62
+ const n = Number(value);
63
+ if (!/^-?\d+$/.test(value.trim()) || !Number.isSafeInteger(n) || n < 0) {
64
+ throw new InvalidArgumentError("expected a non-negative integer");
65
+ }
66
+ return n;
67
+ }
68
+ function collect(value, previous = []) {
69
+ return [
70
+ ...previous,
71
+ ...value.split(",").map((v) => v.trim()).filter(Boolean)
72
+ ];
73
+ }
74
+ function registerCommands(program, run) {
75
+ program.command("app").description("start your local workspace in a Chrome or Edge app window").addOption(new Option("-p, --port <port>", "port to listen on").argParser(parsePort)).option("--project <dir>", "repository to open").action(
76
+ run(async (ctx, opts) => {
77
+ const { startCommand } = await import("./start-CFPOVIAR.js");
78
+ return startCommand(ctx, { ...opts, host: "127.0.0.1", app: true });
79
+ })
80
+ );
81
+ program.command("start").description("start the gateway (OpenAI-compatible /v1, dashboard API and web dashboard)").addOption(new Option("-p, --port <port>", "port to listen on").argParser(parsePort)).option("--host <host>", "interface to bind (default 127.0.0.1)").option("--no-dashboard", "do not serve the web dashboard").option("--project <dir>", "repository whose project brain to serve (default: detected)").option("--verbose", "print gateway request logs").option("-q, --quiet", "do not print the live activity log").action(
82
+ run(async (ctx, opts) => {
83
+ const { startCommand } = await import("./start-CFPOVIAR.js");
84
+ return startCommand(ctx, opts);
85
+ })
86
+ );
87
+ program.command("status").description("gateway health, accounts and 1m/5h/24h quota usage").action(
88
+ run(async (ctx) => {
89
+ const { statusCommand } = await import("./status-E4EACVE2.js");
90
+ return statusCommand(ctx);
91
+ })
92
+ );
93
+ program.command("chat").description("chat TUI (also what bare `davecode` opens in a terminal)").option("-m, --model <id>", "model or route, e.g. davecode/auto or anthropic/claude-sonnet-5-5").option("--project <dir>", "repository whose brain an in-process gateway serves").action(
94
+ run(async (ctx, opts) => {
95
+ const { chatCommand } = await import("./chat-ZDXX3N6X.js");
96
+ return chatCommand(ctx, opts);
97
+ })
98
+ );
99
+ registerAccounts(program, run);
100
+ registerProject(program, run);
101
+ program.command("budget").description("plans, renewals and remaining quota per account (what agents are told)").option("--context", "print only the summary injected into agent prompts").option("--local", "read the local database even if a gateway is running").action(
102
+ run(async (ctx, opts) => {
103
+ const { budgetCommand } = await import("./budget-RBHCEDPP.js");
104
+ return budgetCommand(ctx, opts);
105
+ })
106
+ );
107
+ program.command("doctor").description("check the environment and print fixes").action(
108
+ run(async (ctx) => {
109
+ const { doctorCommand } = await import("./doctor-7RUD4D3A.js");
110
+ return doctorCommand(ctx);
111
+ })
112
+ );
113
+ program.command("run").description("run the autonomous engine on the task graph (live view in a terminal)").option("--once", "implement at most one ready task, print the result and exit").option(
114
+ "--task <id>",
115
+ "run this task instead of the runner's pick (it must be PENDING and unblocked)"
116
+ ).option("--project <dir>", "repository to work on (default: detected)").addHelpText(
117
+ "after",
118
+ `
119
+ Exit codes with --once: 0 success or nothing to do, 1 failed or error, 130 stopped.
120
+ Ctrl+C stops safely: partial work stays on the task branch and the task goes back to PENDING.`
121
+ ).action(
122
+ run(async (ctx, opts) => {
123
+ const { runCommand } = await import("./run-ARUPXFFB.js");
124
+ return runCommand(ctx, opts);
125
+ })
126
+ );
127
+ registerGoals(program, run);
128
+ }
129
+ function registerGoals(program, run) {
130
+ const limit = (flag, description) => new Option(flag, description).argParser((value) => {
131
+ const n = parseInteger(value);
132
+ if (n < 1) throw new InvalidArgumentError("expected a positive integer");
133
+ return n;
134
+ });
135
+ program.command("goal <objective...>").description("pursue an objective with a team of agents (plan, execute, review, re-plan)").addOption(
136
+ limit("--max-rounds <n>", "plan \u2192 execute \u2192 review rounds (capped by goal.maxRounds)")
137
+ ).addOption(limit("--max-tasks <n>", "tasks across all rounds (capped by goal.maxTasks)")).addOption(
138
+ limit("--max-tokens <n>", "token budget for the whole goal (capped by goal.maxTokens)")
139
+ ).option("--dry-run", "plan only: print the task graph without executing it").option("--project <dir>", "repository to work in (default: detected)").addHelpText(
140
+ "after",
141
+ `
142
+ Agents never send emails, post, pay or sign up for anything: such steps become drafts in
143
+ .davecode/goals/<goal-id>/. Code tasks go through the autonomous runner (branch, checks, merge).
144
+ Ctrl+C cancels. Exit codes: 0 succeeded or planned, 1 failed or out of budget, 130 cancelled.
145
+
146
+ Examples:
147
+ davecode goal "Write positioning and landing copy for this app" --dry-run
148
+ davecode goal "Add a /health endpoint with tests" --max-rounds 2`
149
+ ).action(
150
+ run(async (ctx, words, opts) => {
151
+ const { goalCommand } = await import("./goal-JFRNPBSD.js");
152
+ return goalCommand(ctx, words, opts);
153
+ })
154
+ );
155
+ const goals = program.command("goals").description("goals of this repository");
156
+ goals.command("list", { isDefault: true }).alias("ls").description("goals, newest first").option("--project <dir>", "repository (default: detected)").action(
157
+ run(async (ctx, opts) => {
158
+ const { goalsList } = await import("./goal-JFRNPBSD.js");
159
+ return goalsList(ctx, opts);
160
+ })
161
+ );
162
+ goals.command("show <id>").description("tasks, artifacts and summary of a goal").option("--project <dir>", "repository (default: detected)").action(
163
+ run(async (ctx, id, opts) => {
164
+ const { goalsShow } = await import("./goal-JFRNPBSD.js");
165
+ return goalsShow(ctx, id, opts);
166
+ })
167
+ );
168
+ goals.command("cancel <id>").description("cancel a running goal").option("--project <dir>", "repository (default: detected)").action(
169
+ run(async (ctx, id, opts) => {
170
+ const { goalsCancel } = await import("./goal-JFRNPBSD.js");
171
+ return goalsCancel(ctx, id, opts);
172
+ })
173
+ );
174
+ }
175
+ function registerProject(program, run) {
176
+ program.command("init").description("scaffold the project brain (.davecode/) in this repository").option("--name <name>", "project name used in STATE.md and ARCHITECTURE.md").option("--config", "write a starter .davecode/config.json without asking").option("--no-config", "do not write .davecode/config.json").action(
177
+ run(async (ctx, opts) => {
178
+ const { initCommand } = await import("./init-NFYNO3A3.js");
179
+ return initCommand(ctx, opts);
180
+ })
181
+ );
182
+ const tasks = program.command("tasks").description("show and edit the task graph");
183
+ tasks.command("list", { isDefault: true }).alias("ls").description("task tree with status and blocked reasons").action(
184
+ run(async (ctx) => {
185
+ const { tasksList } = await import("./tasks-ZIK6BVEX.js");
186
+ return tasksList(ctx);
187
+ })
188
+ );
189
+ tasks.command("next").description("the task the runner would pick next").action(
190
+ run(async (ctx) => {
191
+ const { tasksNext } = await import("./tasks-ZIK6BVEX.js");
192
+ return tasksNext(ctx);
193
+ })
194
+ );
195
+ tasks.command("add <id> <title...>").description("add a PENDING task").option("-d, --depends <ids>", "dependencies (repeatable or comma-separated)", collect).addOption(new Option("-p, --priority <n>", "higher runs first").argParser(parseInteger)).option("--description <text>", "longer description").option(
196
+ "-a, --acceptance <criterion>",
197
+ "acceptance criterion (repeatable)",
198
+ (v, prev = []) => [...prev, v]
199
+ ).action(
200
+ run(
201
+ async (ctx, id, title, opts) => {
202
+ const { tasksAdd } = await import("./tasks-ZIK6BVEX.js");
203
+ return tasksAdd(ctx, id, title, opts);
204
+ }
205
+ )
206
+ );
207
+ tasks.command("status <id> <status>").description("move a task to PENDING | IN_PROGRESS | SUCCESS | FAILED").option("--notes <text>", "note stored on the task").action(
208
+ run(async (ctx, id, status, opts) => {
209
+ const { tasksStatus } = await import("./tasks-ZIK6BVEX.js");
210
+ return tasksStatus(ctx, id, status, opts);
211
+ })
212
+ );
213
+ const config = program.command("config").description("show the resolved configuration");
214
+ config.command("show", { isDefault: true }).description("resolved config as JSON (secrets redacted)").action(
215
+ run(async (ctx) => {
216
+ const { configShow } = await import("./config-FRMY5OHG.js");
217
+ return configShow(ctx);
218
+ })
219
+ );
220
+ config.command("path").description("where config, state and brains live").action(
221
+ run(async (ctx) => {
222
+ const { configPath } = await import("./config-FRMY5OHG.js");
223
+ return configPath(ctx);
224
+ })
225
+ );
226
+ config.command("get <key>").description("one value by dotted key, e.g. server.port").action(
227
+ run(async (ctx, key) => {
228
+ const { configGet } = await import("./config-FRMY5OHG.js");
229
+ return configGet(ctx, key);
230
+ })
231
+ );
232
+ }
233
+ function addAccountOptions(command, run) {
234
+ return command.option(
235
+ "--provider <kind>",
236
+ "anthropic | openai | gemini | openai-compatible | claude-cli | codex-cli | gemini-cli | gemini-web"
237
+ ).option("--label <name>", "human-friendly name").addOption(
238
+ new Option("--priority <n>", "lower is tried first (default 100)").argParser(parseInteger)
239
+ ).addOption(
240
+ new Option("--weight <n>", "traffic share among equal priorities").argParser(parseInteger)
241
+ ).option("--secret-env <var>", "read the API key from this environment variable").option("--secret-stdin", "read the API key from stdin").option("--secret <value>", "API key (discouraged: visible in shell history)").option("--base-url <url>", "endpoint for openai-compatible accounts").option("--model <id>", "advertised model (repeatable or comma-separated)", collect).option("--default-model <id>", "model used for davecode/auto without a route").option("--binary-path <path>", "CLI binary for claude-cli / codex-cli / gemini-cli").option("--limit <key=value>", "quota limit, e.g. tokens5h=500000 (repeatable)", collect).option("--disabled", "add the account disabled").option("-y, --yes", "never prompt: take everything from flags").option("--no-login", "do not offer to log in after adding a CLI account").option("--local", "write to the local database even if a gateway is running").addHelpText(
242
+ "after",
243
+ `
244
+ Examples:
245
+ davecode accounts add # interactive
246
+ davecode accounts add --provider anthropic --label work --secret-env ANTHROPIC_API_KEY --yes
247
+ echo "$OPENROUTER_KEY" | davecode accounts add --provider openai-compatible \\
248
+ --base-url https://openrouter.ai/api/v1 --model openai/gpt-5.5 --secret-stdin
249
+ davecode accounts add --provider claude-cli --label "Claude Pro" --yes`
250
+ ).action(
251
+ run(async (ctx, opts) => {
252
+ const { accountsAdd } = await import("./accounts-MTMGYKEP.js");
253
+ return accountsAdd(ctx, opts);
254
+ })
255
+ );
256
+ }
257
+ function registerAccounts(program, run) {
258
+ const accounts = program.command("accounts").description("manage provider accounts");
259
+ accounts.command("list", { isDefault: true }).alias("ls").description("list accounts").option("--local", "read the local database even if a gateway is running").action(
260
+ run(async (ctx, opts) => {
261
+ const { accountsList } = await import("./accounts-MTMGYKEP.js");
262
+ return accountsList(ctx, opts);
263
+ })
264
+ );
265
+ addAccountOptions(
266
+ accounts.command("add").description("add an account (interactive in a terminal)"),
267
+ run
268
+ );
269
+ accounts.command("remove <id>").alias("rm").description("remove an account, its secret and its sandbox").option("-y, --yes", "do not ask for confirmation").option("--local", "write to the local database even if a gateway is running").action(
270
+ run(async (ctx, id, opts) => {
271
+ const { accountsRemove } = await import("./accounts-MTMGYKEP.js");
272
+ return accountsRemove(ctx, id, opts);
273
+ })
274
+ );
275
+ for (const [name, enabled] of [
276
+ ["enable", true],
277
+ ["disable", false]
278
+ ]) {
279
+ accounts.command(`${name} <id>`).description(`${name} an account${enabled ? " (also clears error and cooldown state)" : ""}`).option("--local", "write to the local database even if a gateway is running").action(
280
+ run(async (ctx, id, opts) => {
281
+ const { accountsSetEnabled } = await import("./accounts-MTMGYKEP.js");
282
+ return accountsSetEnabled(ctx, id, enabled, opts);
283
+ })
284
+ );
285
+ }
286
+ accounts.command("plan <id>").description("show or set what you pay for an account (plan, price, paid/renewal dates)").option("--plan <name>", 'plan name, e.g. "Claude Pro" or "API pay-as-you-go"').option("--price <amount>", "price per period, e.g. 20").option("--currency <code>", "3-letter currency code (default USD)").option("--period <period>", "month | year (default month)").option("--paid <date>", "last payment date (YYYY-MM-DD)").option("--renews <date>", "next renewal date (YYYY-MM-DD)").option("--notes <text>", "free-form note").option("--clear", "remove the recorded plan").option("--local", "write to the local database even if a gateway is running").addHelpText(
287
+ "after",
288
+ `
289
+ Entered by hand: DaveCode never reads billing pages. Example:
290
+ davecode accounts plan acc_123 --plan "Claude Pro" --price 20 --renews 2026-11-01`
291
+ ).action(
292
+ run(async (ctx, id, opts) => {
293
+ const { accountsPlan } = await import("./accounts-MTMGYKEP.js");
294
+ return accountsPlan(ctx, id, opts);
295
+ })
296
+ );
297
+ accounts.command("login <id> [args...]").description(
298
+ "log a claude-cli / codex-cli / gemini-cli account in, inside its own isolated config dir"
299
+ ).allowUnknownOption().option("--local", "read the local database even if a gateway is running").option("--hold", "wait for Enter before exiting (for windows opened by the dashboard)").addHelpText(
300
+ "after",
301
+ `
302
+ Runs the vendor's official sign-in (claude auth login, codex login, Gemini CLI's
303
+ "Login with Google") with CLAUDE_CONFIG_DIR / CODEX_HOME / GEMINI_CLI_HOME pointing at the
304
+ account's sandbox, so every account keeps a separate login. DaveCode never sees the password.
305
+ Extra arguments after -- replace the default ones (e.g. -- login --device-auth for Codex).`
306
+ ).action(
307
+ run(
308
+ async (ctx, id, args, opts) => {
309
+ const { accountsLogin } = await import("./accounts-MTMGYKEP.js");
310
+ return accountsLogin(ctx, id, args, opts);
311
+ }
312
+ )
313
+ );
314
+ accounts.command("connect <id>").description("connect a subscription: check its login and run the official sign-in if needed").option("--check", "only report whether the account is connected").option("--local", "read the local database even if a gateway is running").addHelpText(
315
+ "after",
316
+ `
317
+ API-key accounts are connected when a key is stored. CLI accounts (claude-cli, codex-cli,
318
+ gemini-cli) ask the vendor CLI for its login status inside the account sandbox and, when not
319
+ connected, start the vendor's own sign-in. Example:
320
+ davecode accounts connect acc_123 --check`
321
+ ).action(
322
+ run(async (ctx, id, opts) => {
323
+ const { accountsConnect } = await import("./accounts-MTMGYKEP.js");
324
+ return accountsConnect(ctx, id, opts);
325
+ })
326
+ );
327
+ addAccountOptions(program.command("add-account").description("alias of `accounts add`"), run);
328
+ }
329
+ function describeError(err) {
330
+ if (err instanceof CliError) {
331
+ return {
332
+ message: err.message,
333
+ exitCode: err.exitCode,
334
+ ...err.hint ? { hint: err.hint } : {}
335
+ };
336
+ }
337
+ if (err instanceof Error) {
338
+ if (err.name === "ConfigError") {
339
+ return {
340
+ message: err.message,
341
+ hint: "Fix the file above or run `davecode config path` to see where config is read from.",
342
+ exitCode: EXIT.failure
343
+ };
344
+ }
345
+ return { message: err.message, exitCode: EXIT.failure };
346
+ }
347
+ return { message: String(err), exitCode: EXIT.failure };
348
+ }
349
+ async function runCli(argv, options) {
350
+ const state = { exitCode: 0 };
351
+ const program = buildProgram(options, state);
352
+ try {
353
+ await program.parseAsync(argv, { from: "user" });
354
+ return state.exitCode;
355
+ } catch (err) {
356
+ if (err instanceof CommanderError) {
357
+ return err.exitCode;
358
+ }
359
+ const { message, hint, exitCode } = describeError(err);
360
+ const theme = state.ctx?.errTheme;
361
+ const label = theme ? theme.error("error") : "error";
362
+ options.io.stderr.write(`${label}: ${message}
363
+ `);
364
+ if (hint) options.io.stderr.write(`${theme ? theme.dim(hint) : hint}
365
+ `);
366
+ if (options.env.DAVECODE_DEBUG && err instanceof Error && err.stack) {
367
+ options.io.stderr.write(`${err.stack}
368
+ `);
369
+ }
370
+ return exitCode;
371
+ }
372
+ }
373
+
374
+ // src/index.ts
375
+ var code = await runCli(process.argv.slice(2), {
376
+ io: { stdout: process.stdout, stderr: process.stderr, stdin: process.stdin },
377
+ env: process.env,
378
+ cwd: process.cwd()
379
+ });
380
+ process.exitCode = code;
381
+ //# sourceMappingURL=index.js.map
@@ -0,0 +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 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,GAA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AM;AAAA,EACf,SAAS,KAAK;AACZ,QAAI,eAAe,gBAAgB;AAEjC,aAAO,IAAI;AAAA,IACb;AACA,UAAM,EAAE,SAAS,MAAM,SAAS,IAAI,cAAc,GAAG;AACrD,UAAM,QAAQ,MAAM,KAAK;AACzB,UAAM,QAAQ,QAAQ,MAAM,MAAM,OAAO,IAAI;AAC7C,YAAQ,GAAG,OAAO,MAAM,GAAG,KAAK,KAAK,OAAO;AAAA,CAAI;AAChD,QAAI,KAAM,SAAQ,GAAG,OAAO,MAAM,GAAG,QAAQ,MAAM,IAAI,IAAI,IAAI,IAAI;AAAA,CAAI;AACvE,QAAI,QAAQ,IAAI,kBAAkB,eAAe,SAAS,IAAI,OAAO;AACnE,cAAQ,GAAG,OAAO,MAAM,GAAG,IAAI,KAAK;AAAA,CAAI;AAAA,IAC1C;AACA,WAAO;AAAA,EACT;AACF;;;ACvlBA,IAAM,OAAO,MAAM,OAAO,QAAQ,KAAK,MAAM,CAAC,GAAG;AAAA,EAC/C,IAAI,EAAE,QAAQ,QAAQ,QAAQ,QAAQ,QAAQ,QAAQ,OAAO,QAAQ,MAAM;AAAA,EAC3E,KAAK,QAAQ;AAAA,EACb,KAAK,QAAQ,IAAI;AACnB,CAAC;AACD,QAAQ,WAAW;","names":["code"]}
@@ -0,0 +1,194 @@
1
+ import {
2
+ PromptCancelledError
3
+ } from "./chunk-IC3TDONV.js";
4
+ import {
5
+ printJson
6
+ } from "./chunk-DYQ56FBT.js";
7
+ import "./chunk-VVCXGQMY.js";
8
+ import {
9
+ detectProjectRoot
10
+ } from "./chunk-PIIJ3RSI.js";
11
+ import {
12
+ CliError,
13
+ EXIT
14
+ } from "./chunk-7XVXEO7U.js";
15
+ import {
16
+ ProjectBrain,
17
+ configSchema,
18
+ projectPaths
19
+ } from "./chunk-C7FDRA3U.js";
20
+
21
+ // src/commands/init.ts
22
+ import { existsSync as existsSync2, readFileSync as readFileSync2, writeFileSync } from "fs";
23
+ import { basename, join as join2, relative } from "path";
24
+
25
+ // src/lib/validate-detect.ts
26
+ import { existsSync, readFileSync } from "fs";
27
+ import { join } from "path";
28
+ function readPackageJson(root) {
29
+ try {
30
+ const value = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
31
+ return value && typeof value === "object" ? value : void 0;
32
+ } catch {
33
+ return void 0;
34
+ }
35
+ }
36
+ function detectPackageManager(root, pkg) {
37
+ const declared = pkg?.packageManager?.split("@")[0];
38
+ if (declared === "pnpm" || declared === "yarn" || declared === "bun" || declared === "npm") {
39
+ return declared;
40
+ }
41
+ if (existsSync(join(root, "pnpm-lock.yaml"))) return "pnpm";
42
+ if (existsSync(join(root, "yarn.lock"))) return "yarn";
43
+ if (existsSync(join(root, "bun.lock")) || existsSync(join(root, "bun.lockb"))) return "bun";
44
+ return "npm";
45
+ }
46
+ var CANDIDATES = {
47
+ lint: ["lint", "lint:check", "check:lint"],
48
+ typecheck: ["typecheck", "type-check", "check-types", "check:types", "types", "tsc"],
49
+ test: ["test", "test:unit", "test:ci"]
50
+ };
51
+ var NPM_PLACEHOLDER = /no test specified/i;
52
+ function runScript(pm, script) {
53
+ if (script === "test") return `${pm} test`;
54
+ switch (pm) {
55
+ case "npm":
56
+ return `npm run ${script}`;
57
+ case "bun":
58
+ return `bun run ${script}`;
59
+ default:
60
+ return `${pm} ${script}`;
61
+ }
62
+ }
63
+ function detectValidateCommands(pkg, pm) {
64
+ const scripts = pkg?.scripts ?? {};
65
+ const found = {};
66
+ for (const [kind, names] of Object.entries(CANDIDATES)) {
67
+ const script = names.find((name) => {
68
+ const body = scripts[name];
69
+ return typeof body === "string" && body.trim() !== "" && !NPM_PLACEHOLDER.test(body);
70
+ });
71
+ if (script) found[kind] = runScript(pm, script);
72
+ }
73
+ return found;
74
+ }
75
+ function starterConfig(validate) {
76
+ return { runner: { validate, judge: { kind: "none" } } };
77
+ }
78
+
79
+ // src/commands/init.ts
80
+ var LOCK_IGNORE = ".davecode/.lock";
81
+ function ensureLockIgnored(root) {
82
+ const path = join2(root, ".gitignore");
83
+ const current = existsSync2(path) ? readFileSync2(path, "utf8") : "";
84
+ const lines = current.split(/\r?\n/).map((l) => l.trim());
85
+ if (lines.includes(LOCK_IGNORE) || lines.includes(".davecode/") || lines.includes(".davecode")) {
86
+ return false;
87
+ }
88
+ const prefix = current === "" || current.endsWith("\n") ? current : `${current}
89
+ `;
90
+ writeFileSync(
91
+ path,
92
+ `${prefix}${current === "" ? "" : "\n"}# DaveCode runtime lock
93
+ ${LOCK_IGNORE}
94
+ `
95
+ );
96
+ return true;
97
+ }
98
+ async function initCommand(ctx, opts, deps = {}) {
99
+ const root = await detectProjectRoot(ctx.cwd, ctx.home) ?? ctx.cwd;
100
+ const paths = projectPaths(root);
101
+ const pkg = readPackageJson(root);
102
+ const name = opts.name?.trim() || pkg?.name || basename(root);
103
+ const before = {
104
+ state: existsSync2(paths.state),
105
+ architecture: existsSync2(paths.architecture),
106
+ taskGraph: existsSync2(paths.taskGraph)
107
+ };
108
+ await ProjectBrain.init(root, { name });
109
+ const created = Object.entries(before).filter(([, existed]) => !existed).map(([file]) => file);
110
+ const pm = detectPackageManager(root, pkg);
111
+ const validate = detectValidateCommands(pkg, pm);
112
+ let configWritten = false;
113
+ let configSkipped;
114
+ if (existsSync2(paths.config)) {
115
+ configSkipped = "exists";
116
+ } else if (opts.config === false) {
117
+ configSkipped = "declined";
118
+ } else {
119
+ let write = opts.config === true;
120
+ if (!write && ctx.interactive) {
121
+ const prompter = deps.prompter ?? (await import("./prompts-L37J72YW.js")).createInkPrompter({
122
+ stdout: ctx.io.stdout,
123
+ stdin: ctx.io.stdin,
124
+ theme: ctx.theme
125
+ });
126
+ const summary = Object.entries(validate).map(([k, v]) => `${k}: ${v}`).join(", ");
127
+ try {
128
+ write = await prompter.confirm(
129
+ summary ? `Write .davecode/config.json with runner.validate (${summary})?` : "Write a starter .davecode/config.json (no lint/typecheck/test scripts found)?",
130
+ true
131
+ );
132
+ } catch (err) {
133
+ if (!(err instanceof PromptCancelledError)) throw err;
134
+ }
135
+ }
136
+ if (write) {
137
+ const content = starterConfig(validate);
138
+ const check = configSchema.safeParse(content);
139
+ if (!check.success) throw new CliError("Generated config is invalid (please report a bug)");
140
+ writeFileSync(paths.config, `${JSON.stringify(content, null, 2)}
141
+ `);
142
+ configWritten = true;
143
+ } else {
144
+ configSkipped = ctx.interactive ? "declined" : "non-interactive";
145
+ }
146
+ }
147
+ const ignoreUpdated = existsSync2(join2(root, ".git")) ? ensureLockIgnored(root) : false;
148
+ if (ctx.json) {
149
+ printJson(ctx, {
150
+ root,
151
+ name,
152
+ created,
153
+ config: configWritten ? paths.config : null,
154
+ validate,
155
+ gitignoreUpdated: ignoreUpdated
156
+ });
157
+ return EXIT.ok;
158
+ }
159
+ const { theme } = ctx;
160
+ const rel = (p) => relative(ctx.cwd, p) || ".";
161
+ ctx.out(
162
+ `${theme.ok(theme.glyph.ok)} Project brain ready for ${theme.bold(name)} ${theme.dim(rel(paths.dir))}`
163
+ );
164
+ const files = [
165
+ ["STATE.md", paths.state, before.state],
166
+ ["ARCHITECTURE.md", paths.architecture, before.architecture],
167
+ ["TASK_GRAPH.json", paths.taskGraph, before.taskGraph]
168
+ ];
169
+ for (const [label, , existed] of files) {
170
+ ctx.out(` ${existed ? theme.dim("kept ") : theme.accent("created")} ${label}`);
171
+ }
172
+ if (configWritten) {
173
+ ctx.out(` ${theme.accent("created")} config.json`);
174
+ for (const [kind, command] of Object.entries(validate)) {
175
+ ctx.out(theme.dim(` runner.validate.${kind} = ${command}`));
176
+ }
177
+ } else if (configSkipped === "exists") {
178
+ ctx.out(` ${theme.dim("kept ")} config.json`);
179
+ } else if (configSkipped === "non-interactive") {
180
+ ctx.out(theme.dim(" config.json not written (pass --config to create a starter config)"));
181
+ }
182
+ if (ignoreUpdated)
183
+ ctx.out(` ${theme.accent("updated")} .gitignore ${theme.dim(`(${LOCK_IGNORE})`)}`);
184
+ ctx.out();
185
+ ctx.out(theme.dim("Next:"));
186
+ ctx.out(` ${theme.accent('davecode tasks add setup "Describe the first task"')}`);
187
+ ctx.out(` ${theme.accent("davecode start")}`);
188
+ return EXIT.ok;
189
+ }
190
+ export {
191
+ ensureLockIgnored,
192
+ initCommand
193
+ };
194
+ //# sourceMappingURL=init-NFYNO3A3.js.map