@cavelon/cli 0.1.9 → 0.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +23 -10
  2. package/dist/access.js +194 -0
  3. package/dist/acting.js +123 -0
  4. package/dist/agent-env.js +20 -2
  5. package/dist/branches.js +4 -3
  6. package/dist/capacity.js +3 -2
  7. package/dist/code-hints.js +5 -4
  8. package/dist/command.js +6 -0
  9. package/dist/commands/api.js +40 -21
  10. package/dist/commands/async.js +7 -4
  11. package/dist/commands/chat.js +18 -15
  12. package/dist/commands/db.js +367 -0
  13. package/dist/commands/docs.js +87 -9
  14. package/dist/commands/fmt.js +6 -4
  15. package/dist/commands/index.js +8 -0
  16. package/dist/commands/init.js +106 -28
  17. package/dist/commands/limits-set.js +12 -11
  18. package/dist/commands/limits.js +4 -3
  19. package/dist/commands/loops.js +75 -19
  20. package/dist/commands/models.js +12 -13
  21. package/dist/commands/sandboxes.js +22 -16
  22. package/dist/commands/schema.js +6 -5
  23. package/dist/commands/session.js +134 -37
  24. package/dist/commands/setup.js +4 -2
  25. package/dist/commands/solution.js +289 -93
  26. package/dist/commands/tenants.js +58 -22
  27. package/dist/commands/values.js +110 -45
  28. package/dist/commands/work.js +31 -17
  29. package/dist/confirm-token.js +15 -5
  30. package/dist/context.js +3 -1
  31. package/dist/contracts.js +39 -13
  32. package/dist/database-queries.js +301 -0
  33. package/dist/default-route.js +1 -1
  34. package/dist/features.js +2 -1
  35. package/dist/fsutil.js +14 -0
  36. package/dist/harness-ref.js +6 -4
  37. package/dist/http.js +39 -4
  38. package/dist/invoke.js +7 -2
  39. package/dist/kit-codes.js +14 -2
  40. package/dist/limits.js +1 -1
  41. package/dist/main.js +13 -1
  42. package/dist/mcp.js +105 -26
  43. package/dist/openapi.js +5 -2
  44. package/dist/operations.js +3 -2
  45. package/dist/package-check.js +29 -4
  46. package/dist/package-files.js +5 -1
  47. package/dist/package-format.js +10 -0
  48. package/dist/preview-report.js +46 -7
  49. package/dist/principal.js +24 -2
  50. package/dist/printed.js +182 -0
  51. package/dist/project.js +2 -1
  52. package/dist/results.js +1 -1
  53. package/dist/secret-access.js +42 -0
  54. package/dist/session.js +39 -19
  55. package/dist/shell.js +0 -3
  56. package/dist/skills/cavelon-authoring/SKILL.md +88 -4
  57. package/dist/skills/cavelon-long-running/SKILL.md +9 -3
  58. package/dist/skills/cavelon-loop/SKILL.md +81 -19
  59. package/dist/skills/cavelon-testing/SKILL.md +28 -1
  60. package/dist/tenant-choice.js +7 -7
  61. package/dist/trace-view.js +11 -1
  62. package/dist/update-check.js +2 -2
  63. package/dist/user-config.js +24 -0
  64. package/package.json +1 -1
@@ -0,0 +1,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
+ };
@@ -2,7 +2,27 @@ import { intOption, positional } from "../command.js";
2
2
  import { CavelonError, ExitCode } from "../errors.js";
3
3
  import { table } from "../format.js";
4
4
  import { NOT_HERE } from "../http.js";
5
- import { cavelonCommand } from "../shell.js";
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,9 +339,17 @@ 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",
352
+ tenantless: true,
299
353
  summary: "Search this instance's docs (titles and summaries).",
300
354
  description: "Ranks the pages of the instance's docs index by the words of the question in their titles, addresses and\n" +
301
355
  "summaries, rare words counting more than common ones. Stop words (English and German) are ignored, words match\n" +
@@ -309,10 +363,22 @@ export const docsSearch = {
309
363
  async run(ctx, input) {
310
364
  const query = (input.positionals.query ?? []).join(" ");
311
365
  const limit = intOption(input, "limit", { min: 1, max: 100, fallback: 10 });
312
- const { entries } = await loadIndex(ctx);
366
+ const { client, entries } = await loadIndex(ctx);
313
367
  const hits = searchIndex(entries, query);
314
368
  const { terms } = queryTerms(query);
315
- 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
+ : "";
316
382
  const none = `No page matches "${query}"${terms.length ? ` (looked for: ${terms.join(", ")})` : " (it has only stop words)"}. ` +
317
383
  (soundsGerman(query)
318
384
  ? `The docs are in English: try English words for the concept (knowledge base, test, trigger, default), `
@@ -320,12 +386,13 @@ export const docsSearch = {
320
386
  `or read the list of all ${entries.length} pages with: ${cavelonCommand("docs", "get", INDEX_REF)}`;
321
387
  return {
322
388
  data: { query, terms, items, total: hits.length, ...(items.length ? {} : { hint: none }) },
323
- text: items.length ? `${table(items, ["page", "title", "description"], 70)}\n\nRead one: cavelon docs get <page>` : none,
389
+ text: items.length ? `${table(rows, ["page", "title", "description"], 70)}${markLine}\n\nRead one: ${cavelonCommand("docs", "get", fill("page"))}` : none,
324
390
  };
325
391
  },
326
392
  };
327
393
  export const docsGet = {
328
394
  name: "docs get",
395
+ tenantless: true,
329
396
  summary: "Print one docs page as markdown.",
330
397
  readOnly: true,
331
398
  idempotent: true,
@@ -357,16 +424,27 @@ export const docsGet = {
357
424
  throw new CavelonError(ExitCode.failure, {
358
425
  code: "doc_not_found",
359
426
  message: `No docs page "${ref}" on this instance.`,
360
- hint: near.length ? `Did you mean: ${near.join(", ")}?` : "Find it with `cavelon docs search <words>`.",
427
+ hint: near.length ? `Did you mean: ${near.join(", ")}?` : `Find it with \`${cavelonCommand("docs", "search", fill("words"))}\`.`,
361
428
  });
362
429
  }
363
430
  const response = await client.get(entry.url, { accept: "text/markdown, text/plain" });
364
431
  const markdown = response.text;
432
+ const audience = headerAudience(response.headers) ?? entry.audience;
433
+ const mark = (await platformMarker(client)(audience)) ? PLATFORM_PAGE_MARK : undefined;
365
434
  const chunk = markdown.slice(offset, offset + max);
366
435
  const next = offset + max < markdown.length ? String(offset + max) : null;
367
436
  return {
368
- data: { page: entry.page, title: entry.title, url: entry.url, markdown: chunk, next_cursor: next, length: markdown.length },
369
- 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)}` : ""),
370
448
  };
371
449
  },
372
450
  };
@@ -7,6 +7,7 @@ import { uncommitted } from "../git.js";
7
7
  import { fileDigest, fileDigests, readPulledFiles, rememberAppliedFiles } from "../local-state.js";
8
8
  import { packageVersionOf } from "../package-check.js";
9
9
  import { canonical, contentPath, readPackage } from "../package-files.js";
10
+ import { cavelonCommand } from "../printed.js";
10
11
  import { exportForm, sectionContent, toYaml } from "../package-format.js";
11
12
  import { requireInstance } from "../session.js";
12
13
  import { requireSolution, schemaFor } from "./solution.js";
@@ -31,6 +32,7 @@ function droppedComments(before, after) {
31
32
  }
32
33
  export const fmt = {
33
34
  name: "fmt",
35
+ tenantless: true,
34
36
  summary: "Bring the package files into the export's form (field order and defaults from the package schema), offline.",
35
37
  description: "A file whose value the export would spell differently is rewritten: each field in the schema's order, and each field it\n" +
36
38
  "leaves out set to what the instance gives it, as the export writes it: the schema's default, an empty list or object for\n" +
@@ -63,7 +65,7 @@ export const fmt = {
63
65
  throw new CavelonError(ExitCode.validation, {
64
66
  code: "package_file_invalid",
65
67
  message: `${invalid.length} package file${invalid.length === 1 ? "" : "s"} cannot be read: ${invalid.map((f) => `${f.file}${f.line ? `:${f.line}` : ""}`).join(", ")}.`,
66
- hint: "Fix them first (`cavelon validate` names each); fmt changes nothing until then.",
68
+ hint: `Fix them first (\`${cavelonCommand("validate")}\` names each); fmt changes nothing until then.`,
67
69
  });
68
70
  }
69
71
  const version = packageVersionOf(disk.package) ?? project.packageVersion;
@@ -72,7 +74,7 @@ export const fmt = {
72
74
  throw new CavelonError(ExitCode.failure, {
73
75
  code: "package_schema_unavailable",
74
76
  message: `No package schema${version ? ` for format ${version}` : ""} is cached for this instance, and it was not read.`,
75
- hint: "Run `cavelon fmt` (or `cavelon validate`) once without --offline while the instance is reachable.",
77
+ hint: `Run \`${cavelonCommand("fmt")}\` (or \`${cavelonCommand("validate")}\`) once without --offline while the instance is reachable.`,
76
78
  });
77
79
  }
78
80
  const changes = [];
@@ -141,7 +143,7 @@ export const fmt = {
141
143
  text: files.length
142
144
  ? [
143
145
  ...files.map((f) => `would format ${f}`),
144
- `${files.length} file${files.length === 1 ? "" : "s"} not in the export's form; run \`cavelon fmt\`.`,
146
+ `${files.length} file${files.length === 1 ? "" : "s"} not in the export's form; run \`${cavelonCommand("fmt")}\`.`,
145
147
  ...(lost.length ? [`fmt would drop the comments of ${commentList}; keep notes you need elsewhere first.`] : []),
146
148
  ].join("\n")
147
149
  : `All ${unchanged} package files are in the export's form.`,
@@ -165,7 +167,7 @@ export const fmt = {
165
167
  text: [
166
168
  ...written.map((f) => `formatted ${f}`),
167
169
  `${written.length} file${written.length === 1 ? "" : "s"} formatted, ${unchanged} already in the export's form.`,
168
- ...(written.length ? [diffable ? "Check it: cavelon validate; then git diff shows what changed." : "Check it: cavelon validate."] : []),
170
+ ...(written.length ? [`Check it: ${cavelonCommand("validate")}${diffable ? "; then git diff shows what changed." : "."}`] : []),
169
171
  ].join("\n"),
170
172
  };
171
173
  },
@@ -14,11 +14,13 @@ 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";
20
21
  const commandsList = {
21
22
  name: "commands",
23
+ tenantless: true,
22
24
  summary: "List every command, whether it is read-only, and its MCP tool.",
23
25
  readOnly: true,
24
26
  idempotent: true,
@@ -36,6 +38,7 @@ const commandsList = {
36
38
  };
37
39
  const mcp = {
38
40
  name: "mcp",
41
+ tenantless: true,
39
42
  summary: "Serve the commands as MCP tools on stdio (for coding agents).",
40
43
  description: "Started by the agent's plugin (`cavelon mcp`); it does not return until the agent disconnects.",
41
44
  readOnly: false,
@@ -100,6 +103,11 @@ export const COMMANDS = [
100
103
  kbUpload,
101
104
  testRun,
102
105
  trace,
106
+ dbConnections,
107
+ dbQueries,
108
+ dbRuns,
109
+ dbTest,
110
+ dbTestRun,
103
111
  loopStart,
104
112
  loopCancel,
105
113
  loopWatch,