@cavelon/cli 0.1.6 → 0.1.8

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.
@@ -13,7 +13,7 @@ export const ENV_OPTION = { type: "string", value: "<name>", description: "Act i
13
13
  const CONFIRM_OPTION = {
14
14
  type: "boolean",
15
15
  mcpToken: true,
16
- description: "Delete it; without this nothing is deleted. Run by a coding agent: the token its preview printed.",
16
+ description: "Delete it; without this nothing is deleted.",
17
17
  };
18
18
  const TOKEN_PREFIXES = ["cbp_", "cvpat_"];
19
19
  const LIST_VALUE_CHARS = 200;
@@ -169,7 +169,7 @@ export const variablesDelete = {
169
169
  mcpTool: false,
170
170
  positionals: [{ name: "name", description: "The variable's name.", required: true }],
171
171
  options: { confirm: CONFIRM_OPTION, env: ENV_OPTION },
172
- 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>"],
173
173
  async run(ctx, input) {
174
174
  const name = positional(input, "name");
175
175
  const flags = targetFlags(await ctx.session());
@@ -361,7 +361,7 @@ export const secretsDelete = {
361
361
  mcpTool: false,
362
362
  positionals: [{ name: "name", description: "The secret's name.", required: true }],
363
363
  options: { confirm: CONFIRM_OPTION, env: ENV_OPTION },
364
- 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>"],
365
365
  async run(ctx, input) {
366
366
  const name = positional(input, "name");
367
367
  await requirePerson(ctx, "delete", name);
@@ -1,4 +1,5 @@
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";
@@ -62,6 +63,32 @@ async function existingDocuments(ctx, kbId) {
62
63
  return undefined;
63
64
  }
64
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
+ }
65
92
  function nameMatches(files, cwd, existing, mode, support) {
66
93
  const matches = [];
67
94
  const mapped = new Set();
@@ -378,7 +405,9 @@ export const kbUpload = {
378
405
  "A file named like an active document of the knowledge base is listed, with what happens to that document. An\n" +
379
406
  "instance that replaces same-named documents on upload does so (--keep-both keeps both); elsewhere the old one stays\n" +
380
407
  "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.",
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.",
382
411
  readOnly: false,
383
412
  mcpTool: "kb_upload",
384
413
  positionals: [{ name: "dir", description: "Folder (or single file) to upload.", required: true }],
@@ -389,7 +418,7 @@ export const kbUpload = {
389
418
  replace: { type: "boolean", description: "Replace active documents with the same file name." },
390
419
  "keep-both": { type: "boolean", description: "Keep active documents with the same file name next to the new ones." },
391
420
  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." },
421
+ "dry-run": { type: "boolean", description: "List what would be uploaded, replaced and found identical; upload nothing." },
393
422
  wait: WAIT_OPTION,
394
423
  timeout: TIMEOUT_OPTION,
395
424
  },
@@ -431,17 +460,30 @@ export const kbUpload = {
431
460
  const matches = existing ? nameMatches(files, ctx.io.cwd, existing, mode, support) : [];
432
461
  const rel = files.map((f) => path.relative(ctx.io.cwd, f) || f);
433
462
  const planned = matches.map(({ outcome: _outcome, ...m }) => m);
434
- const hint = staysActiveHint(matches, mode);
435
463
  const deactivations = matches.filter((m) => m.plan === "deactivate");
436
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");
437
470
  return {
438
- 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
+ },
439
480
  text: [
440
481
  `Would upload ${fileCount(rel.length)}:`,
441
482
  ...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.`] : []),
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.`] : []),
445
487
  ].join("\n"),
446
488
  };
447
489
  }
@@ -504,11 +546,16 @@ export const kbUpload = {
504
546
  }
505
547
  }
506
548
  settleMatches(matches, documents, uploadedFiles);
507
- const operationIds = documents.map((d) => d.operation_id).filter((id) => Boolean(id));
508
549
  const before = new Set((existing ?? []).map((d) => d.id));
509
550
  const outcomes = new Map(documents.map((d) => [d, uploadOutcomeOf(d, before)]));
510
551
  const deduplicated = documents.filter((d) => outcomes.get(d) === "deduplicated");
511
- const created = documents.length - deduplicated.length;
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;
512
559
  const summary = () => ({
513
560
  kb: { id: kb.id, name: kb.name ?? null },
514
561
  documents: documents.map((d) => ({
@@ -526,12 +573,12 @@ export const kbUpload = {
526
573
  const note = staysActiveHint(matches, mode);
527
574
  return [
528
575
  ...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),
576
+ ...matches.filter((m) => m.outcome !== "identical").map(outcomeLine),
530
577
  ...(note ? [note] : []),
531
578
  ];
532
579
  };
533
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.`;
534
- if (operationIds.length < documents.length)
581
+ if (operationIds.length < fresh.length)
535
582
  ctx.warn("The instance returned no operation id for some documents; it may be older than the operations API.");
536
583
  if (failure) {
537
584
  const refused = await deactivate(ctx, kb.id, matches);
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])))
@@ -1,7 +1,7 @@
1
1
  import { closest, displayName, exactMatch } from "./choose.js";
2
2
  import { CavelonError, ExitCode } from "./errors.js";
3
3
  import { callStable } from "./invoke.js";
4
- import { isUuid } from "./session.js";
4
+ import { contextFlags, isUuid } from "./session.js";
5
5
  import { shellWord } from "./shell.js";
6
6
  function notFound(error) {
7
7
  return error instanceof CavelonError && error.status === 404;
@@ -33,14 +33,14 @@ export async function lookupHarness(ctx, ref) {
33
33
  return { harness: hit, candidates: [] };
34
34
  return { candidates: closest(all, ref) };
35
35
  }
36
- export function harnessNotFoundError(ref, candidates, source, command) {
36
+ export function harnessNotFoundError(ref, candidates, source, command, flags = "") {
37
37
  const near = candidates.map(displayName).join(", ");
38
38
  const lines = candidates.map((h) => ` ${command ? command(h.slug) : `--harness ${shellWord(h.slug)}`}`).join("\n");
39
39
  return new CavelonError(ExitCode.failure, {
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> --name <name>` creates one as a draft (`cavelon init --harness <name>` does too).",
43
+ `\`cavelon harness list${flags}\` shows this tenant's solutions with name, slug and id; \`cavelon harness new <slug> --name <name>${flags}\` creates one as a draft.`,
44
44
  details: candidates.length ? { candidates: candidates.map((h) => ({ id: h.id, slug: h.slug, name: h.name })) } : undefined,
45
45
  });
46
46
  }
@@ -49,7 +49,7 @@ export async function resolveHarnessId(ctx, ref) {
49
49
  return ref;
50
50
  const { harness, candidates } = await lookupHarness(ctx, ref);
51
51
  if (!harness)
52
- throw harnessNotFoundError(ref, candidates);
52
+ throw harnessNotFoundError(ref, candidates, undefined, undefined, contextFlags(await ctx.session()));
53
53
  return harness.id;
54
54
  }
55
55
  export function slugFromName(name) {
package/dist/http.js CHANGED
@@ -215,6 +215,7 @@ export function errorFromResponse(status, body, what, headers, sent = {}) {
215
215
  let details;
216
216
  let blockers;
217
217
  let structured;
218
+ let changed;
218
219
  const pick = (source) => {
219
220
  if (typeof source.code === "string")
220
221
  code = source.code;
@@ -232,6 +233,9 @@ export function errorFromResponse(status, body, what, headers, sent = {}) {
232
233
  const detailed = blockerDetails(source.blocker_details);
233
234
  if (detailed.length)
234
235
  structured = detailed;
236
+ const what = Array.isArray(source.changed) ? source.changed.filter((c) => typeof c === "string" && c.trim() !== "") : [];
237
+ if (what.length)
238
+ changed = what;
235
239
  };
236
240
  if (body && typeof body === "object" && !Array.isArray(body)) {
237
241
  const map = body;
@@ -276,6 +280,8 @@ export function errorFromResponse(status, body, what, headers, sent = {}) {
276
280
  hint = ceiling.hint;
277
281
  details = details && typeof details === "object" ? { ...details, ...ceiling.details } : ceiling.details;
278
282
  }
283
+ if (changed)
284
+ details = details && typeof details === "object" && !Array.isArray(details) ? { ...details, changed } : { changed };
279
285
  if (status === 400 && !hint && message && /select a tenant|tenant context|X-Tenant-Id/i.test(message)) {
280
286
  hint = "Choose a tenant with `cavelon use` (it lists your tenants), --tenant or CAVELON_TENANT.";
281
287
  }
package/dist/kit-codes.js CHANGED
@@ -34,7 +34,8 @@ 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 harness new <slug> --name <name>` creates one as a draft, which apply never does." },
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; `cavelon init --harness <name> --new` creates it for a new folder, also beside a similar name." },
38
+ { code: "solution_exists", area: "cli", message: "`init --new` names a solution the tenant already has.", hint: "`cavelon init --harness <slug>` makes the folder that solution's; for a new one, give --new another name." },
38
39
  { 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
40
  { 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
41
  { 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." },
@@ -53,10 +54,13 @@ export const KIT_ERROR_CODES = [
53
54
  { 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
55
  { 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
56
  { 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." },
57
+ { code: "preview_superseded", area: "cli", message: "Another preview was imported after this one, so what it showed is no longer what an import would do; nothing was imported.", hint: "Run `cavelon apply` for a new preview, show it, and confirm its id." },
58
+ { code: "preview_applied", area: "cli", message: "The preview was imported already; nothing was imported again.", hint: "`cavelon apply` previews the files as they are now; confirm that preview's id." },
59
+ { code: "preview_discarded", area: "cli", message: "The preview was discarded (apply --discard); nothing was imported.", hint: "Run `cavelon apply` for a new preview, show it, and confirm its id." },
56
60
  { 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
61
  { 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
62
  { 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`." },
63
+ { code: "solution_not_active", area: "cli", message: "Only an active solution can be the tenant's default route; this one is not (a draft, or inactive after a deactivate), 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
64
  { 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." },
61
65
  { 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." },
62
66
  { code: "limit_not_found", area: "cli", message: "The instance lists no limit by that key.", hint: "`cavelon limits` lists the keys." },
@@ -75,6 +75,24 @@ export async function loadPreview(root, previewId) {
75
75
  export async function deletePreview(root, previewId) {
76
76
  await fs.rm(previewFile(root, previewId), { force: true });
77
77
  }
78
+ const RETIRED_PREVIEWS = "retired-previews.json";
79
+ const RETIRED_KEPT = 200;
80
+ async function readRetired(root) {
81
+ const stored = await readJsonFile(path.join(stateDir(root), RETIRED_PREVIEWS));
82
+ return Array.isArray(stored) ? stored.filter((r) => typeof r?.preview_id === "string") : [];
83
+ }
84
+ export async function retirePreviews(root, retired) {
85
+ if (!retired.length)
86
+ return;
87
+ for (const r of retired)
88
+ await deletePreview(root, r.preview_id);
89
+ const ids = new Set(retired.map((r) => r.preview_id));
90
+ const kept = (await readRetired(root)).filter((r) => !ids.has(r.preview_id));
91
+ await writeState(root, RETIRED_PREVIEWS, JSON.stringify([...kept, ...retired].slice(-RETIRED_KEPT), null, 2));
92
+ }
93
+ export async function retiredPreview(root, previewId) {
94
+ return (await readRetired(root)).find((r) => r.preview_id === previewId);
95
+ }
78
96
  export const PREVIEW_MAX_AGE_MS = 24 * 60 * 60 * 1000;
79
97
  export function previewExpiry(createdAt, now) {
80
98
  const created = Date.parse(createdAt);
package/dist/main.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { parseArgs } from "node:util";
2
- import { GLOBAL_OPTIONS } from "./command.js";
2
+ import { GLOBAL_OPTIONS, optionDescription, optionFlag, renameFormerOptions } from "./command.js";
3
3
  import { createContext, withWarnings } from "./context.js";
4
4
  import { CONFIRM_TOKEN } from "./confirm-token.js";
5
5
  import { asCavelonError, ExitCode, usageError } from "./errors.js";
@@ -36,7 +36,8 @@ export async function run(argv, io, commands = COMMANDS, updates = {}) {
36
36
  }
37
37
  const { spec, rest } = found;
38
38
  const early = [];
39
- const args = spec.preprocess ? spec.preprocess(rest, (message) => early.push(message)) : rest;
39
+ const renamed = renameFormerOptions(spec, rest, (message) => early.push(message));
40
+ const args = spec.preprocess ? spec.preprocess(renamed, (message) => early.push(message)) : renamed;
40
41
  const parsed = parse(spec, args);
41
42
  if (parsed.options.help === true) {
42
43
  io.stdout.write(commandHelp(spec));
@@ -247,10 +248,7 @@ export function usageLine(spec) {
247
248
  return parts.join(" ");
248
249
  }
249
250
  function optionLines(options) {
250
- const rows = Object.entries(options).map(([name, o]) => {
251
- const flag = `${o.short ? `-${o.short}, ` : ""}--${name}${o.type === "string" ? ` ${o.value ?? "<value>"}` : ""}`;
252
- return [flag, o.description + (o.multiple ? " Repeatable." : "")];
253
- });
251
+ const rows = Object.entries(options).map(([name, o]) => [optionFlag(name, o), optionDescription(name, o)]);
254
252
  const width = Math.max(...rows.map(([f]) => f.length));
255
253
  return rows.map(([f, d]) => ` ${f.padEnd(width)} ${d}`);
256
254
  }
package/dist/mcp.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
2
  import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
3
+ import { formerlyWarning } from "./command.js";
3
4
  import { MCP_MAX_WAIT_MS } from "./commands/async.js";
4
5
  import { createContext, withWarnings } from "./context.js";
5
6
  import { asCavelonError, CavelonError, ExitCode, usageError } from "./errors.js";
@@ -16,7 +17,9 @@ const INSTRUCTIONS = "Tools for one Cavelon instance, acting with the token a pe
16
17
  "confirm set to that token: show the person the preview first. The token confirms exactly the change the preview showed; " +
17
18
  "a different change needs a new preview, and confirm: true is refused. The default route " +
18
19
  "(harness_default, activate's make_default) decides which solution the tenant's chat and widget answer with: live traffic, " +
19
- "so ask the person, and confirm only with their yes; the same goes for deactivate, which takes a solution out of live traffic. " +
20
+ "so ask the person, and confirm only with their yes; the same goes for deactivate, which takes a solution out of live traffic " +
21
+ "(its status becomes inactive), and for apply with include_tenant_wide, which imports the tenant-wide sections (tenant_settings, " +
22
+ "model_registry, …) for every solution of the tenant. " +
20
23
  "chat sends one message to a solution and returns its answer: the way to try one that is not the default route. " +
21
24
  "kb_upload names files that match an active document of the knowledge base; with replace it replaces them, and where the " +
22
25
  "instance's upload cannot, it returns what it would deactivate and uploads nothing without its confirm_token. " +
@@ -91,20 +94,24 @@ export function toolFor(spec) {
91
94
  }
92
95
  function argumentsOf(spec, args, warn) {
93
96
  const properties = Object.keys(inputSchema(spec).properties ?? {});
97
+ const former = new Map(Object.entries(spec.options ?? {})
98
+ .filter(([, o]) => o.formerly && !o.cliOnly)
99
+ .map(([name, o]) => [propertyName(o.formerly), propertyName(name)]));
94
100
  const out = {};
95
101
  for (const [key, value] of Object.entries(args)) {
96
102
  if (properties.includes(key)) {
97
103
  out[key] = value;
98
104
  continue;
99
105
  }
100
- const spelled = propertyName(key);
101
- if (spelled !== key && properties.includes(spelled)) {
102
- warn(`"${key}" is spelled "${spelled}" in this tool's schema; "${key}" is still taken for now and will be refused in a later release.`);
103
- if (!(spelled in args))
104
- out[spelled] = value;
106
+ const now = former.get(key);
107
+ if (now) {
108
+ warn(formerlyWarning(`"${key}"`, `"${now}"`));
109
+ if (!(now in args))
110
+ out[now] = value;
105
111
  continue;
106
112
  }
107
- const near = closest(key, properties);
113
+ const spelled = propertyName(key);
114
+ const near = spelled !== key && properties.includes(spelled) ? spelled : closest(key, properties);
108
115
  throw new CavelonError(ExitCode.usage, {
109
116
  code: "unknown_argument",
110
117
  message: `${spec.mcpTool} has no argument "${key}"; nothing was done.${near ? ` Did you mean "${near}"?` : ""}`,
@@ -162,10 +169,10 @@ export function createMcpServer(io, commands) {
162
169
  });
163
170
  if (!spec)
164
171
  return fail(new Error(`Unknown tool ${request.params.name}.`));
165
- const spelling = [];
172
+ const renamed = [];
166
173
  let args;
167
174
  try {
168
- args = argumentsOf(spec, given, (message) => spelling.push(message));
175
+ args = argumentsOf(spec, given, (message) => renamed.push(message));
169
176
  }
170
177
  catch (error) {
171
178
  return fail(error);
@@ -177,7 +184,7 @@ export function createMcpServer(io, commands) {
177
184
  const tenant = !ownsTenant(spec) && typeof args.tenant === "string" ? args.tenant : undefined;
178
185
  const solutionEnv = spec.options?.env && typeof args.env === "string" ? args.env : undefined;
179
186
  const ctx = createContext(mcpIo(io), { json: true, tenant, solutionEnv }, "mcp");
180
- for (const message of spelling)
187
+ for (const message of renamed)
181
188
  ctx.warn(message);
182
189
  try {
183
190
  const result = await spec.run(ctx, inputFrom(spec, args));
@@ -1,6 +1,6 @@
1
1
  import { Ajv2020 } from "ajv/dist/2020.js";
2
2
  import { BRANCH_WIDTH_KEY, branchConcurrency, offText } from "./branches.js";
3
- import { locate, schemaSections } from "./package-files.js";
3
+ import { locate, schemaSections, tenantWideSections } from "./package-files.js";
4
4
  import { PERSONA_SECTION, sectionFields } from "./package-format.js";
5
5
  import { kitErrorEntry } from "./kit-codes.js";
6
6
  import { branches, checkModels, checkReferences, checkUnknownFields, closest, DUPLICATE_CODE, FIELD_UNKNOWN_CODE, MODEL_UNKNOWN_CODE, REFERENCE_MISSING_CODE, REFERENCE_UNKNOWN_CODE, KNOWLEDGE_TOOL_KEYS, } from "./package-references.js";
@@ -25,6 +25,7 @@ const PERSONA_MESSAGES = [
25
25
  { switch: "fallback_message_enabled", text: "fallback_message", what: "fallback message", when: "when the assistant has no answer" },
26
26
  ];
27
27
  const SOLUTION_MISMATCH_CODE = "solution_slug_mismatch";
28
+ const TENANT_WIDE_CODE = "tenant_wide_section";
28
29
  const ASSERTION_UNCHECKED_CODE = "test_assertion_unchecked";
29
30
  const TESTING_DOCS = "/docs/concepts/regression-testing";
30
31
  export const KIT_CODES = [
@@ -53,14 +54,16 @@ export const KIT_CODES = [
53
54
  code: ENDPOINT_LIMIT_CODE,
54
55
  area: "package",
55
56
  message: "A Model Registry row sets max_concurrent_requests without a base_url.",
56
- hint: "The limit belongs to a self-hosted endpoint: add the row's base_url, or remove max_concurrent_requests (empty means no limit).",
57
+ hint: "The limit belongs to a self-hosted endpoint: add the row's base_url, or remove max_concurrent_requests (empty means no limit). " +
58
+ "In a solution's folder, apply sends model_registry only with --include-tenant-wide, for the whole tenant; `cavelon models set-limit` changes one row's limit without a package.",
57
59
  docs: PACKAGE_DOCS,
58
60
  },
59
61
  {
60
62
  code: ENDPOINT_LIMIT_NOT_CARRIED,
61
63
  area: "package",
62
64
  message: "This instance's package format does not carry max_concurrent_requests on Model Registry rows.",
63
- hint: "The import ignores it. Set it on the row in the Admin's model form, or with PATCH /api/v1/model-registry/{model_registry_id}.",
65
+ hint: "The import ignores it. Set it on the row in the Admin's model form, or with `cavelon models set-limit` (PATCH /api/v1/model-registry/{model_registry_id}). " +
66
+ "In a solution's folder, apply sends model_registry only with --include-tenant-wide, for the whole tenant.",
64
67
  docs: PACKAGE_DOCS,
65
68
  },
66
69
  {
@@ -146,6 +149,14 @@ export const KIT_CODES = [
146
149
  "(or set harness in cavelon.yaml to the package's); the import otherwise works on the solution the package names.",
147
150
  docs: PACKAGE_DOCS,
148
151
  },
152
+ {
153
+ code: TENANT_WIDE_CODE,
154
+ area: "package",
155
+ message: "A solution's folder holds a section the whole tenant shares, such as tenant_settings or model_registry.",
156
+ hint: "`cavelon apply` leaves it out of the solution's import; `cavelon apply --include-tenant-wide` sends it, and then every solution of the tenant sees the change. " +
157
+ "Remove the file unless that is meant. An instance that does not publish include_tenant_wide imports it with every apply.",
158
+ docs: PACKAGE_DOCS,
159
+ },
149
160
  {
150
161
  code: "package_file_duplicate",
151
162
  area: "package",
@@ -306,6 +317,8 @@ export function checkPackage(disk, options) {
306
317
  findings.push(...checkPersonaMessages(disk, options.schema));
307
318
  findings.push(...checkUncheckedAssertions(disk, options.schema));
308
319
  findings.push(...checkSolutionSlug(disk, options.solution));
320
+ findings.push(...checkTenantWide(disk, options.schema, options.solution));
321
+ noteTenantWide(findings, options.schema, options.solution);
309
322
  for (const finding of findings) {
310
323
  const entry = findingEntry(options.catalog, finding.code);
311
324
  if (!entry)
@@ -653,6 +666,38 @@ function misnamedVariants(schema, pkg) {
653
666
  return found;
654
667
  }
655
668
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
669
+ function checkTenantWide(disk, schema, solution) {
670
+ if (!solution)
671
+ return [];
672
+ const shared = tenantWideSections(schema);
673
+ return Object.keys(disk.package)
674
+ .filter((section) => shared.has(section))
675
+ .map((section) => {
676
+ const source = disk.sources[section];
677
+ return {
678
+ code: TENANT_WIDE_CODE,
679
+ severity: "warning",
680
+ file: Array.isArray(source) ? source[0]?.file : source?.file,
681
+ path: section,
682
+ message: `${section} is shared by the whole tenant, not this solution's: apply leaves it out unless --include-tenant-wide, which changes it for every solution ` +
683
+ "(an instance that does not publish include_tenant_wide imports it with every apply). Remove the file unless that is meant.",
684
+ };
685
+ });
686
+ }
687
+ function noteTenantWide(findings, schema, solution) {
688
+ if (!solution)
689
+ return;
690
+ const shared = tenantWideSections(schema);
691
+ for (const finding of findings) {
692
+ if (finding.code === TENANT_WIDE_CODE || !finding.path)
693
+ continue;
694
+ const section = /^\/?([A-Za-z0-9_]+)/.exec(finding.path)?.[1];
695
+ if (!section || !shared.has(section))
696
+ continue;
697
+ finding.message +=
698
+ ` ${section} is tenant-wide: a solution's apply leaves it out unless --include-tenant-wide, which changes it for every solution of the tenant.`;
699
+ }
700
+ }
656
701
  function checkSolutionSlug(disk, solution) {
657
702
  if (!solution || UUID.test(solution))
658
703
  return [];
@@ -671,11 +716,11 @@ function checkSolutionSlug(disk, solution) {
671
716
  `rename the slug (and every harness_slug) to "${solution}", or set harness in cavelon.yaml to the package's.`,
672
717
  });
673
718
  }
674
- if (harnesses.length)
675
- return findings;
676
- for (const section of ["agents", "test_suites"]) {
719
+ const packaged = new Set(harnesses.map((h) => h.slug).filter((v) => typeof v === "string"));
720
+ for (const section of harnesses.length ? ["test_suites"] : ["agents", "test_suites"]) {
677
721
  const entries = asList(pkg[section]);
678
- const off = entries.flatMap((entry, i) => (typeof entry.harness_slug === "string" && entry.harness_slug !== slug ? [{ i, name: entry.harness_slug }] : []));
722
+ const fits = (name) => name === slug || packaged.has(name);
723
+ const off = entries.flatMap((entry, i) => (typeof entry.harness_slug === "string" && !fits(entry.harness_slug) ? [{ i, name: entry.harness_slug }] : []));
679
724
  if (!off.length)
680
725
  continue;
681
726
  const names = [...new Set(off.map((o) => o.name))];
@@ -1,6 +1,6 @@
1
1
  import { promises as fs } from "node:fs";
2
2
  import path from "node:path";
3
- import { LineCounter, parseDocument } from "yaml";
3
+ import { CST, LineCounter, Parser, parseDocument } from "yaml";
4
4
  import { CavelonError, ExitCode } from "./errors.js";
5
5
  import { readTextFile, withoutBom, writeFileAtomic } from "./fsutil.js";
6
6
  import { canonical, PERSONA_SECTION, sameEntry, sameSectionValue, sectionContent, sectionFields, toYaml } from "./package-format.js";
@@ -101,6 +101,27 @@ async function exists(dir) {
101
101
  return false;
102
102
  }
103
103
  }
104
+ function errorLine(text, error, lines) {
105
+ const at = error.linePos?.[0]?.line ?? (typeof error.pos?.[0] === "number" ? lines.linePos(error.pos[0]).line : undefined);
106
+ if (error.code !== "MISSING_CHAR" || typeof error.pos?.[0] === "undefined")
107
+ return at;
108
+ const pos = error.pos[0];
109
+ let start;
110
+ const quoted = (t) => {
111
+ if ((t?.type === "double-quoted-scalar" || t?.type === "single-quoted-scalar") && t.offset <= pos && t.offset + t.source.length >= pos)
112
+ start = t.offset;
113
+ };
114
+ for (const token of new Parser().parse(text)) {
115
+ if (token.type !== "document")
116
+ continue;
117
+ quoted(token.value);
118
+ CST.visit(token, (item) => {
119
+ quoted(item.key);
120
+ quoted(item.value);
121
+ });
122
+ }
123
+ return start === undefined ? at : lines.linePos(start).line;
124
+ }
104
125
  function parseFile(root, file, text) {
105
126
  const relative = rel(root, file);
106
127
  if (/\.json$/i.test(file)) {
@@ -124,7 +145,7 @@ function parseFile(root, file, text) {
124
145
  code: "package_file_invalid",
125
146
  severity: "error",
126
147
  file: relative,
127
- line: first.linePos?.[0]?.line ?? (typeof first.pos?.[0] === "number" ? lines.linePos(first.pos[0]).line : undefined),
148
+ line: errorLine(text, first, lines),
128
149
  message: `Not valid YAML: ${first.message.split("\n")[0]}`,
129
150
  },
130
151
  };
@@ -383,6 +404,7 @@ export async function writePackage(root, layout, pkg, schema, options = {}) {
383
404
  if (skip.has(section)) {
384
405
  if (!report.tenant_wide.includes(section))
385
406
  report.tenant_wide.push(section);
407
+ report.kept.push(rel(root, path.join(dir, name)));
386
408
  continue;
387
409
  }
388
410
  if (section in pkg || section === PERSONA_SECTION)
@@ -150,3 +150,13 @@ export function notAppliedLines(list) {
150
150
  })
151
151
  .join("") + (list.length > 20 ? `\n … ${list.length - 20} more (--json)` : "");
152
152
  }
153
+ export function tenantWideReport(raw) {
154
+ if (!isObject(raw) || !Array.isArray(raw.sections))
155
+ return undefined;
156
+ const sections = raw.sections.map(text).filter((s) => s !== null);
157
+ const reaches = Array.isArray(raw.reaches_active_solutions) ? raw.reaches_active_solutions : [];
158
+ const names = reaches
159
+ .map((h) => (isObject(h) ? (text(h.slug) ?? text(h.harness_slug) ?? text(h.name) ?? text(h.id)) : text(h)))
160
+ .filter((n) => n !== null);
161
+ return { sections, applied: raw.applied === true, reaches_active_solutions: [...new Set(names)] };
162
+ }
package/dist/session.js CHANGED
@@ -6,10 +6,19 @@ import { readTenantless } from "./principal.js";
6
6
  import { listsTenants, searchTenants, tenantMissError } from "./tenant-choice.js";
7
7
  import { findProject, readEnvFile } from "./project.js";
8
8
  import { loadUserConfig, tokenKind, updateInstance } from "./user-config.js";
9
+ import { shellWord } from "./shell.js";
9
10
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
10
11
  export function isUuid(value) {
11
12
  return UUID.test(value);
12
13
  }
14
+ export function contextFlags(session) {
15
+ let flags = "";
16
+ if (session.urlSource === "option" && session.url)
17
+ flags += ` --instance ${shellWord(session.url)}`;
18
+ if (session.tenantSource === "option" && session.tenant)
19
+ flags += ` --tenant ${shellWord(session.tenant)}`;
20
+ return flags;
21
+ }
13
22
  function isLocalHost(hostname) {
14
23
  return (hostname === "localhost" ||
15
24
  hostname.endsWith(".localhost") ||
@@ -108,13 +108,18 @@ endpoint.
108
108
  - On rows that already exist, `cavelon models list` shows each row's endpoint
109
109
  and `max_concurrent_requests` (never a key). `cavelon models set-limit
110
110
  <model_id> <n|none>` shows the old and the new value and changes nothing;
111
- with `--confirm` it changes the row. It refuses a row without a `base_url`.
111
+ the confirm command it prints changes the row (from your shell it carries the
112
+ preview's token, `--confirm <token>`). It refuses a row without a `base_url`.
112
113
  Where this instance's package format does not carry the field, `validate`
113
114
  warns that the import ignores it; set it this way instead.
115
+ - `model_registry` is tenant-wide: in a solution's folder, `cavelon apply`
116
+ leaves it out of the import unless `--include-tenant-wide`, which changes it
117
+ for every solution of the tenant (`validate` says so on each finding in the
118
+ file). For one row's limit, prefer `cavelon models set-limit`.
114
119
 
115
120
  **Propose a limit; the person decides.** Say which value you would set and
116
121
  why (what the endpoint serves, which rows share it, what waits or fails now),
117
- then wait for the person's answer. Run `models set-limit --confirm` only after
122
+ then wait for the person's answer. Run the confirm command of `models set-limit` only after
118
123
  they agreed, and never raise or lower a limit without telling them. A limit
119
124
  `cavelon limits` names as the operator's (the run caps, the slot waits, the
120
125
  licence) is not yours or the tenant's to change: tell the person who changes
@@ -305,7 +310,10 @@ schema has them: `cavelon validate` reports an unknown section):
305
310
  instance's export gives them (field order, the schema's defaults filled in,
306
311
  test cases and steps numbered in their written order), so the first `pull`
307
312
  after `apply` shows only what changed on the instance; `cavelon fmt
308
- --check` changes nothing and exits 3 when a file would change.
313
+ --check` changes nothing and exits 3 when a file would change. fmt keeps
314
+ no comments (pull keeps none either) and names each file whose comments
315
+ it drops, as the example files' explanations: keep what the person needs
316
+ elsewhere before running it.
309
317
  2. `cavelon apply --env test` to see what the instance makes of it; the
310
318
  preview re-checks everything on the server, including rules that only the
311
319
  instance can check (graph rules, references between sections).