@cavelon/cli 0.1.15 → 0.1.16

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 (39) hide show
  1. package/README.md +12 -0
  2. package/dist/agent-env.js +2 -0
  3. package/dist/agents.js +14 -7
  4. package/dist/approval-policy.js +1 -0
  5. package/dist/commands/init.js +46 -10
  6. package/dist/commands/session.js +3 -0
  7. package/dist/commands/setup.js +17 -4
  8. package/dist/confirm-token.js +2 -1
  9. package/dist/fsutil.js +24 -7
  10. package/dist/jsonc-config.js +223 -0
  11. package/dist/kit-codes.js +1 -0
  12. package/dist/mcp-command.js +5 -0
  13. package/dist/mcp-directory.js +32 -0
  14. package/dist/mcp-entry.js +21 -0
  15. package/dist/mcp.js +18 -2
  16. package/dist/native-approval/client.js +126 -0
  17. package/dist/native-approval/ipc.js +191 -0
  18. package/dist/native-approval/opencode-server.js +74 -0
  19. package/dist/native-approval/opencode-tui.js +143 -0
  20. package/dist/native-approval/pi-extension.js +84 -0
  21. package/dist/native-approval/preview-pages.js +18 -0
  22. package/dist/native-approval/profile.js +113 -0
  23. package/dist/native-assets/JSONC-LICENSE +21 -0
  24. package/dist/native-assets/LICENSE +201 -0
  25. package/dist/native-assets/MCP-SDK-LICENSE +21 -0
  26. package/dist/native-assets/THIRD-PARTY-NOTICES +368 -0
  27. package/dist/native-assets/TYPEBOX-LICENSE +23 -0
  28. package/dist/native-assets/ZOD-LICENSE +21 -0
  29. package/dist/native-assets/manifest.json +60 -0
  30. package/dist/native-assets/opencode-server.mjs +32273 -0
  31. package/dist/native-assets/opencode-tui.mjs +19055 -0
  32. package/dist/native-assets/pi-extension.mjs +23302 -0
  33. package/dist/native-assets.js +44 -0
  34. package/dist/native-clients.js +181 -0
  35. package/dist/native-install.js +365 -0
  36. package/dist/printed.js +17 -5
  37. package/dist/setup-agents.js +73 -8
  38. package/dist/skills/cavelon-loop/SKILL.md +7 -0
  39. package/package.json +7 -3
package/README.md CHANGED
@@ -21,6 +21,18 @@ in Windows PowerShell. With Python, `uvx cavelon` runs the same executable from
21
21
  PyPI, and `uv tool install cavelon` or `pipx install cavelon` installs it. Then
22
22
  `cavelon setup` sets up your coding agents and logs you in.
23
23
 
24
+ Version 0.1.16 adds OpenCode and Pi with bundled native approval dialogs and
25
+ Qwen Code CLI with native settings, skills and person-terminal confirmation:
26
+
27
+ ```bash
28
+ cavelon setup --agents opencode,pi,qwen
29
+ ```
30
+
31
+ See the [client install pages](https://github.com/goodguys-gmbh/cavelon-dev-kit/blob/main/docs/install/README.md)
32
+ and [qualification matrix](https://github.com/goodguys-gmbh/cavelon-dev-kit/blob/main/docs/coding-agent-qualification.md)
33
+ for pinned versions, tested platforms, updates and removal.
34
+
35
+
24
36
  The full documentation is in the repository's
25
37
  [`docs/`](https://github.com/goodguys-gmbh/cavelon-dev-kit/tree/main/docs):
26
38
  [installation](https://github.com/goodguys-gmbh/cavelon-dev-kit/blob/main/docs/installation.md)
package/dist/agent-env.js CHANGED
@@ -7,11 +7,13 @@ export const AGENT_VARIABLES = [
7
7
  { variable: "CODEX_SANDBOX", agent: "Codex" },
8
8
  { variable: "CURSOR_AGENT", agent: "Cursor" },
9
9
  { variable: "GEMINI_CLI", agent: "Gemini CLI" },
10
+ { variable: "QWEN_CODE", agent: "Qwen Code" },
10
11
  { variable: "COPILOT_CLI", agent: "GitHub Copilot CLI" },
11
12
  { variable: "COPILOT_AGENT", agent: "GitHub Copilot in VS Code" },
12
13
  { variable: "AGENT_CONTEXT_OUT", agent: "Kiro CLI" },
13
14
  { variable: "TERM_PROGRAM", value: "kiro", agent: "Kiro" },
14
15
  { variable: "OPENCODE", agent: "OpenCode" },
16
+ { variable: "PI_SESSION_ID", agent: "Pi" },
15
17
  { variable: "GROK_AGENT", agent: "Grok Build" },
16
18
  { variable: "AI_AGENT", agent: "an agent that follows the AI_AGENT convention" },
17
19
  ];
package/dist/agents.js CHANGED
@@ -5,11 +5,10 @@ import { embeddedContent } from "./embedded.js";
5
5
  import { usageError } from "./errors.js";
6
6
  import { GENERATED_TOKEN } from "./markers.js";
7
7
  import { KIT_VERSION } from "./version.js";
8
- export const MCP_COMMAND = { command: "npx", args: ["-y", "@cavelon/cli@0.1", "mcp"] };
9
- export const INSTALLED_MCP_COMMAND = { command: "cavelon", args: ["mcp"] };
10
- export function mcpCommand(platform = process.platform) {
11
- return platform === "win32" ? { command: "cmd", args: ["/c", MCP_COMMAND.command, ...MCP_COMMAND.args] } : MCP_COMMAND;
12
- }
8
+ import { INSTALLED_MCP_COMMAND, mcpCommand } from "./mcp-command.js";
9
+ import { encodeMcpEntry } from "./mcp-entry.js";
10
+ import { NATIVE_CLIENTS, nativeClient } from "./native-clients.js";
11
+ export { MCP_COMMAND, INSTALLED_MCP_COMMAND, mcpCommand } from "./mcp-command.js";
13
12
  const PLATFORMS = ["win32", "linux"];
14
13
  const otherPlatforms = () => PLATFORMS.filter((p) => (p === "win32") !== (process.platform === "win32"));
15
14
  const jsonServer = (file, key = "mcpServers", extra = {}) => ({
@@ -46,7 +45,11 @@ export const AGENTS = [
46
45
  agent("copilot", "GitHub Copilot in VS Code", () => jsonServer(".vscode/mcp.json", "servers", { type: "stdio" })),
47
46
  agent("gemini", "Gemini CLI", () => jsonServer(".gemini/settings.json")),
48
47
  agent("kiro", "Kiro", () => jsonServer(".kiro/settings/mcp.json")),
49
- agent("pi", "Pi"),
48
+ ...NATIVE_CLIENTS.map(client => agent(client.name, client.label, () => {
49
+ const config = client.project();
50
+ return { ...config, entry: encodeMcpEntry(mcpCommand(), config.entryFormat, config.extra),
51
+ others: [...otherPlatforms().map(p => encodeMcpEntry(mcpCommand(p), config.entryFormat, config.extra)), encodeMcpEntry(INSTALLED_MCP_COMMAND, config.entryFormat, config.extra)] };
52
+ })),
50
53
  agent("other", "any other agent with a shell"),
51
54
  ];
52
55
  const ALIASES = { "claude-code": "claude", vscode: "copilot", "gemini-cli": "gemini" };
@@ -56,7 +59,7 @@ export function parseAgents(values) {
56
59
  return AGENTS;
57
60
  const out = [];
58
61
  for (const raw of names) {
59
- const name = ALIASES[raw] ?? raw;
62
+ const name = ALIASES[raw] ?? nativeClient(raw)?.name ?? raw;
60
63
  const target = AGENTS.find((a) => a.name === name);
61
64
  if (!target)
62
65
  throw usageError(`Unknown agent "${raw}".`, `Known: ${AGENTS.map((a) => a.name).join(", ")}, or all.`);
@@ -66,6 +69,10 @@ export function parseAgents(values) {
66
69
  return out;
67
70
  }
68
71
  export const SKILL_ROOTS = [".agents/skills", ".claude/skills"];
72
+ export function skillRootsFor(agents) {
73
+ return [...new Set([...SKILL_ROOTS, ...agents.flatMap(agent => nativeClient(agent.name)?.projectSkills ?? [])])];
74
+ }
75
+ export const KNOWN_SKILL_ROOTS = [...new Set([...SKILL_ROOTS, ...NATIVE_CLIENTS.flatMap(client => client.projectSkills)])];
69
76
  export function skillsSource() {
70
77
  const here = path.dirname(fileURLToPath(import.meta.url));
71
78
  return [path.join(here, "skills"), path.resolve(here, "..", "..", "plugin", "skills")];
@@ -0,0 +1 @@
1
+ export const PERSON_WAIT_MS = 10 * 60_000;
@@ -2,7 +2,12 @@ import { promises as fs } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { parseDocument } from "yaml";
4
4
  import { boolOption, listOption, stringOption } from "../command.js";
5
- import { AGENTS, bundledSkills, generatedCopy, parseAgents, SKILL_ROOTS } from "../agents.js";
5
+ import { AGENTS, bundledSkills, generatedCopy, parseAgents, KNOWN_SKILL_ROOTS, skillRootsFor } from "../agents.js";
6
+ import { nativeClient, resolveNativeMcp, hasNativeApprovalAdapter } from "../native-clients.js";
7
+ import { applyNativeInstallation, planNativeInstallation } from "../native-install.js";
8
+ import { serverCommand } from "../setup-agents.js";
9
+ import { encodeMcpEntry, isKitMcpEntry } from "../mcp-entry.js";
10
+ import { upsertJsoncEntry } from "../jsonc-config.js";
6
11
  import { CavelonError, ExitCode, usageError } from "../errors.js";
7
12
  import { confinedPath, realPath, within } from "../paths.js";
8
13
  import { readTextFile, withoutBom, writeFileAtomic } from "../fsutil.js";
@@ -192,7 +197,30 @@ async function writeSkills(root, roots) {
192
197
  }
193
198
  return actions;
194
199
  }
195
- async function writeMcp(root, target, onlyExisting) {
200
+ async function writeMcp(root, target, onlyExisting, env) {
201
+ if (target.format === "native") {
202
+ const config = { ...target, ...nativeClient(target.client)?.project(env) };
203
+ if (!hasNativeApprovalAdapter(config)) {
204
+ const selected = await resolveNativeMcp(config, root);
205
+ if ("error" in selected)
206
+ return { file: rel(root, selected.file), action: "skipped", reason: selected.error };
207
+ if (selected.current !== undefined && isKitMcpEntry(selected.current, config.entryFormat, config.extra))
208
+ return { file: rel(root, selected.file), action: "unchanged" };
209
+ const value = encodeMcpEntry(await serverCommand(env), config.entryFormat, config.extra);
210
+ return applyBlock(root, selected.file, upsertJsoncEntry(selected.text, config.keys, value, { onlyExisting, matches: current => isKitMcpEntry(current, config.entryFormat, config.extra) }));
211
+ }
212
+ if (onlyExisting) {
213
+ const selected = await resolveNativeMcp({ ...config, shadowFiles: [] }, root);
214
+ if (!("error" in selected) && selected.current === undefined)
215
+ return { file: rel(root, selected.file), action: "skipped", reason: "it has no cavelon entry" };
216
+ }
217
+ const plan = await planNativeInstallation(config, await serverCommand(env), env, { root });
218
+ if (plan.outcome !== "planned")
219
+ return { file: rel(root, plan.directory), action: plan.outcome, ...(plan.reason ? { reason: plan.reason } : {}) };
220
+ const exists = await fs.stat(plan.directory).then(() => true, () => false);
221
+ await applyNativeInstallation(plan);
222
+ return { file: rel(root, plan.directory), action: exists ? "updated" : "created" };
223
+ }
196
224
  const file = path.join(root, target.file);
197
225
  const existing = await readTextFile(file);
198
226
  if (existing !== undefined && holdsOtherForm(existing, target))
@@ -230,9 +258,9 @@ function holdsOtherForm(existing, target) {
230
258
  }
231
259
  return target.others.some((entry) => JSON.stringify(entry) === JSON.stringify(current));
232
260
  }
233
- async function installedFallback(root) {
261
+ async function installedFallback(root, env) {
234
262
  const skillRoots = [];
235
- for (const skillRoot of SKILL_ROOTS) {
263
+ for (const skillRoot of KNOWN_SKILL_ROOTS) {
236
264
  try {
237
265
  const names = await fs.readdir(path.join(root, skillRoot));
238
266
  for (const name of names.filter((n) => n.startsWith("cavelon-"))) {
@@ -249,6 +277,12 @@ async function installedFallback(root) {
249
277
  for (const agent of AGENTS) {
250
278
  if (!agent.mcp)
251
279
  continue;
280
+ if (agent.mcp.format === "native") {
281
+ const selected = await resolveNativeMcp({ ...agent.mcp, ...nativeClient(agent.name)?.project(env) }, root);
282
+ if ("error" in selected || selected.current !== undefined)
283
+ agents.push(agent);
284
+ continue;
285
+ }
252
286
  const text = await readTextFile(path.join(root, agent.mcp.file));
253
287
  if (text?.includes("cavelon"))
254
288
  agents.push(agent);
@@ -560,13 +594,13 @@ async function runInit(ctx, input) {
560
594
  actions.push(claude);
561
595
  actions.push(await block(root, ".gitignore", GITIGNORE_BLOCK, "hash", { onlyExisting: true }));
562
596
  actions.push(await installHook(root, !boolOption(input, "hook")));
563
- const installed = await installedFallback(root);
564
- const skillRoots = agents.length ? SKILL_ROOTS : installed.skillRoots;
597
+ const installed = await installedFallback(root, ctx.io.env);
598
+ const skillRoots = agents.length ? skillRootsFor(agents) : installed.skillRoots;
565
599
  if (skillRoots.length)
566
600
  actions.push(...(await writeSkills(root, skillRoots)));
567
601
  for (const agent of new Set([...installed.agents, ...agents])) {
568
602
  if (agent.mcp)
569
- actions.push(await writeMcp(root, agent.mcp, !agents.includes(agent)));
603
+ actions.push(await writeMcp(root, agent.mcp, !agents.includes(agent), ctx.io.env));
570
604
  }
571
605
  return { root, actions: actions.filter((a) => !(a.action === "skipped" && /does not exist|no cavelon (block|entry)/.test(a.reason ?? ""))), next, imported: undefined };
572
606
  }
@@ -641,10 +675,12 @@ async function runInit(ctx, input) {
641
675
  if (claude)
642
676
  actions.push(claude);
643
677
  if (agents.length) {
644
- actions.push(...(await writeSkills(root, SKILL_ROOTS)));
645
- for (const agent of agents)
678
+ actions.push(...(await writeSkills(root, skillRootsFor(agents))));
679
+ for (const agent of agents) {
646
680
  if (agent.mcp)
647
- actions.push(await writeMcp(root, agent.mcp, false));
681
+ actions.push(await writeMcp(root, agent.mcp, false, ctx.io.env));
682
+ next.push(...(nativeClient(agent.name)?.notes ?? []));
683
+ }
648
684
  }
649
685
  if (boolOption(input, "hook"))
650
686
  actions.push(await installHook(root, false));
@@ -1,4 +1,5 @@
1
1
  import { capacityLimits, capacityNotes } from "../capacity.js";
2
+ import { refuseForAgent } from "../agent-env.js";
2
3
  import { boolOption, positional } from "../command.js";
3
4
  import { compareContracts, Contracts } from "../contracts.js";
4
5
  import { deleteToken, saveToken } from "../credentials.js";
@@ -76,6 +77,7 @@ export const login = {
76
77
  tenantless: true,
77
78
  summary: "Store a token for an instance (a person runs this, never the agent).",
78
79
  description: "Asks for the token without echoing it, or reads it from standard input with --token-stdin. It is never an argument.\n" +
80
+ "A coding agent's shell is refused before reading input or contacting the instance; log in from your own terminal.\n" +
79
81
  "Create a personal access token (cvpat_…) on /account/access-tokens; a tenant API key (cbp_…) also works.\n" +
80
82
  "The token is kept in the operating system's credential store, or in a file only you can read.\n" +
81
83
  "Without --tenant, login finds the tenants the token reaches: one is used; from several, a person chooses on a terminal by number or name; " +
@@ -93,6 +95,7 @@ export const login = {
93
95
  "op read op://dev/cavelon/token | cavelon login --token-stdin --tenant acme-support",
94
96
  ],
95
97
  async run(ctx, input) {
98
+ refuseForAgent(ctx, "Logging in with a token", cavelonCommand("login"));
96
99
  const session = await ctx.session();
97
100
  const url = session.url;
98
101
  if (!url)
@@ -69,12 +69,15 @@ function planJson(plan, changes = plan.changes) {
69
69
  label: plan.agent.label,
70
70
  found: { command: plan.found.program ?? null, folder: plan.found.folder ?? null },
71
71
  method: plan.method,
72
+ ...(plan.agent.notes ? { notes: plan.agent.notes } : {}),
72
73
  changes: changes.map((c) => ({ kind: c.kind, summary: c.summary, target: c.target, outcome: c.outcome, ...(c.reason ? { reason: c.reason } : {}) })),
73
74
  };
74
75
  }
75
76
  function planText(plans, notFound) {
76
77
  const lines = [];
77
78
  for (const plan of plans) {
79
+ for (const note of plan.agent.notes ?? [])
80
+ lines.push(` ${plan.agent.label}: ${note}`);
78
81
  const todo = plan.changes.filter((c) => c.outcome === "planned");
79
82
  const other = plan.changes.filter((c) => c.outcome !== "planned" && c.outcome !== "unchanged");
80
83
  if (!todo.length && !other.length) {
@@ -183,9 +186,10 @@ async function runSetup(ctx, input) {
183
186
  throw new CavelonError(ExitCode.failure, { code: "skills_missing", message: "This cavelon has no skills to install (its package is incomplete).", hint: "Reinstall @cavelon/cli." });
184
187
  }
185
188
  const command = await serverCommand(env);
189
+ const state = await loadState(env);
186
190
  const plans = [];
187
191
  for (const { agent, found: where } of chosen)
188
- plans.push(await planAgent(agent, where, env, command, skills));
192
+ plans.push(await planAgent(agent, where, env, command, skills, process.platform, state.agents[agent.name]));
189
193
  const pending = plans.some((p) => p.changes.some((c) => c.outcome === "planned"));
190
194
  let results = plans.map((plan) => ({ plan, changes: plan.changes }));
191
195
  let declined = false;
@@ -200,7 +204,6 @@ async function runSetup(ctx, input) {
200
204
  declined = !(await confirm(ctx, "Make these changes?", true));
201
205
  }
202
206
  if (!declined) {
203
- const state = await loadState(env);
204
207
  results = [];
205
208
  for (const plan of plans) {
206
209
  const record = (state.agents[plan.agent.name] ??= {});
@@ -209,6 +212,16 @@ async function runSetup(ctx, input) {
209
212
  }
210
213
  }
211
214
  }
215
+ let recovered = false;
216
+ if (!declined)
217
+ for (const { plan, changes } of results) {
218
+ if (plan.native && changes.some(change => change.kind === "native" && change.outcome === "unchanged") && !state.agents[plan.agent.name]?.native) {
219
+ (state.agents[plan.agent.name] ??= {}).native = { directory: plan.native.directory };
220
+ recovered = true;
221
+ }
222
+ }
223
+ if (recovered)
224
+ await saveState(env, state);
212
225
  const loginReport = declined ? undefined : await loginStep(ctx);
213
226
  const failed = results.some((r) => r.changes.some((c) => c.outcome === "failed"));
214
227
  const ready = results.filter((r) => r.changes.length && r.changes.every((c) => c.outcome === "done" || c.outcome === "unchanged"));
@@ -400,7 +413,7 @@ export const setup = {
400
413
  storesTarget: true,
401
414
  tenantless: true,
402
415
  summary: "Set up your coding agents for Cavelon and log in, in one guided step.",
403
- description: "Finds Claude Code, Codex, Cursor, VS Code with GitHub Copilot, Gemini CLI and Kiro, shows what it will change for each, asks once\n" +
416
+ description: "Finds Claude Code, Codex, Cursor, VS Code with GitHub Copilot, Gemini CLI, Kiro, OpenCode and Pi, shows what it will change for each, asks once\n" +
404
417
  "and does it: Claude Code and Codex get the Cavelon plugin through their own plugin command, Gemini CLI the extension of this\n" +
405
418
  "release (or the files, when the release has none); the others get the `cavelon` MCP server in their user MCP configuration\n" +
406
419
  "and the skills in their user skills folder. It touches nothing else in those files and\n" +
@@ -418,7 +431,7 @@ export const setup = {
418
431
  type: "string",
419
432
  value: "<list>",
420
433
  multiple: true,
421
- description: "Only these agents: claude, codex, cursor, copilot, gemini, kiro, or all (comma-separated). Default: every agent found.",
434
+ description: "Only these agents: claude, codex, cursor, copilot, gemini, kiro, opencode, pi, qwen, or all (comma-separated). Default: every agent found.",
422
435
  },
423
436
  yes: { type: "boolean", short: "y", description: "Make the changes without asking." },
424
437
  check: { type: "boolean", description: "Report what is set up and working; change nothing." },
@@ -1,9 +1,11 @@
1
1
  import { createHash } from "node:crypto";
2
+ import { PERSON_WAIT_MS } from "./approval-policy.js";
2
3
  import { actingTarget, targetLine } from "./acting.js";
3
4
  import { drivenByAgent } from "./agent-env.js";
4
5
  import { CavelonError, ExitCode } from "./errors.js";
5
6
  import { canonical } from "./package-files.js";
6
7
  import { personCommand, PREVIEW_TOKEN } from "./printed.js";
8
+ export { PERSON_WAIT_MS } from "./approval-policy.js";
7
9
  export const CONFIRM_TOKEN = /^[0-9a-f]{12}$/;
8
10
  export function confirmToken(target, tool, change) {
9
11
  return createHash("sha256")
@@ -105,7 +107,6 @@ async function gateOf(ctx, input, tool, change, options) {
105
107
  export function personRoute(ctx, driven) {
106
108
  return driven.by === "mcp" && ctx.askPerson ? "client" : "terminal";
107
109
  }
108
- export const PERSON_WAIT_MS = 10 * 60_000;
109
110
  export async function personApproves(ctx, driven, change, target = {}) {
110
111
  if (personRoute(ctx, driven) === "terminal")
111
112
  throw needsPerson(change.command);
package/dist/fsutil.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { promises as fs } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { randomBytes } from "node:crypto";
4
+ import { setTimeout as delay } from "node:timers/promises";
4
5
  export async function readJsonFile(file) {
5
6
  try {
6
7
  return JSON.parse(await fs.readFile(file, "utf8"));
@@ -29,17 +30,33 @@ export function withoutBom(text) {
29
30
  export async function writeFileAtomic(file, content, mode = 0o644, dirMode = 0o755) {
30
31
  await fs.mkdir(path.dirname(file), { recursive: true, mode: dirMode });
31
32
  const tmp = `${file}.${randomBytes(6).toString("hex")}.tmp`;
32
- const handle = await fs.open(tmp, "w", mode);
33
33
  try {
34
- await handle.writeFile(content, "utf8");
34
+ const handle = await fs.open(tmp, "w", mode);
35
+ try {
36
+ await handle.writeFile(content, "utf8");
37
+ }
38
+ finally {
39
+ await handle.close();
40
+ }
41
+ const existing = await fs.stat(file).then((st) => st.mode & 0o777, () => undefined);
42
+ if (existing !== undefined)
43
+ await fs.chmod(tmp, existing & mode).catch(() => undefined);
44
+ for (let attempt = 0;; attempt++) {
45
+ try {
46
+ await fs.rename(tmp, file);
47
+ break;
48
+ }
49
+ catch (error) {
50
+ const code = error.code;
51
+ if (process.platform !== "win32" || attempt >= 5 || !["EPERM", "EACCES", "EBUSY"].includes(code ?? ""))
52
+ throw error;
53
+ await delay(10 * 2 ** attempt);
54
+ }
55
+ }
35
56
  }
36
57
  finally {
37
- await handle.close();
58
+ await fs.rm(tmp, { force: true }).catch(() => undefined);
38
59
  }
39
- const existing = await fs.stat(file).then((st) => st.mode & 0o777, () => undefined);
40
- if (existing !== undefined)
41
- await fs.chmod(tmp, existing & mode).catch(() => undefined);
42
- await fs.rename(tmp, file);
43
60
  }
44
61
  export async function writePrivateFile(base, file, content) {
45
62
  await writeFileAtomic(file, content, 0o600, 0o700);
@@ -0,0 +1,223 @@
1
+ import { applyEdits, createScanner, findNodeAtLocation, modify, parseTree } from "jsonc-parser";
2
+ function document(text) {
3
+ const errors = [];
4
+ const root = parseTree(text, errors, { allowTrailingComma: true });
5
+ if (errors.length || !root)
6
+ return { error: "it has a JSONC syntax error" };
7
+ if (root.type !== "object")
8
+ return { error: "it is not a JSON object" };
9
+ const duplicate = (node) => {
10
+ if (node.type === "object") {
11
+ const names = node.children?.map(property => property.children[0].value) ?? [];
12
+ if (new Set(names).size !== names.length)
13
+ return true;
14
+ }
15
+ return node.children?.some(duplicate) ?? false;
16
+ };
17
+ if (duplicate(root))
18
+ return { error: "it has duplicate keys, so its effective configuration is ambiguous" };
19
+ return { root };
20
+ }
21
+ function valueOf(node) {
22
+ if (!node)
23
+ return undefined;
24
+ if (node.type === "object")
25
+ return Object.fromEntries((node.children ?? []).map(property => [property.children[0].value, valueOf(property.children[1])]));
26
+ if (node.type === "array")
27
+ return (node.children ?? []).map(valueOf);
28
+ return node.value;
29
+ }
30
+ function comments(text) {
31
+ const scanner = createScanner(text);
32
+ const found = [];
33
+ for (let token = scanner.scan(); token !== 17; token = scanner.scan()) {
34
+ if (token === 12 || token === 13) {
35
+ found.push(text.slice(scanner.getTokenOffset(), scanner.getTokenOffset() + scanner.getTokenLength()));
36
+ }
37
+ }
38
+ return found;
39
+ }
40
+ function same(left, right) {
41
+ if (left === right)
42
+ return true;
43
+ if (!left || !right || typeof left !== "object" || typeof right !== "object")
44
+ return false;
45
+ if (Array.isArray(left) || Array.isArray(right))
46
+ return Array.isArray(left) && Array.isArray(right) && left.length === right.length && left.every((item, index) => same(item, right[index]));
47
+ const keys = Object.keys(left);
48
+ return keys.length === Object.keys(right).length && keys.every(key => Object.hasOwn(right, key) && same(left[key], right[key]));
49
+ }
50
+ function validPath(keys) {
51
+ return keys.length > 0 && keys.every(key => key.length > 0 && !["__proto__", "constructor", "prototype"].includes(key));
52
+ }
53
+ export function readJsoncEntry(text, keys) {
54
+ if (!validPath(keys))
55
+ return { error: "the configuration entry path is invalid" };
56
+ if (text === undefined)
57
+ return { value: undefined, kept: 0 };
58
+ const parsed = document(text);
59
+ if ("error" in parsed)
60
+ return parsed;
61
+ let kept = 0;
62
+ for (let depth = 1; depth <= keys.length; depth++) {
63
+ const node = findNodeAtLocation(parsed.root, keys.slice(0, depth));
64
+ if (!node)
65
+ break;
66
+ if (depth < keys.length && node.type !== "object")
67
+ return { error: `its "${keys.slice(0, depth).join(".")}" is not an object` };
68
+ kept = depth;
69
+ }
70
+ return { value: valueOf(findNodeAtLocation(parsed.root, keys)), kept };
71
+ }
72
+ function removalEdits(text, root, keys) {
73
+ const parent = findNodeAtLocation(root, keys.slice(0, -1));
74
+ const children = parent?.children ?? [];
75
+ const index = children.findIndex(property => property.children?.[0]?.value === keys.at(-1));
76
+ if (index < 0)
77
+ return [];
78
+ return itemRemovalEdits(text, children, index);
79
+ }
80
+ function itemRemovalEdits(text, children, index) {
81
+ const item = children[index];
82
+ const edits = [{ offset: item.offset, length: item.length, content: "" }];
83
+ const scanner = createScanner(text, true);
84
+ scanner.setPosition(item.offset + item.length);
85
+ if (scanner.scan() === 5)
86
+ edits.push({ offset: scanner.getTokenOffset(), length: 1, content: "" });
87
+ else if (index > 0) {
88
+ const previous = children[index - 1];
89
+ scanner.setPosition(previous.offset + previous.length);
90
+ if (scanner.scan() !== 5)
91
+ throw new Error("Missing property separator.");
92
+ edits.push({ offset: scanner.getTokenOffset(), length: 1, content: "" });
93
+ }
94
+ return edits;
95
+ }
96
+ function checkedEdits(text, edits) {
97
+ const content = applyEdits(text, edits);
98
+ const parsed = document(content);
99
+ if ("error" in parsed)
100
+ return { outcome: "skipped", reason: parsed.error };
101
+ if (!same(comments(text), comments(content)))
102
+ return { outcome: "skipped", reason: "changing this entry would remove a personal comment; edit it manually" };
103
+ return content === text ? { outcome: "unchanged" } : { outcome: "updated", content };
104
+ }
105
+ function edit(text, keys, value) {
106
+ try {
107
+ const before = document(text);
108
+ if ("error" in before)
109
+ return { outcome: "skipped", reason: before.error };
110
+ return checkedEdits(text, value === undefined ? removalEdits(text, before.root, keys) : modify(text, keys, value, {}));
111
+ }
112
+ catch {
113
+ return { outcome: "skipped", reason: "this configuration cannot be edited safely" };
114
+ }
115
+ }
116
+ export function upsertJsoncEntry(existing, keys, value, options = {}) {
117
+ if (!validPath(keys))
118
+ return { outcome: "skipped", reason: "the configuration entry path is invalid" };
119
+ if (existing === undefined) {
120
+ if (options.onlyExisting)
121
+ return { outcome: "skipped", reason: "the file does not exist" };
122
+ let root = value;
123
+ for (const key of [...keys].reverse())
124
+ root = { [key]: root };
125
+ return { outcome: "created", content: JSON.stringify(root, null, 2) + "\n" };
126
+ }
127
+ const current = readJsoncEntry(existing, keys);
128
+ if ("error" in current)
129
+ return { outcome: "skipped", reason: current.error };
130
+ if (same(current.value, value))
131
+ return { outcome: "unchanged" };
132
+ if (current.value === undefined && options.onlyExisting)
133
+ return { outcome: "skipped", reason: "it has no Cavelon entry" };
134
+ if (current.value !== undefined && !options.matches?.(current.value))
135
+ return { outcome: "skipped", reason: `its "${keys.join(".")}" is a personal or conflicting entry` };
136
+ const result = edit(existing, keys, value);
137
+ return result.outcome === "updated" && current.value === undefined ? { ...result, outcome: "appended" } : result;
138
+ }
139
+ export function removeJsoncEntry(existing, keys, matches, keep = 0) {
140
+ if (existing === undefined)
141
+ return { outcome: "unchanged" };
142
+ const current = readJsoncEntry(existing, keys);
143
+ if ("error" in current)
144
+ return { outcome: "skipped", reason: current.error };
145
+ if (current.value === undefined)
146
+ return { outcome: "unchanged" };
147
+ if (!matches(current.value))
148
+ return { outcome: "skipped", reason: `its "${keys.join(".")}" was changed since cavelon wrote it` };
149
+ const removed = edit(existing, keys, undefined);
150
+ if (removed.outcome !== "updated")
151
+ return removed;
152
+ let content = removed.content;
153
+ for (let depth = keys.length - 1; depth > keep; depth--) {
154
+ const parsed = document(content);
155
+ if ("error" in parsed)
156
+ break;
157
+ const parent = findNodeAtLocation(parsed.root, keys.slice(0, depth));
158
+ if (!parent || parent.type !== "object" || parent.children?.length || comments(content.slice(parent.offset, parent.offset + parent.length)).length)
159
+ break;
160
+ const trimmed = edit(content, keys.slice(0, depth), undefined);
161
+ if (trimmed.outcome !== "updated")
162
+ break;
163
+ content = trimmed.content;
164
+ }
165
+ const parsed = document(content);
166
+ const empty = "root" in parsed && !parsed.root.children?.length && comments(content).length === 0;
167
+ return { outcome: "updated", content, empty };
168
+ }
169
+ export function appendJsoncMember(existing, keys, member) {
170
+ const current = readJsoncEntry(existing, keys);
171
+ if ("error" in current)
172
+ return { outcome: "skipped", reason: current.error };
173
+ if (current.value === undefined)
174
+ return upsertJsoncEntry(existing, keys, [member]);
175
+ if (!Array.isArray(current.value))
176
+ return { outcome: "skipped", reason: `its "${keys.join(".")}" is not an array` };
177
+ const count = current.value.filter(item => same(item, member)).length;
178
+ if (count > 1)
179
+ return { outcome: "skipped", reason: "the Cavelon member occurs more than once; resolve duplicate entries manually" };
180
+ if (count === 1)
181
+ return { outcome: "unchanged" };
182
+ try {
183
+ const result = checkedEdits(existing, modify(existing, [...keys, current.value.length], member, { isArrayInsertion: true }));
184
+ return result.outcome === "updated" ? { ...result, outcome: "appended" } : result;
185
+ }
186
+ catch {
187
+ return { outcome: "skipped", reason: "this configuration cannot be edited safely" };
188
+ }
189
+ }
190
+ export function removeJsoncMember(existing, keys, member, options = {}) {
191
+ const current = readJsoncEntry(existing, keys);
192
+ if ("error" in current)
193
+ return { outcome: "skipped", reason: current.error };
194
+ if (current.value === undefined)
195
+ return { outcome: "unchanged" };
196
+ if (!Array.isArray(current.value))
197
+ return { outcome: "skipped", reason: `its "${keys.join(".")}" is not an array` };
198
+ const indices = current.value.flatMap((item, index) => same(item, member) ? [index] : []);
199
+ if (!indices.length)
200
+ return { outcome: "unchanged" };
201
+ if (indices.length > 1)
202
+ return { outcome: "skipped", reason: "the Cavelon member occurs more than once; resolve duplicate entries manually" };
203
+ try {
204
+ const before = document(existing);
205
+ if ("error" in before)
206
+ return { outcome: "skipped", reason: before.error };
207
+ const node = findNodeAtLocation(before.root, keys);
208
+ const result = checkedEdits(existing, itemRemovalEdits(existing, node.children, indices[0]));
209
+ if (result.outcome !== "updated")
210
+ return result;
211
+ const parsed = document(result.content);
212
+ if ("error" in parsed)
213
+ return { outcome: "skipped", reason: parsed.error };
214
+ const remaining = findNodeAtLocation(parsed.root, keys);
215
+ if (options.removeEmpty && !remaining.children?.length && !comments(result.content.slice(remaining.offset, remaining.offset + remaining.length)).length) {
216
+ return removeJsoncEntry(result.content, keys, value => Array.isArray(value) && !value.length, keys.length - 1);
217
+ }
218
+ return { ...result, empty: !parsed.root.children?.length && comments(result.content).length === 0 };
219
+ }
220
+ catch {
221
+ return { outcome: "skipped", reason: "this configuration cannot be edited safely" };
222
+ }
223
+ }
package/dist/kit-codes.js CHANGED
@@ -65,6 +65,7 @@ export const KIT_ERROR_CODES = [
65
65
  { code: "preview_expired", area: "cli", message: "The preview is older than the kit keeps previews; nothing was imported.", hint: "Run `cavelon apply` for a new preview, show it, and confirm its id." },
66
66
  { code: "confirm_token_required", area: "cli", message: "Over MCP, or run by a coding agent in its shell, a changing command confirms only with the token its preview returned, never with true or a bare --confirm.", hint: "Call the tool (or run the command) without confirm, show the person the preview, then call it again with the same arguments and confirm set to its confirm_token (--confirm <token> in a shell)." },
67
67
  { code: "confirm_needs_person", area: "cli", message: "A coding agent cannot confirm this change, even with its preview's token: it reaches live traffic or the whole tenant, or cannot be taken back, and the agent's MCP client cannot ask the person (or the agent runs cavelon in its shell). Nothing was changed.", hint: "Show the person the preview; they run the command the refusal names in their own terminal, outside the agent." },
68
+ { code: "native_ui_disconnected", area: "cli", message: "The native person UI call failed after routing. Its outcome may be unknown, so the adapter never retries through another connection.", hint: "Inspect the instance's current state before repeating the change. Reconnect the client; a new guarded attempt needs a fresh preview and person answer." },
68
69
  { code: "confirm_declined", area: "cli", message: "The MCP client asked the person to approve the change, and they declined or did not answer in time. Nothing was changed.", hint: "Ask the person whether they want the change; with their yes, confirm again with the same token, or they run the command in their own terminal." },
69
70
  { code: "token_mismatch", area: "cli", message: "The confirm token is not the one for this change: it belongs to another preview, or the change differs from what its preview showed; nothing was changed (exit code 4).", hint: "Show the person the new preview this answer carries, and confirm only with its confirm_token after their yes; a token confirms exactly the change its preview showed." },
70
71
  { code: "unknown_argument", area: "cli", message: "An MCP tool was called with an argument its schema does not list; nothing was done.", hint: "Call it again with the argument the error names (the tool's schema lists them all), spelled in snake_case." },
@@ -0,0 +1,5 @@
1
+ export const MCP_COMMAND = { command: "npx", args: ["-y", "@cavelon/cli@0.1", "mcp"] };
2
+ export const INSTALLED_MCP_COMMAND = { command: "cavelon", args: ["mcp"] };
3
+ export function mcpCommand(platform = process.platform) {
4
+ return platform === "win32" ? { command: "cmd", args: ["/c", MCP_COMMAND.command, ...MCP_COMMAND.args] } : MCP_COMMAND;
5
+ }
@@ -0,0 +1,32 @@
1
+ import { promises as fs } from "node:fs";
2
+ import path from "node:path";
3
+ import { CavelonError, ExitCode, usageError } from "./errors.js";
4
+ import { cacheDir, configDir, realPath, within } from "./paths.js";
5
+ export async function solutionDirectory(io, selection) {
6
+ if (selection === undefined)
7
+ return { io };
8
+ if (typeof selection !== "string" || !selection.trim() || selection.includes("\0")) {
9
+ throw usageError("solution_dir must be a nonempty solution folder path.");
10
+ }
11
+ const root = await realPath(io.cwd);
12
+ const directory = await realPath(path.resolve(io.cwd, selection));
13
+ if (!within(root, directory)) {
14
+ throw new CavelonError(ExitCode.usage, {
15
+ code: "path_outside_solution",
16
+ message: `The solution folder ${selection} is outside the MCP workspace ${io.cwd}; nothing was done.`,
17
+ hint: "Select a folder inside the workspace, or start a separate MCP session in that repository.",
18
+ });
19
+ }
20
+ for (const privateDir of [configDir(io.env), cacheDir(io.env)]) {
21
+ if (within(await realPath(path.resolve(io.cwd, privateDir)), directory, true)) {
22
+ throw new CavelonError(ExitCode.usage, {
23
+ code: "path_in_kit_directory",
24
+ message: "solution_dir cannot select cavelon's credential or cache directory; nothing was done.",
25
+ });
26
+ }
27
+ }
28
+ const stat = await fs.stat(directory).catch(() => undefined);
29
+ if (!stat?.isDirectory())
30
+ throw usageError(`The solution folder ${selection} is not an existing directory; nothing was done.`);
31
+ return { io: { ...io, cwd: directory }, selected: selection, directory };
32
+ }
@@ -0,0 +1,21 @@
1
+ import { isDeepStrictEqual } from "node:util";
2
+ import { INSTALLED_MCP_COMMAND, mcpCommand } from "./mcp-command.js";
3
+ export function encodeMcpEntry(command, format, extra = {}) {
4
+ return format === "command-array" ? { ...extra, command: [command.command, ...command.args] } : { ...extra, command: command.command, args: command.args };
5
+ }
6
+ export function decodeMcpEntry(value, format) {
7
+ if (!value || typeof value !== "object" || Array.isArray(value))
8
+ return undefined;
9
+ const entry = value;
10
+ const words = format === "command-array" ? entry.command : [entry.command, ...(Array.isArray(entry.args) ? entry.args : [])];
11
+ if (format === "command-args" && !Array.isArray(entry.args))
12
+ return undefined;
13
+ if (!Array.isArray(words) || !words.length || !words.every(word => typeof word === "string") || !words[0])
14
+ return undefined;
15
+ return { command: words[0], args: words.slice(1) };
16
+ }
17
+ export function isKitMcpEntry(value, format, extra = {}) {
18
+ if (!value || typeof value !== "object" || Array.isArray(value))
19
+ return false;
20
+ return [INSTALLED_MCP_COMMAND, mcpCommand("linux"), mcpCommand("win32")].some(command => isDeepStrictEqual(encodeMcpEntry(command, format, extra), value));
21
+ }