@cavelon/cli 0.1.5 → 0.1.7

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 (42) hide show
  1. package/README.md +56 -18
  2. package/dist/command.js +10 -0
  3. package/dist/commands/api.js +40 -36
  4. package/dist/commands/chat.js +183 -0
  5. package/dist/commands/docs.js +77 -9
  6. package/dist/commands/fmt.js +61 -6
  7. package/dist/commands/index.js +3 -0
  8. package/dist/commands/init.js +61 -26
  9. package/dist/commands/inventory.js +21 -0
  10. package/dist/commands/limits-set.js +10 -6
  11. package/dist/commands/loops.js +22 -11
  12. package/dist/commands/models.js +11 -7
  13. package/dist/commands/sandboxes.js +11 -5
  14. package/dist/commands/schema.js +230 -48
  15. package/dist/commands/session.js +100 -14
  16. package/dist/commands/setup.js +22 -6
  17. package/dist/commands/solution.js +493 -86
  18. package/dist/commands/tenants.js +43 -10
  19. package/dist/commands/values.js +20 -11
  20. package/dist/commands/work.js +167 -33
  21. package/dist/confirm-token.js +72 -0
  22. package/dist/format.js +4 -4
  23. package/dist/harness-ref.js +17 -4
  24. package/dist/http.js +6 -0
  25. package/dist/kit-codes.js +11 -1
  26. package/dist/local-state.js +46 -10
  27. package/dist/main.js +38 -6
  28. package/dist/mcp.js +65 -14
  29. package/dist/openapi.js +30 -0
  30. package/dist/package-check.js +206 -18
  31. package/dist/package-files.js +98 -40
  32. package/dist/package-format.js +81 -8
  33. package/dist/package-references.js +77 -10
  34. package/dist/results.js +21 -1
  35. package/dist/session.js +9 -0
  36. package/dist/skills/cavelon-authoring/SKILL.md +54 -21
  37. package/dist/skills/cavelon-long-running/SKILL.md +13 -9
  38. package/dist/skills/cavelon-loop/SKILL.md +124 -28
  39. package/dist/skills/cavelon-testing/SKILL.md +69 -16
  40. package/dist/tenant-choice.js +19 -0
  41. package/dist/trace-view.js +172 -0
  42. package/package.json +1 -1
@@ -1,11 +1,12 @@
1
1
  import { boolOption, CURSOR_OPTION, intOption, LIMIT_OPTION, pageOf, positional, stringOption, } from "../command.js";
2
2
  import { CavelonError, ExitCode, usageError } from "../errors.js";
3
+ import { confirmation, confirmTokenRequired } from "../confirm-token.js";
3
4
  import { keyValues, moreHint, table } from "../format.js";
4
5
  import { callStable } from "../invoke.js";
5
6
  import { formatQuota, limitError, limitsOrWarn, readQuotas } from "../limits.js";
6
7
  import { containing } from "../choose.js";
7
8
  import { readPrincipal, readTenantless } from "../principal.js";
8
- import { requireInstance } from "../session.js";
9
+ import { contextFlags, requireInstance } from "../session.js";
9
10
  import { listsTenants, searchTenants } from "../tenant-choice.js";
10
11
  import { harnessNotFoundError, lookupHarness, resolveHarnessId } from "../harness-ref.js";
11
12
  import { defaultChangeLine, defaultCommands, named, readDefaultRoute, setDefaultRoute } from "../default-route.js";
@@ -44,6 +45,17 @@ function checkCanCreateTenant(principal) {
44
45
  details: { permission: TENANTS_MANAGE, ceiling_role: token.ceiling_role ?? null, sent: false },
45
46
  });
46
47
  }
48
+ const outside = principal.mode !== "platform" && (principal.permissions ? !principal.permissions.includes(TENANTS_MANAGE) : principal.mode === "none");
49
+ if (token.platform_mode_allowed === true && outside) {
50
+ throw new CavelonError(ExitCode.unauthorized, {
51
+ code: "permission_missing",
52
+ message: `The personal access token "${token.name}" may enter Platform mode, but its ceiling${token.ceiling_role ? ` ${token.ceiling_role}` : ""} gives it no ` +
53
+ `role there with ${TENANTS_MANAGE} (asked without a tenant, the instance answers it ${principal.mode === "none" ? "in no mode" : "in a tenant"}), ` +
54
+ "so it cannot create a tenant; nothing was sent.",
55
+ hint: CREATE_TENANT_REMEDY,
56
+ details: { permission: TENANTS_MANAGE, ceiling_role: token.ceiling_role ?? null, mode: principal.mode, sent: false },
57
+ });
58
+ }
47
59
  }
48
60
  async function entersTenant(client, tenantId) {
49
61
  const before = client.target.tenantId;
@@ -230,17 +242,21 @@ export const harnessDefault = {
230
242
  mcpTool: "harness_default",
231
243
  positionals: [{ name: "solution", description: "Name, slug or id of the solution; default: cavelon.yaml's harness." }],
232
244
  options: {
233
- confirm: { type: "boolean", description: "Change the default route (after a person saw the preview)." },
245
+ confirm: { type: "boolean", mcpToken: true, description: "Change the default route (after a person saw the preview)." },
234
246
  },
235
- examples: ["cavelon harness default support", "cavelon harness default support --confirm"],
247
+ examples: ["cavelon harness default support", "cavelon harness default support --confirm", "cavelon harness default support --confirm <token>"],
236
248
  async run(ctx, input) {
237
249
  const session = await ctx.session();
238
250
  const ref = positional(input, "solution") ?? session.envFile?.harness ?? session.project?.harness;
239
251
  if (!ref)
240
252
  throw usageError("Which solution?", "Pass its name or slug (`cavelon harness list` shows them), or run it in a folder whose cavelon.yaml names one.");
253
+ if (ctx.mode === "mcp" && input.options.confirm === true)
254
+ throw confirmTokenRequired("harness_default");
241
255
  const { harness, candidates } = await lookupHarness(ctx, ref);
242
- if (!harness)
243
- throw harnessNotFoundError(ref, candidates, undefined, (slug) => cavelonCommand("harness", "default", slug));
256
+ if (!harness) {
257
+ const flags = contextFlags(session);
258
+ throw harnessNotFoundError(ref, candidates, undefined, (slug) => cavelonCommand("harness", "default", slug) + flags, flags);
259
+ }
244
260
  const route = await readDefaultRoute(ctx);
245
261
  const target = { id: harness.id, slug: harness.slug, name: harness.name, status: harness.status };
246
262
  const current = route.current ? { id: route.current.id, slug: route.current.slug, name: route.current.name } : null;
@@ -248,15 +264,32 @@ export const harnessDefault = {
248
264
  return { data: { changed: false, already_default: true, harness: target, default_route: current }, text: `${named(harness)} is already the tenant's default route.` };
249
265
  }
250
266
  const commands = defaultCommands(harness.slug);
251
- const draft = harness.status !== "active" ? `${named(harness)} is ${harness.status}; activate it first (\`cavelon activate --harness ${harness.slug}\`), or the instance may refuse.` : undefined;
252
- if (!boolOption(input, "confirm")) {
267
+ if (harness.status !== "active") {
268
+ throw new CavelonError(ExitCode.conflict, {
269
+ code: "solution_not_active",
270
+ message: `${named(harness)} is ${harness.status}, and only an active solution can be the tenant's default route; nothing was changed.`,
271
+ hint: `Activate it through the readiness gate and preview the default route in one step: ${cavelonCommand("activate", "--harness", harness.slug, "--make-default")}. ` +
272
+ `The default route stays ${current ? named(current) : "as it is"} until then.`,
273
+ details: { harness: target, default_route: current },
274
+ });
275
+ }
276
+ const gate = await confirmation(ctx, input, "harness_default", { harness: harness.id, from: current?.id ?? null });
277
+ if (!gate.confirmed) {
253
278
  return {
254
- data: { changed: false, harness: target, default_route: current, default_known: route.known, confirm: commands.confirm, ...(draft ? { note: draft } : {}) },
279
+ data: {
280
+ changed: false,
281
+ harness: target,
282
+ default_route: current,
283
+ default_known: route.known,
284
+ confirm: gate.confirm(commands.confirm),
285
+ ...gate.fields,
286
+ },
255
287
  text: [
256
288
  defaultChangeLine(harness, route),
257
- ...(draft ? [draft] : []),
258
- `Show this to a person; with their yes: ${commands.confirm}`,
289
+ ...(gate.mismatch ? [gate.mismatch] : []),
290
+ `Show this to a person; with their yes: ${gate.confirm(commands.confirm)}`,
259
291
  ].join("\n"),
292
+ ...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
260
293
  };
261
294
  }
262
295
  const updated = await setDefaultRoute(ctx, harness.id);
@@ -1,4 +1,5 @@
1
1
  import { boolOption, CURSOR_OPTION, intOption, LIMIT_OPTION, pageOf, positional, stringOption, } from "../command.js";
2
+ import { confirmation } from "../confirm-token.js";
2
3
  import { CavelonError, ExitCode, usageError, validationError } from "../errors.js";
3
4
  import { clip, keyValues, moreHint, table } from "../format.js";
4
5
  import { callStable, workflowOperation } from "../invoke.js";
@@ -9,7 +10,11 @@ import { readHidden } from "../prompt.js";
9
10
  import { requireToken } from "../session.js";
10
11
  import { shellWord } from "../shell.js";
11
12
  export const ENV_OPTION = { type: "string", value: "<name>", description: "Act in the tenant that env/<name>.yaml names." };
12
- const CONFIRM_OPTION = { type: "boolean", description: "Delete it; without this nothing is deleted." };
13
+ const CONFIRM_OPTION = {
14
+ type: "boolean",
15
+ mcpToken: true,
16
+ description: "Delete it; without this nothing is deleted.",
17
+ };
13
18
  const TOKEN_PREFIXES = ["cbp_", "cvpat_"];
14
19
  const LIST_VALUE_CHARS = 200;
15
20
  export function targetFlags(session, env = session.envFile?.name) {
@@ -164,18 +169,20 @@ export const variablesDelete = {
164
169
  mcpTool: false,
165
170
  positionals: [{ name: "name", description: "The variable's name.", required: true }],
166
171
  options: { confirm: CONFIRM_OPTION, env: ENV_OPTION },
167
- examples: ["cavelon variables delete old_url", "cavelon variables delete old_url --confirm"],
172
+ examples: ["cavelon variables delete old_url", "cavelon variables delete old_url --confirm", "cavelon variables delete old_url --confirm <token>"],
168
173
  async run(ctx, input) {
169
174
  const name = positional(input, "name");
170
175
  const flags = targetFlags(await ctx.session());
171
176
  const current = await readVariable(ctx, name);
172
177
  if (!current)
173
178
  return { data: { name, deleted: false, existed: false }, text: `This tenant has no variable "${name}"; nothing to delete.` };
174
- if (!boolOption(input, "confirm")) {
175
- const confirm = `cavelon variables delete ${shellWord(name)}${flags} --confirm`;
179
+ const gate = await confirmation(ctx, input, "variables_delete", { name, value: current.value });
180
+ if (!gate.confirmed) {
181
+ const confirm = gate.confirm(`cavelon variables delete ${shellWord(name)}${flags} --confirm`);
176
182
  return {
177
- data: { name, deleted: false, existed: true, value: current.value, confirm },
178
- text: `Variable ${name} = ${JSON.stringify(clip(current.value, LIST_VALUE_CHARS))}.\nNothing was deleted. Delete it with: ${confirm}`,
183
+ data: { name, deleted: false, existed: true, value: current.value, confirm, ...gate.fields },
184
+ text: `Variable ${name} = ${JSON.stringify(clip(current.value, LIST_VALUE_CHARS))}.\n${gate.mismatch ? `${gate.mismatch}\n` : ""}Nothing was deleted. Delete it with: ${confirm}`,
185
+ ...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
179
186
  };
180
187
  }
181
188
  try {
@@ -354,7 +361,7 @@ export const secretsDelete = {
354
361
  mcpTool: false,
355
362
  positionals: [{ name: "name", description: "The secret's name.", required: true }],
356
363
  options: { confirm: CONFIRM_OPTION, env: ENV_OPTION },
357
- examples: ["cavelon secrets delete old_token", "cavelon secrets delete old_token --confirm"],
364
+ examples: ["cavelon secrets delete old_token", "cavelon secrets delete old_token --confirm", "cavelon secrets delete old_token --confirm <token>"],
358
365
  async run(ctx, input) {
359
366
  const name = positional(input, "name");
360
367
  await requirePerson(ctx, "delete", name);
@@ -363,11 +370,13 @@ export const secretsDelete = {
363
370
  const nothing = { data: { ...current, deleted: false }, text: `Secret ${name} has no value; nothing to delete.` };
364
371
  if (current.status !== "set")
365
372
  return nothing;
366
- if (!boolOption(input, "confirm")) {
367
- const confirm = `cavelon secrets delete ${shellWord(name)}${flags} --confirm`;
373
+ const gate = await confirmation(ctx, input, "secrets_delete", { name, changed_at: current.changed_at ?? null });
374
+ if (!gate.confirmed) {
375
+ const confirm = gate.confirm(`cavelon secrets delete ${shellWord(name)}${flags} --confirm`);
368
376
  return {
369
- data: { ...current, deleted: false, confirm },
370
- text: `Secret ${name} is set${changedNote(current.changed_at)}.\nNothing was deleted. Delete it with: ${confirm}`,
377
+ data: { ...current, deleted: false, confirm, ...gate.fields },
378
+ text: `Secret ${name} is set${changedNote(current.changed_at)}.\n${gate.mismatch ? `${gate.mismatch}\n` : ""}Nothing was deleted. Delete it with: ${confirm}`,
379
+ ...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
371
380
  };
372
381
  }
373
382
  try {
@@ -1,15 +1,18 @@
1
- import { promises as fs } from "node:fs";
1
+ import { createHash } from "node:crypto";
2
+ import { createReadStream, promises as fs } from "node:fs";
2
3
  import path from "node:path";
3
4
  import { boolOption, CURSOR_OPTION, intOption, LIMIT_OPTION, listOption, pageOf, positional, stringOption, } from "../command.js";
4
5
  import { capacityCodeIn, capacityHint, noteLines, runCapacityNote } from "../capacity.js";
6
+ import { assertionCount, assertionLine, retrievalRows, retrievalView, spanAttributes, stepAssertions, suggestedSpan } from "../trace-view.js";
5
7
  import { CavelonError, ExitCode, usageError } from "../errors.js";
8
+ import { confirmation } from "../confirm-token.js";
6
9
  import { confinedPath } from "../paths.js";
7
10
  import { clip, keyValues, moreHint, table } from "../format.js";
8
11
  import { callStable, workflowOperation } from "../invoke.js";
9
12
  import { deref } from "../openapi.js";
10
13
  import { bindsNow, changedBy, limitError, limitsOrWarn, readLimits } from "../limits.js";
11
14
  import { getOperation } from "../operations.js";
12
- import { caseCounts, caseLabel, countsText, failedCase, NOT_PASSED, runVerdict } from "../results.js";
15
+ import { caseCounts, caseLabel, countsText, failedCase, caseKnowledgeOutcomes, NOT_PASSED, runVerdict } from "../results.js";
13
16
  import { isUuid } from "../session.js";
14
17
  import { cavelonCommand, shellWord } from "../shell.js";
15
18
  import { readZipSummary, ZipError } from "../zip.js";
@@ -17,6 +20,28 @@ import { TIMEOUT_OPTION, timeoutMs, waitAndReport } from "./async.js";
17
20
  import { stageErrors, stageErrorText } from "./loops.js";
18
21
  import { resolveHarnessId } from "../harness-ref.js";
19
22
  const WAIT_OPTION = { type: "boolean", description: "Wait for the work to finish (see `cavelon wait`).", cliOnly: true };
23
+ const fileCount = (n) => `${n} file${n === 1 ? "" : "s"}`;
24
+ function uploadOutcomeOf(d, before) {
25
+ if (typeof d.upload_outcome === "string" && d.upload_outcome)
26
+ return d.upload_outcome;
27
+ return before.has(d.id) ? "deduplicated" : null;
28
+ }
29
+ async function refreshStatuses(ctx, kbId, documents) {
30
+ try {
31
+ const list = await callStable(ctx, "GET", DOCUMENTS_ROUTE, "listing a knowledge base's documents", { params: { kb_id: [kbId] } });
32
+ const byId = new Map((Array.isArray(list) ? list : []).map((d) => [d.id, d]));
33
+ for (const d of documents) {
34
+ const status = byId.get(d.id)?.status;
35
+ if (typeof status === "string" && status)
36
+ d.status = status;
37
+ }
38
+ }
39
+ catch (error) {
40
+ if (!(error instanceof CavelonError))
41
+ throw error;
42
+ ctx.warn(`Could not read the documents' statuses after the wait (${error.message}); the operations above say how ingestion ended.`);
43
+ }
44
+ }
20
45
  const UPLOAD_ROUTE = "/api/v1/knowledge-bases/{kb_id}/documents/upload";
21
46
  const DOCUMENTS_ROUTE = "/api/v1/knowledge-bases/{kb_id}/documents";
22
47
  const ACTIVE_ROUTE = "/api/v1/knowledge-bases/{kb_id}/documents/active";
@@ -38,6 +63,32 @@ async function existingDocuments(ctx, kbId) {
38
63
  return undefined;
39
64
  }
40
65
  }
66
+ async function sha256Of(file) {
67
+ const hash = createHash("sha256");
68
+ for await (const chunk of createReadStream(file))
69
+ hash.update(chunk);
70
+ return hash.digest("hex");
71
+ }
72
+ async function identicalFiles(files, cwd, existing) {
73
+ const hashed = existing.filter((d) => typeof d.file_sha256 === "string" && d.file_sha256 !== "");
74
+ if (existing.length && !hashed.length)
75
+ return undefined;
76
+ const byHash = new Map();
77
+ for (const d of [...hashed].sort((a, b) => (b.created_at ?? "").localeCompare(a.created_at ?? ""))) {
78
+ const key = d.file_sha256.toLowerCase();
79
+ if (!byHash.has(key))
80
+ byHash.set(key, d);
81
+ }
82
+ const out = [];
83
+ if (!byHash.size)
84
+ return out;
85
+ for (const file of files) {
86
+ const document = byHash.get(await sha256Of(file));
87
+ if (document)
88
+ out.push({ file: path.relative(cwd, file) || file, document_id: document.id, filename: document.filename });
89
+ }
90
+ return out;
91
+ }
41
92
  function nameMatches(files, cwd, existing, mode, support) {
42
93
  const matches = [];
43
94
  const mapped = new Set();
@@ -354,7 +405,9 @@ export const kbUpload = {
354
405
  "A file named like an active document of the knowledge base is listed, with what happens to that document. An\n" +
355
406
  "instance that replaces same-named documents on upload does so (--keep-both keeps both); elsewhere the old one stays\n" +
356
407
  "active. --replace replaces it: through the instance's own replacement where its upload offers one, else the kit\n" +
357
- "deactivates the old document after the upload (after the wait with --wait), and then only with --confirm.",
408
+ "deactivates the old document after the upload (after the wait with --wait), and then only with --confirm.\n" +
409
+ "--dry-run also names each file identical to an active document, which the upload would not create again, where the\n" +
410
+ "instance publishes its documents' file hashes.",
358
411
  readOnly: false,
359
412
  mcpTool: "kb_upload",
360
413
  positionals: [{ name: "dir", description: "Folder (or single file) to upload.", required: true }],
@@ -364,8 +417,8 @@ export const kbUpload = {
364
417
  ext: { type: "string", multiple: true, value: "<ext>", description: "Only these file extensions (pdf, md, …)." },
365
418
  replace: { type: "boolean", description: "Replace active documents with the same file name." },
366
419
  "keep-both": { type: "boolean", description: "Keep active documents with the same file name next to the new ones." },
367
- confirm: { type: "boolean", description: "With --replace, deactivate the old documents the instance does not replace itself; without it nothing is sent." },
368
- "dry-run": { type: "boolean", description: "List what would be uploaded and replaced, upload nothing." },
420
+ confirm: { type: "boolean", mcpToken: true, description: "With --replace, deactivate the old documents the instance does not replace itself; without it nothing is sent." },
421
+ "dry-run": { type: "boolean", description: "List what would be uploaded, replaced and found identical; upload nothing." },
369
422
  wait: WAIT_OPTION,
370
423
  timeout: TIMEOUT_OPTION,
371
424
  },
@@ -407,29 +460,45 @@ export const kbUpload = {
407
460
  const matches = existing ? nameMatches(files, ctx.io.cwd, existing, mode, support) : [];
408
461
  const rel = files.map((f) => path.relative(ctx.io.cwd, f) || f);
409
462
  const planned = matches.map(({ outcome: _outcome, ...m }) => m);
410
- const hint = staysActiveHint(matches, mode);
411
463
  const deactivations = matches.filter((m) => m.plan === "deactivate");
412
464
  if (boolOption(input, "dry-run")) {
465
+ const identical = existing ? await identicalFiles(files, ctx.io.cwd, existing) : undefined;
466
+ const isIdentical = (m) => Boolean(identical?.some((i) => i.file === m.file && i.document_id === m.document_id));
467
+ const differing = matches.filter((m) => !isIdentical(m));
468
+ const dryHint = staysActiveHint(differing, mode);
469
+ const dryDeactivations = differing.filter((m) => m.plan === "deactivate");
413
470
  return {
414
- data: { kb: kbRef, files: rel, count: rel.length, dry_run: true, existing: planned },
471
+ data: {
472
+ kb: kbRef,
473
+ files: rel,
474
+ count: rel.length,
475
+ dry_run: true,
476
+ existing: planned.map((m, index) => (identical ? { ...m, identical: isIdentical(matches[index]) } : m)),
477
+ content_compared: identical !== undefined,
478
+ identical: identical ?? [],
479
+ },
415
480
  text: [
416
- `Would upload ${rel.length} files:`,
481
+ `Would upload ${fileCount(rel.length)}:`,
417
482
  ...rel,
418
- ...matches.map(plannedLine),
419
- ...(hint ? [hint] : []),
420
- ...(deactivations.length ? [`The kit deactivates ${deactivations.length === 1 ? "that document" : "those documents"} only with --replace --confirm.`] : []),
483
+ ...(identical ?? []).map((i) => `${i.file}: identical to the active document ${shortId(i.document_id)}${i.filename === path.basename(i.file) ? "" : ` (${i.filename})`}; nothing new would be created (deduplicated)`),
484
+ ...differing.map(plannedLine),
485
+ ...(dryHint ? [dryHint] : []),
486
+ ...(dryDeactivations.length ? [`The kit deactivates ${dryDeactivations.length === 1 ? "that document" : "those documents"} only with --replace --confirm.`] : []),
421
487
  ].join("\n"),
422
488
  };
423
489
  }
424
- if (deactivations.length && !boolOption(input, "confirm")) {
425
- const confirm = cavelonCommand("kb", "upload", dirArg, "--kb", kbRef, ...(boolOption(input, "recursive") ? ["-r"] : []), ...extensions.flatMap((e) => ["--ext", e]), "--replace", "--confirm");
490
+ const gate = deactivations.length ? await confirmation(ctx, input, "kb_upload", { kb: kb.id, files: rel, existing: planned }) : undefined;
491
+ if (gate && !gate.confirmed) {
492
+ const confirm = gate.confirm(cavelonCommand("kb", "upload", dirArg, "--kb", kbRef, ...(boolOption(input, "recursive") ? ["-r"] : []), ...extensions.flatMap((e) => ["--ext", e]), "--replace", "--confirm"));
426
493
  return {
427
- data: { kb: { id: kb.id, name: kb.name ?? null }, files: rel, count: rel.length, uploaded: false, existing: planned, confirm },
494
+ data: { kb: { id: kb.id, name: kb.name ?? null }, files: rel, count: rel.length, uploaded: false, existing: planned, confirm, ...gate.fields },
428
495
  text: [
429
- `--replace uploads ${rel.length} files and then deactivates ${deactivations.length} document${deactivations.length === 1 ? "" : "s"} the instance's upload does not replace itself:`,
496
+ `--replace uploads ${fileCount(rel.length)} and then deactivates ${deactivations.length} document${deactivations.length === 1 ? "" : "s"} the instance's upload does not replace itself:`,
430
497
  ...matches.map(plannedLine),
498
+ ...(gate.mismatch ? [gate.mismatch] : []),
431
499
  `Nothing was sent. Upload and deactivate with: ${confirm}`,
432
500
  ].join("\n"),
501
+ ...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
433
502
  };
434
503
  }
435
504
  const batches = [];
@@ -477,7 +546,16 @@ export const kbUpload = {
477
546
  }
478
547
  }
479
548
  settleMatches(matches, documents, uploadedFiles);
480
- const operationIds = documents.map((d) => d.operation_id).filter((id) => Boolean(id));
549
+ const before = new Set((existing ?? []).map((d) => d.id));
550
+ const outcomes = new Map(documents.map((d) => [d, uploadOutcomeOf(d, before)]));
551
+ const deduplicated = documents.filter((d) => outcomes.get(d) === "deduplicated");
552
+ const same = new Set(deduplicated.map((d) => d.id));
553
+ for (const m of matches)
554
+ if (same.has(m.document_id))
555
+ m.outcome = "identical";
556
+ const fresh = documents.filter((d) => !deduplicated.includes(d));
557
+ const operationIds = fresh.map((d) => d.operation_id).filter((id) => Boolean(id));
558
+ const created = fresh.length;
481
559
  const summary = () => ({
482
560
  kb: { id: kb.id, name: kb.name ?? null },
483
561
  documents: documents.map((d) => ({
@@ -485,6 +563,7 @@ export const kbUpload = {
485
563
  filename: d.filename,
486
564
  status: d.status,
487
565
  operation_id: d.operation_id ?? null,
566
+ upload_outcome: outcomes.get(d) ?? null,
488
567
  ...(Array.isArray(d.replaced_document_ids) ? { replaced_document_ids: d.replaced_document_ids } : {}),
489
568
  })),
490
569
  operation_ids: operationIds,
@@ -492,9 +571,14 @@ export const kbUpload = {
492
571
  });
493
572
  const matchLines = () => {
494
573
  const note = staysActiveHint(matches, mode);
495
- return [...matches.map(outcomeLine), ...(note ? [note] : [])];
574
+ return [
575
+ ...deduplicated.map((d) => `${d.filename}: identical to the active document ${shortId(d.id)}; nothing new was created (deduplicated)`),
576
+ ...matches.filter((m) => m.outcome !== "identical").map(outcomeLine),
577
+ ...(note ? [note] : []),
578
+ ];
496
579
  };
497
- if (operationIds.length < documents.length)
580
+ 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.`;
581
+ if (operationIds.length < fresh.length)
498
582
  ctx.warn("The instance returned no operation id for some documents; it may be older than the operations API.");
499
583
  if (failure) {
500
584
  const refused = await deactivate(ctx, kb.id, matches);
@@ -503,7 +587,7 @@ export const kbUpload = {
503
587
  return {
504
588
  data: { ...summary(), error: failure.error.toJSON(), not_uploaded: failure.notUploaded },
505
589
  text: [
506
- `Uploaded ${documents.length} files, then: ${failure.error.message}`,
590
+ `Uploaded ${fileCount(documents.length)}, then: ${failure.error.message}`,
507
591
  `Not uploaded (${failure.notUploaded.length}): ${failure.notUploaded.join(", ")}`,
508
592
  ...matchLines(),
509
593
  ...(operationIds.length ? [`Wait for the uploaded ones with: cavelon wait ${operationIds.join(" ")}`] : []),
@@ -520,9 +604,10 @@ export const kbUpload = {
520
604
  m.outcome = "stays_active";
521
605
  if (refused)
522
606
  ctx.warn(`The old documents stay active: ${refused.message}`);
607
+ await refreshStatuses(ctx, kb.id, documents);
523
608
  return {
524
609
  data: { ...summary(), ...waited.data },
525
- text: [`Uploaded ${documents.length} files.`, ...matchLines(), waited.text].join("\n"),
610
+ text: [uploadedText(""), ...matchLines(), waited.text].join("\n"),
526
611
  exitCode: refused && waited.exitCode === ExitCode.ok ? refused.exitCode : waited.exitCode,
527
612
  };
528
613
  }
@@ -532,7 +617,7 @@ export const kbUpload = {
532
617
  return {
533
618
  data: summary(),
534
619
  text: [
535
- `Uploaded ${documents.length} files to ${kb.name ?? kb.id}.`,
620
+ uploadedText(` to ${kb.name ?? kb.id}`),
536
621
  ...matchLines(),
537
622
  ...(operationIds.length ? [`Operations: ${operationIds.length}`, `Wait with: cavelon wait ${operationIds.join(" ")}`] : []),
538
623
  ].join("\n"),
@@ -695,8 +780,7 @@ function summarizeTrace(t) {
695
780
  };
696
781
  }
697
782
  function outcomeOf(s) {
698
- const attributes = s.attributes_json;
699
- const outcome = attributes && typeof attributes === "object" ? attributes.knowledge_outcome : undefined;
783
+ const outcome = spanAttributes(s.attributes_json)?.knowledge_outcome;
700
784
  return typeof outcome === "string" && outcome ? outcome : null;
701
785
  }
702
786
  function knowledgeOutcomes(spans) {
@@ -725,6 +809,31 @@ function summarizeSpan(s, outcomes) {
725
809
  error,
726
810
  };
727
811
  }
812
+ function spanPick(s) {
813
+ if (s.error_json || s.status === "error" || s.status === "errored")
814
+ return "the one that failed";
815
+ if (s.span_type === "llm")
816
+ return "the last model call";
817
+ if (s.span_type === "retrieval")
818
+ return "the knowledge search";
819
+ return s.span_type ?? "a span";
820
+ }
821
+ function retrievalText(data, view) {
822
+ const head = keyValues([
823
+ ["span", `${data.span_id} (retrieval${data.name ? `, ${data.name}` : ""}${data.agent ? `, agent ${data.agent}` : ""})`],
824
+ ["status", data.status],
825
+ ["query", view.query ?? "not recorded"],
826
+ ["knowledge_outcome", view.knowledge_outcome ?? "not classified by the agent"],
827
+ ["hits", view.sources_total ?? view.source_count ?? view.sources.length],
828
+ ["retrieval_status", view.retrieval_status ?? undefined],
829
+ ["error", data.error ? JSON.stringify(data.error) : undefined],
830
+ ]);
831
+ const rows = retrievalRows(view);
832
+ const hits = rows.length ? `\n\n${table(rows, ["rank", "title", "score", "citable", ...(rows.some((r) => r.cited) ? ["cited"] : []), "document_id"])}` : "";
833
+ const more = view.sources_total && view.sources_total > rows.length ? `\n… ${view.sources_total - rows.length} more hits than the trace keeps` : "";
834
+ const outcome = view.knowledge_outcome ? `\n\nWhat it means: ${cavelonCommand("explain", view.knowledge_outcome)}` : "";
835
+ return `${head}${hits}${more}${outcome}\n\nEverything the span recorded: --json`;
836
+ }
728
837
  function detailOf(value, full) {
729
838
  if (full || value === null || value === undefined)
730
839
  return value ?? null;
@@ -771,13 +880,27 @@ async function capacityFooter(ctx, errors) {
771
880
  return "";
772
881
  return `\n\n${code}: ${capacityHint(code, await readLimits(ctx).catch(() => undefined))}`;
773
882
  }
774
- function notPassedLines(r, max) {
883
+ const ANSWER_CHARS = 300;
884
+ const PASSED_ANSWER_CHARS = 150;
885
+ function stepLines(r, full, answerChars = ANSWER_CHARS) {
886
+ const assertions = stepAssertions(r.judge_breakdown, full);
887
+ const count = assertionCount(assertions);
888
+ const lines = assertions.length ? [` Assertions${count ? ` (${count})` : ""}:`, ...assertions.map((a) => ` ${assertionLine(a)}`)] : [];
889
+ if (r.generated_answer)
890
+ lines.push(` Answer: ${clip(r.generated_answer.replace(/\s+/g, " ").trim(), full ? Number.MAX_SAFE_INTEGER : answerChars)}`);
891
+ return lines;
892
+ }
893
+ function notPassedLines(r, max, full) {
775
894
  const c = failedCase(r, max);
776
895
  const lines = [` ${caseLabel(c)} ${c.status}`];
777
896
  if (c.reason)
778
897
  lines.push(` ${c.reason}`);
779
- if (r.llm_judge_reasoning && r.llm_judge_reasoning !== r.error_message)
898
+ if (r.llm_judge_reasoning && r.error_message && r.llm_judge_reasoning !== r.error_message)
780
899
  lines.push(` Judge: ${clip(r.llm_judge_reasoning, max)}`);
900
+ const knowledge = caseKnowledgeOutcomes(r);
901
+ if (knowledge)
902
+ lines.push(` Knowledge: ${knowledge.join(", ")}`);
903
+ lines.push(...stepLines(r, full));
781
904
  if (r.agent_slug)
782
905
  lines.push(` Answered by: ${r.agent_slug}`);
783
906
  const open = caseTraceCommand(r);
@@ -785,9 +908,13 @@ function notPassedLines(r, max) {
785
908
  lines.push(` Its traces (${open.label}): ${open.command}`);
786
909
  return lines;
787
910
  }
788
- function judgedLines(r, max) {
911
+ function judgedLines(r, max, full) {
789
912
  const score = r.llm_judge_score === null || r.llm_judge_score === undefined ? "" : ` score ${r.llm_judge_score}`;
790
- return [` ${caseLabel(failedCase(r))} ${r.status}${score}`, ` Judge: ${clip(r.llm_judge_reasoning, max)}`];
913
+ return [
914
+ ` ${caseLabel(failedCase(r))} ${r.status}${score}`,
915
+ ...(r.llm_judge_reasoning ? [` Judge: ${clip(r.llm_judge_reasoning, max)}`] : []),
916
+ ...stepLines(r, full, PASSED_ANSWER_CHARS),
917
+ ];
791
918
  }
792
919
  async function testRunView(ctx, id, results, options) {
793
920
  const max = options.full ? Number.MAX_SAFE_INTEGER : 1000;
@@ -801,12 +928,15 @@ async function testRunView(ctx, id, results, options) {
801
928
  conversation_id: r.conversation_id ?? null,
802
929
  run_id: r.agent_run_id ?? null,
803
930
  error: r.error_message ? clip(r.error_message, 200) : null,
931
+ answer: r.generated_answer ? clip(r.generated_answer, options.full ? max : ANSWER_CHARS) : null,
932
+ assertions: stepAssertions(r.judge_breakdown, options.full),
804
933
  judge_reasoning: r.llm_judge_reasoning ? clip(r.llm_judge_reasoning, max) : null,
934
+ knowledge_outcomes: caseKnowledgeOutcomes(r),
805
935
  trace_command: caseTraceCommand(r)?.command ?? null,
806
936
  ...(NOT_PASSED.has(r.status) ? { reason: failedCase(r, max).reason, judge_breakdown: detailOf(r.judge_breakdown, options.full) } : {}),
807
937
  }));
808
938
  const notPassed = page.items.filter((r) => NOT_PASSED.has(r.status));
809
- const judged = page.items.filter((r) => !NOT_PASSED.has(r.status) && r.llm_judge_reasoning);
939
+ const judged = page.items.filter((r) => !NOT_PASSED.has(r.status) && (r.llm_judge_reasoning || stepAssertions(r.judge_breakdown).length || r.generated_answer));
810
940
  const byConversation = page.items.find((r) => r.conversation_id);
811
941
  const byRun = page.items.find((r) => !r.conversation_id && r.agent_run_id);
812
942
  const where = [
@@ -817,8 +947,8 @@ async function testRunView(ctx, id, results, options) {
817
947
  data: { kind: "test", run_id: id, results: { ...page, items } },
818
948
  text: table(items, ["case", "step", "status", "score", ...(items.some((r) => r.agent) ? ["agent"] : []), ...(items.some((r) => r.run_id) ? ["run_id"] : []), "conversation_id"]) +
819
949
  moreHint(page.next_cursor, cavelonCommand("trace", id, "--kind", "test")) +
820
- (notPassed.length ? `\n\nDid not pass:\n${notPassed.flatMap((r) => notPassedLines(r, max)).join("\n")}` : "") +
821
- (judged.length ? `\n\nJudge's reasoning:\n${judged.flatMap((r) => judgedLines(r, options.full ? max : 300)).join("\n")}` : "") +
950
+ (notPassed.length ? `\n\nDid not pass:\n${notPassed.flatMap((r) => notPassedLines(r, max, options.full)).join("\n")}` : "") +
951
+ (judged.length ? `\n\nPassed:\n${judged.flatMap((r) => judgedLines(r, options.full ? max : 300, options.full)).join("\n")}` : "") +
822
952
  `\n\n${where.length ? where.join("\n") : "The instance recorded no conversation or run for these results, so they have no trace to open."}` +
823
953
  (await capacityFooter(ctx, items.map((r) => r.error))),
824
954
  };
@@ -899,26 +1029,30 @@ export const trace = {
899
1029
  if (!span)
900
1030
  throw new CavelonError(ExitCode.failure, { code: "span_not_found", message: `No span ${spanId} in trace ${traceId}.` });
901
1031
  const full = boolOption(input, "full");
1032
+ const attributes = spanAttributes(span.attributes_json) ?? span.attributes_json;
1033
+ const retrieval = span.span_type === "retrieval" ? retrievalView(spanAttributes(span.attributes_json)) : undefined;
902
1034
  const data = {
903
1035
  ...summarizeSpan(span, outcomes),
904
1036
  model: span.model ?? null,
905
1037
  parent_span_id: span.parent_span_id ?? null,
906
1038
  input: detailOf(span.input_json, full),
907
1039
  output: detailOf(span.output_json, full),
908
- attributes: detailOf(span.attributes_json, full),
1040
+ attributes: detailOf(attributes, full),
1041
+ ...(retrieval ? { retrieval } : {}),
909
1042
  tokens: span.token_usage_json ?? null,
910
1043
  error: span.error_json ?? null,
911
1044
  };
912
- return { data, text: JSON.stringify(data, null, 2) };
1045
+ return { data, text: retrieval ? retrievalText(data, retrieval) : JSON.stringify(data, null, 2) };
913
1046
  }
914
1047
  const page = pageOf(spans.map((s) => summarizeSpan(s, outcomes)), limit, cursor);
915
1048
  const base = cavelonCommand("trace", id, ...(kind ? ["--kind", kind] : []), "--trace", traceId);
1049
+ const open = suggestedSpan(spans);
916
1050
  return {
917
1051
  data: { trace: summarizeTrace(detail), spans: page },
918
1052
  text: `${keyValues(Object.entries(summarizeTrace(detail)))}\n\n` +
919
1053
  table(page.items, ["seq", "type", "name", "status", ...(outcomes.size ? ["knowledge_outcome"] : []), "duration_ms", "span_id"]) +
920
1054
  moreHint(page.next_cursor, base) +
921
- (page.items.length ? `\n\nOne span in full, by the span_id in its row: ${base} --span ${shellWord(page.items[0].span_id)}` : ""),
1055
+ (open ? `\n\nOne span in full (${spanPick(open)}), by the span_id in its row: ${base} --span ${shellWord(open.id)}` : ""),
922
1056
  };
923
1057
  }
924
1058
  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/format.js CHANGED
@@ -1,13 +1,13 @@
1
1
  import { shellWord } from "./shell.js";
2
- export function table(rows, columns, maxWidth = 60) {
2
+ export function table(rows, columns, maxWidth = 60, whole = []) {
3
3
  if (rows.length === 0)
4
4
  return "";
5
- const cell = (value) => {
5
+ const cell = (value, column) => {
6
6
  const text = value === null || value === undefined ? "" : typeof value === "object" ? JSON.stringify(value) : String(value);
7
7
  const oneLine = text.replace(/\s+/g, " ");
8
- return oneLine.length > maxWidth ? `${oneLine.slice(0, maxWidth - 1)}…` : oneLine;
8
+ return oneLine.length > maxWidth && !whole.includes(column) ? `${oneLine.slice(0, maxWidth - 1)}…` : oneLine;
9
9
  };
10
- const cells = rows.map((row) => columns.map((c) => cell(row[c])));
10
+ const cells = rows.map((row) => columns.map((c) => cell(row[c], c)));
11
11
  const widths = columns.map((c, i) => Math.max(c.length, ...cells.map((r) => r[i].length)));
12
12
  const line = (values) => values
13
13
  .map((v, i) => (i === values.length - 1 ? v : v.padEnd(widths[i])))