@cavelon/cli 0.1.10 → 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 (40) 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/commands/api.js +38 -19
  6. package/dist/commands/chat.js +10 -5
  7. package/dist/commands/db.js +367 -0
  8. package/dist/commands/docs.js +83 -7
  9. package/dist/commands/index.js +6 -0
  10. package/dist/commands/limits-set.js +4 -2
  11. package/dist/commands/loops.js +60 -5
  12. package/dist/commands/models.js +2 -1
  13. package/dist/commands/sandboxes.js +7 -2
  14. package/dist/commands/session.js +107 -22
  15. package/dist/commands/solution.js +144 -32
  16. package/dist/commands/tenants.js +44 -8
  17. package/dist/commands/values.js +50 -9
  18. package/dist/commands/work.js +13 -5
  19. package/dist/confirm-token.js +12 -4
  20. package/dist/context.js +3 -1
  21. package/dist/contracts.js +37 -12
  22. package/dist/database-queries.js +301 -0
  23. package/dist/fsutil.js +14 -0
  24. package/dist/http.js +36 -2
  25. package/dist/invoke.js +4 -0
  26. package/dist/kit-codes.js +5 -0
  27. package/dist/mcp.js +69 -10
  28. package/dist/package-check.js +19 -0
  29. package/dist/preview-report.js +2 -2
  30. package/dist/principal.js +24 -2
  31. package/dist/secret-access.js +16 -4
  32. package/dist/session.js +36 -8
  33. package/dist/skills/cavelon-authoring/SKILL.md +79 -2
  34. package/dist/skills/cavelon-long-running/SKILL.md +8 -2
  35. package/dist/skills/cavelon-loop/SKILL.md +71 -16
  36. package/dist/skills/cavelon-testing/SKILL.md +28 -1
  37. package/dist/trace-view.js +10 -0
  38. package/dist/update-check.js +2 -2
  39. package/dist/user-config.js +24 -0
  40. 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
+ }
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
+ }
package/dist/http.js CHANGED
@@ -1,3 +1,4 @@
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";
@@ -28,6 +29,7 @@ export class ApiClient {
28
29
  target;
29
30
  env;
30
31
  tokensOff;
32
+ revalidateTenant;
31
33
  constructor(target, env = {}) {
32
34
  this.target = target;
33
35
  this.env = env;
@@ -118,17 +120,41 @@ export class ApiClient {
118
120
  });
119
121
  }
120
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);
121
125
  const tenantless = options.sendTenant !== false && !this.headers(options)["X-Tenant-Id"] && Boolean(this.target.token?.startsWith("cvpat_"));
122
126
  const pathname = new URL(response.url || this.resolve(path)).pathname;
123
127
  const platform = options.sendTenant === false || isPlatformRoute(pathname);
124
- 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 });
125
129
  }
126
130
  return { status: response.status, headers: response.headers, data: data, text };
127
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
+ }
128
149
  async refusal(status, body, what, headers, sent = {}) {
129
150
  if (status === 401 && this.target.token?.startsWith("cvpat_") && (await this.personalAccessTokensOff())) {
130
151
  return tokensDisabledError(this.url);
131
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
+ }
132
158
  return errorFromResponse(status, body, what, headers, sent);
133
159
  }
134
160
  personalAccessTokensOff() {
@@ -294,7 +320,15 @@ export function errorFromResponse(status, body, what, headers, sent = {}) {
294
320
  ? PLATFORM_ROUTE_HINT
295
321
  : sent.tenantless
296
322
  ? `No tenant was named. ${TENANT_ID_HINT} Otherwise check the token's permission ceiling.`
297
- : `The token does not reach this. Check the tenant (\`${cavelonCommand("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
+ }
298
332
  }
299
333
  return new CavelonError(exitCode, {
300
334
  code: code ?? defaultCode(status),
package/dist/invoke.js CHANGED
@@ -108,9 +108,13 @@ export async function callOperation(ctx, client, doc, op, args) {
108
108
  }
109
109
  }
110
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);
111
113
  const pathname = new URL(client.resolve(target)).pathname;
112
114
  throw await client.refusal(response.status, data, `${op.method} ${pathname}`, response.headers, {
113
115
  platform: args.sendTenant === false || isPlatformRoute(pathname),
116
+ method: op.method,
117
+ path: pathname,
114
118
  });
115
119
  }
116
120
  return { status: response.status, contentType, data: isText ? (text ? data : null) : undefined, bytes: isText ? undefined : bytes };
package/dist/kit-codes.js CHANGED
@@ -5,6 +5,8 @@ export const KIT_ERROR_CODES = [
5
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`." },
6
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>." },
7
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." },
8
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." },
9
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." },
10
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." },
@@ -88,6 +90,9 @@ export const KIT_ERROR_CODES = [
88
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." },
89
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." },
90
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." },
91
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." },
92
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." },
93
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." },
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 { accessFor, allOf, credentialWords, operationAccess, whoInstead } from "./access.js";
3
4
  import { formerlyWarning, ownsTenant, propertyName } from "./command.js";
4
5
  import { MCP_MAX_WAIT_MS } from "./commands/async.js";
5
6
  import { createContext, withWarnings } from "./context.js";
@@ -13,7 +14,8 @@ const INSTRUCTIONS = "Tools for one Cavelon instance, acting with the token a pe
13
14
  "loop_start, sandbox_seed, artifacts_export) return operation ids at once; read them with operation_status, which returns " +
14
15
  `the state at once, or waits up to its timeout (at most ${MCP_MAX_WAIT_MS / 1000} s) when given one, and reports waited_ms, ` +
15
16
  "and follow a loop with loop_iterations. What needs confirmation: apply imports only with confirm set to a preview's id; " +
16
- "limits_set, models_set_limit, loop_cancel, sandbox_seed, trigger_identity, harness_default, activate with make_default, deactivate, " +
17
+ "tenant_create, variables_set where it replaces another value, loop_start, limits_set, models_set_limit, loop_cancel, sandbox_seed, " +
18
+ "trigger_identity, harness_default, activate of a solution a channel or trigger reaches or with make_default, deactivate, " +
17
19
  "and api for an operation that is not read-only, " +
18
20
  "return what they would do and a confirm_token, and change nothing until called again with the same arguments and " +
19
21
  "confirm set to that token: show the person the preview first. The token confirms exactly the change the preview showed; " +
@@ -21,7 +23,9 @@ const INSTRUCTIONS = "Tools for one Cavelon instance, acting with the token a pe
21
23
  "(harness_default, activate's make_default) decides which solution the tenant's chat and widget answer with: live traffic, " +
22
24
  "so ask the person, and confirm only with their yes; the same goes for deactivate, which takes a solution out of live traffic " +
23
25
  "(its status becomes inactive), and for apply with include_tenant_wide, which imports the tenant-wide sections (tenant_settings, " +
24
- "model_registry, …) for every solution of the tenant. " +
26
+ "model_registry, …) for every solution of the tenant. A new tenant, a replaced variable (every solution of the tenant reads it) and " +
27
+ "the activation of a solution a channel or trigger reaches are the person's to confirm too; confirm a loop_start on your own " +
28
+ "only for a trigger of a draft solution in a test environment (a run acts as the person and spends budget). " +
25
29
  "chat sends one message to a solution and returns its answer: the way to try one that is not the default route. " +
26
30
  "kb_upload names files that match an active document of the knowledge base; with replace it replaces them, and where the " +
27
31
  "instance's upload cannot, it returns what it would deactivate and uploads nothing without its confirm_token. " +
@@ -31,6 +35,9 @@ const INSTRUCTIONS = "Tools for one Cavelon instance, acting with the token a pe
31
35
  "(x-cavelon-person-only; its reason is in the error), or on an instance that marks none, one that changes a secret, " +
32
36
  "creates or revokes a credential (tokens, API keys, sign-in) or decides an approval; it also refuses a body that sets a field " +
33
37
  "the instance marks as a secret value (x-cavelon-secret): leave the field out and let a person enter the value. " +
38
+ "A tool whose description starts with \"Not for this credential\" is one the instance says this token or key may not use " +
39
+ "in this tenant (whoami lists its permissions, an API key's scopes and the operations a person runs): do not call it to " +
40
+ "find out; tell the person who does it. api_list marks such operations (may_send false) and leaves them out with usable. " +
34
41
  "Run from your shell, cavelon's api command applies the same guards, and sends a changing operation only with --confirm and the token " +
35
42
  "its preview printed. Tools read and write files only " +
36
43
  "inside the solution folder (the folder of cavelon.yaml, or the one the server started in), never in cavelon's own " +
@@ -38,16 +45,25 @@ const INSTRUCTIONS = "Tools for one Cavelon instance, acting with the token a pe
38
45
  "instance allows this tenant (upload sizes and types, run and tool limits, timeouts, quotas) and who changes each. " +
39
46
  "Never change a limit on your own: propose the old and new value (limits_set for a limit a tenant admin changes, " +
40
47
  "models_set_limit for an endpoint's max_concurrent_requests) and let the person decide; an operator's limit goes to the operator. " +
41
- "variables_list/variables_get/variables_set handle plain-text {{var:…}} values. secrets_list shows which {{secret:…}} " +
48
+ "db_connections, db_queries and db_runs read the database connections, saved queries and their runs behind database query " +
49
+ "tools; only a superadmin in the Admin creates or changes a connection or a query, so an apply that changes a query is " +
50
+ "blocked for any token: tell the person, and apply the rest with the query left as the instance holds it. " +
51
+ "variables_list/variables_get/variables_set handle plain-text {{var:…}} values; setting one needs a role that may manage " +
52
+ "the tenant's settings, as a secret does (a Builder's may not): where whoami says the credential may not, tell the person " +
53
+ "who sets it instead of calling variables_set. secrets_list shows which {{secret:…}} " +
42
54
  "values are set, never a value: a person sets a secret, so tell them the exact `cavelon secrets set <name>` command " +
43
55
  "to run in their terminal, and never ask for, read or pass a secret value. Never approve or decide an approval; " +
44
56
  "that stays with a person. Use docs_search before guessing, " +
45
57
  "and api_list/api_describe/api for anything without its own tool. " +
58
+ "use_tenant chooses the tenant for this MCP session only and never changes the tenant stored for the person; every preview " +
59
+ "names the instance, the tenant and the mode it acts on (its target): show that to the person with the change. " +
46
60
  "The first result of a session may carry a warning that cavelon, the Cavelon plugin or this folder's skills are behind " +
47
61
  "the latest release, with the commands that update them: pass it on to the person, who runs them; do not run them yourself.";
48
62
  export function mcpInstructions(commands) {
49
63
  return printingFor({ mode: "mcp", commands }, () => spoken(INSTRUCTIONS));
50
64
  }
65
+ const TOOL_LIST_ACCESS_MS = 5_000;
66
+ const TENANT_CHOOSERS = new Set(["use_tenant", "tenant_create"]);
51
67
  const TOKEN_DESCRIPTION = "Over MCP: the confirm_token this tool's preview returned, which confirms exactly the change it showed; true is refused.";
52
68
  export function toolName(spec) {
53
69
  return spec.mcpTool || undefined;
@@ -88,15 +104,31 @@ export function inputSchema(spec, commands = []) {
88
104
  : { type: ["string", "number"], description };
89
105
  }
90
106
  if (!ownsTenant(spec)) {
91
- properties.tenant = { type: "string", description: "Tenant slug or id, when not the one chosen for this directory." };
107
+ properties.tenant = {
108
+ type: "string",
109
+ description: "Tenant slug or id, when not the one chosen for this directory or with use_tenant in this session. A preview names the tenant it acts on.",
110
+ };
92
111
  }
93
112
  return { type: "object", properties, ...(required.length ? { required } : {}), additionalProperties: false };
94
113
  }
95
- export function toolFor(spec, commands = []) {
114
+ export function notForThisCredential(spec, access) {
115
+ if (!access)
116
+ return undefined;
117
+ for (const operation of spec.operations ?? []) {
118
+ const refused = operationAccess(access, operation);
119
+ if (refused.allowed !== false)
120
+ continue;
121
+ const why = refused.person ? "a person runs it" : `it needs ${allOf(refused.missing)}, which it does not hold`;
122
+ return `Not for this credential: ${credentialWords(access)} may not send ${operation} (${why}). ${whoInstead(access, refused)} Do not call it to find out; tell the person.`;
123
+ }
124
+ return undefined;
125
+ }
126
+ export function toolFor(spec, commands = [], access) {
96
127
  const marked = spec.mcpEffect ?? (spec.readOnly ? "Read-only." : spec.destructive ? "Changes the instance; may delete or overwrite." : "Changes the instance.");
128
+ const refused = notForThisCredential(spec, access);
97
129
  return {
98
130
  name: toolName(spec),
99
- description: mcpSpelling([spec.summary, spec.description, marked].filter(Boolean).join("\n"), spec, commands),
131
+ description: mcpSpelling([refused, spec.summary, spec.description, marked].filter(Boolean).join("\n"), spec, commands),
100
132
  inputSchema: inputSchema(spec, commands),
101
133
  annotations: {
102
134
  title: spec.summary,
@@ -173,9 +205,33 @@ function mcpIo(io) {
173
205
  export function createMcpServer(io, commands, updates = {}) {
174
206
  const tools = commands.filter((c) => c.mcpTool);
175
207
  const byName = new Map(tools.map((c) => [toolName(c), c]));
176
- const server = new Server({ name: "cavelon", version: KIT_VERSION }, { capabilities: { tools: {} }, instructions: mcpInstructions(commands) });
208
+ const server = new Server({ name: "cavelon", version: KIT_VERSION }, { capabilities: { tools: { listChanged: true } }, instructions: mcpInstructions(commands) });
177
209
  const notice = startSessionUpdateCheck(io, updates);
178
- server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: tools.map((t) => toolFor(t, commands)) }));
210
+ const sessionTenants = new Map();
211
+ async function credentialAccess() {
212
+ const read = (async () => {
213
+ const ctx = createContext(mcpIo(io), { json: true, sessionTenants }, "mcp");
214
+ const session = await ctx.session();
215
+ if (!session.url || !session.token)
216
+ return undefined;
217
+ return accessFor(await ctx.client());
218
+ })().catch(() => undefined);
219
+ let timer;
220
+ const late = new Promise((resolve) => {
221
+ timer = setTimeout(() => resolve(undefined), TOOL_LIST_ACCESS_MS);
222
+ timer.unref?.();
223
+ });
224
+ try {
225
+ return await Promise.race([read, late]);
226
+ }
227
+ finally {
228
+ clearTimeout(timer);
229
+ }
230
+ }
231
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
232
+ const access = await credentialAccess();
233
+ return { tools: tools.map((t) => toolFor(t, commands, access)) };
234
+ });
179
235
  async function call(name, given) {
180
236
  const spec = byName.get(name);
181
237
  const fail = (error) => ({ isError: true, body: { error: asCavelonError(error).toJSON() } });
@@ -195,11 +251,12 @@ export function createMcpServer(io, commands, updates = {}) {
195
251
  }
196
252
  const tenant = !ownsTenant(spec) && typeof args.tenant === "string" ? args.tenant : undefined;
197
253
  const solutionEnv = spec.options?.env && typeof args.env === "string" ? args.env : undefined;
198
- const ctx = createContext(mcpIo(io), { json: true, tenant, solutionEnv }, "mcp");
254
+ const ctx = createContext(mcpIo(io), { json: true, tenant, solutionEnv, sessionTenants }, "mcp");
199
255
  for (const message of renamed)
200
256
  ctx.warn(message);
201
257
  try {
202
- const { result, warnings } = await printingFor({ mode: "mcp", commands, ...(spec.storesTarget ? {} : { tenant, env: solutionEnv }) }, async () => {
258
+ const chosen = tenant ?? (await ctx.session().then((s) => (s.tenantSource === "session" ? s.tenant : undefined), () => undefined));
259
+ const { result, warnings } = await printingFor({ mode: "mcp", commands, ...(spec.storesTarget ? {} : { tenant: chosen, env: solutionEnv }) }, async () => {
203
260
  try {
204
261
  const done = await spec.run(ctx, inputFrom(spec, args));
205
262
  return { result: { ...done, data: spokenHints(done.data) }, warnings: ctx.warnings.map(spoken) };
@@ -223,6 +280,8 @@ export function createMcpServer(io, commands, updates = {}) {
223
280
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
224
281
  const warning = notice.forCall(() => server.getClientVersion()?.name);
225
282
  const { body, isError } = await call(request.params.name, (request.params.arguments ?? {}));
283
+ if (!isError && TENANT_CHOOSERS.has(request.params.name))
284
+ void server.sendToolListChanged().catch(() => undefined);
226
285
  let out = body;
227
286
  const text = await warning;
228
287
  if (text) {
@@ -1,5 +1,6 @@
1
1
  import { Ajv2020 } from "ajv/dist/2020.js";
2
2
  import { BRANCH_WIDTH_KEY, branchConcurrency, offText } from "./branches.js";
3
+ import { checkQueryTools, QUERY_CHANGED_CODE, QUERY_FIELDS_IGNORED_CODE } from "./database-queries.js";
3
4
  import { locate, schemaSections, tenantWideSections } from "./package-files.js";
4
5
  import { MANIFEST_SECTION, PERSONA_SECTION, sectionFields } from "./package-format.js";
5
6
  import { kitErrorEntry } from "./kit-codes.js";
@@ -29,6 +30,7 @@ const SOLUTION_MISMATCH_CODE = "solution_slug_mismatch";
29
30
  const TENANT_WIDE_CODE = "tenant_wide_section";
30
31
  const ASSERTION_UNCHECKED_CODE = "test_assertion_unchecked";
31
32
  const TESTING_DOCS = "/docs/concepts/regression-testing";
33
+ const DATABASE_DOCS = "/docs/administration/database-connectors";
32
34
  export const KIT_CODES = [
33
35
  {
34
36
  code: SCHEMA_CODE,
@@ -158,6 +160,22 @@ export const KIT_CODES = [
158
160
  "Remove the file unless that is meant. An instance that does not publish include_tenant_wide imports it with every apply.",
159
161
  docs: PACKAGE_DOCS,
160
162
  },
163
+ {
164
+ code: QUERY_CHANGED_CODE,
165
+ area: "package",
166
+ message: "A database query tool's query (database_query), name or description differs from the last pull or apply, or the tool is new. Only a superadmin in the Admin creates or changes a query; a personal access token's import preview blocks it.",
167
+ hint: "Hand the change to a superadmin, who imports the package in the Admin (`cavelon explain database_query_needs_superadmin` names the step); then apply passes while the queries match. " +
168
+ "To apply the rest first, leave the query as the instance holds it: restore the tool's entry as the last pull wrote it, or remove its database_query block (a query tool without one keeps the instance's query, name and description). " +
169
+ "Rename the tool for one agent with the assignment's config_overrides instead: an override of name, description or max_calls is no query change.",
170
+ docs: DATABASE_DOCS,
171
+ },
172
+ {
173
+ code: QUERY_FIELDS_IGNORED_CODE,
174
+ area: "package",
175
+ message: "A database query tool's params_json_schema or default_config differs from the last pull or apply; the instance derives both from the query and ignores the package's.",
176
+ hint: "Change the query's parameters instead (database_query.parameters), or put the field back as pulled.",
177
+ docs: DATABASE_DOCS,
178
+ },
161
179
  {
162
180
  code: "package_file_duplicate",
163
181
  area: "package",
@@ -320,6 +338,7 @@ export function checkPackage(disk, options) {
320
338
  findings.push(...checkUncheckedAssertions(disk, options.schema));
321
339
  findings.push(...checkSolutionSlug(disk, options.solution));
322
340
  findings.push(...checkTenantWide(disk, options.schema, options.solution));
341
+ findings.push(...checkQueryTools(disk, options.schema, options.queryBaseline));
323
342
  noteTenantWide(findings, options.schema, options.solution);
324
343
  for (const finding of findings) {
325
344
  const entry = findingEntry(options.catalog, finding.code);