@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
@@ -7,6 +7,7 @@ import { harnessNotFoundError, lookupHarness } from "../harness-ref.js";
7
7
  import { callStable, workflowOperation } from "../invoke.js";
8
8
  import { cavelonCommand, fill } from "../printed.js";
9
9
  import { MCP_MAX_WAIT_MS } from "./async.js";
10
+ import { accessFor, activationStep, mayActivate } from "../access.js";
10
11
  function harnessRef(session, input) {
11
12
  const option = stringOption(input, "harness");
12
13
  if (option)
@@ -30,13 +31,13 @@ const HARNESS_OPTION = {
30
31
  };
31
32
  const ENV_OPTION = { type: "string", value: "<name>", description: "Use env/<name>.yaml: its tenant and solution." };
32
33
  const DEFAULT_CHAT_TIMEOUT = "2m";
33
- function chatError(error, harness) {
34
+ function chatError(error, harness, may = null) {
34
35
  if (!(error instanceof CavelonError) || error.status !== 409)
35
36
  return error;
36
37
  const hint = !harness
37
38
  ? `Nothing answers on the tenant's default route yet: name a solution with --harness, or make an active one the default (\`${cavelonCommand("harness", "default", fill("solution"))}\`).`
38
39
  : harness.status !== "active"
39
- ? `${named(harness)} is ${harness.status}: a draft answers only a person's token (as a Playground run), never a tenant API key. Use a personal access token, or activate it first (\`${cavelonCommand("activate", "--harness", harness.slug)}\`).`
40
+ ? `${named(harness)} is ${harness.status}: a draft answers only a person's token (as a Playground run), never a tenant API key. Use a personal access token, or activate it first (${activationStep(may, cavelonCommand("activate", "--harness", harness.slug))}).`
40
41
  : "A session belongs to the solution it started with: leave out --session to start a new one.";
41
42
  return new CavelonError(error.exitCode, { code: error.code, status: error.status, message: error.message, hint, docs: error.docs, details: error.details });
42
43
  }
@@ -51,6 +52,7 @@ export const chat = {
51
52
  readOnly: false,
52
53
  mcpEffect: "Starts or continues a conversation with the solution and runs its agents (model usage, its tools' actions); changes no configuration.",
53
54
  mcpTool: "chat",
55
+ operations: ["POST /api/v1/chat"],
54
56
  positionals: [{ name: "message", description: "What the user says.", required: true }],
55
57
  options: {
56
58
  harness: HARNESS_OPTION,
@@ -79,7 +81,7 @@ export const chat = {
79
81
  answer = await callStable(ctx, "POST", "/api/v1/chat", "chatting with a solution", { body, timeoutMs: timeout });
80
82
  }
81
83
  catch (error) {
82
- throw chatError(error, harness);
84
+ throw chatError(error, harness, error instanceof CavelonError && error.status === 409 ? mayActivate(await accessFor(await ctx.client())) : null);
83
85
  }
84
86
  const target = harness ? { id: harness.id, slug: harness.slug, name: harness.name, status: harness.status } : null;
85
87
  if (answer.retrieval_warning)
@@ -117,6 +119,7 @@ export const deactivate = {
117
119
  destructive: true,
118
120
  idempotent: true,
119
121
  mcpTool: "deactivate",
122
+ operations: ["POST /api/v1/harnesses/{harness_id}/deactivate"],
120
123
  options: {
121
124
  harness: HARNESS_OPTION,
122
125
  env: ENV_OPTION,
@@ -164,7 +167,7 @@ export const deactivate = {
164
167
  data: { changed: false, harness: target, would: "deactivate", confirm: gate.confirm(confirmCommand), ...gate.fields },
165
168
  text: [
166
169
  `Deactivating ${named(harness)} sets it inactive and takes it out of live traffic: the conversations, channels and API keys that name it are no longer answered by it until it is activated again${known}.`,
167
- ...(gate.mismatch ? [gate.mismatch] : []),
170
+ gate.where, ...(gate.mismatch ? [gate.mismatch] : []),
168
171
  `Show this to a person; with their yes: ${gate.confirm(confirmCommand)}`,
169
172
  ].join("\n"),
170
173
  ...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
@@ -175,7 +178,9 @@ export const deactivate = {
175
178
  });
176
179
  return {
177
180
  data: { changed: true, harness: { ...target, status: updated?.status ?? target.status } },
178
- text: `Deactivated ${named(harness)}; status ${updated?.status ?? "unknown"}. \`${cavelonCommand("activate", "--harness", harness.slug)}\` puts it back through its readiness gate.`,
181
+ text: `Deactivated ${named(harness)}; status ${updated?.status ?? "unknown"}. ${mayActivate(await accessFor(await ctx.client())) === false
182
+ ? "A person who may activate puts it back through its readiness gate, in the Admin; this credential may not activate."
183
+ : `\`${cavelonCommand("activate", "--harness", harness.slug)}\` puts it back through its readiness gate.`}`,
179
184
  };
180
185
  },
181
186
  };
@@ -0,0 +1,367 @@
1
+ import { CURSOR_OPTION, intOption, LIMIT_OPTION, listOption, pageOf, positional, stringOption } from "../command.js";
2
+ import { CavelonError, ExitCode, usageError } from "../errors.js";
3
+ import { requireFeature } from "../features.js";
4
+ import { clip, keyValues, moreHint, table } from "../format.js";
5
+ import { callStable } from "../invoke.js";
6
+ import { cavelonCommand, fill } from "../printed.js";
7
+ import { isUuid } from "../session.js";
8
+ const FEATURE = "database_connector_enabled";
9
+ const DOCS_PAGE = "administration/database-connectors";
10
+ const connectorOn = (ctx) => requireFeature(ctx, FEATURE, "database_connector_disabled", "the database connector");
11
+ function ownerOnly(error, what) {
12
+ if (!(error instanceof CavelonError) || error.status !== 403)
13
+ return error;
14
+ return new CavelonError(error.exitCode, {
15
+ code: error.code,
16
+ status: error.status,
17
+ message: error.message,
18
+ hint: `${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. ` +
19
+ `\`${cavelonCommand("whoami")}\` shows the token's role.`,
20
+ docs: error.docs,
21
+ });
22
+ }
23
+ async function listConnections(ctx) {
24
+ await connectorOn(ctx);
25
+ return callStable(ctx, "GET", "/api/v1/database-connectors/connections", "database connections");
26
+ }
27
+ async function listQueries(ctx, connectionId) {
28
+ await connectorOn(ctx);
29
+ return callStable(ctx, "GET", "/api/v1/database-connectors/queries", "database queries", { query: { connection_id: connectionId } });
30
+ }
31
+ async function resolveConnection(ctx, ref) {
32
+ const all = await listConnections(ctx);
33
+ const hit = all.find((c) => c.id === ref.toLowerCase()) ?? all.find((c) => c.name === ref) ?? all.find((c) => c.name.toLowerCase() === ref.toLowerCase());
34
+ if (hit)
35
+ return hit;
36
+ throw new CavelonError(ExitCode.failure, {
37
+ code: "database_connection_not_found",
38
+ message: `No database connection "${ref}" in this tenant.`,
39
+ hint: `\`${cavelonCommand("db", "connections")}\` lists them${all.length ? ` (${all.map((c) => c.name).slice(0, 10).join(", ")})` : "; a superadmin creates one in the Admin"}.`,
40
+ });
41
+ }
42
+ async function resolveQuery(ctx, ref) {
43
+ await connectorOn(ctx);
44
+ if (isUuid(ref)) {
45
+ try {
46
+ return await callStable(ctx, "GET", "/api/v1/database-connectors/queries/{query_id}", "database queries", { params: { query_id: [ref] } });
47
+ }
48
+ catch (error) {
49
+ if (!(error instanceof CavelonError && error.status === 404))
50
+ throw error;
51
+ }
52
+ }
53
+ const all = await listQueries(ctx);
54
+ const hit = all.find((q) => q.id === ref.toLowerCase()) ?? all.find((q) => q.slug === ref) ?? all.find((q) => q.slug.toLowerCase() === ref.toLowerCase());
55
+ if (hit)
56
+ return hit;
57
+ throw new CavelonError(ExitCode.failure, {
58
+ code: "database_query_not_found",
59
+ message: `No database query "${ref}" in this tenant.`,
60
+ hint: `\`${cavelonCommand("db", "queries")}\` lists them by the slug of their tool${all.length ? ` (${all.map((q) => q.slug).slice(0, 10).join(", ")})` : ""}.`,
61
+ });
62
+ }
63
+ function connectionView(c) {
64
+ const { ca_certificate_pem: pem, ...rest } = c;
65
+ return { ...rest, ca_certificate_set: Boolean(pem) };
66
+ }
67
+ function lastTest(c) {
68
+ if (!c.last_test_at)
69
+ return "never";
70
+ return `${c.last_test_outcome ?? "?"} (${c.last_test_at})`;
71
+ }
72
+ const filledBy = (p) => (!p.source || p.source === "model" ? "model" : p.source);
73
+ function parameterRows(parameters) {
74
+ return parameters.map((p) => ({
75
+ name: p.name,
76
+ filled_by: filledBy(p),
77
+ type: p.type ?? "string",
78
+ required: p.required === false ? "no" : "yes",
79
+ constraints: ["max_length", "pattern", "enum", "minimum", "maximum"]
80
+ .filter((k) => p[k] !== undefined && p[k] !== null)
81
+ .map((k) => `${k} ${JSON.stringify(p[k])}`)
82
+ .join(", ") || null,
83
+ description: p.description || null,
84
+ }));
85
+ }
86
+ function explainLine(codes) {
87
+ const distinct = [...new Set(codes.filter((c) => Boolean(c)))];
88
+ if (!distinct.length)
89
+ return "";
90
+ return `\n\nWhat a code means: ${cavelonCommand("explain", fill("code"))} (${distinct.slice(0, 8).join(", ")})`;
91
+ }
92
+ export const dbConnections = {
93
+ name: "db connections",
94
+ summary: "The tenant's database connections: dialect, target, TLS mode, last test and query count; never a password.",
95
+ description: "A superadmin creates and changes connections in the Admin; a token reads them. A package names a query's connection by\n" +
96
+ "name and dialect, so the same name serves in every tenant and environment. A query tool is ready for agents only while\n" +
97
+ "its connection is enabled and its last test passed; the tenant Owner runs the test with `cavelon db test <connection>`.",
98
+ readOnly: true,
99
+ idempotent: true,
100
+ mcpTool: "db_connections",
101
+ options: { limit: { ...LIMIT_OPTION, description: "Return at most n connections (default 50)." }, cursor: CURSOR_OPTION },
102
+ examples: ["cavelon db connections", "cavelon db connections --json"],
103
+ async run(ctx, input) {
104
+ const limit = intOption(input, "limit", { min: 1, max: 500, fallback: 50 });
105
+ const page = pageOf((await listConnections(ctx)).map(connectionView), limit, stringOption(input, "cursor"));
106
+ const rows = page.items.map((c) => {
107
+ const conn = c;
108
+ return {
109
+ name: conn.name,
110
+ dialect: conn.dialect,
111
+ target: `${conn.host}:${conn.port}/${conn.database_name}`,
112
+ tls: conn.tls_mode,
113
+ enabled: conn.is_enabled ? "yes" : "no",
114
+ last_test: lastTest(conn),
115
+ queries: conn.query_count ?? null,
116
+ id: conn.id,
117
+ };
118
+ });
119
+ const untested = page.items.filter((c) => c.last_test_outcome !== "ok").map((c) => String(c.name));
120
+ return {
121
+ data: page,
122
+ text: (table(rows, ["name", "dialect", "target", "tls", "enabled", "last_test", "queries", "id"]) ||
123
+ `No database connections. A superadmin creates one in the Admin (\`${cavelonCommand("docs", "get", DOCS_PAGE)}\` says who does what).`) +
124
+ moreHint(page.next_cursor, cavelonCommand("db", "connections")) +
125
+ (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"))}` : ""),
126
+ };
127
+ },
128
+ };
129
+ export const dbQueries = {
130
+ name: "db queries",
131
+ summary: "The tenant's saved database queries by tool slug; with a query, its SQL, parameters and limits.",
132
+ description: "Each saved query is one agent tool (tool_type database_query). A superadmin writes it in the Admin; `cavelon pull` writes\n" +
133
+ "its definition into the package's tools. A parameter filled by end_user.* comes from the signed-in visitor, never from\n" +
134
+ "the model. Without a query: one line per query. With one (its tool's slug or the query's id): the whole query.",
135
+ readOnly: true,
136
+ idempotent: true,
137
+ mcpTool: "db_queries",
138
+ positionals: [{ name: "query", description: "A query's tool slug or id: show it in full." }],
139
+ options: {
140
+ connection: { type: "string", value: "<connection>", description: "Only the queries of this connection (name or id)." },
141
+ limit: { ...LIMIT_OPTION, description: "Return at most n queries (default 50)." },
142
+ cursor: CURSOR_OPTION,
143
+ },
144
+ examples: ["cavelon db queries", "cavelon db queries --connection shop-db", "cavelon db queries order_status --json"],
145
+ async run(ctx, input) {
146
+ const ref = positional(input, "query");
147
+ if (ref) {
148
+ const q = await resolveQuery(ctx, ref);
149
+ const text = [
150
+ keyValues([
151
+ ["query", `${q.slug} (${q.name})`],
152
+ ["connection", q.connection_name],
153
+ ["description", q.description ? clip(q.description, 300) : undefined],
154
+ ["limits", `max_rows ${q.max_rows}, max_result_chars ${q.max_result_chars}`],
155
+ ["anonymous", q.allows_anonymous ? "visitors may call it without signing in" : "a signed-in visitor only"],
156
+ ["enabled", q.is_enabled ? "yes" : "no"],
157
+ ["version", q.version],
158
+ ["id", q.id],
159
+ ]),
160
+ "",
161
+ "SQL:",
162
+ q.sql_text,
163
+ "",
164
+ q.parameters.length ? table(parameterRows(q.parameters), ["name", "filled_by", "type", "required", "constraints", "description"]) : "No parameters.",
165
+ "",
166
+ `Its runs (no values, no rows): ${cavelonCommand("db", "runs", q.slug)}`,
167
+ ].join("\n");
168
+ return { data: q, text };
169
+ }
170
+ const connectionRef = stringOption(input, "connection");
171
+ const connection = connectionRef ? await resolveConnection(ctx, connectionRef) : undefined;
172
+ const limit = intOption(input, "limit", { min: 1, max: 500, fallback: 50 });
173
+ const all = (await listQueries(ctx, connection?.id)).map(({ sql_text: sql, params_json_schema: _schema, ...q }) => ({ ...q, sql_chars: sql.length }));
174
+ const page = pageOf(all, limit, stringOption(input, "cursor"));
175
+ const rows = page.items.map((q) => ({
176
+ slug: q.slug,
177
+ name: q.name,
178
+ connection: q.connection_name,
179
+ parameters: q.parameters.map((p) => (filledBy(p) === "model" ? p.name : `${p.name} (${filledBy(p)})`)).join(", ") || null,
180
+ max_rows: q.max_rows,
181
+ anonymous: q.allows_anonymous ? "yes" : "no",
182
+ enabled: q.is_enabled ? "yes" : "no",
183
+ version: q.version,
184
+ }));
185
+ return {
186
+ data: page,
187
+ text: (table(rows, ["slug", "name", "connection", "parameters", "max_rows", "anonymous", "enabled", "version"], 60) || "No database queries.") +
188
+ moreHint(page.next_cursor, cavelonCommand("db", "queries")) +
189
+ (rows.length ? `\n\nOne query in full: ${cavelonCommand("db", "queries", fill("slug"))}` : ""),
190
+ };
191
+ },
192
+ };
193
+ export const dbRuns = {
194
+ name: "db runs",
195
+ summary: "A saved query's runs, newest first: source, outcome, error code, duration and row count; never values or rows.",
196
+ 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" +
197
+ "`cavelon explain <code>` says what an error code means and how to fix it.",
198
+ readOnly: true,
199
+ idempotent: true,
200
+ mcpTool: "db_runs",
201
+ positionals: [{ name: "query", description: "The query's tool slug or id.", required: true }],
202
+ options: {
203
+ limit: { ...LIMIT_OPTION, description: "Return at most n runs (default 20, at most 200)." },
204
+ cursor: CURSOR_OPTION,
205
+ },
206
+ examples: ["cavelon db runs order_status", "cavelon db runs order_status --limit 50 --json"],
207
+ async run(ctx, input) {
208
+ const q = await resolveQuery(ctx, positional(input, "query"));
209
+ const limit = intOption(input, "limit", { min: 1, max: 200, fallback: 20 });
210
+ const cursor = stringOption(input, "cursor");
211
+ const offset = cursor === undefined ? 0 : Number(cursor);
212
+ if (!Number.isInteger(offset) || offset < 0)
213
+ throw usageError(`--cursor "${cursor}" is not a cursor from a previous page.`);
214
+ const page = await callStable(ctx, "GET", "/api/v1/database-connectors/queries/{query_id}/runs", "database query runs", {
215
+ params: { query_id: [q.id] },
216
+ query: { limit, offset },
217
+ });
218
+ const items = page.items ?? [];
219
+ const next = typeof page.next_offset === "number" ? String(page.next_offset) : null;
220
+ const rows = items.map((r) => ({
221
+ at: r.created_at,
222
+ source: r.source,
223
+ outcome: r.outcome,
224
+ error_code: r.error_code ?? null,
225
+ duration_ms: r.duration_ms ?? null,
226
+ rows: r.row_count ?? null,
227
+ truncated: r.truncated ? "yes" : null,
228
+ version: r.query_version,
229
+ }));
230
+ return {
231
+ data: { query: { id: q.id, slug: q.slug, version: q.version }, items, next_cursor: next },
232
+ text: (table(rows, ["at", "source", "outcome", "error_code", "duration_ms", "rows", "truncated", "version"]) || `No runs of ${q.slug} yet.`) +
233
+ moreHint(next, cavelonCommand("db", "runs", q.slug)) +
234
+ explainLine(items.map((r) => r.error_code)),
235
+ };
236
+ },
237
+ };
238
+ export const dbTest = {
239
+ name: "db test",
240
+ summary: "Test a database connection step by step (DNS, policy, TCP, TLS, login, SELECT 1, version, write privileges); exit 3 when a step fails.",
241
+ description: "Needs the tenant Owner's permission (database_connectors.test). The result becomes the connection's last test: a query tool\n" +
242
+ "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" +
243
+ "step names its code; `cavelon explain <code>` says how to fix it. A finding under write_privileges means the database user\n" +
244
+ "can write: ask the database administrator for a read-only user.",
245
+ readOnly: false,
246
+ idempotent: true,
247
+ mcpEffect: "Runs the connection test on the instance and stores its outcome as the connection's last test; changes no setting.",
248
+ mcpTool: "db_test",
249
+ operations: ["POST /api/v1/database-connectors/connections/{connection_id}/test"],
250
+ positionals: [{ name: "connection", description: "The connection's name or id.", required: true }],
251
+ examples: ["cavelon db test shop-db", "cavelon db test shop-db --json"],
252
+ async run(ctx, input) {
253
+ const connection = await resolveConnection(ctx, positional(input, "connection"));
254
+ let result;
255
+ try {
256
+ result = await callStable(ctx, "POST", "/api/v1/database-connectors/connections/{connection_id}/test", "testing database connections", {
257
+ params: { connection_id: [connection.id] },
258
+ timeoutMs: 90_000,
259
+ });
260
+ }
261
+ catch (error) {
262
+ throw ownerOnly(error, "A connection test");
263
+ }
264
+ const ok = result.outcome === "ok";
265
+ 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 }));
266
+ const text = [
267
+ `Connection "${connection.name}" (${connection.dialect}): ${ok ? "test passed" : `test failed (${result.outcome})`}, ${result.duration_ms} ms.`,
268
+ table(steps, ["step", "status", "code", ...(steps.some((s) => s.message) ? ["message"] : [])], 80),
269
+ ...(result.server_version ? [`server: ${result.server_version}`] : []),
270
+ ...(result.write_privileges ? [`write privileges: ${clip(JSON.stringify(result.write_privileges), 300)}`] : []),
271
+ ].join("\n");
272
+ return {
273
+ data: { connection: { id: connection.id, name: connection.name, dialect: connection.dialect }, ...result },
274
+ text: text + explainLine(steps.filter((s) => s.code && s.status !== "ok").map((s) => s.code)),
275
+ exitCode: ok ? ExitCode.ok : ExitCode.validation,
276
+ };
277
+ },
278
+ };
279
+ function typed(parameter, raw) {
280
+ const type = parameter?.type ?? "string";
281
+ if (type === "integer" || type === "number") {
282
+ const value = Number(raw);
283
+ if (raw.trim() === "" || !Number.isFinite(value) || (type === "integer" && !Number.isInteger(value))) {
284
+ throw usageError(`--value ${parameter.name}: "${raw}" is not ${type === "integer" ? "an integer" : "a number"}.`);
285
+ }
286
+ return value;
287
+ }
288
+ if (type === "boolean") {
289
+ if (raw === "true" || raw === "false")
290
+ return raw === "true";
291
+ throw usageError(`--value ${parameter.name}: "${raw}" is not true or false.`);
292
+ }
293
+ return raw;
294
+ }
295
+ function runValues(query, given) {
296
+ const values = {};
297
+ for (const pair of given) {
298
+ const at = pair.indexOf("=");
299
+ if (at <= 0)
300
+ throw usageError(`--value takes name=value, got "${pair}".`);
301
+ const name = pair.slice(0, at);
302
+ const parameter = query.parameters.find((p) => p.name === name);
303
+ if (!parameter) {
304
+ throw usageError(`${query.slug} has no parameter "${name}".`, `Its parameters: ${query.parameters.map((p) => `${p.name} (${filledBy(p)}, ${p.type ?? "string"})`).join(", ") || "none"}.`);
305
+ }
306
+ values[name] = typed(parameter, pair.slice(at + 1));
307
+ }
308
+ return values;
309
+ }
310
+ const ROWS_SHOWN = 20;
311
+ export const dbTestRun = {
312
+ name: "db test-run",
313
+ summary: "Run a saved query once with the values given, identity parameters included; show what the model would see and the rows.",
314
+ description: "Needs the tenant Owner's permission (database_connectors.test); it reads the customer's own data. Give each parameter\n" +
315
+ "with --value name=value, those the platform fills from the signed-in visitor (end_user.*) too: that is how an\n" +
316
+ "identity-scoped query is checked for one customer. The instance records the run (counts only) and audits it with your\n" +
317
+ "name; the rows come back once and are never stored. A failed run names its code; `cavelon explain <code>` says more.",
318
+ readOnly: false,
319
+ idempotent: true,
320
+ mcpEffect: "Runs the saved query once on the instance; it leaves a run record (counts only) and an audit entry, and changes no setting.",
321
+ mcpTool: "db_test_run",
322
+ operations: ["POST /api/v1/database-connectors/queries/{query_id}/test-run"],
323
+ positionals: [{ name: "query", description: "The query's tool slug or id.", required: true }],
324
+ options: {
325
+ value: { type: "string", multiple: true, value: "<name=value>", description: "One parameter's value, typed as the parameter's type." },
326
+ rows: { type: "string", value: "<n>", description: `Show at most n rows in the text (default ${ROWS_SHOWN}); --json carries what the instance returned.` },
327
+ },
328
+ 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"],
329
+ async run(ctx, input) {
330
+ const query = await resolveQuery(ctx, positional(input, "query"));
331
+ const values = runValues(query, listOption(input, "value"));
332
+ const shown = intOption(input, "rows", { min: 0, max: 500, fallback: ROWS_SHOWN });
333
+ let result;
334
+ try {
335
+ result = await callStable(ctx, "POST", "/api/v1/database-connectors/queries/{query_id}/test-run", "test runs of database queries", {
336
+ params: { query_id: [query.id] },
337
+ body: { values },
338
+ timeoutMs: 90_000,
339
+ });
340
+ }
341
+ catch (error) {
342
+ throw ownerOnly(error, "A test run");
343
+ }
344
+ const ok = result.outcome === "ok" && !result.error_code;
345
+ const columns = result.columns ?? [];
346
+ 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])])));
347
+ const more = (result.rows?.length ?? 0) - rows.length;
348
+ const text = [
349
+ keyValues([
350
+ ["query", `${query.slug} (version ${query.version})`],
351
+ ["outcome", result.error_code ? `${result.outcome} (${result.error_code}${result.sqlstate ? `, SQLSTATE ${result.sqlstate}` : ""})` : result.outcome],
352
+ ["rows", ok ? `${result.returned_rows ?? rows.length} returned of ${result.row_count ?? "?"}${result.truncated ? ", truncated for the model" : ""}` : undefined],
353
+ ["duration_ms", result.duration_ms],
354
+ ]),
355
+ "",
356
+ "What the model sees:",
357
+ clip(result.model_text, 2000),
358
+ ...(rows.length ? ["", table(rows, columns, 40)] : []),
359
+ ...(more > 0 ? [`… ${more} more rows (--rows, or --json).`] : []),
360
+ ].join("\n");
361
+ return {
362
+ data: { query: { id: query.id, slug: query.slug, version: query.version }, ...result },
363
+ text: text + explainLine([result.error_code]),
364
+ exitCode: ok ? ExitCode.ok : ExitCode.validation,
365
+ };
366
+ },
367
+ };
@@ -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, 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,11 @@ export const COMMANDS = [
102
103
  kbUpload,
103
104
  testRun,
104
105
  trace,
106
+ dbConnections,
107
+ dbQueries,
108
+ dbRuns,
109
+ dbTest,
110
+ dbTestRun,
105
111
  loopStart,
106
112
  loopCancel,
107
113
  loopWatch,
@@ -574,7 +574,9 @@ export const limitsSet = {
574
574
  const allowed = operator
575
575
  ? `a personal access token in Platform mode of a ${anyOf(change.requires_role ?? [], "platform role")}`
576
576
  : `a credential with ${anyOf(change.permissions)} (a session, a personal access token, or an admin API key of the tenant)`;
577
- const gate = await confirmation(ctx, input, "limits_set", { key, value, previous: previous ?? null, operation });
577
+ const gate = await confirmation(ctx, input, "limits_set", { key, value, previous: previous ?? null, operation }, {
578
+ platform: operator ? (target.scope === "one_tenant" ? "tenant" : "outside") : undefined,
579
+ });
578
580
  if (!gate.confirmed) {
579
581
  const confirm = gate.confirm(cavelonCommand("limits", "set", key, argText(value), "--confirm"));
580
582
  const source = target.limit && target.kind === "limit" ? ` (source now: ${target.limit.source}${target.limit.origin ? `, origin: ${target.limit.origin}` : ""})` : "";
@@ -585,7 +587,7 @@ export const limitsSet = {
585
587
  : [];
586
588
  return {
587
589
  data: { ...base, changed: false, sent: false, confirm, ...gate.fields },
588
- text: [`${key}: ${from} → ${to}${source}.`, ...what, `Sends: ${sends}`, `Allowed: ${allowed}.`, ...(gate.mismatch ? [gate.mismatch] : []), `Nothing was changed. Change it with: ${confirm}`].join("\n"),
590
+ text: [`${key}: ${from} → ${to}${source}.`, ...what, `Sends: ${sends}`, `Allowed: ${allowed}.`, gate.where, ...(gate.mismatch ? [gate.mismatch] : []), `Nothing was changed. Change it with: ${confirm}`].join("\n"),
589
591
  ...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
590
592
  };
591
593
  }