@cavelon/cli 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +58 -22
  2. package/dist/choose.js +8 -4
  3. package/dist/code-hints.js +74 -0
  4. package/dist/commands/api.js +83 -44
  5. package/dist/commands/async.js +26 -5
  6. package/dist/commands/chat.js +177 -0
  7. package/dist/commands/docs.js +240 -37
  8. package/dist/commands/fmt.js +120 -0
  9. package/dist/commands/index.js +9 -1
  10. package/dist/commands/init.js +64 -30
  11. package/dist/commands/inventory.js +48 -5
  12. package/dist/commands/limits-set.js +9 -6
  13. package/dist/commands/loops.js +15 -9
  14. package/dist/commands/models.js +16 -7
  15. package/dist/commands/sandboxes.js +8 -4
  16. package/dist/commands/schema.js +361 -0
  17. package/dist/commands/session.js +148 -24
  18. package/dist/commands/setup.js +22 -6
  19. package/dist/commands/solution.js +537 -76
  20. package/dist/commands/tenants.js +156 -15
  21. package/dist/commands/values.js +18 -9
  22. package/dist/commands/work.js +343 -35
  23. package/dist/confirm-token.js +72 -0
  24. package/dist/contracts.js +3 -0
  25. package/dist/default-route.js +21 -0
  26. package/dist/errors.js +4 -0
  27. package/dist/git.js +14 -5
  28. package/dist/harness-ref.js +14 -1
  29. package/dist/http.js +27 -4
  30. package/dist/invoke.js +8 -4
  31. package/dist/kit-codes.js +91 -0
  32. package/dist/limits.js +12 -1
  33. package/dist/local-state.js +32 -7
  34. package/dist/main.js +52 -4
  35. package/dist/mcp.js +72 -15
  36. package/dist/openapi.js +77 -21
  37. package/dist/operations.js +4 -3
  38. package/dist/package-check.js +361 -12
  39. package/dist/package-files.js +92 -45
  40. package/dist/package-format.js +222 -0
  41. package/dist/package-references.js +298 -0
  42. package/dist/preview-report.js +152 -0
  43. package/dist/results.js +21 -1
  44. package/dist/skills/cavelon-authoring/SKILL.md +98 -13
  45. package/dist/skills/cavelon-long-running/SKILL.md +3 -1
  46. package/dist/skills/cavelon-loop/SKILL.md +129 -21
  47. package/dist/skills/cavelon-testing/SKILL.md +130 -10
  48. package/dist/tenant-choice.js +31 -5
  49. package/dist/trace-view.js +172 -0
  50. package/package.json +1 -1
@@ -0,0 +1,21 @@
1
+ import { listHarnesses } from "./harness-ref.js";
2
+ import { callStable } from "./invoke.js";
3
+ import { cavelonCommand } from "./shell.js";
4
+ export async function readDefaultRoute(ctx) {
5
+ const all = await listHarnesses(ctx);
6
+ const known = all.some((h) => typeof h.is_default === "boolean");
7
+ return { known, current: known ? all.find((h) => h.is_default === true) : undefined };
8
+ }
9
+ export const named = (h) => (h.name && h.name !== h.slug ? `${h.name} (${h.slug})` : h.slug);
10
+ export function defaultCommands(slug) {
11
+ return { preview: cavelonCommand("harness", "default", slug), confirm: cavelonCommand("harness", "default", slug, "--confirm") };
12
+ }
13
+ export function defaultChangeLine(target, route) {
14
+ const now = route.current ? named(route.current) : route.known ? "no solution" : "unknown (this instance does not say)";
15
+ return `default → ${now} now; would become ${named(target)}. This changes live traffic: the tenant's chat and widget answer with it where a conversation names no solution.`;
16
+ }
17
+ export async function setDefaultRoute(ctx, harnessId) {
18
+ return callStable(ctx, "POST", "/api/v1/harnesses/{harness_id}/default", "setting the default route", {
19
+ params: { harness_id: [harnessId] },
20
+ });
21
+ }
package/dist/errors.js CHANGED
@@ -17,6 +17,7 @@ export class CavelonError extends Error {
17
17
  status;
18
18
  details;
19
19
  blockers;
20
+ blockerDetails;
20
21
  constructor(exitCode, details) {
21
22
  super(details.message);
22
23
  this.name = "CavelonError";
@@ -27,6 +28,7 @@ export class CavelonError extends Error {
27
28
  this.status = details.status;
28
29
  this.details = details.details;
29
30
  this.blockers = details.blockers;
31
+ this.blockerDetails = details.blockerDetails;
30
32
  }
31
33
  toJSON() {
32
34
  const out = { code: this.code, message: this.message, exit_code: this.exitCode };
@@ -40,6 +42,8 @@ export class CavelonError extends Error {
40
42
  out.details = this.details;
41
43
  if (this.blockers?.length)
42
44
  out.blockers = this.blockers;
45
+ if (this.blockerDetails?.length)
46
+ out.blocker_details = this.blockerDetails;
43
47
  return out;
44
48
  }
45
49
  }
package/dist/git.js CHANGED
@@ -36,11 +36,20 @@ export async function git(args, cwd) {
36
36
  });
37
37
  }
38
38
  export async function uncommitted(cwd, paths) {
39
- const out = await git(["status", "--porcelain", "--untracked-files=all", "--", ...paths], cwd);
39
+ const out = await git(["status", "--porcelain", "-z", "--untracked-files=all", "--", ...paths], cwd);
40
40
  if (out === undefined)
41
41
  return undefined;
42
- return out
43
- .split("\n")
44
- .map((line) => line.slice(3).trim())
45
- .filter(Boolean);
42
+ const prefix = ((await git(["rev-parse", "--show-prefix"], cwd)) ?? "").trim();
43
+ const entries = out.split("\0");
44
+ const files = [];
45
+ for (let i = 0; i < entries.length; i++) {
46
+ const entry = entries[i];
47
+ if (entry.length < 4)
48
+ continue;
49
+ if ("RC".includes(entry[0]) || "RC".includes(entry[1]))
50
+ i++;
51
+ const file = entry.slice(3);
52
+ files.push(prefix && file.startsWith(prefix) ? file.slice(prefix.length) : file);
53
+ }
54
+ return files;
46
55
  }
@@ -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/http.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { capacityCodeIn, capacityHint } from "./capacity.js";
2
2
  import { ceilingRefusal, LIMIT_ABOVE_CEILING } from "./limits.js";
3
3
  import { CavelonError, ExitCode } from "./errors.js";
4
+ import { blockerDetails } from "./preview-report.js";
4
5
  import { KIT_VERSION } from "./version.js";
5
6
  const RUNTIME = process.versions.bun ? "bun/" + process.versions.bun : "node/" + process.versions.node;
6
7
  export const DEFAULT_TIMEOUT_MS = 30_000;
@@ -117,7 +118,9 @@ export class ApiClient {
117
118
  }
118
119
  if (!response.ok && !options.allow?.includes(response.status)) {
119
120
  const tenantless = options.sendTenant !== false && !this.headers(options)["X-Tenant-Id"] && Boolean(this.target.token?.startsWith("cvpat_"));
120
- throw await this.refusal(response.status, data, `${method} ${new URL(response.url || this.resolve(path)).pathname}`, response.headers, { tenantless });
121
+ const pathname = new URL(response.url || this.resolve(path)).pathname;
122
+ const platform = options.sendTenant === false || isPlatformRoute(pathname);
123
+ throw await this.refusal(response.status, data, `${method} ${pathname}`, response.headers, { tenantless, platform });
121
124
  }
122
125
  return { status: response.status, headers: response.headers, data: data, text };
123
126
  }
@@ -187,6 +190,19 @@ function networkError(error, url, signal) {
187
190
  });
188
191
  }
189
192
  const BARE_CODE = /^[a-z][a-z0-9]*(?:_[a-z0-9]+)+$/;
193
+ export function isPlatformRoute(pathname) {
194
+ const words = pathname.split("/").filter(Boolean);
195
+ const at = words.indexOf("v1");
196
+ const first = at < 0 ? undefined : words[at + 1];
197
+ if (!first)
198
+ return false;
199
+ if (first.startsWith("platform") || first === "admin")
200
+ return true;
201
+ return first === "tenants" && words[at + 2] !== "current";
202
+ }
203
+ export const PLATFORM_ROUTE_HINT = "This is a platform route, outside any tenant: it needs a personal access token that allows Platform mode, with a ceiling and " +
204
+ "an owner's global role that grant the permission (creating a tenant needs tenants.manage). `cavelon whoami` shows whether " +
205
+ "this token may enter Platform mode; a platform operator can also do this in the Admin.";
190
206
  export const TENANT_ID_HINT = "A token without Platform mode works only inside a tenant. Run `cavelon use` to choose one of the tenants it reaches, " +
191
207
  "or pass --tenant <name, slug or id> (or set CAVELON_TENANT). An older instance tells such a token nothing without a tenant, " +
192
208
  "not even which tenants it reaches: pass --tenant <tenant-id> there; an operator copies the id in Platform › Tenants. " +
@@ -198,6 +214,7 @@ export function errorFromResponse(status, body, what, headers, sent = {}) {
198
214
  let docs;
199
215
  let details;
200
216
  let blockers;
217
+ let structured;
201
218
  const pick = (source) => {
202
219
  if (typeof source.code === "string")
203
220
  code = source.code;
@@ -212,6 +229,9 @@ export function errorFromResponse(status, body, what, headers, sent = {}) {
212
229
  const said = Array.isArray(source.blockers) ? source.blockers.filter((b) => typeof b === "string" && b !== "") : [];
213
230
  if (said.length)
214
231
  blockers = said;
232
+ const detailed = blockerDetails(source.blocker_details);
233
+ if (detailed.length)
234
+ structured = detailed;
215
235
  };
216
236
  if (body && typeof body === "object" && !Array.isArray(body)) {
217
237
  const map = body;
@@ -263,9 +283,11 @@ export function errorFromResponse(status, body, what, headers, sent = {}) {
263
283
  hint =
264
284
  status === 401
265
285
  ? "The token is missing, expired or revoked. A person runs `cavelon login` with a new one."
266
- : sent.tenantless
267
- ? `No tenant was named. ${TENANT_ID_HINT} Otherwise check the token's permission ceiling.`
268
- : "The token does not reach this. Check the tenant (`cavelon whoami`) and the token's permission ceiling.";
286
+ : sent.platform
287
+ ? PLATFORM_ROUTE_HINT
288
+ : sent.tenantless
289
+ ? `No tenant was named. ${TENANT_ID_HINT} Otherwise check the token's permission ceiling.`
290
+ : "The token does not reach this. Check the tenant (`cavelon whoami`) and the token's permission ceiling.";
269
291
  }
270
292
  return new CavelonError(exitCode, {
271
293
  code: code ?? defaultCode(status),
@@ -275,6 +297,7 @@ export function errorFromResponse(status, body, what, headers, sent = {}) {
275
297
  status,
276
298
  details,
277
299
  blockers,
300
+ blockerDetails: structured,
278
301
  });
279
302
  }
280
303
  export function exitCodeForStatus(status) {
package/dist/invoke.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { promises as fs } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { CavelonError, ExitCode, validationError } from "./errors.js";
4
- import { bodyBytes } from "./http.js";
4
+ import { bodyBytes, isPlatformRoute } from "./http.js";
5
5
  import { coerceParameter, isArrayParameter, operationAt, validateBody } from "./openapi.js";
6
6
  export async function openapiOrWarn(ctx) {
7
7
  try {
@@ -54,7 +54,7 @@ export function buildRequest(op, args) {
54
54
  throw validationError(`${op.alias} needs ${missing.join(", ")}.`, { missing }, "Pass each as -p name=value.");
55
55
  }
56
56
  if (op.requestBody?.required && args.body === undefined && !args.files?.length && !args.bytes) {
57
- throw validationError(`${op.alias} needs a request body.`, undefined, "Pass it with --json '<body>' (or @file, or - for stdin).");
57
+ throw validationError(`${op.alias} needs a request body.`, undefined, "Pass it with --body '<json>' (or @file, or - for stdin).");
58
58
  }
59
59
  return { path: filled, query, headers };
60
60
  }
@@ -106,8 +106,12 @@ export async function callOperation(ctx, client, doc, op, args) {
106
106
  data = text;
107
107
  }
108
108
  }
109
- if (!response.ok)
110
- throw await client.refusal(response.status, data, `${op.method} ${new URL(client.resolve(target)).pathname}`, response.headers);
109
+ if (!response.ok) {
110
+ const pathname = new URL(client.resolve(target)).pathname;
111
+ throw await client.refusal(response.status, data, `${op.method} ${pathname}`, response.headers, {
112
+ platform: args.sendTenant === false || isPlatformRoute(pathname),
113
+ });
114
+ }
111
115
  return { status: response.status, contentType, data: isText ? (text ? data : null) : undefined, bytes: isText ? undefined : bytes };
112
116
  }
113
117
  export async function workflowOperation(ctx, method, pathTemplate, what) {
@@ -0,0 +1,91 @@
1
+ export const KIT_ERROR_CODES = [
2
+ { code: "not_logged_in", area: "cli", message: "There is no token for the instance.", hint: "A person runs `cavelon login` (or sets CAVELON_URL and CAVELON_TOKEN); an agent never handles the token." },
3
+ { code: "no_instance", area: "cli", message: "No Cavelon instance is selected.", hint: "Run `cavelon login --instance <url>`, set CAVELON_URL, or work inside a folder with cavelon.yaml." },
4
+ { code: "unauthorized", area: "cli", message: "The instance refused the token: expired, revoked, or for another instance.", hint: "A person creates a new token on /account/access-tokens and runs `cavelon login`." },
5
+ { code: "tenant_required", area: "cli", message: "The command acts in a tenant, and none is chosen.", hint: "Choose one with `cavelon use` (it lists your tenants), or pass --tenant <name or slug>." },
6
+ { code: "tenant_not_found", area: "cli", message: "No tenant by that name, slug or id that this token reaches.", hint: "`cavelon tenant list` shows the tenants; `cavelon whoami` which ones the token reaches." },
7
+ { code: "no_tenant_reached", area: "cli", message: "The token reaches no tenant on this instance.", hint: "A person adds the token's owner to a tenant, or creates a token for one; `cavelon whoami` shows what it reaches." },
8
+ { code: "api_key_inactive", area: "cli", message: "The tenant API key is revoked or inactive.", hint: "A person creates a new key in the Admin." },
9
+ { code: "api_key_cannot_create_tenants", area: "cli", message: "A tenant API key can never create a tenant.", hint: "Use a personal access token that allows Platform mode, owned by someone with tenants.manage." },
10
+ { code: "platform_mode_not_allowed", area: "cli", message: "The token may not enter Platform mode, which the change needs; nothing was sent.", hint: "A person creates a token with Allow Platform mode and a platform ceiling, or makes the change in the Admin." },
11
+ { code: "permission_missing", area: "cli", message: "The token lacks a permission the change needs; nothing was sent.", hint: "`cavelon whoami` shows the token's ceiling; a person makes the change, or creates a token whose role grants it." },
12
+ { code: "platform_role_required", area: "cli", message: "The change is an operator's: it needs a personal access token in Platform mode of a platform role; nothing was sent.", hint: "Ask the instance's operator, or run it with an operator's token." },
13
+ { code: "forbidden", area: "cli", message: "The credential may not make this change; nothing was sent.", hint: "The message names the permission; a person with it makes the change, or in the Admin." },
14
+ { code: "token_activation_refused", area: "cli", message: "The personal access token was not created with \"may activate\", so it cannot activate solutions.", hint: "A person activates the solution in the Admin, or creates a token with \"may activate\"." },
15
+ { code: "secret_needs_a_person", area: "cli", message: "A tenant API key cannot set or delete a secret; nothing was sent.", hint: "A person logs in with a personal access token and runs `cavelon secrets set <name>`, or uses the Admin." },
16
+ { code: "foreign_url", area: "cli", message: "cavelon refused to send the token to a URL outside the instance.", hint: "Check the instance URL; the token goes only to the instance it was stored for." },
17
+ { code: "network_error", area: "cli", message: "The instance could not be reached.", hint: "Check the instance URL and the network (VPN, proxy, allowlist)." },
18
+ { code: "request_timeout", area: "cli", message: "The instance did not answer in time.", hint: "Retry; CAVELON_HTTP_TIMEOUT_MS raises the limit per request." },
19
+ { code: "unexpected_redirect", area: "cli", message: "The instance redirected a request elsewhere.", hint: "Check the instance URL (https, host, path)." },
20
+ { code: "internal_error", area: "cli", message: "cavelon failed in an unexpected way.", hint: "Run the command again; if it repeats, report it with the command and its output." },
21
+ { code: "operation_unavailable", area: "cli", message: "This instance does not offer what the command needs (the route or a field is not in its OpenAPI).", hint: "The instance may be older than the feature; `cavelon status` shows its version." },
22
+ { code: "openapi_unavailable", area: "cli", message: "The instance does not serve its OpenAPI.", hint: "`cavelon api` needs it; ask the instance's operator to route it." },
23
+ { code: "error_catalog_unavailable", area: "cli", message: "The instance does not publish its error catalog.", hint: "Try `cavelon docs search <code>`." },
24
+ { code: "docs_unavailable", area: "cli", message: "The instance does not serve its docs to agents (no /llms.txt).", hint: "Read the docs in the Admin until the instance is updated." },
25
+ { code: "doc_not_found", area: "cli", message: "No docs page by that name on this instance.", hint: "Find it with `cavelon docs search <words>`." },
26
+ { code: "code_unknown", area: "cli", message: "The code is neither in the instance's error catalog nor one of cavelon's own.", hint: "Check the spelling against the similar codes `cavelon explain` names, or try `cavelon docs search <code>`." },
27
+ { code: "operation_not_found", area: "cli", message: "No such operation: `cavelon api` found no operation by that name in the instance's OpenAPI, or `cavelon wait` no operation (op_…) by that id in this tenant.", hint: "`cavelon api list --search <text>` finds an operation; operation ids are per tenant (`cavelon whoami`, `cavelon status`)." },
28
+ { code: "operation_ambiguous", area: "cli", message: "The short name matches several operations.", hint: "Use the full operationId the message lists." },
29
+ { code: "operation_for_a_person", area: "cli", message: "The operation stays with a person (the instance marks it, or it changes a secret, a credential or an approval), so an agent does not send it.", hint: "A person runs it in their own terminal, or in the Admin." },
30
+ { code: "secret_field_for_a_person", area: "cli", message: "The request sets a field the instance marks as a secret value, so an agent does not send it.", hint: "Leave the field out; a person enters the value with `cavelon secrets set <name>` or in the Admin." },
31
+ { code: "confirmation_required", area: "cli", message: "The command changes something and there is no terminal to ask.", hint: "Read the plan it printed, then run it again with --yes (or --confirm, where it takes that)." },
32
+ { code: "operations_unavailable", area: "cli", message: "The instance does not offer the operations API.", hint: "Its operator turns it on with OPERATIONS_API_ENABLED." },
33
+ { code: "not_an_operation_id", area: "cli", message: "That is not an operation id; they start with op_.", hint: "Commands that start work print the operation id; `cavelon status` lists running ones." },
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
+ { code: "stream_error", area: "cli", message: "The event stream of an operation broke off.", hint: "`cavelon wait <op_id>` polls instead." },
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." },
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
+ { 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
+ { 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." },
41
+ { code: "uncommitted_changes", area: "cli", message: "pull would overwrite or remove package files with changes that are not committed and not what the last pull or apply left.", hint: "Commit them first, apply them with `cavelon apply`, or pass --force to discard them." },
42
+ { code: "package_files_differ", area: "cli", message: "init --from would change or remove package files that hold something else; nothing was written.", hint: "Commit or compare them first, then pass --force to replace them." },
43
+ { code: "package_file_outside", area: "cli", message: "A package file is a link to a file outside the solution folder; nothing was written.", hint: "Move the file into the solution folder and link to it there, or replace the link with the file." },
44
+ { code: "package_import_invalid", area: "cli", message: "The file given to init --from is not a package export.", hint: "Pass a JSON or YAML file with one key per section (manifest, harnesses, agents, …)." },
45
+ { code: "package_schema_unavailable", area: "cli", message: "No package schema is cached for the instance, and it was not read.", hint: "Run `cavelon validate` once without --offline (or `cavelon pull`) while the instance is reachable." },
46
+ { code: "package_version_unsupported", area: "cli", message: "The package is written in a format the instance does not accept.", hint: "`cavelon status --json` lists the accepted versions; pull the package again to get the current one." },
47
+ { code: "export_invalid", area: "cli", message: "The instance's export was not a package.", hint: "Retry; if it repeats, the instance's export is broken (`cavelon status` shows its version)." },
48
+ { code: "file_exists", area: "cli", message: "The output file exists; cavelon does not overwrite it.", hint: "Choose another file with --out." },
49
+ { code: "path_outside_solution", area: "cli", message: "A tool reads and writes files only inside the solution folder.", hint: "Name a file inside the solution folder, or ask the person to run the command in their terminal." },
50
+ { code: "path_in_kit_directory", area: "cli", message: "The file is in cavelon's own directory (login and cache); no tool reads or writes there.", hint: "Name a file in the solution folder." },
51
+ { code: "skills_missing", area: "cli", message: "This cavelon has no skills to install; its package is incomplete.", hint: "Reinstall @cavelon/cli." },
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
+ { 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
+ { 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." },
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." },
62
+ { code: "limit_not_found", area: "cli", message: "The instance lists no limit by that key.", hint: "`cavelon limits` lists the keys." },
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." },
64
+ { code: "tenant_quota_reached", area: "cli", message: "The tenant's solution quota is used up; nothing was sent.", hint: "A platform administrator raises the quota (`cavelon limits` shows it); archiving an unused solution frees one." },
65
+ { code: "license_limit_reached", area: "cli", message: "The licence's cap on solutions is reached; nothing was sent.", hint: "Archive an unused solution, or ask the operator for a renewed licence." },
66
+ { code: "model_not_found", area: "cli", message: "The tenant's Model Registry has no row by that name or id.", hint: "`cavelon models list` shows its rows by model_id and id." },
67
+ { code: "variable_not_set", area: "cli", message: "The tenant has no variable by that name.", hint: "`cavelon variables list` shows them; `cavelon variables set <name> <value>` sets one." },
68
+ { code: "no_suites", area: "cli", message: "The solution (or tenant) has no test suites.", hint: "Write one in tests/ and apply it; the cavelon-testing skill shows how." },
69
+ { code: "no_result", area: "cli", message: "The operation has no result yet.", hint: "`cavelon wait <op_id>` waits for it." },
70
+ { code: "no_trace", area: "cli", message: "The operation's result has no trace.", hint: "Trace a run, test run or conversation id instead." },
71
+ { code: "run_not_found", area: "cli", message: "No run, test run or conversation with that id in this tenant.", hint: "Check the id and the tenant (`cavelon whoami`); --kind names what the id is." },
72
+ { code: "trace_not_found", area: "cli", message: "No trace with that id under the run.", hint: "`cavelon trace <run>` lists the run's traces." },
73
+ { code: "span_not_found", area: "cli", message: "No span with that id in the trace.", hint: "`cavelon trace <run> --trace <id>` lists its spans." },
74
+ { code: "loop_not_found", area: "cli", message: "The run has no loop (yet).", hint: "A loop starts when the run reaches its Masterloop node; `cavelon loop watch <run>` waits for it." },
75
+ { code: "loop_state_conflict", area: "cli", message: "No loop of the run is in a state that allows this.", hint: "`cavelon loop iterations <run>` shows each loop's state." },
76
+ { code: "loop_resume_review_required", area: "cli", message: "The loop paused for a cause a person checks before it resumes.", hint: "A person checks the cause the message names and fixes it, then resumes with the reason." },
77
+ { code: "loop_not_resumable", area: "cli", message: "The loop cannot be resumed.", hint: "Stop the run, fix the cause and start a new run." },
78
+ { code: "sandbox_harness_not_allowed", area: "cli", message: "The solution may not use the Sandbox.", hint: "A person grants Sandbox Access (the allowed solutions) in the Admin." },
79
+ { code: "sandbox_capability_unavailable", area: "cli", message: "The instance does not offer this Sandbox capability.", hint: "The instance may be older than the feature; `cavelon status` shows its version." },
80
+ { code: "sandbox_validation_receipt_unavailable", area: "cli", message: "The instance does not offer a Sandbox validation receipt.", hint: "The instance may be older than the feature; `cavelon status` shows its version." },
81
+ { code: "sandbox_workspace_refresh_unavailable", area: "cli", message: "The instance does not offer refreshing a Sandbox workspace.", hint: "The instance may be older than the feature; `cavelon status` shows its version." },
82
+ { code: "sandbox_transfer_size_limit", area: "cli", message: "The archive is larger than a Sandbox imports at once.", hint: "Seed fewer or smaller files; a seed replaces the whole workspace." },
83
+ { code: "sandbox_artifact_digest_mismatch", area: "cli", message: "The export arrived with another digest than the instance declared; nothing was written.", hint: "Download it again." },
84
+ { code: "invalid_job_id", area: "cli", message: "The instance returned an unexpected job id.", hint: "Retry; if it repeats, report it with the command." },
85
+ { code: "usage", area: "cli", message: "The command was called the wrong way (a missing or invalid argument or option).", hint: "`cavelon <command> --help` shows its arguments." },
86
+ { code: "validation_failed", area: "cli", message: "A value did not pass the check before it was sent, or the instance refused it as invalid.", hint: "The message names the field; `cavelon api describe <operation>` shows the shape." },
87
+ { code: "cancelled", area: "cli", message: "Nothing was chosen or confirmed, so nothing changed.", hint: "Run the command again, or name the choice with an option." },
88
+ ];
89
+ export function kitErrorEntry(code) {
90
+ return KIT_ERROR_CODES.find((e) => e.code === code);
91
+ }
package/dist/limits.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { CavelonError, ExitCode } from "./errors.js";
2
+ import { readPrincipal } from "./principal.js";
2
3
  import { cavelonCommand } from "./shell.js";
3
4
  const NEAR = 0.8;
4
5
  export function changedBy(limit) {
@@ -253,8 +254,18 @@ export async function readQuotas(ctx, limits) {
253
254
  throw error;
254
255
  return { ...base, items: [], unavailable: `${link.path}: ${error.message}` };
255
256
  }
257
+ if (response.status === 403) {
258
+ const ceiling = (await readPrincipal(client).catch(() => undefined))?.token?.ceiling_role;
259
+ return {
260
+ ...base,
261
+ items: [],
262
+ unavailable_status: 403,
263
+ unavailable: `this token${ceiling ? ` (ceiling ${ceiling})` : ""} may not read the tenant's quota usage (${link.path} answered 403). ` +
264
+ "A token whose ceiling includes it, such as a tenant owner's or administrator's, sees the quotas, and so does the Admin; the limits still stand.",
265
+ };
266
+ }
256
267
  if (response.status !== 200 || !response.data || typeof response.data !== "object") {
257
- return { ...base, items: [], unavailable: `${link.path} answered ${response.status}.` };
268
+ return { ...base, items: [], unavailable: `${link.path} answered ${response.status}.`, unavailable_status: response.status };
258
269
  }
259
270
  const items = Object.entries(response.data)
260
271
  .filter((entry) => Boolean(entry[1]) && typeof entry[1] === "object" && !Array.isArray(entry[1]))
@@ -26,18 +26,34 @@ export async function fileDigest(file) {
26
26
  const bytes = await fs.readFile(file).catch(() => undefined);
27
27
  return bytes && createHash("sha256").update(bytes).digest("hex");
28
28
  }
29
- export async function writePulledFiles(root, files) {
29
+ export async function fileDigests(root, files) {
30
30
  const digests = {};
31
31
  for (const file of files) {
32
32
  const value = await fileDigest(path.join(root, file));
33
33
  if (value)
34
34
  digests[file] = value;
35
35
  }
36
- await writeState(root, PULLED_FILES, JSON.stringify({ digests }, null, 2));
36
+ return digests;
37
+ }
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));
42
+ }
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));
37
53
  }
38
54
  export async function readPulledFiles(root) {
39
- const stored = await readJsonFile(path.join(stateDir(root), PULLED_FILES));
40
- 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 : {};
41
57
  }
42
58
  export function digest(value) {
43
59
  return createHash("sha256").update(JSON.stringify(value)).digest("hex");
@@ -59,7 +75,15 @@ export async function loadPreview(root, previewId) {
59
75
  export async function deletePreview(root, previewId) {
60
76
  await fs.rm(previewFile(root, previewId), { force: true });
61
77
  }
62
- 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) {
63
87
  const dir = path.join(stateDir(root), "previews");
64
88
  let names;
65
89
  try {
@@ -71,8 +95,9 @@ export async function listPreviews(root) {
71
95
  const out = [];
72
96
  for (const name of names.filter((n) => n.endsWith(".json"))) {
73
97
  const stored = await readJsonFile(path.join(dir, name));
74
- if (stored?.preview_id)
75
- 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
+ }
76
101
  }
77
102
  return out.sort((a, b) => (a.created_at < b.created_at ? 1 : -1));
78
103
  }
package/dist/main.js CHANGED
@@ -1,8 +1,10 @@
1
1
  import { parseArgs } from "node:util";
2
2
  import { GLOBAL_OPTIONS } from "./command.js";
3
3
  import { createContext, withWarnings } from "./context.js";
4
+ import { CONFIRM_TOKEN } from "./confirm-token.js";
4
5
  import { asCavelonError, ExitCode, usageError } from "./errors.js";
5
6
  import { blockerLines } from "./format.js";
7
+ import { blockerLines as detailedBlockerLines } from "./preview-report.js";
6
8
  import { KIT_VERSION } from "./version.js";
7
9
  import { currentInstall, installLabel } from "./install.js";
8
10
  import { startUpdateCheck } from "./update-check.js";
@@ -33,7 +35,8 @@ export async function run(argv, io, commands = COMMANDS, updates = {}) {
33
35
  throw usageError(`Unknown command "${words.slice(0, 2).join(" ") || argv[0]}".`, group.length ? `Try: ${group.map((c) => `cavelon ${c.name}`).join(", ")}` : "Run `cavelon --help` for the commands.");
34
36
  }
35
37
  const { spec, rest } = found;
36
- const args = spec.preprocess ? spec.preprocess(rest) : rest;
38
+ const early = [];
39
+ const args = spec.preprocess ? spec.preprocess(rest, (message) => early.push(message)) : rest;
37
40
  const parsed = parse(spec, args);
38
41
  if (parsed.options.help === true) {
39
42
  io.stdout.write(commandHelp(spec));
@@ -45,6 +48,8 @@ export async function run(argv, io, commands = COMMANDS, updates = {}) {
45
48
  tenant: typeof parsed.options.tenant === "string" ? parsed.options.tenant : undefined,
46
49
  solutionEnv: spec.options?.env && typeof parsed.options.env === "string" ? parsed.options.env : undefined,
47
50
  });
51
+ for (const message of early)
52
+ ctx.warn(message);
48
53
  notice = startUpdateCheck({
49
54
  io,
50
55
  version: KIT_VERSION,
@@ -112,8 +117,9 @@ function parse(spec, args) {
112
117
  }
113
118
  }
114
119
  const options = { ...GLOBAL_OPTIONS, ...spec.options };
120
+ const { rest, tokens } = takeTokens(spec, args);
115
121
  const config = {
116
- args,
122
+ args: rest,
117
123
  allowPositionals: true,
118
124
  strict: true,
119
125
  options: Object.fromEntries(Object.entries(options).map(([name, o]) => [
@@ -127,10 +133,16 @@ function parse(spec, args) {
127
133
  ({ values, positionals } = parseArgs(config));
128
134
  }
129
135
  catch (error) {
130
- throw usageError(error instanceof Error ? error.message : String(error), `Run \`cavelon ${spec.name} --help\`.`);
136
+ const message = error instanceof Error ? error.message : String(error);
137
+ const unknown = /Unknown option '--([^'=\s]+)/.exec(message)?.[1];
138
+ if (unknown && spec.positionals?.some((p) => p.variadic && p.name === "params")) {
139
+ throw usageError(`Unknown option '--${unknown}'.`, `${spec.name} takes an operation's parameters as name=value: pass ${unknown}=<value> (or -p ${unknown}=<value>). Run \`cavelon ${spec.name} --help\`.`);
140
+ }
141
+ throw usageError(message, `Run \`cavelon ${spec.name} --help\`.`);
131
142
  }
132
143
  if (values.help === true)
133
144
  return { positionals: {}, options: { help: true } };
145
+ Object.assign(values, tokens);
134
146
  const named = {};
135
147
  const specs = spec.positionals ?? [];
136
148
  let index = 0;
@@ -152,6 +164,38 @@ function parse(spec, args) {
152
164
  }
153
165
  return { positionals: named, options: values };
154
166
  }
167
+ function takeTokens(spec, args) {
168
+ const names = Object.entries(spec.options ?? {})
169
+ .filter(([, o]) => o.mcpToken && o.type === "boolean")
170
+ .map(([name]) => name);
171
+ const tokens = {};
172
+ if (!names.length)
173
+ return { rest: args, tokens };
174
+ const rest = [];
175
+ for (let i = 0; i < args.length; i++) {
176
+ const arg = args[i];
177
+ if (arg === "--") {
178
+ rest.push(...args.slice(i));
179
+ break;
180
+ }
181
+ const name = names.find((n) => arg === `--${n}` || arg.startsWith(`--${n}=`));
182
+ if (!name) {
183
+ rest.push(arg);
184
+ continue;
185
+ }
186
+ const inline = arg.startsWith(`--${name}=`) ? arg.slice(name.length + 3) : undefined;
187
+ const next = args[i + 1];
188
+ if (inline)
189
+ tokens[name] = inline;
190
+ else if (inline === undefined && next !== undefined && CONFIRM_TOKEN.test(next)) {
191
+ tokens[name] = next;
192
+ i++;
193
+ }
194
+ else
195
+ rest.push(`--${name}`);
196
+ }
197
+ return { rest, tokens };
198
+ }
155
199
  function missing(spec, name) {
156
200
  return usageError(`Missing <${name}>.`, `Usage: ${usageLine(spec)}`);
157
201
  }
@@ -180,7 +224,11 @@ function printError(io, json, err, warnings) {
180
224
  return;
181
225
  }
182
226
  const lines = [`error: ${err.message}`];
183
- if (err.blockers?.length)
227
+ if (err.blockerDetails?.length) {
228
+ const more = err.blockerDetails.length - 10;
229
+ lines.push(`blockers:${detailedBlockerLines(err.blockerDetails.slice(0, 10))}${more > 0 ? `\n … ${more} more (--json)` : ""}`);
230
+ }
231
+ else if (err.blockers?.length)
184
232
  lines.push(blockerLines(err.blockers));
185
233
  if (err.hint)
186
234
  lines.push(`hint: ${err.hint}`);