@cavelon/cli 0.1.9 → 0.1.11

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 (64) hide show
  1. package/README.md +23 -10
  2. package/dist/access.js +194 -0
  3. package/dist/acting.js +123 -0
  4. package/dist/agent-env.js +20 -2
  5. package/dist/branches.js +4 -3
  6. package/dist/capacity.js +3 -2
  7. package/dist/code-hints.js +5 -4
  8. package/dist/command.js +6 -0
  9. package/dist/commands/api.js +40 -21
  10. package/dist/commands/async.js +7 -4
  11. package/dist/commands/chat.js +18 -15
  12. package/dist/commands/db.js +367 -0
  13. package/dist/commands/docs.js +87 -9
  14. package/dist/commands/fmt.js +6 -4
  15. package/dist/commands/index.js +8 -0
  16. package/dist/commands/init.js +106 -28
  17. package/dist/commands/limits-set.js +12 -11
  18. package/dist/commands/limits.js +4 -3
  19. package/dist/commands/loops.js +75 -19
  20. package/dist/commands/models.js +12 -13
  21. package/dist/commands/sandboxes.js +22 -16
  22. package/dist/commands/schema.js +6 -5
  23. package/dist/commands/session.js +134 -37
  24. package/dist/commands/setup.js +4 -2
  25. package/dist/commands/solution.js +289 -93
  26. package/dist/commands/tenants.js +58 -22
  27. package/dist/commands/values.js +110 -45
  28. package/dist/commands/work.js +31 -17
  29. package/dist/confirm-token.js +15 -5
  30. package/dist/context.js +3 -1
  31. package/dist/contracts.js +39 -13
  32. package/dist/database-queries.js +301 -0
  33. package/dist/default-route.js +1 -1
  34. package/dist/features.js +2 -1
  35. package/dist/fsutil.js +14 -0
  36. package/dist/harness-ref.js +6 -4
  37. package/dist/http.js +39 -4
  38. package/dist/invoke.js +7 -2
  39. package/dist/kit-codes.js +14 -2
  40. package/dist/limits.js +1 -1
  41. package/dist/main.js +13 -1
  42. package/dist/mcp.js +105 -26
  43. package/dist/openapi.js +5 -2
  44. package/dist/operations.js +3 -2
  45. package/dist/package-check.js +29 -4
  46. package/dist/package-files.js +5 -1
  47. package/dist/package-format.js +10 -0
  48. package/dist/preview-report.js +46 -7
  49. package/dist/principal.js +24 -2
  50. package/dist/printed.js +182 -0
  51. package/dist/project.js +2 -1
  52. package/dist/results.js +1 -1
  53. package/dist/secret-access.js +42 -0
  54. package/dist/session.js +39 -19
  55. package/dist/shell.js +0 -3
  56. package/dist/skills/cavelon-authoring/SKILL.md +88 -4
  57. package/dist/skills/cavelon-long-running/SKILL.md +9 -3
  58. package/dist/skills/cavelon-loop/SKILL.md +81 -19
  59. package/dist/skills/cavelon-testing/SKILL.md +28 -1
  60. package/dist/tenant-choice.js +7 -7
  61. package/dist/trace-view.js +11 -1
  62. package/dist/update-check.js +2 -2
  63. package/dist/user-config.js +24 -0
  64. package/package.json +1 -1
@@ -0,0 +1,301 @@
1
+ import path from "node:path";
2
+ import { readJsonFile } from "./fsutil.js";
3
+ import { stateDir, writeState } from "./local-state.js";
4
+ import { locate } from "./package-files.js";
5
+ import { canonical, settledForm } from "./package-format.js";
6
+ export const QUERY_TOOL_TYPE = "database_query";
7
+ const QUERY_FIELD = "database_query";
8
+ const TOOLS_SECTION = "tools";
9
+ const DERIVED_FIELDS = ["params_json_schema", "default_config"];
10
+ const QUERY_FIELDS = ["name", "description", QUERY_FIELD];
11
+ export const QUERY_CHANGED_CODE = "database_query_changed";
12
+ export const QUERY_FIELDS_IGNORED_CODE = "database_query_fields_ignored";
13
+ export const NEEDS_SUPERADMIN_CODE = "database_query_needs_superadmin";
14
+ const BASELINE_FILE = "database-queries.json";
15
+ const isObject = (v) => Boolean(v) && typeof v === "object" && !Array.isArray(v);
16
+ function resolveRef(schema, node) {
17
+ let current = isObject(node) ? node : undefined;
18
+ for (let hops = 0; current && typeof current.$ref === "string" && hops < 10; hops++) {
19
+ const ref = current.$ref;
20
+ if (!ref.startsWith("#/$defs/"))
21
+ return undefined;
22
+ current = schema.$defs?.[ref.slice("#/$defs/".length)];
23
+ }
24
+ return current;
25
+ }
26
+ function toolSchema(schema) {
27
+ if (!schema)
28
+ return undefined;
29
+ const tools = resolveRef(schema, schema.properties?.[TOOLS_SECTION]);
30
+ return resolveRef(schema, tools?.items);
31
+ }
32
+ export function schemaKnowsQueries(schema) {
33
+ const properties = toolSchema(schema)?.properties;
34
+ return isObject(properties) && QUERY_FIELD in properties;
35
+ }
36
+ function parameterSchema(schema) {
37
+ const field = toolSchema(schema)?.properties?.[QUERY_FIELD];
38
+ const branches = isObject(field) && Array.isArray(field.anyOf) ? field.anyOf : [field];
39
+ for (const branch of branches) {
40
+ const query = resolveRef(schema, branch);
41
+ const parameters = query?.properties?.parameters;
42
+ const items = isObject(parameters) ? resolveRef(schema, parameters.items) : undefined;
43
+ if (items)
44
+ return items;
45
+ }
46
+ return undefined;
47
+ }
48
+ export function queryTools(pkg) {
49
+ const tools = pkg[TOOLS_SECTION];
50
+ if (!Array.isArray(tools))
51
+ return [];
52
+ return tools.flatMap((tool, index) => isObject(tool) && tool.tool_type === QUERY_TOOL_TYPE && typeof tool.slug === "string" ? [{ index, slug: tool.slug, tool }] : []);
53
+ }
54
+ const BIND = /(?<![:\p{L}\p{N}_\\]):([\p{L}\p{N}_]+)(?!:)/gu;
55
+ export function bindNames(sql) {
56
+ const names = [];
57
+ for (const match of sql.matchAll(BIND))
58
+ if (!names.includes(match[1]))
59
+ names.push(match[1]);
60
+ return names;
61
+ }
62
+ const CONSTRAINTS_BY_TYPE = {
63
+ string: ["max_length", "pattern", "enum"],
64
+ integer: ["minimum", "maximum", "enum"],
65
+ number: ["minimum", "maximum", "enum"],
66
+ };
67
+ const CONSTRAINTS = ["max_length", "pattern", "enum", "minimum", "maximum"];
68
+ const problem = (code, message, at) => ({ code, message, ...(at ? { at } : {}) });
69
+ const isNumber = (v) => typeof v === "number" && Number.isFinite(v);
70
+ function parameterProblems(p, index, defaults) {
71
+ const name = typeof p.name === "string" ? p.name : `#${index + 1}`;
72
+ const source = p.source ?? defaults.source;
73
+ const type = typeof (p.type ?? defaults.type) === "string" ? String(p.type ?? defaults.type) : "string";
74
+ const required = p.required ?? defaults.required;
75
+ const at = `parameters/${index}`;
76
+ const said = (what) => `parameter '${name}': ${what}`;
77
+ const set = CONSTRAINTS.filter((key) => p[key] !== undefined && p[key] !== null);
78
+ if (typeof source === "string" && source !== defaults.source) {
79
+ if (type !== "string")
80
+ return [problem("parameter_context_not_string", said(`a context parameter (${source}) has type string`), `${at}/type`)];
81
+ if (required === false)
82
+ return [problem("parameter_context_optional", said(`a context parameter (${source}) is always required`), `${at}/required`)];
83
+ if (set.length)
84
+ return [problem("parameter_context_constrained", said(`the platform fills a context parameter, so ${set.join(", ")} does not apply`), `${at}/${set[0]}`)];
85
+ return [];
86
+ }
87
+ const problems = [];
88
+ if (typeof p.description !== "string" || !p.description.trim()) {
89
+ problems.push(problem("parameter_description_missing", said("the model needs a description of what to fill in"), at));
90
+ }
91
+ const misplaced = set.filter((key) => !(CONSTRAINTS_BY_TYPE[type] ?? []).includes(key));
92
+ if (misplaced.length) {
93
+ problems.push(problem("parameter_constraint_not_applicable", said(`${misplaced.join(", ")} does not apply to type ${type}`), `${at}/${misplaced[0]}`));
94
+ return problems;
95
+ }
96
+ if (isNumber(p.minimum) && isNumber(p.maximum) && p.minimum > p.maximum) {
97
+ problems.push(problem("parameter_bounds_inverted", said("minimum is greater than maximum"), `${at}/minimum`));
98
+ }
99
+ if (type === "integer" && [p.minimum, p.maximum].some((b) => isNumber(b) && !Number.isInteger(b))) {
100
+ problems.push(problem("parameter_bounds_not_integer", said("an integer's bounds must be integers"), at));
101
+ }
102
+ if (Array.isArray(p.enum)) {
103
+ const fits = (v) => type === "string"
104
+ ? typeof v === "string" && (!isNumber(p.max_length) || v.length <= p.max_length)
105
+ : type === "integer"
106
+ ? Number.isInteger(v)
107
+ : isNumber(v);
108
+ if (!p.enum.every(fits))
109
+ problems.push(problem("parameter_enum_invalid", said(`every enum value must be a ${type} within its limits`), `${at}/enum`));
110
+ else if (new Set(p.enum.map((v) => JSON.stringify(v))).size !== p.enum.length)
111
+ problems.push(problem("parameter_enum_repeats", said("enum values repeat"), `${at}/enum`));
112
+ }
113
+ return problems;
114
+ }
115
+ export function queryProblems(query, schema) {
116
+ const props = (parameterSchema(schema)?.properties ?? {});
117
+ const defaults = { source: props.source?.default ?? "model", type: props.type?.default ?? "string", required: props.required?.default ?? true };
118
+ const parameters = Array.isArray(query.parameters) ? query.parameters.filter(isObject) : [];
119
+ const problems = [];
120
+ const names = parameters.map((p) => p.name).filter((n) => typeof n === "string");
121
+ const repeated = [...new Set(names.filter((n, i) => names.indexOf(n) !== i))].sort((a, b) => a.localeCompare(b, "en"));
122
+ if (repeated.length)
123
+ problems.push(problem("parameter_names_repeat", `parameter names repeat: ${repeated.join(", ")}`, "parameters"));
124
+ parameters.forEach((p, index) => problems.push(...parameterProblems(p, index, defaults)));
125
+ if (typeof query.sql_text === "string" && query.sql_text.trim()) {
126
+ const found = bindNames(query.sql_text);
127
+ const missing = found.filter((n) => !names.includes(n)).sort((a, b) => a.localeCompare(b, "en"));
128
+ const unused = [...new Set(names)].filter((n) => !found.includes(n)).sort((a, b) => a.localeCompare(b, "en"));
129
+ if (missing.length || unused.length) {
130
+ const parts = [
131
+ ...(missing.length ? [`placeholders without a declared parameter: ${missing.map((n) => `:${n}`).join(", ")}`] : []),
132
+ ...(unused.length ? [`declared parameters the SQL never uses: ${unused.join(", ")}`] : []),
133
+ ];
134
+ problems.push(problem("bind_mismatch", `The SQL and its parameters disagree; ${parts.join("; ")}.`, "sql_text"));
135
+ }
136
+ }
137
+ const context = parameters.some((p) => typeof p.source === "string" && p.source !== defaults.source);
138
+ if (query.allows_anonymous === true && context) {
139
+ problems.push(problem("anonymous_with_context_parameter", "allows_anonymous is true, but a parameter is filled from the signed-in visitor's identity, so the query needs a visitor anyway.", "allows_anonymous"));
140
+ }
141
+ return problems;
142
+ }
143
+ function settledTool(schema, tool) {
144
+ const settled = settledForm(schema, schema.properties?.[TOOLS_SECTION], [tool]);
145
+ return Array.isArray(settled) && isObject(settled[0]) ? settled[0] : tool;
146
+ }
147
+ function baselineOf(schema, tool) {
148
+ const settled = settledTool(schema, tool);
149
+ const out = {};
150
+ for (const key of [...QUERY_FIELDS, ...DERIVED_FIELDS])
151
+ if (settled[key] !== undefined)
152
+ out[key] = settled[key];
153
+ return out;
154
+ }
155
+ export async function readQueryBaseline(root) {
156
+ const stored = await readJsonFile(path.join(stateDir(root), BASELINE_FILE));
157
+ return stored && isObject(stored.tools) ? stored : undefined;
158
+ }
159
+ export async function rememberQueries(root, pkg, schema, by, now) {
160
+ if (!schema || !schemaKnowsQueries(schema))
161
+ return;
162
+ const previous = by === "apply" ? (await readQueryBaseline(root))?.tools : undefined;
163
+ const tools = {};
164
+ for (const { slug, tool } of queryTools(pkg)) {
165
+ const kept = previous?.[slug];
166
+ tools[slug] = !isObject(tool[QUERY_FIELD]) && kept ? { ...baselineOf(schema, tool), ...pick(kept, QUERY_FIELDS) } : baselineOf(schema, tool);
167
+ }
168
+ const baseline = { written_at: now.toISOString(), by, tools };
169
+ await writeState(root, BASELINE_FILE, `${JSON.stringify(baseline, null, 2)}\n`);
170
+ }
171
+ function pick(tool, keys) {
172
+ const out = {};
173
+ for (const key of keys)
174
+ if (tool[key] !== undefined)
175
+ out[key] = tool[key];
176
+ return out;
177
+ }
178
+ const same = (a, b) => canonical(a ?? null) === canonical(b ?? null);
179
+ export function queryChanges(pkg, schema, baseline) {
180
+ const out = [];
181
+ for (const { slug, index, tool } of queryTools(pkg)) {
182
+ if (!isObject(tool[QUERY_FIELD]))
183
+ continue;
184
+ const before = baseline.tools[slug];
185
+ const now = baselineOf(schema, tool);
186
+ if (!before) {
187
+ out.push({ slug, index, created: true, fields: [...QUERY_FIELDS] });
188
+ continue;
189
+ }
190
+ const fields = QUERY_FIELDS.filter((key) => !same(before[key], now[key]));
191
+ if (fields.length)
192
+ out.push({ slug, index, created: false, fields });
193
+ }
194
+ return out;
195
+ }
196
+ export function checkQueryTools(disk, schema, baseline) {
197
+ if (!schemaKnowsQueries(schema))
198
+ return [];
199
+ const findings = [];
200
+ for (const { slug, index, tool } of queryTools(disk.package)) {
201
+ const query = tool[QUERY_FIELD];
202
+ if (!isObject(query))
203
+ continue;
204
+ for (const problem of queryProblems(query, schema)) {
205
+ findings.push({
206
+ code: problem.code,
207
+ severity: "error",
208
+ ...locate(disk, `/${TOOLS_SECTION}/${index}/${QUERY_FIELD}${problem.at ? `/${problem.at}` : ""}`),
209
+ message: `Query tool "${slug}": ${problem.message}`,
210
+ });
211
+ }
212
+ }
213
+ if (!baseline)
214
+ return findings;
215
+ for (const change of queryChanges(disk.package, schema, baseline)) {
216
+ const what = change.created
217
+ ? `is new since the last ${baseline.by}: creating a query`
218
+ : `changes its ${change.fields.map((f) => (f === QUERY_FIELD ? "query (database_query)" : f)).join(", ")} since the last ${baseline.by}: ` +
219
+ `${change.fields.some((f) => f !== QUERY_FIELD) ? "a query tool's own name and description belong to the query, and changing one" : "changing a query"}`;
220
+ findings.push({
221
+ code: QUERY_CHANGED_CODE,
222
+ severity: "warning",
223
+ ...locate(disk, `/${TOOLS_SECTION}/${change.index}`),
224
+ message: `Query tool "${change.slug}" ${what} needs a superadmin in the Admin, and the import preview of a personal access token ` +
225
+ `blocks it (${NEEDS_SUPERADMIN_CODE}). An agent's or skill's override of the tool's name, description or max_calls is no query change.`,
226
+ });
227
+ }
228
+ for (const { slug, index, tool } of queryTools(disk.package)) {
229
+ const before = baseline.tools[slug];
230
+ if (!before)
231
+ continue;
232
+ const now = baselineOf(schema, tool);
233
+ const edited = DERIVED_FIELDS.filter((key) => !same(before[key], now[key]));
234
+ if (!edited.length)
235
+ continue;
236
+ findings.push({
237
+ code: QUERY_FIELDS_IGNORED_CODE,
238
+ severity: "warning",
239
+ ...locate(disk, `/${TOOLS_SECTION}/${index}/${edited[0]}`),
240
+ message: `Query tool "${slug}" changes its ${edited.join(" and ")}; the instance derives ${edited.length === 1 ? "it" : "them"} from the query's parameters and ignores the package's.`,
241
+ });
242
+ }
243
+ return findings;
244
+ }
245
+ export function connectorOffer(caps) {
246
+ const features = isObject(caps?.features) ? caps.features : {};
247
+ const section = isObject(caps?.database_connector) ? caps.database_connector : {};
248
+ return {
249
+ ...(typeof features.database_connector_enabled === "boolean" ? { enabled: features.database_connector_enabled } : {}),
250
+ ...(Array.isArray(section.dialects) ? { dialects: section.dialects.filter((d) => typeof d === "string") } : {}),
251
+ ...(typeof section.may_write_queries === "boolean" ? { may_write_queries: section.may_write_queries } : {}),
252
+ ...(typeof section.setting === "string" ? { setting: section.setting } : {}),
253
+ ...(typeof section.queries_written_by === "string" ? { queries_written_by: section.queries_written_by } : {}),
254
+ };
255
+ }
256
+ const named = (slugs) => slugs.map((s) => `"${s}"`).join(", ");
257
+ export function applyQueryNotes(pkg, changes, offer) {
258
+ const tools = queryTools(pkg);
259
+ if (!tools.length)
260
+ return { warnings: [] };
261
+ const warnings = [];
262
+ const setting = offer.setting ?? "its setting";
263
+ if (offer.enabled === false) {
264
+ warnings.push(`The package holds database query tools (${named(tools.map((t) => t.slug))}), and this instance has the database connector switched off (${setting}): ` +
265
+ "the import may carry them, but no agent gets a database tool until its operator switches the connector on.");
266
+ }
267
+ else if (offer.enabled && offer.dialects) {
268
+ const unrun = tools.filter((t) => {
269
+ const dialect = isObject(t.tool[QUERY_FIELD]) && isObject(t.tool[QUERY_FIELD].connection) ? t.tool[QUERY_FIELD].connection.dialect : undefined;
270
+ return typeof dialect === "string" && !offer.dialects.includes(dialect);
271
+ });
272
+ if (unrun.length) {
273
+ warnings.push(`This instance runs ${offer.dialects.length ? `only ${offer.dialects.join(", ")} queries` : "no database queries"}; ${named(unrun.map((t) => t.slug))} ` +
274
+ `${unrun.length === 1 ? "names" : "name"} another dialect, so no agent can call ${unrun.length === 1 ? "it" : "them"} here.`);
275
+ }
276
+ }
277
+ const slugs = changes.map((c) => c.slug);
278
+ if (slugs.length && offer.may_write_queries === false) {
279
+ warnings.push(`This apply would ${changes.every((c) => c.created) ? "create" : "create or change"} the database quer${slugs.length === 1 ? "y" : "ies"} ${named(slugs)}, ` +
280
+ `which this credential may not do (may_write_queries is false): the preview blocks ${slugs.length === 1 ? "it" : "them"}, and one blocked query stops the whole import. ` +
281
+ (offer.queries_written_by ? `${offer.queries_written_by} ` : "") +
282
+ "To apply the rest first, leave each such query as the instance holds it (restore the tool's entry as the last pull wrote it, or remove its database_query block).");
283
+ }
284
+ return {
285
+ warnings,
286
+ data: {
287
+ tools: tools.map((t) => t.slug),
288
+ changed: changes.map((c) => ({ slug: c.slug, created: c.created, fields: c.fields })),
289
+ connector_enabled: offer.enabled ?? null,
290
+ dialects: offer.dialects ?? null,
291
+ may_write_queries: offer.may_write_queries ?? null,
292
+ },
293
+ };
294
+ }
295
+ export function queryBlockedHint(files) {
296
+ const where = files.length ? ` in ${files.join(", ")}` : "";
297
+ return ("A database query the import would create or change stops the whole import: nothing is applied while one blocks. " +
298
+ "A superadmin applies it in the Admin (the blocker's hint names where); after that, apply passes while the queries match. " +
299
+ `To apply the other changes first, leave each blocked query as the instance holds it${where}: restore the tool's entry as the last pull wrote it, ` +
300
+ "or remove its database_query block (the tool then keeps the instance's query, name and description), and apply again.");
301
+ }
@@ -1,6 +1,6 @@
1
1
  import { listHarnesses } from "./harness-ref.js";
2
2
  import { callStable } from "./invoke.js";
3
- import { cavelonCommand } from "./shell.js";
3
+ import { cavelonCommand } from "./printed.js";
4
4
  export async function readDefaultRoute(ctx) {
5
5
  const all = await listHarnesses(ctx);
6
6
  const known = all.some((h) => typeof h.is_default === "boolean");
package/dist/features.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import { stringOption } from "./command.js";
3
3
  import { CavelonError, ExitCode, usageError } from "./errors.js";
4
+ import { cavelonCommand } from "./printed.js";
4
5
  import { isUuid } from "./session.js";
5
6
  export async function requireFeature(ctx, feature, code, what) {
6
7
  const caps = await (await ctx.contracts()).capabilities();
@@ -8,7 +9,7 @@ export async function requireFeature(ctx, feature, code, what) {
8
9
  throw new CavelonError(ExitCode.failure, {
9
10
  code,
10
11
  message: `This instance has ${what} switched off.`,
11
- hint: `Its operator switches it on (${feature.toUpperCase()}); \`cavelon status\` shows the instance.`,
12
+ hint: `Its operator switches it on (${feature.toUpperCase()}); \`${cavelonCommand("status")}\` shows the instance.`,
12
13
  });
13
14
  }
14
15
  }
package/dist/fsutil.js CHANGED
@@ -41,3 +41,17 @@ export async function writeFileAtomic(file, content, mode = 0o644, dirMode = 0o7
41
41
  await fs.chmod(tmp, existing & mode).catch(() => undefined);
42
42
  await fs.rename(tmp, file);
43
43
  }
44
+ export async function writePrivateFile(base, file, content) {
45
+ await writeFileAtomic(file, content, 0o600, 0o700);
46
+ const root = path.resolve(base);
47
+ for (let dir = path.dirname(path.resolve(file));; dir = path.dirname(dir)) {
48
+ const rel = path.relative(root, dir);
49
+ if (rel === ".." || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel))
50
+ break;
51
+ const mode = await fs.stat(dir).then((st) => st.mode & 0o777, () => undefined);
52
+ if (mode !== undefined && mode & 0o077)
53
+ await fs.chmod(dir, mode & 0o700).catch(() => undefined);
54
+ if (rel === "")
55
+ break;
56
+ }
57
+ }
@@ -1,7 +1,8 @@
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 { contextFlags, isUuid } from "./session.js";
4
+ import { cavelonCommand, fill } from "./printed.js";
5
+ import { isUuid } from "./session.js";
5
6
  import { shellWord } from "./shell.js";
6
7
  function notFound(error) {
7
8
  return error instanceof CavelonError && error.status === 404;
@@ -33,14 +34,15 @@ export async function lookupHarness(ctx, ref) {
33
34
  return { harness: hit, candidates: [] };
34
35
  return { candidates: closest(all, ref) };
35
36
  }
36
- export function harnessNotFoundError(ref, candidates, source, command, flags = "") {
37
+ export function harnessNotFoundError(ref, candidates, source, command) {
37
38
  const near = candidates.map(displayName).join(", ");
38
39
  const lines = candidates.map((h) => ` ${command ? command(h.slug) : `--harness ${shellWord(h.slug)}`}`).join("\n");
39
40
  return new CavelonError(ExitCode.failure, {
40
41
  code: "solution_not_found",
41
42
  message: `No solution "${ref}" in this tenant${source ? ` (from ${source})` : ""}.${near ? ` Closest: ${near}.` : ""}`,
42
43
  hint: (candidates.length ? `If you meant one of them:\n${lines}\n` : "") +
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
+ `\`${cavelonCommand("harness", "list")}\` shows this tenant's solutions with name, slug and id; ` +
45
+ `\`${cavelonCommand("harness", "new", fill("slug"), "--name", fill("name"))}\` creates one as a draft.`,
44
46
  details: candidates.length ? { candidates: candidates.map((h) => ({ id: h.id, slug: h.slug, name: h.name })) } : undefined,
45
47
  });
46
48
  }
@@ -49,7 +51,7 @@ export async function resolveHarnessId(ctx, ref) {
49
51
  return ref;
50
52
  const { harness, candidates } = await lookupHarness(ctx, ref);
51
53
  if (!harness)
52
- throw harnessNotFoundError(ref, candidates, undefined, undefined, contextFlags(await ctx.session()));
54
+ throw harnessNotFoundError(ref, candidates);
53
55
  return harness.id;
54
56
  }
55
57
  export function slugFromName(name) {
package/dist/http.js CHANGED
@@ -1,7 +1,9 @@
1
+ import { accessFor, forbiddenHint } from "./access.js";
1
2
  import { capacityCodeIn, capacityHint } from "./capacity.js";
2
3
  import { ceilingRefusal, LIMIT_ABOVE_CEILING } from "./limits.js";
3
4
  import { CavelonError, ExitCode } from "./errors.js";
4
5
  import { blockerDetails } from "./preview-report.js";
6
+ import { cavelonCommand } from "./printed.js";
5
7
  import { KIT_VERSION } from "./version.js";
6
8
  const RUNTIME = process.versions.bun ? "bun/" + process.versions.bun : "node/" + process.versions.node;
7
9
  export const DEFAULT_TIMEOUT_MS = 30_000;
@@ -27,6 +29,7 @@ export class ApiClient {
27
29
  target;
28
30
  env;
29
31
  tokensOff;
32
+ revalidateTenant;
30
33
  constructor(target, env = {}) {
31
34
  this.target = target;
32
35
  this.env = env;
@@ -117,17 +120,41 @@ export class ApiClient {
117
120
  });
118
121
  }
119
122
  if (!response.ok && !options.allow?.includes(response.status)) {
123
+ if (await this.tenantMoved(method, path, response.status, options))
124
+ return this.request(method, path, options);
120
125
  const tenantless = options.sendTenant !== false && !this.headers(options)["X-Tenant-Id"] && Boolean(this.target.token?.startsWith("cvpat_"));
121
126
  const pathname = new URL(response.url || this.resolve(path)).pathname;
122
127
  const platform = options.sendTenant === false || isPlatformRoute(pathname);
123
- throw await this.refusal(response.status, data, `${method} ${pathname}`, response.headers, { tenantless, platform });
128
+ throw await this.refusal(response.status, data, `${method} ${pathname}`, response.headers, { tenantless, platform, method, path: pathname });
124
129
  }
125
130
  return { status: response.status, headers: response.headers, data: data, text };
126
131
  }
132
+ async tenantMoved(method, path, status, options = {}) {
133
+ const sentTenant = this.headers(options)["X-Tenant-Id"];
134
+ if ((status !== 403 && status !== 404) || !sentTenant || !this.revalidateTenant)
135
+ return false;
136
+ const revalidate = this.revalidateTenant;
137
+ this.revalidateTenant = undefined;
138
+ if (!(await revalidate()))
139
+ return false;
140
+ if (method === "GET" || method === "HEAD")
141
+ return true;
142
+ throw new CavelonError(ExitCode.conflict, {
143
+ code: "tenant_moved",
144
+ status,
145
+ message: `${method} ${path} was refused in tenant ${sentTenant}, which a cached slug named; the slug now names tenant ${this.target.tenantId}. Nothing was changed.`,
146
+ hint: "Run the command again: it now acts in the tenant the slug names, and a change previews there first.",
147
+ });
148
+ }
127
149
  async refusal(status, body, what, headers, sent = {}) {
128
150
  if (status === 401 && this.target.token?.startsWith("cvpat_") && (await this.personalAccessTokensOff())) {
129
151
  return tokensDisabledError(this.url);
130
152
  }
153
+ if (status === 403 && sent.method && sent.path && this.target.token && !sent.platform && !sent.tenantless) {
154
+ const kind = this.target.token.startsWith("cbp_") ? "api_key" : this.target.token.startsWith("cvpat_") ? "personal_access_token" : undefined;
155
+ const access = await accessFor(this).catch(() => undefined);
156
+ sent = { ...sent, credential: { kind, access, method: sent.method, path: sent.path } };
157
+ }
131
158
  return errorFromResponse(status, body, what, headers, sent);
132
159
  }
133
160
  personalAccessTokensOff() {
@@ -274,7 +301,7 @@ export function errorFromResponse(status, body, what, headers, sent = {}) {
274
301
  hint = retryAfter ? `Retry after ${retryAfter} seconds.` : "Retry later.";
275
302
  const capacity = capacityCodeIn(code) ?? (status === 429 || status === 503 ? capacityCodeIn(message) : undefined);
276
303
  if (capacity)
277
- hint = [hint, capacityHint(capacity), `\`cavelon explain ${capacity}\` says more.`].filter(Boolean).join(" ");
304
+ hint = [hint, capacityHint(capacity), `\`${cavelonCommand("explain", capacity)}\` says more.`].filter(Boolean).join(" ");
278
305
  const ceiling = code === LIMIT_ABOVE_CEILING ? ceilingRefusal(body) : undefined;
279
306
  if (ceiling) {
280
307
  hint = ceiling.hint;
@@ -283,7 +310,7 @@ export function errorFromResponse(status, body, what, headers, sent = {}) {
283
310
  if (changed)
284
311
  details = details && typeof details === "object" && !Array.isArray(details) ? { ...details, changed } : { changed };
285
312
  if (status === 400 && !hint && message && /select a tenant|tenant context|X-Tenant-Id/i.test(message)) {
286
- hint = "Choose a tenant with `cavelon use` (it lists your tenants), --tenant or CAVELON_TENANT.";
313
+ hint = `Choose a tenant with \`${cavelonCommand("use")}\` (it lists your tenants), --tenant or CAVELON_TENANT.`;
287
314
  }
288
315
  if ((status === 401 || status === 403) && !hint) {
289
316
  hint =
@@ -293,7 +320,15 @@ export function errorFromResponse(status, body, what, headers, sent = {}) {
293
320
  ? PLATFORM_ROUTE_HINT
294
321
  : sent.tenantless
295
322
  ? `No tenant was named. ${TENANT_ID_HINT} Otherwise check the token's permission ceiling.`
296
- : "The token does not reach this. Check the tenant (`cavelon whoami`) and the token's permission ceiling.";
323
+ : sent.credential
324
+ ? undefined
325
+ : `The token does not reach this. Check the tenant (\`${cavelonCommand("whoami")}\`) and the token's permission ceiling.`;
326
+ if (!hint && sent.credential) {
327
+ const forbidden = forbiddenHint(message ?? "", sent.credential);
328
+ hint = forbidden.hint;
329
+ if (details === undefined)
330
+ details = forbidden.details;
331
+ }
297
332
  }
298
333
  return new CavelonError(exitCode, {
299
334
  code: code ?? defaultCode(status),
package/dist/invoke.js CHANGED
@@ -3,6 +3,7 @@ import path from "node:path";
3
3
  import { CavelonError, ExitCode, validationError } from "./errors.js";
4
4
  import { bodyBytes, isPlatformRoute } from "./http.js";
5
5
  import { coerceParameter, isArrayParameter, operationAt, validateBody } from "./openapi.js";
6
+ import { cavelonCommand } from "./printed.js";
6
7
  export async function openapiOrWarn(ctx) {
7
8
  try {
8
9
  return await (await ctx.contracts()).openapi();
@@ -107,9 +108,13 @@ export async function callOperation(ctx, client, doc, op, args) {
107
108
  }
108
109
  }
109
110
  if (!response.ok) {
111
+ if (await client.tenantMoved(op.method, target, response.status, { sendTenant: args.sendTenant }))
112
+ return callOperation(ctx, client, doc, op, args);
110
113
  const pathname = new URL(client.resolve(target)).pathname;
111
114
  throw await client.refusal(response.status, data, `${op.method} ${pathname}`, response.headers, {
112
115
  platform: args.sendTenant === false || isPlatformRoute(pathname),
116
+ method: op.method,
117
+ path: pathname,
113
118
  });
114
119
  }
115
120
  return { status: response.status, contentType, data: isText ? (text ? data : null) : undefined, bytes: isText ? undefined : bytes };
@@ -122,7 +127,7 @@ export async function workflowOperation(ctx, method, pathTemplate, what) {
122
127
  throw new CavelonError(ExitCode.failure, {
123
128
  code: "operation_unavailable",
124
129
  message: `This instance does not offer ${what} (${method} ${pathTemplate} is not in its OpenAPI).`,
125
- hint: "The instance may be older than this feature; `cavelon status` shows its version.",
130
+ hint: `The instance may be older than this feature; \`${cavelonCommand("status")}\` shows its version.`,
126
131
  });
127
132
  }
128
133
  return { doc, op };
@@ -156,7 +161,7 @@ export async function callStable(ctx, method, pathTemplate, what, args = {}) {
156
161
  throw new CavelonError(ExitCode.failure, {
157
162
  code: "operation_unavailable",
158
163
  message: `This instance's ${method} ${pathTemplate} does not take ${unknown.join(", ")}, so it cannot do this (${what}).`,
159
- hint: "The instance may be older than this feature; `cavelon status` shows its version.",
164
+ hint: `The instance may be older than this feature; \`${cavelonCommand("status")}\` shows its version.`,
160
165
  });
161
166
  }
162
167
  }
package/dist/kit-codes.js CHANGED
@@ -1,9 +1,12 @@
1
+ import { printMode } from "./printed.js";
1
2
  export const KIT_ERROR_CODES = [
2
3
  { 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
4
  { 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
5
  { 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
6
  { 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
7
  { 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." },
8
+ { code: "tenant_mismatch", area: "cli", message: "The tenant API key acts only in its own tenant, and the command names another; nothing was sent there.", hint: "Use a key of the tenant you name (CAVELON_TOKEN), or name the key's tenant, or leave the tenant out where the key is meant." },
9
+ { code: "tenant_moved", area: "cli", message: "A change was refused in the tenant a cached slug named, and the slug now names another tenant; nothing was changed.", hint: "Run the command again: it acts in the tenant the slug names now, and a change previews there first." },
7
10
  { 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
11
  { 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
12
  { 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." },
@@ -28,7 +31,7 @@ export const KIT_ERROR_CODES = [
28
31
  { code: "operation_ambiguous", area: "cli", message: "The short name matches several operations.", hint: "Use the full operationId the message lists." },
29
32
  { 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
33
  { 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)." },
34
+ { 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." },
32
35
  { 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
36
  { 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
37
  { 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." },
@@ -59,6 +62,7 @@ export const KIT_ERROR_CODES = [
59
62
  { 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." },
60
63
  { 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." },
61
64
  { 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)." },
65
+ { code: "token_mismatch", area: "cli", message: "The confirm token is not the one for this change: it belongs to another preview, or the change differs from what its preview showed; nothing was changed (exit code 4).", hint: "Show the person the new preview this answer carries, and confirm only with its confirm_token after their yes; a token confirms exactly the change its preview showed." },
62
66
  { 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." },
63
67
  { 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`." },
64
68
  { 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." },
@@ -86,10 +90,18 @@ export const KIT_ERROR_CODES = [
86
90
  { 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." },
87
91
  { 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." },
88
92
  { code: "invalid_job_id", area: "cli", message: "The instance returned an unexpected job id.", hint: "Retry; if it repeats, report it with the command." },
93
+ { code: "database_connector_disabled", area: "cli", message: "This instance has the database connector switched off.", hint: "Its operator switches it on (DATABASE_CONNECTOR_ENABLED); until then no agent gets a database tool." },
94
+ { code: "database_connection_not_found", area: "cli", message: "No database connection by that name or id in this tenant.", hint: "`cavelon db connections` lists them; a superadmin creates one in the Admin." },
95
+ { code: "database_query_not_found", area: "cli", message: "No saved database query by that tool slug or id in this tenant.", hint: "`cavelon db queries` lists them; a superadmin writes one in the Admin, and `cavelon pull` brings it into the package." },
89
96
  { 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." },
90
97
  { 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." },
91
98
  { 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." },
92
99
  ];
100
+ const MCP_HINTS = {
101
+ usage: "The message names the argument; the tool's input schema lists them all.",
102
+ };
93
103
  export function kitErrorEntry(code) {
94
- return KIT_ERROR_CODES.find((e) => e.code === code);
104
+ const entry = KIT_ERROR_CODES.find((e) => e.code === code);
105
+ const mcp = entry && printMode() === "mcp" ? MCP_HINTS[code] : undefined;
106
+ return mcp ? { ...entry, hint: mcp } : entry;
95
107
  }
package/dist/limits.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { CavelonError, ExitCode } from "./errors.js";
2
2
  import { readPrincipal } from "./principal.js";
3
- import { cavelonCommand } from "./shell.js";
3
+ import { cavelonCommand } from "./printed.js";
4
4
  const NEAR = 0.8;
5
5
  export function changedBy(limit) {
6
6
  if (limit.changeable_by === "tenant_admin")
package/dist/main.js CHANGED
@@ -1,10 +1,12 @@
1
1
  import { parseArgs } from "node:util";
2
2
  import { GLOBAL_OPTIONS, optionDescription, optionFlag, renameFormerOptions } from "./command.js";
3
+ import { agentVariable } from "./agent-env.js";
3
4
  import { createContext, withWarnings } from "./context.js";
4
5
  import { CONFIRM_TOKEN } from "./confirm-token.js";
5
6
  import { asCavelonError, ExitCode, usageError } from "./errors.js";
6
7
  import { blockerLines } from "./format.js";
7
8
  import { blockerLines as detailedBlockerLines } from "./preview-report.js";
9
+ import { printingFor, spokenError } from "./printed.js";
8
10
  import { KIT_VERSION } from "./version.js";
9
11
  import { currentInstall, installLabel } from "./install.js";
10
12
  import { startUpdateCheck } from "./update-check.js";
@@ -59,7 +61,17 @@ export async function run(argv, io, commands = COMMANDS, updates = {}) {
59
61
  command: spec.name,
60
62
  fetch: updates.fetch,
61
63
  });
62
- const result = await spec.run(ctx, parsed);
64
+ const { globals } = ctx;
65
+ const given = spec.storesTarget ? {} : { instance: globals.instance, tenant: globals.tenant, env: globals.solutionEnv };
66
+ const target = { mode: "cli", commands, agentShell: Boolean(agentVariable(io.env)), ...given };
67
+ const result = await printingFor(target, async () => {
68
+ try {
69
+ return await spec.run(ctx, parsed);
70
+ }
71
+ catch (error) {
72
+ throw spokenError(error);
73
+ }
74
+ });
63
75
  printResult(ctx, result);
64
76
  await printNotice(io, notice);
65
77
  return result.exitCode ?? ExitCode.ok;