@cavelon/cli 0.1.8 → 0.1.10

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 (53) hide show
  1. package/dist/branches.js +4 -3
  2. package/dist/capacity.js +3 -2
  3. package/dist/code-hints.js +5 -4
  4. package/dist/command.js +6 -0
  5. package/dist/commands/api.js +3 -3
  6. package/dist/commands/async.js +7 -4
  7. package/dist/commands/chat.js +10 -12
  8. package/dist/commands/docs.js +5 -3
  9. package/dist/commands/fmt.js +6 -4
  10. package/dist/commands/index.js +2 -0
  11. package/dist/commands/init.js +106 -28
  12. package/dist/commands/limits-set.js +8 -9
  13. package/dist/commands/limits.js +4 -3
  14. package/dist/commands/loops.js +15 -14
  15. package/dist/commands/models.js +10 -12
  16. package/dist/commands/sandboxes.js +15 -14
  17. package/dist/commands/schema.js +6 -5
  18. package/dist/commands/session.js +27 -15
  19. package/dist/commands/setup.js +4 -2
  20. package/dist/commands/solution.js +152 -68
  21. package/dist/commands/tenants.js +14 -14
  22. package/dist/commands/values.js +62 -38
  23. package/dist/commands/work.js +18 -12
  24. package/dist/confirm-token.js +3 -1
  25. package/dist/contracts.js +2 -1
  26. package/dist/default-route.js +1 -1
  27. package/dist/features.js +2 -1
  28. package/dist/harness-ref.js +6 -4
  29. package/dist/http.js +4 -3
  30. package/dist/invoke.js +3 -2
  31. package/dist/kit-codes.js +9 -2
  32. package/dist/limits.js +1 -1
  33. package/dist/main.js +13 -1
  34. package/dist/mcp.js +65 -32
  35. package/dist/openapi.js +5 -2
  36. package/dist/operations.js +3 -2
  37. package/dist/package-check.js +10 -4
  38. package/dist/package-files.js +5 -1
  39. package/dist/package-format.js +10 -0
  40. package/dist/preview-report.js +44 -5
  41. package/dist/printed.js +182 -0
  42. package/dist/project.js +2 -1
  43. package/dist/results.js +1 -1
  44. package/dist/secret-access.js +30 -0
  45. package/dist/session.js +3 -11
  46. package/dist/shell.js +0 -3
  47. package/dist/skills/cavelon-authoring/SKILL.md +9 -2
  48. package/dist/skills/cavelon-long-running/SKILL.md +1 -1
  49. package/dist/skills/cavelon-loop/SKILL.md +16 -4
  50. package/dist/tenant-choice.js +7 -7
  51. package/dist/trace-view.js +1 -1
  52. package/dist/update-check.js +156 -10
  53. package/package.json +1 -1
package/dist/mcp.js CHANGED
@@ -1,10 +1,12 @@
1
1
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
2
  import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
3
- import { formerlyWarning } from "./command.js";
3
+ import { formerlyWarning, ownsTenant, propertyName } from "./command.js";
4
4
  import { MCP_MAX_WAIT_MS } from "./commands/async.js";
5
5
  import { createContext, withWarnings } from "./context.js";
6
6
  import { asCavelonError, CavelonError, ExitCode, usageError } from "./errors.js";
7
7
  import { closest } from "./package-references.js";
8
+ import { printingFor, spoken, spokenError, spokenHints } from "./printed.js";
9
+ import { startSessionUpdateCheck } from "./update-check.js";
8
10
  import { KIT_VERSION } from "./version.js";
9
11
  const INSTRUCTIONS = "Tools for one Cavelon instance, acting with the token a person stored with `cavelon login` " +
10
12
  "(or CAVELON_TOKEN). You never see or pass the token. Tools that start work (kb_upload, test_run, " +
@@ -29,7 +31,7 @@ const INSTRUCTIONS = "Tools for one Cavelon instance, acting with the token a pe
29
31
  "(x-cavelon-person-only; its reason is in the error), or on an instance that marks none, one that changes a secret, " +
30
32
  "creates or revokes a credential (tokens, API keys, sign-in) or decides an approval; it also refuses a body that sets a field " +
31
33
  "the instance marks as a secret value (x-cavelon-secret): leave the field out and let a person enter the value. " +
32
- "`cavelon api` run from your shell applies the same guards, and sends a changing operation only with --confirm and the token " +
34
+ "Run from your shell, cavelon's api command applies the same guards, and sends a changing operation only with --confirm and the token " +
33
35
  "its preview printed. Tools read and write files only " +
34
36
  "inside the solution folder (the folder of cavelon.yaml, or the one the server started in), never in cavelon's own " +
35
37
  "config or cache directory. Read limits before planning a solution: it lists what the " +
@@ -40,49 +42,62 @@ const INSTRUCTIONS = "Tools for one Cavelon instance, acting with the token a pe
40
42
  "values are set, never a value: a person sets a secret, so tell them the exact `cavelon secrets set <name>` command " +
41
43
  "to run in their terminal, and never ask for, read or pass a secret value. Never approve or decide an approval; " +
42
44
  "that stays with a person. Use docs_search before guessing, " +
43
- "and api_list/api_describe/api for anything without its own tool.";
45
+ "and api_list/api_describe/api for anything without its own tool. " +
46
+ "The first result of a session may carry a warning that cavelon, the Cavelon plugin or this folder's skills are behind " +
47
+ "the latest release, with the commands that update them: pass it on to the person, who runs them; do not run them yourself.";
48
+ export function mcpInstructions(commands) {
49
+ return printingFor({ mode: "mcp", commands }, () => spoken(INSTRUCTIONS));
50
+ }
44
51
  const TOKEN_DESCRIPTION = "Over MCP: the confirm_token this tool's preview returned, which confirms exactly the change it showed; true is refused.";
45
52
  export function toolName(spec) {
46
53
  return spec.mcpTool || undefined;
47
54
  }
48
- function ownsTenant(spec) {
49
- return Boolean(spec.positionals?.some((p) => p.name === "tenant") || spec.options?.tenant);
50
- }
51
- export function propertyName(name) {
52
- return name.replaceAll("-", "_");
55
+ export { propertyName };
56
+ export function mcpSpelling(text, spec, commands = []) {
57
+ const own = new Set(Object.entries(spec.options ?? {}).filter(([, o]) => !o.cliOnly).map(([name]) => name));
58
+ if (!ownsTenant(spec))
59
+ own.add("tenant");
60
+ return text
61
+ .replace(/`cavelon ([a-z][a-z -]*[a-z])`/g, (whole, words) => {
62
+ const tool = commands.find((c) => c.name === words)?.mcpTool;
63
+ return tool ? `\`${tool}\`` : whole;
64
+ })
65
+ .replace(/--([a-z][a-z0-9-]*)/g, (whole, name) => (own.has(name) ? propertyName(name) : whole));
53
66
  }
54
- export function inputSchema(spec) {
67
+ export function inputSchema(spec, commands = []) {
55
68
  const properties = {};
56
69
  const required = [];
70
+ const said = (text) => mcpSpelling(text, spec, commands);
57
71
  for (const p of spec.positionals ?? []) {
58
72
  properties[propertyName(p.name)] = p.variadic
59
- ? { type: "array", items: { type: "string" }, description: p.description }
60
- : { type: "string", description: p.description };
73
+ ? { type: "array", items: { type: "string" }, description: said(p.description) }
74
+ : { type: "string", description: said(p.description) };
61
75
  if (p.required)
62
76
  required.push(propertyName(p.name));
63
77
  }
64
78
  for (const [name, option] of Object.entries(spec.options ?? {})) {
65
79
  if (option.cliOnly)
66
80
  continue;
81
+ const description = said(option.mcpDescription ?? option.description);
67
82
  properties[propertyName(name)] = option.mcpToken
68
- ? { type: "string", description: `${option.description} ${TOKEN_DESCRIPTION}` }
83
+ ? { type: "string", description: `${description} ${TOKEN_DESCRIPTION}` }
69
84
  : option.type === "boolean"
70
- ? { type: "boolean", description: option.description }
85
+ ? { type: "boolean", description }
71
86
  : option.multiple
72
- ? { type: "array", items: { type: "string" }, description: option.description }
73
- : { type: ["string", "number"], description: option.description };
87
+ ? { type: "array", items: { type: "string" }, description }
88
+ : { type: ["string", "number"], description };
74
89
  }
75
90
  if (!ownsTenant(spec)) {
76
91
  properties.tenant = { type: "string", description: "Tenant slug or id, when not the one chosen for this directory." };
77
92
  }
78
93
  return { type: "object", properties, ...(required.length ? { required } : {}), additionalProperties: false };
79
94
  }
80
- export function toolFor(spec) {
95
+ export function toolFor(spec, commands = []) {
81
96
  const marked = spec.mcpEffect ?? (spec.readOnly ? "Read-only." : spec.destructive ? "Changes the instance; may delete or overwrite." : "Changes the instance.");
82
97
  return {
83
98
  name: toolName(spec),
84
- description: [spec.summary, spec.description, marked].filter(Boolean).join("\n"),
85
- inputSchema: inputSchema(spec),
99
+ description: mcpSpelling([spec.summary, spec.description, marked].filter(Boolean).join("\n"), spec, commands),
100
+ inputSchema: inputSchema(spec, commands),
86
101
  annotations: {
87
102
  title: spec.summary,
88
103
  readOnlyHint: spec.readOnly,
@@ -155,20 +170,17 @@ function missingRequired(spec, args) {
155
170
  function mcpIo(io) {
156
171
  return { ...io, stdout: { write: () => true, isTTY: false } };
157
172
  }
158
- export function createMcpServer(io, commands) {
173
+ export function createMcpServer(io, commands, updates = {}) {
159
174
  const tools = commands.filter((c) => c.mcpTool);
160
175
  const byName = new Map(tools.map((c) => [toolName(c), c]));
161
- const server = new Server({ name: "cavelon", version: KIT_VERSION }, { capabilities: { tools: {} }, instructions: INSTRUCTIONS });
162
- server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: tools.map(toolFor) }));
163
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
164
- const spec = byName.get(request.params.name);
165
- const given = (request.params.arguments ?? {});
166
- const fail = (error) => ({
167
- isError: true,
168
- content: [{ type: "text", text: JSON.stringify({ error: asCavelonError(error).toJSON() }) }],
169
- });
176
+ const server = new Server({ name: "cavelon", version: KIT_VERSION }, { capabilities: { tools: {} }, instructions: mcpInstructions(commands) });
177
+ const notice = startSessionUpdateCheck(io, updates);
178
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: tools.map((t) => toolFor(t, commands)) }));
179
+ async function call(name, given) {
180
+ const spec = byName.get(name);
181
+ const fail = (error) => ({ isError: true, body: { error: asCavelonError(error).toJSON() } });
170
182
  if (!spec)
171
- return fail(new Error(`Unknown tool ${request.params.name}.`));
183
+ return fail(new Error(`Unknown tool ${name}.`));
172
184
  const renamed = [];
173
185
  let args;
174
186
  try {
@@ -187,18 +199,39 @@ export function createMcpServer(io, commands) {
187
199
  for (const message of renamed)
188
200
  ctx.warn(message);
189
201
  try {
190
- const result = await spec.run(ctx, inputFrom(spec, args));
202
+ const { result, warnings } = await printingFor({ mode: "mcp", commands, ...(spec.storesTarget ? {} : { tenant, env: solutionEnv }) }, async () => {
203
+ try {
204
+ const done = await spec.run(ctx, inputFrom(spec, args));
205
+ return { result: { ...done, data: spokenHints(done.data) }, warnings: ctx.warnings.map(spoken) };
206
+ }
207
+ catch (error) {
208
+ throw spokenError(error);
209
+ }
210
+ });
191
211
  let data = result.data;
192
212
  if (data && typeof data === "object" && !Array.isArray(data)) {
193
- data = ctx.warnings.length ? withWarnings(data, ctx.warnings) : { ...data };
213
+ data = warnings.length ? withWarnings(data, warnings) : { ...data };
194
214
  if (result.exitCode)
195
215
  data.exit_code = result.exitCode;
196
216
  }
197
- return { content: [{ type: "text", text: JSON.stringify(data ?? null) }] };
217
+ return { body: data ?? null };
198
218
  }
199
219
  catch (error) {
200
220
  return fail(error);
201
221
  }
222
+ }
223
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
224
+ const warning = notice.forCall(() => server.getClientVersion()?.name);
225
+ const { body, isError } = await call(request.params.name, (request.params.arguments ?? {}));
226
+ let out = body;
227
+ const text = await warning;
228
+ if (text) {
229
+ if (out && typeof out === "object" && !Array.isArray(out))
230
+ out = withWarnings(out, [text]);
231
+ else
232
+ notice.keep();
233
+ }
234
+ return { ...(isError ? { isError } : {}), content: [{ type: "text", text: JSON.stringify(out) }] };
202
235
  });
203
236
  return server;
204
237
  }
package/dist/openapi.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { Ajv2020 } from "ajv/dist/2020.js";
2
2
  import addFormatsModule from "ajv-formats";
3
3
  import { CavelonError, ExitCode, validationError } from "./errors.js";
4
+ import { cavelonCommand, fill } from "./printed.js";
4
5
  const METHODS = ["get", "put", "post", "delete", "patch", "head", "options"];
5
6
  export function aliasOf(operationId, path, method) {
6
7
  const suffix = `${path.replace(/\W/g, "_")}_${method.toLowerCase()}`;
@@ -97,7 +98,9 @@ export function findOperation(doc, name) {
97
98
  throw new CavelonError(ExitCode.usage, {
98
99
  code: "operation_not_found",
99
100
  message: `This instance publishes no operation "${name}".`,
100
- hint: similar.length ? `Did you mean: ${similar.join(", ")}? (\`cavelon api list --search <text>\`)` : "Find it with `cavelon api list --search <text>`.",
101
+ hint: similar.length
102
+ ? `Did you mean: ${similar.join(", ")}? (\`${cavelonCommand("api", "list", "--search", fill("text"))}\`)`
103
+ : `Find it with \`${cavelonCommand("api", "list", "--search", fill("text"))}\`.`,
101
104
  });
102
105
  }
103
106
  function looseName(name) {
@@ -187,7 +190,7 @@ export function validateBody(doc, op, body) {
187
190
  return;
188
191
  const errors = schemaErrors(doc, schema, body);
189
192
  if (errors.length) {
190
- throw validationError(`The body does not match ${op.alias}'s schema: ${errors.join("; ")}`, errors, `See \`cavelon api describe ${op.alias}\`.`);
193
+ throw validationError(`The body does not match ${op.alias}'s schema: ${errors.join("; ")}`, errors, `See \`${cavelonCommand("api", "describe", op.alias)}\`.`);
191
194
  }
192
195
  }
193
196
  export function secretFields(doc, schema, body) {
@@ -1,4 +1,5 @@
1
1
  import { CavelonError, ExitCode } from "./errors.js";
2
+ import { cavelonCommand } from "./printed.js";
2
3
  import { failureLines } from "./results.js";
3
4
  export const TERMINAL = new Set(["succeeded", "failed", "cancelled"]);
4
5
  export function isSettled(op) {
@@ -44,7 +45,7 @@ export async function getOperation(client, id, signal) {
44
45
  throw new CavelonError(ExitCode.usage, {
45
46
  code: "not_an_operation_id",
46
47
  message: `"${id}" is not an operation id (they start with op_).`,
47
- hint: "Commands that start work print the operation id; `cavelon status` lists running ones.",
48
+ hint: `Commands that start work print the operation id; \`${cavelonCommand("status")}\` lists running ones.`,
48
49
  });
49
50
  }
50
51
  const probe = await client.get("/api/v1/operations", { query: { limit: 1 }, allow: [404] });
@@ -54,7 +55,7 @@ export async function getOperation(client, id, signal) {
54
55
  code: "operation_not_found",
55
56
  status: 404,
56
57
  message: `No operation ${id} in this tenant.`,
57
- hint: "Operation ids are per tenant; check `cavelon whoami`.",
58
+ hint: `Operation ids are per tenant; check \`${cavelonCommand("whoami")}\`.`,
58
59
  });
59
60
  }
60
61
  throw error;
@@ -1,8 +1,9 @@
1
1
  import { Ajv2020 } from "ajv/dist/2020.js";
2
2
  import { BRANCH_WIDTH_KEY, branchConcurrency, offText } from "./branches.js";
3
3
  import { locate, schemaSections, tenantWideSections } from "./package-files.js";
4
- import { PERSONA_SECTION, sectionFields } from "./package-format.js";
4
+ import { MANIFEST_SECTION, PERSONA_SECTION, sectionFields } from "./package-format.js";
5
5
  import { kitErrorEntry } from "./kit-codes.js";
6
+ import { cavelonCommand, fill, folderCommand } from "./printed.js";
6
7
  import { branches, checkModels, checkReferences, checkUnknownFields, closest, DUPLICATE_CODE, FIELD_UNKNOWN_CODE, MODEL_UNKNOWN_CODE, REFERENCE_MISSING_CODE, REFERENCE_UNKNOWN_CODE, KNOWLEDGE_TOOL_KEYS, } from "./package-references.js";
7
8
  export const SCHEMA_CODE = "package_schema_invalid";
8
9
  const ENDPOINT_LIMIT_CODE = "model_endpoint_limit_without_base_url";
@@ -305,7 +306,8 @@ export function checkPackage(disk, options) {
305
306
  if (seen.has(key))
306
307
  continue;
307
308
  seen.add(key);
308
- findings.push({ code: SCHEMA_CODE, severity: "error", ...locate(disk, pointer), message, hint: schemaHint(disk.package, pointer) });
309
+ const manifest = error.keyword === "required" && pointer === "" && error.params.missingProperty === MANIFEST_SECTION;
310
+ findings.push({ code: SCHEMA_CODE, severity: "error", ...locate(disk, pointer), message, hint: manifest ? manifestHint() : schemaHint(disk.package, pointer) });
309
311
  }
310
312
  }
311
313
  findings.push(...checkEndpointLimits(disk, options.schema));
@@ -592,11 +594,15 @@ export function schemaPathOf(pkg, pointer) {
592
594
  }
593
595
  return names.join(".");
594
596
  }
597
+ function manifestHint() {
598
+ return (`\`${folderCommand("pull")}\` writes the instance's manifest (the package format and the tenant the package is for); for a solution not on the instance ` +
599
+ `yet, run \`${folderCommand("init")}\` again in this folder: it writes a minimal one.`);
600
+ }
595
601
  function schemaHint(pkg, pointer) {
596
602
  const at = schemaPathOf(pkg, pointer);
597
603
  return at
598
- ? `Fix the field the finding names; \`cavelon schema ${at}\` lists the fields there (type, required, allowed values) with a minimal entry.`
599
- : "Fix the field the finding names; `cavelon schema` lists the sections, and `cavelon schema <section>` their fields.";
604
+ ? `Fix the field the finding names; \`${cavelonCommand("schema", at)}\` lists the fields there (type, required, allowed values) with a minimal entry.`
605
+ : `Fix the field the finding names; \`${cavelonCommand("schema")}\` lists the sections, and \`${cavelonCommand("schema", fill("section"))}\` their fields.`;
600
606
  }
601
607
  const propertiesIn = (node) => asObject(node.properties);
602
608
  function listedValues(schema, node) {
@@ -3,7 +3,7 @@ import path from "node:path";
3
3
  import { CST, LineCounter, Parser, parseDocument } from "yaml";
4
4
  import { CavelonError, ExitCode } from "./errors.js";
5
5
  import { readTextFile, withoutBom, writeFileAtomic } from "./fsutil.js";
6
- import { canonical, PERSONA_SECTION, sameEntry, sameSectionValue, sectionContent, sectionFields, toYaml } from "./package-format.js";
6
+ import { canonical, MANIFEST_SECTION, PERSONA_SECTION, sameEntry, sameSectionValue, sectionContent, sectionFields, toYaml } from "./package-format.js";
7
7
  export { canonical, toYaml };
8
8
  export const DEFAULT_LAYOUT = { package: "package", items: {} };
9
9
  const PACKAGE_FILE = /\.(ya?ml|json)$/i;
@@ -183,6 +183,10 @@ export async function readPackage(root, layout) {
183
183
  sources[section] = parsed.source;
184
184
  if (!parsed.finding && section === PERSONA_SECTION && (parsed.value === null || parsed.value === undefined))
185
185
  continue;
186
+ if (!parsed.finding && section === MANIFEST_SECTION) {
187
+ pkg[section] = parsed.value;
188
+ continue;
189
+ }
186
190
  empty = false;
187
191
  if (parsed.finding) {
188
192
  findings.push(parsed.finding);
@@ -1,5 +1,6 @@
1
1
  import { stringify } from "yaml";
2
2
  export const PERSONA_SECTION = "persona";
3
+ export const MANIFEST_SECTION = "manifest";
3
4
  export function toYaml(value) {
4
5
  return stringify(value, { lineWidth: 0, aliasDuplicateObjects: false });
5
6
  }
@@ -59,6 +60,15 @@ export function sectionFields(schema, section) {
59
60
  return undefined;
60
61
  return Object.fromEntries(Object.entries(props).map(([k, v]) => [k, resolve(schema, v) ?? {}]));
61
62
  }
63
+ export function requiredFields(schema, section) {
64
+ if (!schema)
65
+ return undefined;
66
+ const node = resolve(schema, schema.properties?.[section]);
67
+ const object = node ? branches(schema, node).find((b) => propertiesOf(b)) : undefined;
68
+ if (!object)
69
+ return undefined;
70
+ return Array.isArray(object.required) ? object.required.filter((k) => typeof k === "string") : [];
71
+ }
62
72
  export function canonical(value) {
63
73
  return JSON.stringify(value, (_key, v) => {
64
74
  if (v && typeof v === "object" && !Array.isArray(v)) {
@@ -1,6 +1,6 @@
1
1
  import { clip } from "./format.js";
2
2
  import { locate } from "./package-files.js";
3
- import { cavelonCommand } from "./shell.js";
3
+ import { cavelonCommand } from "./printed.js";
4
4
  const isObject = (v) => Boolean(v) && typeof v === "object" && !Array.isArray(v);
5
5
  const text = (v) => (typeof v === "string" && v.trim() ? v : null);
6
6
  const first = (o, keys) => keys.map((k) => o[k]).find((v) => v !== undefined);
@@ -101,13 +101,40 @@ export function fieldChanges(raw) {
101
101
  }
102
102
  return out;
103
103
  }
104
+ function commonPrefix(a, b) {
105
+ let n = 0;
106
+ while (n < a.length && n < b.length && a[n] === b[n])
107
+ n++;
108
+ return n;
109
+ }
104
110
  function shown(value) {
105
111
  if (value === undefined || value === null)
106
112
  return "null";
107
113
  return clip(JSON.stringify(value), 80);
108
114
  }
115
+ const DIFF_CONTEXT = 30;
116
+ export function shownPair(before, after) {
117
+ if (typeof before !== "string" || typeof after !== "string" || (JSON.stringify(before).length <= 80 && JSON.stringify(after).length <= 80)) {
118
+ return [shown(before), shown(after)];
119
+ }
120
+ const start = commonPrefix(before, after);
121
+ let end = 0;
122
+ while (end < before.length - start && end < after.length - start && before[before.length - 1 - end] === after[after.length - 1 - end])
123
+ end++;
124
+ const from = Math.max(0, start - DIFF_CONTEXT);
125
+ const window = (value) => {
126
+ const to = Math.min(value.length, value.length - end + DIFF_CONTEXT);
127
+ const part = JSON.stringify(value.slice(from, to));
128
+ return `${from > 0 ? "…" : ""}${clip(part, 160)}${to < value.length ? "…" : ""}`;
129
+ };
130
+ return [window(before), window(after)];
131
+ }
109
132
  export function changeLines(changes, max = 20) {
110
- const lines = changes.slice(0, max).map((c) => `\n - ${c.object}.${c.field}: ${shown(c.old)} → ${shown(c.new)}`);
133
+ const lines = changes.slice(0, max).map((c) => {
134
+ const [before, after] = shownPair(c.old, c.new);
135
+ const at = typeof c.old === "string" && typeof c.new === "string" && (before.startsWith("…") || after.startsWith("…")) ? ` (from character ${commonPrefix(c.old, c.new) + 1})` : "";
136
+ return `\n - ${c.object}.${c.field}: ${before} → ${after}${at}`;
137
+ });
111
138
  return lines.join("") + (changes.length > max ? `\n … ${changes.length - max} more (--json)` : "");
112
139
  }
113
140
  function harnessSlugAt(path, pkg, fallback) {
@@ -150,13 +177,25 @@ export function notAppliedLines(list) {
150
177
  })
151
178
  .join("") + (list.length > 20 ? `\n … ${list.length - 20} more (--json)` : "");
152
179
  }
180
+ const names = (raw) => (Array.isArray(raw) ? raw.map(text).filter((s) => s !== null) : undefined);
153
181
  export function tenantWideReport(raw) {
154
182
  if (!isObject(raw) || !Array.isArray(raw.sections))
155
183
  return undefined;
156
- const sections = raw.sections.map(text).filter((s) => s !== null);
184
+ const sections = names(raw.sections);
157
185
  const reaches = Array.isArray(raw.reaches_active_solutions) ? raw.reaches_active_solutions : [];
158
- const names = reaches
186
+ const solutions = reaches
159
187
  .map((h) => (isObject(h) ? (text(h.slug) ?? text(h.harness_slug) ?? text(h.name) ?? text(h.id)) : text(h)))
160
188
  .filter((n) => n !== null);
161
- return { sections, applied: raw.applied === true, reaches_active_solutions: [...new Set(names)] };
189
+ const applied = raw.applied === true;
190
+ const said = names(raw.would_import) ?? names(raw.imported);
191
+ const leftOut = names(raw.left_out);
192
+ const imports = said ?? (leftOut ? sections.filter((s) => !leftOut.includes(s)) : applied ? sections : []);
193
+ return {
194
+ sections,
195
+ applied,
196
+ imports,
197
+ left_out: leftOut ?? sections.filter((s) => !imports.includes(s)),
198
+ listed: said !== undefined || leftOut !== undefined,
199
+ reaches_active_solutions: [...new Set(solutions)],
200
+ };
162
201
  }
@@ -0,0 +1,182 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { ownsTenant, propertyName } from "./command.js";
3
+ import { CavelonError } from "./errors.js";
4
+ import { shellWord } from "./shell.js";
5
+ export function fill(name) {
6
+ return { placeholder: name };
7
+ }
8
+ const current = new AsyncLocalStorage();
9
+ export function printingFor(target, run) {
10
+ return current.run(target, run);
11
+ }
12
+ export function printMode() {
13
+ return current.getStore()?.mode ?? "cli";
14
+ }
15
+ export function cavelonCommand(...words) {
16
+ return printedCommand(words);
17
+ }
18
+ export function folderCommand(...words) {
19
+ const target = current.getStore();
20
+ return target ? current.run({ mode: target.mode, commands: target.commands, agentShell: target.agentShell }, () => printedCommand(words)) : printedCommand(words);
21
+ }
22
+ export function printedCommand(words, override = {}) {
23
+ const target = current.getStore();
24
+ const spec = target ? commandOf(target.commands, words) : undefined;
25
+ if (target && spec) {
26
+ const env = override.env !== undefined ? override.env ?? undefined : target.env;
27
+ if (target.mode === "mcp") {
28
+ const call = toolCall(target, spec, words.slice(spec.name.split(" ").length), env);
29
+ if (call)
30
+ return call;
31
+ }
32
+ const line = withTarget(spec, words, { ...target, env });
33
+ return commandLine(target.agentShell ? withTokenPlaceholder(line) : line);
34
+ }
35
+ return commandLine(words);
36
+ }
37
+ function withTokenPlaceholder(words) {
38
+ const at = words.indexOf("--confirm");
39
+ if (at < 0)
40
+ return [...words];
41
+ const next = words[at + 1];
42
+ if (next !== undefined && (typeof next !== "string" || !next.startsWith("-")))
43
+ return [...words];
44
+ return [...words.slice(0, at + 1), fill(PREVIEW_TOKEN_NAME), ...words.slice(at + 1)];
45
+ }
46
+ function commandLine(words) {
47
+ return ["cavelon", ...words.map((w) => (typeof w === "string" ? shellWord(w) : `<${w.placeholder}>`))].join(" ");
48
+ }
49
+ function commandOf(commands, words) {
50
+ const lead = [];
51
+ for (const word of words.slice(0, 3)) {
52
+ if (typeof word !== "string" || word.startsWith("-"))
53
+ break;
54
+ lead.push(word);
55
+ }
56
+ for (let n = lead.length; n > 0; n--) {
57
+ const spec = commands.find((c) => c.name === lead.slice(0, n).join(" "));
58
+ if (spec)
59
+ return spec;
60
+ }
61
+ return undefined;
62
+ }
63
+ const has = (words, flag) => words.some((w) => w === flag || (typeof w === "string" && w.startsWith(`${flag}=`)));
64
+ function withTarget(spec, words, target) {
65
+ const added = [];
66
+ if (target.instance && !has(words, "--instance"))
67
+ added.push("--instance", target.instance);
68
+ if (target.env && spec.options?.env && !has(words, "--env"))
69
+ added.push("--env", target.env);
70
+ if (target.tenant && takesTenant(spec) && !has(words, "--tenant"))
71
+ added.push("--tenant", target.tenant);
72
+ const at = words.indexOf("--confirm");
73
+ return at < 0 ? [...words, ...added] : [...words.slice(0, at), ...added, ...words.slice(at)];
74
+ }
75
+ function takesTenant(spec) {
76
+ return !spec.tenantless && !ownsTenant(spec);
77
+ }
78
+ const PREVIEW_TOKEN_NAME = "confirm_token of its preview";
79
+ export const PREVIEW_TOKEN = `<${PREVIEW_TOKEN_NAME}>`;
80
+ function toolCall(target, spec, args, env) {
81
+ const tool = spec.mcpTool ? spec : spec.mcpInstead ? target.commands.find((c) => c.name === spec.mcpInstead) : undefined;
82
+ if (!tool?.mcpTool)
83
+ return undefined;
84
+ const out = {};
85
+ const positionals = [...(tool.positionals ?? [])];
86
+ const value = (w) => (w === undefined ? undefined : typeof w === "string" ? w : `<${w.placeholder}>`);
87
+ for (let i = 0; i < args.length; i++) {
88
+ const word = args[i];
89
+ if (typeof word === "string" && word.startsWith("--")) {
90
+ const eq = word.indexOf("=");
91
+ const name = eq < 0 ? word.slice(2) : word.slice(2, eq);
92
+ const inline = eq < 0 ? undefined : word.slice(eq + 1);
93
+ const take = () => inline ?? value(args[++i]);
94
+ if (name === "json")
95
+ continue;
96
+ if (name === "instance") {
97
+ take();
98
+ continue;
99
+ }
100
+ if (name === "tenant" && takesTenant(tool)) {
101
+ out.tenant = take();
102
+ continue;
103
+ }
104
+ const own = tool === spec ? undefined : spec.options?.[name];
105
+ const option = tool.options?.[name] ?? (own ? { ...own, cliOnly: true } : undefined);
106
+ if (!option)
107
+ return undefined;
108
+ if (option.type === "string") {
109
+ const v = take();
110
+ if (option.cliOnly)
111
+ continue;
112
+ if (option.multiple)
113
+ out[propertyName(name)] = [...(out[propertyName(name)] ?? []), v];
114
+ else
115
+ out[propertyName(name)] = v;
116
+ }
117
+ else if (option.mcpToken) {
118
+ const next = args[i + 1];
119
+ const token = inline ?? (next !== undefined && (typeof next !== "string" || !next.startsWith("-")) ? value(args[++i]) : undefined);
120
+ out[propertyName(name)] = token ?? PREVIEW_TOKEN;
121
+ }
122
+ else if (!option.cliOnly) {
123
+ out[propertyName(name)] = true;
124
+ }
125
+ continue;
126
+ }
127
+ const p = positionals[0];
128
+ if (!p)
129
+ return undefined;
130
+ const key = propertyName(p.name);
131
+ if (p.variadic)
132
+ out[key] = [...(out[key] ?? []), value(word)];
133
+ else {
134
+ out[key] = value(word);
135
+ positionals.shift();
136
+ }
137
+ }
138
+ if (target.tenant && takesTenant(tool) && out.tenant === undefined)
139
+ out.tenant = target.tenant;
140
+ if (env && tool.options?.env && out.env === undefined)
141
+ out.env = env;
142
+ return `${tool.mcpTool} ${JSON.stringify(out)}`;
143
+ }
144
+ const NAMED_COMMAND = /`cavelon ([^`]+)`/g;
145
+ const SPAN_WORD = /<[^>]*>|\S+/g;
146
+ export function spoken(text) {
147
+ if (!current.getStore() || !text.includes("`cavelon "))
148
+ return text;
149
+ return text.replace(NAMED_COMMAND, (whole, line) => {
150
+ const words = (line.match(SPAN_WORD) ?? []).map((w) => (w.startsWith("<") && w.endsWith(">") ? fill(w.slice(1, -1)) : w));
151
+ const printed = printedCommand(words);
152
+ if (printed === commandLine(words))
153
+ return whole;
154
+ return `\`${printed.endsWith(" {}") ? printed.slice(0, -" {}".length) : printed}\``;
155
+ });
156
+ }
157
+ const HINT_FIELDS = new Set(["hint", "next", "fix", "cli_fix", "kit_hint", "warnings"]);
158
+ export function spokenHints(value) {
159
+ if (!current.getStore())
160
+ return value;
161
+ const walk = (v, hint) => {
162
+ if (typeof v === "string")
163
+ return hint ? spoken(v) : v;
164
+ if (Array.isArray(v))
165
+ return v.map((item) => walk(item, hint));
166
+ if (v && typeof v === "object")
167
+ return Object.fromEntries(Object.entries(v).map(([key, item]) => [key, walk(item, HINT_FIELDS.has(key))]));
168
+ return v;
169
+ };
170
+ return walk(value, false);
171
+ }
172
+ export function spokenError(error) {
173
+ if (!(error instanceof CavelonError) || !current.getStore())
174
+ return error;
175
+ const hint = error.hint === undefined ? undefined : spoken(error.hint);
176
+ const details = spokenHints(error.details);
177
+ const blockerDetails = spokenHints(error.blockerDetails);
178
+ if (hint === error.hint && JSON.stringify(details) === JSON.stringify(error.details) && JSON.stringify(blockerDetails) === JSON.stringify(error.blockerDetails))
179
+ return error;
180
+ const { exitCode, code, message, docs, status, blockers } = error;
181
+ return new CavelonError(exitCode, { code, message, hint, docs, status, details, blockers, blockerDetails });
182
+ }
package/dist/project.js CHANGED
@@ -4,6 +4,7 @@ import { parse } from "yaml";
4
4
  import { readTextFile } from "./fsutil.js";
5
5
  import { CavelonError, ExitCode, usageError } from "./errors.js";
6
6
  import { layoutFrom } from "./package-files.js";
7
+ import { cavelonCommand } from "./printed.js";
7
8
  export const PROJECT_FILE = "cavelon.yaml";
8
9
  function stringField(value, ...keys) {
9
10
  if (typeof value === "string" && value.trim())
@@ -100,7 +101,7 @@ export async function readEnvFile(project, name) {
100
101
  const known = await envNames(project);
101
102
  throw usageError(`No ${ENV_DIR}/${name}.yaml in this solution; nothing was sent.`, known.length
102
103
  ? `Its env files: ${known.join(", ")}. Pass one of them to --env, or write ${ENV_DIR}/${name}.yaml first.`
103
- : "`cavelon init` writes env/test.yaml and env/prod.yaml.");
104
+ : `\`${cavelonCommand("init")}\` writes env/test.yaml and env/prod.yaml.`);
104
105
  }
105
106
  let raw;
106
107
  try {
package/dist/results.js CHANGED
@@ -2,7 +2,7 @@ import { CavelonError } from "./errors.js";
2
2
  import { clip } from "./format.js";
3
3
  import { failedAssertions } from "./trace-view.js";
4
4
  import { callStable } from "./invoke.js";
5
- import { cavelonCommand } from "./shell.js";
5
+ import { cavelonCommand } from "./printed.js";
6
6
  export function caseKnowledgeOutcomes(r) {
7
7
  if (!Array.isArray(r.tool_calls))
8
8
  return null;
@@ -0,0 +1,30 @@
1
+ import { CavelonError, ExitCode } from "./errors.js";
2
+ import { cavelonCommand } from "./printed.js";
3
+ export const SECRETS_PERMISSIONS = ["settings.secrets.manage", "settings.manage"];
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
+ export function maySetSecrets(principal) {
6
+ if (!principal)
7
+ return null;
8
+ if (principal.kind === "api_key")
9
+ return false;
10
+ if (!principal.permissions || principal.mode !== "tenant")
11
+ return null;
12
+ return SECRETS_PERMISSIONS.some((p) => principal.permissions.includes(p));
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) : [];
17
+ }
18
+ export function secretSetterHint(name) {
19
+ return `${SECRET_SETTER}: \`${cavelonCommand("secrets", "set", name)}\`.`;
20
+ }
21
+ export function secretsPermissionMissing(verb, name, permissions) {
22
+ const needs = permissions.length ? permissions.join(" or ") : "a permission to manage secrets";
23
+ return new CavelonError(ExitCode.unauthorized, {
24
+ code: "permission_missing",
25
+ status: 403,
26
+ message: `This token's role may not ${verb} secrets: the instance refused it, as that needs ${needs}. Secret ${name} is unchanged.`,
27
+ hint: secretSetterHint(name),
28
+ details: { name, permissions, sent: true },
29
+ });
30
+ }