@cavelon/cli 0.0.0 → 0.1.1
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 +697 -3
- package/dist/LICENSE +201 -0
- package/dist/agents.js +91 -0
- package/dist/branches.js +61 -0
- package/dist/capacity.js +162 -0
- package/dist/cli.js +4 -0
- package/dist/command.js +62 -0
- package/dist/commands/api.js +243 -0
- package/dist/commands/async.js +207 -0
- package/dist/commands/docs.js +158 -0
- package/dist/commands/index.js +112 -0
- package/dist/commands/init.js +452 -0
- package/dist/commands/inventory.js +56 -0
- package/dist/commands/limits-set.js +624 -0
- package/dist/commands/limits.js +156 -0
- package/dist/commands/loops.js +792 -0
- package/dist/commands/models.js +197 -0
- package/dist/commands/sandboxes.js +667 -0
- package/dist/commands/session.js +476 -0
- package/dist/commands/solution.js +760 -0
- package/dist/commands/tenants.js +266 -0
- package/dist/commands/values.js +383 -0
- package/dist/commands/work.js +744 -0
- package/dist/context.js +56 -0
- package/dist/contracts.js +189 -0
- package/dist/credentials.js +134 -0
- package/dist/errors.js +64 -0
- package/dist/features.js +37 -0
- package/dist/format.js +36 -0
- package/dist/fsutil.js +40 -0
- package/dist/git.js +41 -0
- package/dist/http.js +286 -0
- package/dist/invoke.js +161 -0
- package/dist/io.js +49 -0
- package/dist/limits.js +299 -0
- package/dist/local-state.js +60 -0
- package/dist/main.js +227 -0
- package/dist/markers.js +113 -0
- package/dist/mcp.js +130 -0
- package/dist/openapi.js +223 -0
- package/dist/operations.js +107 -0
- package/dist/package-check.js +342 -0
- package/dist/package-files.js +329 -0
- package/dist/pair-order.js +39 -0
- package/dist/paths.js +28 -0
- package/dist/principal.js +33 -0
- package/dist/project.js +138 -0
- package/dist/prompt.js +34 -0
- package/dist/results.js +66 -0
- package/dist/session.js +166 -0
- package/dist/shell.js +41 -0
- package/dist/skills/cavelon-authoring/SKILL.md +214 -0
- package/dist/skills/cavelon-long-running/SKILL.md +181 -0
- package/dist/skills/cavelon-loop/SKILL.md +158 -0
- package/dist/skills/cavelon-testing/SKILL.md +90 -0
- package/dist/sse.js +44 -0
- package/dist/tar.js +172 -0
- package/dist/user-config.js +36 -0
- package/dist/version.js +17 -0
- package/dist/zip.js +132 -0
- package/package.json +40 -4
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { catalogEntry } from "./package-check.js";
|
|
2
|
+
export const PAIR_ORDER = [
|
|
3
|
+
"apply the iteration solution",
|
|
4
|
+
"apply the parent",
|
|
5
|
+
"run the parent's loop suite",
|
|
6
|
+
"activate the iteration solution",
|
|
7
|
+
"activate the parent",
|
|
8
|
+
];
|
|
9
|
+
export const DRAFT_ITERATION_NEEDS_DRAFT_PARENT = "runtime_draft_iteration_needs_draft_parent";
|
|
10
|
+
export const ITERATION_UNAVAILABLE = "runtime_external_iteration_harness_unavailable";
|
|
11
|
+
export const ITERATION_DRAFT = "masterloop_iteration_harness_draft";
|
|
12
|
+
const POINTERS = {
|
|
13
|
+
[ITERATION_UNAVAILABLE]: "Step 1 comes first: `cavelon apply` the iteration solution into its own solution, bind that solution's id " +
|
|
14
|
+
"under runtime_bindings in the parent's env/<name>.yaml, then apply the parent (step 2).",
|
|
15
|
+
[DRAFT_ITERATION_NEEDS_DRAFT_PARENT]: "Step 2 binds a draft iteration only into a draft parent: apply the parent into a draft solution " +
|
|
16
|
+
"(a new one, or `cavelon harness new <slug>`), or activate the iteration solution first (step 4).",
|
|
17
|
+
[ITERATION_DRAFT]: "Step 4 comes before step 5: once the parent's loop suite passed, `cavelon activate` the iteration solution, " +
|
|
18
|
+
"then activate the parent.",
|
|
19
|
+
};
|
|
20
|
+
export const PAIR_ORDER_CODES = Object.keys(POINTERS);
|
|
21
|
+
export function pairOrderText() {
|
|
22
|
+
return `The order that needs no override: ${PAIR_ORDER.map((step, i) => `${i + 1}. ${step}`).join("; ")}. \`cavelon activate\` never forces.`;
|
|
23
|
+
}
|
|
24
|
+
export function pairOrderPointer(code) {
|
|
25
|
+
const pointer = POINTERS[code];
|
|
26
|
+
return pointer ? `${pointer} ${pairOrderText()}` : undefined;
|
|
27
|
+
}
|
|
28
|
+
export function pairOrderHint(catalog, texts) {
|
|
29
|
+
const said = texts.filter((t) => typeof t === "string" && t !== "");
|
|
30
|
+
for (const code of PAIR_ORDER_CODES) {
|
|
31
|
+
const entry = catalogEntry(catalog, code);
|
|
32
|
+
const named = new RegExp(`\\b${code}\\b`);
|
|
33
|
+
if (!said.some((t) => named.test(t) || (entry?.message ? t.includes(entry.message) : false)))
|
|
34
|
+
continue;
|
|
35
|
+
const catalogSentence = entry ? [entry.message, entry.hint].filter(Boolean).join(" ") : "";
|
|
36
|
+
return { code, hint: [`${code}:`, catalogSentence, pairOrderPointer(code)].filter(Boolean).join(" ") };
|
|
37
|
+
}
|
|
38
|
+
return undefined;
|
|
39
|
+
}
|
package/dist/paths.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import os from "node:os";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
function home(env) {
|
|
4
|
+
return env.HOME || env.USERPROFILE || os.homedir();
|
|
5
|
+
}
|
|
6
|
+
export function configDir(env) {
|
|
7
|
+
if (env.CAVELON_CONFIG_DIR)
|
|
8
|
+
return env.CAVELON_CONFIG_DIR;
|
|
9
|
+
if (env.XDG_CONFIG_HOME)
|
|
10
|
+
return path.join(env.XDG_CONFIG_HOME, "cavelon");
|
|
11
|
+
if (process.platform === "win32" && env.APPDATA)
|
|
12
|
+
return path.join(env.APPDATA, "cavelon");
|
|
13
|
+
return path.join(home(env), ".config", "cavelon");
|
|
14
|
+
}
|
|
15
|
+
export function cacheDir(env) {
|
|
16
|
+
if (env.CAVELON_CACHE_DIR)
|
|
17
|
+
return env.CAVELON_CACHE_DIR;
|
|
18
|
+
if (env.XDG_CACHE_HOME)
|
|
19
|
+
return path.join(env.XDG_CACHE_HOME, "cavelon");
|
|
20
|
+
if (process.platform === "win32" && env.LOCALAPPDATA)
|
|
21
|
+
return path.join(env.LOCALAPPDATA, "cavelon", "cache");
|
|
22
|
+
return path.join(home(env), ".cache", "cavelon");
|
|
23
|
+
}
|
|
24
|
+
export function instanceKey(url) {
|
|
25
|
+
const parsed = new URL(url);
|
|
26
|
+
const parts = [parsed.hostname, parsed.port, parsed.pathname.replace(/^\/+|\/+$/g, "")].filter(Boolean);
|
|
27
|
+
return parts.join("_").replace(/[^A-Za-z0-9._-]+/g, "_");
|
|
28
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export async function readPrincipal(client, options = {}) {
|
|
2
|
+
const response = await client.get("/api/v1/meta/principal", { allow: [400, 403, 404, 405], sendTenant: options.sendTenant });
|
|
3
|
+
if (response.status !== 200 || !response.data?.kind)
|
|
4
|
+
return undefined;
|
|
5
|
+
const { permissions, ...rest } = response.data;
|
|
6
|
+
return Array.isArray(permissions) ? { ...rest, permissions: permissions.filter((p) => typeof p === "string") } : rest;
|
|
7
|
+
}
|
|
8
|
+
export async function readGlobalRole(client) {
|
|
9
|
+
const response = await client.get("/api/v1/auth/me", { allow: [400, 401, 403, 404], sendTenant: false });
|
|
10
|
+
if (response.status !== 200 || !response.data)
|
|
11
|
+
return undefined;
|
|
12
|
+
const role = response.data.global_role;
|
|
13
|
+
return typeof role === "string" && role ? role : null;
|
|
14
|
+
}
|
|
15
|
+
export const EXPIRY_WARNING_DAYS = 7;
|
|
16
|
+
export function expiryOf(principal, now) {
|
|
17
|
+
const expiresAt = principal?.token?.expires_at ?? principal?.api_key?.expires_at ?? null;
|
|
18
|
+
if (!expiresAt)
|
|
19
|
+
return { expires_at: null, days_left: null };
|
|
20
|
+
const ms = new Date(expiresAt).getTime() - now.getTime();
|
|
21
|
+
const days = Math.floor(ms / 86_400_000);
|
|
22
|
+
const what = principal?.token ? `The personal access token "${principal.token.name}"` : `The API key "${principal?.api_key?.name}"`;
|
|
23
|
+
if (ms <= 0)
|
|
24
|
+
return { expires_at: expiresAt, days_left: days, warning: `${what} has expired.` };
|
|
25
|
+
if (ms <= EXPIRY_WARNING_DAYS * 86_400_000) {
|
|
26
|
+
const when = days < 1 ? "within a day" : `in ${days} day${days === 1 ? "" : "s"}`;
|
|
27
|
+
const renew = principal?.token
|
|
28
|
+
? "A person creates a new one on /account/access-tokens and runs `cavelon login`."
|
|
29
|
+
: "A tenant administrator issues a new key in Settings → API keys.";
|
|
30
|
+
return { expires_at: expiresAt, days_left: days, warning: `${what} expires ${when} (${expiresAt}). ${renew}` };
|
|
31
|
+
}
|
|
32
|
+
return { expires_at: expiresAt, days_left: days };
|
|
33
|
+
}
|
package/dist/project.js
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { parse } from "yaml";
|
|
3
|
+
import { readTextFile } from "./fsutil.js";
|
|
4
|
+
import { CavelonError, ExitCode, usageError } from "./errors.js";
|
|
5
|
+
import { layoutFrom } from "./package-files.js";
|
|
6
|
+
export const PROJECT_FILE = "cavelon.yaml";
|
|
7
|
+
function stringField(value, ...keys) {
|
|
8
|
+
if (typeof value === "string" && value.trim())
|
|
9
|
+
return value.trim();
|
|
10
|
+
if (value && typeof value === "object") {
|
|
11
|
+
for (const key of keys) {
|
|
12
|
+
const nested = value[key];
|
|
13
|
+
if (typeof nested === "string" && nested.trim())
|
|
14
|
+
return nested.trim();
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
return undefined;
|
|
18
|
+
}
|
|
19
|
+
export async function findProject(cwd) {
|
|
20
|
+
let dir = path.resolve(cwd);
|
|
21
|
+
for (;;) {
|
|
22
|
+
const file = path.join(dir, PROJECT_FILE);
|
|
23
|
+
const text = await readTextFile(file);
|
|
24
|
+
if (text !== undefined)
|
|
25
|
+
return parseProject(file, text);
|
|
26
|
+
const parent = path.dirname(dir);
|
|
27
|
+
if (parent === dir)
|
|
28
|
+
return undefined;
|
|
29
|
+
dir = parent;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
export function parseProject(file, text) {
|
|
33
|
+
let raw;
|
|
34
|
+
try {
|
|
35
|
+
raw = parse(text) ?? {};
|
|
36
|
+
}
|
|
37
|
+
catch (error) {
|
|
38
|
+
throw new CavelonError(ExitCode.validation, {
|
|
39
|
+
code: "project_file_invalid",
|
|
40
|
+
message: `${file} is not valid YAML: ${error instanceof Error ? error.message : String(error)}`,
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
|
|
44
|
+
throw new CavelonError(ExitCode.validation, {
|
|
45
|
+
code: "project_file_invalid",
|
|
46
|
+
message: `${file} must be a YAML mapping.`,
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
const map = raw;
|
|
50
|
+
refuseCredentials(file, map);
|
|
51
|
+
return {
|
|
52
|
+
file,
|
|
53
|
+
root: path.dirname(file),
|
|
54
|
+
instance: stringField(map.instance, "url") ?? stringField(map.url),
|
|
55
|
+
tenant: stringField(map.tenant, "id", "slug"),
|
|
56
|
+
harness: stringField(map.harness, "slug", "id"),
|
|
57
|
+
packageVersion: stringField(map.package_version),
|
|
58
|
+
layout: layoutFrom(map),
|
|
59
|
+
raw: map,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
function refuseCredentials(file, map) {
|
|
63
|
+
for (const forbidden of ["token", "api_key", "secret"]) {
|
|
64
|
+
if (forbidden in map) {
|
|
65
|
+
throw new CavelonError(ExitCode.validation, {
|
|
66
|
+
code: "project_file_has_secret",
|
|
67
|
+
message: `${file} has a "${forbidden}" key. Solution files never hold a credential.`,
|
|
68
|
+
hint: "Remove it, revoke the token, and use `cavelon login` or CAVELON_TOKEN instead.",
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
export const ENV_DIR = "env";
|
|
74
|
+
export function envFilePath(project, name) {
|
|
75
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(name)) {
|
|
76
|
+
throw usageError(`"${name}" is not an environment name.`, "Use letters, digits, dashes and underscores, as in --env test.");
|
|
77
|
+
}
|
|
78
|
+
return path.join(project.root, ENV_DIR, `${name}.yaml`);
|
|
79
|
+
}
|
|
80
|
+
export async function readEnvFile(project, name) {
|
|
81
|
+
const file = envFilePath(project, name);
|
|
82
|
+
const text = await readTextFile(file);
|
|
83
|
+
if (text === undefined)
|
|
84
|
+
return { name, file, exists: false, runtimeBindings: {}, raw: {} };
|
|
85
|
+
let raw;
|
|
86
|
+
try {
|
|
87
|
+
raw = parse(text) ?? {};
|
|
88
|
+
}
|
|
89
|
+
catch (error) {
|
|
90
|
+
throw new CavelonError(ExitCode.validation, {
|
|
91
|
+
code: "env_file_invalid",
|
|
92
|
+
message: `${file} is not valid YAML: ${error instanceof Error ? error.message : String(error)}`,
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
|
|
96
|
+
throw new CavelonError(ExitCode.validation, { code: "env_file_invalid", message: `${file} must be a YAML mapping.` });
|
|
97
|
+
}
|
|
98
|
+
const map = raw;
|
|
99
|
+
refuseCredentials(file, map);
|
|
100
|
+
const bindings = {};
|
|
101
|
+
const declared = map.runtime_bindings;
|
|
102
|
+
if (declared !== undefined && declared !== null) {
|
|
103
|
+
if (typeof declared !== "object" || Array.isArray(declared)) {
|
|
104
|
+
throw new CavelonError(ExitCode.validation, {
|
|
105
|
+
code: "env_file_invalid",
|
|
106
|
+
message: `${file}: runtime_bindings must map each requirement key to a resource id.`,
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
for (const [key, value] of Object.entries(declared)) {
|
|
110
|
+
if (value === null || value === undefined || value === "")
|
|
111
|
+
continue;
|
|
112
|
+
if (typeof value !== "string") {
|
|
113
|
+
throw new CavelonError(ExitCode.validation, {
|
|
114
|
+
code: "env_file_invalid",
|
|
115
|
+
message: `${file}: runtime_bindings.${key} must be a resource id, got ${JSON.stringify(value)}.`,
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
bindings[key] = value.trim();
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
const mode = stringField(map.mode);
|
|
122
|
+
if (mode !== undefined && mode !== "overwrite" && mode !== "replace") {
|
|
123
|
+
throw new CavelonError(ExitCode.validation, {
|
|
124
|
+
code: "env_file_invalid",
|
|
125
|
+
message: `${file}: mode must be overwrite or replace, got "${mode}".`,
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
return {
|
|
129
|
+
name,
|
|
130
|
+
file,
|
|
131
|
+
exists: true,
|
|
132
|
+
tenant: stringField(map.tenant, "id", "slug"),
|
|
133
|
+
harness: stringField(map.harness, "slug", "id"),
|
|
134
|
+
mode: mode,
|
|
135
|
+
runtimeBindings: bindings,
|
|
136
|
+
raw: map,
|
|
137
|
+
};
|
|
138
|
+
}
|
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
|
+
}
|
package/dist/results.js
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
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
|
+
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") };
|
|
12
|
+
}
|
|
13
|
+
const MAX_CASES = 5;
|
|
14
|
+
const REASON_CHARS = 500;
|
|
15
|
+
export function failedCase(r, max = REASON_CHARS) {
|
|
16
|
+
const reason = r.error_message ?? r.llm_judge_reasoning ?? null;
|
|
17
|
+
return {
|
|
18
|
+
case: r.test_case_name ?? r.id,
|
|
19
|
+
step: r.step_order ?? null,
|
|
20
|
+
status: r.status,
|
|
21
|
+
reason: reason ? clip(reason, max) : null,
|
|
22
|
+
run_id: r.agent_run_id ?? null,
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
export async function resultFailure(ctx, op) {
|
|
26
|
+
if (op.status !== "succeeded" || op.result_ref?.type !== "test_run")
|
|
27
|
+
return undefined;
|
|
28
|
+
const id = op.result_ref.id;
|
|
29
|
+
try {
|
|
30
|
+
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)
|
|
33
|
+
return undefined;
|
|
34
|
+
const results = await callStable(ctx, "GET", "/api/v1/test-runs/{run_id}/results", "test results", { params: { run_id: [id] } });
|
|
35
|
+
return {
|
|
36
|
+
type: "test_run",
|
|
37
|
+
id,
|
|
38
|
+
suite: run.suite_name ?? run.suite_id,
|
|
39
|
+
failed_cases: failed,
|
|
40
|
+
errored_cases: errors,
|
|
41
|
+
cases: results.filter((r) => NOT_PASSED.has(r.status)).slice(0, MAX_CASES).map((r) => failedCase(r)),
|
|
42
|
+
trace: cavelonCommand("trace", id),
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
catch (error) {
|
|
46
|
+
if (!(error instanceof CavelonError))
|
|
47
|
+
throw error;
|
|
48
|
+
ctx.warn(`Could not read test run ${id} to see whether its cases passed (${error.message}); \`${cavelonCommand("trace", id)}\` shows them.`);
|
|
49
|
+
return undefined;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
export function caseLabel(c) {
|
|
53
|
+
return c.step === null ? c.case : `${c.case} (step ${c.step})`;
|
|
54
|
+
}
|
|
55
|
+
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}`];
|
|
58
|
+
for (const c of failure.cases)
|
|
59
|
+
lines.push(` ${caseLabel(c)} ${c.status}${c.reason ? ": " + c.reason : ""}`);
|
|
60
|
+
const shown = failure.cases.length;
|
|
61
|
+
const total = failure.failed_cases + failure.errored_cases;
|
|
62
|
+
if (total > shown)
|
|
63
|
+
lines.push(` … ${total - shown} more`);
|
|
64
|
+
lines.push(` Look closer: ${failure.trace}`);
|
|
65
|
+
return lines.join("\n");
|
|
66
|
+
}
|
package/dist/session.js
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
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
|
+
export async function resolveSession(env, cwd, globals) {
|
|
37
|
+
const project = await findProject(cwd);
|
|
38
|
+
const config = await loadUserConfig(env);
|
|
39
|
+
let envFile;
|
|
40
|
+
if (globals.solutionEnv) {
|
|
41
|
+
if (!project) {
|
|
42
|
+
throw usageError(`--env ${globals.solutionEnv} needs a solution folder.`, "Run it inside a folder with cavelon.yaml, or run `cavelon init` first.");
|
|
43
|
+
}
|
|
44
|
+
envFile = await readEnvFile(project, globals.solutionEnv);
|
|
45
|
+
}
|
|
46
|
+
let url;
|
|
47
|
+
let urlSource;
|
|
48
|
+
const envUrl = env.CAVELON_URL ? normalizeUrl(env.CAVELON_URL, env) : undefined;
|
|
49
|
+
if (globals.instance)
|
|
50
|
+
[url, urlSource] = [normalizeUrl(globals.instance, env), "option"];
|
|
51
|
+
else if (envUrl)
|
|
52
|
+
[url, urlSource] = [envUrl, "CAVELON_URL"];
|
|
53
|
+
else if (project?.instance)
|
|
54
|
+
[url, urlSource] = [normalizeUrl(project.instance, env), "cavelon.yaml"];
|
|
55
|
+
else if (config.current_instance)
|
|
56
|
+
[url, urlSource] = [config.current_instance, "login"];
|
|
57
|
+
const settings = (url && config.instances[url]) || {};
|
|
58
|
+
const session = { url, urlSource, project, envFile, settings };
|
|
59
|
+
if (!url)
|
|
60
|
+
return session;
|
|
61
|
+
if (env.CAVELON_TOKEN && !envUrl)
|
|
62
|
+
session.ignoredEnvToken = true;
|
|
63
|
+
if (env.CAVELON_TOKEN && envUrl === url) {
|
|
64
|
+
session.token = env.CAVELON_TOKEN.trim();
|
|
65
|
+
session.tokenSource = "CAVELON_TOKEN";
|
|
66
|
+
}
|
|
67
|
+
else {
|
|
68
|
+
const stored = await readToken(env, url, settings.credential_store);
|
|
69
|
+
if (stored) {
|
|
70
|
+
session.token = stored.token;
|
|
71
|
+
session.tokenSource = "login";
|
|
72
|
+
session.tokenStore = stored.store;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
if (session.token)
|
|
76
|
+
session.tokenKind = tokenKind(session.token);
|
|
77
|
+
const projectMatches = project && (!project.instance || normalizeUrl(project.instance, env) === url);
|
|
78
|
+
if (globals.tenant)
|
|
79
|
+
[session.tenant, session.tenantSource] = [globals.tenant, "option"];
|
|
80
|
+
else if (env.CAVELON_TENANT)
|
|
81
|
+
[session.tenant, session.tenantSource] = [env.CAVELON_TENANT.trim(), "CAVELON_TENANT"];
|
|
82
|
+
else if (projectMatches && envFile?.tenant)
|
|
83
|
+
[session.tenant, session.tenantSource] = [envFile.tenant, `env/${envFile.name}.yaml`];
|
|
84
|
+
else if (projectMatches && project?.tenant)
|
|
85
|
+
[session.tenant, session.tenantSource] = [project.tenant, "cavelon.yaml"];
|
|
86
|
+
else if (settings.tenant)
|
|
87
|
+
[session.tenant, session.tenantSource] = [settings.tenant, "use"];
|
|
88
|
+
return session;
|
|
89
|
+
}
|
|
90
|
+
export function requireInstance(session) {
|
|
91
|
+
if (!session.url) {
|
|
92
|
+
throw new CavelonError(ExitCode.usage, {
|
|
93
|
+
code: "no_instance",
|
|
94
|
+
message: "No Cavelon instance selected.",
|
|
95
|
+
hint: "Run `cavelon login --instance <url>`, set CAVELON_URL, or work inside a folder with cavelon.yaml.",
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
return session.url;
|
|
99
|
+
}
|
|
100
|
+
export function requireToken(session) {
|
|
101
|
+
const url = requireInstance(session);
|
|
102
|
+
if (!session.token) {
|
|
103
|
+
if (session.ignoredEnvToken) {
|
|
104
|
+
throw new CavelonError(ExitCode.unauthorized, {
|
|
105
|
+
code: "not_logged_in",
|
|
106
|
+
message: `No token for ${url}: CAVELON_TOKEN is set, but CAVELON_URL is not.`,
|
|
107
|
+
hint: "Set CAVELON_URL to the instance the token belongs to; CAVELON_TOKEN is sent only there.",
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
throw notLoggedIn(url);
|
|
111
|
+
}
|
|
112
|
+
return session.token;
|
|
113
|
+
}
|
|
114
|
+
export async function lookupTenantId(client, ref) {
|
|
115
|
+
if (isUuid(ref))
|
|
116
|
+
return { id: ref };
|
|
117
|
+
const wanted = ref.toLowerCase();
|
|
118
|
+
if (client.target.token?.startsWith("cvpat_")) {
|
|
119
|
+
const me = await client.get("/api/v1/auth/me", { sendTenant: false, allow: [403, 404] });
|
|
120
|
+
if (me.status === 200 && me.data) {
|
|
121
|
+
const tenants = [...(me.data.memberships ?? []), ...(me.data.accessible_tenants ?? [])];
|
|
122
|
+
const hit = tenants.find((t) => t.tenant_name?.toLowerCase() === wanted || t.tenant_id === ref);
|
|
123
|
+
if (hit)
|
|
124
|
+
return { id: hit.tenant_id, name: hit.tenant_name };
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
const page = await client.get("/api/v1/tenants", {
|
|
128
|
+
query: { search: ref, limit: 50 },
|
|
129
|
+
sendTenant: false,
|
|
130
|
+
allow: [400, 403, 404],
|
|
131
|
+
});
|
|
132
|
+
if (page.status === 200) {
|
|
133
|
+
const hit = page.data?.items?.find((t) => t.slug?.toLowerCase() === wanted || t.name?.toLowerCase() === wanted);
|
|
134
|
+
if (hit)
|
|
135
|
+
return { id: hit.id, name: hit.name };
|
|
136
|
+
}
|
|
137
|
+
return undefined;
|
|
138
|
+
}
|
|
139
|
+
export async function resolveTenantId(env, session, client) {
|
|
140
|
+
if (!session.tenant || !session.url)
|
|
141
|
+
return undefined;
|
|
142
|
+
if (session.tokenKind === "api_key")
|
|
143
|
+
return undefined;
|
|
144
|
+
if (isUuid(session.tenant))
|
|
145
|
+
return session.tenant;
|
|
146
|
+
const cached = session.settings.tenant_ids?.[session.tenant];
|
|
147
|
+
if (cached)
|
|
148
|
+
return cached;
|
|
149
|
+
if (session.tenantSource === "use" && session.settings.tenant_id)
|
|
150
|
+
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
|
+
}
|
|
159
|
+
const url = session.url;
|
|
160
|
+
const slug = session.tenant;
|
|
161
|
+
await updateInstance(env, url, (current) => ({ ...current, tenant_ids: { ...current.tenant_ids, [slug]: found.id } }));
|
|
162
|
+
return found.id;
|
|
163
|
+
}
|
|
164
|
+
export async function reloadSettings(env, url) {
|
|
165
|
+
return (await loadUserConfig(env)).instances[url] ?? {};
|
|
166
|
+
}
|
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
|
+
}
|