@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
@@ -143,7 +143,7 @@ function harnessSlugAt(path, pkg, fallback) {
143
143
  const entry = index !== undefined ? list[Number(index)] : undefined;
144
144
  return (isObject(entry) && text(entry.slug)) || fallback;
145
145
  }
146
- export function notApplied(raw, pkg, harness) {
146
+ export function notApplied(raw, pkg, harness, mayActivate = null) {
147
147
  if (!Array.isArray(raw))
148
148
  return [];
149
149
  return raw
@@ -164,7 +164,7 @@ export function notApplied(raw, pkg, harness) {
164
164
  if (field === "is_default")
165
165
  return { ...n, command: cavelonCommand("harness", "default", slug ?? "<solution>") };
166
166
  if (field === "status")
167
- return { ...n, command: slug ? cavelonCommand("activate", "--harness", slug) : cavelonCommand("activate") };
167
+ return mayActivate === false ? n : { ...n, command: slug ? cavelonCommand("activate", "--harness", slug) : cavelonCommand("activate") };
168
168
  return n;
169
169
  });
170
170
  }
package/dist/principal.js CHANGED
@@ -2,8 +2,30 @@ export async function readPrincipal(client, options = {}) {
2
2
  const response = await client.get("/api/v1/meta/principal", { allow: [400, 403, 404, 405], sendTenant: options.sendTenant });
3
3
  if (response.status !== 200 || !response.data?.kind)
4
4
  return undefined;
5
- const { permissions, ...rest } = response.data;
6
- return Array.isArray(permissions) ? { ...rest, permissions: permissions.filter((p) => typeof p === "string") } : rest;
5
+ const { permissions, needs_a_person: needsAPerson, tenant, ...rest } = response.data;
6
+ const principal = rest;
7
+ if (Array.isArray(permissions))
8
+ principal.permissions = permissions.filter((p) => typeof p === "string");
9
+ if (Array.isArray(needsAPerson))
10
+ principal.needs_a_person = operationsNeedingAPerson(needsAPerson);
11
+ if (tenant === null)
12
+ principal.tenant = null;
13
+ else if (tenant && typeof tenant === "object" && typeof tenant.id === "string") {
14
+ const text = (v) => (typeof v === "string" && v ? v : null);
15
+ principal.tenant = { id: tenant.id, name: text(tenant.name), slug: text(tenant.slug) };
16
+ }
17
+ return principal;
18
+ }
19
+ function operationsNeedingAPerson(value) {
20
+ return value
21
+ .filter((o) => Boolean(o) && typeof o === "object")
22
+ .filter((o) => typeof o.method === "string" && typeof o.path === "string")
23
+ .map((o) => ({
24
+ operation: typeof o.operation === "string" && o.operation ? o.operation : null,
25
+ method: o.method.toUpperCase(),
26
+ path: o.path,
27
+ reason: typeof o.reason === "string" ? o.reason : "",
28
+ }));
7
29
  }
8
30
  const TENANT_PAGE = 200;
9
31
  const MAX_TENANT_PAGES = 5;
@@ -1,5 +1,5 @@
1
1
  import { CavelonError, ExitCode } from "./errors.js";
2
- import { cavelonCommand } from "./printed.js";
2
+ import { cavelonCommand, fill } from "./printed.js";
3
3
  export const SECRETS_PERMISSIONS = ["settings.secrets.manage", "settings.manage"];
4
4
  export const SECRET_SETTER = "A tenant Owner (or another role allowed to manage secrets) sets it, in the Admin under Settings › Secrets or with their own token";
5
5
  export function maySetSecrets(principal) {
@@ -11,9 +11,21 @@ export function maySetSecrets(principal) {
11
11
  return null;
12
12
  return SECRETS_PERMISSIONS.some((p) => principal.permissions.includes(p));
13
13
  }
14
- export function permissionsNamed(message) {
15
- const at = /permissions?:\s*([\w.]+(?:\s*,\s*[\w.]+)*)/i.exec(message);
16
- return at ? at[1].split(",").map((p) => p.trim()).filter(Boolean) : [];
14
+ export { permissionsNamed } from "./access.js";
15
+ export const VARIABLE_SETTER = "A tenant Owner (or another role allowed to manage the tenant's settings) sets it, in the Admin under Settings › Variables or with their own token";
16
+ export function variableSetterHint(name, value) {
17
+ const shown = value !== undefined && value.length <= 120 && !value.includes("\n") ? value : fill("value");
18
+ return `${VARIABLE_SETTER}: \`${cavelonCommand("variables", "set", name, shown)}\`.`;
19
+ }
20
+ export function variablesPermissionMissing(verb, name, permissions, value) {
21
+ const needs = permissions.length ? permissions.join(" or ") : "a permission to manage the tenant's settings";
22
+ return new CavelonError(ExitCode.unauthorized, {
23
+ code: "permission_missing",
24
+ status: 403,
25
+ message: `This credential may not ${verb} tenant variables: the instance refused it, as that needs ${needs}. Variable ${name} is unchanged.`,
26
+ hint: variableSetterHint(name, value),
27
+ details: { name, permissions, sent: true },
28
+ });
17
29
  }
18
30
  export function secretSetterHint(name) {
19
31
  return `${SECRET_SETTER}: \`${cavelonCommand("secrets", "set", name)}\`.`;
package/dist/session.js CHANGED
@@ -5,7 +5,7 @@ import { exactMatch } from "./choose.js";
5
5
  import { readTenantless } from "./principal.js";
6
6
  import { listsTenants, searchTenants, tenantMissError } from "./tenant-choice.js";
7
7
  import { findProject, readEnvFile } from "./project.js";
8
- import { loadUserConfig, tokenKind, updateInstance } from "./user-config.js";
8
+ import { cachedTenantRef, loadUserConfig, tokenKind, updateInstance, withoutTenantRef, withTenantRefs, } from "./user-config.js";
9
9
  import { cavelonCommand, fill } from "./printed.js";
10
10
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
11
11
  export function isUuid(value) {
@@ -97,6 +97,10 @@ export async function resolveSession(env, cwd, globals) {
97
97
  [session.tenant, session.tenantSource] = [envFile.tenant, `env/${envFile.name}.yaml`];
98
98
  else if (projectMatches && project?.tenant)
99
99
  [session.tenant, session.tenantSource] = [project.tenant, "cavelon.yaml"];
100
+ else if (globals.sessionTenants?.get(url)) {
101
+ session.sessionTenant = globals.sessionTenants.get(url);
102
+ [session.tenant, session.tenantSource] = [session.sessionTenant.ref, "session"];
103
+ }
100
104
  else if (settings.tenant)
101
105
  [session.tenant, session.tenantSource] = [settings.tenant, "use"];
102
106
  return session;
@@ -225,23 +229,47 @@ async function findTenant(client, ref) {
225
229
  }
226
230
  return { known: memberships };
227
231
  }
228
- export async function resolveTenantId(env, session, client) {
232
+ export function knownTenantId(session, now = new Date()) {
229
233
  if (!session.tenant || !session.url)
230
234
  return undefined;
231
235
  if (session.tokenKind === "api_key")
232
236
  return undefined;
233
237
  if (isUuid(session.tenant))
234
238
  return session.tenant;
235
- const cached = session.settings.tenant_ids?.[session.tenant];
236
- if (cached)
237
- return cached;
239
+ if (session.tenantSource === "session" && session.sessionTenant)
240
+ return session.sessionTenant.id;
238
241
  if (session.tenantSource === "use" && session.settings.tenant_id)
239
242
  return session.settings.tenant_id;
240
- const found = await lookupTenantId(client, session.tenant, session.tenantSource);
243
+ return cachedTenantRef(session.settings, session.tenant, session.token, now);
244
+ }
245
+ export async function resolveTenantId(env, session, client, now = new Date()) {
246
+ if (!session.tenant || !session.url)
247
+ return undefined;
248
+ if (session.tokenKind === "api_key")
249
+ return undefined;
250
+ const known = knownTenantId(session, now);
241
251
  const url = session.url;
242
252
  const slug = session.tenant;
243
- await updateInstance(env, url, (current) => ({ ...current, tenant_ids: { ...current.tenant_ids, [slug]: found.id } }));
244
- return found.id;
253
+ const fromCache = known !== undefined && !isUuid(slug) && session.tenantSource !== "use" && session.tenantSource !== "session";
254
+ const resolve = async () => {
255
+ const found = await lookupTenantId(client, slug, session.tenantSource);
256
+ if (client.target.token) {
257
+ const token = client.target.token;
258
+ await updateInstance(env, url, (current) => withTenantRefs(current, [slug], found.id, token, now));
259
+ }
260
+ return found.id;
261
+ };
262
+ if (!fromCache)
263
+ return known ?? resolve();
264
+ client.revalidateTenant = async () => {
265
+ await updateInstance(env, url, (current) => withoutTenantRef(current, slug));
266
+ const fresh = await resolve().catch(() => undefined);
267
+ if (!fresh || fresh === client.target.tenantId)
268
+ return false;
269
+ client.target.tenantId = fresh;
270
+ return true;
271
+ };
272
+ return known;
245
273
  }
246
274
  export async function reloadSettings(env, url) {
247
275
  return (await loadUserConfig(env)).instances[url] ?? {};
@@ -70,7 +70,8 @@ for a public widget), **propose the change; the person decides.**
70
70
  otherwise refuses naming the role and the Admin page; `--tenant <tenant>`
71
71
  then sets one tenant's own run cap. Without a `change` it cannot be changed
72
72
  at runtime. Tell the person who changes it and where, and design within it
73
- meanwhile; never ask for an operator's token.
73
+ meanwhile; never ask for an operator's token. A docs page marked "Platform
74
+ page" describes such an operator's task: this token can read it, not do it.
74
75
  - A rate limit only goes down to what the operator allows; above the ceiling
75
76
  (`maximum_setting`), it is the operator's too. That holds for the per-visitor
76
77
  limits (`rate_limit_chat_visitor_rpm`, `rate_limit_widget_visitor_rpm`) as
@@ -295,7 +296,15 @@ schema has them: `cavelon validate` reports an unknown section):
295
296
  - **Variables** are plain text that anyone who may view the tenant's settings
296
297
  reads. You may set one with `cavelon variables set <name> <value>` (the
297
298
  `variables_set` tool) when the value is not a credential and you know it;
298
- ask the person otherwise. `cavelon variables list` shows them.
299
+ ask the person otherwise. Setting one needs the permission a secret needs: a
300
+ Builder's role may not (`cavelon whoami` says "may set variables: no", and
301
+ `apply` says so under "needs variables"); then tell the person that a tenant
302
+ Owner sets it, in the Admin under Settings › Variables or with their own
303
+ token. `cavelon variables list` shows them. A variable
304
+ is tenant-wide: replacing a value previews the old and the new one and
305
+ changes nothing without `--confirm` (the `confirm_token` over MCP); every
306
+ solution of the tenant reads it, active ones too, so show the person that
307
+ preview and confirm only with their yes. A new variable is set at once.
299
308
  - **Secrets are set by a person, never by you.** Tell the person the exact
300
309
  command `apply` printed, `cavelon secrets set <name>` (with the `--env` and
301
310
  `--tenant` it printed), to run in their own terminal; it asks for the value
@@ -309,6 +318,74 @@ schema has them: `cavelon validate` reports an unknown section):
309
318
  Admin under Settings › Secrets or with their own token; do not suggest the
310
319
  command to someone whose role cannot run it.
311
320
 
321
+ ## Database query tools
322
+
323
+ A database query tool lets an agent answer from a customer's live database. A
324
+ saved, read-only query is one tool (`tool_type: database_query` in
325
+ `package/tools.yaml`); the model only calls it and fills the parameters it is
326
+ given, and never writes SQL. `cavelon schema tools.database_query` lists the
327
+ fields this instance takes; `cavelon docs get administration/database-connectors`
328
+ says who does what on the instance.
329
+
330
+ ```yaml
331
+ - slug: order_status # the function name the model calls: a-z, 0-9, - and _
332
+ name: Order status # the label in the Admin
333
+ description: Status and shipping date of one of the signed-in visitor's orders, by order number.
334
+ tool_type: database_query
335
+ scope: tenant_local
336
+ database_query:
337
+ connection: { name: shop-db, dialect: postgresql } # by name only: never a host, user or password
338
+ sql_text: SELECT number, status, shipped_at FROM orders WHERE number = :order_no AND email = :email LIMIT 5
339
+ parameters:
340
+ - name: order_no
341
+ type: string
342
+ description: Order number as printed on the confirmation, e.g. A-10023
343
+ pattern: "^[A-Z]-[0-9]{4,8}$"
344
+ max_length: 20
345
+ - name: email
346
+ source: end_user.email # filled by the instance from the signed-in visitor
347
+ type: string
348
+ max_rows: 5
349
+ allows_anonymous: false
350
+ ```
351
+
352
+ - **Who writes a query.** Only a superadmin of the instance creates or changes
353
+ a query, in the Admin; your token never does. The query's SQL, parameters,
354
+ limits and `allows_anonymous`, and the tool's own `slug`, `name` and
355
+ `description`, are all part of the query. `cavelon validate` warns
356
+ (`database_query_changed`) for each query tool that differs from the last
357
+ pull or apply, and the import preview blocks it
358
+ (`database_query_needs_superadmin`), which stops the whole apply. Propose a
359
+ query change to the person as a diff of `package/tools.yaml`; they hand it
360
+ to a superadmin, who imports the package in the Admin. What you may change
361
+ freely is how agents and skills use the tool: the assignment
362
+ (`tool_assignments` with `config_overrides` `name`, `description` or
363
+ `max_calls`) is no query change. `params_json_schema` and `default_config`
364
+ of a query tool are derived from the query, and the instance ignores the
365
+ package's (`database_query_fields_ignored`).
366
+ - **Identity parameters.** A parameter with `source: end_user.id`,
367
+ `end_user.external_subject` or `end_user.email` is filled by the instance
368
+ from the signed-in visitor's verified identity (an email only once
369
+ verified), never by the model: it is a required string without
370
+ constraints. Scope every query that returns a person's data by such a
371
+ parameter, so a visitor only reads their own rows. Without a signed-in
372
+ visitor the call answers `identity_required` and the query does not run.
373
+ - **`allows_anonymous`.** Set it to true only for public data (stock, prices,
374
+ opening hours) and only on a query without an identity parameter; the
375
+ instance refuses it otherwise (`anonymous_with_context_parameter`).
376
+ - **Safe query design.** One `SELECT` or `WITH` statement; select only the
377
+ columns the answer needs (never `SELECT *`); always bound the rows (`LIMIT`,
378
+ `TOP`, `FETCH FIRST`) and keep `max_rows` small; constrain every model
379
+ parameter (`pattern`, `max_length`, `enum`, `minimum`/`maximum`) and
380
+ describe it, since the model fills it from the conversation; where a lookup
381
+ has no identity parameter, ask for a second factor (an order number and its
382
+ postal code) rather than one guessable key. Each `:name` in the SQL needs
383
+ exactly one parameter of that name (a literal colon is `\:`); validate checks
384
+ this (`bind_mismatch`) and each parameter's type and constraints.
385
+ - `cavelon explain <code>` explains every code the connector uses: what
386
+ `validate` and the preview name, the codes of a failed call (`timeout`,
387
+ `identity_required`, …) and of a connection test.
388
+
312
389
  ## After each edit
313
390
 
314
391
  1. `cavelon validate` until it reports no errors (`--strict` before an apply
@@ -57,14 +57,20 @@ Do not work around it; use the other column.
57
57
  ## Run and follow
58
58
 
59
59
  ```bash
60
- cavelon loop start <trigger> --input @request.json # prints the run id and an operation id
60
+ cavelon loop start <trigger> --input @request.json # previews: the trigger, its solution, the payload
61
+ cavelon loop start <trigger> --input @request.json --confirm <token> # starts it: the run id and an operation id
61
62
  cavelon loop watch <run> --timeout 5m # each iteration's verdict, then the loop's outcome
62
63
  cavelon loop iterations <run> # state, budget, iterations (a page at a time)
63
64
  cavelon wait <operation-id> --timeout 90s # exit 0 done, 1 failed, 5 needs a person, 6 still running
64
65
  ```
65
66
 
66
67
  A loop started from `cavelon` runs **as the person whose token it is**, checked
67
- again on every iteration. If `loop start` exits 8 (a timeout, a cut
68
+ again on every iteration, and spends the tenant's budget. So `loop start`
69
+ previews first and starts nothing without `--confirm`: run the confirm command
70
+ it prints (from your shell it carries the preview's token; over MCP call
71
+ `loop_start` again with `confirm` set to its `confirm_token`). Confirm on your
72
+ own only for a trigger of a draft solution in a test environment; show the
73
+ person the preview of any other. If `loop start` exits 8 (a timeout, a cut
68
74
  connection), the run may have started: retry only with the
69
75
  `--idempotency-key <key>` its error names, never without it, or a second run
70
76
  starts and spends the budget again. `cavelon trace <operation-id>` reads the
@@ -18,7 +18,16 @@ use it when you parse the result.
18
18
  deactivate; whether it is ready to
19
19
  activate, its latest test run), the last pull and the open previews.
20
20
  `cavelon whoami` says who the token acts as, when it expires, whether it may
21
- enter Platform mode and which tenants it reaches.
21
+ enter Platform mode, which tenants it reaches, and what it may do there: its
22
+ permissions (an API key's scopes too), whether it may activate and set
23
+ variables, and the operations a person runs instead.
24
+ - **Offer only what the credential may do.** Over MCP, a tool whose
25
+ description starts with "Not for this credential" is one the instance says
26
+ this token or key may not use in this tenant; `api_list` marks such
27
+ operations (`may_send: false`). Do not call them to find out: tell the
28
+ person who does it (the description says who), as for a secret. Where the
29
+ instance does not say (an older one), try, and a refusal names what the
30
+ credential lacks.
22
31
  - **Never handle a token.** If a command exits 7 (not authorised) or says no
23
32
  token, ask the person to run `cavelon login --instance <url>` themselves (in a
24
33
  terminal, or with a `!` prefix where your client offers one). Never ask them
@@ -28,7 +37,11 @@ use it when you parse the result.
28
37
  their terminal, `cavelon secrets set <name>` (as `apply` prints it, with its
29
38
  `--env` and `--tenant`). Never ask for the value, never pipe or pass one yourself; there is
30
39
  no MCP tool for it. Plain-text variables you may set with `cavelon variables
31
- set <name> <value>` when the value is not a credential.
40
+ set <name> <value>` when the value is not a credential and your role may
41
+ manage the tenant's settings, as for a secret: a Builder's may not, and
42
+ `cavelon whoami` then says "may set variables: no". Then tell the person
43
+ that a tenant Owner sets it, in the Admin under Settings › Variables or with
44
+ their own token.
32
45
  - **Pass on an update warning.** The first MCP result of a session may warn
33
46
  that `cavelon`, the Cavelon plugin or this folder's skills are behind the
34
47
  latest release (`… is out; this is …`, `The Cavelon plugin is …`), with the
@@ -58,7 +71,13 @@ use it when you parse the result.
58
71
  pass `--tenant` (and `--instance`) to every command, `harness new` and
59
72
  `pull` included: without it a command acts in the tenant `cavelon use`
60
73
  chose, which may be another one. The commands `cavelon` prints carry the
61
- `--tenant` (and `--env`) you gave, confirm lines included; run them as printed. `apply` never creates a solution: when the one an env file names
74
+ `--tenant` (and `--env`) you gave, confirm lines included; run them as printed.
75
+ Every preview names where it acts (`acts on:`, `target` in `--json`): the
76
+ instance, the tenant and the mode; show it to the person with the change.
77
+ Over MCP, `use_tenant` chooses the tenant for this session only and never
78
+ changes the person's stored tenant. A tenant API key in `CAVELON_TOKEN` acts
79
+ only in its own tenant: a command that names another is refused with
80
+ `tenant_mismatch`; never work around it, tell the person which key fits. `apply` never creates a solution: when the one an env file names
62
81
  is missing it stops with `solution_not_found` and names that command. To start from a package file (a blueprint, an
63
82
  export from another instance), run
64
83
  `cavelon init --instance <url> --tenant <tenant> --from <file>` instead of
@@ -71,6 +90,18 @@ use it when you parse the result.
71
90
  In their own terminal, a plain `cavelon init` asks them. Ask for the instance
72
91
  URL if you do not know it.
73
92
 
93
+ - **Database connections are set up by a person.** A database query tool
94
+ needs a connection of the name and dialect its package names, tested
95
+ successfully, in every tenant it is applied to. A superadmin creates it in
96
+ the Admin (Settings › Security & access › Databases), and the tenant Owner tests it
97
+ (`cavelon db test <connection>`); you never handle its host, user or
98
+ password. Use the same connection name in every tenant and environment
99
+ (`env/test.yaml`, `env/prod.yaml`), each pointing at that environment's
100
+ database, so one package serves them all. `cavelon db connections` shows
101
+ which exist and whether their last test passed. A pull writes each query's
102
+ SQL into `package/tools.yaml`, so the repository holds it: review it like
103
+ code.
104
+
74
105
  ## The loop
75
106
 
76
107
  1. **Pull** what is live: `cavelon pull`. It refuses when `package/` has
@@ -119,6 +150,13 @@ use it when you parse the result.
119
150
  code, package file and path, and hint; `cavelon explain <code>` says more.
120
151
  A preview that changes nothing says "Nothing to import" and stores no
121
152
  preview: there is nothing to confirm.
153
+ **A database query your package creates or changes stops the whole
154
+ apply** (`database_query_needs_superadmin`): only a superadmin writes a
155
+ query, in the Admin, and `apply` says so before it sends. Tell the person;
156
+ to apply the other changes now, leave the query as the instance holds it
157
+ (restore the tool's entry as the last pull wrote it, or remove its
158
+ `database_query` block) and preview again. Once a superadmin has imported
159
+ the package in the Admin, `apply` passes while the queries match.
122
160
  5. **Confirm** exactly that preview: `cavelon apply --confirm <preview-id>`
123
161
  (the line `apply` printed, with the same `--env` and `--tenant`). Exit 4
124
162
  means the preview is stale and nothing was imported: the target changed on
@@ -164,7 +202,8 @@ use it when you parse the result.
164
202
  were put on the VM (customer VM).
165
203
  7. **Test**: `cavelon test run --suite <suite>`, then `cavelon wait <operation>`.
166
204
  See the cavelon-testing skill. A solution with a Masterloop node is run with
167
- `cavelon loop start <trigger>` and followed with `cavelon loop watch <run>`;
205
+ `cavelon loop start <trigger>` (it previews; run the confirm command it
206
+ prints) and followed with `cavelon loop watch <run>`;
168
207
  see the cavelon-long-running skill.
169
208
  8. **Fix** what the results and traces show, and go back to step 2. Commit
170
209
  when a step works.
@@ -221,13 +260,23 @@ only show what would happen. Show it to the person before `cavelon trigger
221
260
  identity <trigger> <key> --confirm` (it gives a trigger standing authority),
222
261
  before `cavelon harness default … --confirm`, `cavelon activate
223
262
  --make-default --confirm` or `cavelon deactivate --confirm` (they move live
224
- traffic), and
263
+ traffic), before `cavelon activate --confirm` of a solution its preview says a
264
+ channel or trigger reaches (it goes live for them at once), before
265
+ `cavelon tenant create … --confirm` (a new tenant on the platform) and
266
+ `cavelon variables set … --confirm` that replaces a value (every solution of
267
+ the tenant reads it, active ones too), and
225
268
  before `cavelon sandbox seed … --confirm` or `cavelon loop cancel … --confirm` on
226
- anything but a test Sandbox or a run you started yourself.
269
+ anything but a test Sandbox or a run you started yourself. `cavelon loop start
270
+ <trigger>` previews too, because a run acts as the person and spends budget:
271
+ confirm it on your own only for a trigger of a draft solution in a test
272
+ environment, and show the person every other one. A new variable, and a draft
273
+ solution no channel or trigger reaches, need no confirm.
227
274
 
228
- **Over MCP, confirm with the preview's token.** `api`, `limits_set`,
275
+ **Over MCP, confirm with the preview's token.** `api`, `tenant_create`,
276
+ `variables_set` where it replaces a value, `loop_start`, `limits_set`,
229
277
  `models_set_limit`, `loop_cancel`, `sandbox_seed`, `trigger_identity`,
230
- `harness_default`, `deactivate`, `activate` with `make_default`, and
278
+ `harness_default`, `deactivate`, `activate` of a solution a channel or
279
+ trigger reaches or with `make_default`, and
231
280
  `kb_upload` where it would deactivate documents return a `confirm_token` with
232
281
  their preview. Show
233
282
  the preview, then call the tool again with the same arguments and `confirm`
@@ -242,9 +291,11 @@ make the call as written, filling a value in angle brackets (a
242
291
  `confirm_token` comes from that tool's preview).
243
292
 
244
293
  **From your shell, `--confirm` takes the same token.** Run by a coding agent,
294
+ `tenant create`, `variables set` (replacing a value), `loop start`,
245
295
  `limits set`, `models set-limit`, `loop cancel`, `sandbox seed`,
246
- `trigger identity`, `harness default`, `activate --make-default`,
247
- `deactivate`, `kb upload --replace`, `variables delete` and `secrets delete`
296
+ `trigger identity`, `harness default`, `activate` (of a solution a channel or
297
+ trigger reaches, or with `--make-default`),
298
+ `deactivate`, `kb upload --replace` and `variables delete`
248
299
  print their preview with a confirm token and the command that confirms it
249
300
  (`… --confirm <token>`). Show the preview, then run exactly that command. A
250
301
  bare `--confirm`, as the docs show it for a person's terminal, changes nothing
@@ -254,9 +305,7 @@ preview. A line printed before its preview exists ends in
254
305
  `--confirm` first for the preview and its token.
255
306
 
256
307
  **`cavelon api` from your shell has the guards of the MCP `api` tool**, since
257
- `cavelon` sees that a coding agent runs it (`CLAUDECODE`, `CODEX_THREAD_ID`, `CODEX_SANDBOX`,
258
- `CURSOR_AGENT`, `GEMINI_CLI`, `COPILOT_CLI`, `COPILOT_AGENT`, `AI_AGENT` or
259
- `CAVELON_AGENT=1`):
308
+ `cavelon` sees that a coding agent runs it:
260
309
 
261
310
  - For an operation that is not read-only, it prints the request and a confirm
262
311
  token and sends nothing. Show the request to the person when the rules above
@@ -269,10 +318,14 @@ preview. A line printed before its preview exists ends in
269
318
  both marks up front.
270
319
  Tell the person what the error's hint says; for a secret field, send the rest
271
320
  without it and let the person enter the value (`cavelon secrets set <name>`
272
- or the Admin). Never work around a refusal, by unsetting the variable or by
273
- any other way.
321
+ or the Admin). Never work around a refusal in any way.
274
322
  - Its `@file` body, `--file` and `--output` stay inside the solution folder.
275
323
 
324
+ `cavelon secrets set` and `cavelon secrets delete` are refused from your shell
325
+ (`operation_for_a_person`, exit 5), with or without `--confirm`, before a value
326
+ is read or anything is sent: give the person the command from the error's hint
327
+ to run in their own terminal.
328
+
276
329
  `activate` goes through the readiness gate only, and only with a token that
277
330
  may activate. It never forces: activating without the evidence stays a person's
278
331
  decision in the Admin, so do not ask for it as a shortcut.
@@ -329,7 +382,9 @@ preview · 5 needs a person · 6 timed out (still running) · 7 not authorised
329
382
  - `cavelon docs search <query>` and `cavelon docs get <page>`: the instance's
330
383
  own docs, for its version. They are in English; a German question works for
331
384
  the core concepts, English words for the rest. `cavelon docs get index`
332
- lists every page.
385
+ lists every page. A page marked "Platform page" (`mark` in `--json`)
386
+ describes an operator's actions this token cannot take: tell the person who
387
+ can, never ask for a Platform-mode token.
333
388
  - `.cavelon/inventory.md`: the tenant's solutions, knowledge bases, tools,
334
389
  skills, models, test suites and sandboxes from the last pull; `cavelon sandbox list` for their
335
390
  current state and mode.
@@ -133,6 +133,30 @@ no verdict; `cavelon explain <status>` says what it means and what to do next:
133
133
  The case's own reason (which knowledge base, which value) is in the output of
134
134
  `test run --wait`, `wait` and `cavelon trace <run>`.
135
135
 
136
+ ## Database query tools
137
+
138
+ Test a solution with database query tools against a test database, never the
139
+ customer's live one: the test tenant (`--env test`) has a connection of the
140
+ same name pointing at a test database with known rows, set up by a person in
141
+ the Admin. Then:
142
+
143
+ - A step can assert the agent calls the query (`tool_called` with the tool's
144
+ slug), and the judge checks the answer against the known rows.
145
+ - A test run has no signed-in visitor. A query with an identity parameter
146
+ (`end_user.*`), or one without `allows_anonymous`, answers
147
+ `identity_required` there and runs nothing: such a step checks that the
148
+ agent asks the visitor to sign in, not the rows. The instance does not yet
149
+ let a suite name a test Chat User whose identity its queries use (a suite's
150
+ `as_chat_user` reader reads knowledge as that person, nothing more).
151
+ - To check what an identity-scoped query returns for one customer, the tenant
152
+ Owner runs it once with `cavelon db test-run <query> --value <name>=<value>`,
153
+ identity parameters included; it shows what the model would see. Never put
154
+ a real customer's data into a test file.
155
+ - `cavelon db runs <query>` lists each run's outcome and error code (never a
156
+ value or a row), and `cavelon trace` shows the code a failed call answered
157
+ the model with on the tool's span (`error_code`); `cavelon explain <code>`
158
+ says how to fix it.
159
+
136
160
  ## Reading what happened
137
161
 
138
162
  ```bash
@@ -228,4 +252,7 @@ the body does the same, but needs the id and a confirm. `cavelon deactivate
228
252
  previews first and is the person's decision, so show the preview and confirm
229
253
  only with their yes. When every suite passes,
230
254
  `cavelon activate --harness <name or slug>` goes through the readiness gate; if the
231
- token may not activate, a person activates in the Admin.
255
+ token may not activate, a person activates in the Admin. A solution that a
256
+ channel or an active trigger reaches goes live for them at once, so its
257
+ activation previews first and needs the confirm it prints: show it to the
258
+ person and confirm only with their yes.
@@ -1,3 +1,4 @@
1
+ import { QUERY_TOOL_TYPE } from "./database-queries.js";
1
2
  import { clip } from "./format.js";
2
3
  const REASONING_CHARS = 300;
3
4
  const VALUE_CHARS = 120;
@@ -121,6 +122,15 @@ export function retrievalRows(view) {
121
122
  document_id: h.document_id,
122
123
  }));
123
124
  }
125
+ export function queryErrorCode(s) {
126
+ if (s.tool_type !== QUERY_TOOL_TYPE)
127
+ return null;
128
+ const output = spanAttributes(s.output_json);
129
+ const preview = typeof output?.output_preview === "string" ? output.output_preview : typeof s.output_json === "string" ? s.output_json : undefined;
130
+ const answer = (preview !== undefined ? spanAttributes(preview) : undefined) ?? output;
131
+ const code = answer?.error;
132
+ return typeof code === "string" && /^[a-z][a-z0-9_]{0,63}$/.test(code) ? code : null;
133
+ }
124
134
  export function suggestedSpan(spans) {
125
135
  const inOrder = spans.slice().sort((a, b) => (a.sequence ?? 0) - (b.sequence ?? 0));
126
136
  const last = (pick) => inOrder.filter(pick).pop();
@@ -2,7 +2,7 @@ import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { SKILL_ROOTS } from "./agents.js";
4
4
  import { currentInstall, NPM_PACKAGE, REPOSITORY } from "./install.js";
5
- import { readJsonFile, readTextFile, writeFileAtomic } from "./fsutil.js";
5
+ import { readJsonFile, readTextFile, writePrivateFile } from "./fsutil.js";
6
6
  import { isGenerated } from "./markers.js";
7
7
  import { cacheDir } from "./paths.js";
8
8
  import { findProject } from "./project.js";
@@ -71,7 +71,7 @@ async function withState(io, source, version, fetchImpl, use) {
71
71
  }
72
72
  const result = use(state, now);
73
73
  if (JSON.stringify(state) !== before)
74
- await writeFileAtomic(file, `${JSON.stringify(state, null, 2)}\n`, 0o600, 0o700);
74
+ await writePrivateFile(cacheDir(io.env), file, `${JSON.stringify(state, null, 2)}\n`);
75
75
  return result;
76
76
  }
77
77
  function within(stamp, now) {
@@ -1,6 +1,30 @@
1
+ import { createHash } from "node:crypto";
1
2
  import path from "node:path";
2
3
  import { configDir } from "./paths.js";
3
4
  import { readJsonFile, writeFileAtomic } from "./fsutil.js";
5
+ export const TENANT_REF_TTL_MS = 24 * 60 * 60 * 1000;
6
+ export function credentialFingerprint(token) {
7
+ return createHash("sha256").update(token).digest("hex").slice(0, 16);
8
+ }
9
+ export function cachedTenantRef(settings, ref, token, now) {
10
+ const entry = settings.tenant_refs?.[ref];
11
+ if (!entry || !token || entry.credential !== credentialFingerprint(token))
12
+ return undefined;
13
+ const age = now.getTime() - new Date(entry.resolved_at).getTime();
14
+ return age >= 0 && age < TENANT_REF_TTL_MS ? entry.id : undefined;
15
+ }
16
+ export function withTenantRefs(settings, refs, id, token, now) {
17
+ const credential = credentialFingerprint(token);
18
+ const kept = Object.entries(settings.tenant_refs ?? {}).filter(([, e]) => now.getTime() - new Date(e.resolved_at).getTime() < TENANT_REF_TTL_MS);
19
+ const added = refs.filter((r) => Boolean(r) && !isUuidLike(r)).map((r) => [r, { id, credential, resolved_at: now.toISOString() }]);
20
+ const { tenant_ids: _old, ...rest } = settings;
21
+ return { ...rest, tenant_refs: Object.fromEntries([...kept, ...added]) };
22
+ }
23
+ export function withoutTenantRef(settings, ref) {
24
+ const { [ref]: _gone, ...others } = settings.tenant_refs ?? {};
25
+ return { ...settings, tenant_refs: others };
26
+ }
27
+ const isUuidLike = (value) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value);
4
28
  export function userConfigPath(env) {
5
29
  return path.join(configDir(env), "config.json");
6
30
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cavelon/cli",
3
- "version": "0.1.10",
3
+ "version": "0.1.11",
4
4
  "description": "The cavelon binary: CLI and local MCP server for building Cavelon solutions with a coding agent.",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://github.com/goodguys-gmbh/cavelon-dev-kit",