@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.
- package/README.md +27 -13
- package/dist/agent-env.js +24 -0
- package/dist/agents.js +15 -7
- package/dist/choose.js +112 -0
- package/dist/commands/api.js +133 -27
- package/dist/commands/index.js +2 -0
- package/dist/commands/init.js +162 -24
- package/dist/commands/limits-set.js +2 -2
- package/dist/commands/limits.js +1 -1
- package/dist/commands/loops.js +1 -1
- package/dist/commands/sandboxes.js +2 -2
- package/dist/commands/session.js +176 -46
- package/dist/commands/setup.js +426 -0
- package/dist/commands/solution.js +48 -42
- package/dist/commands/tenants.js +33 -22
- package/dist/commands/work.js +2 -2
- package/dist/embedded.js +7 -0
- package/dist/git.js +14 -9
- package/dist/harness-ref.js +54 -0
- package/dist/http.js +15 -7
- package/dist/install.js +94 -0
- package/dist/main.js +31 -2
- package/dist/markers.js +53 -0
- package/dist/mcp.js +6 -3
- package/dist/openapi.js +44 -0
- package/dist/paths.js +7 -6
- package/dist/principal.js +43 -0
- package/dist/prompt.js +55 -11
- package/dist/results.js +65 -5
- package/dist/run-program.js +92 -0
- package/dist/session.js +72 -15
- package/dist/setup-agents.js +544 -0
- package/dist/skills/cavelon-authoring/SKILL.md +4 -1
- package/dist/skills/cavelon-loop/SKILL.md +29 -6
- package/dist/skills/cavelon-testing/SKILL.md +15 -1
- package/dist/tenant-choice.js +93 -0
- package/dist/update-check.js +118 -0
- package/dist/version.js +2 -1
- package/package.json +7 -4
package/dist/paths.js
CHANGED
|
@@ -4,7 +4,7 @@ import os from "node:os";
|
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import { CavelonError, ExitCode } from "./errors.js";
|
|
6
6
|
import { findProject } from "./project.js";
|
|
7
|
-
function
|
|
7
|
+
export function homeDir(env) {
|
|
8
8
|
return env.HOME || env.USERPROFILE || os.homedir();
|
|
9
9
|
}
|
|
10
10
|
export function configDir(env) {
|
|
@@ -14,7 +14,7 @@ export function configDir(env) {
|
|
|
14
14
|
return path.join(env.XDG_CONFIG_HOME, "cavelon");
|
|
15
15
|
if (process.platform === "win32" && env.APPDATA)
|
|
16
16
|
return path.join(env.APPDATA, "cavelon");
|
|
17
|
-
return path.join(
|
|
17
|
+
return path.join(homeDir(env), ".config", "cavelon");
|
|
18
18
|
}
|
|
19
19
|
export function cacheDir(env) {
|
|
20
20
|
if (env.CAVELON_CACHE_DIR)
|
|
@@ -23,7 +23,7 @@ export function cacheDir(env) {
|
|
|
23
23
|
return path.join(env.XDG_CACHE_HOME, "cavelon");
|
|
24
24
|
if (process.platform === "win32" && env.LOCALAPPDATA)
|
|
25
25
|
return path.join(env.LOCALAPPDATA, "cavelon", "cache");
|
|
26
|
-
return path.join(
|
|
26
|
+
return path.join(homeDir(env), ".cache", "cavelon");
|
|
27
27
|
}
|
|
28
28
|
export function instanceKey(url) {
|
|
29
29
|
const parsed = new URL(url);
|
|
@@ -31,16 +31,17 @@ export function instanceKey(url) {
|
|
|
31
31
|
const readable = parts.join("_").replace(/[^A-Za-z0-9._-]+/g, "_");
|
|
32
32
|
return `${readable}-${createHash("sha256").update(url).digest("hex").slice(0, 8)}`;
|
|
33
33
|
}
|
|
34
|
-
export async function confinedPath(ctx, raw, what) {
|
|
34
|
+
export async function confinedPath(ctx, raw, what, confine = ctx.mode === "mcp") {
|
|
35
35
|
const resolved = path.resolve(ctx.io.cwd, raw);
|
|
36
|
-
if (
|
|
36
|
+
if (!confine)
|
|
37
37
|
return resolved;
|
|
38
38
|
const root = (await findProject(ctx.io.cwd))?.root ?? ctx.io.cwd;
|
|
39
39
|
const real = await realPath(resolved);
|
|
40
40
|
if (!within(await realPath(root), real)) {
|
|
41
|
+
const who = ctx.mode === "mcp" ? "over MCP a tool" : "run by a coding agent, cavelon";
|
|
41
42
|
throw new CavelonError(ExitCode.usage, {
|
|
42
43
|
code: "path_outside_solution",
|
|
43
|
-
message: `${what} ${raw} is outside the solution folder ${root};
|
|
44
|
+
message: `${what} ${raw} is outside the solution folder ${root}; ${who} reads and writes only there.`,
|
|
44
45
|
hint: "Name a file inside the solution folder, or ask the person to run the command in their terminal.",
|
|
45
46
|
});
|
|
46
47
|
}
|
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/prompt.js
CHANGED
|
@@ -1,34 +1,78 @@
|
|
|
1
1
|
import { CavelonError, ExitCode } from "./errors.js";
|
|
2
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
if (char === "\
|
|
22
|
-
|
|
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
|
-
|
|
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
|
@@ -10,8 +10,55 @@ function summaryCount(summary, key) {
|
|
|
10
10
|
const value = Number(summary?.[key] ?? 0);
|
|
11
11
|
return Number.isFinite(value) && value > 0 ? value : 0;
|
|
12
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"];
|
|
13
|
+
export const NOT_PASSED_COUNTS = ["failed", "errors", "technical_errors", "not_run", "cases_not_run", "missing_results", "unmeasurable_cases", "skipped"];
|
|
14
|
+
export const WAITING_COUNTS = ["pending_review", "calibration_required"];
|
|
15
|
+
export const TESTING_PAGE = "concepts/regression-testing";
|
|
16
|
+
export const CASE_STATUSES = [
|
|
17
|
+
{
|
|
18
|
+
status: "calibration_required",
|
|
19
|
+
counts: ["calibration_required"],
|
|
20
|
+
short: "a knowledge base or value the case needs was not ready",
|
|
21
|
+
meaning: "The instance did not run the case. When it accepted the run (its preflight), a knowledge base the case needs had no ready documents (knowledge_base_not_ready), or a {{var:…}} value the case refers to was not set (tenant_value_missing); the result's reason names which. The run keeps that verdict even if the documents become ready while it runs.",
|
|
22
|
+
next: "Wait until the knowledge base's documents are processed (`cavelon wait` on the upload's operation), or set the value (`cavelon variables set`), then start a new run.",
|
|
23
|
+
section: "preflight-is-decided-when-the-run-is-accepted",
|
|
24
|
+
},
|
|
25
|
+
{
|
|
26
|
+
status: "pending_review",
|
|
27
|
+
counts: ["pending_review"],
|
|
28
|
+
short: "the answer waits for a person's verdict",
|
|
29
|
+
meaning: "The case ran, and its answer waits for a manual verdict: Auto-Evaluate is off for the suite, so no judge scored it.",
|
|
30
|
+
next: "Tell the person: they set Pass, Fail or Skip on the result in the instance. To have the judge score it, turn Auto-Evaluate on for the suite and run it again.",
|
|
31
|
+
section: "reviewing-results",
|
|
32
|
+
},
|
|
33
|
+
{
|
|
34
|
+
status: "not_run",
|
|
35
|
+
counts: ["not_run", "cases_not_run", "missing_results"],
|
|
36
|
+
short: "the step produced no result",
|
|
37
|
+
meaning: "The step produced no result: the run was cancelled or stopped before it (after repeated provider refusals, for example), or the case was held back before any step ran. The run is not comparable and has no pass rate.",
|
|
38
|
+
next: "`cavelon trace <test-run-id>` shows which steps ran and the reasons recorded; fix the cause and start a new run.",
|
|
39
|
+
section: "reviewing-results",
|
|
40
|
+
},
|
|
41
|
+
{
|
|
42
|
+
status: "not_evaluated",
|
|
43
|
+
counts: ["unevaluated_steps"],
|
|
44
|
+
short: "a preparation step, not scored",
|
|
45
|
+
meaning: "A preparation step (`evaluate: false`, or a fixed response): it sets up the dialog for a later step and is not scored, so it counts toward neither side of the pass rate. It does not fail a run.",
|
|
46
|
+
next: "Nothing, unless the step should be judged: then give it `evaluate: true` and a reference answer or criteria.",
|
|
47
|
+
section: "reviewing-results",
|
|
48
|
+
},
|
|
49
|
+
{
|
|
50
|
+
status: "skip",
|
|
51
|
+
counts: ["skipped"],
|
|
52
|
+
short: "the step was skipped",
|
|
53
|
+
meaning: "The step was skipped: a person set a Skip verdict to park the case, or the run was cancelled before the step. The run is not comparable and has no pass rate.",
|
|
54
|
+
next: "When the case applies again, a person replaces the Skip verdict in the instance; after a cancelled run, start a new one.",
|
|
55
|
+
section: "reviewing-results",
|
|
56
|
+
},
|
|
57
|
+
];
|
|
58
|
+
export function caseStatus(name) {
|
|
59
|
+
const wanted = name.trim().toLowerCase().replaceAll(" ", "_").replaceAll("-", "_");
|
|
60
|
+
return CASE_STATUSES.find((s) => s.status === wanted || s.counts.includes(wanted));
|
|
61
|
+
}
|
|
15
62
|
export function runVerdict(summary) {
|
|
16
63
|
const counts = {};
|
|
17
64
|
for (const key of [...NOT_PASSED_COUNTS, ...WAITING_COUNTS]) {
|
|
@@ -33,9 +80,16 @@ export function runVerdict(summary) {
|
|
|
33
80
|
}
|
|
34
81
|
export function countsText(counts) {
|
|
35
82
|
return Object.entries(counts)
|
|
36
|
-
.map(([key, value]) =>
|
|
83
|
+
.map(([key, value]) => {
|
|
84
|
+
const why = WAITING_COUNTS.includes(key) ? caseStatus(key)?.short : undefined;
|
|
85
|
+
return `${value} ${key === "errors" ? "errored" : key.replaceAll("_", " ")}${why ? ` (${why})` : ""}`;
|
|
86
|
+
})
|
|
37
87
|
.join(", ");
|
|
38
88
|
}
|
|
89
|
+
function explainedStatuses(counts) {
|
|
90
|
+
const statuses = Object.keys(counts).map((key) => caseStatus(key)?.status);
|
|
91
|
+
return [...new Set(statuses.filter((s) => Boolean(s)))];
|
|
92
|
+
}
|
|
39
93
|
const MAX_CASES = 5;
|
|
40
94
|
const REASON_CHARS = 500;
|
|
41
95
|
export function failedCase(r, max = REASON_CHARS) {
|
|
@@ -69,7 +123,10 @@ export async function resultFailure(ctx, op) {
|
|
|
69
123
|
comparable: verdict.comparable,
|
|
70
124
|
non_comparable_reasons: verdict.non_comparable_reasons,
|
|
71
125
|
exit_code: verdict.exit_code,
|
|
72
|
-
cases: results
|
|
126
|
+
cases: results
|
|
127
|
+
.filter((r) => NOT_PASSED.has(r.status) || WAITING_COUNTS.includes(r.status))
|
|
128
|
+
.slice(0, MAX_CASES)
|
|
129
|
+
.map((r) => failedCase(r)),
|
|
73
130
|
trace: cavelonCommand("trace", id),
|
|
74
131
|
};
|
|
75
132
|
}
|
|
@@ -96,9 +153,12 @@ export function failureLines(failure) {
|
|
|
96
153
|
for (const c of failure.cases)
|
|
97
154
|
lines.push(` ${caseLabel(c)} ${c.status}${c.reason ? ": " + c.reason : ""}`);
|
|
98
155
|
const shown = failure.cases.length;
|
|
99
|
-
const total = failure.failed_cases + failure.errored_cases;
|
|
156
|
+
const total = failure.failed_cases + failure.errored_cases + WAITING_COUNTS.reduce((sum, key) => sum + (failure.counts[key] ?? 0), 0);
|
|
100
157
|
if (total > shown)
|
|
101
158
|
lines.push(` … ${total - shown} more`);
|
|
159
|
+
const statuses = explainedStatuses(failure.counts);
|
|
160
|
+
if (statuses.length)
|
|
161
|
+
lines.push(` What to do: ${statuses.map((s) => cavelonCommand("explain", s)).join("; ")}`);
|
|
102
162
|
lines.push(` Look closer: ${failure.trace}`);
|
|
103
163
|
return lines.join("\n");
|
|
104
164
|
}
|
|
@@ -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;
|
|
@@ -122,21 +126,81 @@ export function requireToken(session) {
|
|
|
122
126
|
}
|
|
123
127
|
const MAX_SLUG_LOOKUPS = 25;
|
|
124
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.";
|
|
125
|
-
export
|
|
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) {
|
|
126
138
|
if (isUuid(ref))
|
|
127
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) {
|
|
128
188
|
const wanted = ref.toLowerCase();
|
|
129
189
|
const memberships = new Map();
|
|
130
190
|
if (client.target.token?.startsWith("cvpat_")) {
|
|
131
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
|
+
}
|
|
132
196
|
if (me.status === 200 && me.data) {
|
|
133
197
|
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 };
|
|
198
|
+
const hit = tenants.find((t) => t.tenant_name?.toLowerCase() === wanted || t.tenant_slug?.toLowerCase() === wanted || t.tenant_id === ref);
|
|
137
199
|
for (const t of tenants)
|
|
138
200
|
if (isUuid(t.tenant_id))
|
|
139
201
|
memberships.set(t.tenant_id, t.tenant_name);
|
|
202
|
+
if (hit)
|
|
203
|
+
return { found: { id: hit.tenant_id, name: hit.tenant_name, ...(hit.tenant_slug ? { slug: hit.tenant_slug } : {}) }, known: memberships };
|
|
140
204
|
}
|
|
141
205
|
}
|
|
142
206
|
const page = await client.get("/api/v1/tenants", {
|
|
@@ -147,7 +211,7 @@ export async function lookupTenantId(client, ref) {
|
|
|
147
211
|
if (page.status === 200) {
|
|
148
212
|
const hit = page.data?.items?.find((t) => t.slug?.toLowerCase() === wanted || t.name?.toLowerCase() === wanted);
|
|
149
213
|
if (hit)
|
|
150
|
-
return { id: hit.id, name: hit.name };
|
|
214
|
+
return { found: { id: hit.id, name: hit.name, slug: hit.slug }, known: memberships };
|
|
151
215
|
}
|
|
152
216
|
for (const [id, name] of [...memberships].slice(0, MAX_SLUG_LOOKUPS)) {
|
|
153
217
|
const detail = await client.get(`/api/v1/tenants/${id}`, {
|
|
@@ -156,9 +220,9 @@ export async function lookupTenantId(client, ref) {
|
|
|
156
220
|
allow: [400, 403, 404, 422],
|
|
157
221
|
});
|
|
158
222
|
if (detail.status === 200 && detail.data?.slug?.toLowerCase() === wanted)
|
|
159
|
-
return { id, name: detail.data.name ?? name };
|
|
223
|
+
return { found: { id, name: detail.data.name ?? name, slug: detail.data.slug }, known: memberships };
|
|
160
224
|
}
|
|
161
|
-
return
|
|
225
|
+
return { known: memberships };
|
|
162
226
|
}
|
|
163
227
|
export async function resolveTenantId(env, session, client) {
|
|
164
228
|
if (!session.tenant || !session.url)
|
|
@@ -172,14 +236,7 @@ export async function resolveTenantId(env, session, client) {
|
|
|
172
236
|
return cached;
|
|
173
237
|
if (session.tenantSource === "use" && session.settings.tenant_id)
|
|
174
238
|
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
|
-
}
|
|
239
|
+
const found = await lookupTenantId(client, session.tenant, session.tenantSource);
|
|
183
240
|
const url = session.url;
|
|
184
241
|
const slug = session.tenant;
|
|
185
242
|
await updateInstance(env, url, (current) => ({ ...current, tenant_ids: { ...current.tenant_ids, [slug]: found.id } }));
|