@cavelon/cli 0.1.5 → 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.
@@ -1,5 +1,6 @@
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";
@@ -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,7 +242,7 @@ 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
247
  examples: ["cavelon harness default support", "cavelon harness default support --confirm"],
236
248
  async run(ctx, input) {
@@ -238,6 +250,8 @@ export const harnessDefault = {
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
256
  if (!harness)
243
257
  throw harnessNotFoundError(ref, candidates, undefined, (slug) => cavelonCommand("harness", "default", slug));
@@ -248,15 +262,32 @@ export const harnessDefault = {
248
262
  return { data: { changed: false, already_default: true, harness: target, default_route: current }, text: `${named(harness)} is already the tenant's default route.` };
249
263
  }
250
264
  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")) {
265
+ if (harness.status !== "active") {
266
+ throw new CavelonError(ExitCode.conflict, {
267
+ code: "solution_not_active",
268
+ message: `${named(harness)} is ${harness.status}, and only an active solution can be the tenant's default route; nothing was changed.`,
269
+ hint: `Activate it through the readiness gate and preview the default route in one step: ${cavelonCommand("activate", "--harness", harness.slug, "--make-default")}. ` +
270
+ `The default route stays ${current ? named(current) : "as it is"} until then.`,
271
+ details: { harness: target, default_route: current },
272
+ });
273
+ }
274
+ const gate = await confirmation(ctx, input, "harness_default", { harness: harness.id, from: current?.id ?? null });
275
+ if (!gate.confirmed) {
253
276
  return {
254
- data: { changed: false, harness: target, default_route: current, default_known: route.known, confirm: commands.confirm, ...(draft ? { note: draft } : {}) },
277
+ data: {
278
+ changed: false,
279
+ harness: target,
280
+ default_route: current,
281
+ default_known: route.known,
282
+ confirm: gate.confirm(commands.confirm),
283
+ ...gate.fields,
284
+ },
255
285
  text: [
256
286
  defaultChangeLine(harness, route),
257
- ...(draft ? [draft] : []),
258
- `Show this to a person; with their yes: ${commands.confirm}`,
287
+ ...(gate.mismatch ? [gate.mismatch] : []),
288
+ `Show this to a person; with their yes: ${gate.confirm(commands.confirm)}`,
259
289
  ].join("\n"),
290
+ ...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
260
291
  };
261
292
  }
262
293
  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. Run by a coding agent: the token its preview printed.",
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) {
@@ -171,11 +176,13 @@ export const variablesDelete = {
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 {
@@ -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 {
@@ -2,14 +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
10
  import { callStable, workflowOperation } from "../invoke.js";
9
11
  import { deref } from "../openapi.js";
10
12
  import { bindsNow, changedBy, limitError, limitsOrWarn, readLimits } from "../limits.js";
11
13
  import { getOperation } from "../operations.js";
12
- import { caseCounts, caseLabel, countsText, failedCase, NOT_PASSED, runVerdict } from "../results.js";
14
+ import { caseCounts, caseLabel, countsText, failedCase, caseKnowledgeOutcomes, NOT_PASSED, runVerdict } from "../results.js";
13
15
  import { isUuid } from "../session.js";
14
16
  import { cavelonCommand, shellWord } from "../shell.js";
15
17
  import { readZipSummary, ZipError } from "../zip.js";
@@ -17,6 +19,28 @@ import { TIMEOUT_OPTION, timeoutMs, waitAndReport } from "./async.js";
17
19
  import { stageErrors, stageErrorText } from "./loops.js";
18
20
  import { resolveHarnessId } from "../harness-ref.js";
19
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
+ }
20
44
  const UPLOAD_ROUTE = "/api/v1/knowledge-bases/{kb_id}/documents/upload";
21
45
  const DOCUMENTS_ROUTE = "/api/v1/knowledge-bases/{kb_id}/documents";
22
46
  const ACTIVE_ROUTE = "/api/v1/knowledge-bases/{kb_id}/documents/active";
@@ -364,7 +388,7 @@ export const kbUpload = {
364
388
  ext: { type: "string", multiple: true, value: "<ext>", description: "Only these file extensions (pdf, md, …)." },
365
389
  replace: { type: "boolean", description: "Replace active documents with the same file name." },
366
390
  "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." },
391
+ confirm: { type: "boolean", mcpToken: true, description: "With --replace, deactivate the old documents the instance does not replace itself; without it nothing is sent." },
368
392
  "dry-run": { type: "boolean", description: "List what would be uploaded and replaced, upload nothing." },
369
393
  wait: WAIT_OPTION,
370
394
  timeout: TIMEOUT_OPTION,
@@ -413,7 +437,7 @@ export const kbUpload = {
413
437
  return {
414
438
  data: { kb: kbRef, files: rel, count: rel.length, dry_run: true, existing: planned },
415
439
  text: [
416
- `Would upload ${rel.length} files:`,
440
+ `Would upload ${fileCount(rel.length)}:`,
417
441
  ...rel,
418
442
  ...matches.map(plannedLine),
419
443
  ...(hint ? [hint] : []),
@@ -421,15 +445,18 @@ export const kbUpload = {
421
445
  ].join("\n"),
422
446
  };
423
447
  }
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");
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"));
426
451
  return {
427
- data: { kb: { id: kb.id, name: kb.name ?? null }, files: rel, count: rel.length, uploaded: false, existing: planned, confirm },
452
+ data: { kb: { id: kb.id, name: kb.name ?? null }, files: rel, count: rel.length, uploaded: false, existing: planned, confirm, ...gate.fields },
428
453
  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:`,
454
+ `--replace uploads ${fileCount(rel.length)} and then deactivates ${deactivations.length} document${deactivations.length === 1 ? "" : "s"} the instance's upload does not replace itself:`,
430
455
  ...matches.map(plannedLine),
456
+ ...(gate.mismatch ? [gate.mismatch] : []),
431
457
  `Nothing was sent. Upload and deactivate with: ${confirm}`,
432
458
  ].join("\n"),
459
+ ...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
433
460
  };
434
461
  }
435
462
  const batches = [];
@@ -478,6 +505,10 @@ export const kbUpload = {
478
505
  }
479
506
  settleMatches(matches, documents, uploadedFiles);
480
507
  const operationIds = documents.map((d) => d.operation_id).filter((id) => Boolean(id));
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;
481
512
  const summary = () => ({
482
513
  kb: { id: kb.id, name: kb.name ?? null },
483
514
  documents: documents.map((d) => ({
@@ -485,6 +516,7 @@ export const kbUpload = {
485
516
  filename: d.filename,
486
517
  status: d.status,
487
518
  operation_id: d.operation_id ?? null,
519
+ upload_outcome: outcomes.get(d) ?? null,
488
520
  ...(Array.isArray(d.replaced_document_ids) ? { replaced_document_ids: d.replaced_document_ids } : {}),
489
521
  })),
490
522
  operation_ids: operationIds,
@@ -492,8 +524,13 @@ export const kbUpload = {
492
524
  });
493
525
  const matchLines = () => {
494
526
  const note = staysActiveHint(matches, mode);
495
- return [...matches.map(outcomeLine), ...(note ? [note] : [])];
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
+ ];
496
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.`;
497
534
  if (operationIds.length < documents.length)
498
535
  ctx.warn("The instance returned no operation id for some documents; it may be older than the operations API.");
499
536
  if (failure) {
@@ -503,7 +540,7 @@ export const kbUpload = {
503
540
  return {
504
541
  data: { ...summary(), error: failure.error.toJSON(), not_uploaded: failure.notUploaded },
505
542
  text: [
506
- `Uploaded ${documents.length} files, then: ${failure.error.message}`,
543
+ `Uploaded ${fileCount(documents.length)}, then: ${failure.error.message}`,
507
544
  `Not uploaded (${failure.notUploaded.length}): ${failure.notUploaded.join(", ")}`,
508
545
  ...matchLines(),
509
546
  ...(operationIds.length ? [`Wait for the uploaded ones with: cavelon wait ${operationIds.join(" ")}`] : []),
@@ -520,9 +557,10 @@ export const kbUpload = {
520
557
  m.outcome = "stays_active";
521
558
  if (refused)
522
559
  ctx.warn(`The old documents stay active: ${refused.message}`);
560
+ await refreshStatuses(ctx, kb.id, documents);
523
561
  return {
524
562
  data: { ...summary(), ...waited.data },
525
- text: [`Uploaded ${documents.length} files.`, ...matchLines(), waited.text].join("\n"),
563
+ text: [uploadedText(""), ...matchLines(), waited.text].join("\n"),
526
564
  exitCode: refused && waited.exitCode === ExitCode.ok ? refused.exitCode : waited.exitCode,
527
565
  };
528
566
  }
@@ -532,7 +570,7 @@ export const kbUpload = {
532
570
  return {
533
571
  data: summary(),
534
572
  text: [
535
- `Uploaded ${documents.length} files to ${kb.name ?? kb.id}.`,
573
+ uploadedText(` to ${kb.name ?? kb.id}`),
536
574
  ...matchLines(),
537
575
  ...(operationIds.length ? [`Operations: ${operationIds.length}`, `Wait with: cavelon wait ${operationIds.join(" ")}`] : []),
538
576
  ].join("\n"),
@@ -695,8 +733,7 @@ function summarizeTrace(t) {
695
733
  };
696
734
  }
697
735
  function outcomeOf(s) {
698
- const attributes = s.attributes_json;
699
- const outcome = attributes && typeof attributes === "object" ? attributes.knowledge_outcome : undefined;
736
+ const outcome = spanAttributes(s.attributes_json)?.knowledge_outcome;
700
737
  return typeof outcome === "string" && outcome ? outcome : null;
701
738
  }
702
739
  function knowledgeOutcomes(spans) {
@@ -725,6 +762,31 @@ function summarizeSpan(s, outcomes) {
725
762
  error,
726
763
  };
727
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
+ }
728
790
  function detailOf(value, full) {
729
791
  if (full || value === null || value === undefined)
730
792
  return value ?? null;
@@ -771,13 +833,27 @@ async function capacityFooter(ctx, errors) {
771
833
  return "";
772
834
  return `\n\n${code}: ${capacityHint(code, await readLimits(ctx).catch(() => undefined))}`;
773
835
  }
774
- 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) {
775
847
  const c = failedCase(r, max);
776
848
  const lines = [` ${caseLabel(c)} ${c.status}`];
777
849
  if (c.reason)
778
850
  lines.push(` ${c.reason}`);
779
- 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)
780
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));
781
857
  if (r.agent_slug)
782
858
  lines.push(` Answered by: ${r.agent_slug}`);
783
859
  const open = caseTraceCommand(r);
@@ -785,9 +861,13 @@ function notPassedLines(r, max) {
785
861
  lines.push(` Its traces (${open.label}): ${open.command}`);
786
862
  return lines;
787
863
  }
788
- function judgedLines(r, max) {
864
+ function judgedLines(r, max, full) {
789
865
  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)}`];
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
+ ];
791
871
  }
792
872
  async function testRunView(ctx, id, results, options) {
793
873
  const max = options.full ? Number.MAX_SAFE_INTEGER : 1000;
@@ -801,12 +881,15 @@ async function testRunView(ctx, id, results, options) {
801
881
  conversation_id: r.conversation_id ?? null,
802
882
  run_id: r.agent_run_id ?? null,
803
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),
804
886
  judge_reasoning: r.llm_judge_reasoning ? clip(r.llm_judge_reasoning, max) : null,
887
+ knowledge_outcomes: caseKnowledgeOutcomes(r),
805
888
  trace_command: caseTraceCommand(r)?.command ?? null,
806
889
  ...(NOT_PASSED.has(r.status) ? { reason: failedCase(r, max).reason, judge_breakdown: detailOf(r.judge_breakdown, options.full) } : {}),
807
890
  }));
808
891
  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);
892
+ const judged = page.items.filter((r) => !NOT_PASSED.has(r.status) && (r.llm_judge_reasoning || stepAssertions(r.judge_breakdown).length || r.generated_answer));
810
893
  const byConversation = page.items.find((r) => r.conversation_id);
811
894
  const byRun = page.items.find((r) => !r.conversation_id && r.agent_run_id);
812
895
  const where = [
@@ -817,8 +900,8 @@ async function testRunView(ctx, id, results, options) {
817
900
  data: { kind: "test", run_id: id, results: { ...page, items } },
818
901
  text: table(items, ["case", "step", "status", "score", ...(items.some((r) => r.agent) ? ["agent"] : []), ...(items.some((r) => r.run_id) ? ["run_id"] : []), "conversation_id"]) +
819
902
  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")}` : "") +
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")}` : "") +
822
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."}` +
823
906
  (await capacityFooter(ctx, items.map((r) => r.error))),
824
907
  };
@@ -899,26 +982,30 @@ export const trace = {
899
982
  if (!span)
900
983
  throw new CavelonError(ExitCode.failure, { code: "span_not_found", message: `No span ${spanId} in trace ${traceId}.` });
901
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;
902
987
  const data = {
903
988
  ...summarizeSpan(span, outcomes),
904
989
  model: span.model ?? null,
905
990
  parent_span_id: span.parent_span_id ?? null,
906
991
  input: detailOf(span.input_json, full),
907
992
  output: detailOf(span.output_json, full),
908
- attributes: detailOf(span.attributes_json, full),
993
+ attributes: detailOf(attributes, full),
994
+ ...(retrieval ? { retrieval } : {}),
909
995
  tokens: span.token_usage_json ?? null,
910
996
  error: span.error_json ?? null,
911
997
  };
912
- return { data, text: JSON.stringify(data, null, 2) };
998
+ return { data, text: retrieval ? retrievalText(data, retrieval) : JSON.stringify(data, null, 2) };
913
999
  }
914
1000
  const page = pageOf(spans.map((s) => summarizeSpan(s, outcomes)), limit, cursor);
915
1001
  const base = cavelonCommand("trace", id, ...(kind ? ["--kind", kind] : []), "--trace", traceId);
1002
+ const open = suggestedSpan(spans);
916
1003
  return {
917
1004
  data: { trace: summarizeTrace(detail), spans: page },
918
1005
  text: `${keyValues(Object.entries(summarizeTrace(detail)))}\n\n` +
919
1006
  table(page.items, ["seq", "type", "name", "status", ...(outcomes.size ? ["knowledge_outcome"] : []), "duration_ms", "span_id"]) +
920
1007
  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)}` : ""),
1008
+ (open ? `\n\nOne span in full (${spanPick(open)}), by the span_id in its row: ${base} --span ${shellWord(open.id)}` : ""),
922
1009
  };
923
1010
  }
924
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
+ }
@@ -40,7 +40,7 @@ export function harnessNotFoundError(ref, candidates, source, command) {
40
40
  code: "solution_not_found",
41
41
  message: `No solution "${ref}" in this tenant${source ? ` (from ${source})` : ""}.${near ? ` Closest: ${near}.` : ""}`,
42
42
  hint: (candidates.length ? `If you meant one of them:\n${lines}\n` : "") +
43
- "`cavelon harness list` shows this tenant's solutions with name, slug and id; `cavelon harness new <slug>` creates one, and an env file's harness is created by `apply`.",
43
+ "`cavelon harness list` shows this tenant's solutions with name, slug and id; `cavelon harness new <slug> --name <name>` creates one as a draft (`cavelon init --harness <name>` does too).",
44
44
  details: candidates.length ? { candidates: candidates.map((h) => ({ id: h.id, slug: h.slug, name: h.name })) } : undefined,
45
45
  });
46
46
  }
@@ -52,3 +52,16 @@ export async function resolveHarnessId(ctx, ref) {
52
52
  throw harnessNotFoundError(ref, candidates);
53
53
  return harness.id;
54
54
  }
55
+ export function slugFromName(name) {
56
+ const plain = name.normalize("NFKD").replace(/[\u0300-\u036f]/g, "").toLowerCase();
57
+ let slug = plain.replace(/[^a-z0-9]+/g, "-");
58
+ while (slug.startsWith("-"))
59
+ slug = slug.slice(1);
60
+ while (slug.endsWith("-"))
61
+ slug = slug.slice(0, -1);
62
+ slug = slug.slice(0, 60);
63
+ while (slug.endsWith("-"))
64
+ slug = slug.slice(0, -1);
65
+ return slug;
66
+ }
67
+ export const SLUG = /^[a-z0-9][a-z0-9-]*$/;
package/dist/kit-codes.js CHANGED
@@ -34,7 +34,7 @@ export const KIT_ERROR_CODES = [
34
34
  { code: "operation_gone", area: "cli", message: "The operation no longer exists on the instance.", hint: "Start the work again; `cavelon status` lists the running operations." },
35
35
  { code: "stream_error", area: "cli", message: "The event stream of an operation broke off.", hint: "`cavelon wait <op_id>` polls instead." },
36
36
  { code: "no_solution", area: "cli", message: "This folder is not a Cavelon solution (no cavelon.yaml here or above).", hint: "Run `cavelon init`; `cavelon harness list` shows the tenant's solutions." },
37
- { code: "solution_not_found", area: "cli", message: "No solution by that name, slug or id in this tenant.", hint: "`cavelon harness list` shows them; `cavelon apply --env <name>` creates the one an env file names." },
37
+ { code: "solution_not_found", area: "cli", message: "No solution by that name, slug or id in this tenant.", hint: "`cavelon harness list` shows them; `cavelon harness new <slug> --name <name>` creates one as a draft, which apply never does." },
38
38
  { code: "project_file_invalid", area: "cli", message: "cavelon.yaml is not a valid YAML mapping.", hint: "Fix the file at the place the message names." },
39
39
  { code: "project_file_has_secret", area: "cli", message: "cavelon.yaml holds a credential; solution files never do.", hint: "Remove it, revoke the token, and use `cavelon login` or CAVELON_TOKEN instead." },
40
40
  { code: "env_file_invalid", area: "cli", message: "An env/<name>.yaml file is invalid (not a mapping, a runtime binding that is not a resource id, or an unknown mode).", hint: "Fix the field the message names." },
@@ -52,6 +52,12 @@ export const KIT_ERROR_CODES = [
52
52
  { code: "preview_unknown", area: "cli", message: "No open preview with that id in this solution.", hint: "Run `cavelon apply` for a new preview and confirm its id; `cavelon status` lists the open ones." },
53
53
  { code: "preview_other_instance", area: "cli", message: "The preview was made on another instance.", hint: "Confirm it with the instance it was made on, or preview again here." },
54
54
  { code: "preview_other_tenant", area: "cli", message: "The preview was made for another tenant than this command acts in.", hint: "Run the confirm command the preview printed (it names --env and --tenant), or preview again here." },
55
+ { code: "preview_files_changed", area: "cli", message: "The package files changed since the preview; nothing was imported.", hint: "Run `cavelon apply` for a preview of the files as they are now, show it, and confirm its id; --allow-stale with --confirm imports what the old preview showed." },
56
+ { code: "preview_expired", area: "cli", message: "The preview is older than the kit keeps previews; nothing was imported.", hint: "Run `cavelon apply` for a new preview, show it, and confirm its id." },
57
+ { code: "confirm_token_required", area: "cli", message: "Over MCP, or run by a coding agent in its shell, a changing command confirms only with the token its preview returned, never with true or a bare --confirm.", hint: "Call the tool (or run the command) without confirm, show the person the preview, then call it again with the same arguments and confirm set to its confirm_token (--confirm <token> in a shell)." },
58
+ { code: "unknown_argument", area: "cli", message: "An MCP tool was called with an argument its schema does not list; nothing was done.", hint: "Call it again with the argument the error names (the tool's schema lists them all), spelled in snake_case." },
59
+ { code: "solution_not_active", area: "cli", message: "Only an active solution can be the tenant's default route; this one is a draft (or archived), so nothing was changed.", hint: "Activate it through the readiness gate and preview the default route in one step: `cavelon activate --harness <slug> --make-default`." },
60
+ { code: "default_route_deactivate", area: "cli", message: "The solution is the tenant's default route, so deactivate refused it; nothing was changed.", hint: "Ask the person which solution should answer in the tenant's chat and widget instead, make it the default (`cavelon harness default <solution>`), then deactivate." },
55
61
  { code: "default_route_unknown", area: "cli", message: "The instance does not say which solution is the tenant's default route (no is_default in its solution list).", hint: "The instance may be older than default routes; check the default in the Admin." },
56
62
  { code: "limit_not_found", area: "cli", message: "The instance lists no limit by that key.", hint: "`cavelon limits` lists the keys." },
57
63
  { code: "limit_changed_by_operator", area: "cli", message: "The limit is not the tenant's to change: the operator sets it; nothing was sent.", hint: "Ask the instance's operator; `cavelon limits --key <key>` says who changes it and how." },
@@ -35,16 +35,25 @@ export async function fileDigests(root, files) {
35
35
  }
36
36
  return digests;
37
37
  }
38
- export async function writePulledFiles(root, files) {
39
- await writeState(root, PULLED_FILES, JSON.stringify({ digests: await fileDigests(root, files) }, null, 2));
38
+ const readPulled = async (root) => (await readJsonFile(path.join(stateDir(root), PULLED_FILES))) ?? {};
39
+ export async function writePulledFiles(root, files, items) {
40
+ const kept = items ?? (await readPulled(root)).items;
41
+ await writeState(root, PULLED_FILES, JSON.stringify({ digests: await fileDigests(root, files), ...(kept ? { items: kept } : {}) }, null, 2));
40
42
  }
41
- export async function rememberAppliedFiles(root, digests) {
42
- const known = await readPulledFiles(root);
43
- await writeState(root, PULLED_FILES, JSON.stringify({ digests: { ...known, ...digests } }, null, 2));
43
+ export async function readItemFiles(root) {
44
+ const items = (await readPulled(root)).items;
45
+ return items && typeof items === "object" && !Array.isArray(items) ? items : {};
46
+ }
47
+ export async function rememberAppliedFiles(root, known, unknown = []) {
48
+ const digests = { ...(await readPulledFiles(root)), ...known };
49
+ for (const file of unknown)
50
+ delete digests[file];
51
+ const items = (await readPulled(root)).items;
52
+ await writeState(root, PULLED_FILES, JSON.stringify({ digests, ...(items ? { items } : {}) }, null, 2));
44
53
  }
45
54
  export async function readPulledFiles(root) {
46
- const stored = await readJsonFile(path.join(stateDir(root), PULLED_FILES));
47
- return stored?.digests && typeof stored.digests === "object" ? stored.digests : {};
55
+ const stored = await readPulled(root);
56
+ return stored.digests && typeof stored.digests === "object" ? stored.digests : {};
48
57
  }
49
58
  export function digest(value) {
50
59
  return createHash("sha256").update(JSON.stringify(value)).digest("hex");
@@ -66,7 +75,15 @@ export async function loadPreview(root, previewId) {
66
75
  export async function deletePreview(root, previewId) {
67
76
  await fs.rm(previewFile(root, previewId), { force: true });
68
77
  }
69
- export async function listPreviews(root) {
78
+ export const PREVIEW_MAX_AGE_MS = 24 * 60 * 60 * 1000;
79
+ export function previewExpiry(createdAt, now) {
80
+ const created = Date.parse(createdAt);
81
+ if (Number.isNaN(created))
82
+ return { expires_at: null, expired: true };
83
+ const expires = created + PREVIEW_MAX_AGE_MS;
84
+ return { expires_at: new Date(expires).toISOString(), expired: now.getTime() >= expires };
85
+ }
86
+ export async function listPreviews(root, now) {
70
87
  const dir = path.join(stateDir(root), "previews");
71
88
  let names;
72
89
  try {
@@ -78,8 +95,9 @@ export async function listPreviews(root) {
78
95
  const out = [];
79
96
  for (const name of names.filter((n) => n.endsWith(".json"))) {
80
97
  const stored = await readJsonFile(path.join(dir, name));
81
- if (stored?.preview_id)
82
- out.push({ preview_id: stored.preview_id, created_at: stored.created_at, env: stored.env, harness: stored.harness });
98
+ if (stored?.preview_id) {
99
+ out.push({ preview_id: stored.preview_id, created_at: stored.created_at, env: stored.env, harness: stored.harness, ...previewExpiry(stored.created_at, now) });
100
+ }
83
101
  }
84
102
  return out.sort((a, b) => (a.created_at < b.created_at ? 1 : -1));
85
103
  }