@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
@@ -3,17 +3,18 @@ import path from "node:path";
3
3
  import { boolOption, CURSOR_OPTION, intOption, LIMIT_OPTION, listOption, pageOf, positional, stringOption, } from "../command.js";
4
4
  import { capacityCodeIn, capacityHint, noteLines, runCapacityNote } from "../capacity.js";
5
5
  import { CavelonError, ExitCode, usageError } from "../errors.js";
6
+ import { confinedPath } from "../paths.js";
6
7
  import { clip, keyValues, moreHint, table } from "../format.js";
7
8
  import { callStable } from "../invoke.js";
8
9
  import { bindsNow, changedBy, limitError, limitsOrWarn, readLimits } from "../limits.js";
9
10
  import { getOperation } from "../operations.js";
10
- import { caseCounts, caseLabel, failedCase, NOT_PASSED } from "../results.js";
11
+ import { caseCounts, caseLabel, countsText, failedCase, NOT_PASSED, runVerdict } from "../results.js";
11
12
  import { isUuid } from "../session.js";
12
13
  import { cavelonCommand, shellWord } from "../shell.js";
13
14
  import { readZipSummary, ZipError } from "../zip.js";
14
15
  import { TIMEOUT_OPTION, timeoutMs, waitAndReport } from "./async.js";
15
16
  import { stageErrors, stageErrorText } from "./loops.js";
16
- import { resolveHarnessId } from "./tenants.js";
17
+ import { resolveHarnessId } from "../harness-ref.js";
17
18
  const WAIT_OPTION = { type: "boolean", description: "Wait for the work to finish (see `cavelon wait`).", cliOnly: true };
18
19
  async function resolveKbId(ctx, ref) {
19
20
  if (isUuid(ref))
@@ -253,7 +254,7 @@ export const kbUpload = {
253
254
  },
254
255
  examples: ["cavelon kb upload ./docs --kb FAQ", "cavelon kb upload ./manuals --kb FAQ -r --ext pdf --wait --timeout 5m"],
255
256
  async run(ctx, input) {
256
- const dir = path.resolve(ctx.io.cwd, positional(input, "dir"));
257
+ const dir = await confinedPath(ctx, positional(input, "dir"), "The folder");
257
258
  const kbRef = stringOption(input, "kb");
258
259
  if (!kbRef)
259
260
  throw usageError("Which knowledge base?", "Pass --kb <name-or-id>.");
@@ -341,10 +342,17 @@ export const kbUpload = {
341
342
  },
342
343
  };
343
344
  function summaryText(summary) {
344
- return ["passed", "failed", "errors", "pass_rate"]
345
- .filter((k) => k in summary)
346
- .map((k) => k + " " + String(summary[k]))
347
- .join(" ");
345
+ const verdict = runVerdict(summary);
346
+ const shown = ["passed", "failed", "errors"].filter((k) => k in summary).map((k) => k + " " + String(summary[k]));
347
+ const others = Object.fromEntries(Object.entries(verdict.counts).filter(([k]) => !["failed", "errors"].includes(k)));
348
+ if (Object.keys(others).length)
349
+ shown.push(countsText(others));
350
+ if ("pass_rate" in summary)
351
+ shown.push(`pass_rate ${String(summary.pass_rate)}`);
352
+ if (verdict.comparable === false) {
353
+ shown.push(`not comparable${verdict.non_comparable_reasons.length ? ` (${verdict.non_comparable_reasons.join(", ")})` : ""}`);
354
+ }
355
+ return shown.join(" ");
348
356
  }
349
357
  function resumeCommand(pending, timeout) {
350
358
  return cavelonCommand("wait", ...pending, ...(timeout ? ["--timeout", timeout] : []));
@@ -353,12 +361,13 @@ export const testRun = {
353
361
  name: "test run",
354
362
  summary: "Start test-suite runs; returns operation ids.",
355
363
  description: "Without --suite, runs every suite of the solution (--harness, or cavelon.yaml's harness).\n" +
356
- "With --wait, exits 1 when a case failed, 5 when answers wait for a manual verdict.",
364
+ "With --wait, exits 1 when a case failed or a run measured nothing comparable (cases not run, technical errors),\n" +
365
+ "5 when answers wait for a manual verdict or a value a case needs.",
357
366
  readOnly: false,
358
367
  mcpTool: "test_run",
359
368
  options: {
360
369
  suite: { type: "string", multiple: true, value: "<suite>", description: "Suite name or id." },
361
- harness: { type: "string", value: "<harness>", description: "Solution slug or id to run against." },
370
+ harness: { type: "string", value: "<harness>", description: "The solution to run against: its name, slug or id." },
362
371
  wait: WAIT_OPTION,
363
372
  timeout: TIMEOUT_OPTION,
364
373
  "idempotency-key": { type: "string", value: "<key>", description: "Send an Idempotency-Key with each start." },
@@ -416,15 +425,21 @@ export const testRun = {
416
425
  const waited = await waitAndReport(ctx, operationIds, timeoutMs(ctx, rawTimeout));
417
426
  const results = [];
418
427
  let failedCases = 0;
428
+ let verdictCode = ExitCode.ok;
419
429
  for (const run of runs) {
420
430
  const latest = await callStable(ctx, "GET", "/api/v1/test-runs/{run_id}", "test runs", { params: { run_id: [run.id] } });
421
431
  const { failed, errors } = caseCounts(latest.summary);
422
432
  failedCases += failed + errors;
433
+ if (!waited.pending.includes(run.operation_id ?? "")) {
434
+ const code = runVerdict(latest.summary).exit_code;
435
+ if (code === ExitCode.failure || (code === ExitCode.needsAction && verdictCode === ExitCode.ok))
436
+ verdictCode = code;
437
+ }
423
438
  results.push({ run_id: latest.id, suite: latest.suite_name ?? latest.suite_id, status: latest.status, summary: latest.summary ?? {} });
424
439
  }
425
440
  let exitCode = waited.exitCode;
426
- if (exitCode === ExitCode.ok && failedCases > 0)
427
- exitCode = ExitCode.failure;
441
+ if (exitCode === ExitCode.ok)
442
+ exitCode = verdictCode;
428
443
  const resume = waited.pending.length ? resumeCommand(waited.pending, rawTimeout) : undefined;
429
444
  const text = [
430
445
  waited.body,
@@ -615,16 +630,18 @@ export const trace = {
615
630
  const cursor = stringOption(input, "cursor");
616
631
  if (id.startsWith("op_")) {
617
632
  const op = await getOperation(await ctx.client(), id);
618
- if (!op.result_ref)
633
+ const ref = op.result_ref;
634
+ if (!ref)
619
635
  throw new CavelonError(ExitCode.failure, { code: "no_result", message: `${id} has no result yet (${op.status}).` });
620
- if (op.result_ref.type !== "test_run") {
636
+ const triggerRun = ref.type === "agent_run" || Boolean(ref.href?.startsWith("/api/v1/triggers/runs/"));
637
+ if (ref.type !== "test_run" && !triggerRun) {
621
638
  throw new CavelonError(ExitCode.failure, {
622
639
  code: "no_trace",
623
- message: `${id} is a ${op.kind}; its result is a ${op.result_ref.type}, which has no trace.`,
640
+ message: `${id} is a ${op.kind}; its result is a ${ref.type}, which has no trace.`,
624
641
  });
625
642
  }
626
- id = op.result_ref.id;
627
- kind = "test";
643
+ id = ref.id;
644
+ kind = triggerRun ? "trigger" : "test";
628
645
  }
629
646
  const traceId = stringOption(input, "trace");
630
647
  const spanId = stringOption(input, "span");
package/dist/context.js CHANGED
@@ -52,5 +52,9 @@ export function createContext(io, globals, mode = "cli") {
52
52
  }
53
53
  export function withWarnings(data, warnings) {
54
54
  const own = Array.isArray(data.warnings) ? data.warnings : [];
55
- return { ...data, warnings: [...own, ...warnings.filter((w) => !own.includes(w))] };
55
+ const messageOf = (entry) => (entry && typeof entry === "object" ? entry.message : entry);
56
+ const seen = new Set(own.map(messageOf));
57
+ const objects = own.some((entry) => entry && typeof entry === "object");
58
+ const added = warnings.filter((w) => !seen.has(w)).map((message) => (objects ? { code: null, message } : message));
59
+ return { ...data, warnings: [...own, ...added] };
56
60
  }
package/dist/contracts.js CHANGED
@@ -1,9 +1,13 @@
1
+ import { createHash } from "node:crypto";
1
2
  import path from "node:path";
2
3
  import { CavelonError, ExitCode } from "./errors.js";
3
4
  import { NOT_HERE } from "./http.js";
4
5
  import { cacheDir, instanceKey } from "./paths.js";
5
6
  import { readJsonFile, readTextFile, writeFileAtomic } from "./fsutil.js";
6
7
  import { SUPPORTED_CONTRACTS } from "./version.js";
8
+ const NOT_MODIFIED = Symbol("not modified");
9
+ const RELEASE_TTL_SECONDS = 3600;
10
+ const DEVELOPMENT_TTL_SECONDS = 60;
7
11
  const OPENAPI_PATHS = ["/openapi.json", "/api/v1/openapi.json"];
8
12
  export class Contracts {
9
13
  client;
@@ -21,26 +25,29 @@ export class Contracts {
21
25
  get root() {
22
26
  return path.join(cacheDir(this.env), instanceKey(this.client.url));
23
27
  }
24
- get ttlMs() {
25
- const seconds = Number(this.env.CAVELON_CONTRACT_TTL_SECONDS);
26
- return (Number.isFinite(seconds) && seconds >= 0 && this.env.CAVELON_CONTRACT_TTL_SECONDS !== "" ? seconds : 3600) * 1000;
28
+ ttlSeconds(version) {
29
+ const raw = this.env.CAVELON_CONTRACT_TTL_SECONDS;
30
+ const seconds = Number(raw);
31
+ if (raw !== undefined && raw !== "" && Number.isFinite(seconds) && seconds >= 0)
32
+ return seconds;
33
+ return Contracts.isDevelopment(version) ? DEVELOPMENT_TTL_SECONDS : RELEASE_TTL_SECONDS;
27
34
  }
28
- isMoving(version) {
35
+ static isDevelopment(version) {
29
36
  return version === "unknown" || /dev|snapshot|local/i.test(version);
30
37
  }
31
38
  versionDir(version) {
32
39
  return path.join(this.root, version.replace(/[^A-Za-z0-9._-]+/g, "_"));
33
40
  }
34
- fresh(fetchedAt) {
41
+ fresh(fetchedAt, version) {
35
42
  if (!fetchedAt)
36
43
  return false;
37
- return this.now().getTime() - new Date(fetchedAt).getTime() < this.ttlMs;
44
+ return this.now().getTime() - new Date(fetchedAt).getTime() < this.ttlSeconds(version) * 1000;
38
45
  }
39
46
  async capabilities(options = {}) {
40
47
  if (this.caps !== undefined && !options.refresh)
41
48
  return this.caps;
42
49
  const state = await readJsonFile(path.join(this.root, "state.json"));
43
- if (!options.refresh && state && this.fresh(state.checked_at)) {
50
+ if (!options.refresh && state && this.fresh(state.checked_at, state.version)) {
44
51
  const cached = await readJsonFile(path.join(this.versionDir(state.version), "capabilities.json"));
45
52
  if (cached) {
46
53
  this.caps = cached;
@@ -83,30 +90,58 @@ export class Contracts {
83
90
  async cached(file, load, parse, options = {}) {
84
91
  const version = await this.version();
85
92
  const target = path.join(this.versionDir(version), file);
86
- const meta = path.join(this.versionDir(version), `${file}.meta.json`);
87
- if (!options.refresh) {
88
- const text = await readTextFile(target);
89
- const info = await readJsonFile(meta);
90
- if (text !== undefined && (!this.isMoving(version) || this.fresh(info?.fetched_at))) {
91
- try {
92
- return parse(text);
93
- }
94
- catch {
95
- }
93
+ const metaFile = path.join(this.versionDir(version), `${file}.meta.json`);
94
+ const text = await readTextFile(target);
95
+ const meta = await readJsonFile(metaFile);
96
+ let cached;
97
+ if (text !== undefined) {
98
+ try {
99
+ cached = { value: parse(text) };
100
+ }
101
+ catch {
96
102
  }
97
103
  }
98
- const { value, serialized } = await load();
99
- await writeFileAtomic(target, serialized);
100
- await writeFileAtomic(meta, JSON.stringify({ fetched_at: this.now().toISOString() }));
101
- return value;
104
+ if (cached && !options.refresh && (!Contracts.isDevelopment(version) || this.fresh(meta?.fetched_at, version)))
105
+ return cached.value;
106
+ const loaded = await load(cached ? meta?.etag : undefined);
107
+ const fetchedAt = this.now().toISOString();
108
+ if (loaded === NOT_MODIFIED) {
109
+ if (!cached)
110
+ throw new Error(`${file}: the instance answered 304 Not Modified without being sent an ETag.`);
111
+ await writeFileAtomic(metaFile, JSON.stringify({ ...meta, fetched_at: fetchedAt }));
112
+ return cached.value;
113
+ }
114
+ await writeFileAtomic(target, loaded.serialized);
115
+ await writeFileAtomic(metaFile, JSON.stringify({ fetched_at: fetchedAt, ...(loaded.etag ? { etag: loaded.etag } : {}) }));
116
+ return loaded.value;
117
+ }
118
+ async getJson(route, etag, options = {}) {
119
+ const response = await this.client.get(route, {
120
+ query: options.query,
121
+ timeoutMs: options.timeoutMs,
122
+ allow: [...(options.allow ?? []), ...(etag ? [304] : [])],
123
+ headers: etag ? { "If-None-Match": etag } : undefined,
124
+ });
125
+ if (etag && response.status === 304)
126
+ return NOT_MODIFIED;
127
+ if (response.status < 200 || response.status >= 300)
128
+ return undefined;
129
+ return { value: response.data, serialized: response.text, etag: response.headers.get("etag") ?? undefined };
130
+ }
131
+ async getRequired(route, etag, query) {
132
+ const loaded = await this.getJson(route, etag, { query });
133
+ if (!loaded)
134
+ throw new Error(`${route} answered neither a body nor an error.`);
135
+ return loaded;
102
136
  }
103
137
  async openapi(options = {}) {
104
- return this.cached("openapi.json", async () => {
138
+ return this.cached("openapi.json", async (etag) => {
105
139
  for (const candidate of OPENAPI_PATHS) {
106
- const response = await this.client.get(candidate, { allow: NOT_HERE, timeoutMs: 120_000 });
107
- if (response.status === 200 && response.data && typeof response.data === "object" && "paths" in response.data) {
108
- return { value: response.data, serialized: response.text };
109
- }
140
+ const loaded = await this.getJson(candidate, etag, { allow: NOT_HERE, timeoutMs: 120_000 });
141
+ if (loaded === NOT_MODIFIED)
142
+ return loaded;
143
+ if (loaded?.value && typeof loaded.value === "object" && "paths" in loaded.value)
144
+ return loaded;
110
145
  }
111
146
  throw new CavelonError(ExitCode.failure, {
112
147
  code: "openapi_unavailable",
@@ -117,10 +152,7 @@ export class Contracts {
117
152
  }
118
153
  async errorCatalog(options = {}) {
119
154
  try {
120
- return await this.cached("error-catalog.json", async () => {
121
- const response = await this.client.get("/api/v1/meta/error-catalog");
122
- return { value: response.data, serialized: response.text };
123
- }, (text) => JSON.parse(text), options);
155
+ return await this.cached("error-catalog.json", (etag) => this.getRequired("/api/v1/meta/error-catalog", etag), (text) => JSON.parse(text), options);
124
156
  }
125
157
  catch (error) {
126
158
  if (error instanceof CavelonError && error.status === 404)
@@ -132,12 +164,7 @@ export class Contracts {
132
164
  const wanted = version ?? (await this.capabilities())?.contracts?.package_versions?.current;
133
165
  const file = Contracts.packageSchemaFile(wanted ?? "current");
134
166
  try {
135
- return await this.cached(file, async () => {
136
- const response = await this.client.get("/api/v1/meta/package-schema", {
137
- query: { version: wanted },
138
- });
139
- return { value: response.data, serialized: response.text };
140
- }, (text) => JSON.parse(text), options);
167
+ return await this.cached(file, (etag) => this.getRequired("/api/v1/meta/package-schema", etag, { version: wanted }), (text) => JSON.parse(text), options);
141
168
  }
142
169
  catch (error) {
143
170
  if (error instanceof CavelonError && error.status === 404) {
@@ -157,8 +184,26 @@ export class Contracts {
157
184
  const state = await readJsonFile(path.join(this.root, "state.json"));
158
185
  if (!state)
159
186
  return undefined;
160
- const value = await readJsonFile(path.join(this.versionDir(state.version), file));
161
- return value === undefined ? undefined : { value, version: state.version };
187
+ const target = path.join(this.versionDir(state.version), file);
188
+ const text = await readTextFile(target);
189
+ if (text === undefined)
190
+ return undefined;
191
+ let value;
192
+ try {
193
+ value = JSON.parse(text);
194
+ }
195
+ catch {
196
+ return undefined;
197
+ }
198
+ const meta = file === "capabilities.json" ? { fetched_at: state.checked_at } : await readJsonFile(`${target}.meta.json`);
199
+ return {
200
+ value,
201
+ version: state.version,
202
+ fetched_at: meta?.fetched_at ?? null,
203
+ etag: meta?.etag ?? null,
204
+ sha256: createHash("sha256").update(text).digest("hex").slice(0, 12),
205
+ stale: Contracts.isDevelopment(state.version) && !this.fresh(meta?.fetched_at, state.version),
206
+ };
162
207
  }
163
208
  static packageSchemaFile(version) {
164
209
  return `package-schema-${version.replace(/[^A-Za-z0-9._-]+/g, "_")}.json`;
@@ -0,0 +1,7 @@
1
+ let embedded;
2
+ export function embed(content) {
3
+ embedded = content;
4
+ }
5
+ export function embeddedContent() {
6
+ return embedded;
7
+ }
package/dist/features.js CHANGED
@@ -30,6 +30,21 @@ export function idempotencyKey(input) {
30
30
  throw usageError("--idempotency-key must be a UUID.");
31
31
  return given.toLowerCase();
32
32
  }
33
+ export function withRetryKey(error, key) {
34
+ if (!(error instanceof CavelonError) || error.exitCode !== ExitCode.server)
35
+ return error;
36
+ const rest = error.hint?.replace(/^Retry[;.]\s*/, "");
37
+ const details = error.details && typeof error.details === "object" && !Array.isArray(error.details) ? error.details : {};
38
+ return new CavelonError(error.exitCode, {
39
+ code: error.code,
40
+ message: error.message,
41
+ hint: [`Retry with --idempotency-key ${key}, so the instance does not do it twice.`, rest ? rest[0].toUpperCase() + rest.slice(1) : ""].filter(Boolean).join(" "),
42
+ docs: error.docs,
43
+ status: error.status,
44
+ details: { ...details, idempotency_key: key },
45
+ blockers: error.blockers,
46
+ });
47
+ }
33
48
  export function stableKey(seed) {
34
49
  const hex = createHash("sha256").update(seed).digest("hex");
35
50
  const variant = ((Number.parseInt(hex[16], 16) & 0x3) | 0x8).toString(16);
package/dist/fsutil.js CHANGED
@@ -23,6 +23,9 @@ export async function readTextFile(file) {
23
23
  throw error;
24
24
  }
25
25
  }
26
+ export function withoutBom(text) {
27
+ return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
28
+ }
26
29
  export async function writeFileAtomic(file, content, mode = 0o644, dirMode = 0o755) {
27
30
  await fs.mkdir(path.dirname(file), { recursive: true, mode: dirMode });
28
31
  const tmp = `${file}.${randomBytes(6).toString("hex")}.tmp`;
package/dist/git.js CHANGED
@@ -1,25 +1,30 @@
1
1
  import { execFile } from "node:child_process";
2
2
  import { promises as fs } from "node:fs";
3
3
  import path from "node:path";
4
- export async function resolveGit(env = process.env, platform = process.platform) {
4
+ export async function findProgram(name, env = process.env, platform = process.platform, extensions = [".exe"]) {
5
5
  const windows = platform === "win32";
6
6
  const pathApi = windows ? path.win32 : path.posix;
7
7
  const search = (windows ? (env.PATH ?? env.Path) : env.PATH) ?? "";
8
- const name = windows ? "git.exe" : "git";
8
+ const names = windows ? extensions.map((ext) => name + ext) : [name];
9
9
  for (const entry of search.split(pathApi.delimiter)) {
10
10
  const dir = windows && entry.length > 1 && entry.startsWith('"') && entry.endsWith('"') ? entry.slice(1, -1) : entry;
11
11
  if (!dir || !pathApi.isAbsolute(dir))
12
12
  continue;
13
- const candidate = pathApi.join(dir, name);
14
- const found = await fs
15
- .stat(candidate)
16
- .then((st) => st.isFile() && (windows || (st.mode & 0o111) !== 0))
17
- .catch(() => false);
18
- if (found)
19
- return candidate;
13
+ for (const file of names) {
14
+ const candidate = pathApi.join(dir, file);
15
+ const found = await fs
16
+ .stat(candidate)
17
+ .then((st) => st.isFile() && (windows || (st.mode & 0o111) !== 0))
18
+ .catch(() => false);
19
+ if (found)
20
+ return candidate;
21
+ }
20
22
  }
21
23
  return undefined;
22
24
  }
25
+ export function resolveGit(env = process.env, platform = process.platform) {
26
+ return findProgram("git", env, platform);
27
+ }
23
28
  export async function git(args, cwd) {
24
29
  const executable = await resolveGit();
25
30
  if (!executable)
@@ -0,0 +1,54 @@
1
+ import { closest, displayName, exactMatch } from "./choose.js";
2
+ import { CavelonError, ExitCode } from "./errors.js";
3
+ import { callStable } from "./invoke.js";
4
+ import { isUuid } from "./session.js";
5
+ import { shellWord } from "./shell.js";
6
+ function notFound(error) {
7
+ return error instanceof CavelonError && error.status === 404;
8
+ }
9
+ export async function listHarnesses(ctx) {
10
+ return callStable(ctx, "GET", "/api/v1/harnesses", "listing solutions");
11
+ }
12
+ export async function lookupHarness(ctx, ref) {
13
+ if (isUuid(ref)) {
14
+ try {
15
+ return { harness: await callStable(ctx, "GET", "/api/v1/harnesses/{harness_id}", "reading solutions", { params: { harness_id: [ref] } }), candidates: [] };
16
+ }
17
+ catch (error) {
18
+ if (!notFound(error))
19
+ throw error;
20
+ return { candidates: [] };
21
+ }
22
+ }
23
+ try {
24
+ return { harness: await callStable(ctx, "GET", "/api/v1/harnesses/by-slug/{slug}", "finding solutions by slug", { params: { slug: [ref] } }), candidates: [] };
25
+ }
26
+ catch (error) {
27
+ if (!notFound(error))
28
+ throw error;
29
+ }
30
+ const all = await listHarnesses(ctx);
31
+ const hit = exactMatch(all, ref);
32
+ if (hit)
33
+ return { harness: hit, candidates: [] };
34
+ return { candidates: closest(all, ref) };
35
+ }
36
+ export function harnessNotFoundError(ref, candidates, source, command) {
37
+ const near = candidates.map(displayName).join(", ");
38
+ const lines = candidates.map((h) => ` ${command ? command(h.slug) : `--harness ${shellWord(h.slug)}`}`).join("\n");
39
+ return new CavelonError(ExitCode.failure, {
40
+ code: "solution_not_found",
41
+ message: `No solution "${ref}" in this tenant${source ? ` (from ${source})` : ""}.${near ? ` Closest: ${near}.` : ""}`,
42
+ hint: (candidates.length ? `If you meant one of them:\n${lines}\n` : "") +
43
+ "`cavelon harness list` shows this tenant's solutions with name, slug and id; `cavelon harness new <slug>` creates one, and an env file's harness is created by `apply`.",
44
+ details: candidates.length ? { candidates: candidates.map((h) => ({ id: h.id, slug: h.slug, name: h.name })) } : undefined,
45
+ });
46
+ }
47
+ export async function resolveHarnessId(ctx, ref) {
48
+ if (isUuid(ref))
49
+ return ref;
50
+ const { harness, candidates } = await lookupHarness(ctx, ref);
51
+ if (!harness)
52
+ throw harnessNotFoundError(ref, candidates);
53
+ return harness.id;
54
+ }
package/dist/http.js CHANGED
@@ -2,6 +2,7 @@ import { capacityCodeIn, capacityHint } from "./capacity.js";
2
2
  import { ceilingRefusal, LIMIT_ABOVE_CEILING } from "./limits.js";
3
3
  import { CavelonError, ExitCode } from "./errors.js";
4
4
  import { KIT_VERSION } from "./version.js";
5
+ const RUNTIME = process.versions.bun ? "bun/" + process.versions.bun : "node/" + process.versions.node;
5
6
  export const DEFAULT_TIMEOUT_MS = 30_000;
6
7
  export const NOT_HERE = [301, 302, 303, 307, 308, 401, 403, 404, 405, 406];
7
8
  export const PERSONAL_ACCESS_TOKENS_DISABLED = "personal_access_tokens_disabled";
@@ -15,6 +16,12 @@ export function tokensDisabledError(url) {
15
16
  "works for the commands that accept one: a person runs `cavelon login` with it.",
16
17
  });
17
18
  }
19
+ function leading(text, slashes) {
20
+ let i = 0;
21
+ while (i < text.length && (text.charCodeAt(i) <= 0x20 || (slashes && (text[i] === "/" || text[i] === "\\"))))
22
+ i++;
23
+ return i;
24
+ }
18
25
  export class ApiClient {
19
26
  target;
20
27
  env;
@@ -28,19 +35,23 @@ export class ApiClient {
28
35
  }
29
36
  resolve(pathOrUrl, query) {
30
37
  const base = new URL(this.target.url.endsWith("/") ? this.target.url : `${this.target.url}/`);
31
- let url;
32
- if (/^https?:\/\//i.test(pathOrUrl)) {
33
- url = new URL(pathOrUrl);
34
- if (url.origin !== base.origin) {
35
- throw new CavelonError(ExitCode.usage, {
36
- code: "foreign_url",
37
- message: `Refusing to send the token to ${url.origin}; the instance is ${base.origin}.`,
38
- });
38
+ const foreign = (where, why = `the instance is ${base.origin}`) => new CavelonError(ExitCode.usage, { code: "foreign_url", message: `Refusing to send the token to ${where}; ${why}.` });
39
+ const parse = (input, against) => {
40
+ try {
41
+ return new URL(input, against);
39
42
  }
43
+ catch {
44
+ throw foreign(JSON.stringify(input), "it is not a URL on the instance");
45
+ }
46
+ };
47
+ const hasScheme = /^[a-z][a-z0-9+.-]*:/i.test(pathOrUrl.slice(leading(pathOrUrl, false)));
48
+ const url = hasScheme ? parse(pathOrUrl) : parse(pathOrUrl.slice(leading(pathOrUrl, true)), base);
49
+ for (const candidate of [url, parse(pathOrUrl, base)]) {
50
+ if (candidate.origin !== base.origin)
51
+ throw foreign(candidate.origin === "null" ? candidate.protocol : candidate.origin);
40
52
  }
41
- else {
42
- url = new URL(pathOrUrl.replace(/^\/+/, ""), base);
43
- }
53
+ if (!hasScheme && !url.pathname.startsWith(base.pathname))
54
+ throw foreign(url.pathname, `it is outside the instance's path ${base.pathname}`);
44
55
  for (const [key, value] of Object.entries(query ?? {})) {
45
56
  if (value === undefined || value === null)
46
57
  continue;
@@ -54,7 +65,7 @@ export class ApiClient {
54
65
  }
55
66
  headers(options = {}) {
56
67
  const headers = {
57
- "User-Agent": `cavelon/${KIT_VERSION} node/${process.versions.node}`,
68
+ "User-Agent": `cavelon/${KIT_VERSION} ${RUNTIME}`,
58
69
  Accept: options.accept ?? "application/json",
59
70
  ...options.headers,
60
71
  };
@@ -105,15 +116,16 @@ export class ApiClient {
105
116
  });
106
117
  }
107
118
  if (!response.ok && !options.allow?.includes(response.status)) {
108
- throw await this.refusal(response.status, data, `${method} ${new URL(response.url || this.resolve(path)).pathname}`, response.headers);
119
+ const tenantless = options.sendTenant !== false && !this.headers(options)["X-Tenant-Id"] && Boolean(this.target.token?.startsWith("cvpat_"));
120
+ throw await this.refusal(response.status, data, `${method} ${new URL(response.url || this.resolve(path)).pathname}`, response.headers, { tenantless });
109
121
  }
110
122
  return { status: response.status, headers: response.headers, data: data, text };
111
123
  }
112
- async refusal(status, body, what, headers) {
124
+ async refusal(status, body, what, headers, sent = {}) {
113
125
  if (status === 401 && this.target.token?.startsWith("cvpat_") && (await this.personalAccessTokensOff())) {
114
126
  return tokensDisabledError(this.url);
115
127
  }
116
- return errorFromResponse(status, body, what, headers);
128
+ return errorFromResponse(status, body, what, headers, sent);
117
129
  }
118
130
  personalAccessTokensOff() {
119
131
  this.tokensOff ??= (async () => {
@@ -149,6 +161,14 @@ function parseBody(text, contentType) {
149
161
  }
150
162
  return text;
151
163
  }
164
+ export async function bodyBytes(response, url, signal) {
165
+ try {
166
+ return new Uint8Array(await response.arrayBuffer());
167
+ }
168
+ catch (error) {
169
+ throw networkError(error, url, signal);
170
+ }
171
+ }
152
172
  function networkError(error, url, signal) {
153
173
  const reason = signal?.reason;
154
174
  if (reason?.name === "TimeoutError" || error?.name === "TimeoutError") {
@@ -167,7 +187,11 @@ function networkError(error, url, signal) {
167
187
  });
168
188
  }
169
189
  const BARE_CODE = /^[a-z][a-z0-9]*(?:_[a-z0-9]+)+$/;
170
- export function errorFromResponse(status, body, what, headers) {
190
+ export const TENANT_ID_HINT = "A token without Platform mode works only inside a tenant. Run `cavelon use` to choose one of the tenants it reaches, " +
191
+ "or pass --tenant <name, slug or id> (or set CAVELON_TENANT). An older instance tells such a token nothing without a tenant, " +
192
+ "not even which tenants it reaches: pass --tenant <tenant-id> there; an operator copies the id in Platform › Tenants. " +
193
+ "A token limited to one tenant needs none.";
194
+ export function errorFromResponse(status, body, what, headers, sent = {}) {
171
195
  let code;
172
196
  let message;
173
197
  let hint;
@@ -233,13 +257,15 @@ export function errorFromResponse(status, body, what, headers) {
233
257
  details = details && typeof details === "object" ? { ...details, ...ceiling.details } : ceiling.details;
234
258
  }
235
259
  if (status === 400 && !hint && message && /select a tenant|tenant context|X-Tenant-Id/i.test(message)) {
236
- hint = "Choose a tenant with `cavelon use <tenant>`, --tenant or CAVELON_TENANT.";
260
+ hint = "Choose a tenant with `cavelon use` (it lists your tenants), --tenant or CAVELON_TENANT.";
237
261
  }
238
262
  if ((status === 401 || status === 403) && !hint) {
239
263
  hint =
240
264
  status === 401
241
265
  ? "The token is missing, expired or revoked. A person runs `cavelon login` with a new one."
242
- : "The token does not reach this. Check the tenant (`cavelon whoami`) and the token's permission ceiling.";
266
+ : sent.tenantless
267
+ ? `No tenant was named. ${TENANT_ID_HINT} Otherwise check the token's permission ceiling.`
268
+ : "The token does not reach this. Check the tenant (`cavelon whoami`) and the token's permission ceiling.";
243
269
  }
244
270
  return new CavelonError(exitCode, {
245
271
  code: code ?? defaultCode(status),