@cavelon/cli 0.1.2 → 0.1.4

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.
@@ -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`).",
@@ -123,7 +129,7 @@ async function writeMcp(root, target, onlyExisting) {
123
129
  if (target.format === "toml")
124
130
  return applyBlock(root, file, upsertBlock(existing, target.block, "hash", { onlyExisting }));
125
131
  if (onlyExisting) {
126
- let present = false;
132
+ let present;
127
133
  try {
128
134
  present = Boolean(existing && JSON.parse(existing)[target.keys[0]]?.[target.keys[1]]);
129
135
  }
@@ -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",