@cavelon/cli 0.1.1 → 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.
Files changed (52) hide show
  1. package/README.md +50 -20
  2. package/dist/agents.js +43 -19
  3. package/dist/choose.js +112 -0
  4. package/dist/command.js +1 -1
  5. package/dist/commands/api.js +76 -6
  6. package/dist/commands/index.js +2 -0
  7. package/dist/commands/init.js +196 -29
  8. package/dist/commands/limits-set.js +17 -8
  9. package/dist/commands/limits.js +2 -2
  10. package/dist/commands/loops.js +12 -6
  11. package/dist/commands/sandboxes.js +27 -20
  12. package/dist/commands/session.js +179 -45
  13. package/dist/commands/setup.js +426 -0
  14. package/dist/commands/solution.js +137 -91
  15. package/dist/commands/tenants.js +33 -22
  16. package/dist/commands/values.js +8 -5
  17. package/dist/commands/work.js +33 -16
  18. package/dist/context.js +5 -1
  19. package/dist/contracts.js +83 -38
  20. package/dist/embedded.js +7 -0
  21. package/dist/features.js +15 -0
  22. package/dist/fsutil.js +3 -0
  23. package/dist/git.js +14 -9
  24. package/dist/harness-ref.js +54 -0
  25. package/dist/http.js +44 -18
  26. package/dist/install.js +94 -0
  27. package/dist/invoke.js +17 -13
  28. package/dist/limits.js +9 -1
  29. package/dist/local-state.js +18 -0
  30. package/dist/main.js +31 -2
  31. package/dist/markers.js +53 -0
  32. package/dist/mcp.js +9 -2
  33. package/dist/openapi.js +10 -0
  34. package/dist/operations.js +1 -1
  35. package/dist/package-check.js +1 -1
  36. package/dist/package-files.js +103 -38
  37. package/dist/paths.js +53 -4
  38. package/dist/principal.js +43 -0
  39. package/dist/project.js +23 -4
  40. package/dist/prompt.js +55 -11
  41. package/dist/results.js +47 -9
  42. package/dist/run-program.js +92 -0
  43. package/dist/session.js +100 -19
  44. package/dist/setup-agents.js +544 -0
  45. package/dist/skills/cavelon-authoring/SKILL.md +13 -3
  46. package/dist/skills/cavelon-long-running/SKILL.md +5 -1
  47. package/dist/skills/cavelon-loop/SKILL.md +15 -9
  48. package/dist/skills/cavelon-testing/SKILL.md +9 -2
  49. package/dist/tenant-choice.js +93 -0
  50. package/dist/update-check.js +118 -0
  51. package/dist/version.js +2 -1
  52. package/package.json +5 -2
package/dist/paths.js CHANGED
@@ -1,6 +1,10 @@
1
+ import { createHash } from "node:crypto";
2
+ import { promises as fs } from "node:fs";
1
3
  import os from "node:os";
2
4
  import path from "node:path";
3
- function home(env) {
5
+ import { CavelonError, ExitCode } from "./errors.js";
6
+ import { findProject } from "./project.js";
7
+ export function homeDir(env) {
4
8
  return env.HOME || env.USERPROFILE || os.homedir();
5
9
  }
6
10
  export function configDir(env) {
@@ -10,7 +14,7 @@ export function configDir(env) {
10
14
  return path.join(env.XDG_CONFIG_HOME, "cavelon");
11
15
  if (process.platform === "win32" && env.APPDATA)
12
16
  return path.join(env.APPDATA, "cavelon");
13
- return path.join(home(env), ".config", "cavelon");
17
+ return path.join(homeDir(env), ".config", "cavelon");
14
18
  }
15
19
  export function cacheDir(env) {
16
20
  if (env.CAVELON_CACHE_DIR)
@@ -19,10 +23,55 @@ export function cacheDir(env) {
19
23
  return path.join(env.XDG_CACHE_HOME, "cavelon");
20
24
  if (process.platform === "win32" && env.LOCALAPPDATA)
21
25
  return path.join(env.LOCALAPPDATA, "cavelon", "cache");
22
- return path.join(home(env), ".cache", "cavelon");
26
+ return path.join(homeDir(env), ".cache", "cavelon");
23
27
  }
24
28
  export function instanceKey(url) {
25
29
  const parsed = new URL(url);
26
30
  const parts = [parsed.hostname, parsed.port, parsed.pathname.replace(/^\/+|\/+$/g, "")].filter(Boolean);
27
- return parts.join("_").replace(/[^A-Za-z0-9._-]+/g, "_");
31
+ const readable = parts.join("_").replace(/[^A-Za-z0-9._-]+/g, "_");
32
+ return `${readable}-${createHash("sha256").update(url).digest("hex").slice(0, 8)}`;
33
+ }
34
+ export async function confinedPath(ctx, raw, what) {
35
+ const resolved = path.resolve(ctx.io.cwd, raw);
36
+ if (ctx.mode !== "mcp")
37
+ return resolved;
38
+ const root = (await findProject(ctx.io.cwd))?.root ?? ctx.io.cwd;
39
+ const real = await realPath(resolved);
40
+ if (!within(await realPath(root), real)) {
41
+ throw new CavelonError(ExitCode.usage, {
42
+ code: "path_outside_solution",
43
+ message: `${what} ${raw} is outside the solution folder ${root}; over MCP a tool reads and writes only there.`,
44
+ hint: "Name a file inside the solution folder, or ask the person to run the command in their terminal.",
45
+ });
46
+ }
47
+ for (const dir of [configDir(ctx.io.env), cacheDir(ctx.io.env)]) {
48
+ if (within(await realPath(path.resolve(ctx.io.cwd, dir)), real, true)) {
49
+ throw new CavelonError(ExitCode.usage, {
50
+ code: "path_in_kit_directory",
51
+ message: `${what} ${raw} is in cavelon's own directory ${dir}, which holds its login and cache; no tool reads or writes there.`,
52
+ });
53
+ }
54
+ }
55
+ return resolved;
56
+ }
57
+ export async function realPath(file) {
58
+ const rest = [];
59
+ let current = file;
60
+ for (;;) {
61
+ try {
62
+ return path.join(await fs.realpath(current), ...rest.reverse());
63
+ }
64
+ catch (error) {
65
+ const parent = path.dirname(current);
66
+ if (error.code !== "ENOENT" || parent === current)
67
+ throw error;
68
+ rest.push(path.basename(current));
69
+ current = parent;
70
+ }
71
+ }
72
+ }
73
+ export function within(dir, file, fold = false) {
74
+ const norm = (p) => (fold && (process.platform === "win32" || process.platform === "darwin") ? p.toLowerCase() : p);
75
+ const rel = path.relative(norm(dir), norm(file));
76
+ return rel === "" || (rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel));
28
77
  }
package/dist/principal.js CHANGED
@@ -5,6 +5,49 @@ export async function readPrincipal(client, options = {}) {
5
5
  const { permissions, ...rest } = response.data;
6
6
  return Array.isArray(permissions) ? { ...rest, permissions: permissions.filter((p) => typeof p === "string") } : rest;
7
7
  }
8
+ const TENANT_PAGE = 200;
9
+ const MAX_TENANT_PAGES = 5;
10
+ function reachableTenants(value) {
11
+ if (!Array.isArray(value))
12
+ return undefined;
13
+ const text = (v) => (typeof v === "string" && v ? v : null);
14
+ return value
15
+ .filter((t) => Boolean(t) && typeof t === "object" && typeof t.id === "string")
16
+ .map((t) => ({ id: t.id, slug: text(t.slug), name: text(t.name), role: text(t.role), is_default: t.is_default === true }));
17
+ }
18
+ export async function readTenantless(client, options = {}) {
19
+ const read = (cursor) => client.get("/api/v1/meta/principal", {
20
+ allow: [400, 403, 404, 405, 422],
21
+ sendTenant: false,
22
+ query: options.search !== undefined ? { search: options.search } : { limit: TENANT_PAGE, cursor },
23
+ });
24
+ const response = await read();
25
+ if (response.status === 403) {
26
+ const detail = response.data?.detail;
27
+ return { refused: true, said: typeof detail === "string" && detail ? detail : "403 Forbidden" };
28
+ }
29
+ if (response.status !== 200 || !response.data)
30
+ return undefined;
31
+ const { mode, tenant_id: tenantId } = response.data;
32
+ let tenants = reachableTenants(response.data.tenants);
33
+ let next = response.data.next_cursor;
34
+ for (let pages = 1; tenants && options.search === undefined && typeof next === "string" && next && pages < MAX_TENANT_PAGES; pages++) {
35
+ const page = await read(next);
36
+ const more = page.status === 200 ? reachableTenants(page.data?.tenants) : undefined;
37
+ if (!more)
38
+ break;
39
+ tenants = [...tenants, ...more];
40
+ next = page.data?.next_cursor;
41
+ }
42
+ const reachesAll = response.data.reaches_all_tenants === true;
43
+ if (mode === "tenant" && typeof tenantId === "string")
44
+ return { refused: false, tenantId, platform: false, tenants, reachesAll };
45
+ if (mode === "platform" && response.data.token?.platform_mode_allowed !== false)
46
+ return { refused: false, tenantId: null, platform: true, tenants, reachesAll };
47
+ if (!tenants)
48
+ return undefined;
49
+ return { refused: false, tenantId: null, platform: false, tenants, reachesAll };
50
+ }
8
51
  export async function readGlobalRole(client) {
9
52
  const response = await client.get("/api/v1/auth/me", { allow: [400, 401, 403, 404], sendTenant: false });
10
53
  if (response.status !== 200 || !response.data)
package/dist/project.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { promises as fs } from "node:fs";
1
2
  import path from "node:path";
2
3
  import { parse } from "yaml";
3
4
  import { readTextFile } from "./fsutil.js";
@@ -71,17 +72,36 @@ function refuseCredentials(file, map) {
71
72
  }
72
73
  }
73
74
  export const ENV_DIR = "env";
75
+ const ENV_NAME = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
74
76
  export function envFilePath(project, name) {
75
- if (!/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(name)) {
77
+ if (!ENV_NAME.test(name)) {
76
78
  throw usageError(`"${name}" is not an environment name.`, "Use letters, digits, dashes and underscores, as in --env test.");
77
79
  }
78
80
  return path.join(project.root, ENV_DIR, `${name}.yaml`);
79
81
  }
82
+ export async function envNames(project) {
83
+ let entries;
84
+ try {
85
+ entries = await fs.readdir(path.join(project.root, ENV_DIR));
86
+ }
87
+ catch {
88
+ return [];
89
+ }
90
+ return entries
91
+ .filter((entry) => entry.endsWith(".yaml"))
92
+ .map((entry) => entry.slice(0, -".yaml".length))
93
+ .filter((name) => ENV_NAME.test(name))
94
+ .sort();
95
+ }
80
96
  export async function readEnvFile(project, name) {
81
97
  const file = envFilePath(project, name);
82
98
  const text = await readTextFile(file);
83
- if (text === undefined)
84
- return { name, file, exists: false, runtimeBindings: {}, raw: {} };
99
+ if (text === undefined) {
100
+ const known = await envNames(project);
101
+ throw usageError(`No ${ENV_DIR}/${name}.yaml in this solution; nothing was sent.`, known.length
102
+ ? `Its env files: ${known.join(", ")}. Pass one of them to --env, or write ${ENV_DIR}/${name}.yaml first.`
103
+ : "`cavelon init` writes env/test.yaml and env/prod.yaml.");
104
+ }
85
105
  let raw;
86
106
  try {
87
107
  raw = parse(text) ?? {};
@@ -128,7 +148,6 @@ export async function readEnvFile(project, name) {
128
148
  return {
129
149
  name,
130
150
  file,
131
- exists: true,
132
151
  tenant: stringField(map.tenant, "id", "slug"),
133
152
  harness: stringField(map.harness, "slug", "id"),
134
153
  mode: mode,
package/dist/prompt.js CHANGED
@@ -1,34 +1,78 @@
1
1
  import { CavelonError, ExitCode } from "./errors.js";
2
- export function readHidden(io, label, cancelled = "Login cancelled.") {
2
+ const leftover = new WeakMap();
3
+ export function canAsk(ctx) {
4
+ return ctx.mode === "cli" && !ctx.json && Boolean(ctx.io.stdin.isTTY) && Boolean(ctx.io.stderr.isTTY);
5
+ }
6
+ function cancelledError(message) {
7
+ return new CavelonError(ExitCode.failure, { code: "cancelled", message });
8
+ }
9
+ function readUntilLine(io, label, hidden, cancelled) {
3
10
  const stdin = io.stdin;
4
11
  return new Promise((resolve, reject) => {
5
12
  let value = "";
13
+ let done = false;
6
14
  io.stderr.write(label);
7
- const finish = (error) => {
8
- stdin.setRawMode?.(false);
15
+ const finish = (error, rest = "") => {
16
+ done = true;
17
+ if (rest)
18
+ leftover.set(stdin, rest);
19
+ else
20
+ leftover.delete(stdin);
21
+ if (hidden)
22
+ stdin.setRawMode?.(false);
9
23
  stdin.off?.("data", onData);
24
+ stdin.off?.("end", onEnd);
10
25
  stdin.pause?.();
11
- io.stderr.write("\n");
26
+ if (hidden || error)
27
+ io.stderr.write("\n");
12
28
  if (error)
13
29
  reject(error);
14
30
  else
15
31
  resolve(value);
16
32
  };
17
- const onData = (chunk) => {
18
- for (const char of typeof chunk === "string" ? chunk : chunk.toString("utf8")) {
19
- if (char === "\r" || char === "\n")
20
- return finish();
21
- if (char === "\u0003" || char === "\u0004") {
22
- return finish(new CavelonError(ExitCode.failure, { code: "cancelled", message: cancelled }));
33
+ const take = (text) => {
34
+ const chars = [...text];
35
+ for (let i = 0; i < chars.length; i++) {
36
+ const char = chars[i];
37
+ if (char === "\r" || char === "\n") {
38
+ const next = char === "\r" && chars[i + 1] === "\n" ? i + 2 : i + 1;
39
+ return finish(undefined, chars.slice(next).join(""));
23
40
  }
41
+ if (char === "\u0003" || char === "\u0004")
42
+ return finish(cancelledError(cancelled));
24
43
  if (char === "\u007f" || char === "\b")
25
44
  value = value.slice(0, -1);
26
45
  else if (char >= " ")
27
46
  value += char;
28
47
  }
29
48
  };
30
- stdin.setRawMode?.(true);
49
+ const onData = (chunk) => {
50
+ if (!done)
51
+ take(typeof chunk === "string" ? chunk : chunk.toString("utf8"));
52
+ };
53
+ const onEnd = () => {
54
+ if (!done)
55
+ finish(cancelledError(cancelled));
56
+ };
57
+ const pending = leftover.get(stdin);
58
+ if (pending) {
59
+ leftover.delete(stdin);
60
+ take(pending);
61
+ if (done)
62
+ return;
63
+ }
64
+ if (stdin.readableEnded)
65
+ return finish(cancelledError(cancelled));
66
+ if (hidden)
67
+ stdin.setRawMode?.(true);
31
68
  stdin.on?.("data", onData);
69
+ stdin.on?.("end", onEnd);
32
70
  stdin.resume?.();
33
71
  });
34
72
  }
73
+ export function readHidden(io, label, cancelled = "Login cancelled.") {
74
+ return readUntilLine(io, label, true, cancelled);
75
+ }
76
+ export async function readLine(io, label, cancelled = "Cancelled; nothing was chosen.") {
77
+ return (await readUntilLine(io, label, false, cancelled)).trim();
78
+ }
package/dist/results.js CHANGED
@@ -4,11 +4,37 @@ import { callStable } from "./invoke.js";
4
4
  import { cavelonCommand } from "./shell.js";
5
5
  export const NOT_PASSED = new Set(["fail", "error"]);
6
6
  export function caseCounts(summary) {
7
- const count = (key) => {
8
- const value = Number(summary?.[key] ?? 0);
9
- return Number.isFinite(value) && value > 0 ? value : 0;
10
- };
11
- return { failed: count("failed"), errors: count("errors") };
7
+ return { failed: summaryCount(summary, "failed"), errors: summaryCount(summary, "errors") };
8
+ }
9
+ function summaryCount(summary, key) {
10
+ const value = Number(summary?.[key] ?? 0);
11
+ return Number.isFinite(value) && value > 0 ? value : 0;
12
+ }
13
+ const NOT_PASSED_COUNTS = ["failed", "errors", "technical_errors", "not_run", "cases_not_run", "missing_results", "unmeasurable_cases", "skipped"];
14
+ const WAITING_COUNTS = ["pending_review", "calibration_required"];
15
+ export function runVerdict(summary) {
16
+ const counts = {};
17
+ for (const key of [...NOT_PASSED_COUNTS, ...WAITING_COUNTS]) {
18
+ const value = summaryCount(summary, key);
19
+ if (value > 0)
20
+ counts[key] = value;
21
+ }
22
+ const said = summary?.comparable;
23
+ const comparable = typeof said === "boolean" ? said : summary && "pass_rate" in summary && summary.pass_rate == null ? false : null;
24
+ const reasons = Array.isArray(summary?.non_comparable_reasons) ? summary.non_comparable_reasons.map(String) : [];
25
+ let exitCode = 0;
26
+ if (NOT_PASSED_COUNTS.some((k) => k in counts))
27
+ exitCode = 1;
28
+ else if (WAITING_COUNTS.some((k) => k in counts))
29
+ exitCode = 5;
30
+ else if (comparable === false)
31
+ exitCode = 1;
32
+ return { counts, comparable, non_comparable_reasons: reasons, exit_code: exitCode };
33
+ }
34
+ export function countsText(counts) {
35
+ return Object.entries(counts)
36
+ .map(([key, value]) => `${value} ${key === "errors" ? "errored" : key.replaceAll("_", " ")}`)
37
+ .join(", ");
12
38
  }
13
39
  const MAX_CASES = 5;
14
40
  const REASON_CHARS = 500;
@@ -28,9 +54,10 @@ export async function resultFailure(ctx, op) {
28
54
  const id = op.result_ref.id;
29
55
  try {
30
56
  const run = await callStable(ctx, "GET", "/api/v1/test-runs/{run_id}", "test runs", { params: { run_id: [id] } });
31
- const { failed, errors } = caseCounts(run.summary);
32
- if (failed + errors === 0)
57
+ const verdict = runVerdict(run.summary);
58
+ if (verdict.exit_code === 0)
33
59
  return undefined;
60
+ const { failed, errors } = caseCounts(run.summary);
34
61
  const results = await callStable(ctx, "GET", "/api/v1/test-runs/{run_id}/results", "test results", { params: { run_id: [id] } });
35
62
  return {
36
63
  type: "test_run",
@@ -38,6 +65,10 @@ export async function resultFailure(ctx, op) {
38
65
  suite: run.suite_name ?? run.suite_id,
39
66
  failed_cases: failed,
40
67
  errored_cases: errors,
68
+ counts: verdict.counts,
69
+ comparable: verdict.comparable,
70
+ non_comparable_reasons: verdict.non_comparable_reasons,
71
+ exit_code: verdict.exit_code,
41
72
  cases: results.filter((r) => NOT_PASSED.has(r.status)).slice(0, MAX_CASES).map((r) => failedCase(r)),
42
73
  trace: cavelonCommand("trace", id),
43
74
  };
@@ -53,8 +84,15 @@ export function caseLabel(c) {
53
84
  return c.step === null ? c.case : `${c.case} (step ${c.step})`;
54
85
  }
55
86
  export function failureLines(failure) {
56
- const counts = [failure.failed_cases ? `${failure.failed_cases} failed` : "", failure.errored_cases ? `${failure.errored_cases} errored` : ""].filter(Boolean).join(", ");
57
- const lines = [` test run ${failure.id} (${failure.suite}) finished, but cases did not pass: ${counts}`];
87
+ const head = ` test run ${failure.id} (${failure.suite}) finished, but`;
88
+ const counts = countsText(failure.counts);
89
+ const lines = [
90
+ counts
91
+ ? `${head} ${failure.exit_code === 5 ? "answers wait for a person" : "cases did not pass"}: ${counts}`
92
+ : `${head} it measured nothing comparable and has no pass rate`,
93
+ ];
94
+ if (failure.comparable === false && failure.non_comparable_reasons.length)
95
+ lines.push(` Not comparable: ${failure.non_comparable_reasons.join(", ")}`);
58
96
  for (const c of failure.cases)
59
97
  lines.push(` ${caseLabel(c)} ${c.status}${c.reason ? ": " + c.reason : ""}`);
60
98
  const shown = failure.cases.length;
@@ -0,0 +1,92 @@
1
+ import { execFile, spawn } from "node:child_process";
2
+ import path from "node:path";
3
+ const MAX_OUTPUT = 4 * 1024 * 1024;
4
+ export function invocation(file, args, env = process.env, platform = process.platform) {
5
+ if (platform === "win32" && /\.(cmd|bat)$/i.test(file)) {
6
+ const line = [`"${file}"`, ...args.map((a) => (/^[\w@./:=-]+$/.test(a) ? a : `"${a.replaceAll('"', '""')}"`))].join(" ");
7
+ return { file: env.ComSpec || env.COMSPEC || "cmd.exe", args: ["/d", "/s", "/c", `"${line}"`], verbatim: true };
8
+ }
9
+ return { file, args, verbatim: false };
10
+ }
11
+ export function runProgram(file, args, options) {
12
+ const how = invocation(file, args, options.env);
13
+ return new Promise((resolve) => {
14
+ execFile(how.file, how.args, {
15
+ env: options.env,
16
+ cwd: options.cwd,
17
+ timeout: options.timeoutMs,
18
+ maxBuffer: MAX_OUTPUT,
19
+ windowsHide: true,
20
+ windowsVerbatimArguments: how.verbatim,
21
+ encoding: "utf8",
22
+ }, (error, stdout, stderr) => {
23
+ if (!error)
24
+ return resolve({ code: 0, stdout, stderr });
25
+ const err = error;
26
+ if (err.killed)
27
+ return resolve({ code: null, stdout, stderr, error: `${path.basename(file)} did not finish within ${Math.round(options.timeoutMs / 1000)} s` });
28
+ if (typeof err.code === "number")
29
+ return resolve({ code: err.code, stdout, stderr });
30
+ resolve({ code: null, stdout, stderr, error: err.message });
31
+ });
32
+ });
33
+ }
34
+ export function probeMcpServer(command, args, options) {
35
+ return new Promise((resolve) => {
36
+ let settled = false;
37
+ let out = "";
38
+ let err = "";
39
+ const child = spawn(command, args, { env: options.env, cwd: options.cwd, stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
40
+ const finish = (probe) => {
41
+ if (settled)
42
+ return;
43
+ settled = true;
44
+ clearTimeout(timer);
45
+ child.stdin.end();
46
+ child.kill();
47
+ resolve(probe);
48
+ };
49
+ const timer = setTimeout(() => finish({ ok: false, error: `it did not answer within ${Math.round(options.timeoutMs / 1000)} s` }), options.timeoutMs);
50
+ child.on("error", (error) => finish({ ok: false, error: error.code === "ENOENT" ? `${command} was not found` : error.message }));
51
+ child.on("exit", (code) => finish({ ok: false, error: `it stopped (exit ${code ?? "signal"})${err.trim() ? `: ${lastLine(err)}` : ""}` }));
52
+ child.stderr.on("data", (chunk) => {
53
+ if (err.length < MAX_OUTPUT)
54
+ err += chunk.toString("utf8");
55
+ });
56
+ child.stdout.on("data", (chunk) => {
57
+ out += chunk.toString("utf8");
58
+ if (out.length > MAX_OUTPUT)
59
+ return finish({ ok: false, error: "it wrote more than an MCP answer" });
60
+ let newline;
61
+ while ((newline = out.indexOf("\n")) >= 0) {
62
+ const line = out.slice(0, newline).trim();
63
+ out = out.slice(newline + 1);
64
+ if (!line)
65
+ continue;
66
+ try {
67
+ const message = JSON.parse(line);
68
+ if (message.id !== 1)
69
+ continue;
70
+ if (message.result) {
71
+ const info = message.result.serverInfo;
72
+ return finish({ ok: true, server: info ? `${info.name ?? "?"} ${info.version ?? ""}`.trim() : undefined });
73
+ }
74
+ return finish({ ok: false, error: message.error?.message ?? "it refused to initialize" });
75
+ }
76
+ catch {
77
+ }
78
+ }
79
+ });
80
+ child.stdin.on("error", () => undefined);
81
+ child.stdin.write(JSON.stringify({
82
+ jsonrpc: "2.0",
83
+ id: 1,
84
+ method: "initialize",
85
+ params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "cavelon-setup-check", version: options.clientVersion } },
86
+ }) + "\n");
87
+ });
88
+ }
89
+ function lastLine(text) {
90
+ const lines = text.split(/\r?\n/).filter((l) => l.trim());
91
+ return (lines[lines.length - 1] ?? "").slice(0, 300);
92
+ }
package/dist/session.js CHANGED
@@ -1,5 +1,9 @@
1
1
  import { CavelonError, ExitCode, notLoggedIn, usageError } from "./errors.js";
2
+ import { TENANT_ID_HINT } from "./http.js";
2
3
  import { readToken } from "./credentials.js";
4
+ import { exactMatch } from "./choose.js";
5
+ import { readTenantless } from "./principal.js";
6
+ import { listsTenants, searchTenants, tenantMissError } from "./tenant-choice.js";
3
7
  import { findProject, readEnvFile } from "./project.js";
4
8
  import { loadUserConfig, tokenKind, updateInstance } from "./user-config.js";
5
9
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
@@ -33,6 +37,16 @@ export function normalizeUrl(input, env = {}) {
33
37
  const pathname = url.pathname.replace(/\/+$/, "");
34
38
  return `${url.protocol}//${url.host.toLowerCase()}${pathname}`;
35
39
  }
40
+ function sameUrl(input, url, env) {
41
+ if (!input)
42
+ return false;
43
+ try {
44
+ return normalizeUrl(input, env) === url;
45
+ }
46
+ catch {
47
+ return false;
48
+ }
49
+ }
36
50
  export async function resolveSession(env, cwd, globals) {
37
51
  const project = await findProject(cwd);
38
52
  const config = await loadUserConfig(env);
@@ -45,11 +59,10 @@ export async function resolveSession(env, cwd, globals) {
45
59
  }
46
60
  let url;
47
61
  let urlSource;
48
- const envUrl = env.CAVELON_URL ? normalizeUrl(env.CAVELON_URL, env) : undefined;
49
62
  if (globals.instance)
50
63
  [url, urlSource] = [normalizeUrl(globals.instance, env), "option"];
51
- else if (envUrl)
52
- [url, urlSource] = [envUrl, "CAVELON_URL"];
64
+ else if (env.CAVELON_URL)
65
+ [url, urlSource] = [normalizeUrl(env.CAVELON_URL, env), "CAVELON_URL"];
53
66
  else if (project?.instance)
54
67
  [url, urlSource] = [normalizeUrl(project.instance, env), "cavelon.yaml"];
55
68
  else if (config.current_instance)
@@ -58,9 +71,9 @@ export async function resolveSession(env, cwd, globals) {
58
71
  const session = { url, urlSource, project, envFile, settings };
59
72
  if (!url)
60
73
  return session;
61
- if (env.CAVELON_TOKEN && !envUrl)
74
+ if (env.CAVELON_TOKEN && !env.CAVELON_URL)
62
75
  session.ignoredEnvToken = true;
63
- if (env.CAVELON_TOKEN && envUrl === url) {
76
+ if (env.CAVELON_TOKEN && sameUrl(env.CAVELON_URL, url, env)) {
64
77
  session.token = env.CAVELON_TOKEN.trim();
65
78
  session.tokenSource = "CAVELON_TOKEN";
66
79
  }
@@ -74,7 +87,7 @@ export async function resolveSession(env, cwd, globals) {
74
87
  }
75
88
  if (session.token)
76
89
  session.tokenKind = tokenKind(session.token);
77
- const projectMatches = project && (!project.instance || normalizeUrl(project.instance, env) === url);
90
+ const projectMatches = project && (!project.instance || sameUrl(project.instance, url, env));
78
91
  if (globals.tenant)
79
92
  [session.tenant, session.tenantSource] = [globals.tenant, "option"];
80
93
  else if (env.CAVELON_TENANT)
@@ -111,17 +124,83 @@ export function requireToken(session) {
111
124
  }
112
125
  return session.token;
113
126
  }
114
- export async function lookupTenantId(client, ref) {
127
+ const MAX_SLUG_LOOKUPS = 25;
128
+ export const TENANT_REF_HINT = "Use the tenant's name or id instead: a member's token finds a tenant by its slug only where it may view the tenant's settings. `cavelon tenant list` shows the names and ids.";
129
+ export function tenantRequiredError(url, said, lead = "No tenant is chosen") {
130
+ return new CavelonError(ExitCode.usage, {
131
+ code: "tenant_required",
132
+ status: 403,
133
+ message: `${lead}, and ${url} answers this token only inside a tenant: ${said}`,
134
+ hint: TENANT_ID_HINT,
135
+ });
136
+ }
137
+ export async function lookupTenantId(client, ref, from) {
115
138
  if (isUuid(ref))
116
139
  return { id: ref };
140
+ if (client.target.token?.startsWith("cvpat_")) {
141
+ const reach = await readTenantless(client);
142
+ if (listsTenants(reach) && !reach.platform)
143
+ return findInReach(client, reach, ref, from);
144
+ }
145
+ const lookup = await findTenant(client, ref);
146
+ if (lookup.found)
147
+ return lookup.found;
148
+ throw tenantNotFoundError(ref, lookup.known, from);
149
+ }
150
+ function foundOf(tenant) {
151
+ return { id: tenant.id, ...(tenant.name ? { name: tenant.name } : {}), ...(tenant.slug ? { slug: tenant.slug } : {}) };
152
+ }
153
+ async function findInReach(client, reach, ref, from) {
154
+ const own = exactMatch(reach.tenants, ref);
155
+ if (own)
156
+ return foundOf(own);
157
+ const pool = [...reach.tenants];
158
+ if (reach.reachesAll) {
159
+ const words = [ref, ...ref.split(/[\s_-]+/).filter((w) => w.length >= 3 && w !== ref)].slice(0, 4);
160
+ for (const word of words) {
161
+ const found = await searchTenants(client, word);
162
+ const hit = exactMatch(found, ref);
163
+ if (hit)
164
+ return foundOf(hit);
165
+ for (const t of found)
166
+ if (!pool.some((p) => p.id === t.id))
167
+ pool.push(t);
168
+ if (pool.length > reach.tenants.length)
169
+ break;
170
+ }
171
+ }
172
+ throw tenantMissError(ref, pool, reach.reachesAll, from);
173
+ }
174
+ const MAX_NAMED_TENANTS = 20;
175
+ function tenantNotFoundError(ref, known, from) {
176
+ const tenants = [...known].map(([id, name]) => ({ id, name: name || null }));
177
+ const named = tenants.slice(0, MAX_NAMED_TENANTS).map((t) => (t.name ? `${t.name} (${t.id})` : t.id));
178
+ if (tenants.length > MAX_NAMED_TENANTS)
179
+ named.push(`and ${tenants.length - MAX_NAMED_TENANTS} more`);
180
+ return new CavelonError(ExitCode.failure, {
181
+ code: "tenant_not_found",
182
+ message: `No tenant "${ref}" that this token can see${from ? ` (from ${from})` : ""}.${named.length ? ` Your tenants: ${named.join(", ")}.` : ""}`,
183
+ hint: TENANT_REF_HINT,
184
+ details: tenants.length ? { tenants } : undefined,
185
+ });
186
+ }
187
+ async function findTenant(client, ref) {
117
188
  const wanted = ref.toLowerCase();
189
+ const memberships = new Map();
118
190
  if (client.target.token?.startsWith("cvpat_")) {
119
191
  const me = await client.get("/api/v1/auth/me", { sendTenant: false, allow: [403, 404] });
192
+ if (me.status === 403) {
193
+ const said = typeof me.data?.detail === "string" ? me.data.detail : "403 Forbidden";
194
+ throw tenantRequiredError(client.url, said, `Cannot find tenant "${ref}" by its name or slug`);
195
+ }
120
196
  if (me.status === 200 && me.data) {
121
197
  const tenants = [...(me.data.memberships ?? []), ...(me.data.accessible_tenants ?? [])];
122
- const hit = tenants.find((t) => t.tenant_name?.toLowerCase() === wanted || t.tenant_id === ref);
198
+ const hit = tenants.find((t) => t.tenant_name?.toLowerCase() === wanted || t.tenant_slug?.toLowerCase() === wanted || t.tenant_id === ref);
199
+ for (const t of tenants)
200
+ if (isUuid(t.tenant_id))
201
+ memberships.set(t.tenant_id, t.tenant_name);
123
202
  if (hit)
124
- return { id: hit.tenant_id, name: hit.tenant_name };
203
+ return { found: { id: hit.tenant_id, name: hit.tenant_name, ...(hit.tenant_slug ? { slug: hit.tenant_slug } : {}) }, known: memberships };
125
204
  }
126
205
  }
127
206
  const page = await client.get("/api/v1/tenants", {
@@ -132,9 +211,18 @@ export async function lookupTenantId(client, ref) {
132
211
  if (page.status === 200) {
133
212
  const hit = page.data?.items?.find((t) => t.slug?.toLowerCase() === wanted || t.name?.toLowerCase() === wanted);
134
213
  if (hit)
135
- return { id: hit.id, name: hit.name };
214
+ return { found: { id: hit.id, name: hit.name, slug: hit.slug }, known: memberships };
215
+ }
216
+ for (const [id, name] of [...memberships].slice(0, MAX_SLUG_LOOKUPS)) {
217
+ const detail = await client.get(`/api/v1/tenants/${id}`, {
218
+ sendTenant: false,
219
+ headers: { "X-Tenant-Id": id },
220
+ allow: [400, 403, 404, 422],
221
+ });
222
+ if (detail.status === 200 && detail.data?.slug?.toLowerCase() === wanted)
223
+ return { found: { id, name: detail.data.name ?? name, slug: detail.data.slug }, known: memberships };
136
224
  }
137
- return undefined;
225
+ return { known: memberships };
138
226
  }
139
227
  export async function resolveTenantId(env, session, client) {
140
228
  if (!session.tenant || !session.url)
@@ -148,14 +236,7 @@ export async function resolveTenantId(env, session, client) {
148
236
  return cached;
149
237
  if (session.tenantSource === "use" && session.settings.tenant_id)
150
238
  return session.settings.tenant_id;
151
- const found = await lookupTenantId(client, session.tenant);
152
- if (!found) {
153
- throw new CavelonError(ExitCode.failure, {
154
- code: "tenant_not_found",
155
- message: `No tenant "${session.tenant}" that this token can see (from ${session.tenantSource}).`,
156
- hint: "Use the tenant's id instead; `cavelon tenant list` shows the ids.",
157
- });
158
- }
239
+ const found = await lookupTenantId(client, session.tenant, session.tenantSource);
159
240
  const url = session.url;
160
241
  const slug = session.tenant;
161
242
  await updateInstance(env, url, (current) => ({ ...current, tenant_ids: { ...current.tenant_ids, [slug]: found.id } }));