@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,426 @@
1
+ import { promises as fs } from "node:fs";
2
+ import path from "node:path";
3
+ import { boolOption, listOption } from "../command.js";
4
+ import { createContext } from "../context.js";
5
+ import { asCavelonError, CavelonError, ExitCode, usageError } from "../errors.js";
6
+ import { readJsonFile, writeFileAtomic } from "../fsutil.js";
7
+ import { configDir } from "../paths.js";
8
+ import { canAsk, readLine } from "../prompt.js";
9
+ import { probeMcpServer } from "../run-program.js";
10
+ import { cavelonCommand } from "../shell.js";
11
+ import { agentByName, applyPlan, checkAgent, findAgent, loadSkills, planAgent, removeAgent, serverCommand, setupAgents, } from "../setup-agents.js";
12
+ import { KIT_VERSION } from "../version.js";
13
+ import { login, whoami } from "./session.js";
14
+ const PROBE_TIMEOUT_MS = 120_000;
15
+ const EXAMPLE_BRIEF = "Build a Cavelon solution that answers our customers' questions from the FAQ pages in ./faq, and test it.";
16
+ function statePath(env) {
17
+ return path.join(configDir(env), "setup.json");
18
+ }
19
+ async function loadState(env) {
20
+ const raw = await readJsonFile(statePath(env));
21
+ return { agents: raw?.agents && typeof raw.agents === "object" ? raw.agents : {} };
22
+ }
23
+ async function saveState(env, state) {
24
+ for (const [name, record] of Object.entries(state.agents))
25
+ if (!Object.keys(record).length)
26
+ delete state.agents[name];
27
+ if (!Object.keys(state.agents).length) {
28
+ await fs.rm(statePath(env), { force: true });
29
+ return;
30
+ }
31
+ await writeFileAtomic(statePath(env), JSON.stringify(state, null, 2) + "\n", 0o600, 0o700);
32
+ }
33
+ function namedAgents(input, agents) {
34
+ const names = listOption(input, "agents")
35
+ .flatMap((v) => v.split(","))
36
+ .map((v) => v.trim())
37
+ .filter(Boolean);
38
+ if (names.some((n) => n.toLowerCase() === "all"))
39
+ return agents;
40
+ const out = [];
41
+ for (const name of names) {
42
+ const agent = agentByName(agents, name);
43
+ if (!agent)
44
+ throw usageError(`Unknown agent "${name}".`, `Known: ${agents.map((a) => a.name).join(", ")}.`);
45
+ if (!out.includes(agent))
46
+ out.push(agent);
47
+ }
48
+ return out;
49
+ }
50
+ function changeLine(change) {
51
+ if (change.kind === "plugin" || change.kind === "marketplace")
52
+ return `${change.summary}: runs \`${change.target}\``;
53
+ return `${change.summary} ${change.target}`;
54
+ }
55
+ function outcomeLine(change) {
56
+ const label = {
57
+ planned: "to do",
58
+ done: "done",
59
+ unchanged: "already",
60
+ skipped: "left",
61
+ failed: "failed",
62
+ removed: "removed",
63
+ };
64
+ return ` ${label[change.outcome].padEnd(8)} ${changeLine(change)}${change.reason ? ` (${change.reason})` : ""}`;
65
+ }
66
+ function planJson(plan, changes = plan.changes) {
67
+ return {
68
+ name: plan.agent.name,
69
+ label: plan.agent.label,
70
+ found: { command: plan.found.program ?? null, folder: plan.found.folder ?? null },
71
+ method: plan.method,
72
+ changes: changes.map((c) => ({ kind: c.kind, summary: c.summary, target: c.target, outcome: c.outcome, ...(c.reason ? { reason: c.reason } : {}) })),
73
+ };
74
+ }
75
+ function planText(plans, notFound) {
76
+ const lines = [];
77
+ for (const plan of plans) {
78
+ const todo = plan.changes.filter((c) => c.outcome === "planned");
79
+ const other = plan.changes.filter((c) => c.outcome !== "planned" && c.outcome !== "unchanged");
80
+ if (!todo.length && !other.length) {
81
+ lines.push(` ${plan.agent.label}: already set up.`);
82
+ continue;
83
+ }
84
+ lines.push(` ${plan.agent.label}:`);
85
+ for (const change of todo)
86
+ lines.push(` - ${changeLine(change)}`);
87
+ for (const change of other)
88
+ lines.push(` - not possible: ${changeLine(change)}${change.reason ? ` (${change.reason})` : ""}`);
89
+ }
90
+ if (notFound.length)
91
+ lines.push(` Not found on this computer: ${notFound.map((a) => a.label).join(", ")}.`);
92
+ return lines.join("\n");
93
+ }
94
+ async function confirm(ctx, question, defaultYes) {
95
+ const answer = (await readLine(ctx.io, `${question} ${defaultYes ? "[Y/n]" : "[y/N]"} `, "Cancelled; nothing was changed.")).toLowerCase();
96
+ if (!answer)
97
+ return defaultYes;
98
+ return answer.startsWith("y") || answer.startsWith("j");
99
+ }
100
+ function confirmationRequired(what, details) {
101
+ return new CavelonError(ExitCode.usage, {
102
+ code: "confirmation_required",
103
+ message: `Nothing was changed: ${what}, and there is no terminal to ask.`,
104
+ hint: "Read the plan in details, then run the same command with --yes.",
105
+ details,
106
+ });
107
+ }
108
+ function normalizeAddress(raw) {
109
+ const text = raw.trim();
110
+ if (!text)
111
+ return undefined;
112
+ const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(text) ? text : `https://${text}`;
113
+ try {
114
+ const url = new URL(withScheme);
115
+ if (url.protocol !== "https:" && url.protocol !== "http:")
116
+ return undefined;
117
+ return url.toString();
118
+ }
119
+ catch {
120
+ return undefined;
121
+ }
122
+ }
123
+ async function loginStep(ctx) {
124
+ const session = await ctx.session();
125
+ if (session.url && session.token)
126
+ return { status: "already", instance: session.url, text: `Already logged in to ${session.url}.` };
127
+ if (!canAsk(ctx)) {
128
+ return {
129
+ status: "not_logged_in",
130
+ instance: session.url ?? null,
131
+ next: `Log in from your own terminal: ${cavelonCommand("login", "--instance", session.url ?? "https://cavelon.example.com")}`,
132
+ };
133
+ }
134
+ let url = session.url;
135
+ const err = ctx.io.stderr;
136
+ err.write("\nLog in to Cavelon.\n");
137
+ if (!url) {
138
+ err.write("Your Cavelon address is the one you open Cavelon at in the browser, for example https://cavelon.example.com.\n");
139
+ for (let tries = 0; tries < 3 && !url; tries++) {
140
+ const typed = await readLine(ctx.io, "Cavelon address (Enter to log in later): ", "Cancelled; the agents are set up, logging in is not.");
141
+ if (!typed)
142
+ return { status: "skipped", instance: null, next: `Log in later: ${cavelonCommand("login", "--instance", "https://cavelon.example.com")}` };
143
+ url = normalizeAddress(typed);
144
+ if (!url)
145
+ err.write(`"${typed}" is not a web address. Type it as it shows in the browser's address bar.\n`);
146
+ }
147
+ if (!url)
148
+ return { status: "skipped", instance: null, next: `Log in later: ${cavelonCommand("login", "--instance", "https://cavelon.example.com")}` };
149
+ }
150
+ err.write(`In Cavelon (${url}), open your user menu, then Personal access tokens, then Create token. Copy the token and paste it below.\n` +
151
+ "It is not shown while you paste, and it is kept in your system's credential store, never in a file of your project.\n");
152
+ const sub = createContext(ctx.io, { ...ctx.globals, json: ctx.json, instance: url });
153
+ try {
154
+ const result = await login.run(sub, { positionals: {}, options: {} });
155
+ for (const warning of sub.warnings)
156
+ ctx.warn(warning);
157
+ return { status: "logged_in", instance: url, text: result.text, ...(result.exitCode ? { exitCode: result.exitCode } : {}) };
158
+ }
159
+ catch (error) {
160
+ for (const warning of sub.warnings)
161
+ ctx.warn(warning);
162
+ const err = asCavelonError(error);
163
+ return {
164
+ status: "failed",
165
+ instance: url,
166
+ error: err.toJSON(),
167
+ text: `Not logged in: ${err.message}${err.hint ? `\n ${err.hint}` : ""}`,
168
+ next: `Log in again: ${cavelonCommand("login", "--instance", url)}`,
169
+ exitCode: err.exitCode,
170
+ };
171
+ }
172
+ }
173
+ async function runSetup(ctx, input) {
174
+ const env = ctx.io.env;
175
+ const agents = setupAgents(env);
176
+ const named = namedAgents(input, agents);
177
+ const found = await Promise.all(agents.map(async (agent) => ({ agent, found: await findAgent(agent, env) })));
178
+ const isFound = (f) => Boolean(f.found.program || f.found.folder);
179
+ const chosen = named.length ? found.filter((f) => named.includes(f.agent)) : found.filter(isFound);
180
+ const notFound = named.length ? [] : found.filter((f) => !isFound(f)).map((f) => f.agent);
181
+ const skills = await loadSkills();
182
+ if (!skills.length) {
183
+ 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
+ }
185
+ const command = await serverCommand(env);
186
+ const plans = [];
187
+ for (const { agent, found: where } of chosen)
188
+ plans.push(await planAgent(agent, where, env, command, skills));
189
+ const pending = plans.some((p) => p.changes.some((c) => c.outcome === "planned"));
190
+ let results = plans.map((plan) => ({ plan, changes: plan.changes }));
191
+ let declined = false;
192
+ if (pending) {
193
+ if (!boolOption(input, "yes")) {
194
+ if (!canAsk(ctx)) {
195
+ if (!ctx.json)
196
+ ctx.io.stderr.write(`cavelon setup would change this:\n${planText(plans, notFound)}\n`);
197
+ throw confirmationRequired("setup changes your coding agents' settings only when you agree", { agents: plans.map((p) => planJson(p)), server: command });
198
+ }
199
+ ctx.io.stderr.write(`cavelon setup will change this for you:\n${planText(plans, notFound)}\nNothing else in these files changes, and \`cavelon setup --remove\` undoes it.\n`);
200
+ declined = !(await confirm(ctx, "Make these changes?", true));
201
+ }
202
+ if (!declined) {
203
+ const state = await loadState(env);
204
+ results = [];
205
+ for (const plan of plans) {
206
+ const record = (state.agents[plan.agent.name] ??= {});
207
+ results.push({ plan, changes: await applyPlan(plan, env, command, skills, record) });
208
+ await saveState(env, state);
209
+ }
210
+ }
211
+ }
212
+ const loginReport = declined ? undefined : await loginStep(ctx);
213
+ const failed = results.some((r) => r.changes.some((c) => c.outcome === "failed"));
214
+ const ready = results.filter((r) => r.changes.length && r.changes.every((c) => c.outcome === "done" || c.outcome === "unchanged"));
215
+ const changed = results.filter((r) => r.changes.some((c) => c.outcome === "done"));
216
+ const next = [];
217
+ if (declined)
218
+ next.push("Nothing was changed. Run cavelon setup again when you are ready.");
219
+ else {
220
+ if (loginReport?.next)
221
+ next.push(loginReport.next);
222
+ if (changed.length)
223
+ next.push(`Restart ${joinLabels(changed.map((r) => r.plan.agent.label))} if ${changed.length > 1 ? "they are" : "it is"} open, so ${changed.length > 1 ? "they load" : "it loads"} Cavelon.`);
224
+ if (ready.length) {
225
+ next.push(`Open an empty folder in ${joinLabels(ready.map((r) => r.plan.agent.label), "or")} and describe what to build, for example:`, ` "${EXAMPLE_BRIEF}"`);
226
+ next.push(`Or start a solution yourself in an empty folder: ${cavelonCommand("init")}`);
227
+ }
228
+ else if (!chosen.length) {
229
+ next.push("No coding agent was found. Install one (Claude Code, Codex, Cursor, VS Code with GitHub Copilot, Gemini CLI or Kiro) and run cavelon setup again,", ` or name yours: ${cavelonCommand("setup", "--agents", "cursor")}`);
230
+ }
231
+ }
232
+ const lines = [];
233
+ if (!chosen.length)
234
+ lines.push("No coding agent found on this computer.");
235
+ for (const { plan, changes } of results) {
236
+ lines.push(`${plan.agent.label}:`);
237
+ lines.push(...changes.map(outcomeLine));
238
+ }
239
+ if (notFound.length && chosen.length)
240
+ lines.push(`Not found: ${notFound.map((a) => a.label).join(", ")}.`);
241
+ if (loginReport?.text)
242
+ lines.push("", loginReport.text);
243
+ if (next.length)
244
+ lines.push("", "Next:", ...next.map((n) => ` ${n}`));
245
+ const exitCode = failed ? ExitCode.failure : (loginReport?.exitCode ?? ExitCode.ok);
246
+ return {
247
+ data: {
248
+ agents: results.map((r) => planJson(r.plan, r.changes)),
249
+ not_found: notFound.map((a) => a.name),
250
+ server: command,
251
+ declined,
252
+ login: loginReport ? { status: loginReport.status, instance: loginReport.instance, ...(loginReport.error ? { error: loginReport.error } : {}) } : null,
253
+ next,
254
+ },
255
+ text: lines.join("\n"),
256
+ exitCode,
257
+ };
258
+ }
259
+ function joinLabels(labels, word = "and") {
260
+ if (labels.length <= 1)
261
+ return labels.join("");
262
+ return `${labels.slice(0, -1).join(", ")} ${word} ${labels[labels.length - 1]}`;
263
+ }
264
+ async function runCheck(ctx, input) {
265
+ const env = ctx.io.env;
266
+ const agents = setupAgents(env);
267
+ const named = namedAgents(input, agents);
268
+ const state = await loadState(env);
269
+ const checks = [];
270
+ for (const agent of named.length ? named : agents) {
271
+ const check = await checkAgent(agent, env, state.agents[agent.name]);
272
+ if (named.length || check.found || state.agents[agent.name])
273
+ checks.push(check);
274
+ }
275
+ const servers = [];
276
+ for (const server of checks.flatMap((c) => c.servers)) {
277
+ if (!servers.some((s) => JSON.stringify(s) === JSON.stringify(server)))
278
+ servers.push(server);
279
+ }
280
+ if (!servers.length)
281
+ servers.push(await serverCommand(env));
282
+ const probes = [];
283
+ for (const server of servers) {
284
+ const probe = await probeMcpServer(server.command, server.args, { env, cwd: ctx.io.cwd, timeoutMs: PROBE_TIMEOUT_MS, clientVersion: KIT_VERSION });
285
+ probes.push({ command: [server.command, ...server.args].join(" "), ...probe });
286
+ }
287
+ const session = await ctx.session();
288
+ let loginCheck;
289
+ if (!session.url || !session.token) {
290
+ loginCheck = { ok: false, instance: session.url ?? null, problem: `not logged in; run ${cavelonCommand("login", "--instance", session.url ?? "https://cavelon.example.com")}` };
291
+ }
292
+ else {
293
+ try {
294
+ const result = await whoami.run(ctx, { positionals: {}, options: {} });
295
+ const data = result.data;
296
+ loginCheck = { ok: true, instance: session.url, who: data.owner?.email ?? undefined, tenant: data.tenant?.name ?? data.tenant?.id ?? null };
297
+ }
298
+ catch (error) {
299
+ const err = asCavelonError(error);
300
+ loginCheck = { ok: false, instance: session.url, problem: `${err.message}${err.hint ? ` ${err.hint}` : ""}` };
301
+ }
302
+ }
303
+ const ok = checks.length > 0 && checks.every((c) => c.ok) && probes.every((p) => p.ok) && loginCheck.ok;
304
+ const mark = (good) => (good ? ctx.style.green("ok ") : ctx.style.red("no "));
305
+ const lines = [];
306
+ if (!checks.length)
307
+ lines.push(`${mark(false)}No coding agent found, and setup has set up none.`);
308
+ for (const check of checks) {
309
+ lines.push(`${mark(check.ok)}${check.label}${check.found ? "" : " (not found on this computer)"}`);
310
+ for (const detail of check.details)
311
+ lines.push(` ${detail}`);
312
+ }
313
+ for (const probe of probes) {
314
+ lines.push(`${mark(probe.ok)}The Cavelon tools start: ${probe.command}${probe.ok ? (probe.server ? ` (${probe.server})` : "") : ` (${probe.error})`}`);
315
+ }
316
+ lines.push(loginCheck.ok
317
+ ? `${mark(true)}Logged in to ${loginCheck.instance}${loginCheck.who ? ` as ${loginCheck.who}` : ""}${loginCheck.tenant ? `, tenant ${loginCheck.tenant}` : ""}`
318
+ : `${mark(false)}Login: ${loginCheck.problem}`);
319
+ if (!ok)
320
+ lines.push("", `Run ${cavelonCommand("setup")} to set up what is missing.`);
321
+ return {
322
+ data: {
323
+ ok,
324
+ agents: checks.map(({ servers: _servers, ...c }) => c),
325
+ server: probes,
326
+ login: loginCheck,
327
+ },
328
+ text: lines.join("\n"),
329
+ exitCode: ok ? ExitCode.ok : ExitCode.failure,
330
+ };
331
+ }
332
+ function removalLines(agent, record) {
333
+ const lines = [];
334
+ if (record.plugin_installed)
335
+ lines.push("uninstall the Cavelon plugin");
336
+ if (record.marketplace_added)
337
+ lines.push("remove the Cavelon plugin marketplace");
338
+ if (record.mcp)
339
+ lines.push(`remove the "cavelon" tools server from ${record.mcp.file}`);
340
+ if (record.skills)
341
+ lines.push(`remove the Cavelon skills from ${record.skills.dir}${path.sep}`);
342
+ return lines.length ? [` ${agent.label}:`, ...lines.map((l) => ` - ${l}`)] : [];
343
+ }
344
+ async function runRemove(ctx, input) {
345
+ const env = ctx.io.env;
346
+ const agents = setupAgents(env);
347
+ const named = namedAgents(input, agents);
348
+ const state = await loadState(env);
349
+ const targets = (named.length ? named : agents).filter((a) => state.agents[a.name] && Object.keys(state.agents[a.name]).length);
350
+ if (!targets.length) {
351
+ return { data: { agents: [], removed: false }, text: "Nothing to remove: cavelon setup has not changed anything here." };
352
+ }
353
+ const plan = targets.flatMap((a) => removalLines(a, state.agents[a.name]));
354
+ if (!boolOption(input, "yes")) {
355
+ if (!canAsk(ctx)) {
356
+ throw confirmationRequired("--remove undoes what setup did only when you agree", { agents: targets.map((a) => ({ name: a.name, label: a.label, recorded: state.agents[a.name] })) });
357
+ }
358
+ ctx.io.stderr.write(`cavelon setup --remove will undo this:\n${plan.join("\n")}\n`);
359
+ if (!(await confirm(ctx, "Undo these changes?", false))) {
360
+ return { data: { agents: [], removed: false, declined: true }, text: "Nothing was changed." };
361
+ }
362
+ }
363
+ const skills = await loadSkills();
364
+ const removing = new Set(targets.map((a) => a.name));
365
+ const shared = new Set(Object.entries(state.agents)
366
+ .filter(([name]) => !removing.has(name))
367
+ .flatMap(([, record]) => (record.skills ? [record.skills.dir] : [])));
368
+ const results = [];
369
+ for (const agent of targets) {
370
+ results.push({ agent, changes: await removeAgent(agent, state.agents[agent.name], env, skills, shared) });
371
+ await saveState(env, state);
372
+ }
373
+ const failed = results.some((r) => r.changes.some((c) => c.outcome === "failed" || c.outcome === "skipped"));
374
+ const lines = results.flatMap((r) => [`${r.agent.label}:`, ...r.changes.map(outcomeLine)]);
375
+ lines.push("", `Your login stays; ${cavelonCommand("logout")} removes it.`);
376
+ if (results.some((r) => r.changes.some((c) => c.outcome === "removed")))
377
+ lines.push(`Restart ${joinLabels(results.map((r) => r.agent.label))} if ${results.length > 1 ? "they are" : "it is"} open.`);
378
+ return {
379
+ data: {
380
+ agents: results.map((r) => ({ name: r.agent.name, label: r.agent.label, changes: r.changes })),
381
+ removed: true,
382
+ },
383
+ text: lines.join("\n"),
384
+ exitCode: failed ? ExitCode.failure : ExitCode.ok,
385
+ };
386
+ }
387
+ export const setup = {
388
+ name: "setup",
389
+ summary: "Set up your coding agents for Cavelon and log in, in one guided step.",
390
+ 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" +
391
+ "and does it: Claude Code and Codex get the Cavelon plugin through their own plugin command; the others get the `cavelon` MCP\n" +
392
+ "server in their user MCP configuration and the skills in their user skills folder. It touches nothing else in those files and\n" +
393
+ "records what it did, so --remove undoes exactly that. Then it logs in if needed, choosing the tenant by name as `login` does.\n" +
394
+ "The server starts as `cavelon mcp` when cavelon is installed, otherwise through npx. --check reports what is set up and\n" +
395
+ "working: each agent's entry, the MCP server starting, and the login. Without a terminal it changes nothing unless --yes.",
396
+ readOnly: false,
397
+ destructive: true,
398
+ idempotent: true,
399
+ mcpTool: false,
400
+ options: {
401
+ agents: {
402
+ type: "string",
403
+ value: "<list>",
404
+ multiple: true,
405
+ description: "Only these agents: claude, codex, cursor, copilot, gemini, kiro, or all (comma-separated). Default: every agent found.",
406
+ },
407
+ yes: { type: "boolean", short: "y", description: "Make the changes without asking." },
408
+ check: { type: "boolean", description: "Report what is set up and working; change nothing." },
409
+ remove: { type: "boolean", description: "Undo what setup did (your login stays)." },
410
+ },
411
+ examples: [
412
+ "cavelon setup",
413
+ "cavelon setup --agents claude,codex --instance https://cavelon.example.com --yes",
414
+ "cavelon setup --check",
415
+ "cavelon setup --remove",
416
+ ],
417
+ async run(ctx, input) {
418
+ if (boolOption(input, "check") && boolOption(input, "remove"))
419
+ throw usageError("--check and --remove do not go together.");
420
+ if (boolOption(input, "check"))
421
+ return runCheck(ctx, input);
422
+ if (boolOption(input, "remove"))
423
+ return runRemove(ctx, input);
424
+ return runSetup(ctx, input);
425
+ },
426
+ };
@@ -8,6 +8,7 @@ import { clip, keyValues } from "../format.js";
8
8
  import { readTextFile, writeFileAtomic } from "../fsutil.js";
9
9
  import { uncommitted } from "../git.js";
10
10
  import { callStable } from "../invoke.js";
11
+ import { harnessNotFoundError, lookupHarness } from "../harness-ref.js";
11
12
  import { ceilingHint, LIMIT_ABOVE_CEILING, parseLimits, readLimits } from "../limits.js";
12
13
  import { deletePreview, digest, fileDigest, listPreviews, loadPreview, readPulledFiles, savePreview, writePulledFiles, writeState, } from "../local-state.js";
13
14
  import { catalogEntry, checkPackage, KIT_CODES, packageVersionOf } from "../package-check.js";
@@ -19,14 +20,14 @@ import { listedPages } from "./docs.js";
19
20
  import { writeInventory } from "./inventory.js";
20
21
  import { cavelonCommand, shellWord } from "../shell.js";
21
22
  import { secretSetCommand, targetFlags, variableSetCommand } from "./values.js";
22
- const HARNESS_OPTION = { type: "string", value: "<slug>", description: "The solution (harness); default: env file, then cavelon.yaml." };
23
+ const HARNESS_OPTION = { type: "string", value: "<harness>", description: "The solution (harness): its name, slug or id; default: env file, then cavelon.yaml." };
23
24
  const ENV_OPTION = { type: "string", value: "<name>", description: "Use env/<name>.yaml: its tenant, solution and runtime bindings." };
24
25
  export function requireSolution(session) {
25
26
  if (!session.project) {
26
27
  throw new CavelonError(ExitCode.usage, {
27
28
  code: "no_solution",
28
29
  message: "This folder is not a Cavelon solution (no cavelon.yaml here or above).",
29
- hint: "Run `cavelon init` for a new solution, then `cavelon pull --harness <slug>` for an existing one.",
30
+ hint: "Run `cavelon init`: it asks which solution, or a new one, on a terminal. `cavelon harness list` shows the solutions.",
30
31
  });
31
32
  }
32
33
  return session.project;
@@ -41,32 +42,11 @@ function harnessRef(session, input) {
41
42
  return { ref: session.project.harness, source: "cavelon.yaml" };
42
43
  return {};
43
44
  }
44
- async function findHarness(ctx, ref) {
45
- if (isUuid(ref)) {
46
- try {
47
- return await callStable(ctx, "GET", "/api/v1/harnesses/{harness_id}", "reading solutions", { params: { harness_id: [ref] } });
48
- }
49
- catch (error) {
50
- if (error instanceof CavelonError && error.status === 404)
51
- return undefined;
52
- throw error;
53
- }
54
- }
55
- try {
56
- return await callStable(ctx, "GET", "/api/v1/harnesses/by-slug/{slug}", "finding solutions by slug", { params: { slug: [ref] } });
57
- }
58
- catch (error) {
59
- if (error instanceof CavelonError && error.status === 404)
60
- return undefined;
61
- throw error;
62
- }
63
- }
64
- function harnessNotFound(ref, source) {
65
- return new CavelonError(ExitCode.failure, {
66
- code: "solution_not_found",
67
- message: `No solution "${ref}" in this tenant${source ? ` (from ${source})` : ""}.`,
68
- hint: "`cavelon harness list` shows them; `cavelon harness new <slug>` creates one, and an env file's harness is created by `apply`.",
69
- });
45
+ async function findHarness(ctx, ref, source) {
46
+ const { harness, candidates } = await lookupHarness(ctx, ref);
47
+ if (!harness)
48
+ throw harnessNotFoundError(ref, candidates, source);
49
+ return harness;
70
50
  }
71
51
  async function cachedFirst(ctx, what, cached, offline, fetch) {
72
52
  if (cached && (offline || !cached.stale))
@@ -171,7 +151,7 @@ export const pull = {
171
151
  idempotent: true,
172
152
  mcpTool: "pull",
173
153
  options: {
174
- harness: { type: "string", value: "<slug>", description: "The solution to export; recorded in cavelon.yaml when it names none." },
154
+ harness: { type: "string", value: "<harness>", description: "The solution to export, by name, slug or id; its slug is recorded in cavelon.yaml when it names none." },
175
155
  force: { type: "boolean", description: "Overwrite package files that have uncommitted changes (outside git: changes since the last pull)." },
176
156
  },
177
157
  examples: ["cavelon pull --harness support", "cavelon pull && git diff -- package tests"],
@@ -188,8 +168,6 @@ export const pull = {
188
168
  let harness;
189
169
  if (ref) {
190
170
  harness = await findHarness(ctx, ref);
191
- if (!harness)
192
- throw harnessNotFound(ref);
193
171
  }
194
172
  const scope = harness ? "agent_graph" : "full_config";
195
173
  const exported = await callStable(ctx, "GET", "/api/v1/agent-graph/export", "exporting packages", {
@@ -524,11 +502,11 @@ async function applyTarget(ctx, session, input, pkg) {
524
502
  const { ref, source } = harnessRef(session, input);
525
503
  if (!ref)
526
504
  return undefined;
527
- const found = await findHarness(ctx, ref);
505
+ const { harness: found, candidates } = await lookupHarness(ctx, ref);
528
506
  if (found)
529
507
  return { ...found, created: false };
530
508
  if (!source?.startsWith("env/") || isUuid(ref))
531
- throw harnessNotFound(ref, source);
509
+ throw harnessNotFoundError(ref, candidates, source);
532
510
  const name = packageHarnessName(pkg, ref) ?? ref;
533
511
  const created = await callStable(ctx, "POST", "/api/v1/harnesses", "creating solutions", { body: { slug: ref, name } });
534
512
  ctx.warn(`Created the draft solution ${created.name} (${created.slug}) that ${source} names.`);
@@ -584,7 +562,7 @@ export const apply = {
584
562
  throw usageError(`--mode must be overwrite or replace, got "${mode}".`);
585
563
  const { disk, findings } = await validatePackage(ctx, project, false);
586
564
  if (disk.empty)
587
- throw usageError(`No package files in ${project.layout.package}/.`, "Run `cavelon pull --harness <slug>` first, or write the package files.");
565
+ throw usageError(`No package files in ${project.layout.package}/.`, "Run `cavelon pull --harness <name or slug>` first (`cavelon harness list` shows them), or write the package files.");
588
566
  const errors = findings.filter((f) => f.severity === "error");
589
567
  if (errors.length) {
590
568
  return {
@@ -782,7 +760,7 @@ export const activate = {
782
760
  const session = await ctx.session();
783
761
  const { ref, source } = harnessRef(session, input);
784
762
  if (!ref)
785
- throw usageError("Which solution?", "Pass --harness <slug>, or set harness in cavelon.yaml or the env file.");
763
+ throw usageError("Which solution?", "Pass --harness <name or slug> (`cavelon harness list` shows them), or set harness in cavelon.yaml or the env file.");
786
764
  const client = await ctx.client();
787
765
  const principal = await readPrincipal(client);
788
766
  if (principal?.kind === "personal_access_token" && principal.token && !principal.token.may_activate) {
@@ -792,9 +770,7 @@ export const activate = {
792
770
  hint: "A person activates the solution in the Admin, or creates a token with \"may activate\" on /account/access-tokens.",
793
771
  });
794
772
  }
795
- const harness = await findHarness(ctx, ref);
796
- if (!harness)
797
- throw harnessNotFound(ref, source);
773
+ const harness = await findHarness(ctx, ref, source);
798
774
  if (harness.status === "active") {
799
775
  return { data: { activated: false, already_active: true, harness }, text: `${harness.name} (${harness.slug}) is already active.` };
800
776
  }