@dirgha/code 1.13.2 → 1.15.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 (32) hide show
  1. package/dist/cli/flags.js +15 -14
  2. package/dist/cli/flags.js.map +1 -1
  3. package/dist/cli/main.js +229 -152
  4. package/dist/cli/main.js.map +1 -1
  5. package/dist/cli/subcommands/ask.d.ts +1 -1
  6. package/dist/cli/subcommands/ask.js +53 -28
  7. package/dist/cli/subcommands/ask.js.map +1 -1
  8. package/dist/cli/subcommands/verify.d.ts +1 -1
  9. package/dist/cli/subcommands/verify.js +90 -37
  10. package/dist/cli/subcommands/verify.js.map +1 -1
  11. package/dist/tui/ink/App.d.ts +10 -10
  12. package/dist/tui/ink/App.js +359 -237
  13. package/dist/tui/ink/App.js.map +1 -1
  14. package/dist/tui/ink/components/DenseToolMessage.d.ts +3 -2
  15. package/dist/tui/ink/components/DenseToolMessage.js +50 -30
  16. package/dist/tui/ink/components/DenseToolMessage.js.map +1 -1
  17. package/dist/tui/ink/components/InputBox.d.ts +4 -2
  18. package/dist/tui/ink/components/InputBox.js +66 -31
  19. package/dist/tui/ink/components/InputBox.js.map +1 -1
  20. package/dist/tui/ink/components/ThinkingBlock.d.ts +4 -5
  21. package/dist/tui/ink/components/ThinkingBlock.js +17 -3
  22. package/dist/tui/ink/components/ThinkingBlock.js.map +1 -1
  23. package/dist/tui/ink/components/ToolBox.d.ts +2 -2
  24. package/dist/tui/ink/components/ToolBox.js +49 -26
  25. package/dist/tui/ink/components/ToolBox.js.map +1 -1
  26. package/dist/tui/ink/components/ToolGroup.d.ts +2 -2
  27. package/dist/tui/ink/components/ToolGroup.js +44 -36
  28. package/dist/tui/ink/components/ToolGroup.js.map +1 -1
  29. package/dist/tui/ink/use-event-projection.d.ts +9 -9
  30. package/dist/tui/ink/use-event-projection.js +83 -37
  31. package/dist/tui/ink/use-event-projection.js.map +1 -1
  32. package/package.json +1 -1
package/dist/cli/main.js CHANGED
@@ -7,49 +7,49 @@
7
7
  * and stdin is a TTY, enter the interactive REPL. When stdin is piped,
8
8
  * read the prompt from stdin and run non-interactively.
9
9
  */
10
- import { argv, cwd, exit, stdin, stdout } from 'node:process';
11
- import { randomUUID } from 'node:crypto';
12
- import { createEventStream } from '../kernel/event-stream.js';
13
- import { runAgentLoop } from '../kernel/agent-loop.js';
14
- import { ProviderRegistry } from '../providers/index.js';
15
- import { builtInTools, createToolExecutor, createToolRegistry } from '../tools/index.js';
16
- import { loadConfig } from './config.js';
17
- import { parseFlags } from './flags.js';
18
- import { runInteractive } from './interactive.js';
19
- import { runInkTUI } from '../tui/ink/index.js';
20
- import { builtinSlashCommands } from './slash/index.js';
21
- import { renderStreamingEvents } from '../tui/renderer.js';
22
- import { createSessionStore } from '../context/session.js';
23
- import { runSubmitPaper } from './submit-paper.js';
24
- import { runLogin, runLogout, runSetup, findSubcommand } from './subcommands/index.js';
25
- import { appendAudit } from '../audit/writer.js';
26
- import { buildAgentHooksFromConfig } from '../hooks/config-bridge.js';
27
- import { hydrateEnvFromKeyStore } from '../auth/keystore.js';
28
- import { hydrateEnvFromPool } from '../auth/keypool.js';
29
- import { createExtensionAPI, loadExtensions } from '../extensions/api.js';
30
- import { createErrorClassifier } from '../intelligence/error-classifier.js';
31
- import { createCompactionTransform } from '../context/compaction.js';
32
- import { contextWindowFor, findPrice, findFailover, resolveModelAlias } from '../intelligence/prices.js';
33
- import { routeModel } from '../providers/dispatch.js';
34
- import { loadProjectPrimer, composeSystemPrompt } from '../context/primer.js';
35
- import { loadSoul } from '../context/soul.js';
36
- import { modePreamble, resolveMode, isAutoApprove } from '../context/mode.js';
37
- import { enforceMode, composeHooks } from '../context/mode-enforcement.js';
38
- import { loadSkills } from '../skills/loader.js';
39
- import { matchSkills } from '../skills/matcher.js';
40
- import { injectSkills } from '../skills/runtime.js';
41
- import { createRequire } from 'node:module';
10
+ import { argv, cwd, exit, stdin, stdout } from "node:process";
11
+ import { randomUUID } from "node:crypto";
12
+ import { createEventStream } from "../kernel/event-stream.js";
13
+ import { runAgentLoop } from "../kernel/agent-loop.js";
14
+ import { ProviderRegistry } from "../providers/index.js";
15
+ import { builtInTools, createToolExecutor, createToolRegistry, } from "../tools/index.js";
16
+ import { loadConfig } from "./config.js";
17
+ import { parseFlags } from "./flags.js";
18
+ import { runInteractive } from "./interactive.js";
19
+ import { runInkTUI } from "../tui/ink/index.js";
20
+ import { builtinSlashCommands } from "./slash/index.js";
21
+ import { renderStreamingEvents } from "../tui/renderer.js";
22
+ import { createSessionStore } from "../context/session.js";
23
+ import { runSubmitPaper } from "./submit-paper.js";
24
+ import { runLogin, runLogout, runSetup, findSubcommand, } from "./subcommands/index.js";
25
+ import { appendAudit } from "../audit/writer.js";
26
+ import { buildAgentHooksFromConfig } from "../hooks/config-bridge.js";
27
+ import { hydrateEnvFromKeyStore } from "../auth/keystore.js";
28
+ import { hydrateEnvFromPool } from "../auth/keypool.js";
29
+ import { createExtensionAPI, loadExtensions } from "../extensions/api.js";
30
+ import { createErrorClassifier } from "../intelligence/error-classifier.js";
31
+ import { createCompactionTransform } from "../context/compaction.js";
32
+ import { contextWindowFor, findPrice, findFailover, resolveModelAlias, } from "../intelligence/prices.js";
33
+ import { routeModel } from "../providers/dispatch.js";
34
+ import { loadProjectPrimer, composeSystemPrompt } from "../context/primer.js";
35
+ import { loadSoul } from "../context/soul.js";
36
+ import { modePreamble, resolveMode, isAutoApprove, } from "../context/mode.js";
37
+ import { enforceMode, composeHooks } from "../context/mode-enforcement.js";
38
+ import { loadSkills } from "../skills/loader.js";
39
+ import { matchSkills } from "../skills/matcher.js";
40
+ import { injectSkills } from "../skills/runtime.js";
41
+ import { createRequire } from "node:module";
42
42
  // `--version` / `-V` prints the package version and exits, matching every
43
43
  // other CLI on the planet. Without this, the flag-parser strips `--version`
44
44
  // as a generic boolean and falls through to the interactive REPL.
45
45
  const PKG_VERSION = (() => {
46
46
  try {
47
47
  const req = createRequire(import.meta.url);
48
- const pkg = req('../../package.json');
49
- return typeof pkg.version === 'string' ? pkg.version : '0.0.0-dev';
48
+ const pkg = req("../../package.json");
49
+ return typeof pkg.version === "string" ? pkg.version : "0.0.0-dev";
50
50
  }
51
51
  catch {
52
- return '0.0.0-dev';
52
+ return "0.0.0-dev";
53
53
  }
54
54
  })();
55
55
  async function main() {
@@ -75,58 +75,72 @@ async function main() {
75
75
  // Loading failures are non-fatal — the failing extension is named on
76
76
  // stderr and the rest of the CLI continues.
77
77
  const { api: extAPI, registry: extRegistry } = createExtensionAPI();
78
- const { join: pathJoin } = await import('node:path');
79
- const { homedir: hd } = await import('node:os');
80
- const extResult = await loadExtensions({ rootDir: pathJoin(hd(), '.dirgha', 'extensions'), api: extAPI });
78
+ const { join: pathJoin } = await import("node:path");
79
+ const { homedir: hd } = await import("node:os");
80
+ const extResult = await loadExtensions({
81
+ rootDir: pathJoin(hd(), ".dirgha", "extensions"),
82
+ api: extAPI,
83
+ });
81
84
  for (const f of extResult.failed) {
82
85
  process.stderr.write(`[extensions] ${f.name} failed to load: ${f.error.message}\n`);
83
86
  }
84
87
  void extRegistry; // surface for downstream wiring (slashes / tools / events)
85
88
  // Subcommand dispatch (positional 0 as verb).
86
- if (positionals[0] === 'submit-paper') {
89
+ if (positionals[0] === "submit-paper") {
87
90
  const doi = positionals[1];
88
91
  if (!doi) {
89
- stdout.write('usage: dirgha submit-paper <doi> [--open-pr]\n');
92
+ stdout.write("usage: dirgha submit-paper <doi> [--open-pr]\n");
90
93
  exit(1);
91
94
  }
92
- const code = await runSubmitPaper({ doi, openPr: flags['open-pr'] === true });
95
+ const code = await runSubmitPaper({
96
+ doi,
97
+ openPr: flags["open-pr"] === true,
98
+ });
93
99
  exit(code);
94
100
  }
95
101
  // Pass the RAW argv tail (includes flags like `--provider=...`) so
96
102
  // sub-flags survive the top-level parser, the same pattern as fleet.
97
- if (positionals[0] === 'login') {
103
+ if (positionals[0] === "login") {
98
104
  const rawArgs = argv.slice(2);
99
- const verbIdx = rawArgs.indexOf('login');
105
+ const verbIdx = rawArgs.indexOf("login");
100
106
  const tail = verbIdx >= 0 ? rawArgs.slice(verbIdx + 1) : positionals.slice(1);
101
107
  exit(await runLogin(tail));
102
108
  }
103
- if (positionals[0] === 'logout') {
109
+ if (positionals[0] === "logout") {
104
110
  const rawArgs = argv.slice(2);
105
- const verbIdx = rawArgs.indexOf('logout');
111
+ const verbIdx = rawArgs.indexOf("logout");
106
112
  const tail = verbIdx >= 0 ? rawArgs.slice(verbIdx + 1) : positionals.slice(1);
107
113
  exit(await runLogout(tail));
108
114
  }
109
- if (positionals[0] === 'setup')
115
+ if (positionals[0] === "setup")
110
116
  exit(await runSetup(positionals.slice(1)));
111
- if (positionals[0] === 'fleet') {
117
+ if (positionals[0] === "fleet") {
112
118
  // `dirgha fleet <launch|list|merge|discard|triple|cleanup>` —
113
119
  // parallel-agent orchestration in git worktrees. We pass the
114
120
  // RAW argv tail (positionals + flags) so the fleet dispatcher
115
121
  // can read its own subcommand-specific flags like --single,
116
122
  // --branch=<x>, --auto-merge, --strategy that the top-level
117
123
  // parser doesn't know about.
118
- const { fleetCommand } = await import('../fleet/cli-command.js');
124
+ const { fleetCommand } = await import("../fleet/cli-command.js");
119
125
  const config = await loadConfig(cwd());
120
126
  const rawArgs = argv.slice(2);
121
- const verbIdx = rawArgs.indexOf('fleet');
127
+ const verbIdx = rawArgs.indexOf("fleet");
122
128
  const tail = verbIdx >= 0 ? rawArgs.slice(verbIdx + 1) : positionals.slice(1);
123
129
  const code = await fleetCommand(tail, {
124
130
  cwd: cwd(),
125
- model: resolveModelAlias(typeof flags.model === 'string' ? flags.model : (typeof flags.m === 'string' ? flags.m : config.model)),
131
+ model: resolveModelAlias(typeof flags.model === "string"
132
+ ? flags.model
133
+ : typeof flags.m === "string"
134
+ ? flags.m
135
+ : config.model),
126
136
  json: flags.json === true,
127
137
  verbose: flags.verbose === true,
128
- maxTurns: typeof flags['max-turns'] === 'string' ? Number.parseInt(flags['max-turns'], 10) : config.maxTurns,
129
- concurrency: typeof flags.concurrency === 'string' ? Number.parseInt(flags.concurrency, 10) : undefined,
138
+ maxTurns: typeof flags["max-turns"] === "string"
139
+ ? Number.parseInt(flags["max-turns"], 10)
140
+ : config.maxTurns,
141
+ concurrency: typeof flags.concurrency === "string"
142
+ ? Number.parseInt(flags.concurrency, 10)
143
+ : undefined,
130
144
  });
131
145
  exit(code);
132
146
  }
@@ -153,23 +167,44 @@ async function main() {
153
167
  // sender's internal 8s budget keeps the request alive in case
154
168
  // Node's event loop survives long enough for it to flush.
155
169
  try {
156
- const { trackCommand } = await import('../telemetry/sender.js');
170
+ const { trackCommand } = await import("../telemetry/sender.js");
157
171
  await Promise.race([
158
172
  trackCommand(verb, PKG_VERSION),
159
- new Promise(r => setTimeout(r, 1000)),
173
+ new Promise((r) => setTimeout(r, 1000)),
160
174
  ]);
161
175
  }
162
- catch { /* telemetry must never affect the user's command */ }
176
+ catch {
177
+ /* telemetry must never affect the user's command */
178
+ }
163
179
  exit(code);
164
180
  }
165
181
  }
166
182
  const config = await loadConfig(cwd());
167
- const rawModel = (typeof flags.model === 'string' ? flags.model : (typeof flags.m === 'string' ? flags.m : config.model));
183
+ // CLI-level overrides for flags that affect interactive mode too.
184
+ // `--yolo` is the most surface-level form of "skip every approval",
185
+ // more discoverable than `DIRGHA_MODE=yolo`.
186
+ if (flags.yolo === true)
187
+ config.mode = "yolo";
188
+ if (typeof flags.mode === "string" &&
189
+ ["plan", "act", "yolo", "verify", "ask"].includes(flags.mode)) {
190
+ config.mode = flags.mode;
191
+ }
192
+ const rawModel = typeof flags.model === "string"
193
+ ? flags.model
194
+ : typeof flags.m === "string"
195
+ ? flags.m
196
+ : config.model;
168
197
  const model = resolveModelAlias(rawModel);
169
198
  const json = flags.json === true;
170
199
  const print = flags.print === true;
171
- const system = typeof flags.system === 'string' ? flags.system : (typeof flags.s === 'string' ? flags.s : undefined);
172
- const maxTurns = typeof flags['max-turns'] === 'string' ? Number.parseInt(flags['max-turns'], 10) : config.maxTurns;
200
+ const system = typeof flags.system === "string"
201
+ ? flags.system
202
+ : typeof flags.s === "string"
203
+ ? flags.s
204
+ : undefined;
205
+ const maxTurns = typeof flags["max-turns"] === "string"
206
+ ? Number.parseInt(flags["max-turns"], 10)
207
+ : config.maxTurns;
173
208
  const providers = new ProviderRegistry();
174
209
  const sessions = createSessionStore();
175
210
  // Load MCP servers from config and bridge their tools into the
@@ -179,32 +214,38 @@ async function main() {
179
214
  const allTools = [...builtInTools];
180
215
  let mcpShutdown = async () => { };
181
216
  if (config.mcpServers && Object.keys(config.mcpServers).length > 0) {
182
- const { loadMcpServers } = await import('../mcp/loader.js');
217
+ const { loadMcpServers } = await import("../mcp/loader.js");
183
218
  const mcp = await loadMcpServers(config.mcpServers, {
184
- onWarn: msg => { process.stderr.write(`warning: ${msg}\n`); },
219
+ onWarn: (msg) => {
220
+ process.stderr.write(`warning: ${msg}\n`);
221
+ },
185
222
  });
186
223
  allTools.push(...mcp.tools);
187
224
  mcpShutdown = mcp.shutdown;
188
225
  }
189
226
  const registry = createToolRegistry(allTools);
190
- process.once('exit', () => { void mcpShutdown(); });
191
- process.once('SIGINT', () => { void mcpShutdown().then(() => process.exit(130)); });
227
+ process.once("exit", () => {
228
+ void mcpShutdown();
229
+ });
230
+ process.once("SIGINT", () => {
231
+ void mcpShutdown().then(() => process.exit(130));
232
+ });
192
233
  // Subagent dispatch: register `task` so the model can spawn a fresh
193
234
  // agent for a sub-goal. Built lazily so the
194
235
  // delegator can capture the now-finalised registry + provider.
195
- const { SubagentDelegator } = await import('../subagents/delegator.js');
196
- const { createTaskTool } = await import('../tools/task.js');
236
+ const { SubagentDelegator } = await import("../subagents/delegator.js");
237
+ const { createTaskTool } = await import("../tools/task.js");
197
238
  // Provider is constructed below; capture via closure so the tool sees
198
239
  // the same one. Re-pulled fresh inside execute() so failover swaps work.
199
240
  const taskDelegatorRef = { current: null };
200
241
  registry.register(createTaskTool({
201
242
  delegate: async (req) => {
202
243
  if (!taskDelegatorRef.current)
203
- throw new Error('subagent delegator not yet initialised');
244
+ throw new Error("subagent delegator not yet initialised");
204
245
  return taskDelegatorRef.current.delegate(req);
205
246
  },
206
247
  }));
207
- let prompt = positionals.join(' ').trim();
248
+ let prompt = positionals.join(" ").trim();
208
249
  if (!prompt && !stdin.isTTY)
209
250
  prompt = (await readAllStdin()).trim();
210
251
  if (!prompt) {
@@ -215,8 +256,8 @@ async function main() {
215
256
  // First-run wizard: if the user has no BYOK keys saved AND no
216
257
  // hosted token, auto-launch the three-step setup flow. The wizard
217
258
  // itself prints CI-safe help when stdin is non-TTY.
218
- if (stdin.isTTY && await isFirstRun()) {
219
- const { runWizard } = await import('./flows/wizard.js');
259
+ if (stdin.isTTY && (await isFirstRun())) {
260
+ const { runWizard } = await import("./flows/wizard.js");
220
261
  const code = await runWizard([]);
221
262
  // If they completed setup, fall through into the REPL so they
222
263
  // can immediately use what they just configured. Otherwise exit.
@@ -232,22 +273,22 @@ async function main() {
232
273
  // TERM_PROGRAM=vscode and only use ink when one is present.
233
274
  // Override with DIRGHA_FORCE_INK=1 if the user knows their
234
275
  // console actually works.
235
- const explicitNoInk = process.env['DIRGHA_NO_INK'] === '1';
236
- const explicitForceInk = process.env['DIRGHA_FORCE_INK'] === '1';
237
- const onWindowsLegacy = process.platform === 'win32'
238
- && !process.env['WT_SESSION']
239
- && process.env['ConEmuANSI'] !== 'ON'
240
- && process.env['TERM_PROGRAM'] !== 'vscode';
276
+ const explicitNoInk = process.env["DIRGHA_NO_INK"] === "1";
277
+ const explicitForceInk = process.env["DIRGHA_FORCE_INK"] === "1";
278
+ const onWindowsLegacy = process.platform === "win32" &&
279
+ !process.env["WT_SESSION"] &&
280
+ process.env["ConEmuANSI"] !== "ON" &&
281
+ process.env["TERM_PROGRAM"] !== "vscode";
241
282
  const autoFallbackToReadline = onWindowsLegacy && !explicitForceInk;
242
283
  const useInk = !explicitNoInk && !autoFallbackToReadline && stdin.isTTY;
243
284
  if (autoFallbackToReadline && !explicitNoInk) {
244
285
  // Surface the swap so the user knows why the UI looks different.
245
- stdout.write('\x1b[33mNote:\x1b[0m Windows legacy console detected — using readline mode.\n'
246
- + ' For the full Ink TUI, run inside Windows Terminal, the VS Code terminal,\n'
247
- + ' or set \x1b[36mDIRGHA_FORCE_INK=1\x1b[0m to override.\n\n');
286
+ stdout.write("\x1b[33mNote:\x1b[0m Windows legacy console detected — using readline mode.\n" +
287
+ " For the full Ink TUI, run inside Windows Terminal, the VS Code terminal,\n" +
288
+ " or set \x1b[36mDIRGHA_FORCE_INK=1\x1b[0m to override.\n\n");
248
289
  }
249
290
  if (useInk) {
250
- const slashCommands = builtinSlashCommands.map(c => ({
291
+ const slashCommands = builtinSlashCommands.map((c) => ({
251
292
  name: c.name,
252
293
  description: c.description,
253
294
  ...(c.aliases !== undefined ? { aliases: c.aliases } : {}),
@@ -256,18 +297,35 @@ async function main() {
256
297
  // takes 1-2s during which nothing renders. Without this the user
257
298
  // sees a blank screen and assumes the app froze. The line is
258
299
  // overdrawn instantly when ink mounts.
259
- stdout.write('\n Launching dirgha…\n');
260
- await runInkTUI({ registry, providers, sessions, config, cwd: cwd(), systemPrompt: system, slashCommands });
300
+ stdout.write("\n Launching dirgha…\n");
301
+ await runInkTUI({
302
+ registry,
303
+ providers,
304
+ sessions,
305
+ config,
306
+ cwd: cwd(),
307
+ systemPrompt: system,
308
+ slashCommands,
309
+ });
261
310
  }
262
311
  else {
263
- await runInteractive({ registry, providers, sessions, config, cwd: cwd(), systemPrompt: system });
312
+ await runInteractive({
313
+ registry,
314
+ providers,
315
+ sessions,
316
+ config,
317
+ cwd: cwd(),
318
+ systemPrompt: system,
319
+ });
264
320
  }
265
321
  return;
266
322
  }
267
323
  const sessionId = randomUUID();
268
324
  const events = createEventStream();
269
325
  if (json) {
270
- events.subscribe(ev => { stdout.write(`${JSON.stringify(ev)}\n`); });
326
+ events.subscribe((ev) => {
327
+ stdout.write(`${JSON.stringify(ev)}\n`);
328
+ });
271
329
  }
272
330
  else {
273
331
  events.subscribe(renderStreamingEvents({ showThinking: config.showThinking }));
@@ -285,38 +343,46 @@ async function main() {
285
343
  const providerId = routeModel(model);
286
344
  const price = findPrice(providerId, model);
287
345
  const computeCost = (input, output, cached) => price
288
- ? (input / 1_000_000) * price.inputPerM + (output / 1_000_000) * price.outputPerM + (cached / 1_000_000) * (price.cachedInputPerM ?? 0)
346
+ ? (input / 1_000_000) * price.inputPerM +
347
+ (output / 1_000_000) * price.outputPerM +
348
+ (cached / 1_000_000) * (price.cachedInputPerM ?? 0)
289
349
  : 0;
290
350
  events.subscribe(async (ev) => {
291
351
  try {
292
- if (ev.type === 'usage') {
352
+ if (ev.type === "usage") {
293
353
  const cached = ev.cachedTokens ?? 0;
294
- await session.append({ type: 'usage', ts: sessionTs(), usage: {
354
+ await session.append({
355
+ type: "usage",
356
+ ts: sessionTs(),
357
+ usage: {
295
358
  inputTokens: ev.inputTokens,
296
359
  outputTokens: ev.outputTokens,
297
360
  cachedTokens: cached,
298
361
  costUsd: computeCost(ev.inputTokens, ev.outputTokens, cached),
299
- } });
362
+ },
363
+ });
300
364
  }
301
365
  }
302
- catch { /* never let persistence I/O break the run */ }
366
+ catch {
367
+ /* never let persistence I/O break the run */
368
+ }
303
369
  });
304
370
  // Audit writer: produce entries the `dirgha audit` reader can show.
305
371
  // Tool executions, errors, and end-of-turn are the high-signal ones.
306
- events.subscribe(ev => {
307
- if (ev.type === 'tool_exec_end') {
372
+ events.subscribe((ev) => {
373
+ if (ev.type === "tool_exec_end") {
308
374
  void appendAudit({
309
- kind: 'tool',
375
+ kind: "tool",
310
376
  actor: sessionId,
311
- summary: `${ev.id} ${ev.isError ? 'error' : 'done'} ${ev.durationMs}ms`,
377
+ summary: `${ev.id} ${ev.isError ? "error" : "done"} ${ev.durationMs}ms`,
312
378
  toolId: ev.id,
313
379
  isError: ev.isError,
314
380
  durationMs: ev.durationMs,
315
381
  });
316
382
  }
317
- else if (ev.type === 'agent_end') {
383
+ else if (ev.type === "agent_end") {
318
384
  void appendAudit({
319
- kind: 'turn-end',
385
+ kind: "turn-end",
320
386
  actor: sessionId,
321
387
  summary: `model=${model} stop=${ev.stopReason} in=${ev.usage.inputTokens} out=${ev.usage.outputTokens}`,
322
388
  model,
@@ -324,8 +390,12 @@ async function main() {
324
390
  usage: ev.usage,
325
391
  });
326
392
  }
327
- else if (ev.type === 'error') {
328
- void appendAudit({ kind: 'error', actor: sessionId, summary: ev.message });
393
+ else if (ev.type === "error") {
394
+ void appendAudit({
395
+ kind: "error",
396
+ actor: sessionId,
397
+ summary: ev.message,
398
+ });
329
399
  }
330
400
  });
331
401
  const executor = createToolExecutor({ registry, cwd: cwd(), sessionId });
@@ -339,8 +409,9 @@ async function main() {
339
409
  // surface-level form of "skip every approval", more discoverable
340
410
  // than `DIRGHA_MODE=yolo`.
341
411
  if (flags.yolo === true)
342
- mode = 'yolo';
343
- if (typeof flags.mode === 'string' && ['plan', 'act', 'yolo', 'verify', 'ask'].includes(flags.mode)) {
412
+ mode = "yolo";
413
+ if (typeof flags.mode === "string" &&
414
+ ["plan", "act", "yolo", "verify", "ask"].includes(flags.mode)) {
344
415
  mode = flags.mode;
345
416
  }
346
417
  const autoApprove = isAutoApprove(mode);
@@ -348,7 +419,7 @@ async function main() {
348
419
  // `audit list` can surface every dirgha invocation, not just turns.
349
420
  // Lives after mode-resolve so we can include it in the entry.
350
421
  void appendAudit({
351
- kind: 'session-start',
422
+ kind: "session-start",
352
423
  actor: sessionId,
353
424
  summary: `model=${model} mode=${mode} cwd=${cwd()}`,
354
425
  model,
@@ -368,18 +439,29 @@ async function main() {
368
439
  userSystem: system,
369
440
  });
370
441
  const messages = [];
371
- messages.push({ role: 'system', content: composedSystem });
372
- messages.push({ role: 'user', content: prompt });
442
+ messages.push({ role: "system", content: composedSystem });
443
+ messages.push({ role: "user", content: prompt });
373
444
  // Append the user prompt before the turn so a crash mid-stream still
374
445
  // leaves a recoverable transcript prefix.
375
- await session.append({ type: 'message', ts: sessionTs(), message: { role: 'user', content: prompt } });
376
- await session.append({ type: 'message', ts: sessionTs(), message: { role: 'system', content: composedSystem } });
446
+ await session.append({
447
+ type: "message",
448
+ ts: sessionTs(),
449
+ message: { role: "user", content: prompt },
450
+ });
451
+ await session.append({
452
+ type: "message",
453
+ ts: sessionTs(),
454
+ message: { role: "system", content: composedSystem },
455
+ });
377
456
  // Skills: load all available; inject the ones whose triggers match
378
457
  // this turn's user prompt. Project-local skills override user skills
379
458
  // when names collide (loadSkills handles that). Skill bodies are
380
459
  // injected as a synthetic user message before the live prompt.
381
460
  const allSkills = await loadSkills({ cwd: cwd() });
382
- const matched = matchSkills(allSkills, { platform: 'cli', userMessage: prompt });
461
+ const matched = matchSkills(allSkills, {
462
+ platform: "cli",
463
+ userMessage: prompt,
464
+ });
383
465
  // Provider construction can fail eagerly (e.g. ANTHROPIC_API_KEY
384
466
  // unset). When it does AND the user has a known failover model in
385
467
  // the registry, swap to that before we even reach the agent loop.
@@ -394,7 +476,14 @@ async function main() {
394
476
  if (!fallback)
395
477
  throw err;
396
478
  process.stderr.write(`\n[failover] ${model} → ${fallback} (${err instanceof Error ? err.message : String(err)})\n`);
397
- void appendAudit({ kind: 'failover', actor: sessionId, summary: `${model} → ${fallback}`, from: model, to: fallback, reason: err instanceof Error ? err.message : String(err) });
479
+ void appendAudit({
480
+ kind: "failover",
481
+ actor: sessionId,
482
+ summary: `${model} → ${fallback}`,
483
+ from: model,
484
+ to: fallback,
485
+ reason: err instanceof Error ? err.message : String(err),
486
+ });
398
487
  activeModel = fallback;
399
488
  provider = providers.forModel(fallback);
400
489
  }
@@ -422,7 +511,13 @@ async function main() {
422
511
  const after = r.tokensAfter.toLocaleString();
423
512
  const pct = Math.round((1 - r.tokensAfter / r.tokensBefore) * 100);
424
513
  process.stderr.write(`\n[compacted] ${before} → ${after} tokens (-${pct}%)\n`);
425
- void appendAudit({ kind: 'compaction', actor: sessionId, summary: `${before} → ${after} (-${pct}%)`, tokensBefore: r.tokensBefore, tokensAfter: r.tokensAfter });
514
+ void appendAudit({
515
+ kind: "compaction",
516
+ actor: sessionId,
517
+ summary: `${before} → ${after} (-${pct}%)`,
518
+ tokensBefore: r.tokensBefore,
519
+ tokensAfter: r.tokensAfter,
520
+ });
426
521
  },
427
522
  });
428
523
  // Compose: compact first, then inject skills before the live user
@@ -436,7 +531,7 @@ async function main() {
436
531
  const userHooks = buildAgentHooksFromConfig(config);
437
532
  const composedHooks = composeHooks(enforceMode(mode), userHooks);
438
533
  const errorClassifier = createErrorClassifier();
439
- let result = await runAgentLoop({
534
+ const result = await runAgentLoop({
440
535
  sessionId,
441
536
  model: activeModel,
442
537
  messages,
@@ -450,74 +545,56 @@ async function main() {
450
545
  autoApprove,
451
546
  ...(composedHooks !== undefined ? { hooks: composedHooks } : {}),
452
547
  });
453
- // Runtime failover: if the agent loop errored (5xx, timeout, etc.)
454
- // and we have a registered fallback for the active model, swap and
455
- // continue from the LAST PERSISTED HISTORY (not the original prompt)
456
- // so multi-turn work doesn't lose progress. Skipped when we already
457
- // failed over at construction time so we don't double-hop.
458
- if (result.stopReason === 'error' && activeModel === model) {
459
- const fallback = findFailover(activeModel);
460
- if (fallback) {
461
- try {
462
- const fallbackProvider = providers.forModel(fallback);
463
- process.stderr.write(`\n[failover] ${activeModel} → ${fallback} (mid-session at turn ${result.turnCount})\n`);
464
- void appendAudit({ kind: 'failover', actor: sessionId, summary: `${activeModel} → ${fallback} (turn ${result.turnCount})`, from: activeModel, to: fallback, turn: result.turnCount });
465
- result = await runAgentLoop({
466
- sessionId,
467
- model: fallback,
468
- // Resume from whatever messages survived — partial work isn't lost.
469
- messages: result.messages,
470
- tools: sanitized.definitions,
471
- maxTurns: Math.max(1, maxTurns - result.turnCount),
472
- provider: fallbackProvider,
473
- toolExecutor: executor,
474
- events,
475
- contextTransform: compactionTransform,
476
- errorClassifier,
477
- autoApprove,
478
- ...(composedHooks !== undefined ? { hooks: composedHooks } : {}),
479
- });
480
- }
481
- catch { /* swallow — original error already reported */ }
482
- }
548
+ // v1.15.0: no mid-session runtime failover — model switches during a
549
+ // running session cause confusion and inconsistent results. If the
550
+ // provider returns a transient error the agent loop surfaces it as a
551
+ // normal error and the caller can retry with a different model on the
552
+ // next invocation. Construction-time failover (missing API key) is
553
+ // still active because it never reaches the loop.
554
+ if (result.stopReason === "error") {
555
+ process.stderr.write(`\n[failed] ${activeModel} (turn ${result.turnCount})\n`);
483
556
  }
484
557
  // Persist every message produced by the turn (assistant turns + tool
485
558
  // results). Skip the user + system messages we already appended above.
486
559
  const initialCount = 2;
487
560
  for (const msg of result.messages.slice(initialCount)) {
488
561
  try {
489
- await session.append({ type: 'message', ts: sessionTs(), message: msg });
562
+ await session.append({ type: "message", ts: sessionTs(), message: msg });
563
+ }
564
+ catch {
565
+ /* swallow */
490
566
  }
491
- catch { /* swallow */ }
492
567
  }
493
568
  if (!json)
494
- stdout.write('\n');
495
- if (result.stopReason === 'error')
569
+ stdout.write("\n");
570
+ if (result.stopReason === "error")
496
571
  exit(2);
497
572
  }
498
573
  async function isFirstRun() {
499
- const { stat } = await import('node:fs/promises');
500
- const { homedir } = await import('node:os');
501
- const { join } = await import('node:path');
574
+ const { stat } = await import("node:fs/promises");
575
+ const { homedir } = await import("node:os");
576
+ const { join } = await import("node:path");
502
577
  const home = homedir();
503
578
  const candidates = [
504
- join(home, '.dirgha', 'keys.json'),
505
- join(home, '.dirgha', 'credentials.json'),
506
- join(home, '.dirgha', 'config.json'),
579
+ join(home, ".dirgha", "keys.json"),
580
+ join(home, ".dirgha", "credentials.json"),
581
+ join(home, ".dirgha", "config.json"),
507
582
  ];
508
583
  for (const p of candidates) {
509
- const exists = await stat(p).then(() => true).catch(() => false);
584
+ const exists = await stat(p)
585
+ .then(() => true)
586
+ .catch(() => false);
510
587
  if (exists)
511
588
  return false;
512
589
  }
513
590
  return true;
514
591
  }
515
592
  function readAllStdin() {
516
- return new Promise(resolve => {
593
+ return new Promise((resolve) => {
517
594
  const chunks = [];
518
- stdin.setEncoding('utf8');
519
- stdin.on('data', c => chunks.push(typeof c === 'string' ? c : c.toString('utf8')));
520
- stdin.on('end', () => resolve(chunks.join('')));
595
+ stdin.setEncoding("utf8");
596
+ stdin.on("data", (c) => chunks.push(typeof c === "string" ? c : c.toString("utf8")));
597
+ stdin.on("end", () => resolve(chunks.join("")));
521
598
  });
522
599
  }
523
600
  function printHelp() {
@@ -548,8 +625,8 @@ Subcommands:
548
625
  login / logout / setup Auth + first-run wizard
549
626
  update [--check] [--yes] Check for + install latest @dirgha/code
550
627
  telemetry <status|enable|...> Anonymous usage opt-in (default: OFF)
551
- scaffold "<prompt>" [--serve] Spin up a new project from a prompt
552
628
  submit-paper <doi> Fetch Crossref metadata, emit JSON
629
+ scaffold "<prompt>" [--serve] Spin up a new project from a prompt
553
630
 
554
631
  Options:
555
632
  -m, --model <id> Model id (default from config)