@cavelon/cli 0.1.2 → 0.1.3

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.
@@ -0,0 +1,544 @@
1
+ import { promises as fs } from "node:fs";
2
+ import path from "node:path";
3
+ import { bundledSkills, generatedCopy, INSTALLED_MCP_COMMAND, mcpCommand } from "./agents.js";
4
+ import { readTextFile, writeFileAtomic } from "./fsutil.js";
5
+ import { findProgram } from "./git.js";
6
+ import { isGenerated, removeBlock, removeJsonEntry, upsertBlock, upsertJsonEntry } from "./markers.js";
7
+ import { homeDir } from "./paths.js";
8
+ import { runProgram } from "./run-program.js";
9
+ export const MARKETPLACE_SOURCE = "goodguys-gmbh/cavelon-dev-kit";
10
+ export const MARKETPLACE = "cavelon-dev-kit";
11
+ export const PLUGIN_ID = "cavelon@cavelon-dev-kit";
12
+ function vscodeUserDir(env, platform) {
13
+ const home = homeDir(env);
14
+ if (platform === "win32")
15
+ return path.join(env.APPDATA || path.join(home, "AppData", "Roaming"), "Code", "User");
16
+ if (platform === "darwin")
17
+ return path.join(home, "Library", "Application Support", "Code", "User");
18
+ return path.join(env.XDG_CONFIG_HOME || path.join(home, ".config"), "Code", "User");
19
+ }
20
+ const json = (file, key = "mcpServers", extra = {}) => ({ file, format: "json", keys: [key, "cavelon"], extra });
21
+ export function setupAgents(env, platform = process.platform) {
22
+ const home = homeDir(env);
23
+ const claudeDir = env.CLAUDE_CONFIG_DIR || path.join(home, ".claude");
24
+ const codexDir = env.CODEX_HOME || path.join(home, ".codex");
25
+ const geminiDir = path.join(env.GEMINI_CLI_HOME || home, ".gemini");
26
+ const vscode = vscodeUserDir(env, platform);
27
+ return [
28
+ {
29
+ name: "claude",
30
+ label: "Claude Code",
31
+ commands: ["claude"],
32
+ folders: [claudeDir],
33
+ plugin: "claude",
34
+ mcp: json(env.CLAUDE_CONFIG_DIR ? path.join(env.CLAUDE_CONFIG_DIR, ".claude.json") : path.join(home, ".claude.json")),
35
+ skills: path.join(claudeDir, "skills"),
36
+ },
37
+ {
38
+ name: "codex",
39
+ label: "Codex",
40
+ commands: ["codex"],
41
+ folders: [codexDir],
42
+ plugin: "codex",
43
+ mcp: { file: path.join(codexDir, "config.toml"), format: "toml" },
44
+ skills: path.join(home, ".agents", "skills"),
45
+ },
46
+ {
47
+ name: "cursor",
48
+ label: "Cursor",
49
+ commands: ["cursor", "cursor-agent"],
50
+ folders: [path.join(home, ".cursor")],
51
+ mcp: json(path.join(home, ".cursor", "mcp.json")),
52
+ skills: path.join(home, ".cursor", "skills"),
53
+ },
54
+ {
55
+ name: "copilot",
56
+ label: "VS Code with GitHub Copilot",
57
+ commands: ["code"],
58
+ folders: [vscode],
59
+ mcp: json(path.join(vscode, "mcp.json"), "servers", { type: "stdio" }),
60
+ skills: path.join(home, ".copilot", "skills"),
61
+ },
62
+ {
63
+ name: "gemini",
64
+ label: "Gemini CLI",
65
+ commands: ["gemini"],
66
+ folders: [geminiDir],
67
+ mcp: json(path.join(geminiDir, "settings.json")),
68
+ skills: path.join(geminiDir, "skills"),
69
+ },
70
+ {
71
+ name: "kiro",
72
+ label: "Kiro",
73
+ commands: ["kiro", "kiro-cli"],
74
+ folders: [path.join(home, ".kiro")],
75
+ mcp: json(path.join(home, ".kiro", "settings", "mcp.json")),
76
+ skills: path.join(home, ".kiro", "skills"),
77
+ },
78
+ ];
79
+ }
80
+ const ALIASES = { "claude-code": "claude", vscode: "copilot", "vs-code": "copilot", "gemini-cli": "gemini", "cursor-agent": "cursor" };
81
+ export function agentByName(agents, raw) {
82
+ const name = raw.trim().toLowerCase();
83
+ return agents.find((a) => a.name === (ALIASES[name] ?? name));
84
+ }
85
+ const WINDOWS_EXTENSIONS = [".exe", ".cmd", ".bat"];
86
+ export async function findAgent(agent, env, platform = process.platform) {
87
+ const found = {};
88
+ for (const command of agent.commands) {
89
+ found.program = await findProgram(command, env, platform, WINDOWS_EXTENSIONS);
90
+ if (found.program)
91
+ break;
92
+ }
93
+ for (const folder of agent.folders) {
94
+ if (await isDirectory(folder)) {
95
+ found.folder = folder;
96
+ break;
97
+ }
98
+ }
99
+ return found;
100
+ }
101
+ async function isDirectory(dir) {
102
+ return fs.stat(dir).then((st) => st.isDirectory(), () => false);
103
+ }
104
+ export async function serverCommand(env, platform = process.platform) {
105
+ return (await findProgram("cavelon", env, platform, [".exe"])) ? INSTALLED_MCP_COMMAND : mcpCommand(platform);
106
+ }
107
+ function knownCommands() {
108
+ return [INSTALLED_MCP_COMMAND, mcpCommand("linux"), mcpCommand("win32")];
109
+ }
110
+ function jsonEntry(mcp, command) {
111
+ return { ...mcp.extra, command: command.command, args: command.args };
112
+ }
113
+ function isOwnJsonEntry(mcp, value) {
114
+ return knownCommands().some((c) => JSON.stringify(jsonEntry(mcp, c)) === JSON.stringify(value));
115
+ }
116
+ function tomlBlock(command) {
117
+ return ["[mcp_servers.cavelon]", `command = ${JSON.stringify(command.command)}`, `args = [${command.args.map((a) => JSON.stringify(a)).join(", ")}]`].join("\n");
118
+ }
119
+ function hasOwnTomlServer(text) {
120
+ let inBlock = false;
121
+ for (const line of text.split(/\r?\n/)) {
122
+ const trimmed = line.trim();
123
+ if (trimmed === "# cavelon:begin")
124
+ inBlock = true;
125
+ else if (trimmed === "# cavelon:end")
126
+ inBlock = false;
127
+ else if (!inBlock && /^\[\s*mcp_servers\s*\.\s*"?cavelon"?\s*\]/.test(trimmed))
128
+ return true;
129
+ }
130
+ return false;
131
+ }
132
+ const RUN_TIMEOUT_MS = 180_000;
133
+ const LIST_TIMEOUT_MS = 60_000;
134
+ function display(program, args) {
135
+ return [path.basename(program).replace(/\.(exe|cmd|bat)$/i, ""), ...args].join(" ");
136
+ }
137
+ async function pluginState(kind, program, env) {
138
+ const read = async (args) => {
139
+ const result = await runProgram(program, args, { env, timeoutMs: LIST_TIMEOUT_MS });
140
+ if (result.code !== 0)
141
+ return { error: result.error ?? `\`${display(program, args)}\` failed: ${firstLine(result.stderr || result.stdout)}` };
142
+ try {
143
+ return { value: JSON.parse(result.stdout) };
144
+ }
145
+ catch {
146
+ return { error: `\`${display(program, args)}\` did not answer in JSON` };
147
+ }
148
+ };
149
+ const plugins = await read(["plugin", "list", "--json"]);
150
+ if ("error" in plugins)
151
+ return { error: plugins.error };
152
+ const markets = await read(["plugin", "marketplace", "list", "--json"]);
153
+ if ("error" in markets)
154
+ return { error: markets.error };
155
+ if (kind === "claude") {
156
+ const list = Array.isArray(plugins.value) ? plugins.value : [];
157
+ const mine = list.find((p) => p.id === PLUGIN_ID && p.scope === "user");
158
+ const names = Array.isArray(markets.value) ? markets.value.map((m) => m.name) : [];
159
+ return { marketplace: names.includes(MARKETPLACE), installed: Boolean(mine), enabled: mine?.enabled !== false };
160
+ }
161
+ const installed = (plugins.value?.installed ?? []).find((p) => p.pluginId === PLUGIN_ID && p.installed !== false);
162
+ const names = (markets.value?.marketplaces ?? []).map((m) => m.name);
163
+ return { marketplace: names.includes(MARKETPLACE), installed: Boolean(installed), enabled: installed?.enabled !== false };
164
+ }
165
+ function firstLine(text) {
166
+ return (text.split(/\r?\n/).find((l) => l.trim()) ?? "").trim().slice(0, 300);
167
+ }
168
+ function pluginCommands(kind) {
169
+ return {
170
+ marketplaceAdd: ["plugin", "marketplace", "add", MARKETPLACE_SOURCE],
171
+ marketplaceRemove: ["plugin", "marketplace", "remove", MARKETPLACE],
172
+ install: kind === "claude" ? ["plugin", "install", PLUGIN_ID, "--scope", "user"] : ["plugin", "add", PLUGIN_ID],
173
+ uninstall: kind === "claude" ? ["plugin", "uninstall", PLUGIN_ID, "--scope", "user"] : ["plugin", "remove", PLUGIN_ID],
174
+ };
175
+ }
176
+ export async function planAgent(agent, found, env, command, skills, platform = process.platform) {
177
+ const usePlugin = Boolean(agent.plugin && found.program);
178
+ const plan = { agent, found, method: usePlugin ? "plugin" : "files", changes: [] };
179
+ if (usePlugin) {
180
+ const kind = agent.plugin;
181
+ const program = found.program;
182
+ const commands = pluginCommands(kind);
183
+ const state = await pluginState(kind, program, env);
184
+ if ("error" in state) {
185
+ plan.changes.push({ kind: "plugin", summary: "install the Cavelon plugin", target: display(program, commands.install), outcome: "failed", reason: state.error });
186
+ return plan;
187
+ }
188
+ plan.plugin = state;
189
+ if (!state.marketplace) {
190
+ plan.changes.push({ kind: "marketplace", summary: "add the Cavelon plugin marketplace", target: display(program, commands.marketplaceAdd), outcome: "planned" });
191
+ }
192
+ plan.changes.push({
193
+ kind: "plugin",
194
+ summary: "install the Cavelon plugin (skills and tools)",
195
+ target: display(program, commands.install),
196
+ outcome: state.installed ? "unchanged" : "planned",
197
+ ...(state.installed && !state.enabled ? { reason: `it is installed but turned off; turn it on in ${agent.label}` } : {}),
198
+ });
199
+ }
200
+ if (!usePlugin || platform === "win32")
201
+ plan.changes.push(await mcpChange(agent.mcp, command, false));
202
+ if (!usePlugin)
203
+ plan.changes.push(await skillsChange(agent.skills, skills, false));
204
+ return plan;
205
+ }
206
+ async function mcpChange(mcp, command, apply, state) {
207
+ const summary = 'add the "cavelon" tools server to';
208
+ const existing = await readTextFile(mcp.file);
209
+ let result;
210
+ if (mcp.format === "json") {
211
+ let current;
212
+ try {
213
+ current = existing ? mcp.keys.reduce((node, key) => (node && typeof node === "object" ? node[key] : undefined), JSON.parse(existing)) : undefined;
214
+ }
215
+ catch {
216
+ current = undefined;
217
+ }
218
+ if (current !== undefined && !isOwnJsonEntry(mcp, current)) {
219
+ return { kind: "mcp", summary, target: mcp.file, outcome: "skipped", reason: `it already has a "cavelon" server of its own; left as it is` };
220
+ }
221
+ result = upsertJsonEntry(existing, mcp.keys, jsonEntry(mcp, command));
222
+ if (result.outcome === "skipped")
223
+ result.reason = `${result.reason}; add "${mcp.keys.join(".")}": ${JSON.stringify(jsonEntry(mcp, command))} yourself`;
224
+ }
225
+ else {
226
+ if (existing !== undefined && hasOwnTomlServer(existing)) {
227
+ return { kind: "mcp", summary, target: mcp.file, outcome: "skipped", reason: "it already has an [mcp_servers.cavelon] table of its own; left as it is" };
228
+ }
229
+ result = upsertBlock(existing, tomlBlock(command), "hash");
230
+ }
231
+ if (result.outcome === "unchanged")
232
+ return { kind: "mcp", summary, target: mcp.file, outcome: "unchanged" };
233
+ if (result.outcome === "skipped")
234
+ return { kind: "mcp", summary, target: mcp.file, outcome: "skipped", reason: result.reason };
235
+ if (!apply)
236
+ return { kind: "mcp", summary: result.outcome === "updated" ? 'update the "cavelon" tools server in' : summary, target: mcp.file, outcome: "planned" };
237
+ const createdDir = await topmostMissing(path.dirname(mcp.file));
238
+ await writeKeepingMode(mcp.file, result.content);
239
+ if (state && !state.mcp) {
240
+ state.mcp = {
241
+ file: mcp.file,
242
+ created: existing === undefined,
243
+ ...(mcp.format === "json" ? { kept: existing ? keptDepth(existing, mcp.keys) : 0 } : {}),
244
+ ...(createdDir ? { created_dir: createdDir } : {}),
245
+ };
246
+ }
247
+ return { kind: "mcp", summary, target: mcp.file, outcome: "done" };
248
+ }
249
+ function keptDepth(text, keys) {
250
+ let node;
251
+ try {
252
+ node = JSON.parse(text);
253
+ }
254
+ catch {
255
+ return keys.length;
256
+ }
257
+ let depth = 0;
258
+ for (const key of keys.slice(0, -1)) {
259
+ if (!node || typeof node !== "object" || !(key in node))
260
+ break;
261
+ node = node[key];
262
+ depth++;
263
+ }
264
+ return depth;
265
+ }
266
+ async function writeKeepingMode(file, content) {
267
+ const target = await fs.realpath(file).catch(() => file);
268
+ const mode = await fs.stat(target).then((st) => st.mode & 0o777, () => 0o600);
269
+ await writeFileAtomic(target, content, mode, 0o700);
270
+ }
271
+ async function skillsChange(dir, skills, apply, state) {
272
+ const summary = `copy the ${skills.length} Cavelon skills to`;
273
+ const target = dir + path.sep;
274
+ const createdDir = await topmostMissing(dir);
275
+ let changed = 0;
276
+ const foreign = [];
277
+ for (const skill of skills) {
278
+ for (const file of skill.files) {
279
+ const full = path.join(dir, skill.name, ...file.path.split("/"));
280
+ const content = generatedCopy(file, "setup");
281
+ const existing = await readTextFile(full);
282
+ if (existing === content)
283
+ continue;
284
+ if (existing !== undefined && !isGenerated(existing)) {
285
+ foreign.push(`${skill.name}/${file.path}`);
286
+ continue;
287
+ }
288
+ changed++;
289
+ if (apply)
290
+ await writeFileAtomic(full, content);
291
+ }
292
+ }
293
+ if (apply && changed && state && !state.skills)
294
+ state.skills = { dir, ...(createdDir ? { created_dir: createdDir } : {}) };
295
+ const reason = foreign.length ? `${foreign.join(", ")} ${foreign.length === 1 ? "is" : "are"} not cavelon's; left as ${foreign.length === 1 ? "it is" : "they are"}` : undefined;
296
+ if (!changed)
297
+ return { kind: "skills", summary, target, outcome: foreign.length ? "skipped" : "unchanged", ...(reason ? { reason } : {}) };
298
+ return { kind: "skills", summary, target, outcome: apply ? "done" : "planned", ...(reason ? { reason } : {}) };
299
+ }
300
+ export async function applyPlan(plan, env, command, skills, record) {
301
+ const done = [];
302
+ for (const change of plan.changes) {
303
+ if (change.outcome !== "planned") {
304
+ done.push(change);
305
+ continue;
306
+ }
307
+ try {
308
+ if (change.kind === "marketplace" || change.kind === "plugin") {
309
+ const commands = pluginCommands(plan.agent.plugin);
310
+ const args = change.kind === "marketplace" ? commands.marketplaceAdd : commands.install;
311
+ const result = await runProgram(plan.found.program, args, { env, timeoutMs: RUN_TIMEOUT_MS });
312
+ if (result.code !== 0) {
313
+ done.push({ ...change, outcome: "failed", reason: result.error ?? firstLine(result.stderr || result.stdout) ?? `exit ${result.code}` });
314
+ break;
315
+ }
316
+ if (change.kind === "marketplace")
317
+ record.marketplace_added = true;
318
+ else
319
+ record.plugin_installed = true;
320
+ done.push({ ...change, outcome: "done" });
321
+ }
322
+ else if (change.kind === "mcp") {
323
+ done.push(await mcpChange(plan.agent.mcp, command, true, record));
324
+ }
325
+ else {
326
+ done.push(await skillsChange(plan.agent.skills, skills, true, record));
327
+ }
328
+ }
329
+ catch (error) {
330
+ done.push({ ...change, outcome: "failed", reason: error instanceof Error ? error.message : String(error) });
331
+ break;
332
+ }
333
+ }
334
+ return done;
335
+ }
336
+ export async function removeAgent(agent, record, env, skills, sharedSkillDirs) {
337
+ const changes = [];
338
+ if (record.plugin_installed || record.marketplace_added) {
339
+ const found = await findAgent(agent, env);
340
+ const commands = pluginCommands(agent.plugin);
341
+ const steps = [];
342
+ if (record.plugin_installed)
343
+ steps.push(["plugin", commands.uninstall, "uninstall the Cavelon plugin", "plugin_installed"]);
344
+ if (record.marketplace_added)
345
+ steps.push(["marketplace", commands.marketplaceRemove, "remove the Cavelon plugin marketplace", "marketplace_added"]);
346
+ for (const [kind, args, summary, key] of steps) {
347
+ if (!found.program) {
348
+ changes.push({ kind, summary, target: [agent.commands[0], ...args].join(" "), outcome: "failed", reason: `${agent.commands[0]} is not on the PATH; run it yourself` });
349
+ continue;
350
+ }
351
+ const result = await runProgram(found.program, args, { env, timeoutMs: RUN_TIMEOUT_MS });
352
+ if (result.code === 0) {
353
+ delete record[key];
354
+ changes.push({ kind, summary, target: display(found.program, args), outcome: "removed" });
355
+ }
356
+ else {
357
+ changes.push({ kind, summary, target: display(found.program, args), outcome: "failed", reason: result.error ?? firstLine(result.stderr || result.stdout) });
358
+ }
359
+ }
360
+ }
361
+ if (record.mcp) {
362
+ const change = await removeMcp(agent.mcp, record.mcp);
363
+ if (change.outcome !== "failed" && change.outcome !== "skipped")
364
+ delete record.mcp;
365
+ changes.push(change);
366
+ }
367
+ if (record.skills) {
368
+ const change = await removeSkills(record.skills, skills, sharedSkillDirs.has(record.skills.dir));
369
+ delete record.skills;
370
+ changes.push(change);
371
+ }
372
+ return changes;
373
+ }
374
+ async function removeMcp(mcp, record) {
375
+ const summary = 'remove the "cavelon" tools server from';
376
+ const existing = await readTextFile(mcp.file);
377
+ if (existing === undefined)
378
+ return { kind: "mcp", summary, target: mcp.file, outcome: "unchanged" };
379
+ const result = mcp.format === "json"
380
+ ? removeJsonEntry(existing, mcp.keys, (value) => isOwnJsonEntry(mcp, value), record.kept ?? mcp.keys.length - 1)
381
+ : removeBlock(existing, "hash");
382
+ if (result.outcome === "unchanged")
383
+ return { kind: "mcp", summary, target: mcp.file, outcome: "unchanged" };
384
+ if (result.outcome === "skipped")
385
+ return { kind: "mcp", summary, target: mcp.file, outcome: "skipped", reason: result.reason };
386
+ if (result.empty && record.created) {
387
+ await fs.rm(mcp.file, { force: true });
388
+ if (record.created_dir)
389
+ await removeEmptyDirs(path.dirname(mcp.file), record.created_dir);
390
+ }
391
+ else {
392
+ await writeKeepingMode(mcp.file, result.content);
393
+ }
394
+ return { kind: "mcp", summary, target: mcp.file, outcome: "removed" };
395
+ }
396
+ async function removeSkills(record, skills, stillUsed) {
397
+ const summary = "remove the Cavelon skills from";
398
+ const target = record.dir + path.sep;
399
+ if (stillUsed)
400
+ return { kind: "skills", summary, target, outcome: "unchanged", reason: "another agent set up by cavelon still uses them" };
401
+ let removed = 0;
402
+ for (const skill of skills) {
403
+ const folder = path.join(record.dir, skill.name);
404
+ for (const file of skill.files) {
405
+ const full = path.join(folder, ...file.path.split("/"));
406
+ if (isGenerated(await readTextFile(full).catch(() => undefined))) {
407
+ await fs.rm(full, { force: true });
408
+ removed++;
409
+ }
410
+ }
411
+ await fs.rmdir(folder).catch(() => undefined);
412
+ }
413
+ if (record.created_dir)
414
+ await removeEmptyDirs(record.dir, record.created_dir);
415
+ return { kind: "skills", summary, target, outcome: removed ? "removed" : "unchanged" };
416
+ }
417
+ async function removeEmptyDirs(dir, top) {
418
+ const last = path.resolve(top);
419
+ let current = path.resolve(dir);
420
+ while (current.startsWith(last)) {
421
+ try {
422
+ await fs.rmdir(current);
423
+ }
424
+ catch {
425
+ return;
426
+ }
427
+ if (current === last)
428
+ return;
429
+ current = path.dirname(current);
430
+ }
431
+ }
432
+ async function topmostMissing(dir) {
433
+ let missing;
434
+ let current = path.resolve(dir);
435
+ while (!(await fs.stat(current).then(() => true, () => false))) {
436
+ missing = current;
437
+ const parent = path.dirname(current);
438
+ if (parent === current)
439
+ break;
440
+ current = parent;
441
+ }
442
+ return missing;
443
+ }
444
+ export async function checkAgent(agent, env, record, platform = process.platform) {
445
+ const found = await findAgent(agent, env, platform);
446
+ const check = { name: agent.name, label: agent.label, found: Boolean(found.program || found.folder), method: null, ok: true, details: [], servers: [] };
447
+ if (agent.plugin && found.program) {
448
+ check.method = "plugin";
449
+ const state = await pluginState(agent.plugin, found.program, env);
450
+ if ("error" in state) {
451
+ check.ok = false;
452
+ check.details.push(`could not ask ${agent.label} about its plugins: ${state.error}`);
453
+ }
454
+ else if (!state.installed) {
455
+ check.ok = false;
456
+ check.details.push("the Cavelon plugin is not installed");
457
+ }
458
+ else if (!state.enabled) {
459
+ check.ok = false;
460
+ check.details.push(`the Cavelon plugin is installed but turned off; turn it on in ${agent.label}`);
461
+ }
462
+ else {
463
+ check.details.push("the Cavelon plugin is installed");
464
+ if (platform !== "win32")
465
+ check.servers.push(await serverCommand(env, platform));
466
+ }
467
+ if (platform !== "win32")
468
+ return check;
469
+ }
470
+ else {
471
+ check.method = "files";
472
+ }
473
+ const entry = await readEntry(agent.mcp);
474
+ if (entry.server) {
475
+ check.details.push(`the "cavelon" tools server is in ${agent.mcp.file}`);
476
+ check.servers.push(entry.server);
477
+ }
478
+ else {
479
+ check.ok = false;
480
+ check.details.push(entry.problem ?? `${agent.mcp.file} has no "cavelon" tools server`);
481
+ }
482
+ if (check.method === "files") {
483
+ const missing = [];
484
+ for (const skill of await bundledSkills()) {
485
+ if ((await readTextFile(path.join(agent.skills, skill.name, "SKILL.md"))) === undefined)
486
+ missing.push(skill.name);
487
+ }
488
+ if (missing.length) {
489
+ check.ok = false;
490
+ check.details.push(`skills missing in ${agent.skills}: ${missing.join(", ")}`);
491
+ }
492
+ else {
493
+ check.details.push(`the Cavelon skills are in ${agent.skills}`);
494
+ }
495
+ }
496
+ if (!record && !check.found)
497
+ check.ok = false;
498
+ return check;
499
+ }
500
+ async function readEntry(mcp) {
501
+ const text = await readTextFile(mcp.file);
502
+ if (text === undefined)
503
+ return { problem: `${mcp.file} does not exist` };
504
+ if (mcp.format === "toml") {
505
+ const lines = text.split(/\r?\n/);
506
+ const start = lines.findIndex((l) => /^\[\s*mcp_servers\s*\.\s*"?cavelon"?\s*\]/.test(l.trim()));
507
+ if (start < 0)
508
+ return { problem: `${mcp.file} has no [mcp_servers.cavelon]` };
509
+ const value = (key) => {
510
+ for (const line of lines.slice(start + 1)) {
511
+ const trimmed = line.trim();
512
+ if (trimmed.startsWith("["))
513
+ break;
514
+ const equals = trimmed.indexOf("=");
515
+ if (equals > 0 && trimmed.slice(0, equals).trim() === key)
516
+ return trimmed.slice(equals + 1).trim();
517
+ }
518
+ return undefined;
519
+ };
520
+ try {
521
+ const command = JSON.parse(value("command") ?? "null");
522
+ const args = JSON.parse(value("args") ?? "[]");
523
+ if (typeof command === "string" && Array.isArray(args))
524
+ return { server: { command, args: args.map(String) } };
525
+ }
526
+ catch {
527
+ }
528
+ return { problem: `the [mcp_servers.cavelon] table in ${mcp.file} is not in a form setup can read` };
529
+ }
530
+ let value;
531
+ try {
532
+ value = mcp.keys.reduce((node, key) => (node && typeof node === "object" ? node[key] : undefined), JSON.parse(text));
533
+ }
534
+ catch {
535
+ return { problem: `${mcp.file} is not plain JSON, so setup cannot read it` };
536
+ }
537
+ const entry = value;
538
+ if (!entry || typeof entry.command !== "string")
539
+ return { problem: `${mcp.file} has no "cavelon" tools server` };
540
+ return { server: { command: entry.command, args: Array.isArray(entry.args) ? entry.args.map(String) : [] } };
541
+ }
542
+ export async function loadSkills() {
543
+ return bundledSkills();
544
+ }
@@ -38,12 +38,17 @@ use it when you parse the result.
38
38
  or tell the person who to ask instead of working around it. `cavelon status`
39
39
  says when a quota is close to full.
40
40
  - No `cavelon.yaml` here or above: for a new solution run
41
- `cavelon init --instance <url> --tenant <tenant> --harness <slug>`; for an
42
- existing one add `cavelon pull --harness <slug>` after it. To start from a
43
- package file (a blueprint, an export from another instance), run
41
+ `cavelon init --instance <url> --tenant <tenant> --harness <solution>`, where
42
+ the tenant and the solution are each a name, slug or id; for an existing one
43
+ add `cavelon pull` after it. To start from a package file (a blueprint, an
44
+ export from another instance), run
44
45
  `cavelon init --instance <url> --tenant <tenant> --from <file>` instead of
45
- splitting it by hand or importing it in the Admin. Ask the person for the
46
- instance and tenant if you do not know them; do not guess.
46
+ splitting it by hand or importing it in the Admin. Never guess a tenant or a
47
+ solution, and never ask the person for an id they would have to look up:
48
+ `cavelon tenant list --json` and `cavelon harness list --json` list the
49
+ names, slugs and ids to choose from, and the person names one by its name.
50
+ In their own terminal, a plain `cavelon init` asks them. Ask for the instance
51
+ URL if you do not know it.
47
52
 
48
53
  ## The loop
49
54
 
@@ -55,7 +60,7 @@ use it when you parse the result.
55
60
  (one file per test suite). See the cavelon-authoring skill.
56
61
  3. **Validate** offline: `cavelon validate`. Fix every error; `cavelon explain
57
62
  <code>` says what a code means and how to fix it.
58
- 4. **Preview**: `cavelon apply --env test` (or `--harness <slug>`). Nothing is
63
+ 4. **Preview**: `cavelon apply --env test` (or `--harness <name or slug>`). Nothing is
59
64
  imported yet. Read the preview: what is created, updated or deleted, which
60
65
  active solutions it reaches, what the target still needs (variables and
61
66
  secrets with the command that sets each, OAuth grants, runtime bindings,
@@ -93,5 +93,5 @@ Change one thing at a time, then run the same suite again and compare:
93
93
  a smaller model or fewer tool rounds often suffice for a step.
94
94
 
95
95
  Record why a change helped in the commit message. When every suite passes,
96
- `cavelon activate --harness <slug>` goes through the readiness gate; if the
96
+ `cavelon activate --harness <name or slug>` goes through the readiness gate; if the
97
97
  token may not activate, a person activates in the Admin.
@@ -0,0 +1,93 @@
1
+ import { closest, displayName, MAX_LISTED, pick } from "./choose.js";
2
+ import { CavelonError, ExitCode } from "./errors.js";
3
+ import { readTenantless } from "./principal.js";
4
+ import { canAsk } from "./prompt.js";
5
+ import { cavelonCommand } from "./shell.js";
6
+ export function listsTenants(tenantless) {
7
+ return Boolean(tenantless && !tenantless.refused && tenantless.tenants);
8
+ }
9
+ export function tenantRef(tenant) {
10
+ return tenant.slug ?? tenant.id;
11
+ }
12
+ export function tenantTitle(tenant) {
13
+ const names = [tenant.slug && tenant.slug !== tenant.name ? tenant.slug : undefined, tenant.id].filter(Boolean).join(", ");
14
+ return tenant.name ? `${tenant.name} (${names})` : tenant.slug ? `${tenant.slug} (${tenant.id})` : tenant.id;
15
+ }
16
+ export async function searchTenants(client, text) {
17
+ const found = await readTenantless(client, { search: text });
18
+ return found && !found.refused ? (found.tenants ?? []) : [];
19
+ }
20
+ export async function chooseTenant(ctx, client, reach) {
21
+ const { tenants, reachesAll } = reach;
22
+ if (!reachesAll && tenants.length === 1)
23
+ return { kind: "chosen", tenant: tenants[0], how: "only" };
24
+ if (!reachesAll && tenants.length === 0)
25
+ return { kind: "none" };
26
+ if (!canAsk(ctx))
27
+ return { kind: "open" };
28
+ const intro = reachesAll
29
+ ? `This token reaches every tenant on ${client.url}.${tenants.length ? " Yours:" : ""}`
30
+ : `This token reaches ${tenants.length} tenants on ${client.url}:`;
31
+ const picked = await pick(ctx, {
32
+ intro,
33
+ question: "Which tenant?",
34
+ items: tenants,
35
+ extra: (t) => t.role ?? undefined,
36
+ preferred: tenants.find((t) => t.is_default),
37
+ search: reachesAll ? (text) => searchTenants(client, text) : undefined,
38
+ });
39
+ if (!("item" in picked))
40
+ throw new Error("unreachable: the tenant list offers no other entry");
41
+ return { kind: "chosen", tenant: picked.item, how: "picked" };
42
+ }
43
+ export function commandLines(tenants, command) {
44
+ const shown = tenants.slice(0, MAX_LISTED).map((t) => ({ text: command(tenantRef(t)), name: t.name && t.name !== t.slug ? t.name : "" }));
45
+ const width = Math.max(...shown.map((s) => s.text.length));
46
+ const lines = shown.map((s) => ` ${s.name ? `${s.text.padEnd(width)} ${s.name}` : s.text}`);
47
+ if (tenants.length > shown.length)
48
+ lines.push(` … and ${tenants.length - shown.length} more (\`cavelon tenant list\` lists them)`);
49
+ return lines.join("\n");
50
+ }
51
+ export function choicesOf(tenants, command) {
52
+ return tenants.map((t) => ({ id: t.id, slug: t.slug, name: t.name, role: t.role, is_default: t.is_default, command: command(tenantRef(t)) }));
53
+ }
54
+ export function tenantOpenError(url, reach, lead, command = { line: (ref) => cavelonCommand("use", ref), template: "cavelon use <name or slug>" }) {
55
+ const { tenants, reachesAll } = reach;
56
+ const what = reachesAll ? "every tenant" : `${tenants.length} tenants`;
57
+ const lines = tenants.length ? `Run the line for the tenant you want:\n${commandLines(tenants, command.line)}` : "";
58
+ const search = reachesAll
59
+ ? `${lines ? "\nAny other tenant: " : "Choose one: "}\`${command.template}\`; \`cavelon tenant list --search <part of the name>\` finds its slug.`
60
+ : "";
61
+ return new CavelonError(ExitCode.usage, {
62
+ code: "tenant_required",
63
+ message: `${lead}This token reaches ${what} on ${url}, and there is no terminal to ask which one to use.`,
64
+ hint: `${lines}${search}`,
65
+ details: { tenants: choicesOf(tenants, command.line), reaches_all_tenants: reachesAll },
66
+ });
67
+ }
68
+ export function noTenantError(url, atLogin = true) {
69
+ return new CavelonError(ExitCode.unauthorized, {
70
+ code: "no_tenant_reached",
71
+ message: `This token reaches no tenant on ${url}${atLogin ? ", so nothing was stored" : ""}.`,
72
+ hint: `Open ${url}/account/access-tokens, create a token for the tenant you work in (or ask a tenant administrator to add you to one), ` +
73
+ "then run `cavelon login` again with the new token.",
74
+ });
75
+ }
76
+ export function tenantMissError(ref, pool, reachesAll, from) {
77
+ const near = closest(pool, ref);
78
+ const listed = near.length ? near : pool.slice(0, MAX_LISTED);
79
+ const label = near.length ? "Closest" : "This token reaches";
80
+ const names = listed.map(displayName).join(", ");
81
+ const hints = [];
82
+ if (listed.length)
83
+ hints.push(`Run the line for the tenant you mean:\n${commandLines(listed, (r) => cavelonCommand("use", r))}`);
84
+ hints.push(reachesAll
85
+ ? "This token reaches every tenant: `cavelon tenant list --search <part of the name>` finds one."
86
+ : "`cavelon tenant list` shows the tenants this token reaches with name, slug and id; `cavelon use` alone lets you choose.");
87
+ return new CavelonError(ExitCode.failure, {
88
+ code: "tenant_not_found",
89
+ message: `No tenant "${ref}" that this token reaches${from ? ` (from ${from})` : ""}.${names ? ` ${label}: ${names}.` : ""}`,
90
+ hint: hints.join("\n"),
91
+ details: { tenants: listed.map((t) => ({ id: t.id, slug: t.slug, name: t.name })) },
92
+ });
93
+ }