@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.
package/README.md CHANGED
@@ -6,13 +6,20 @@ learns each instance's API, features and docs from what the instance publishes
6
6
  (its OpenAPI, `/api/v1/meta/capabilities`, `/api/v1/meta/error-catalog` and
7
7
  `/llms.txt`), so a new core release needs no new `cavelon` release.
8
8
 
9
- Node.js 20.3 or newer. Install it from npm, or run it as `npx -y @cavelon/cli`:
9
+ Node.js 20.3 or newer. Run it through `npx`, which needs no install; to type
10
+ `cavelon`, install it globally (or define an alias for the `npx` command):
10
11
 
11
12
  ```bash
13
+ npx -y @cavelon/cli --help
12
14
  npm i -g @cavelon/cli
13
- cavelon --help
14
15
  ```
15
16
 
17
+ Without Node.js, one line installs a standalone `cavelon` into your user
18
+ folder: `curl -fsSL https://github.com/goodguys-gmbh/cavelon-dev-kit/releases/latest/download/install.sh | sh`
19
+ on macOS and Linux, `irm https://github.com/goodguys-gmbh/cavelon-dev-kit/releases/latest/download/install.ps1 | iex`
20
+ in Windows PowerShell. Then `cavelon setup` sets up your coding agents and logs
21
+ you in.
22
+
16
23
  The full documentation is in the repository's
17
24
  [`docs/`](https://github.com/goodguys-gmbh/cavelon-dev-kit/tree/main/docs):
18
25
  [installation](https://github.com/goodguys-gmbh/cavelon-dev-kit/blob/main/docs/installation.md)
@@ -45,9 +52,13 @@ This page is a compact reference.
45
52
  standard input instead. **`cavelon` never takes a token as an argument**, so it
46
53
  stays out of shell history. Run it in a terminal of your own: an agent's
47
54
  shell (`!` in Claude Code) has no terminal to type the token into.
48
- 3. `cavelon whoami` shows who the token acts as, its name and when it expires (it
49
- warns from seven days before), and whether it may activate solutions. With a
50
- token that reaches several tenants, choose one: `cavelon use <tenant>`.
55
+ `login` finds the tenants the token reaches: it uses the only one, or asks
56
+ you to choose by number or part of a name. Without a terminal it stores the
57
+ token and prints one `cavelon use <tenant>` line per tenant (exit 2).
58
+ 3. `cavelon whoami` shows who the token acts as, in which tenant (name, slug
59
+ and id), its name and when it expires (it warns from seven days before), and
60
+ whether it may activate solutions. `cavelon use` chooses another tenant from
61
+ the same list.
51
62
 
52
63
  The token goes into the operating system's credential store (Keychain, Windows
53
64
  Credential Manager, Secret Service). Where there is none, it goes into
@@ -67,14 +78,14 @@ Environment variables replace the login:
67
78
  |---|---|
68
79
  | `CAVELON_URL` | the instance URL |
69
80
  | `CAVELON_TOKEN` | a personal access token (`cvpat_…`) or a tenant API key (`cbp_…`); needs `CAVELON_URL` |
70
- | `CAVELON_TENANT` | the tenant slug or id, for a personal token that reaches several tenants |
81
+ | `CAVELON_TENANT` | the tenant's name, slug or id, for a personal token that reaches several tenants |
71
82
 
72
83
  ### Which instance, token and tenant
73
84
 
74
85
  Highest first:
75
86
 
76
- 1. command-line options: `--instance <url>`, `--tenant <tenant>` (there is no
77
- token option);
87
+ 1. command-line options: `--instance <url>`, `--tenant <name, slug or id>`
88
+ (there is no token option);
78
89
  2. `CAVELON_URL`, `CAVELON_TOKEN`, `CAVELON_TENANT`;
79
90
  3. the nearest `cavelon.yaml` from the current directory upwards (instance URL
80
91
  and tenant, never a token);
@@ -97,22 +108,23 @@ Every command takes `--json` (one JSON document on stdout, errors included),
97
108
 
98
109
  | Command | Marked | What it does |
99
110
  |---|---|---|
111
+ | `setup [--agents] [--yes] [--check] [--remove]` | changing (destructive) | Set up the coding agents on this computer (the plugin for Claude Code and Codex; the MCP server and skills in the user settings of Cursor, VS Code with GitHub Copilot, Gemini CLI and Kiro) and log in. `--check` reports what works, `--remove` undoes it. A person runs this; not an MCP tool. |
100
112
  | `login [--token-stdin]` | changing | Store a token for an instance. A person runs this. |
101
113
  | `logout [--all]` | changing | Delete the stored token. |
102
- | `whoami` | read-only | Owner or key, tenant, role, and where the credential came from. |
103
- | `use <tenant>` / `use --clear` | changing | Choose the tenant for this instance. |
114
+ | `whoami` | read-only | Owner or key, tenant (name, slug and id), role, and where the credential came from. |
115
+ | `use [<tenant>]` / `use --clear` | changing | Choose the tenant for this instance, by name, slug or id, or from a list. |
104
116
  | `status [--offline]` | read-only | Instance, credential, tenant, solution folder, running operations, quotas close to full. |
105
117
  | `limits [--key <key>] [--source <source>]` | read-only | The instance's limits for this tenant by source, who changes each and how; the tenant's quotas with their use (the monthly Processing Step cap among them); branch concurrency. |
106
118
  | `limits set <key> <value> [--confirm]` | changing (destructive) | Change a limit through the operation the instance names: a tenant admin's, a quota of the Tenant Owner's (inference budget, Processing Step cap), or an operator's run cap with a Platform-mode token; without `--confirm`, shows the old and new value. |
107
119
  | `models list` | read-only | The tenant's Model Registry rows with their endpoint and `max_concurrent_requests`; never a key. |
108
120
  | `models set-limit <model> <n\|none> [--confirm]` | changing (destructive) | Set or clear a row's `max_concurrent_requests`; without `--confirm`, shows the old and new value. |
109
121
  | `tenant create <slug> [--name] [--use]` | changing | Create a tenant (personal token in Platform mode with `tenants.manage`). |
110
- | `tenant list [--search]` | read-only | Tenants the token can see. |
111
- | `harness list [--readiness]` | read-only | The tenant's solutions. |
122
+ | `tenant list [--search]` | read-only | Tenants the token can see, with name, slug, role and id. |
123
+ | `harness list [--readiness]` | read-only | The tenant's solutions, with slug, name, status and id. |
112
124
  | `harness new <slug> [--name] [--description]` | changing | Create an empty draft solution. |
113
125
  | `harness clone <source> [--slug] [--name] [--no-tests] [--no-triggers]` | changing | Copy a solution into a new draft. |
114
126
  | `activate [--harness] [--env]` | changing | Activate through the readiness gate only, never by force. |
115
- | `init [--harness] [--agents <list>] [--hook] [--update] [--from <file> [--force]]` | changing (files) | Make this folder a solution: `cavelon.yaml`, `package/`, `tests/`, `env/`, `.cavelon/`; `--from` writes a package file into it. |
127
+ | `init [--harness] [--agents <list>] [--hook] [--update] [--from <file> [--force]]` | changing (files) | Make this folder a solution: `cavelon.yaml`, `package/`, `tests/`, `env/`, `.cavelon/`; on a terminal it asks for the tenant and the solution (or a new one by name); `--from` writes a package file into it. |
116
128
  | `pull [--harness] [--force]` | changing (files) | Write the instance's package into `package/` and `tests/`, the inventory into `.cavelon/`. |
117
129
  | `validate [--offline]` | read-only | Check the package files against the cached package schema. |
118
130
  | `apply [--env] [--harness] [--mode]` | changing | Preview the files against the instance; prints and stores a preview id. |
@@ -699,7 +711,9 @@ an agent only with a new plugin or `init --update`. With `cavelon` installed,
699
711
  |---|---|
700
712
  | `~/.config/cavelon/config.json` | the current instance, the tenant chosen with `use`, which store holds the token. Never a token. |
701
713
  | `~/.config/cavelon/credentials.json` | the token per instance (0600), only where there is no OS credential store |
714
+ | `~/.config/cavelon/setup.json` | what `cavelon setup` changed in your coding agents, so `setup --remove` undoes exactly that (0600) |
702
715
  | `~/.cache/cavelon/<instance>/<version>/` | the instance's capabilities, OpenAPI, error catalog, package schema and docs index |
716
+ | `~/.cache/cavelon/update-check.json` | when the latest release was last looked up and announced; `CAVELON_NO_UPDATE_CHECK=1` turns the check off |
703
717
 
704
718
  `CAVELON_CONFIG_DIR` and `CAVELON_CACHE_DIR` move them; `XDG_CONFIG_HOME` and
705
719
  `XDG_CACHE_HOME` are honoured. `CAVELON_CREDENTIAL_STORE=file` skips the OS store.
package/dist/agents.js CHANGED
@@ -1,10 +1,12 @@
1
1
  import { promises as fs } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
+ import { embeddedContent } from "./embedded.js";
4
5
  import { usageError } from "./errors.js";
5
6
  import { GENERATED_TOKEN } from "./markers.js";
6
7
  import { KIT_VERSION } from "./version.js";
7
8
  export const MCP_COMMAND = { command: "npx", args: ["-y", "@cavelon/cli@0.1", "mcp"] };
9
+ export const INSTALLED_MCP_COMMAND = { command: "cavelon", args: ["mcp"] };
8
10
  export function mcpCommand(platform = process.platform) {
9
11
  return platform === "win32" ? { command: "cmd", args: ["/c", MCP_COMMAND.command, ...MCP_COMMAND.args] } : MCP_COMMAND;
10
12
  }
@@ -15,14 +17,16 @@ const jsonServer = (file, key = "mcpServers", extra = {}) => ({
15
17
  format: "json",
16
18
  keys: [key, "cavelon"],
17
19
  entry: { ...extra, ...mcpCommand() },
18
- others: otherPlatforms().map((p) => ({ ...extra, ...mcpCommand(p) })),
20
+ others: [...otherPlatforms().map((p) => ({ ...extra, ...mcpCommand(p) })), { ...extra, ...INSTALLED_MCP_COMMAND }],
19
21
  });
20
22
  const tomlServer = (file) => {
21
- const block = (platform) => {
22
- const { command, args } = mcpCommand(platform);
23
- return ["[mcp_servers.cavelon]", `command = "${command}"`, `args = [${args.map((a) => `"${a}"`).join(", ")}]`].join("\n");
23
+ const block = ({ command, args }) => ["[mcp_servers.cavelon]", `command = "${command}"`, `args = [${args.map((a) => JSON.stringify(a)).join(", ")}]`].join("\n");
24
+ return {
25
+ file,
26
+ format: "toml",
27
+ block: block(mcpCommand()),
28
+ others: [...otherPlatforms().map((p) => block(mcpCommand(p))), block(INSTALLED_MCP_COMMAND)],
24
29
  };
25
- return { file, format: "toml", block: block(process.platform), others: otherPlatforms().map(block) };
26
30
  };
27
31
  function agent(name, label, mcp) {
28
32
  if (!mcp)
@@ -67,6 +71,9 @@ export function skillsSource() {
67
71
  return [path.join(here, "skills"), path.resolve(here, "..", "..", "plugin", "skills")];
68
72
  }
69
73
  export async function bundledSkills() {
74
+ const embedded = embeddedContent();
75
+ if (embedded)
76
+ return embedded.skills;
70
77
  for (const dir of skillsSource()) {
71
78
  let entries;
72
79
  try {
@@ -96,10 +103,11 @@ export async function bundledSkills() {
96
103
  }
97
104
  return [];
98
105
  }
99
- export function generatedCopy(file) {
106
+ export function generatedCopy(file, by = "init") {
100
107
  if (!file.path.endsWith(".md"))
101
108
  return file.content;
102
- const mark = `<!-- ${GENERATED_TOKEN}: written by \`cavelon init --agents\` (cavelon ${KIT_VERSION}); \`cavelon init --update\` replaces this file. Put your own notes in another file. -->`;
109
+ const how = by === "init" ? "`cavelon init --agents` (cavelon " + KIT_VERSION + "); `cavelon init --update` replaces this file" : "`cavelon setup` (cavelon " + KIT_VERSION + "); `cavelon setup` replaces it and `cavelon setup --remove` removes it";
110
+ const mark = `<!-- ${GENERATED_TOKEN}: written by ${how}. Put your own notes in another file. -->`;
103
111
  const front = /^---\r?\n[\s\S]*?\r?\n---\r?\n/.exec(file.content);
104
112
  if (front)
105
113
  return `${front[0]}${mark}\n${file.content.slice(front[0].length)}`;
package/dist/choose.js ADDED
@@ -0,0 +1,112 @@
1
+ import { CavelonError, ExitCode } from "./errors.js";
2
+ import { readLine } from "./prompt.js";
3
+ export const MAX_LISTED = 20;
4
+ const MAX_TRIES = 5;
5
+ function lower(value) {
6
+ return (value ?? "").toLowerCase();
7
+ }
8
+ export function exactMatch(items, ref) {
9
+ const wanted = ref.trim().toLowerCase();
10
+ return (items.find((t) => t.id === ref.trim()) ??
11
+ items.find((t) => lower(t.slug) === wanted) ??
12
+ (() => {
13
+ const byName = items.filter((t) => lower(t.name) === wanted);
14
+ return byName.length === 1 ? byName[0] : undefined;
15
+ })());
16
+ }
17
+ export function containing(items, text) {
18
+ const wanted = text.trim().toLowerCase();
19
+ return items.filter((t) => lower(t.name).includes(wanted) || lower(t.slug).includes(wanted));
20
+ }
21
+ function editDistance(a, b) {
22
+ let previous = Array.from({ length: b.length + 1 }, (_, i) => i);
23
+ for (let i = 1; i <= a.length; i++) {
24
+ const current = [i];
25
+ for (let j = 1; j <= b.length; j++) {
26
+ current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
27
+ }
28
+ previous = current;
29
+ }
30
+ return previous[b.length];
31
+ }
32
+ export function closest(items, ref, max = 5) {
33
+ const wanted = ref.trim().toLowerCase();
34
+ if (!wanted)
35
+ return items.slice(0, max);
36
+ const scored = items.flatMap((item) => {
37
+ const words = [lower(item.slug), lower(item.name)].filter(Boolean);
38
+ if (words.some((w) => w.includes(wanted)))
39
+ return [{ item, score: 0 }];
40
+ if (words.some((w) => w.length >= 3 && wanted.includes(w)))
41
+ return [{ item, score: 1 }];
42
+ const distance = Math.min(...words.map((w) => editDistance(w, wanted)));
43
+ return distance <= Math.max(2, Math.floor(wanted.length / 3)) ? [{ item, score: distance + 1 }] : [];
44
+ });
45
+ return scored
46
+ .sort((a, b) => a.score - b.score)
47
+ .slice(0, max)
48
+ .map((s) => s.item);
49
+ }
50
+ export function displayName(item) {
51
+ if (item.name && item.slug && item.name !== item.slug)
52
+ return `${item.name} (${item.slug})`;
53
+ return item.name ?? item.slug ?? item.id;
54
+ }
55
+ function line(index, item, extra, preferred) {
56
+ const slug = item.slug && item.slug !== item.name ? ` ${item.slug}` : "";
57
+ const notes = [extra, preferred ? "default, press Enter" : undefined].filter(Boolean).join(", ");
58
+ return ` ${String(index).padStart(2)} ${item.name ?? item.slug ?? item.id}${slug}${notes ? ` (${notes})` : ""}`;
59
+ }
60
+ export async function pick(ctx, options) {
61
+ const write = (text) => ctx.io.stderr.write(`${text}\n`);
62
+ let shown = options.items.slice(0, MAX_LISTED);
63
+ const show = (items) => {
64
+ items.forEach((item, i) => write(line(i + 1, item, options.extra?.(item), item === options.preferred)));
65
+ if (options.other)
66
+ write(` ${String(items.length + 1).padStart(2)} ${options.other.label}`);
67
+ };
68
+ write(options.intro);
69
+ show(shown);
70
+ if (options.items.length > shown.length)
71
+ write(` … and ${options.items.length - shown.length} more: type part of a name to find one.`);
72
+ const hint = shown.length || options.other ? "type its number or part of its name" : "type part of its name";
73
+ for (let tries = 0; tries < MAX_TRIES; tries++) {
74
+ const answer = await readLine(ctx.io, `${options.question} ${ctx.style.dim(`(${hint})`)} `);
75
+ if (!answer) {
76
+ if (options.preferred)
77
+ return { item: options.preferred };
78
+ write("Type a number from the list, or part of a name.");
79
+ continue;
80
+ }
81
+ if (options.other && answer.toLowerCase() === options.other.word)
82
+ return { other: true };
83
+ if (/^\d+$/.test(answer)) {
84
+ const n = Number(answer);
85
+ if (n >= 1 && n <= shown.length)
86
+ return { item: shown[n - 1] };
87
+ if (options.other && n === shown.length + 1)
88
+ return { other: true };
89
+ write(`There is no number ${n} in the list.`);
90
+ continue;
91
+ }
92
+ let found = containing(options.items, answer);
93
+ if (!found.length && options.search)
94
+ found = await options.search(answer);
95
+ const exact = exactMatch(found, answer);
96
+ if (exact)
97
+ return { item: exact };
98
+ if (found.length === 1)
99
+ return { item: found[0] };
100
+ if (!found.length) {
101
+ const near = closest(options.items, answer);
102
+ write(`Nothing is called "${answer}".${near.length ? ` Did you mean ${near.map(displayName).join(", ")}?` : ""} Try another part of the name.`);
103
+ continue;
104
+ }
105
+ shown = found.slice(0, MAX_LISTED);
106
+ write(`${found.length} match "${answer}":`);
107
+ show(shown);
108
+ if (found.length > shown.length)
109
+ write(` … and ${found.length - shown.length} more: type more of the name.`);
110
+ }
111
+ throw new CavelonError(ExitCode.usage, { code: "cancelled", message: "Nothing was chosen.", hint: "Run the command again, or name it with an option." });
112
+ }
@@ -4,6 +4,7 @@ import { wait, watch } from "./async.js";
4
4
  import { docsGet, docsSearch } from "./docs.js";
5
5
  import { login, logout, status, use, whoami } from "./session.js";
6
6
  import { init } from "./init.js";
7
+ import { setup } from "./setup.js";
7
8
  import { limits } from "./limits.js";
8
9
  import { limitsSet } from "./limits-set.js";
9
10
  import { modelsList, modelsSetLimit } from "./models.js";
@@ -53,6 +54,7 @@ const mcp = {
53
54
  },
54
55
  };
55
56
  export const COMMANDS = [
57
+ setup,
56
58
  login,
57
59
  logout,
58
60
  whoami,
@@ -11,9 +11,15 @@ import { ensureStateDir, STATE_DIR } from "../local-state.js";
11
11
  import { isGenerated, upsertBlock, upsertJsonEntry } from "../markers.js";
12
12
  import { packageVersionOf } from "../package-check.js";
13
13
  import { defaultLayoutFor, safeSectionName, schemaSections, toYaml, writePackage } from "../package-files.js";
14
- import { readPrincipal } from "../principal.js";
14
+ import { readPrincipal, readTenantless } from "../principal.js";
15
15
  import { ENV_DIR, parseProject, PROJECT_FILE } from "../project.js";
16
- import { requireInstance, requireToken } from "../session.js";
16
+ import { canAsk, readLine } from "../prompt.js";
17
+ import { pick } from "../choose.js";
18
+ import { harnessNotFoundError, listHarnesses, lookupHarness } from "../harness-ref.js";
19
+ import { lookupTenantId, requireInstance, requireToken, tenantRequiredError } from "../session.js";
20
+ import { cavelonCommand } from "../shell.js";
21
+ import { chooseTenant, listsTenants, noTenantError, tenantOpenError, tenantRef, tenantTitle } from "../tenant-choice.js";
22
+ import { createHarness } from "./tenants.js";
17
23
  import { schemaFor, setProjectKey } from "./solution.js";
18
24
  const HOOK_LINES = (prefix) => [
19
25
  "# Check the Cavelon package before each commit (`cavelon init --hook`).",
@@ -210,18 +216,133 @@ async function installHook(root, onlyExisting) {
210
216
  }
211
217
  return action;
212
218
  }
213
- function solutionYaml(values) {
219
+ function solutionYaml(values, tenantNote) {
220
+ let body = toYaml(values).trimEnd();
221
+ if (tenantNote)
222
+ body = body.split("\n").map((line) => (line.startsWith("tenant: ") ? `${line} # ${tenantNote}` : line)).join("\n");
214
223
  return [
215
224
  "# A Cavelon solution. `cavelon` finds this file from the working directory upwards;",
216
225
  "# it names the instance, tenant and solution, never a token.",
217
- toYaml(values).trimEnd(),
226
+ body,
218
227
  "",
219
228
  ].join("\n");
220
229
  }
230
+ function commentText(text) {
231
+ return [...text].map((c) => (c < " " || c === "\u007f" ? " " : c)).join("").trim();
232
+ }
233
+ export function slugFromName(name) {
234
+ const plain = name.normalize("NFKD").replace(/[\u0300-\u036f]/g, "").toLowerCase();
235
+ let slug = plain.replace(/[^a-z0-9]+/g, "-");
236
+ while (slug.startsWith("-"))
237
+ slug = slug.slice(1);
238
+ while (slug.endsWith("-"))
239
+ slug = slug.slice(0, -1);
240
+ slug = slug.slice(0, 60);
241
+ while (slug.endsWith("-"))
242
+ slug = slug.slice(0, -1);
243
+ return slug;
244
+ }
245
+ const SLUG = /^[a-z0-9][a-z0-9-]*$/;
246
+ async function initTenant(ctx, session) {
247
+ if (session.tokenKind === "api_key")
248
+ return session.tenant ? { ref: session.tenant } : undefined;
249
+ const client = await ctx.client({ tenant: false });
250
+ const pat = session.tokenKind === "personal_access_token";
251
+ const tenantless = pat ? await readTenantless(client) : undefined;
252
+ const reach = listsTenants(tenantless) ? tenantless : undefined;
253
+ if (session.tenant) {
254
+ const found = await lookupTenantId(client, session.tenant, session.tenantSource);
255
+ const listed = reach?.tenants.find((t) => t.id === found.id);
256
+ const name = found.name ?? listed?.name ?? undefined;
257
+ const slug = found.slug ?? listed?.slug ?? undefined;
258
+ return { ref: slug ?? session.tenant, id: found.id, name, slug };
259
+ }
260
+ if (tenantless?.refused)
261
+ throw tenantRequiredError(client.url, tenantless.said);
262
+ if (reach && !reach.platform && (canAsk(ctx) || !reach.tenantId)) {
263
+ const choice = await chooseTenant(ctx, client, reach);
264
+ if (choice.kind === "none")
265
+ throw noTenantError(client.url, false);
266
+ if (choice.kind === "open") {
267
+ throw tenantOpenError(client.url, reach, "A solution belongs to one tenant. ", {
268
+ line: (ref) => cavelonCommand("init", "--tenant", ref),
269
+ template: "cavelon init --tenant <name or slug>",
270
+ });
271
+ }
272
+ const t = choice.tenant;
273
+ if (choice.how === "picked")
274
+ ctx.io.stderr.write(`Using tenant ${tenantTitle(t)}.\n`);
275
+ return { ref: tenantRef(t), id: t.id, name: t.name ?? undefined, slug: t.slug ?? undefined };
276
+ }
277
+ const placed = reach?.tenantId ?? (tenantless && !tenantless.refused ? tenantless.tenantId : null) ?? (await readPrincipal(await ctx.client()))?.tenant_id;
278
+ if (!placed)
279
+ return undefined;
280
+ const listed = reach?.tenants.find((t) => t.id === placed);
281
+ return { ref: listed?.slug ?? placed, id: placed, name: listed?.name ?? undefined, slug: listed?.slug ?? undefined };
282
+ }
283
+ async function initHarness(ctx, given) {
284
+ if (given) {
285
+ let lookup;
286
+ try {
287
+ lookup = await lookupHarness(ctx, given);
288
+ }
289
+ catch (error) {
290
+ ctx.warn(`Could not check solution "${given}" on the instance: ${error instanceof Error ? error.message : String(error)}`);
291
+ return { slug: given };
292
+ }
293
+ if (lookup.harness)
294
+ return { slug: lookup.harness.slug };
295
+ if (SLUG.test(given))
296
+ return { slug: given, missing: true };
297
+ throw harnessNotFoundError(given, lookup.candidates, undefined, (slug) => cavelonCommand("init", "--harness", slug));
298
+ }
299
+ let all;
300
+ try {
301
+ all = await listHarnesses(ctx);
302
+ }
303
+ catch {
304
+ return {};
305
+ }
306
+ const choices = all.map((h) => ({ id: h.id, slug: h.slug, name: h.name, status: h.status }));
307
+ if (!canAsk(ctx))
308
+ return { choices };
309
+ const write = (text) => ctx.io.stderr.write(`${text}\n`);
310
+ let name;
311
+ if (all.length) {
312
+ const picked = await pick(ctx, {
313
+ intro: `This tenant has ${all.length} solution${all.length === 1 ? "" : "s"}:`,
314
+ question: "Which solution does this folder hold?",
315
+ items: all,
316
+ extra: (h) => h.status,
317
+ other: { label: "a new solution (or type new)", word: "new" },
318
+ });
319
+ if ("item" in picked)
320
+ return { slug: picked.item.slug };
321
+ name = await readLine(ctx.io, "Name of the new solution: ");
322
+ }
323
+ else {
324
+ write("This tenant has no solutions yet.");
325
+ name = await readLine(ctx.io, "Name of the new solution (press Enter to decide later): ");
326
+ if (!name)
327
+ return {};
328
+ }
329
+ let base = slugFromName(name);
330
+ while (!base) {
331
+ write("The name needs at least one letter or digit.");
332
+ name = await readLine(ctx.io, "Name of the new solution: ");
333
+ base = slugFromName(name);
334
+ }
335
+ let slug = base;
336
+ for (let n = 2; all.some((h) => h.slug === slug); n++)
337
+ slug = `${base}-${n}`;
338
+ const created = await createHarness(ctx, { slug, name: name.slice(0, 255) });
339
+ write(`Created the draft solution ${created.name} (${created.slug}).`);
340
+ return { slug: created.slug, created: true };
341
+ }
221
342
  function envYaml(name, harness) {
222
343
  return [
223
344
  `# Where \`cavelon apply --env ${name}\` goes. Never a token or a secret value.`,
224
- "# tenant: <slug or id> # default: the tenant in cavelon.yaml",
345
+ "# tenant: <name, slug or id> # default: the tenant in cavelon.yaml",
225
346
  harness ? `harness: ${harness}` : "# harness: <slug> # created as a draft when it does not exist yet",
226
347
  "# mode: overwrite # or replace",
227
348
  "# runtime_bindings: # the package's runtime requirement key -> this tenant's resource id",
@@ -348,6 +469,7 @@ async function runInit(ctx, input) {
348
469
  return { root, actions: actions.filter((a) => !(a.action === "skipped" && /does not exist|no cavelon (block|entry)/.test(a.reason ?? ""))), next, imported: undefined };
349
470
  }
350
471
  const packageHarness = imported ? onlyHarnessSlug(imported) : undefined;
472
+ let chosenHarness;
351
473
  const root = ctx.io.cwd;
352
474
  const existing = await readTextFile(path.join(root, PROJECT_FILE));
353
475
  if (existing !== undefined) {
@@ -356,35 +478,38 @@ async function runInit(ctx, input) {
356
478
  else {
357
479
  const url = requireInstance(session);
358
480
  requireToken(session);
481
+ const tenant = await initTenant(ctx, session);
482
+ if (tenant?.id)
483
+ [session.tenant, session.tenantSource] = [tenant.id, session.tenantSource ?? "option"];
359
484
  const contracts = await ctx.contracts();
360
485
  const caps = await contracts.capabilities();
361
486
  if (contracts.needsTenant) {
362
487
  throw new CavelonError(ExitCode.usage, {
363
488
  code: "tenant_required",
364
489
  message: "A solution belongs to one tenant, and none is chosen.",
365
- hint: "Pass --tenant <slug>, or run `cavelon use <tenant>` first.",
490
+ hint: "Pass --tenant <name or slug>, or run `cavelon use` first to choose one.",
366
491
  });
367
492
  }
368
493
  const schema = await contracts.packageSchema();
369
494
  await contracts.errorCatalog().catch(() => null);
370
495
  if (!schema)
371
496
  ctx.warn("The instance does not publish its package schema; `validate` will have nothing to check against.");
372
- let tenant = session.tenant;
373
- if (!tenant && session.tokenKind !== "api_key") {
374
- const principal = await readPrincipal(await ctx.client());
375
- tenant = principal?.tenant_id ?? undefined;
376
- }
377
- const harness = stringOption(input, "harness") ?? packageHarness;
497
+ const decided = stringOption(input, "harness") ? await initHarness(ctx, stringOption(input, "harness")) : packageHarness ? { slug: packageHarness } : await initHarness(ctx, undefined);
498
+ chosenHarness = decided;
499
+ const harness = decided.slug;
500
+ if (decided.missing)
501
+ next.push(`Solution ${harness} is not on the instance yet: \`cavelon apply --env test\` creates it as a draft.`);
378
502
  const values = { instance: url };
379
503
  if (tenant)
380
- values.tenant = tenant;
504
+ values.tenant = tenant.ref;
381
505
  if (harness)
382
506
  values.harness = harness;
383
507
  const version = caps?.contracts?.package_versions?.current ?? schema?.["x-package-version"];
384
508
  if (version)
385
509
  values.package_version = version;
386
510
  values.layout = defaultLayoutFor(schema);
387
- await writeFileAtomic(path.join(root, PROJECT_FILE), solutionYaml(values));
511
+ const note = tenant && (tenant.name || tenant.id !== tenant.ref) ? commentText([tenant.name, tenant.id !== tenant.ref ? tenant.id : undefined].filter(Boolean).join(", ")) : undefined;
512
+ await writeFileAtomic(path.join(root, PROJECT_FILE), solutionYaml(values, note));
388
513
  actions.push({ file: PROJECT_FILE, action: "created" });
389
514
  }
390
515
  const project = parseProject(path.join(root, PROJECT_FILE), (await readTextFile(path.join(root, PROJECT_FILE))));
@@ -417,14 +542,21 @@ async function runInit(ctx, input) {
417
542
  result = await importPackage(ctx, project, from, imported, boolOption(input, "force"));
418
543
  if (packageHarness && !project.harness && !stringOption(input, "harness"))
419
544
  await setProjectKey(project, "harness", packageHarness);
420
- next.unshift("Check it offline: cavelon validate", `Preview it on the instance: cavelon apply${harness ? " --env test" : " --harness <slug>"}`);
545
+ next.unshift("Check it offline: cavelon validate", `Preview it on the instance: cavelon apply${harness ? " --env test" : " --harness <name or slug>"}`);
421
546
  }
422
547
  else if (!(await hasPackageFiles(root, project.layout.package))) {
423
- next.unshift(harness
424
- ? `Bring the solution into package/: cavelon pull`
425
- : "Bring an existing solution into package/: cavelon pull --harness <slug> (or write package files, then cavelon validate)");
548
+ const choices = chosenHarness?.choices ?? [];
549
+ if (chosenHarness?.created || chosenHarness?.missing)
550
+ next.unshift("Write the package files in package/, then: cavelon validate");
551
+ else if (harness)
552
+ next.unshift(`Bring the solution into package/: cavelon pull`);
553
+ else if (choices.length) {
554
+ next.unshift("Bring one of this tenant's solutions into package/ (or write package files, then cavelon validate):", ...choices.slice(0, 10).map((h) => ` ${cavelonCommand("pull", "--harness", h.slug)}${h.name !== h.slug ? ` ${h.name}` : ""}`), ...(choices.length > 10 ? [` … and ${choices.length - 10} more (\`cavelon harness list\`)`] : []));
555
+ }
556
+ else
557
+ next.unshift("Bring an existing solution into package/: cavelon pull --harness <name or slug> (or write package files, then cavelon validate)");
426
558
  }
427
- return { root, actions, next, imported: result };
559
+ return { root, actions, next, imported: result, harness: chosenHarness };
428
560
  }
429
561
  export const init = {
430
562
  name: "init",
@@ -440,7 +572,11 @@ export const init = {
440
572
  idempotent: true,
441
573
  mcpTool: "init",
442
574
  options: {
443
- harness: { type: "string", value: "<slug>", description: "The solution (harness) this folder holds; pull and apply use it." },
575
+ harness: {
576
+ type: "string",
577
+ value: "<harness>",
578
+ description: "The solution (harness) this folder holds, by name, slug or id; its slug goes into cavelon.yaml. Without it, init asks on a terminal.",
579
+ },
444
580
  agents: {
445
581
  type: "string",
446
582
  value: "<list>",
@@ -453,13 +589,14 @@ export const init = {
453
589
  force: { type: "boolean", description: "With --from: replace package files that hold something else." },
454
590
  },
455
591
  examples: [
456
- "cavelon init --instance https://cavelon.example.com --tenant acme --harness support",
592
+ "cavelon init",
593
+ "cavelon init --instance https://cavelon.example.com --tenant \"Acme Support\" --harness \"Support FAQ\"",
457
594
  "cavelon init --agents codex,cursor --hook",
458
595
  "cavelon init --update",
459
596
  "cavelon init --instance https://cavelon.example.com --tenant acme --from ./blueprint.json",
460
597
  ],
461
598
  async run(ctx, input) {
462
- const { root, actions, next, imported } = await runInit(ctx, input);
599
+ const { root, actions, next, imported, harness } = await runInit(ctx, input);
463
600
  const changed = actions.filter((a) => a.action !== "unchanged");
464
601
  const skipped = actions.filter((a) => a.action === "skipped");
465
602
  for (const s of skipped)
@@ -476,6 +613,7 @@ export const init = {
476
613
  lines.length ? lines.join("\n") : "Nothing to change.",
477
614
  ...(next.length ? ["", "Next:", ...next.map((n) => ` ${n}`)] : []),
478
615
  ].join("\n");
479
- return { data: { solution: root, files: actions, ...(imported ? { imported } : {}), next }, text };
616
+ const choices = harness?.choices && !harness.slug ? { solutions: harness.choices } : {};
617
+ return { data: { solution: root, files: actions, ...(imported ? { imported } : {}), ...choices, next }, text };
480
618
  },
481
619
  };
@@ -349,7 +349,7 @@ async function pathParams(ctx, change, principal) {
349
349
  }
350
350
  const tenantId = (await ctx.client()).target.tenantId ?? principal?.tenant_id ?? undefined;
351
351
  if (!tenantId)
352
- throw usageError("Which tenant? Choose one with `cavelon use <tenant>` or --tenant.");
352
+ throw usageError("Which tenant? Choose one with `cavelon use` (it lists your tenants) or --tenant.");
353
353
  params[name] = [tenantId];
354
354
  }
355
355
  return params;
@@ -505,7 +505,7 @@ export const limitsSet = {
505
505
  throw new CavelonError(ExitCode.usage, {
506
506
  code: "tenant_required",
507
507
  message: "Limits belong to a tenant, and none is chosen.",
508
- hint: "Choose one with `cavelon use <tenant>` or pass --tenant; an operator's change reads the limits of any tenant and sends in Platform mode.",
508
+ hint: "Choose one with `cavelon use` (it lists your tenants) or pass --tenant; an operator's change reads the limits of any tenant and sends in Platform mode.",
509
509
  });
510
510
  }
511
511
  if (!published.published) {
@@ -56,7 +56,7 @@ export const limits = {
56
56
  throw new CavelonError(ExitCode.usage, {
57
57
  code: "tenant_required",
58
58
  message: "Limits belong to a tenant, and none is chosen.",
59
- hint: "Choose one with `cavelon use <tenant>` or pass --tenant.",
59
+ hint: "Choose one with `cavelon use` (it lists your tenants) or pass --tenant <name or slug>.",
60
60
  });
61
61
  }
62
62
  if (!published.published) {
@@ -691,7 +691,7 @@ async function resolveApiKey(ctx, ref) {
691
691
  const client = await ctx.client();
692
692
  const tenantId = client.target.tenantId ?? (await readPrincipal(client))?.tenant_id ?? undefined;
693
693
  if (!tenantId)
694
- throw usageError("Which tenant's API keys? Choose one with `cavelon use <tenant>` or --tenant, or pass the key's id.");
694
+ throw usageError("Which tenant's API keys? Choose one with `cavelon use` (it lists your tenants) or --tenant, or pass the key's id.");
695
695
  const keys = [];
696
696
  for (let offset = 0; offset < 1000; offset += 100) {
697
697
  const page = await callStable(ctx, "GET", "/api/v1/tenants/{tenant_id}/api-keys", "API keys", {
@@ -12,7 +12,7 @@ import { isUuid } from "../session.js";
12
12
  import { cavelonCommand } from "../shell.js";
13
13
  import { archiveFrom } from "../tar.js";
14
14
  import { TIMEOUT_OPTION, timeoutMs, waitAndReport } from "./async.js";
15
- import { resolveHarnessId } from "./tenants.js";
15
+ import { resolveHarnessId } from "../harness-ref.js";
16
16
  const MODES = {
17
17
  isolated_container: {
18
18
  offers: ["archive", "receipt"],
@@ -27,7 +27,7 @@ const WAIT_OPTION = { type: "boolean", description: "Wait for the job to finish
27
27
  const HARNESS_OPTION = {
28
28
  type: "string",
29
29
  value: "<harness>",
30
- description: "The solution the Sandbox is read for (default: cavelon.yaml's, or the Sandbox's only allowed one).",
30
+ description: "The solution the Sandbox is read for, by name, slug or id (default: cavelon.yaml's, or the Sandbox's only allowed one).",
31
31
  };
32
32
  const REVISION_OPTION = {
33
33
  type: "string",