@cavelon/cli 0.0.0 → 0.1.2

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 (61) hide show
  1. package/README.md +713 -3
  2. package/dist/LICENSE +201 -0
  3. package/dist/agents.js +107 -0
  4. package/dist/branches.js +61 -0
  5. package/dist/capacity.js +162 -0
  6. package/dist/cli.js +4 -0
  7. package/dist/command.js +62 -0
  8. package/dist/commands/api.js +313 -0
  9. package/dist/commands/async.js +207 -0
  10. package/dist/commands/docs.js +158 -0
  11. package/dist/commands/index.js +112 -0
  12. package/dist/commands/init.js +481 -0
  13. package/dist/commands/inventory.js +56 -0
  14. package/dist/commands/limits-set.js +633 -0
  15. package/dist/commands/limits.js +156 -0
  16. package/dist/commands/loops.js +798 -0
  17. package/dist/commands/models.js +197 -0
  18. package/dist/commands/sandboxes.js +674 -0
  19. package/dist/commands/session.js +480 -0
  20. package/dist/commands/solution.js +830 -0
  21. package/dist/commands/tenants.js +266 -0
  22. package/dist/commands/values.js +386 -0
  23. package/dist/commands/work.js +761 -0
  24. package/dist/context.js +60 -0
  25. package/dist/contracts.js +234 -0
  26. package/dist/credentials.js +134 -0
  27. package/dist/errors.js +64 -0
  28. package/dist/features.js +52 -0
  29. package/dist/format.js +36 -0
  30. package/dist/fsutil.js +43 -0
  31. package/dist/git.js +41 -0
  32. package/dist/http.js +304 -0
  33. package/dist/invoke.js +165 -0
  34. package/dist/io.js +49 -0
  35. package/dist/limits.js +307 -0
  36. package/dist/local-state.js +78 -0
  37. package/dist/main.js +227 -0
  38. package/dist/markers.js +113 -0
  39. package/dist/mcp.js +137 -0
  40. package/dist/openapi.js +233 -0
  41. package/dist/operations.js +107 -0
  42. package/dist/package-check.js +342 -0
  43. package/dist/package-files.js +394 -0
  44. package/dist/pair-order.js +39 -0
  45. package/dist/paths.js +77 -0
  46. package/dist/principal.js +33 -0
  47. package/dist/project.js +157 -0
  48. package/dist/prompt.js +34 -0
  49. package/dist/results.js +104 -0
  50. package/dist/session.js +190 -0
  51. package/dist/shell.js +41 -0
  52. package/dist/skills/cavelon-authoring/SKILL.md +224 -0
  53. package/dist/skills/cavelon-long-running/SKILL.md +185 -0
  54. package/dist/skills/cavelon-loop/SKILL.md +159 -0
  55. package/dist/skills/cavelon-testing/SKILL.md +97 -0
  56. package/dist/sse.js +44 -0
  57. package/dist/tar.js +172 -0
  58. package/dist/user-config.js +36 -0
  59. package/dist/version.js +17 -0
  60. package/dist/zip.js +132 -0
  61. package/package.json +40 -4
@@ -0,0 +1,157 @@
1
+ import { promises as fs } from "node:fs";
2
+ import path from "node:path";
3
+ import { parse } from "yaml";
4
+ import { readTextFile } from "./fsutil.js";
5
+ import { CavelonError, ExitCode, usageError } from "./errors.js";
6
+ import { layoutFrom } from "./package-files.js";
7
+ export const PROJECT_FILE = "cavelon.yaml";
8
+ function stringField(value, ...keys) {
9
+ if (typeof value === "string" && value.trim())
10
+ return value.trim();
11
+ if (value && typeof value === "object") {
12
+ for (const key of keys) {
13
+ const nested = value[key];
14
+ if (typeof nested === "string" && nested.trim())
15
+ return nested.trim();
16
+ }
17
+ }
18
+ return undefined;
19
+ }
20
+ export async function findProject(cwd) {
21
+ let dir = path.resolve(cwd);
22
+ for (;;) {
23
+ const file = path.join(dir, PROJECT_FILE);
24
+ const text = await readTextFile(file);
25
+ if (text !== undefined)
26
+ return parseProject(file, text);
27
+ const parent = path.dirname(dir);
28
+ if (parent === dir)
29
+ return undefined;
30
+ dir = parent;
31
+ }
32
+ }
33
+ export function parseProject(file, text) {
34
+ let raw;
35
+ try {
36
+ raw = parse(text) ?? {};
37
+ }
38
+ catch (error) {
39
+ throw new CavelonError(ExitCode.validation, {
40
+ code: "project_file_invalid",
41
+ message: `${file} is not valid YAML: ${error instanceof Error ? error.message : String(error)}`,
42
+ });
43
+ }
44
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
45
+ throw new CavelonError(ExitCode.validation, {
46
+ code: "project_file_invalid",
47
+ message: `${file} must be a YAML mapping.`,
48
+ });
49
+ }
50
+ const map = raw;
51
+ refuseCredentials(file, map);
52
+ return {
53
+ file,
54
+ root: path.dirname(file),
55
+ instance: stringField(map.instance, "url") ?? stringField(map.url),
56
+ tenant: stringField(map.tenant, "id", "slug"),
57
+ harness: stringField(map.harness, "slug", "id"),
58
+ packageVersion: stringField(map.package_version),
59
+ layout: layoutFrom(map),
60
+ raw: map,
61
+ };
62
+ }
63
+ function refuseCredentials(file, map) {
64
+ for (const forbidden of ["token", "api_key", "secret"]) {
65
+ if (forbidden in map) {
66
+ throw new CavelonError(ExitCode.validation, {
67
+ code: "project_file_has_secret",
68
+ message: `${file} has a "${forbidden}" key. Solution files never hold a credential.`,
69
+ hint: "Remove it, revoke the token, and use `cavelon login` or CAVELON_TOKEN instead.",
70
+ });
71
+ }
72
+ }
73
+ }
74
+ export const ENV_DIR = "env";
75
+ const ENV_NAME = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
76
+ export function envFilePath(project, name) {
77
+ if (!ENV_NAME.test(name)) {
78
+ throw usageError(`"${name}" is not an environment name.`, "Use letters, digits, dashes and underscores, as in --env test.");
79
+ }
80
+ return path.join(project.root, ENV_DIR, `${name}.yaml`);
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
+ }
96
+ export async function readEnvFile(project, name) {
97
+ const file = envFilePath(project, name);
98
+ const text = await readTextFile(file);
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
+ }
105
+ let raw;
106
+ try {
107
+ raw = parse(text) ?? {};
108
+ }
109
+ catch (error) {
110
+ throw new CavelonError(ExitCode.validation, {
111
+ code: "env_file_invalid",
112
+ message: `${file} is not valid YAML: ${error instanceof Error ? error.message : String(error)}`,
113
+ });
114
+ }
115
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
116
+ throw new CavelonError(ExitCode.validation, { code: "env_file_invalid", message: `${file} must be a YAML mapping.` });
117
+ }
118
+ const map = raw;
119
+ refuseCredentials(file, map);
120
+ const bindings = {};
121
+ const declared = map.runtime_bindings;
122
+ if (declared !== undefined && declared !== null) {
123
+ if (typeof declared !== "object" || Array.isArray(declared)) {
124
+ throw new CavelonError(ExitCode.validation, {
125
+ code: "env_file_invalid",
126
+ message: `${file}: runtime_bindings must map each requirement key to a resource id.`,
127
+ });
128
+ }
129
+ for (const [key, value] of Object.entries(declared)) {
130
+ if (value === null || value === undefined || value === "")
131
+ continue;
132
+ if (typeof value !== "string") {
133
+ throw new CavelonError(ExitCode.validation, {
134
+ code: "env_file_invalid",
135
+ message: `${file}: runtime_bindings.${key} must be a resource id, got ${JSON.stringify(value)}.`,
136
+ });
137
+ }
138
+ bindings[key] = value.trim();
139
+ }
140
+ }
141
+ const mode = stringField(map.mode);
142
+ if (mode !== undefined && mode !== "overwrite" && mode !== "replace") {
143
+ throw new CavelonError(ExitCode.validation, {
144
+ code: "env_file_invalid",
145
+ message: `${file}: mode must be overwrite or replace, got "${mode}".`,
146
+ });
147
+ }
148
+ return {
149
+ name,
150
+ file,
151
+ tenant: stringField(map.tenant, "id", "slug"),
152
+ harness: stringField(map.harness, "slug", "id"),
153
+ mode: mode,
154
+ runtimeBindings: bindings,
155
+ raw: map,
156
+ };
157
+ }
package/dist/prompt.js ADDED
@@ -0,0 +1,34 @@
1
+ import { CavelonError, ExitCode } from "./errors.js";
2
+ export function readHidden(io, label, cancelled = "Login cancelled.") {
3
+ const stdin = io.stdin;
4
+ return new Promise((resolve, reject) => {
5
+ let value = "";
6
+ io.stderr.write(label);
7
+ const finish = (error) => {
8
+ stdin.setRawMode?.(false);
9
+ stdin.off?.("data", onData);
10
+ stdin.pause?.();
11
+ io.stderr.write("\n");
12
+ if (error)
13
+ reject(error);
14
+ else
15
+ resolve(value);
16
+ };
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 }));
23
+ }
24
+ if (char === "\u007f" || char === "\b")
25
+ value = value.slice(0, -1);
26
+ else if (char >= " ")
27
+ value += char;
28
+ }
29
+ };
30
+ stdin.setRawMode?.(true);
31
+ stdin.on?.("data", onData);
32
+ stdin.resume?.();
33
+ });
34
+ }
@@ -0,0 +1,104 @@
1
+ import { CavelonError } from "./errors.js";
2
+ import { clip } from "./format.js";
3
+ import { callStable } from "./invoke.js";
4
+ import { cavelonCommand } from "./shell.js";
5
+ export const NOT_PASSED = new Set(["fail", "error"]);
6
+ export function caseCounts(summary) {
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(", ");
38
+ }
39
+ const MAX_CASES = 5;
40
+ const REASON_CHARS = 500;
41
+ export function failedCase(r, max = REASON_CHARS) {
42
+ const reason = r.error_message ?? r.llm_judge_reasoning ?? null;
43
+ return {
44
+ case: r.test_case_name ?? r.id,
45
+ step: r.step_order ?? null,
46
+ status: r.status,
47
+ reason: reason ? clip(reason, max) : null,
48
+ run_id: r.agent_run_id ?? null,
49
+ };
50
+ }
51
+ export async function resultFailure(ctx, op) {
52
+ if (op.status !== "succeeded" || op.result_ref?.type !== "test_run")
53
+ return undefined;
54
+ const id = op.result_ref.id;
55
+ try {
56
+ const run = await callStable(ctx, "GET", "/api/v1/test-runs/{run_id}", "test runs", { params: { run_id: [id] } });
57
+ const verdict = runVerdict(run.summary);
58
+ if (verdict.exit_code === 0)
59
+ return undefined;
60
+ const { failed, errors } = caseCounts(run.summary);
61
+ const results = await callStable(ctx, "GET", "/api/v1/test-runs/{run_id}/results", "test results", { params: { run_id: [id] } });
62
+ return {
63
+ type: "test_run",
64
+ id,
65
+ suite: run.suite_name ?? run.suite_id,
66
+ failed_cases: failed,
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,
72
+ cases: results.filter((r) => NOT_PASSED.has(r.status)).slice(0, MAX_CASES).map((r) => failedCase(r)),
73
+ trace: cavelonCommand("trace", id),
74
+ };
75
+ }
76
+ catch (error) {
77
+ if (!(error instanceof CavelonError))
78
+ throw error;
79
+ ctx.warn(`Could not read test run ${id} to see whether its cases passed (${error.message}); \`${cavelonCommand("trace", id)}\` shows them.`);
80
+ return undefined;
81
+ }
82
+ }
83
+ export function caseLabel(c) {
84
+ return c.step === null ? c.case : `${c.case} (step ${c.step})`;
85
+ }
86
+ export function failureLines(failure) {
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(", ")}`);
96
+ for (const c of failure.cases)
97
+ lines.push(` ${caseLabel(c)} ${c.status}${c.reason ? ": " + c.reason : ""}`);
98
+ const shown = failure.cases.length;
99
+ const total = failure.failed_cases + failure.errored_cases;
100
+ if (total > shown)
101
+ lines.push(` … ${total - shown} more`);
102
+ lines.push(` Look closer: ${failure.trace}`);
103
+ return lines.join("\n");
104
+ }
@@ -0,0 +1,190 @@
1
+ import { CavelonError, ExitCode, notLoggedIn, usageError } from "./errors.js";
2
+ import { readToken } from "./credentials.js";
3
+ import { findProject, readEnvFile } from "./project.js";
4
+ import { loadUserConfig, tokenKind, updateInstance } from "./user-config.js";
5
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
6
+ export function isUuid(value) {
7
+ return UUID.test(value);
8
+ }
9
+ function isLocalHost(hostname) {
10
+ return (hostname === "localhost" ||
11
+ hostname.endsWith(".localhost") ||
12
+ hostname === "127.0.0.1" ||
13
+ hostname === "[::1]" ||
14
+ hostname === "::1");
15
+ }
16
+ export function normalizeUrl(input, env = {}) {
17
+ const trimmed = input.trim();
18
+ const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`;
19
+ let url;
20
+ try {
21
+ url = new URL(withScheme);
22
+ }
23
+ catch {
24
+ throw usageError(`"${input}" is not an instance URL.`, "Pass it as https://cavelon.example.com.");
25
+ }
26
+ if (url.protocol !== "https:" && url.protocol !== "http:")
27
+ throw usageError(`"${input}" is not an http(s) URL.`);
28
+ if (url.username || url.password)
29
+ throw usageError("The instance URL must not contain credentials.");
30
+ if (url.protocol === "http:" && !isLocalHost(url.hostname) && env.CAVELON_ALLOW_HTTP !== "1") {
31
+ throw usageError(`Refusing to send a token over plain http to ${url.host}.`, "Use https. For a test instance on a private network, set CAVELON_ALLOW_HTTP=1.");
32
+ }
33
+ const pathname = url.pathname.replace(/\/+$/, "");
34
+ return `${url.protocol}//${url.host.toLowerCase()}${pathname}`;
35
+ }
36
+ function sameUrl(input, url, env) {
37
+ if (!input)
38
+ return false;
39
+ try {
40
+ return normalizeUrl(input, env) === url;
41
+ }
42
+ catch {
43
+ return false;
44
+ }
45
+ }
46
+ export async function resolveSession(env, cwd, globals) {
47
+ const project = await findProject(cwd);
48
+ const config = await loadUserConfig(env);
49
+ let envFile;
50
+ if (globals.solutionEnv) {
51
+ if (!project) {
52
+ throw usageError(`--env ${globals.solutionEnv} needs a solution folder.`, "Run it inside a folder with cavelon.yaml, or run `cavelon init` first.");
53
+ }
54
+ envFile = await readEnvFile(project, globals.solutionEnv);
55
+ }
56
+ let url;
57
+ let urlSource;
58
+ if (globals.instance)
59
+ [url, urlSource] = [normalizeUrl(globals.instance, env), "option"];
60
+ else if (env.CAVELON_URL)
61
+ [url, urlSource] = [normalizeUrl(env.CAVELON_URL, env), "CAVELON_URL"];
62
+ else if (project?.instance)
63
+ [url, urlSource] = [normalizeUrl(project.instance, env), "cavelon.yaml"];
64
+ else if (config.current_instance)
65
+ [url, urlSource] = [config.current_instance, "login"];
66
+ const settings = (url && config.instances[url]) || {};
67
+ const session = { url, urlSource, project, envFile, settings };
68
+ if (!url)
69
+ return session;
70
+ if (env.CAVELON_TOKEN && !env.CAVELON_URL)
71
+ session.ignoredEnvToken = true;
72
+ if (env.CAVELON_TOKEN && sameUrl(env.CAVELON_URL, url, env)) {
73
+ session.token = env.CAVELON_TOKEN.trim();
74
+ session.tokenSource = "CAVELON_TOKEN";
75
+ }
76
+ else {
77
+ const stored = await readToken(env, url, settings.credential_store);
78
+ if (stored) {
79
+ session.token = stored.token;
80
+ session.tokenSource = "login";
81
+ session.tokenStore = stored.store;
82
+ }
83
+ }
84
+ if (session.token)
85
+ session.tokenKind = tokenKind(session.token);
86
+ const projectMatches = project && (!project.instance || sameUrl(project.instance, url, env));
87
+ if (globals.tenant)
88
+ [session.tenant, session.tenantSource] = [globals.tenant, "option"];
89
+ else if (env.CAVELON_TENANT)
90
+ [session.tenant, session.tenantSource] = [env.CAVELON_TENANT.trim(), "CAVELON_TENANT"];
91
+ else if (projectMatches && envFile?.tenant)
92
+ [session.tenant, session.tenantSource] = [envFile.tenant, `env/${envFile.name}.yaml`];
93
+ else if (projectMatches && project?.tenant)
94
+ [session.tenant, session.tenantSource] = [project.tenant, "cavelon.yaml"];
95
+ else if (settings.tenant)
96
+ [session.tenant, session.tenantSource] = [settings.tenant, "use"];
97
+ return session;
98
+ }
99
+ export function requireInstance(session) {
100
+ if (!session.url) {
101
+ throw new CavelonError(ExitCode.usage, {
102
+ code: "no_instance",
103
+ message: "No Cavelon instance selected.",
104
+ hint: "Run `cavelon login --instance <url>`, set CAVELON_URL, or work inside a folder with cavelon.yaml.",
105
+ });
106
+ }
107
+ return session.url;
108
+ }
109
+ export function requireToken(session) {
110
+ const url = requireInstance(session);
111
+ if (!session.token) {
112
+ if (session.ignoredEnvToken) {
113
+ throw new CavelonError(ExitCode.unauthorized, {
114
+ code: "not_logged_in",
115
+ message: `No token for ${url}: CAVELON_TOKEN is set, but CAVELON_URL is not.`,
116
+ hint: "Set CAVELON_URL to the instance the token belongs to; CAVELON_TOKEN is sent only there.",
117
+ });
118
+ }
119
+ throw notLoggedIn(url);
120
+ }
121
+ return session.token;
122
+ }
123
+ const MAX_SLUG_LOOKUPS = 25;
124
+ 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.";
125
+ export async function lookupTenantId(client, ref) {
126
+ if (isUuid(ref))
127
+ return { id: ref };
128
+ const wanted = ref.toLowerCase();
129
+ const memberships = new Map();
130
+ if (client.target.token?.startsWith("cvpat_")) {
131
+ const me = await client.get("/api/v1/auth/me", { sendTenant: false, allow: [403, 404] });
132
+ if (me.status === 200 && me.data) {
133
+ const tenants = [...(me.data.memberships ?? []), ...(me.data.accessible_tenants ?? [])];
134
+ const hit = tenants.find((t) => t.tenant_name?.toLowerCase() === wanted || t.tenant_id === ref);
135
+ if (hit)
136
+ return { id: hit.tenant_id, name: hit.tenant_name };
137
+ for (const t of tenants)
138
+ if (isUuid(t.tenant_id))
139
+ memberships.set(t.tenant_id, t.tenant_name);
140
+ }
141
+ }
142
+ const page = await client.get("/api/v1/tenants", {
143
+ query: { search: ref, limit: 50 },
144
+ sendTenant: false,
145
+ allow: [400, 403, 404],
146
+ });
147
+ if (page.status === 200) {
148
+ const hit = page.data?.items?.find((t) => t.slug?.toLowerCase() === wanted || t.name?.toLowerCase() === wanted);
149
+ if (hit)
150
+ return { id: hit.id, name: hit.name };
151
+ }
152
+ for (const [id, name] of [...memberships].slice(0, MAX_SLUG_LOOKUPS)) {
153
+ const detail = await client.get(`/api/v1/tenants/${id}`, {
154
+ sendTenant: false,
155
+ headers: { "X-Tenant-Id": id },
156
+ allow: [400, 403, 404, 422],
157
+ });
158
+ if (detail.status === 200 && detail.data?.slug?.toLowerCase() === wanted)
159
+ return { id, name: detail.data.name ?? name };
160
+ }
161
+ return undefined;
162
+ }
163
+ export async function resolveTenantId(env, session, client) {
164
+ if (!session.tenant || !session.url)
165
+ return undefined;
166
+ if (session.tokenKind === "api_key")
167
+ return undefined;
168
+ if (isUuid(session.tenant))
169
+ return session.tenant;
170
+ const cached = session.settings.tenant_ids?.[session.tenant];
171
+ if (cached)
172
+ return cached;
173
+ if (session.tenantSource === "use" && session.settings.tenant_id)
174
+ return session.settings.tenant_id;
175
+ const found = await lookupTenantId(client, session.tenant);
176
+ if (!found) {
177
+ throw new CavelonError(ExitCode.failure, {
178
+ code: "tenant_not_found",
179
+ message: `No tenant "${session.tenant}" that this token can see (from ${session.tenantSource}).`,
180
+ hint: TENANT_REF_HINT,
181
+ });
182
+ }
183
+ const url = session.url;
184
+ const slug = session.tenant;
185
+ await updateInstance(env, url, (current) => ({ ...current, tenant_ids: { ...current.tenant_ids, [slug]: found.id } }));
186
+ return found.id;
187
+ }
188
+ export async function reloadSettings(env, url) {
189
+ return (await loadUserConfig(env)).instances[url] ?? {};
190
+ }
package/dist/shell.js ADDED
@@ -0,0 +1,41 @@
1
+ const SHELLS = ["posix", "powershell", "cmd"];
2
+ export function detectShell(env, platform = process.platform) {
3
+ const named = env.CAVELON_SHELL?.trim().toLowerCase();
4
+ if (named && SHELLS.includes(named))
5
+ return named;
6
+ if (platform !== "win32")
7
+ return "posix";
8
+ if (env.MSYSTEM || env.SHELL)
9
+ return "posix";
10
+ const modules = (env.PSModulePath ?? "").split(";").filter(Boolean);
11
+ return modules.length >= 3 ? "powershell" : "cmd";
12
+ }
13
+ let current = detectShell({}, process.platform);
14
+ export function useShell(shell) {
15
+ current = shell;
16
+ }
17
+ export function currentShell() {
18
+ return current;
19
+ }
20
+ const BARE = {
21
+ posix: /^[\w.@%+=:,/-]+$/,
22
+ powershell: /^[\w.%+=:/\\-]+$/,
23
+ cmd: /^[\w.@+=:,/\\-]+$/,
24
+ };
25
+ const POSIX_QUOTE = String.raw `'\''`;
26
+ const POWERSHELL_QUOTES = new Set(["'", "\u2018", "\u2019", "\u201a", "\u201b"]);
27
+ export function shellWord(word, shell = current) {
28
+ if (word !== "" && BARE[shell].test(word) && !(shell === "powershell" && word.startsWith("@")))
29
+ return word;
30
+ switch (shell) {
31
+ case "posix":
32
+ return "'" + word.replaceAll("'", POSIX_QUOTE) + "'";
33
+ case "powershell":
34
+ return `'${[...word].map((c) => (POWERSHELL_QUOTES.has(c) ? c + c : c)).join("")}'`;
35
+ case "cmd":
36
+ return `"${word.replaceAll('"', '""')}"`;
37
+ }
38
+ }
39
+ export function cavelonCommand(...words) {
40
+ return ["cavelon", ...words.map((w) => shellWord(w))].join(" ");
41
+ }