@cavelon/cli 0.1.4 → 0.1.6

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 (50) hide show
  1. package/README.md +58 -22
  2. package/dist/choose.js +8 -4
  3. package/dist/code-hints.js +74 -0
  4. package/dist/commands/api.js +83 -44
  5. package/dist/commands/async.js +26 -5
  6. package/dist/commands/chat.js +177 -0
  7. package/dist/commands/docs.js +240 -37
  8. package/dist/commands/fmt.js +120 -0
  9. package/dist/commands/index.js +9 -1
  10. package/dist/commands/init.js +64 -30
  11. package/dist/commands/inventory.js +48 -5
  12. package/dist/commands/limits-set.js +9 -6
  13. package/dist/commands/loops.js +15 -9
  14. package/dist/commands/models.js +16 -7
  15. package/dist/commands/sandboxes.js +8 -4
  16. package/dist/commands/schema.js +361 -0
  17. package/dist/commands/session.js +148 -24
  18. package/dist/commands/setup.js +22 -6
  19. package/dist/commands/solution.js +537 -76
  20. package/dist/commands/tenants.js +156 -15
  21. package/dist/commands/values.js +18 -9
  22. package/dist/commands/work.js +343 -35
  23. package/dist/confirm-token.js +72 -0
  24. package/dist/contracts.js +3 -0
  25. package/dist/default-route.js +21 -0
  26. package/dist/errors.js +4 -0
  27. package/dist/git.js +14 -5
  28. package/dist/harness-ref.js +14 -1
  29. package/dist/http.js +27 -4
  30. package/dist/invoke.js +8 -4
  31. package/dist/kit-codes.js +91 -0
  32. package/dist/limits.js +12 -1
  33. package/dist/local-state.js +32 -7
  34. package/dist/main.js +52 -4
  35. package/dist/mcp.js +72 -15
  36. package/dist/openapi.js +77 -21
  37. package/dist/operations.js +4 -3
  38. package/dist/package-check.js +361 -12
  39. package/dist/package-files.js +92 -45
  40. package/dist/package-format.js +222 -0
  41. package/dist/package-references.js +298 -0
  42. package/dist/preview-report.js +152 -0
  43. package/dist/results.js +21 -1
  44. package/dist/skills/cavelon-authoring/SKILL.md +98 -13
  45. package/dist/skills/cavelon-long-running/SKILL.md +3 -1
  46. package/dist/skills/cavelon-loop/SKILL.md +129 -21
  47. package/dist/skills/cavelon-testing/SKILL.md +130 -10
  48. package/dist/tenant-choice.js +31 -5
  49. package/dist/trace-view.js +172 -0
  50. package/package.json +1 -1
@@ -2,13 +2,16 @@ import { promises as fs } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { boolOption, CURSOR_OPTION, intOption, LIMIT_OPTION, listOption, pageOf, positional, stringOption, } from "../command.js";
4
4
  import { capacityCodeIn, capacityHint, noteLines, runCapacityNote } from "../capacity.js";
5
+ import { assertionCount, assertionLine, retrievalRows, retrievalView, spanAttributes, stepAssertions, suggestedSpan } from "../trace-view.js";
5
6
  import { CavelonError, ExitCode, usageError } from "../errors.js";
7
+ import { confirmation } from "../confirm-token.js";
6
8
  import { confinedPath } from "../paths.js";
7
9
  import { clip, keyValues, moreHint, table } from "../format.js";
8
- import { callStable } from "../invoke.js";
10
+ import { callStable, workflowOperation } from "../invoke.js";
11
+ import { deref } from "../openapi.js";
9
12
  import { bindsNow, changedBy, limitError, limitsOrWarn, readLimits } from "../limits.js";
10
13
  import { getOperation } from "../operations.js";
11
- import { caseCounts, caseLabel, countsText, failedCase, NOT_PASSED, runVerdict } from "../results.js";
14
+ import { caseCounts, caseLabel, countsText, failedCase, caseKnowledgeOutcomes, NOT_PASSED, runVerdict } from "../results.js";
12
15
  import { isUuid } from "../session.js";
13
16
  import { cavelonCommand, shellWord } from "../shell.js";
14
17
  import { readZipSummary, ZipError } from "../zip.js";
@@ -16,6 +19,137 @@ import { TIMEOUT_OPTION, timeoutMs, waitAndReport } from "./async.js";
16
19
  import { stageErrors, stageErrorText } from "./loops.js";
17
20
  import { resolveHarnessId } from "../harness-ref.js";
18
21
  const WAIT_OPTION = { type: "boolean", description: "Wait for the work to finish (see `cavelon wait`).", cliOnly: true };
22
+ const fileCount = (n) => `${n} file${n === 1 ? "" : "s"}`;
23
+ function uploadOutcomeOf(d, before) {
24
+ if (typeof d.upload_outcome === "string" && d.upload_outcome)
25
+ return d.upload_outcome;
26
+ return before.has(d.id) ? "deduplicated" : null;
27
+ }
28
+ async function refreshStatuses(ctx, kbId, documents) {
29
+ try {
30
+ const list = await callStable(ctx, "GET", DOCUMENTS_ROUTE, "listing a knowledge base's documents", { params: { kb_id: [kbId] } });
31
+ const byId = new Map((Array.isArray(list) ? list : []).map((d) => [d.id, d]));
32
+ for (const d of documents) {
33
+ const status = byId.get(d.id)?.status;
34
+ if (typeof status === "string" && status)
35
+ d.status = status;
36
+ }
37
+ }
38
+ catch (error) {
39
+ if (!(error instanceof CavelonError))
40
+ throw error;
41
+ ctx.warn(`Could not read the documents' statuses after the wait (${error.message}); the operations above say how ingestion ended.`);
42
+ }
43
+ }
44
+ const UPLOAD_ROUTE = "/api/v1/knowledge-bases/{kb_id}/documents/upload";
45
+ const DOCUMENTS_ROUTE = "/api/v1/knowledge-bases/{kb_id}/documents";
46
+ const ACTIVE_ROUTE = "/api/v1/knowledge-bases/{kb_id}/documents/active";
47
+ function replaceSupport(doc, op) {
48
+ const schema = op.requestBody?.content?.["multipart/form-data"]?.schema;
49
+ const properties = doc && schema ? deref(doc, schema)?.properties : undefined;
50
+ return { byIds: Boolean(properties?.replace_doc_ids), byName: Boolean(properties?.replace_existing) };
51
+ }
52
+ const shortId = (id) => `${id.slice(0, 8)}…`;
53
+ async function existingDocuments(ctx, kbId) {
54
+ try {
55
+ const list = await callStable(ctx, "GET", DOCUMENTS_ROUTE, "listing a knowledge base's documents", { params: { kb_id: [kbId] } });
56
+ return (Array.isArray(list) ? list : []).filter((d) => d.is_active !== false && typeof d.filename === "string");
57
+ }
58
+ catch (error) {
59
+ if (!(error instanceof CavelonError))
60
+ throw error;
61
+ ctx.warn(`Could not list the knowledge base's documents (${error.message}); files named like an existing document are not reported.`);
62
+ return undefined;
63
+ }
64
+ }
65
+ function nameMatches(files, cwd, existing, mode, support) {
66
+ const matches = [];
67
+ const mapped = new Set();
68
+ for (const file of files) {
69
+ const filename = path.basename(file);
70
+ const same = existing.filter((d) => d.filename === filename).sort((a, b) => (b.created_at ?? "").localeCompare(a.created_at ?? ""));
71
+ same.forEach((document, index) => {
72
+ let plan = "stays_active";
73
+ if (mode === "default" && support.byName)
74
+ plan = "replaced_by_name";
75
+ if (mode === "replace")
76
+ plan = index === 0 && support.byIds && !mapped.has(filename) ? "replace_by_id" : "deactivate";
77
+ matches.push({ file: path.relative(cwd, file) || file, filename, document_id: document.id, plan });
78
+ });
79
+ mapped.add(filename);
80
+ }
81
+ return matches;
82
+ }
83
+ function plannedLine(match) {
84
+ const head = `${match.filename} exists (${shortId(match.document_id)})`;
85
+ switch (match.plan) {
86
+ case "stays_active":
87
+ return `${head} and stays active`;
88
+ case "replaced_by_name":
89
+ return `${head} and is replaced by the upload (--keep-both keeps it)`;
90
+ case "replace_by_id":
91
+ return `${head} and is replaced once the new file is verified`;
92
+ case "deactivate":
93
+ return `${head} and is deactivated after the upload`;
94
+ }
95
+ }
96
+ function outcomeLine(match) {
97
+ const head = `${match.filename} exists (${shortId(match.document_id)})`;
98
+ switch (match.outcome) {
99
+ case "replaced":
100
+ return `${head}: replaced`;
101
+ case "replace_requested":
102
+ return `${head}: replaced once the new file is verified`;
103
+ case "deactivated":
104
+ return `${head}: deactivated`;
105
+ case "not_uploaded":
106
+ return `${head} and stays active: its new version was not uploaded`;
107
+ default:
108
+ return `${head} and stays active`;
109
+ }
110
+ }
111
+ function staysActiveHint(matches, mode) {
112
+ return mode === "default" && matches.some((m) => (m.outcome ?? m.plan) === "stays_active")
113
+ ? "Both versions answer. --replace replaces the existing document; --keep-both keeps both without this note."
114
+ : "";
115
+ }
116
+ function settleMatches(matches, uploaded, uploadedFiles) {
117
+ const reported = uploaded.some((d) => Array.isArray(d.replaced_document_ids));
118
+ const replaced = new Set(uploaded.flatMap((d) => (Array.isArray(d.replaced_document_ids) ? d.replaced_document_ids : [])));
119
+ for (const match of matches) {
120
+ if (!uploadedFiles.has(match.file))
121
+ match.outcome = "not_uploaded";
122
+ else if (replaced.has(match.document_id))
123
+ match.outcome = "replaced";
124
+ else if (match.plan === "replace_by_id" && !reported)
125
+ match.outcome = "replace_requested";
126
+ else if (match.plan === "deactivate")
127
+ match.outcome = undefined;
128
+ else
129
+ match.outcome = "stays_active";
130
+ }
131
+ }
132
+ async function deactivate(ctx, kbId, matches) {
133
+ const due = matches.filter((m) => m.plan === "deactivate" && m.outcome === undefined);
134
+ if (!due.length)
135
+ return undefined;
136
+ try {
137
+ await callStable(ctx, "PATCH", ACTIVE_ROUTE, "deactivating a document", {
138
+ params: { kb_id: [kbId] },
139
+ body: { updates: due.map((m) => ({ id: m.document_id, is_active: false })) },
140
+ });
141
+ for (const m of due)
142
+ m.outcome = "deactivated";
143
+ return undefined;
144
+ }
145
+ catch (error) {
146
+ if (!(error instanceof CavelonError))
147
+ throw error;
148
+ for (const m of due)
149
+ m.outcome = "stays_active";
150
+ return error;
151
+ }
152
+ }
19
153
  async function resolveKbId(ctx, ref) {
20
154
  if (isUuid(ref))
21
155
  return { id: ref };
@@ -240,7 +374,11 @@ export const kbUpload = {
240
374
  summary: "Upload a folder's documents into a knowledge base; returns operation ids.",
241
375
  description: "Hidden files are skipped. Ingestion runs on the instance; `cavelon wait` follows it.\n" +
242
376
  "Files are checked against the instance's published upload limits first. A .zip goes only to a tenant that expands\n" +
243
- "archives, and only within its caps on file count, unpacked size and compression ratio.",
377
+ "archives, and only within its caps on file count, unpacked size and compression ratio.\n" +
378
+ "A file named like an active document of the knowledge base is listed, with what happens to that document. An\n" +
379
+ "instance that replaces same-named documents on upload does so (--keep-both keeps both); elsewhere the old one stays\n" +
380
+ "active. --replace replaces it: through the instance's own replacement where its upload offers one, else the kit\n" +
381
+ "deactivates the old document after the upload (after the wait with --wait), and then only with --confirm.",
244
382
  readOnly: false,
245
383
  mcpTool: "kb_upload",
246
384
  positionals: [{ name: "dir", description: "Folder (or single file) to upload.", required: true }],
@@ -248,16 +386,27 @@ export const kbUpload = {
248
386
  kb: { type: "string", value: "<kb>", description: "Knowledge base name or id (required)." },
249
387
  recursive: { type: "boolean", short: "r", description: "Include subfolders." },
250
388
  ext: { type: "string", multiple: true, value: "<ext>", description: "Only these file extensions (pdf, md, …)." },
251
- "dry-run": { type: "boolean", description: "List what would be uploaded, upload nothing." },
389
+ replace: { type: "boolean", description: "Replace active documents with the same file name." },
390
+ "keep-both": { type: "boolean", description: "Keep active documents with the same file name next to the new ones." },
391
+ confirm: { type: "boolean", mcpToken: true, description: "With --replace, deactivate the old documents the instance does not replace itself; without it nothing is sent." },
392
+ "dry-run": { type: "boolean", description: "List what would be uploaded and replaced, upload nothing." },
252
393
  wait: WAIT_OPTION,
253
394
  timeout: TIMEOUT_OPTION,
254
395
  },
255
- examples: ["cavelon kb upload ./docs --kb FAQ", "cavelon kb upload ./manuals --kb FAQ -r --ext pdf --wait --timeout 5m"],
396
+ examples: [
397
+ "cavelon kb upload ./docs --kb FAQ",
398
+ "cavelon kb upload ./docs/bergbahn-faq.md --kb FAQ --replace --dry-run",
399
+ "cavelon kb upload ./manuals --kb FAQ -r --ext pdf --wait --timeout 5m",
400
+ ],
256
401
  async run(ctx, input) {
257
- const dir = await confinedPath(ctx, positional(input, "dir"), "The folder");
402
+ const dirArg = positional(input, "dir");
403
+ const dir = await confinedPath(ctx, dirArg, "The folder");
258
404
  const kbRef = stringOption(input, "kb");
259
405
  if (!kbRef)
260
406
  throw usageError("Which knowledge base?", "Pass --kb <name-or-id>.");
407
+ const mode = boolOption(input, "replace") ? "replace" : boolOption(input, "keep-both") ? "keep-both" : "default";
408
+ if (mode === "replace" && boolOption(input, "keep-both"))
409
+ throw usageError("--replace and --keep-both exclude each other.");
261
410
  const extensions = listOption(input, "ext").flatMap((e) => e.split(",")).map((e) => e.replace(/^\./, "").toLowerCase()).filter(Boolean);
262
411
  let stat;
263
412
  try {
@@ -275,11 +424,41 @@ export const kbUpload = {
275
424
  if (found.refusals.length)
276
425
  throw refusalError(found, files.length);
277
426
  }
427
+ const kb = await resolveKbId(ctx, kbRef);
428
+ const { doc, op } = await workflowOperation(ctx, "POST", UPLOAD_ROUTE, "document upload");
429
+ const support = replaceSupport(doc, op);
430
+ const existing = await existingDocuments(ctx, kb.id);
431
+ const matches = existing ? nameMatches(files, ctx.io.cwd, existing, mode, support) : [];
432
+ const rel = files.map((f) => path.relative(ctx.io.cwd, f) || f);
433
+ const planned = matches.map(({ outcome: _outcome, ...m }) => m);
434
+ const hint = staysActiveHint(matches, mode);
435
+ const deactivations = matches.filter((m) => m.plan === "deactivate");
278
436
  if (boolOption(input, "dry-run")) {
279
- const rel = files.map((f) => path.relative(ctx.io.cwd, f) || f);
280
- return { data: { kb: kbRef, files: rel, count: rel.length, dry_run: true }, text: `Would upload ${rel.length} files:\n${rel.join("\n")}` };
437
+ return {
438
+ data: { kb: kbRef, files: rel, count: rel.length, dry_run: true, existing: planned },
439
+ text: [
440
+ `Would upload ${fileCount(rel.length)}:`,
441
+ ...rel,
442
+ ...matches.map(plannedLine),
443
+ ...(hint ? [hint] : []),
444
+ ...(deactivations.length ? [`The kit deactivates ${deactivations.length === 1 ? "that document" : "those documents"} only with --replace --confirm.`] : []),
445
+ ].join("\n"),
446
+ };
447
+ }
448
+ const gate = deactivations.length ? await confirmation(ctx, input, "kb_upload", { kb: kb.id, files: rel, existing: planned }) : undefined;
449
+ if (gate && !gate.confirmed) {
450
+ const confirm = gate.confirm(cavelonCommand("kb", "upload", dirArg, "--kb", kbRef, ...(boolOption(input, "recursive") ? ["-r"] : []), ...extensions.flatMap((e) => ["--ext", e]), "--replace", "--confirm"));
451
+ return {
452
+ data: { kb: { id: kb.id, name: kb.name ?? null }, files: rel, count: rel.length, uploaded: false, existing: planned, confirm, ...gate.fields },
453
+ text: [
454
+ `--replace uploads ${fileCount(rel.length)} and then deactivates ${deactivations.length} document${deactivations.length === 1 ? "" : "s"} the instance's upload does not replace itself:`,
455
+ ...matches.map(plannedLine),
456
+ ...(gate.mismatch ? [gate.mismatch] : []),
457
+ `Nothing was sent. Upload and deactivate with: ${confirm}`,
458
+ ].join("\n"),
459
+ ...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
460
+ };
281
461
  }
282
- const kb = await resolveKbId(ctx, kbRef);
283
462
  const batches = [];
284
463
  let current = [];
285
464
  let bytes = 0;
@@ -296,15 +475,26 @@ export const kbUpload = {
296
475
  if (current.length)
297
476
  batches.push(current);
298
477
  const documents = [];
478
+ const uploadedFiles = new Set();
299
479
  let failure;
300
480
  for (const [index, batch] of batches.entries()) {
481
+ const names = new Set(batch.map((f) => path.basename(f)));
482
+ const replaceIds = Object.fromEntries(matches.filter((m) => m.plan === "replace_by_id" && names.has(m.filename)).map((m) => [m.filename, m.document_id]));
483
+ const fields = {};
484
+ if (Object.keys(replaceIds).length)
485
+ fields.replace_doc_ids = JSON.stringify(replaceIds);
486
+ if (mode === "keep-both" && support.byName)
487
+ fields.replace_existing = false;
301
488
  try {
302
- const uploaded = await callStable(ctx, "POST", "/api/v1/knowledge-bases/{kb_id}/documents/upload", "document upload", {
489
+ const uploaded = await callStable(ctx, "POST", UPLOAD_ROUTE, "document upload", {
303
490
  params: { kb_id: [kb.id] },
491
+ body: Object.keys(fields).length ? fields : undefined,
304
492
  files: batch.map((f) => ({ field: "files", path: f })),
305
493
  timeoutMs: 300_000,
306
494
  });
307
495
  documents.push(...uploaded);
496
+ for (const f of batch)
497
+ uploadedFiles.add(path.relative(ctx.io.cwd, f) || f);
308
498
  }
309
499
  catch (error) {
310
500
  if (!(error instanceof CavelonError) || documents.length === 0)
@@ -313,31 +503,78 @@ export const kbUpload = {
313
503
  break;
314
504
  }
315
505
  }
506
+ settleMatches(matches, documents, uploadedFiles);
316
507
  const operationIds = documents.map((d) => d.operation_id).filter((id) => Boolean(id));
317
- const summary = {
508
+ const before = new Set((existing ?? []).map((d) => d.id));
509
+ const outcomes = new Map(documents.map((d) => [d, uploadOutcomeOf(d, before)]));
510
+ const deduplicated = documents.filter((d) => outcomes.get(d) === "deduplicated");
511
+ const created = documents.length - deduplicated.length;
512
+ const summary = () => ({
318
513
  kb: { id: kb.id, name: kb.name ?? null },
319
- documents: documents.map((d) => ({ id: d.id, filename: d.filename, status: d.status, operation_id: d.operation_id ?? null })),
514
+ documents: documents.map((d) => ({
515
+ id: d.id,
516
+ filename: d.filename,
517
+ status: d.status,
518
+ operation_id: d.operation_id ?? null,
519
+ upload_outcome: outcomes.get(d) ?? null,
520
+ ...(Array.isArray(d.replaced_document_ids) ? { replaced_document_ids: d.replaced_document_ids } : {}),
521
+ })),
320
522
  operation_ids: operationIds,
523
+ existing: matches,
524
+ });
525
+ const matchLines = () => {
526
+ const note = staysActiveHint(matches, mode);
527
+ return [
528
+ ...deduplicated.map((d) => `${d.filename}: identical to the active document ${shortId(d.id)}; nothing new was created (deduplicated)`),
529
+ ...matches.filter((m) => !deduplicated.some((d) => d.filename === m.filename)).map(outcomeLine),
530
+ ...(note ? [note] : []),
531
+ ];
321
532
  };
533
+ const uploadedText = (where) => created ? `Uploaded ${fileCount(created)}${where}.` : `Nothing new uploaded${where}: the content of ${deduplicated.length === 1 ? "the file is" : "every file is"} already active.`;
322
534
  if (operationIds.length < documents.length)
323
535
  ctx.warn("The instance returned no operation id for some documents; it may be older than the operations API.");
324
536
  if (failure) {
537
+ const refused = await deactivate(ctx, kb.id, matches);
538
+ if (refused)
539
+ ctx.warn(`The old documents stay active: ${refused.message}`);
325
540
  return {
326
- data: { ...summary, error: failure.error.toJSON(), not_uploaded: failure.notUploaded },
327
- text: `Uploaded ${documents.length} files, then: ${failure.error.message}\n` +
328
- `Not uploaded (${failure.notUploaded.length}): ${failure.notUploaded.join(", ")}\n` +
329
- (operationIds.length ? `Wait for the uploaded ones with: cavelon wait ${operationIds.join(" ")}` : ""),
541
+ data: { ...summary(), error: failure.error.toJSON(), not_uploaded: failure.notUploaded },
542
+ text: [
543
+ `Uploaded ${fileCount(documents.length)}, then: ${failure.error.message}`,
544
+ `Not uploaded (${failure.notUploaded.length}): ${failure.notUploaded.join(", ")}`,
545
+ ...matchLines(),
546
+ ...(operationIds.length ? [`Wait for the uploaded ones with: cavelon wait ${operationIds.join(" ")}`] : []),
547
+ ].join("\n"),
330
548
  exitCode: failure.error.exitCode,
331
549
  };
332
550
  }
333
551
  if (boolOption(input, "wait") && ctx.mode === "cli" && operationIds.length) {
334
552
  const waited = await waitAndReport(ctx, operationIds, timeoutMs(ctx, stringOption(input, "timeout")));
335
- return { data: { ...summary, ...waited.data }, text: `Uploaded ${documents.length} files.\n${waited.text}`, exitCode: waited.exitCode };
553
+ const refused = waited.exitCode === ExitCode.ok ? await deactivate(ctx, kb.id, matches) : undefined;
554
+ if (waited.exitCode !== ExitCode.ok)
555
+ for (const m of matches)
556
+ if (m.outcome === undefined)
557
+ m.outcome = "stays_active";
558
+ if (refused)
559
+ ctx.warn(`The old documents stay active: ${refused.message}`);
560
+ await refreshStatuses(ctx, kb.id, documents);
561
+ return {
562
+ data: { ...summary(), ...waited.data },
563
+ text: [uploadedText(""), ...matchLines(), waited.text].join("\n"),
564
+ exitCode: refused && waited.exitCode === ExitCode.ok ? refused.exitCode : waited.exitCode,
565
+ };
336
566
  }
567
+ const refused = await deactivate(ctx, kb.id, matches);
568
+ if (refused)
569
+ ctx.warn(`The old documents stay active: ${refused.message}`);
337
570
  return {
338
- data: summary,
339
- text: `Uploaded ${documents.length} files to ${kb.name ?? kb.id}.` +
340
- (operationIds.length ? `\nOperations: ${operationIds.length}\nWait with: cavelon wait ${operationIds.join(" ")}` : ""),
571
+ data: summary(),
572
+ text: [
573
+ uploadedText(` to ${kb.name ?? kb.id}`),
574
+ ...matchLines(),
575
+ ...(operationIds.length ? [`Operations: ${operationIds.length}`, `Wait with: cavelon wait ${operationIds.join(" ")}`] : []),
576
+ ].join("\n"),
577
+ exitCode: refused?.exitCode,
341
578
  };
342
579
  },
343
580
  };
@@ -495,7 +732,23 @@ function summarizeTrace(t) {
495
732
  conversation_id: t.conversation_id ?? null,
496
733
  };
497
734
  }
498
- function summarizeSpan(s) {
735
+ function outcomeOf(s) {
736
+ const outcome = spanAttributes(s.attributes_json)?.knowledge_outcome;
737
+ return typeof outcome === "string" && outcome ? outcome : null;
738
+ }
739
+ function knowledgeOutcomes(spans) {
740
+ const out = new Map();
741
+ for (const s of spans) {
742
+ const outcome = outcomeOf(s);
743
+ if (!outcome)
744
+ continue;
745
+ out.set(s.id, outcome);
746
+ if (s.span_type === "retrieval" && s.parent_span_id && !out.has(s.parent_span_id))
747
+ out.set(s.parent_span_id, outcome);
748
+ }
749
+ return out;
750
+ }
751
+ function summarizeSpan(s, outcomes) {
499
752
  const error = s.error_json ? clip(typeof s.error_json === "string" ? s.error_json : JSON.stringify(s.error_json), 200) : null;
500
753
  return {
501
754
  span_id: s.id,
@@ -505,9 +758,35 @@ function summarizeSpan(s) {
505
758
  agent: s.agent_slug ?? null,
506
759
  status: s.status ?? null,
507
760
  duration_ms: s.duration_ms ?? null,
761
+ knowledge_outcome: outcomeOf(s) ?? outcomes?.get(s.id) ?? null,
508
762
  error,
509
763
  };
510
764
  }
765
+ function spanPick(s) {
766
+ if (s.error_json || s.status === "error" || s.status === "errored")
767
+ return "the one that failed";
768
+ if (s.span_type === "llm")
769
+ return "the last model call";
770
+ if (s.span_type === "retrieval")
771
+ return "the knowledge search";
772
+ return s.span_type ?? "a span";
773
+ }
774
+ function retrievalText(data, view) {
775
+ const head = keyValues([
776
+ ["span", `${data.span_id} (retrieval${data.name ? `, ${data.name}` : ""}${data.agent ? `, agent ${data.agent}` : ""})`],
777
+ ["status", data.status],
778
+ ["query", view.query ?? "not recorded"],
779
+ ["knowledge_outcome", view.knowledge_outcome ?? "not classified by the agent"],
780
+ ["hits", view.sources_total ?? view.source_count ?? view.sources.length],
781
+ ["retrieval_status", view.retrieval_status ?? undefined],
782
+ ["error", data.error ? JSON.stringify(data.error) : undefined],
783
+ ]);
784
+ const rows = retrievalRows(view);
785
+ const hits = rows.length ? `\n\n${table(rows, ["rank", "title", "score", "citable", ...(rows.some((r) => r.cited) ? ["cited"] : []), "document_id"])}` : "";
786
+ const more = view.sources_total && view.sources_total > rows.length ? `\n… ${view.sources_total - rows.length} more hits than the trace keeps` : "";
787
+ const outcome = view.knowledge_outcome ? `\n\nWhat it means: ${cavelonCommand("explain", view.knowledge_outcome)}` : "";
788
+ return `${head}${hits}${more}${outcome}\n\nEverything the span recorded: --json`;
789
+ }
511
790
  function detailOf(value, full) {
512
791
  if (full || value === null || value === undefined)
513
792
  return value ?? null;
@@ -554,21 +833,41 @@ async function capacityFooter(ctx, errors) {
554
833
  return "";
555
834
  return `\n\n${code}: ${capacityHint(code, await readLimits(ctx).catch(() => undefined))}`;
556
835
  }
557
- function notPassedLines(r, max) {
836
+ const ANSWER_CHARS = 300;
837
+ const PASSED_ANSWER_CHARS = 150;
838
+ function stepLines(r, full, answerChars = ANSWER_CHARS) {
839
+ const assertions = stepAssertions(r.judge_breakdown, full);
840
+ const count = assertionCount(assertions);
841
+ const lines = assertions.length ? [` Assertions${count ? ` (${count})` : ""}:`, ...assertions.map((a) => ` ${assertionLine(a)}`)] : [];
842
+ if (r.generated_answer)
843
+ lines.push(` Answer: ${clip(r.generated_answer.replace(/\s+/g, " ").trim(), full ? Number.MAX_SAFE_INTEGER : answerChars)}`);
844
+ return lines;
845
+ }
846
+ function notPassedLines(r, max, full) {
558
847
  const c = failedCase(r, max);
559
848
  const lines = [` ${caseLabel(c)} ${c.status}`];
560
849
  if (c.reason)
561
850
  lines.push(` ${c.reason}`);
562
- if (r.llm_judge_reasoning && r.llm_judge_reasoning !== r.error_message)
851
+ if (r.llm_judge_reasoning && r.error_message && r.llm_judge_reasoning !== r.error_message)
563
852
  lines.push(` Judge: ${clip(r.llm_judge_reasoning, max)}`);
853
+ const knowledge = caseKnowledgeOutcomes(r);
854
+ if (knowledge)
855
+ lines.push(` Knowledge: ${knowledge.join(", ")}`);
856
+ lines.push(...stepLines(r, full));
857
+ if (r.agent_slug)
858
+ lines.push(` Answered by: ${r.agent_slug}`);
564
859
  const open = caseTraceCommand(r);
565
860
  if (open)
566
861
  lines.push(` Its traces (${open.label}): ${open.command}`);
567
862
  return lines;
568
863
  }
569
- function judgedLines(r, max) {
864
+ function judgedLines(r, max, full) {
570
865
  const score = r.llm_judge_score === null || r.llm_judge_score === undefined ? "" : ` score ${r.llm_judge_score}`;
571
- return [` ${caseLabel(failedCase(r))} ${r.status}${score}`, ` Judge: ${clip(r.llm_judge_reasoning, max)}`];
866
+ return [
867
+ ` ${caseLabel(failedCase(r))} ${r.status}${score}`,
868
+ ...(r.llm_judge_reasoning ? [` Judge: ${clip(r.llm_judge_reasoning, max)}`] : []),
869
+ ...stepLines(r, full, PASSED_ANSWER_CHARS),
870
+ ];
572
871
  }
573
872
  async function testRunView(ctx, id, results, options) {
574
873
  const max = options.full ? Number.MAX_SAFE_INTEGER : 1000;
@@ -578,15 +877,19 @@ async function testRunView(ctx, id, results, options) {
578
877
  step: r.step_order ?? null,
579
878
  status: r.status,
580
879
  score: r.llm_judge_score ?? null,
880
+ agent: r.agent_slug ?? null,
581
881
  conversation_id: r.conversation_id ?? null,
582
882
  run_id: r.agent_run_id ?? null,
583
883
  error: r.error_message ? clip(r.error_message, 200) : null,
884
+ answer: r.generated_answer ? clip(r.generated_answer, options.full ? max : ANSWER_CHARS) : null,
885
+ assertions: stepAssertions(r.judge_breakdown, options.full),
584
886
  judge_reasoning: r.llm_judge_reasoning ? clip(r.llm_judge_reasoning, max) : null,
887
+ knowledge_outcomes: caseKnowledgeOutcomes(r),
585
888
  trace_command: caseTraceCommand(r)?.command ?? null,
586
889
  ...(NOT_PASSED.has(r.status) ? { reason: failedCase(r, max).reason, judge_breakdown: detailOf(r.judge_breakdown, options.full) } : {}),
587
890
  }));
588
891
  const notPassed = page.items.filter((r) => NOT_PASSED.has(r.status));
589
- const judged = page.items.filter((r) => !NOT_PASSED.has(r.status) && r.llm_judge_reasoning);
892
+ const judged = page.items.filter((r) => !NOT_PASSED.has(r.status) && (r.llm_judge_reasoning || stepAssertions(r.judge_breakdown).length || r.generated_answer));
590
893
  const byConversation = page.items.find((r) => r.conversation_id);
591
894
  const byRun = page.items.find((r) => !r.conversation_id && r.agent_run_id);
592
895
  const where = [
@@ -595,10 +898,10 @@ async function testRunView(ctx, id, results, options) {
595
898
  ].filter(Boolean);
596
899
  return {
597
900
  data: { kind: "test", run_id: id, results: { ...page, items } },
598
- text: table(items, ["case", "step", "status", "score", ...(items.some((r) => r.run_id) ? ["run_id"] : []), "conversation_id"]) +
901
+ text: table(items, ["case", "step", "status", "score", ...(items.some((r) => r.agent) ? ["agent"] : []), ...(items.some((r) => r.run_id) ? ["run_id"] : []), "conversation_id"]) +
599
902
  moreHint(page.next_cursor, cavelonCommand("trace", id, "--kind", "test")) +
600
- (notPassed.length ? `\n\nDid not pass:\n${notPassed.flatMap((r) => notPassedLines(r, max)).join("\n")}` : "") +
601
- (judged.length ? `\n\nJudge's reasoning:\n${judged.flatMap((r) => judgedLines(r, options.full ? max : 300)).join("\n")}` : "") +
903
+ (notPassed.length ? `\n\nDid not pass:\n${notPassed.flatMap((r) => notPassedLines(r, max, options.full)).join("\n")}` : "") +
904
+ (judged.length ? `\n\nPassed:\n${judged.flatMap((r) => judgedLines(r, options.full ? max : 300, options.full)).join("\n")}` : "") +
602
905
  `\n\n${where.length ? where.join("\n") : "The instance recorded no conversation or run for these results, so they have no trace to open."}` +
603
906
  (await capacityFooter(ctx, items.map((r) => r.error))),
604
907
  };
@@ -673,31 +976,36 @@ export const trace = {
673
976
  }
674
977
  }
675
978
  const spans = (detail.spans ?? []).slice().sort((a, b) => (a.sequence ?? 0) - (b.sequence ?? 0));
979
+ const outcomes = knowledgeOutcomes(spans);
676
980
  if (spanId) {
677
981
  const span = spans.find((s) => s.id === spanId);
678
982
  if (!span)
679
983
  throw new CavelonError(ExitCode.failure, { code: "span_not_found", message: `No span ${spanId} in trace ${traceId}.` });
680
984
  const full = boolOption(input, "full");
985
+ const attributes = spanAttributes(span.attributes_json) ?? span.attributes_json;
986
+ const retrieval = span.span_type === "retrieval" ? retrievalView(spanAttributes(span.attributes_json)) : undefined;
681
987
  const data = {
682
- ...summarizeSpan(span),
988
+ ...summarizeSpan(span, outcomes),
683
989
  model: span.model ?? null,
684
990
  parent_span_id: span.parent_span_id ?? null,
685
991
  input: detailOf(span.input_json, full),
686
992
  output: detailOf(span.output_json, full),
687
- attributes: detailOf(span.attributes_json, full),
993
+ attributes: detailOf(attributes, full),
994
+ ...(retrieval ? { retrieval } : {}),
688
995
  tokens: span.token_usage_json ?? null,
689
996
  error: span.error_json ?? null,
690
997
  };
691
- return { data, text: JSON.stringify(data, null, 2) };
998
+ return { data, text: retrieval ? retrievalText(data, retrieval) : JSON.stringify(data, null, 2) };
692
999
  }
693
- const page = pageOf(spans.map(summarizeSpan), limit, cursor);
1000
+ const page = pageOf(spans.map((s) => summarizeSpan(s, outcomes)), limit, cursor);
694
1001
  const base = cavelonCommand("trace", id, ...(kind ? ["--kind", kind] : []), "--trace", traceId);
1002
+ const open = suggestedSpan(spans);
695
1003
  return {
696
1004
  data: { trace: summarizeTrace(detail), spans: page },
697
1005
  text: `${keyValues(Object.entries(summarizeTrace(detail)))}\n\n` +
698
- table(page.items, ["seq", "type", "name", "status", "duration_ms", "span_id"]) +
1006
+ table(page.items, ["seq", "type", "name", "status", ...(outcomes.size ? ["knowledge_outcome"] : []), "duration_ms", "span_id"]) +
699
1007
  moreHint(page.next_cursor, base) +
700
- (page.items.length ? `\n\nOne span in full, by the span_id in its row: ${base} --span ${shellWord(page.items[0].span_id)}` : ""),
1008
+ (open ? `\n\nOne span in full (${spanPick(open)}), by the span_id in its row: ${base} --span ${shellWord(open.id)}` : ""),
701
1009
  };
702
1010
  }
703
1011
  const order = kind ? [kind] : ["trigger", "test", "conversation"];
@@ -0,0 +1,72 @@
1
+ import { createHash } from "node:crypto";
2
+ import { drivenByAgent } from "./agent-env.js";
3
+ import { CavelonError, ExitCode } from "./errors.js";
4
+ import { canonical } from "./package-files.js";
5
+ export const CONFIRM_TOKEN = /^[0-9a-f]{12}$/;
6
+ export function confirmToken(target, tool, change) {
7
+ return createHash("sha256")
8
+ .update(canonical({ instance: target.url ?? null, tenant: target.tenant ?? null, tool, change }))
9
+ .digest("hex")
10
+ .slice(0, 12);
11
+ }
12
+ export function confirmGiven(input) {
13
+ const value = input.options.confirm;
14
+ return value !== undefined && value !== false && value !== "";
15
+ }
16
+ export function withToken(command, token) {
17
+ if (command.endsWith(" --confirm"))
18
+ return `${command} ${token}`;
19
+ const at = command.indexOf(" --confirm ");
20
+ if (at >= 0)
21
+ return `${command.slice(0, at)} --confirm ${token}${command.slice(at + " --confirm".length)}`;
22
+ return `${command} --confirm ${token}`;
23
+ }
24
+ export async function confirmation(ctx, input, tool, change) {
25
+ const given = input.options.confirm;
26
+ const driven = drivenByAgent(ctx);
27
+ const tokenGiven = typeof given === "string" && given !== "";
28
+ if (!driven && !tokenGiven)
29
+ return { confirmed: given === true, fields: {}, confirm: (command) => command };
30
+ if (driven?.by === "mcp" && given === true)
31
+ throw confirmTokenRequired(tool);
32
+ const session = await ctx.session();
33
+ const token = confirmToken({ url: session.url, tenant: session.tenant }, tool, change);
34
+ const confirm = (command) => (driven?.by === "mcp" ? confirmWith(tool, token) : driven ? withToken(command, token) : command);
35
+ if (given === true && driven?.by === "agent") {
36
+ return {
37
+ confirmed: false,
38
+ fields: { confirm_token: token, token_required: true },
39
+ confirm,
40
+ mismatch: `--confirm alone does not confirm when a coding agent runs cavelon (${driven.variable} is set). Nothing was changed: show the person this preview, and with their yes run the command below, which carries this change's token.`,
41
+ exitCode: ExitCode.needsAction,
42
+ };
43
+ }
44
+ if (!tokenGiven)
45
+ return { confirmed: false, fields: { confirm_token: token }, confirm };
46
+ if (given === token)
47
+ return { confirmed: true, fields: {}, confirm };
48
+ return {
49
+ confirmed: false,
50
+ fields: { confirm_token: token, token_mismatch: true },
51
+ confirm,
52
+ mismatch: "The confirm token is not this change's: the change differs from its preview, or the token is another one's. Nothing was changed.",
53
+ exitCode: ExitCode.conflict,
54
+ };
55
+ }
56
+ export function shellTokenRequired(command, variable) {
57
+ return new CavelonError(ExitCode.needsAction, {
58
+ code: "confirm_token_required",
59
+ message: `--confirm alone does not confirm when a coding agent runs cavelon (${variable} is set); nothing was changed.`,
60
+ hint: `Run \`${command}\` without --confirm, show the person the preview, and with their yes run the command it prints, which carries the change's token.`,
61
+ });
62
+ }
63
+ export function confirmTokenRequired(tool) {
64
+ return new CavelonError(ExitCode.usage, {
65
+ code: "confirm_token_required",
66
+ message: `${tool} confirms only with the confirm_token its preview returned, not with true; nothing was changed.`,
67
+ hint: `Call ${tool} without confirm, show the person what it would do, then call it again with the same arguments and confirm set to its confirm_token.`,
68
+ });
69
+ }
70
+ export function confirmWith(tool, token) {
71
+ return `Show the person this, then call ${tool} again with the same arguments and confirm: "${token}" to make exactly this change.`;
72
+ }
package/dist/contracts.js CHANGED
@@ -17,6 +17,7 @@ export class Contracts {
17
17
  live = false;
18
18
  versionValue;
19
19
  needsTenant = false;
20
+ cachedAt;
20
21
  constructor(client, env, now) {
21
22
  this.client = client;
22
23
  this.env = env;
@@ -52,11 +53,13 @@ export class Contracts {
52
53
  if (cached) {
53
54
  this.caps = cached;
54
55
  this.versionValue = state.version;
56
+ this.cachedAt = state.checked_at;
55
57
  return cached;
56
58
  }
57
59
  }
58
60
  const response = await this.client.get("/api/v1/meta/capabilities", { allow: [400, 404] });
59
61
  this.live = true;
62
+ this.cachedAt = undefined;
60
63
  if (response.status === 400) {
61
64
  this.needsTenant = true;
62
65
  this.caps = null;