@cavelon/cli 0.1.10 → 0.1.12

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 (45) hide show
  1. package/README.md +34 -15
  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/change-confirmation.js +93 -0
  6. package/dist/commands/api.js +77 -30
  7. package/dist/commands/chat.js +16 -8
  8. package/dist/commands/db.js +474 -0
  9. package/dist/commands/docs.js +83 -7
  10. package/dist/commands/index.js +7 -0
  11. package/dist/commands/limits-set.js +11 -5
  12. package/dist/commands/loops.js +72 -9
  13. package/dist/commands/models.js +12 -6
  14. package/dist/commands/sandboxes.js +7 -2
  15. package/dist/commands/session.js +111 -24
  16. package/dist/commands/setup.js +1 -1
  17. package/dist/commands/solution.js +211 -54
  18. package/dist/commands/tenants.js +55 -12
  19. package/dist/commands/values.js +104 -23
  20. package/dist/commands/work.js +13 -5
  21. package/dist/confirm-token.js +90 -7
  22. package/dist/context.js +5 -1
  23. package/dist/contracts.js +37 -12
  24. package/dist/database-queries.js +301 -0
  25. package/dist/fsutil.js +14 -0
  26. package/dist/http.js +69 -3
  27. package/dist/install.js +30 -0
  28. package/dist/invoke.js +12 -2
  29. package/dist/kit-codes.js +9 -2
  30. package/dist/mcp.js +106 -19
  31. package/dist/openapi.js +7 -0
  32. package/dist/package-check.js +19 -0
  33. package/dist/preview-report.js +2 -2
  34. package/dist/principal.js +24 -2
  35. package/dist/printed.js +5 -0
  36. package/dist/secret-access.js +30 -9
  37. package/dist/session.js +36 -8
  38. package/dist/skills/cavelon-authoring/SKILL.md +93 -10
  39. package/dist/skills/cavelon-long-running/SKILL.md +18 -8
  40. package/dist/skills/cavelon-loop/SKILL.md +126 -41
  41. package/dist/skills/cavelon-testing/SKILL.md +32 -3
  42. package/dist/trace-view.js +10 -0
  43. package/dist/update-check.js +2 -2
  44. package/dist/user-config.js +24 -0
  45. package/package.json +1 -1
@@ -0,0 +1,474 @@
1
+ import { CURSOR_OPTION, intOption, LIMIT_OPTION, listOption, pageOf, positional, stringOption } from "../command.js";
2
+ import { CavelonError, ExitCode, usageError } from "../errors.js";
3
+ import { connectorOffer } from "../database-queries.js";
4
+ import { requireFeature } from "../features.js";
5
+ import { clip, keyValues, moreHint, table } from "../format.js";
6
+ import { callStable } from "../invoke.js";
7
+ import { cavelonCommand, fill } from "../printed.js";
8
+ import { isUuid } from "../session.js";
9
+ const FEATURE = "database_connector_enabled";
10
+ const DOCS_PAGE = "administration/database-connectors";
11
+ const connectorOn = (ctx) => requireFeature(ctx, FEATURE, "database_connector_disabled", "the database connector");
12
+ function withPermissionHint(error, hint) {
13
+ if (!(error instanceof CavelonError) || error.status !== 403)
14
+ return error;
15
+ return new CavelonError(error.exitCode, {
16
+ code: error.code,
17
+ status: error.status,
18
+ message: error.message,
19
+ hint: `${hint} \`${cavelonCommand("whoami")}\` shows the token's role.`,
20
+ docs: error.docs,
21
+ });
22
+ }
23
+ const ownerOnly = (error, what) => withPermissionHint(error, `${what} needs the tenant Owner's permission (database_connectors.test), or a superadmin in the Admin; the roles that read the connections do not hold it.`);
24
+ const viewerOnly = (error) => withPermissionHint(error, "Reading the database connector needs database_connectors.view, which the tenant roles that see tools hold, and a superadmin in Tenant mode.");
25
+ async function read(ctx, path, what, query) {
26
+ await connectorOn(ctx);
27
+ try {
28
+ return await callStable(ctx, "GET", path, what, { query });
29
+ }
30
+ catch (error) {
31
+ throw viewerOnly(error);
32
+ }
33
+ }
34
+ const listConnections = (ctx) => read(ctx, "/api/v1/database-connectors/connections", "database connections");
35
+ const listQueries = (ctx, connectionId) => read(ctx, "/api/v1/database-connectors/queries", "database queries", { connection_id: connectionId });
36
+ async function resolveConnection(ctx, ref) {
37
+ const all = await listConnections(ctx);
38
+ const hit = all.find((c) => c.id === ref.toLowerCase()) ?? all.find((c) => c.name === ref) ?? all.find((c) => c.name.toLowerCase() === ref.toLowerCase());
39
+ if (hit)
40
+ return hit;
41
+ throw new CavelonError(ExitCode.failure, {
42
+ code: "database_connection_not_found",
43
+ message: `No database connection "${ref}" in this tenant.`,
44
+ hint: `\`${cavelonCommand("db", "connections")}\` lists them${all.length ? ` (${all.map((c) => c.name).slice(0, 10).join(", ")})` : "; a superadmin creates one in the Admin"}.`,
45
+ });
46
+ }
47
+ async function resolveQuery(ctx, ref) {
48
+ await connectorOn(ctx);
49
+ if (isUuid(ref)) {
50
+ try {
51
+ return await callStable(ctx, "GET", "/api/v1/database-connectors/queries/{query_id}", "database queries", { params: { query_id: [ref] } });
52
+ }
53
+ catch (error) {
54
+ if (!(error instanceof CavelonError && error.status === 404))
55
+ throw viewerOnly(error);
56
+ }
57
+ }
58
+ const all = await listQueries(ctx);
59
+ const hit = all.find((q) => q.id === ref.toLowerCase()) ?? all.find((q) => q.slug === ref) ?? all.find((q) => q.slug.toLowerCase() === ref.toLowerCase());
60
+ if (hit)
61
+ return hit;
62
+ throw new CavelonError(ExitCode.failure, {
63
+ code: "database_query_not_found",
64
+ message: `No database query "${ref}" in this tenant.`,
65
+ hint: `\`${cavelonCommand("db", "queries")}\` lists them by the slug of their tool${all.length ? ` (${all.map((q) => q.slug).slice(0, 10).join(", ")})` : ""}.`,
66
+ });
67
+ }
68
+ function connectionView(c) {
69
+ const { ca_certificate_pem: pem, ...rest } = c;
70
+ return { ...rest, ca_certificate_set: Boolean(pem) };
71
+ }
72
+ const DAY_MS = 86_400_000;
73
+ const EXPIRY_WARNING_DAYS = 30;
74
+ const day = (iso) => iso.slice(0, 10);
75
+ function expiryWarnings(connections, now) {
76
+ const warnings = [];
77
+ for (const c of connections) {
78
+ for (const cert of c.ca_certificates ?? []) {
79
+ const until = Date.parse(cert.not_after);
80
+ if (Number.isNaN(until))
81
+ continue;
82
+ const days = Math.floor((until - now.getTime()) / DAY_MS);
83
+ if (days >= EXPIRY_WARNING_DAYS)
84
+ continue;
85
+ const when = until <= now.getTime()
86
+ ? `expired on ${day(cert.not_after)}`
87
+ : `expires on ${day(cert.not_after)} (in ${days === 0 ? "less than a day" : `${days} day${days === 1 ? "" : "s"}`})`;
88
+ warnings.push(`The CA certificate "${cert.subject}" of the database connection "${c.name}" ${when}: from then its TLS check fails, and with it the connection's queries. ` +
89
+ `A superadmin uploads the renewed CA in the Admin; then the tenant Owner tests the connection again: ${cavelonCommand("db", "test", c.name)}`);
90
+ }
91
+ }
92
+ return warnings;
93
+ }
94
+ function caLines(connections) {
95
+ const lines = [];
96
+ for (const c of connections) {
97
+ if (c.ca_certificates?.length) {
98
+ for (const cert of c.ca_certificates)
99
+ lines.push(`${c.name}: ${cert.subject}, valid until ${day(cert.not_after)}`);
100
+ }
101
+ else if (!c.ca_certificates && c.ca_certificate_sha256?.length) {
102
+ const n = c.ca_certificate_sha256.length;
103
+ lines.push(`${c.name}: a CA is set (${n} certificate${n === 1 ? "" : "s"}); this instance does not publish their subject or expiry`);
104
+ }
105
+ }
106
+ return lines.length ? ["", "", "CA certificates:", ...lines] : [];
107
+ }
108
+ function lastTest(c) {
109
+ if (!c.last_test_at)
110
+ return "never";
111
+ return `${c.last_test_outcome ?? "?"} (${c.last_test_at})`;
112
+ }
113
+ const filledBy = (p) => (!p.source || p.source === "model" ? "model" : p.source);
114
+ function parameterRows(parameters) {
115
+ return parameters.map((p) => ({
116
+ name: p.name,
117
+ filled_by: filledBy(p),
118
+ type: p.type ?? "string",
119
+ required: p.required === false ? "no" : "yes",
120
+ constraints: ["max_length", "pattern", "enum", "minimum", "maximum"]
121
+ .filter((k) => p[k] !== undefined && p[k] !== null)
122
+ .map((k) => `${k} ${JSON.stringify(p[k])}`)
123
+ .join(", ") || null,
124
+ description: p.description || null,
125
+ }));
126
+ }
127
+ function explainLine(codes) {
128
+ const distinct = [...new Set(codes.filter((c) => Boolean(c)))];
129
+ if (!distinct.length)
130
+ return "";
131
+ return `\n\nWhat a code means: ${cavelonCommand("explain", fill("code"))} (${distinct.slice(0, 8).join(", ")})`;
132
+ }
133
+ function firewallSentence(offer) {
134
+ const { egress_ips: ips, connections_per_process: perProcess } = offer.network;
135
+ const pool = `Each process of the instance that runs agents opens at most ${perProcess} connection${perProcess === 1 ? "" : "s"} per database connection.`;
136
+ if (!ips.length) {
137
+ return ("The instance's operator has named no addresses it connects from, so it does not say what to allowlist: " +
138
+ `ask the operator before opening the database's firewall. ${pool}`);
139
+ }
140
+ const these = ips.length === 1 ? "this address" : "these addresses";
141
+ return `Allow ${ips.join(", ")} through the database's firewall, on the database's port: the instance connects to a customer's database only from ${these}. ${pool}`;
142
+ }
143
+ export const dbInstance = {
144
+ name: "db instance",
145
+ summary: "What this instance offers for database connections: the dialects it runs, and the addresses a database's firewall lets in.",
146
+ description: "Read it before a database connection is set up: a connection of a dialect the instance does not run can be saved, but\n" +
147
+ "its test and queries answer unavailable, and the customer's database must let the instance's egress addresses in. An\n" +
148
+ "instance older than this route says only its dialects, in its capabilities.",
149
+ readOnly: true,
150
+ idempotent: true,
151
+ mcpTool: "db_instance",
152
+ examples: ["cavelon db instance", "cavelon db instance --json"],
153
+ async run(ctx) {
154
+ let offer;
155
+ try {
156
+ offer = await read(ctx, "/api/v1/database-connectors/instance", "the database connector's dialects and network");
157
+ }
158
+ catch (error) {
159
+ const unpublished = error instanceof CavelonError && (error.code === "operation_unavailable" || error.status === 404);
160
+ if (!unpublished)
161
+ throw error;
162
+ const dialects = connectorOffer(await (await ctx.contracts()).capabilities()).dialects;
163
+ return {
164
+ data: { published: false, runnable_dialects: dialects ?? null, network: null },
165
+ text: "This instance does not publish which addresses it connects to databases from (it is older than that); its operator knows them." +
166
+ (dialects ? `\nDialects it runs: ${dialects.join(", ") || "none"}` : ""),
167
+ };
168
+ }
169
+ const firewall = firewallSentence(offer);
170
+ return {
171
+ data: { published: true, ...offer, firewall },
172
+ text: [
173
+ keyValues([
174
+ ["dialects", offer.runnable_dialects.join(", ") || "none"],
175
+ ["egress_ips", offer.network.egress_ips.join(", ") || "none named"],
176
+ ["connections_per_process", offer.network.connections_per_process],
177
+ ]),
178
+ "",
179
+ firewall,
180
+ ...(offer.runnable_dialects.length ? [] : ["", "This instance runs no database dialect: a connection can be saved, but its test and queries answer unavailable."]),
181
+ ].join("\n"),
182
+ };
183
+ },
184
+ };
185
+ export const dbConnections = {
186
+ name: "db connections",
187
+ summary: "The tenant's database connections: dialect, target, TLS mode, CA certificates, last test and query count; never a password.",
188
+ description: "A superadmin creates and changes connections in the Admin; a token reads them. A package names a query's connection by\n" +
189
+ "name and dialect, so the same name serves in every tenant and environment. A query tool is ready for agents only while\n" +
190
+ "its connection is enabled and its last test passed; the tenant Owner runs the test with `cavelon db test <connection>`.\n" +
191
+ `It warns of a CA certificate that has expired or expires within ${EXPIRY_WARNING_DAYS} days.`,
192
+ readOnly: true,
193
+ idempotent: true,
194
+ mcpTool: "db_connections",
195
+ options: { limit: { ...LIMIT_OPTION, description: "Return at most n connections (default 50)." }, cursor: CURSOR_OPTION },
196
+ examples: ["cavelon db connections", "cavelon db connections --json"],
197
+ async run(ctx, input) {
198
+ const limit = intOption(input, "limit", { min: 1, max: 500, fallback: 50 });
199
+ const all = await listConnections(ctx);
200
+ for (const warning of expiryWarnings(all, ctx.io.now()))
201
+ ctx.warn(warning);
202
+ const page = pageOf(all.map(connectionView), limit, stringOption(input, "cursor"));
203
+ const rows = page.items.map((c) => {
204
+ const conn = c;
205
+ return {
206
+ name: conn.name,
207
+ dialect: conn.dialect,
208
+ target: `${conn.host}:${conn.port}/${conn.database_name}`,
209
+ tls: conn.tls_mode,
210
+ enabled: conn.is_enabled ? "yes" : "no",
211
+ last_test: lastTest(conn),
212
+ queries: conn.query_count ?? null,
213
+ id: conn.id,
214
+ };
215
+ });
216
+ const untested = page.items.filter((c) => c.last_test_outcome !== "ok").map((c) => String(c.name));
217
+ const refused = page.items.filter((c) => c.query_enable_refusal?.code);
218
+ return {
219
+ data: page,
220
+ text: (table(rows, ["name", "dialect", "target", "tls", "enabled", "last_test", "queries", "id"]) ||
221
+ `No database connections. A superadmin creates one in the Admin (\`${cavelonCommand("docs", "get", DOCS_PAGE)}\` says who does what).`) +
222
+ caLines(page.items).join("\n") +
223
+ moreHint(page.next_cursor, cavelonCommand("db", "connections")) +
224
+ (untested.length ? `\n\nNot tested successfully: ${untested.join(", ")}; its queries are not ready for agents. The Owner tests one with: ${cavelonCommand("db", "test", fill("connection"))}` : "") +
225
+ (refused.length
226
+ ? `\n\nQueries cannot be enabled on: ${refused.map((c) => `${c.name} (${c.query_enable_refusal.code}${c.query_enable_refusal.message ? `: ${clip(c.query_enable_refusal.message, 200)}` : ""})`).join("; ")}` +
227
+ explainLine(refused.map((c) => c.query_enable_refusal.code))
228
+ : ""),
229
+ };
230
+ },
231
+ };
232
+ export const dbQueries = {
233
+ name: "db queries",
234
+ summary: "The tenant's saved database queries by tool slug; with a query, its SQL, parameters and limits.",
235
+ description: "Each saved query is one agent tool (tool_type database_query). A superadmin writes it in the Admin; `cavelon pull` writes\n" +
236
+ "its definition into the package's tools. A parameter filled by end_user.* comes from the signed-in visitor, never from\n" +
237
+ "the model. Without a query: one line per query. With one (its tool's slug or the query's id): the whole query.",
238
+ readOnly: true,
239
+ idempotent: true,
240
+ mcpTool: "db_queries",
241
+ positionals: [{ name: "query", description: "A query's tool slug or id: show it in full." }],
242
+ options: {
243
+ connection: { type: "string", value: "<connection>", description: "Only the queries of this connection (name or id)." },
244
+ limit: { ...LIMIT_OPTION, description: "Return at most n queries (default 50)." },
245
+ cursor: CURSOR_OPTION,
246
+ },
247
+ examples: ["cavelon db queries", "cavelon db queries --connection shop-db", "cavelon db queries order_status --json"],
248
+ async run(ctx, input) {
249
+ const ref = positional(input, "query");
250
+ if (ref) {
251
+ const q = await resolveQuery(ctx, ref);
252
+ const text = [
253
+ keyValues([
254
+ ["query", `${q.slug} (${q.name})`],
255
+ ["connection", q.connection_name],
256
+ ["description", q.description ? clip(q.description, 300) : undefined],
257
+ ["limits", `max_rows ${q.max_rows}, max_result_chars ${q.max_result_chars}`],
258
+ ["anonymous", q.allows_anonymous ? "visitors may call it without signing in" : "a signed-in visitor only"],
259
+ ["enabled", q.is_enabled ? "yes" : "no"],
260
+ ["version", q.version],
261
+ ["id", q.id],
262
+ ]),
263
+ "",
264
+ "SQL:",
265
+ q.sql_text,
266
+ "",
267
+ q.parameters.length ? table(parameterRows(q.parameters), ["name", "filled_by", "type", "required", "constraints", "description"]) : "No parameters.",
268
+ "",
269
+ `Its runs (no values, no rows): ${cavelonCommand("db", "runs", q.slug)}`,
270
+ ].join("\n");
271
+ return { data: q, text };
272
+ }
273
+ const connectionRef = stringOption(input, "connection");
274
+ const connection = connectionRef ? await resolveConnection(ctx, connectionRef) : undefined;
275
+ const limit = intOption(input, "limit", { min: 1, max: 500, fallback: 50 });
276
+ const all = (await listQueries(ctx, connection?.id)).map(({ sql_text: sql, params_json_schema: _schema, ...q }) => ({ ...q, sql_chars: sql.length }));
277
+ const page = pageOf(all, limit, stringOption(input, "cursor"));
278
+ const rows = page.items.map((q) => ({
279
+ slug: q.slug,
280
+ name: q.name,
281
+ connection: q.connection_name,
282
+ parameters: q.parameters.map((p) => (filledBy(p) === "model" ? p.name : `${p.name} (${filledBy(p)})`)).join(", ") || null,
283
+ max_rows: q.max_rows,
284
+ anonymous: q.allows_anonymous ? "yes" : "no",
285
+ enabled: q.is_enabled ? "yes" : "no",
286
+ version: q.version,
287
+ }));
288
+ return {
289
+ data: page,
290
+ text: (table(rows, ["slug", "name", "connection", "parameters", "max_rows", "anonymous", "enabled", "version"], 60) || "No database queries.") +
291
+ moreHint(page.next_cursor, cavelonCommand("db", "queries")) +
292
+ (rows.length ? `\n\nOne query in full: ${cavelonCommand("db", "queries", fill("slug"))}` : ""),
293
+ };
294
+ },
295
+ };
296
+ export const dbRuns = {
297
+ name: "db runs",
298
+ summary: "A saved query's runs, newest first: source, outcome, error code, duration and row count; never values or rows.",
299
+ description: "Every run leaves this evidence, an agent's call and a test run alike; the instance keeps no parameter value, row or SQL.\n" +
300
+ "`cavelon explain <code>` says what an error code means and how to fix it.",
301
+ readOnly: true,
302
+ idempotent: true,
303
+ mcpTool: "db_runs",
304
+ positionals: [{ name: "query", description: "The query's tool slug or id.", required: true }],
305
+ options: {
306
+ limit: { ...LIMIT_OPTION, description: "Return at most n runs (default 20, at most 200)." },
307
+ cursor: CURSOR_OPTION,
308
+ },
309
+ examples: ["cavelon db runs order_status", "cavelon db runs order_status --limit 50 --json"],
310
+ async run(ctx, input) {
311
+ const q = await resolveQuery(ctx, positional(input, "query"));
312
+ const limit = intOption(input, "limit", { min: 1, max: 200, fallback: 20 });
313
+ const cursor = stringOption(input, "cursor");
314
+ const offset = cursor === undefined ? 0 : Number(cursor);
315
+ if (!Number.isInteger(offset) || offset < 0)
316
+ throw usageError(`--cursor "${cursor}" is not a cursor from a previous page.`);
317
+ const page = await callStable(ctx, "GET", "/api/v1/database-connectors/queries/{query_id}/runs", "database query runs", {
318
+ params: { query_id: [q.id] },
319
+ query: { limit, offset },
320
+ }).catch((error) => {
321
+ throw viewerOnly(error);
322
+ });
323
+ const items = page.items ?? [];
324
+ const next = typeof page.next_offset === "number" ? String(page.next_offset) : null;
325
+ const rows = items.map((r) => ({
326
+ at: r.created_at,
327
+ source: r.source,
328
+ outcome: r.outcome,
329
+ error_code: r.error_code ?? null,
330
+ duration_ms: r.duration_ms ?? null,
331
+ rows: r.row_count ?? null,
332
+ truncated: r.truncated ? "yes" : null,
333
+ version: r.query_version,
334
+ }));
335
+ return {
336
+ data: { query: { id: q.id, slug: q.slug, version: q.version }, items, next_cursor: next },
337
+ text: (table(rows, ["at", "source", "outcome", "error_code", "duration_ms", "rows", "truncated", "version"]) || `No runs of ${q.slug} yet.`) +
338
+ moreHint(next, cavelonCommand("db", "runs", q.slug)) +
339
+ explainLine(items.map((r) => r.error_code)),
340
+ };
341
+ },
342
+ };
343
+ export const dbTest = {
344
+ name: "db test",
345
+ summary: "Test a database connection step by step (DNS, policy, TCP, TLS, login, SELECT 1, version, write privileges); exit 3 when a step fails.",
346
+ description: "Needs the tenant Owner's permission (database_connectors.test). The result becomes the connection's last test: a query tool\n" +
347
+ "is ready for agents only while it passed, and a package's query needs a tested connection of its name to import. A failed\n" +
348
+ "step names its code; `cavelon explain <code>` says how to fix it. A finding under write_privileges means the database user\n" +
349
+ "can write: ask the database administrator for a read-only user. On SQL Server, which has no read-only transaction, the\n" +
350
+ "connection's queries then do not run (write_privileges_unacknowledged) until its login may only read or a superadmin\n" +
351
+ "acknowledges the write privileges in the Admin.",
352
+ readOnly: false,
353
+ idempotent: true,
354
+ mcpEffect: "Runs the connection test on the instance and stores its outcome as the connection's last test; changes no setting.",
355
+ mcpTool: "db_test",
356
+ operations: ["POST /api/v1/database-connectors/connections/{connection_id}/test"],
357
+ positionals: [{ name: "connection", description: "The connection's name or id.", required: true }],
358
+ examples: ["cavelon db test shop-db", "cavelon db test shop-db --json"],
359
+ async run(ctx, input) {
360
+ const connection = await resolveConnection(ctx, positional(input, "connection"));
361
+ let result;
362
+ try {
363
+ result = await callStable(ctx, "POST", "/api/v1/database-connectors/connections/{connection_id}/test", "testing database connections", {
364
+ params: { connection_id: [connection.id] },
365
+ timeoutMs: 90_000,
366
+ });
367
+ }
368
+ catch (error) {
369
+ throw ownerOnly(error, "A connection test");
370
+ }
371
+ const ok = result.outcome === "ok";
372
+ const steps = (result.steps ?? []).map((s) => ({ step: s.name, status: s.status, code: s.code ?? null, message: s.driver_message ? clip(s.driver_message, 160) : null }));
373
+ const text = [
374
+ `Connection "${connection.name}" (${connection.dialect}): ${ok ? "test passed" : `test failed (${result.outcome})`}, ${result.duration_ms} ms.`,
375
+ table(steps, ["step", "status", "code", ...(steps.some((s) => s.message) ? ["message"] : [])], 80),
376
+ ...(result.server_version ? [`server: ${result.server_version}`] : []),
377
+ ...(result.write_privileges ? [`write privileges: ${clip(JSON.stringify(result.write_privileges), 300)}`] : []),
378
+ ].join("\n");
379
+ return {
380
+ data: { connection: { id: connection.id, name: connection.name, dialect: connection.dialect }, ...result },
381
+ text: text + explainLine(steps.filter((s) => s.code && s.status !== "ok").map((s) => s.code)),
382
+ exitCode: ok ? ExitCode.ok : ExitCode.validation,
383
+ };
384
+ },
385
+ };
386
+ function typed(parameter, raw) {
387
+ const type = parameter?.type ?? "string";
388
+ if (type === "integer" || type === "number") {
389
+ const value = Number(raw);
390
+ if (raw.trim() === "" || !Number.isFinite(value) || (type === "integer" && !Number.isInteger(value))) {
391
+ throw usageError(`--value ${parameter.name}: "${raw}" is not ${type === "integer" ? "an integer" : "a number"}.`);
392
+ }
393
+ return value;
394
+ }
395
+ if (type === "boolean") {
396
+ if (raw === "true" || raw === "false")
397
+ return raw === "true";
398
+ throw usageError(`--value ${parameter.name}: "${raw}" is not true or false.`);
399
+ }
400
+ return raw;
401
+ }
402
+ function runValues(query, given) {
403
+ const values = {};
404
+ for (const pair of given) {
405
+ const at = pair.indexOf("=");
406
+ if (at <= 0)
407
+ throw usageError(`--value takes name=value, got "${pair}".`);
408
+ const name = pair.slice(0, at);
409
+ const parameter = query.parameters.find((p) => p.name === name);
410
+ if (!parameter) {
411
+ throw usageError(`${query.slug} has no parameter "${name}".`, `Its parameters: ${query.parameters.map((p) => `${p.name} (${filledBy(p)}, ${p.type ?? "string"})`).join(", ") || "none"}.`);
412
+ }
413
+ values[name] = typed(parameter, pair.slice(at + 1));
414
+ }
415
+ return values;
416
+ }
417
+ const ROWS_SHOWN = 20;
418
+ export const dbTestRun = {
419
+ name: "db test-run",
420
+ summary: "Run a saved query once with the values given, identity parameters included; show what the model would see and the rows.",
421
+ description: "Needs the tenant Owner's permission (database_connectors.test); it reads the customer's own data. Give each parameter\n" +
422
+ "with --value name=value, those the platform fills from the signed-in visitor (end_user.*) too: that is how an\n" +
423
+ "identity-scoped query is checked for one customer. The instance records the run (counts only) and audits it with your\n" +
424
+ "name; the rows come back once and are never stored. A failed run names its code; `cavelon explain <code>` says more.",
425
+ readOnly: false,
426
+ idempotent: true,
427
+ mcpEffect: "Runs the saved query once on the instance; it leaves a run record (counts only) and an audit entry, and changes no setting.",
428
+ mcpTool: "db_test_run",
429
+ operations: ["POST /api/v1/database-connectors/queries/{query_id}/test-run"],
430
+ positionals: [{ name: "query", description: "The query's tool slug or id.", required: true }],
431
+ options: {
432
+ value: { type: "string", multiple: true, value: "<name=value>", description: "One parameter's value, typed as the parameter's type." },
433
+ rows: { type: "string", value: "<n>", description: `Show at most n rows in the text (default ${ROWS_SHOWN}); --json carries what the instance returned.` },
434
+ },
435
+ examples: ["cavelon db test-run order_status --value order_no=A-10023 --value email=ada@example.com", "cavelon db test-run stock --value sku=4711 --json"],
436
+ async run(ctx, input) {
437
+ const query = await resolveQuery(ctx, positional(input, "query"));
438
+ const values = runValues(query, listOption(input, "value"));
439
+ const shown = intOption(input, "rows", { min: 0, max: 500, fallback: ROWS_SHOWN });
440
+ let result;
441
+ try {
442
+ result = await callStable(ctx, "POST", "/api/v1/database-connectors/queries/{query_id}/test-run", "test runs of database queries", {
443
+ params: { query_id: [query.id] },
444
+ body: { values },
445
+ timeoutMs: 90_000,
446
+ });
447
+ }
448
+ catch (error) {
449
+ throw ownerOnly(error, "A test run");
450
+ }
451
+ const ok = result.outcome === "ok" && !result.error_code;
452
+ const columns = result.columns ?? [];
453
+ const rows = (result.rows ?? []).slice(0, shown).map((row) => Object.fromEntries(columns.map((c, i) => [c, row[i] === null || typeof row[i] !== "object" ? row[i] : JSON.stringify(row[i])])));
454
+ const more = (result.rows?.length ?? 0) - rows.length;
455
+ const text = [
456
+ keyValues([
457
+ ["query", `${query.slug} (version ${query.version})`],
458
+ ["outcome", result.error_code ? `${result.outcome} (${result.error_code}${result.sqlstate ? `, SQLSTATE ${result.sqlstate}` : ""})` : result.outcome],
459
+ ["rows", ok ? `${result.returned_rows ?? rows.length} returned of ${result.row_count ?? "?"}${result.truncated ? ", truncated for the model" : ""}` : undefined],
460
+ ["duration_ms", result.duration_ms],
461
+ ]),
462
+ "",
463
+ "What the model sees:",
464
+ clip(result.model_text, 2000),
465
+ ...(rows.length ? ["", table(rows, columns, 40)] : []),
466
+ ...(more > 0 ? [`… ${more} more rows (--rows, or --json).`] : []),
467
+ ].join("\n");
468
+ return {
469
+ data: { query: { id: query.id, slug: query.slug, version: query.version }, ...result },
470
+ text: text + explainLine([result.error_code]),
471
+ exitCode: ok ? ExitCode.ok : ExitCode.validation,
472
+ };
473
+ },
474
+ };
@@ -3,6 +3,26 @@ import { CavelonError, ExitCode } from "../errors.js";
3
3
  import { table } from "../format.js";
4
4
  import { NOT_HERE } from "../http.js";
5
5
  import { cavelonCommand, fill } from "../printed.js";
6
+ import { readPrincipal } from "../principal.js";
7
+ const PLATFORM_AUDIENCE = "platform";
8
+ export const PLATFORM_PAGE_MARK = "Platform page: the actions it describes need a personal access token with Platform mode; this token can read the page but not act on it.";
9
+ const AUDIENCE_PREFIX = "(audience:";
10
+ function splitAudience(line) {
11
+ const trimmed = line.trimEnd();
12
+ if (!trimmed.endsWith(")"))
13
+ return { rest: line };
14
+ const start = trimmed.toLowerCase().lastIndexOf(AUDIENCE_PREFIX);
15
+ if (start < 0)
16
+ return { rest: line };
17
+ const audience = trimmed.slice(start + AUDIENCE_PREFIX.length, -1).trim().toLowerCase();
18
+ if (!/^[a-z][a-z0-9_-]*$/.test(audience))
19
+ return { rest: line };
20
+ return { rest: trimmed.slice(0, start).trimEnd(), audience };
21
+ }
22
+ function headerAudience(headers) {
23
+ const value = headers?.get("x-docs-audience")?.trim().toLowerCase();
24
+ return value || undefined;
25
+ }
6
26
  const INDEX_PATHS = ["/llms.txt", "/api/v1/docs/llms.txt"];
7
27
  function unavailable(url) {
8
28
  return new CavelonError(ExitCode.failure, {
@@ -31,13 +51,14 @@ export function parseIndex(text, base) {
31
51
  section = heading[1];
32
52
  continue;
33
53
  }
34
- const link = /^\s*[-*]\s+\[([^\]]+)\]\(([^)\s]+)\)(?::\s*(.*))?$/.exec(line);
54
+ const { rest, audience } = splitAudience(line);
55
+ const link = /^\s*[-*]\s+\[([^\]]+)\]\(([^)\s]+)\)(?::\s*(.*))?$/.exec(rest);
35
56
  if (!link)
36
57
  continue;
37
58
  const pathname = new URL(link[2], `${base}/`).pathname;
38
59
  const url = `${new URL(base).origin}${pathname}`;
39
60
  const page = pathname.replace(/^.*?\/docs\//, "").replace(/^\//, "").replace(/\.md$/, "");
40
- entries.push({ page, title: link[1], description: (link[3] ?? "").trim(), section, url });
61
+ entries.push({ page, title: link[1], description: (link[3] ?? "").trim(), section, url, ...(audience ? { audience } : {}) });
41
62
  }
42
63
  return entries;
43
64
  }
@@ -52,6 +73,31 @@ async function loadIndex(ctx) {
52
73
  }
53
74
  return { client, entries: parseIndex(text, client.url), text };
54
75
  }
76
+ async function cannotActInPlatformMode(client) {
77
+ if (!client.target.token)
78
+ return false;
79
+ const principal = await readPrincipal(client).catch(() => undefined);
80
+ if (principal?.kind === "api_key")
81
+ return true;
82
+ const allowed = principal?.token?.platform_mode_allowed;
83
+ if (principal?.kind !== "personal_access_token" || typeof allowed !== "boolean")
84
+ return false;
85
+ if (!allowed)
86
+ return true;
87
+ if (principal.mode === "platform")
88
+ return false;
89
+ const outside = principal.tenant_id ? await readPrincipal(client, { sendTenant: false }).catch(() => undefined) : principal;
90
+ return outside?.mode === "none";
91
+ }
92
+ function platformMarker(client) {
93
+ let cannot;
94
+ return (audience) => {
95
+ if (audience !== PLATFORM_AUDIENCE)
96
+ return Promise.resolve(false);
97
+ cannot ??= cannotActInPlatformMode(client);
98
+ return cannot;
99
+ };
100
+ }
55
101
  export async function listedPages(ctx, pages) {
56
102
  try {
57
103
  const { entries } = await loadIndex(ctx);
@@ -293,6 +339,13 @@ export function searchIndex(entries, query) {
293
339
  .sort((a, b) => b.score - a.score || a.title.localeCompare(b.title))
294
340
  .map(({ evidence: _evidence, ...e }) => e);
295
341
  }
342
+ function underTitle(text, line) {
343
+ const end = text.indexOf("\n");
344
+ const first = end < 0 ? text : text.slice(0, end);
345
+ if (!/^#\s/.test(first))
346
+ return `${line}\n\n${text}`;
347
+ return `${first}\n\n${line}\n${end < 0 ? "" : text.slice(end)}`;
348
+ }
296
349
  const INDEX_REF = "index";
297
350
  export const docsSearch = {
298
351
  name: "docs search",
@@ -310,10 +363,22 @@ export const docsSearch = {
310
363
  async run(ctx, input) {
311
364
  const query = (input.positionals.query ?? []).join(" ");
312
365
  const limit = intOption(input, "limit", { min: 1, max: 100, fallback: 10 });
313
- const { entries } = await loadIndex(ctx);
366
+ const { client, entries } = await loadIndex(ctx);
314
367
  const hits = searchIndex(entries, query);
315
368
  const { terms } = queryTerms(query);
316
- const items = hits.slice(0, limit).map(({ page, title, description, section }) => ({ page, title, section, description }));
369
+ const marked = platformMarker(client);
370
+ const items = await Promise.all(hits.slice(0, limit).map(async ({ page, title, description, section, audience }) => ({
371
+ page,
372
+ title,
373
+ section,
374
+ description,
375
+ ...(audience ? { audience } : {}),
376
+ ...((await marked(audience)) ? { mark: PLATFORM_PAGE_MARK } : {}),
377
+ })));
378
+ const rows = items.map((item) => ("mark" in item ? { ...item, title: `${item.title} (platform page)` } : item));
379
+ const markLine = items.some((item) => "mark" in item)
380
+ ? `\n\nA (platform page) describes actions that need a personal access token with Platform mode: this token can read it but not act on it.`
381
+ : "";
317
382
  const none = `No page matches "${query}"${terms.length ? ` (looked for: ${terms.join(", ")})` : " (it has only stop words)"}. ` +
318
383
  (soundsGerman(query)
319
384
  ? `The docs are in English: try English words for the concept (knowledge base, test, trigger, default), `
@@ -321,7 +386,7 @@ export const docsSearch = {
321
386
  `or read the list of all ${entries.length} pages with: ${cavelonCommand("docs", "get", INDEX_REF)}`;
322
387
  return {
323
388
  data: { query, terms, items, total: hits.length, ...(items.length ? {} : { hint: none }) },
324
- text: items.length ? `${table(items, ["page", "title", "description"], 70)}\n\nRead one: ${cavelonCommand("docs", "get", fill("page"))}` : none,
389
+ text: items.length ? `${table(rows, ["page", "title", "description"], 70)}${markLine}\n\nRead one: ${cavelonCommand("docs", "get", fill("page"))}` : none,
325
390
  };
326
391
  },
327
392
  };
@@ -364,11 +429,22 @@ export const docsGet = {
364
429
  }
365
430
  const response = await client.get(entry.url, { accept: "text/markdown, text/plain" });
366
431
  const markdown = response.text;
432
+ const audience = headerAudience(response.headers) ?? entry.audience;
433
+ const mark = (await platformMarker(client)(audience)) ? PLATFORM_PAGE_MARK : undefined;
367
434
  const chunk = markdown.slice(offset, offset + max);
368
435
  const next = offset + max < markdown.length ? String(offset + max) : null;
369
436
  return {
370
- data: { page: entry.page, title: entry.title, url: entry.url, markdown: chunk, next_cursor: next, length: markdown.length },
371
- text: chunk + (next ? `\n\n… page continues: ${cavelonCommand("docs", "get", entry.page, "--cursor", next)}` : ""),
437
+ data: {
438
+ page: entry.page,
439
+ title: entry.title,
440
+ url: entry.url,
441
+ ...(audience ? { audience } : {}),
442
+ ...(mark ? { mark } : {}),
443
+ markdown: chunk,
444
+ next_cursor: next,
445
+ length: markdown.length,
446
+ },
447
+ text: (mark ? underTitle(chunk, `> ${mark}`) : chunk) + (next ? `\n\n… page continues: ${cavelonCommand("docs", "get", entry.page, "--cursor", next)}` : ""),
372
448
  };
373
449
  },
374
450
  };
@@ -14,6 +14,7 @@ import { activate, apply, explain, pull, validate } from "./solution.js";
14
14
  import { schema } from "./schema.js";
15
15
  import { harnessClone, harnessDefault, harnessList, harnessNew, tenantCreate, tenantList } from "./tenants.js";
16
16
  import { kbUpload, testRun, trace } from "./work.js";
17
+ import { dbConnections, dbInstance, dbQueries, dbRuns, dbTest, dbTestRun } from "./db.js";
17
18
  import { secretsDelete, secretsList, secretsSet, variablesDelete, variablesGet, variablesList, variablesSet } from "./values.js";
18
19
  import { loopCancel, loopIterations, loopPause, loopResume, loopStart, loopWatch, triggerIdentity } from "./loops.js";
19
20
  import { artifactsExport, sandboxActivity, sandboxCat, sandboxFiles, sandboxList, sandboxLogs, sandboxReceipt, sandboxRefresh, sandboxSeed, sandboxValidate, } from "./sandboxes.js";
@@ -102,6 +103,12 @@ export const COMMANDS = [
102
103
  kbUpload,
103
104
  testRun,
104
105
  trace,
106
+ dbInstance,
107
+ dbConnections,
108
+ dbQueries,
109
+ dbRuns,
110
+ dbTest,
111
+ dbTestRun,
105
112
  loopStart,
106
113
  loopCancel,
107
114
  loopWatch,