@mcoda/codali 0.1.135-codali.13 → 0.1.135-codali.18

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 (54) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/ORCHESTRATION.md +53 -0
  3. package/README.md +44 -5
  4. package/config/orchestration.schema.json +56 -0
  5. package/dist/cli/TerminalArtifacts.d.ts +5 -0
  6. package/dist/cli/TerminalArtifacts.d.ts.map +1 -0
  7. package/dist/cli/TerminalArtifacts.js +26 -0
  8. package/dist/cli/TerminalCommand.d.ts.map +1 -1
  9. package/dist/cli/TerminalCommand.js +363 -62
  10. package/dist/cli/TerminalInput.d.ts +7 -0
  11. package/dist/cli/TerminalInput.d.ts.map +1 -1
  12. package/dist/cli/TerminalInput.js +53 -7
  13. package/dist/cli/TerminalModels.d.ts +6 -0
  14. package/dist/cli/TerminalModels.d.ts.map +1 -0
  15. package/dist/cli/TerminalModels.js +45 -0
  16. package/dist/cli/TerminalPlan.d.ts +40 -0
  17. package/dist/cli/TerminalPlan.d.ts.map +1 -0
  18. package/dist/cli/TerminalPlan.js +37 -0
  19. package/dist/cli/tui/TerminalCells.d.ts +6 -0
  20. package/dist/cli/tui/TerminalCells.d.ts.map +1 -0
  21. package/dist/cli/tui/TerminalCells.js +47 -0
  22. package/dist/cli/tui/TerminalEditor.d.ts +22 -0
  23. package/dist/cli/tui/TerminalEditor.d.ts.map +1 -0
  24. package/dist/cli/tui/TerminalEditor.js +88 -0
  25. package/dist/cli/tui/TerminalPresentation.d.ts +4 -0
  26. package/dist/cli/tui/TerminalPresentation.d.ts.map +1 -0
  27. package/dist/cli/tui/TerminalPresentation.js +68 -0
  28. package/dist/cli/tui/TerminalScreen.d.ts +49 -0
  29. package/dist/cli/tui/TerminalScreen.d.ts.map +1 -0
  30. package/dist/cli/tui/TerminalScreen.js +130 -0
  31. package/dist/cli/tui/TerminalTui.d.ts +78 -0
  32. package/dist/cli/tui/TerminalTui.d.ts.map +1 -0
  33. package/dist/cli/tui/TerminalTui.js +469 -0
  34. package/dist/cli.d.ts.map +1 -1
  35. package/dist/cli.js +4 -2
  36. package/dist/config/OrchestrationConfig.d.ts +15 -0
  37. package/dist/config/OrchestrationConfig.d.ts.map +1 -1
  38. package/dist/config/OrchestrationConfig.js +19 -1
  39. package/dist/connectors/media/MediaJobStore.d.ts +2 -1
  40. package/dist/connectors/media/MediaJobStore.d.ts.map +1 -1
  41. package/dist/connectors/media/MediaJobStore.js +11 -3
  42. package/dist/runtime/InteractionRouter.d.ts +30 -0
  43. package/dist/runtime/InteractionRouter.d.ts.map +1 -0
  44. package/dist/runtime/InteractionRouter.js +53 -0
  45. package/dist/runtime/PreparedMemory.d.ts +3 -0
  46. package/dist/runtime/PreparedMemory.d.ts.map +1 -0
  47. package/dist/runtime/PreparedMemory.js +30 -0
  48. package/dist/runtime/SessionController.d.ts +27 -1
  49. package/dist/runtime/SessionController.d.ts.map +1 -1
  50. package/dist/runtime/SessionController.js +275 -33
  51. package/dist/session/SessionStore.d.ts +5 -1
  52. package/dist/session/SessionStore.d.ts.map +1 -1
  53. package/dist/session/SessionStore.js +11 -2
  54. package/package.json +4 -3
@@ -15,10 +15,15 @@ import { TerminalInput, insertTerminalPaste } from "./TerminalInput.js";
15
15
  import { ModelServiceError } from "../providers/ModelServiceError.js";
16
16
  import { discoverHostToolchain } from "../tools/shell/HostToolchain.js";
17
17
  import { ensureManagedDocdexRuntime, inspectManagedDocdexRuntime } from "../docdex/ManagedRuntime.js";
18
+ import { TerminalTui } from "./tui/TerminalTui.js";
19
+ import { inspectPlanDiff } from "./TerminalPlan.js";
20
+ import { openTerminalArtifact } from "./TerminalArtifacts.js";
21
+ import { mediaJobSummary } from "../connectors/media/ConfiguredMediaTools.js";
22
+ import { proposeTerminalModel, saveTerminalModel, terminalModelOperation } from "./TerminalModels.js";
18
23
  const DEFAULT_PROVIDER = { adapter: "mswarm", baseUrl: "https://api.mswarm.org/v1/swarm/self-hosted/openai", credentialRef: "env:MCODA_MSWARM_API_KEY" };
19
24
  const CONFIG_PATH = path.join(os.homedir(), ".codali", "orchestration.json");
20
- const COMMANDS = ["/help", "/usage", "/status", "/permissions", "/effort", "/models", "/config", "/goal", "/plan", "/tasks", "/decisions", "/context", "/diff", "/review", "/compact", "/checkpoint", "/sessions", "/resume", "/fork", "/retention", "/delete-session", "/new", "/steer", "/continue", "/cancel", "/reconcile", "/reconcile-media", "/export", "/artifacts", "/quit"];
21
- const HELP = `Codali terminal\n codali [chat] [prompt] [--workspace-root PATH] [--config PATH]\n codali exec PROMPT [--json] [--permissions plan|ask|workspace] [--effort low|medium|high|max]\n codali setup [--config PATH] [--docdex-binary PATH]\n codali login [--stdin] | logout | auth status\n codali sessions | resume SESSION_ID | status SESSION_ID\n\n${COMMANDS.join(" ")}\n\nCtrl-C cancels the active turn. A second Ctrl-C exits after cleanup.\nIn noninteractive mode approvals are denied; choose an explicit permission profile.\nProject tasks: mcoda codali chat --project-task TASK_KEY (existing workspace task database).\nExit codes: 0 verified completion, 1 error, 2 open/blocked goal, 130 cancelled.`;
25
+ const COMMANDS = ["/help", "/usage", "/status", "/permissions", "/effort", "/model", "/models", "/config", "/goal", "/plan", "/tasks", "/decisions", "/context", "/diff", "/tools", "/mcp", "/docdex", "/review", "/compact", "/checkpoint", "/sessions", "/resume", "/fork", "/retention", "/delete-session", "/new", "/clear", "/steer", "/continue", "/stop", "/cancel", "/reconcile", "/reconcile-media", "/export", "/artifacts", "/exit", "/quit"];
26
+ const HELP = `Codali terminal\n codali [chat] [prompt] [--workspace-root PATH] [--config PATH]\n codali exec PROMPT [--json] [--permissions plan|ask|workspace] [--effort low|medium|high|max]\n codali setup [--config PATH] [--docdex-binary PATH]\n codali login [--stdin] | logout | auth status\n codali sessions | resume SESSION_ID | status SESSION_ID\n\n${COMMANDS.join(" ")}\n\nInteractive terminals open the TUI; --plain selects line-oriented output.\nEnter sends/queues; Alt-Enter or Ctrl-J inserts a newline; Ctrl-S steers.\nCtrl-P commands; Ctrl-R history; Tab completes commands and @files.\nPage Up/Down scroll; Ctrl-O expands tools; Escape closes views or cancels.\nCtrl-C cancels the active turn. A second Ctrl-C exits after cleanup.\nIn noninteractive mode approvals are denied; choose an explicit permission profile.\nProject tasks: mcoda codali chat --project-task TASK_KEY (existing workspace task database).\nExit codes: 0 verified completion, 1 error, 2 open/blocked goal, 130 cancelled.`;
22
27
  export const parseTerminalArguments = (argv) => {
23
28
  const [command = "chat", ...input] = argv;
24
29
  const result = { command, prompt: "", workspaceRoot: process.cwd(), effort: "medium", permissions: "ask", json: false, plain: false, stdin: false };
@@ -34,7 +39,7 @@ export const parseTerminalArguments = (argv) => {
34
39
  result[flag.slice(2)] = true;
35
40
  continue;
36
41
  }
37
- if (["--workspace-root", "--config", "--docdex-binary", "--effort", "--permissions", "--project-task"].includes(flag)) {
42
+ if (["--workspace-root", "--config", "--file", "--docdex-binary", "--effort", "--permissions", "--permission-profile", "--output-format", "--project-task"].includes(flag)) {
38
43
  const value = input[++i];
39
44
  if (!value || value.startsWith("--"))
40
45
  throw new Error(`Missing value for ${flag}`);
@@ -42,6 +47,16 @@ export const parseTerminalArguments = (argv) => {
42
47
  result.workspaceRoot = path.resolve(value);
43
48
  if (flag === "--config")
44
49
  result.config = path.resolve(value);
50
+ if (flag === "--file") {
51
+ if (command !== "config")
52
+ throw new Error("--file is a config validate option");
53
+ result.config = path.resolve(value);
54
+ }
55
+ if (flag === "--output-format") {
56
+ if (!["jsonl", "text"].includes(value))
57
+ throw new Error("Expected --output-format jsonl or text");
58
+ result.json = value === "jsonl";
59
+ }
45
60
  if (flag === "--docdex-binary") {
46
61
  if (command !== "setup")
47
62
  throw new Error("--docdex-binary is a setup option");
@@ -54,7 +69,7 @@ export const parseTerminalArguments = (argv) => {
54
69
  throw new Error("Invalid effort level");
55
70
  result.effort = value;
56
71
  }
57
- if (flag === "--permissions") {
72
+ if (flag === "--permissions" || flag === "--permission-profile") {
58
73
  if (!["plan", "ask", "workspace"].includes(value))
59
74
  throw new Error("Invalid permission profile");
60
75
  result.permissions = value;
@@ -98,6 +113,12 @@ export const setupTerminalConfig = async (destination, options = {}) => {
98
113
  config.bindings.lead = { candidates: lead.map(entry => entry.id) };
99
114
  for (const role of ["architect", "worker", "reviewer", "planner", "compactor", "router", "adjudicator", "synthesizer", "verifier", "repair"])
100
115
  config.bindings[role] = { useBinding: "lead" };
116
+ // The evaluated local intent model is an explicit configurable binding.
117
+ const intent = catalog.filter(entry => entry.health === "healthy" && entry.id.endsWith("qwen3-4b-instruct-2507") && entry.operations.includes("chat.completions"));
118
+ for (const entry of intent)
119
+ config.models[entry.id] = { provider: "mswarm", catalogId: entry.id, revision: String(entry.raw.digest ?? entry.raw.revision ?? "catalog-unversioned"), operations: ["chat.completions"], backend: entry.backend, contextWindow: entry.contextWindow ?? 16384, maxOutputTokens: 1024, supportsTools: false, supportsStreaming: false };
120
+ config.bindings.intent = intent.length ? { candidates: [...intent.map(entry => entry.id), ...lead.map(entry => entry.id)] } : { useBinding: "lead" };
121
+ config.interaction = { routerBinding: "intent", answerBinding: "lead", promptVersion: "interaction-v8" };
101
122
  config.bindings.helper = { enabled: false };
102
123
  config.bindings.embedding = { enabled: false };
103
124
  // Only explicit operator contracts can initialize an index. Incompatible
@@ -209,7 +230,8 @@ export class TerminalCommand {
209
230
  await this.execute(argv, host);
210
231
  }
211
232
  catch (error) {
212
- if (!argv.includes("--json"))
233
+ const format = argv.lastIndexOf("--output-format");
234
+ if (!(argv.lastIndexOf("--json") > format || (format >= 0 && argv[format + 1] === "jsonl")))
213
235
  throw error;
214
236
  const message = redactSecretValues(error instanceof Error ? error.message : String(error));
215
237
  process.stdout.write(`${JSON.stringify({ schemaVersion: 1, type: "command_failed", data: { message, completed: false } })}\n`);
@@ -222,6 +244,8 @@ export class TerminalCommand {
222
244
  return;
223
245
  }
224
246
  const args = parseTerminalArguments(argv);
247
+ if (process.env.TERM === "dumb" || !process.stdout.isTTY)
248
+ args.plain = true;
225
249
  if (args.projectTask && !host.projectTaskAuthority)
226
250
  throw new Error("Use mcoda codali with --project-task to attach to the existing mcoda task repository");
227
251
  if (args.stdin && ["chat", "exec"].includes(args.command)) {
@@ -233,7 +257,12 @@ export class TerminalCommand {
233
257
  }
234
258
  args.prompt = [args.prompt, text.trim()].filter(Boolean).join("\n\n");
235
259
  }
236
- const output = (value) => { const text = redactSecretValues(typeof value === "string" ? value : JSON.stringify(value, null, args.json ? 0 : 2)); process.stdout.write(`${args.json ? text : terminalText(text)}\n`); };
260
+ let tui;
261
+ let outputTitle = "Details";
262
+ const output = (value) => { const text = redactSecretValues(typeof value === "string" ? value : JSON.stringify(value, null, args.json ? 0 : 2)); if (tui) {
263
+ tui.show(typeof value === "string" ? text : JSON.parse(text), outputTitle);
264
+ return;
265
+ } process.stdout.write(`${args.json ? text : terminalText(text)}\n`); };
237
266
  if (args.command === "login") {
238
267
  const key = await readTerminalCredential(args.stdin);
239
268
  if (!key)
@@ -262,7 +291,7 @@ export class TerminalCommand {
262
291
  }
263
292
  if (args.command === "setup") {
264
293
  const resolved = await setupTerminalConfig(args.config ?? process.env.CODALI_ORCHESTRATION_CONFIG ?? CONFIG_PATH, { prepareRuntime: () => ensureManagedDocdexRuntime({ binary: args.docdexBinary }) });
265
- const docdex = resolved.config.docdex ? { mode: "managed", ...resolved.config.docdex, initialization: "Private repository indexing starts with the first session" }
294
+ const docdex = resolved.config.docdex ? { mode: "managed", ...resolved.config.docdex, initialization: "Private repository indexing starts when execution needs it" }
266
295
  : { mode: "unavailable", reason: "No entitled embedding route advertises a pinned model and complete preprocessing contract" };
267
296
  output({ configuration: resolved.source, hash: resolved.hash, bindings: resolved.config.bindings, docdex });
268
297
  return;
@@ -271,18 +300,30 @@ export class TerminalCommand {
271
300
  output(await terminalDoctor(args.config));
272
301
  return;
273
302
  }
303
+ if (args.command === "config" && args.prompt !== "validate")
304
+ throw new Error("Usage: codali config validate --file PATH");
274
305
  let resolved = await loadOrchestrationConfig(args.config).catch(error => { throw new Error(`Cannot load orchestration configuration; run codali setup. ${error instanceof Error ? error.message : String(error)}`); });
275
- const interactive = args.command === "chat" && !!process.stdin.isTTY && !args.json;
306
+ if (args.command === "config") {
307
+ output({ valid: true, source: resolved.source, hash: resolved.hash });
308
+ return;
309
+ }
310
+ const interactive = ["chat", "resume"].includes(args.command) && !!process.stdin.isTTY && !args.json;
276
311
  let rl;
277
312
  let pendingApproval;
278
313
  let closed = false;
279
314
  let lastCtrlC = 0;
315
+ let cancelEpoch = 0;
280
316
  let activeRun;
317
+ let commandAbort;
281
318
  const queued = [];
282
319
  const approve = async (request, signal) => {
283
320
  if (!interactive || closed)
284
321
  return { allow: false };
285
- const reviewableArgs = JSON.stringify(request.args, (key, value) => /authorization|api[_-]?key|password|credential|secret|signature|token/i.test(key) ? "[redacted]" : value, 2);
322
+ const reviewableArgs = redactSecretValues(JSON.stringify(request.args, (key, value) => /authorization|api[_-]?key|password|credential|secret|signature|token/i.test(key) ? "[redacted]" : value, 2));
323
+ if (tui) {
324
+ const decision = await tui.approve(`Permission · ${request.tool}`, `${request.kind}\n\n${reviewableArgs}`, signal);
325
+ return { allow: decision !== "deny", scope: decision === "session" ? "session" : "once" };
326
+ }
286
327
  process.stderr.write(terminalText(`\nPermission: ${request.tool} (${request.kind})\n${reviewableArgs}\nAllow once, for this session, or deny? [once/session/deny]\n`));
287
328
  return new Promise(resolve => {
288
329
  const abort = () => { pendingApproval = undefined; resolve({ allow: false }); };
@@ -296,6 +337,10 @@ export class TerminalCommand {
296
337
  const controller = new SessionController({ workspaceRoot: await fs.realpath(args.workspaceRoot), resolved, effort: args.effort, permissions: args.permissions, approve, allowWeb: args.allowWeb, allowMemory: args.allowMemory, allowMedia: args.allowMedia, allowNetwork: args.allowNetwork,
297
338
  projectTaskKey: args.projectTask, projectTaskAuthority: host.projectTaskAuthority,
298
339
  onEvent: (event) => {
340
+ if (tui) {
341
+ tui.event(event);
342
+ return;
343
+ }
299
344
  if (args.json) {
300
345
  output(event);
301
346
  return;
@@ -318,24 +363,43 @@ export class TerminalCommand {
318
363
  process.stderr.write(`[Docdex: ${terminalText(String(event.data.status))}]\n`);
319
364
  },
320
365
  });
321
- const showPrompt = () => { if (!closed && !controller.busy && !pendingApproval) {
366
+ const cancelTurn = () => { cancelEpoch++; commandAbort?.abort(new Error("Cancelled by user")); controller.cancel(); };
367
+ const showPrompt = () => { if (tui) {
368
+ tui.update({ busy: !!activeRun || controller.busy, effort: controller.effort, permissions: controller.gate.profile, tokens: controller.usageSnapshot().tokens, queued: queued.length, session: controller.sessionId });
369
+ return;
370
+ } if (!closed && !controller.busy && !pendingApproval) {
322
371
  rl?.setPrompt("codali> ");
323
372
  rl?.prompt();
324
373
  } };
325
- const run = (prompt) => {
374
+ const run = (prompt, newSession = false, epoch = cancelEpoch) => {
375
+ if (closed || epoch !== cancelEpoch) {
376
+ showPrompt();
377
+ return;
378
+ }
379
+ tui?.update({ busy: true, activity: "Preparing turn", queued: queued.length });
326
380
  activeRun = (async () => {
327
381
  try {
328
- if (controller.state?.status === "completed" && prompt)
329
- await controller.start(prompt);
330
- const result = await controller.run(prompt);
331
- if (!args.json)
382
+ if (closed || epoch !== cancelEpoch)
383
+ return;
384
+ if (newSession && controller.sessionId)
385
+ await controller.clearSession();
386
+ if (closed || epoch !== cancelEpoch)
387
+ throw new Error("Cancelled by user before execution");
388
+ const result = prompt ? await controller.interact(prompt) : await controller.run();
389
+ if (tui)
390
+ tui.result(redactSecretValues(result.content));
391
+ else if (!args.json)
332
392
  output(`\n${result.content}`);
333
393
  if (!interactive)
334
- process.exitCode = result.completed || args.permissions === "plan" ? 0 : 2;
394
+ process.exitCode = result.completed || "mode" in result && result.mode !== "execute" || args.permissions === "plan" ? 0 : 2;
335
395
  }
336
396
  catch (error) {
337
397
  const message = redactSecretValues(error instanceof Error ? error.message : String(error));
338
- if (args.json)
398
+ if (tui) {
399
+ tui.error(message);
400
+ tui.update({ activity: "Turn stopped" });
401
+ }
402
+ else if (args.json)
339
403
  output({ schemaVersion: 1, type: "command_failed", sessionId: controller.sessionId, data: { message, completed: false } });
340
404
  else
341
405
  process.stderr.write(`${terminalText(message)}\n`);
@@ -345,33 +409,58 @@ export class TerminalCommand {
345
409
  finally {
346
410
  pendingApproval?.("deny");
347
411
  pendingApproval = undefined;
348
- activeRun = undefined;
349
412
  if (!closed && queued.length) {
350
413
  const next = queued.shift();
351
- await controller.steer(next);
352
- run();
414
+ const nextEpoch = cancelEpoch;
415
+ try {
416
+ if (next.steer && controller.state && controller.state.status !== "completed") {
417
+ await controller.steer(next.text);
418
+ activeRun = undefined;
419
+ run(undefined, false, nextEpoch);
420
+ }
421
+ else {
422
+ activeRun = undefined;
423
+ run(next.text, false, nextEpoch);
424
+ }
425
+ }
426
+ catch (error) {
427
+ activeRun = undefined;
428
+ const message = terminalText(error instanceof Error ? error.message : String(error));
429
+ if (tui)
430
+ tui.error(message);
431
+ else
432
+ process.stderr.write(`${message}\n`);
433
+ showPrompt();
434
+ }
353
435
  }
354
- else
436
+ else {
437
+ activeRun = undefined;
355
438
  showPrompt();
439
+ }
356
440
  }
357
441
  })();
358
442
  };
359
443
  const command = async (line) => {
444
+ const commandEpoch = cancelEpoch;
360
445
  const [name, ...parts] = line.trim().split(/\s+/);
361
446
  const value = parts.join(" ");
362
- if (name === "/cancel") {
363
- controller.cancel();
447
+ outputTitle = name.slice(1);
448
+ if (name === "/cancel" || name === "/stop") {
449
+ queued.length = 0;
450
+ cancelTurn();
364
451
  pendingApproval?.("deny");
365
452
  pendingApproval = undefined;
453
+ tui?.notice("Stopping the turn and clearing queued instructions; waiting for owned work to settle.");
366
454
  return;
367
455
  }
368
- if (name === "/quit") {
456
+ if (name === "/quit" || name === "/exit") {
369
457
  closed = true;
370
458
  queued.length = 0;
371
- controller.cancel();
459
+ cancelTurn();
372
460
  pendingApproval?.("deny");
373
461
  pendingApproval = undefined;
374
462
  rl?.close();
463
+ tui?.stop();
375
464
  return;
376
465
  }
377
466
  if (name === "/help")
@@ -380,7 +469,7 @@ export class TerminalCommand {
380
469
  output(controller.status());
381
470
  else if (name === "/usage") {
382
471
  const reconciliation = await controller.reconcileUsage();
383
- output({ session: controller.usageSnapshot(), reconciliation, server: await usageFor(resolved) });
472
+ output({ session: controller.usageSnapshot(), turn: controller.turnUsageSnapshot(), reconciliation, server: await usageFor(resolved) });
384
473
  }
385
474
  else if (name === "/permissions") {
386
475
  if (value === "clear")
@@ -408,39 +497,178 @@ export class TerminalCommand {
408
497
  await controller.reloadConfiguration(next);
409
498
  resolved = next;
410
499
  }
500
+ else if (parts[0] === "validate" || parts[0] === "diff") {
501
+ const file = parts.slice(1).join(" ");
502
+ if (!file)
503
+ throw new Error("Usage: /config validate|diff PATH");
504
+ const proposed = await loadOrchestrationConfig(path.resolve(file));
505
+ if (parts[0] === "validate")
506
+ output({ valid: true, source: proposed.source, hash: proposed.hash });
507
+ else {
508
+ const keys = new Set([...Object.keys(resolved.config), ...Object.keys(proposed.config)]);
509
+ output({ current: resolved.hash, proposed: proposed.hash, changes: [...keys].filter(key => JSON.stringify(resolved.config[key]) !== JSON.stringify(proposed.config[key])).map(key => ({ setting: key, before: resolved.config[key], after: proposed.config[key] })), activated: false });
510
+ }
511
+ return;
512
+ }
411
513
  else if (value)
412
- throw new Error("Usage: /config [reload]");
514
+ throw new Error("Usage: /config [reload|validate PATH|diff PATH]");
413
515
  output({ source: resolved.source, hash: resolved.hash, configuration: resolved.config });
414
516
  }
415
- else if (name === "/models")
416
- output(resolved.config.bindings);
417
- else if (name === "/goal")
418
- output(controller.state ? { original: controller.state.originalObjective, objective: controller.state.objective, requirements: controller.state.requirements, amendments: controller.state.amendments } : {});
419
- else if (name === "/tasks")
420
- output({ tasks: controller.state?.tasks ?? [], media: await controller.artifacts() });
421
- else if (name === "/plan")
422
- output({ revision: controller.state?.planRevision ?? 1, phases: controller.state?.phases ?? [], tasks: controller.state?.tasks ?? [], history: controller.state?.planHistory?.map(p => ({ revision: p.revision, goalRevision: p.goalRevision, at: p.at, reason: p.reason })) ?? [] });
517
+ else if (name === "/models" || name === "/model") {
518
+ if (!value)
519
+ output({ source: resolved.source, configHash: resolved.hash, bindings: resolved.config.bindings, models: resolved.config.models, select: "/model select BINDING MODEL_ID [--save] (shared configuration)" });
520
+ else {
521
+ if (name !== "/model" || parts[0] !== "select" || ![3, 4].includes(parts.length) || parts.length === 4 && parts[3] !== "--save")
522
+ throw new Error("Usage: /model select BINDING MODEL_ID [--save]. Preview first; --save changes the shared configuration for future turns and other consumers on reload.");
523
+ if (activeRun || controller.busy)
524
+ throw new Error("Change model bindings between turns");
525
+ const [, binding, modelId] = parts;
526
+ const proposed = proposeTerminalModel(resolved, binding, modelId);
527
+ const active = new AbortController();
528
+ commandAbort = active;
529
+ try {
530
+ const signal = AbortSignal.any([active.signal, AbortSignal.timeout(15000)]);
531
+ const selected = await new ConfiguredProvider(proposed, binding).select(terminalModelOperation(binding), signal, ["lead", "architect", "worker", "reviewer"].includes(binding));
532
+ signal.throwIfAborted();
533
+ if (commandEpoch !== cancelEpoch || closed)
534
+ throw new Error("Cancelled before saving model selection");
535
+ if (parts[3] === "--save") {
536
+ await saveTerminalModel(resolved, proposed, signal);
537
+ resolved = proposed;
538
+ try {
539
+ await controller.reloadConfiguration(proposed);
540
+ }
541
+ catch (error) {
542
+ closed = true;
543
+ queued.length = 0;
544
+ tui?.stop();
545
+ rl?.close();
546
+ throw new Error(`Configuration saved to ${proposed.source}, but session activation failed. Restart Codali before continuing. ${error instanceof Error ? error.message : String(error)}`);
547
+ }
548
+ }
549
+ output({ source: proposed.source, scope: "Shared configuration; other consumers apply it on reload", binding, modelId, backend: selected.actual.backend, health: selected.actual.health, configHash: proposed.hash, saved: parts[3] === "--save", activated: parts[3] === "--save", ...(parts[3] === "--save" ? {} : { apply: `/model select ${binding} ${modelId} --save` }) });
550
+ }
551
+ finally {
552
+ if (commandAbort === active)
553
+ commandAbort = undefined;
554
+ }
555
+ }
556
+ }
557
+ else if (name === "/goal") {
558
+ if (parts[0] === "amend") {
559
+ if (activeRun || controller.busy)
560
+ throw new Error("Use /steer TEXT during a turn or stop before amending the goal");
561
+ const instruction = parts.slice(1).join(" ");
562
+ if (!instruction)
563
+ throw new Error("Usage: /goal amend INSTRUCTION");
564
+ await controller.steer(instruction);
565
+ }
566
+ else if (value && value !== "show")
567
+ throw new Error("Usage: /goal [show|amend INSTRUCTION]");
568
+ output(controller.state ? { original: controller.state.originalObjective, objective: controller.state.objective, revision: controller.state.goalRevision, constraints: controller.state.constraints, nonGoals: controller.state.nonGoals, requirements: controller.state.requirements, amendments: controller.state.amendments } : {});
569
+ }
570
+ else if (name === "/tasks") {
571
+ if (!value)
572
+ output({ tasks: controller.state?.tasks ?? [], media: await controller.artifacts() });
573
+ else if (parts[0] === "media" && parts[1] && parts.length === 2)
574
+ output(mediaJobSummary(await controller.mediaStore().read(parts[1])));
575
+ else if (parts[0] === "cancel" && parts[1] && parts.length === 2)
576
+ output(mediaJobSummary(await controller.mediaStore().cancel(parts[1])));
577
+ else
578
+ throw new Error("Usage: /tasks [media JOB_ID|cancel JOB_ID]. Cancellation is a request until the media worker confirms it.");
579
+ }
580
+ else if (name === "/plan") {
581
+ if (parts[0] === "diff") {
582
+ if (!controller.state)
583
+ throw new Error("Start a goal before inspecting its plan");
584
+ if (parts.length > 3)
585
+ throw new Error("Usage: /plan diff [FROM [TO]]");
586
+ output(inspectPlanDiff(controller.state, parts[1] === undefined ? undefined : Number(parts[1]), parts[2] === undefined ? undefined : Number(parts[2])));
587
+ return;
588
+ }
589
+ else if (parts[0] === "mode") {
590
+ if (controller.busy)
591
+ throw new Error("Cancel the active turn before changing plan mode");
592
+ if (!["plan", "execute"].includes(parts[1]))
593
+ throw new Error("Usage: /plan mode plan|execute");
594
+ controller.gate.setProfile(parts[1] === "plan" ? "plan" : "ask");
595
+ }
596
+ else if (parts[0] === "edit") {
597
+ if (controller.busy)
598
+ throw new Error("Cancel the active turn before revising the plan");
599
+ const instruction = parts.slice(1).join(" ");
600
+ if (!instruction)
601
+ throw new Error("Usage: /plan edit INSTRUCTION");
602
+ if (!controller.state)
603
+ throw new Error("Start a goal before editing its plan");
604
+ controller.gate.setProfile("plan");
605
+ await controller.steer(`Revise the plan as requested: ${instruction}`);
606
+ run(undefined, false, commandEpoch);
607
+ return;
608
+ }
609
+ else if (value && !["show", "history"].includes(value))
610
+ throw new Error("Usage: /plan [show|history|diff [FROM [TO]]|edit INSTRUCTION|mode plan|execute]");
611
+ output({ revision: controller.state?.planRevision ?? 1, mode: controller.gate.profile === "plan" ? "plan" : "execute", phases: controller.state?.phases ?? [], tasks: controller.state?.tasks ?? [], history: controller.state?.planHistory?.map(p => ({ revision: p.revision, goalRevision: p.goalRevision, at: p.at, reason: p.reason })) ?? [] });
612
+ }
423
613
  else if (name === "/decisions")
424
614
  output(controller.state?.decisions ?? []);
425
615
  else if (name === "/context")
426
- output({ goal: controller.state, configHash: resolved.hash });
616
+ output({ conversation: controller.conversationSnapshot(), goal: controller.state, configHash: resolved.hash });
427
617
  else if (name === "/diff")
428
618
  output(await controller.diff());
619
+ else if (name === "/tools")
620
+ output(controller.registry.list().map(tool => ({ name: tool.name, description: tool.description })));
621
+ else if (name === "/mcp")
622
+ output({ connectors: controller.status().connectors, tools: controller.registry.list().filter(tool => tool.name.startsWith("mcp")).map(tool => ({ name: tool.name, description: tool.description })) });
623
+ else if (name === "/docdex")
624
+ output({ configuredRuntime: resolved.config.docdex, embedding: resolved.config.bindings.embedding, availableTools: controller.registry.list().filter(tool => tool.name.startsWith("docdex")).map(tool => tool.name), initialization: "Private repository indexing starts when execution needs it" });
429
625
  else if (name === "/sessions")
430
626
  output(await controller.store.listSessions());
431
- else if (name === "/artifacts")
432
- output(await controller.artifacts());
627
+ else if (name === "/artifacts") {
628
+ if (!value)
629
+ output(await controller.artifacts());
630
+ else if (parts[0] === "export" && parts[1] && parts.length >= 3) {
631
+ if (activeRun || controller.busy)
632
+ throw new Error("Stop and wait for the current turn before exporting an artifact");
633
+ output(await controller.exportArtifact(parts[1], parts.slice(2).join(" ")));
634
+ }
635
+ else if (parts[0] === "open" && parts[1] && parts.length === 2) {
636
+ const active = new AbortController();
637
+ commandAbort = active;
638
+ try {
639
+ output({ opened: await openTerminalArtifact(controller.mediaStore(), parts[1], active.signal) });
640
+ }
641
+ finally {
642
+ if (commandAbort === active)
643
+ commandAbort = undefined;
644
+ }
645
+ }
646
+ else
647
+ throw new Error("Usage: /artifacts [export JOB_ID PATH|open JOB_ID]");
648
+ }
649
+ else if (name === "/steer" && (activeRun || controller.busy)) {
650
+ if (!value)
651
+ throw new Error("Provide the correction");
652
+ queued.unshift({ text: value, steer: true });
653
+ cancelTurn();
654
+ tui?.notice("Cancelling the turn; steering will apply at the next safe checkpoint.");
655
+ }
433
656
  else if (name === "/retention") {
434
657
  const days = value ? Number(value) : 30;
435
658
  if (!Number.isFinite(days) || days < 0)
436
659
  throw new Error("Retention days must be nonnegative");
437
660
  output({ dryRun: true, days, candidates: (await controller.store.listSessions()).filter(s => s.status === "completed" && Date.parse(s.updatedAt) < Date.now() - days * 86400000).map(s => ({ id: s.sessionId, updatedAt: s.updatedAt })), action: "Use /delete-session ID to remove a reviewed session and its local artifacts" });
438
661
  }
439
- else if (controller.busy)
662
+ else if (activeRun || controller.busy)
440
663
  throw new Error("This command requires an idle turn; use /cancel or queue an instruction");
441
664
  else if (name === "/resume") {
442
665
  await controller.resume(value);
443
- output(controller.status());
666
+ if (tui) {
667
+ tui.restore((await controller.store.readTranscript(value)).map(item => item.data.event).filter(Boolean));
668
+ showPrompt();
669
+ }
670
+ else
671
+ output(controller.status());
444
672
  }
445
673
  else if (name === "/fork") {
446
674
  output({ sessionId: await controller.fork(), verification: "Fresh verification required; permissions were reset" });
@@ -449,11 +677,18 @@ export class TerminalCommand {
449
677
  await controller.deleteSession(value);
450
678
  output({ deleted: value });
451
679
  }
452
- else if (name === "/new") {
453
- if (!value)
454
- throw new Error("Provide the new objective");
455
- await controller.start(value);
456
- run();
680
+ else if (name === "/new" || name === "/clear") {
681
+ await controller.clearSession();
682
+ tui?.restore([]);
683
+ tui?.update({ activity: "Ready" });
684
+ if (value) {
685
+ tui?.user(value);
686
+ run(value, true, commandEpoch);
687
+ }
688
+ else if (tui)
689
+ tui.notice("Fresh session. Enter an objective to begin; previous sessions remain available through /sessions and /resume.");
690
+ else
691
+ output("Fresh session. Enter an objective to begin; previous sessions are preserved.");
457
692
  }
458
693
  else if (name === "/steer") {
459
694
  if (!value)
@@ -462,7 +697,7 @@ export class TerminalCommand {
462
697
  output(controller.state);
463
698
  }
464
699
  else if (name === "/continue")
465
- run();
700
+ run(undefined, false, commandEpoch);
466
701
  else if (name === "/checkpoint") {
467
702
  await controller.checkpoint(value || "User checkpoint");
468
703
  output("Checkpoint saved.");
@@ -475,7 +710,7 @@ export class TerminalCommand {
475
710
  if (!controller.state)
476
711
  throw new Error("No goal to review");
477
712
  await controller.steer("Review the current changes against the original goal and architecture decisions; fix concrete findings and reverify.");
478
- run();
713
+ run(undefined, false, commandEpoch);
479
714
  }
480
715
  else if (name === "/reconcile") {
481
716
  const [id, outcome, ...note] = parts;
@@ -498,11 +733,13 @@ export class TerminalCommand {
498
733
  else
499
734
  throw new Error(`Unknown command ${name}; use /help`);
500
735
  };
501
- const onSignal = () => { const now = Date.now(); if (!controller.busy || now - lastCtrlC < 1000) {
736
+ const onSignal = () => { const now = Date.now(); if ((!activeRun && !controller.busy) || now - lastCtrlC < 1000) {
502
737
  closed = true;
738
+ queued.length = 0;
503
739
  rl?.close();
504
- } lastCtrlC = now; controller.cancel(); pendingApproval?.("deny"); pendingApproval = undefined; };
505
- const onTerminate = () => { closed = true; queued.length = 0; controller.cancel(); pendingApproval?.("deny"); pendingApproval = undefined; rl?.close(); };
740
+ tui?.stop();
741
+ } lastCtrlC = now; cancelTurn(); pendingApproval?.("deny"); pendingApproval = undefined; };
742
+ const onTerminate = () => { closed = true; queued.length = 0; cancelTurn(); pendingApproval?.("deny"); pendingApproval = undefined; rl?.close(); tui?.stop(); };
506
743
  process.on("SIGINT", onSignal);
507
744
  process.on("SIGTERM", onTerminate);
508
745
  try {
@@ -517,7 +754,7 @@ export class TerminalCommand {
517
754
  await controller.checkpoint(rest.join(" "));
518
755
  else if (args.command === "amend")
519
756
  await controller.steer(rest.join(" "));
520
- else if (args.command === "resume") {
757
+ else if (args.command === "resume" && !interactive) {
521
758
  if (controller.state?.status === "completed")
522
759
  output(controller.status());
523
760
  else {
@@ -526,8 +763,12 @@ export class TerminalCommand {
526
763
  }
527
764
  return;
528
765
  }
529
- output(controller.status());
530
- return;
766
+ if (args.command === "resume" && interactive)
767
+ args.prompt = "";
768
+ else {
769
+ output(controller.status());
770
+ return;
771
+ }
531
772
  }
532
773
  if (!interactive) {
533
774
  if (!args.prompt)
@@ -536,7 +777,6 @@ export class TerminalCommand {
536
777
  await activeRun;
537
778
  return;
538
779
  }
539
- output(`Codali — ${resolved.config.profile}\nWorkspace: ${controller.workspaceRoot}\nUse /help for commands. Permissions: ${args.permissions}; effort: ${args.effort}.`);
540
780
  const historyFile = path.join(path.dirname(controller.store.storageDir), "terminal-history.json");
541
781
  let history = [];
542
782
  try {
@@ -545,6 +785,63 @@ export class TerminalCommand {
545
785
  history = value.filter(v => typeof v === "string").slice(0, 500);
546
786
  }
547
787
  catch { /* First terminal session has no history. */ }
788
+ if (!args.plain && process.stdout.isTTY && process.env.TERM !== "dumb") {
789
+ let chain = Promise.resolve();
790
+ const descriptions = { help: "Commands and keyboard shortcuts", status: "Workspace and current task", usage: "Usage and account limits", permissions: "Permission policy and grants", effort: "Model effort budget", models: "Configured model routes", config: "Inspect or reload configuration", goal: "Goal and requirements", plan: "Plan and dependencies", tasks: "Tasks, progress and media jobs", decisions: "Architecture decisions", context: "Retained task context", diff: "Inspect actual workspace changes", review: "Review and verify changes", sessions: "Saved sessions", artifacts: "Generated media and files", compact: "Compact context safely", checkpoint: "Save a checkpoint", continue: "Continue the current task", cancel: "Cancel the active turn", quit: "Close Codali" };
791
+ const packageInfo = JSON.parse(await fs.readFile(new URL("../../package.json", import.meta.url), "utf8"));
792
+ tui = new TerminalTui({ workspace: controller.workspaceRoot, profile: resolved.config.profile, version: packageInfo.version, effort: args.effort, permissions: args.permissions, history,
793
+ commands: COMMANDS.map(name => ({ name, description: descriptions[name.slice(1)] ?? name.slice(1).replace(/-/g, " ") })),
794
+ cancel: onSignal, close: onTerminate,
795
+ submit: (line, intent) => {
796
+ if (/^\/(stop|cancel|exit|quit)\s*$/.test(line)) {
797
+ void command(line).then(showPrompt).catch(error => tui.error(String(error)));
798
+ return;
799
+ }
800
+ const inputEpoch = cancelEpoch;
801
+ chain = chain.then(async () => {
802
+ if (closed || inputEpoch !== cancelEpoch)
803
+ return;
804
+ if (line.startsWith("/") && !/[\r\n]/.test(line)) {
805
+ await command(line);
806
+ showPrompt();
807
+ return;
808
+ }
809
+ tui.user(line);
810
+ if (activeRun || controller.busy) {
811
+ if (intent === "steer") {
812
+ queued.unshift({ text: line, steer: true });
813
+ cancelTurn();
814
+ tui.notice("Cancelling the turn; steering will apply at the next safe checkpoint.");
815
+ }
816
+ else {
817
+ queued.push({ text: line });
818
+ tui.notice("Message queued for the next turn.");
819
+ }
820
+ }
821
+ else
822
+ run(line, false, inputEpoch);
823
+ showPrompt();
824
+ }).catch(error => tui.error(redactSecretValues(error instanceof Error ? error.message : String(error))));
825
+ }
826
+ });
827
+ tui.start();
828
+ if (controller.sessionId) {
829
+ tui.restore((await controller.store.readTranscript(controller.sessionId)).map(item => item.data.event).filter(Boolean));
830
+ showPrompt();
831
+ }
832
+ if (args.prompt) {
833
+ tui.user(args.prompt);
834
+ run(args.prompt);
835
+ }
836
+ await tui.wait();
837
+ closed = true;
838
+ cancelTurn();
839
+ await chain;
840
+ await activeRun;
841
+ await atomicWriteJson(historyFile, tui.editor.history.map(value => redactSecretValues(value)));
842
+ return;
843
+ }
844
+ output(`Codali — ${resolved.config.profile}\nWorkspace: ${controller.workspaceRoot}\nUse /help for commands. Permissions: ${args.permissions}; effort: ${args.effort}.`);
548
845
  const pasteInput = args.plain ? undefined : new TerminalInput({ onPaste: text => { if (rl)
549
846
  insertTerminalPaste(rl, text); }, onRejected: message => { process.stderr.write(`${message}\n`); showPrompt(); } });
550
847
  const input = pasteInput ? Object.assign(pasteInput, { isTTY: process.stdin.isTTY, setRawMode: (mode) => process.stdin.setRawMode(mode) }) : process.stdin;
@@ -557,7 +854,14 @@ export class TerminalCommand {
557
854
  rl.on("SIGINT", onSignal);
558
855
  let chain = Promise.resolve();
559
856
  rl.on("line", line => {
857
+ if (/^\/(stop|cancel|exit|quit)\s*$/.test(line)) {
858
+ void command(line).then(showPrompt).catch(error => process.stderr.write(`${terminalText(String(error))}\n`));
859
+ return;
860
+ }
861
+ const inputEpoch = cancelEpoch;
560
862
  chain = chain.then(async () => {
863
+ if (closed || inputEpoch !== cancelEpoch)
864
+ return;
561
865
  if (pendingApproval) {
562
866
  const response = line.trim().toLowerCase();
563
867
  if (!["once", "session", "deny"].includes(response)) {
@@ -577,16 +881,12 @@ export class TerminalCommand {
577
881
  await command(line);
578
882
  showPrompt();
579
883
  }
580
- else if (controller.busy) {
581
- queued.push(line);
884
+ else if (activeRun || controller.busy) {
885
+ queued.push({ text: line });
582
886
  output("Instruction queued for the next turn. Use /cancel to interrupt first.");
583
887
  }
584
- else if (controller.state && controller.state.status !== "completed") {
585
- await controller.steer(line);
586
- run();
587
- }
588
888
  else
589
- run(line);
889
+ run(line, false, inputEpoch);
590
890
  }).catch(error => { process.stderr.write(`${terminalText(error instanceof Error ? error.message : String(error))}\n`); showPrompt(); });
591
891
  });
592
892
  if (args.prompt)
@@ -595,7 +895,7 @@ export class TerminalCommand {
595
895
  showPrompt();
596
896
  await new Promise(resolve => rl.once("close", () => {
597
897
  closed = true;
598
- controller.cancel();
898
+ cancelTurn();
599
899
  pendingApproval?.("deny");
600
900
  pendingApproval = undefined;
601
901
  if (pasteInput) {
@@ -613,6 +913,7 @@ export class TerminalCommand {
613
913
  process.off("SIGINT", onSignal);
614
914
  process.off("SIGTERM", onTerminate);
615
915
  rl?.close();
916
+ tui?.stop();
616
917
  }
617
918
  }
618
919
  }