@cavelon/cli 0.1.9 → 0.1.11
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 +23 -10
- package/dist/access.js +194 -0
- package/dist/acting.js +123 -0
- package/dist/agent-env.js +20 -2
- package/dist/branches.js +4 -3
- package/dist/capacity.js +3 -2
- package/dist/code-hints.js +5 -4
- package/dist/command.js +6 -0
- package/dist/commands/api.js +40 -21
- package/dist/commands/async.js +7 -4
- package/dist/commands/chat.js +18 -15
- package/dist/commands/db.js +367 -0
- package/dist/commands/docs.js +87 -9
- package/dist/commands/fmt.js +6 -4
- package/dist/commands/index.js +8 -0
- package/dist/commands/init.js +106 -28
- package/dist/commands/limits-set.js +12 -11
- package/dist/commands/limits.js +4 -3
- package/dist/commands/loops.js +75 -19
- package/dist/commands/models.js +12 -13
- package/dist/commands/sandboxes.js +22 -16
- package/dist/commands/schema.js +6 -5
- package/dist/commands/session.js +134 -37
- package/dist/commands/setup.js +4 -2
- package/dist/commands/solution.js +289 -93
- package/dist/commands/tenants.js +58 -22
- package/dist/commands/values.js +110 -45
- package/dist/commands/work.js +31 -17
- package/dist/confirm-token.js +15 -5
- package/dist/context.js +3 -1
- package/dist/contracts.js +39 -13
- package/dist/database-queries.js +301 -0
- package/dist/default-route.js +1 -1
- package/dist/features.js +2 -1
- package/dist/fsutil.js +14 -0
- package/dist/harness-ref.js +6 -4
- package/dist/http.js +39 -4
- package/dist/invoke.js +7 -2
- package/dist/kit-codes.js +14 -2
- package/dist/limits.js +1 -1
- package/dist/main.js +13 -1
- package/dist/mcp.js +105 -26
- package/dist/openapi.js +5 -2
- package/dist/operations.js +3 -2
- package/dist/package-check.js +29 -4
- package/dist/package-files.js +5 -1
- package/dist/package-format.js +10 -0
- package/dist/preview-report.js +46 -7
- package/dist/principal.js +24 -2
- package/dist/printed.js +182 -0
- package/dist/project.js +2 -1
- package/dist/results.js +1 -1
- package/dist/secret-access.js +42 -0
- package/dist/session.js +39 -19
- package/dist/shell.js +0 -3
- package/dist/skills/cavelon-authoring/SKILL.md +88 -4
- package/dist/skills/cavelon-long-running/SKILL.md +9 -3
- package/dist/skills/cavelon-loop/SKILL.md +81 -19
- package/dist/skills/cavelon-testing/SKILL.md +28 -1
- package/dist/tenant-choice.js +7 -7
- package/dist/trace-view.js +11 -1
- package/dist/update-check.js +2 -2
- package/dist/user-config.js +24 -0
- package/package.json +1 -1
package/dist/commands/work.js
CHANGED
|
@@ -3,7 +3,7 @@ import { createReadStream, promises as fs } from "node:fs";
|
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { boolOption, CURSOR_OPTION, intOption, LIMIT_OPTION, listOption, pageOf, positional, stringOption, } from "../command.js";
|
|
5
5
|
import { capacityCodeIn, capacityHint, noteLines, runCapacityNote } from "../capacity.js";
|
|
6
|
-
import { assertionCount, assertionLine, retrievalRows, retrievalView, spanAttributes, stepAssertions, suggestedSpan } from "../trace-view.js";
|
|
6
|
+
import { assertionCount, assertionLine, queryErrorCode, retrievalRows, retrievalView, spanAttributes, stepAssertions, suggestedSpan } from "../trace-view.js";
|
|
7
7
|
import { CavelonError, ExitCode, usageError } from "../errors.js";
|
|
8
8
|
import { confirmation } from "../confirm-token.js";
|
|
9
9
|
import { confinedPath } from "../paths.js";
|
|
@@ -14,7 +14,7 @@ import { bindsNow, changedBy, limitError, limitsOrWarn, readLimits } from "../li
|
|
|
14
14
|
import { getOperation } from "../operations.js";
|
|
15
15
|
import { caseCounts, caseLabel, countsText, failedCase, caseKnowledgeOutcomes, NOT_PASSED, runVerdict } from "../results.js";
|
|
16
16
|
import { isUuid } from "../session.js";
|
|
17
|
-
import { cavelonCommand
|
|
17
|
+
import { cavelonCommand } from "../printed.js";
|
|
18
18
|
import { readZipSummary, ZipError } from "../zip.js";
|
|
19
19
|
import { TIMEOUT_OPTION, timeoutMs, waitAndReport } from "./async.js";
|
|
20
20
|
import { stageErrors, stageErrorText } from "./loops.js";
|
|
@@ -118,6 +118,8 @@ function plannedLine(match) {
|
|
|
118
118
|
return `${head} and is replaced once the new file is verified`;
|
|
119
119
|
case "deactivate":
|
|
120
120
|
return `${head} and is deactivated after the upload`;
|
|
121
|
+
case "identical":
|
|
122
|
+
return `${head} and stays as it is: the file is identical to it`;
|
|
121
123
|
}
|
|
122
124
|
}
|
|
123
125
|
function outcomeLine(match) {
|
|
@@ -190,7 +192,7 @@ async function resolveKbId(ctx, ref) {
|
|
|
190
192
|
throw new CavelonError(ExitCode.failure, {
|
|
191
193
|
code: hits.length ? "kb_ambiguous" : "kb_not_found",
|
|
192
194
|
message: hits.length ? `${hits.length} knowledge bases are named "${ref}".` : `No knowledge base named "${ref}".`,
|
|
193
|
-
hint:
|
|
195
|
+
hint: `Pass its id; \`${cavelonCommand("api", "list_knowledge_bases")}\` lists them.`,
|
|
194
196
|
});
|
|
195
197
|
}
|
|
196
198
|
async function collectFiles(dir, recursive, extensions) {
|
|
@@ -410,6 +412,7 @@ export const kbUpload = {
|
|
|
410
412
|
"instance publishes its documents' file hashes.",
|
|
411
413
|
readOnly: false,
|
|
412
414
|
mcpTool: "kb_upload",
|
|
415
|
+
operations: ["POST /api/v1/knowledge-bases/{kb_id}/documents/upload"],
|
|
413
416
|
positionals: [{ name: "dir", description: "Folder (or single file) to upload.", required: true }],
|
|
414
417
|
options: {
|
|
415
418
|
kb: { type: "string", value: "<kb>", description: "Knowledge base name or id (required)." },
|
|
@@ -467,19 +470,22 @@ export const kbUpload = {
|
|
|
467
470
|
const differing = matches.filter((m) => !isIdentical(m));
|
|
468
471
|
const dryHint = staysActiveHint(differing, mode);
|
|
469
472
|
const dryDeactivations = differing.filter((m) => m.plan === "deactivate");
|
|
473
|
+
const same = new Set((identical ?? []).map((i) => i.file));
|
|
474
|
+
const fresh = rel.filter((f) => !same.has(f));
|
|
470
475
|
return {
|
|
471
476
|
data: {
|
|
472
477
|
kb: kbRef,
|
|
473
478
|
files: rel,
|
|
474
479
|
count: rel.length,
|
|
480
|
+
new_files: fresh,
|
|
475
481
|
dry_run: true,
|
|
476
|
-
existing: planned.map((m, index) => (identical ? { ...m, identical: isIdentical(matches[index]) } : m)),
|
|
482
|
+
existing: planned.map((m, index) => (identical ? { ...m, identical: isIdentical(matches[index]), ...(isIdentical(matches[index]) ? { plan: "identical" } : {}) } : m)),
|
|
477
483
|
content_compared: identical !== undefined,
|
|
478
484
|
identical: identical ?? [],
|
|
479
485
|
},
|
|
480
486
|
text: [
|
|
481
|
-
`Would upload ${fileCount(
|
|
482
|
-
...
|
|
487
|
+
fresh.length ? `Would upload ${fileCount(fresh.length)}:` : "Nothing new to upload:",
|
|
488
|
+
...fresh,
|
|
483
489
|
...(identical ?? []).map((i) => `${i.file}: identical to the active document ${shortId(i.document_id)}${i.filename === path.basename(i.file) ? "" : ` (${i.filename})`}; nothing new would be created (deduplicated)`),
|
|
484
490
|
...differing.map(plannedLine),
|
|
485
491
|
...(dryHint ? [dryHint] : []),
|
|
@@ -489,13 +495,13 @@ export const kbUpload = {
|
|
|
489
495
|
}
|
|
490
496
|
const gate = deactivations.length ? await confirmation(ctx, input, "kb_upload", { kb: kb.id, files: rel, existing: planned }) : undefined;
|
|
491
497
|
if (gate && !gate.confirmed) {
|
|
492
|
-
const confirm = gate.confirm(cavelonCommand("kb", "upload", dirArg, "--kb", kbRef, ...(boolOption(input, "recursive") ? ["
|
|
498
|
+
const confirm = gate.confirm(cavelonCommand("kb", "upload", dirArg, "--kb", kbRef, ...(boolOption(input, "recursive") ? ["--recursive"] : []), ...extensions.flatMap((e) => ["--ext", e]), "--replace", "--confirm"));
|
|
493
499
|
return {
|
|
494
500
|
data: { kb: { id: kb.id, name: kb.name ?? null }, files: rel, count: rel.length, uploaded: false, existing: planned, confirm, ...gate.fields },
|
|
495
501
|
text: [
|
|
496
502
|
`--replace uploads ${fileCount(rel.length)} and then deactivates ${deactivations.length} document${deactivations.length === 1 ? "" : "s"} the instance's upload does not replace itself:`,
|
|
497
503
|
...matches.map(plannedLine),
|
|
498
|
-
...(gate.mismatch ? [gate.mismatch] : []),
|
|
504
|
+
gate.where, ...(gate.mismatch ? [gate.mismatch] : []),
|
|
499
505
|
`Nothing was sent. Upload and deactivate with: ${confirm}`,
|
|
500
506
|
].join("\n"),
|
|
501
507
|
...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
|
|
@@ -590,7 +596,7 @@ export const kbUpload = {
|
|
|
590
596
|
`Uploaded ${fileCount(documents.length)}, then: ${failure.error.message}`,
|
|
591
597
|
`Not uploaded (${failure.notUploaded.length}): ${failure.notUploaded.join(", ")}`,
|
|
592
598
|
...matchLines(),
|
|
593
|
-
...(operationIds.length ? [`Wait for the uploaded ones with:
|
|
599
|
+
...(operationIds.length ? [`Wait for the uploaded ones with: ${cavelonCommand("wait", ...operationIds)}`] : []),
|
|
594
600
|
].join("\n"),
|
|
595
601
|
exitCode: failure.error.exitCode,
|
|
596
602
|
};
|
|
@@ -619,7 +625,7 @@ export const kbUpload = {
|
|
|
619
625
|
text: [
|
|
620
626
|
uploadedText(` to ${kb.name ?? kb.id}`),
|
|
621
627
|
...matchLines(),
|
|
622
|
-
...(operationIds.length ? [`Operations: ${operationIds.length}`, `Wait with:
|
|
628
|
+
...(operationIds.length ? [`Operations: ${operationIds.length}`, `Wait with: ${cavelonCommand("wait", ...operationIds)}`] : []),
|
|
623
629
|
].join("\n"),
|
|
624
630
|
exitCode: refused?.exitCode,
|
|
625
631
|
};
|
|
@@ -649,6 +655,7 @@ export const testRun = {
|
|
|
649
655
|
"5 when answers wait for a manual verdict or a value a case needs.",
|
|
650
656
|
readOnly: false,
|
|
651
657
|
mcpTool: "test_run",
|
|
658
|
+
operations: ["POST /api/v1/test-suites/{suite_id}/runs"],
|
|
652
659
|
options: {
|
|
653
660
|
suite: { type: "string", multiple: true, value: "<suite>", description: "Suite name or id." },
|
|
654
661
|
harness: { type: "string", value: "<harness>", description: "The solution to run against: its name, slug or id." },
|
|
@@ -675,7 +682,7 @@ export const testRun = {
|
|
|
675
682
|
throw new CavelonError(ExitCode.failure, {
|
|
676
683
|
code: hit.length ? "suite_ambiguous" : "suite_not_found",
|
|
677
684
|
message: hit.length ? `${hit.length} suites are named "${ref}"; pass its id.` : `No test suite "${ref}"${harnessRef ? ` for ${harnessRef}` : ""}.`,
|
|
678
|
-
hint: "
|
|
685
|
+
hint: `\`${cavelonCommand("api", "list_suites")}\` lists the suites.`,
|
|
679
686
|
});
|
|
680
687
|
}
|
|
681
688
|
return hit;
|
|
@@ -736,7 +743,7 @@ export const testRun = {
|
|
|
736
743
|
return {
|
|
737
744
|
data: { runs: started, operation_ids: operationIds },
|
|
738
745
|
text: table(started, ["suite", "run_id", "status", "operation_id"]) +
|
|
739
|
-
(operationIds.length ? `\n\nWait with:
|
|
746
|
+
(operationIds.length ? `\n\nWait with: ${cavelonCommand("wait", ...operationIds)}` : ""),
|
|
740
747
|
};
|
|
741
748
|
},
|
|
742
749
|
};
|
|
@@ -797,6 +804,7 @@ function knowledgeOutcomes(spans) {
|
|
|
797
804
|
}
|
|
798
805
|
function summarizeSpan(s, outcomes) {
|
|
799
806
|
const error = s.error_json ? clip(typeof s.error_json === "string" ? s.error_json : JSON.stringify(s.error_json), 200) : null;
|
|
807
|
+
const code = queryErrorCode(s);
|
|
800
808
|
return {
|
|
801
809
|
span_id: s.id,
|
|
802
810
|
seq: s.sequence ?? null,
|
|
@@ -806,6 +814,8 @@ function summarizeSpan(s, outcomes) {
|
|
|
806
814
|
status: s.status ?? null,
|
|
807
815
|
duration_ms: s.duration_ms ?? null,
|
|
808
816
|
knowledge_outcome: outcomeOf(s) ?? outcomes?.get(s.id) ?? null,
|
|
817
|
+
...(s.tool_type ? { tool_type: s.tool_type } : {}),
|
|
818
|
+
...(code ? { error_code: code } : {}),
|
|
809
819
|
error,
|
|
810
820
|
};
|
|
811
821
|
}
|
|
@@ -1042,17 +1052,21 @@ export const trace = {
|
|
|
1042
1052
|
tokens: span.token_usage_json ?? null,
|
|
1043
1053
|
error: span.error_json ?? null,
|
|
1044
1054
|
};
|
|
1045
|
-
|
|
1055
|
+
const code = queryErrorCode(span);
|
|
1056
|
+
const meaning = code ? `\n\nThe query answered the model with ${code}. What it means: ${cavelonCommand("explain", code)}` : "";
|
|
1057
|
+
return { data, text: retrieval ? retrievalText(data, retrieval) : JSON.stringify(data, null, 2) + meaning };
|
|
1046
1058
|
}
|
|
1047
1059
|
const page = pageOf(spans.map((s) => summarizeSpan(s, outcomes)), limit, cursor);
|
|
1048
|
-
const
|
|
1049
|
-
const
|
|
1060
|
+
const words = ["trace", id, ...(kind ? ["--kind", kind] : []), "--trace", traceId];
|
|
1061
|
+
const base = cavelonCommand(...words);
|
|
1062
|
+
const open = suggestedSpan(spans.map((s) => (queryErrorCode(s) ? { ...s, status: "error" } : s)));
|
|
1063
|
+
const codes = page.items.some((s) => "error_code" in s);
|
|
1050
1064
|
return {
|
|
1051
1065
|
data: { trace: summarizeTrace(detail), spans: page },
|
|
1052
1066
|
text: `${keyValues(Object.entries(summarizeTrace(detail)))}\n\n` +
|
|
1053
|
-
table(page.items, ["seq", "type", "name", "status", ...(outcomes.size ? ["knowledge_outcome"] : []), "duration_ms", "span_id"]) +
|
|
1067
|
+
table(page.items, ["seq", "type", "name", "status", ...(outcomes.size ? ["knowledge_outcome"] : []), ...(codes ? ["error_code"] : []), "duration_ms", "span_id"]) +
|
|
1054
1068
|
moreHint(page.next_cursor, base) +
|
|
1055
|
-
(open ? `\n\nOne span in full (${spanPick(open)}), by the span_id in its row: ${
|
|
1069
|
+
(open ? `\n\nOne span in full (${spanPick(open)}), by the span_id in its row: ${cavelonCommand(...words, "--span", open.id)}` : ""),
|
|
1056
1070
|
};
|
|
1057
1071
|
}
|
|
1058
1072
|
const order = kind ? [kind] : ["trigger", "test", "conversation"];
|
package/dist/confirm-token.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
|
+
import { actingTarget, targetLine } from "./acting.js";
|
|
2
3
|
import { drivenByAgent } from "./agent-env.js";
|
|
3
4
|
import { CavelonError, ExitCode } from "./errors.js";
|
|
4
5
|
import { canonical } from "./package-files.js";
|
|
6
|
+
import { PREVIEW_TOKEN } from "./printed.js";
|
|
5
7
|
export const CONFIRM_TOKEN = /^[0-9a-f]{12}$/;
|
|
6
8
|
export function confirmToken(target, tool, change) {
|
|
7
9
|
return createHash("sha256")
|
|
@@ -13,7 +15,8 @@ export function confirmGiven(input) {
|
|
|
13
15
|
const value = input.options.confirm;
|
|
14
16
|
return value !== undefined && value !== false && value !== "";
|
|
15
17
|
}
|
|
16
|
-
export function withToken(
|
|
18
|
+
export function withToken(printed, token) {
|
|
19
|
+
const command = printed.replace(` --confirm ${PREVIEW_TOKEN}`, " --confirm");
|
|
17
20
|
if (command.endsWith(" --confirm"))
|
|
18
21
|
return `${command} ${token}`;
|
|
19
22
|
const at = command.indexOf(" --confirm ");
|
|
@@ -21,7 +24,14 @@ export function withToken(command, token) {
|
|
|
21
24
|
return `${command.slice(0, at)} --confirm ${token}${command.slice(at + " --confirm".length)}`;
|
|
22
25
|
return `${command} --confirm ${token}`;
|
|
23
26
|
}
|
|
24
|
-
export async function confirmation(ctx, input, tool, change) {
|
|
27
|
+
export async function confirmation(ctx, input, tool, change, options = {}) {
|
|
28
|
+
const gate = await gateOf(ctx, input, tool, change);
|
|
29
|
+
if (gate.confirmed)
|
|
30
|
+
return { ...gate, where: "" };
|
|
31
|
+
const target = await actingTarget(ctx, options);
|
|
32
|
+
return { ...gate, fields: { target, ...gate.fields }, where: targetLine(target) };
|
|
33
|
+
}
|
|
34
|
+
async function gateOf(ctx, input, tool, change) {
|
|
25
35
|
const given = input.options.confirm;
|
|
26
36
|
const driven = drivenByAgent(ctx);
|
|
27
37
|
const tokenGiven = typeof given === "string" && given !== "";
|
|
@@ -37,7 +47,7 @@ export async function confirmation(ctx, input, tool, change) {
|
|
|
37
47
|
confirmed: false,
|
|
38
48
|
fields: { confirm_token: token, token_required: true },
|
|
39
49
|
confirm,
|
|
40
|
-
mismatch: `--confirm alone does not confirm when a coding agent runs cavelon
|
|
50
|
+
mismatch: `--confirm alone does not confirm when a coding agent runs cavelon. Nothing was changed: show the person this preview, and with their yes run the command below, which carries this change's token.`,
|
|
41
51
|
exitCode: ExitCode.needsAction,
|
|
42
52
|
};
|
|
43
53
|
}
|
|
@@ -53,10 +63,10 @@ export async function confirmation(ctx, input, tool, change) {
|
|
|
53
63
|
exitCode: ExitCode.conflict,
|
|
54
64
|
};
|
|
55
65
|
}
|
|
56
|
-
export function shellTokenRequired(command
|
|
66
|
+
export function shellTokenRequired(command) {
|
|
57
67
|
return new CavelonError(ExitCode.needsAction, {
|
|
58
68
|
code: "confirm_token_required",
|
|
59
|
-
message:
|
|
69
|
+
message: "--confirm alone does not confirm when a coding agent runs cavelon; nothing was changed.",
|
|
60
70
|
hint: `Run \`${command}\` without --confirm, show the person the preview, and with their yes run the command it prints, which carries the change's token.`,
|
|
61
71
|
});
|
|
62
72
|
}
|
package/dist/context.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { checkKeyTenant } from "./acting.js";
|
|
1
2
|
import { Contracts } from "./contracts.js";
|
|
2
3
|
import { ApiClient } from "./http.js";
|
|
3
4
|
import { colorEnabled, styleFor } from "./io.js";
|
|
@@ -32,7 +33,8 @@ export function createContext(io, globals, mode = "cli") {
|
|
|
32
33
|
clientPromise ??= (async () => {
|
|
33
34
|
const session = await ctx.session();
|
|
34
35
|
const client = new ApiClient({ url: requireInstance(session), token: requireToken(session) }, io.env);
|
|
35
|
-
client.target.tenantId =
|
|
36
|
+
client.target.tenantId =
|
|
37
|
+
session.tokenKind === "api_key" ? await checkKeyTenant(client, session, (m) => ctx.warn(m)) : await resolveTenantId(io.env, session, client, io.now());
|
|
36
38
|
return client;
|
|
37
39
|
})();
|
|
38
40
|
return clientPromise;
|
package/dist/contracts.js
CHANGED
|
@@ -3,7 +3,8 @@ import path from "node:path";
|
|
|
3
3
|
import { CavelonError, ExitCode } from "./errors.js";
|
|
4
4
|
import { NOT_HERE } from "./http.js";
|
|
5
5
|
import { cacheDir, instanceKey } from "./paths.js";
|
|
6
|
-
import {
|
|
6
|
+
import { cavelonCommand } from "./printed.js";
|
|
7
|
+
import { readJsonFile, readTextFile, writePrivateFile } from "./fsutil.js";
|
|
7
8
|
import { SUPPORTED_CONTRACTS } from "./version.js";
|
|
8
9
|
const NOT_MODIFIED = Symbol("not modified");
|
|
9
10
|
const RELEASE_TTL_SECONDS = 3600;
|
|
@@ -36,6 +37,9 @@ export class Contracts {
|
|
|
36
37
|
static isDevelopment(version) {
|
|
37
38
|
return version === "unknown" || /dev|snapshot|local/i.test(version);
|
|
38
39
|
}
|
|
40
|
+
async write(file, content) {
|
|
41
|
+
await writePrivateFile(cacheDir(this.env), file, content);
|
|
42
|
+
}
|
|
39
43
|
versionDir(version) {
|
|
40
44
|
return path.join(this.root, version.replace(/[^A-Za-z0-9._-]+/g, "_"));
|
|
41
45
|
}
|
|
@@ -48,12 +52,14 @@ export class Contracts {
|
|
|
48
52
|
if (this.caps !== undefined && !options.refresh)
|
|
49
53
|
return this.caps;
|
|
50
54
|
const state = await readJsonFile(path.join(this.root, "state.json"));
|
|
51
|
-
if (!options.refresh && state
|
|
52
|
-
const
|
|
55
|
+
if (!options.refresh && state) {
|
|
56
|
+
const file = path.join(this.versionDir(state.version), this.cacheName("capabilities.json"));
|
|
57
|
+
const meta = await readJsonFile(`${file}.meta.json`);
|
|
58
|
+
const cached = this.fresh(meta?.fetched_at, state.version) ? await readJsonFile(file) : undefined;
|
|
53
59
|
if (cached) {
|
|
54
60
|
this.caps = cached;
|
|
55
61
|
this.versionValue = state.version;
|
|
56
|
-
this.cachedAt =
|
|
62
|
+
this.cachedAt = meta?.fetched_at;
|
|
57
63
|
return cached;
|
|
58
64
|
}
|
|
59
65
|
}
|
|
@@ -75,9 +81,11 @@ export class Contracts {
|
|
|
75
81
|
else {
|
|
76
82
|
this.caps = response.data;
|
|
77
83
|
this.versionValue = response.data.instance.version || "unknown";
|
|
78
|
-
|
|
84
|
+
const file = path.join(this.versionDir(this.versionValue), this.cacheName("capabilities.json"));
|
|
85
|
+
await this.write(file, JSON.stringify(response.data, null, 2));
|
|
86
|
+
await this.write(`${file}.meta.json`, JSON.stringify({ fetched_at: now }));
|
|
79
87
|
}
|
|
80
|
-
await
|
|
88
|
+
await this.write(path.join(this.root, "state.json"), JSON.stringify({ version: this.versionValue, checked_at: now }, null, 2));
|
|
81
89
|
return this.caps;
|
|
82
90
|
}
|
|
83
91
|
async liveCapabilities() {
|
|
@@ -111,11 +119,11 @@ export class Contracts {
|
|
|
111
119
|
if (loaded === NOT_MODIFIED) {
|
|
112
120
|
if (!cached)
|
|
113
121
|
throw new Error(`${file}: the instance answered 304 Not Modified without being sent an ETag.`);
|
|
114
|
-
await
|
|
122
|
+
await this.write(metaFile, JSON.stringify({ ...meta, fetched_at: fetchedAt }));
|
|
115
123
|
return cached.value;
|
|
116
124
|
}
|
|
117
|
-
await
|
|
118
|
-
await
|
|
125
|
+
await this.write(target, loaded.serialized);
|
|
126
|
+
await this.write(metaFile, JSON.stringify({ fetched_at: fetchedAt, ...(loaded.etag ? { etag: loaded.etag } : {}) }));
|
|
119
127
|
return loaded.value;
|
|
120
128
|
}
|
|
121
129
|
async getJson(route, etag, options = {}) {
|
|
@@ -175,7 +183,7 @@ export class Contracts {
|
|
|
175
183
|
throw new CavelonError(ExitCode.validation, {
|
|
176
184
|
code: "package_version_unsupported",
|
|
177
185
|
message: `${this.client.url} does not accept package version ${wanted}.`,
|
|
178
|
-
hint:
|
|
186
|
+
hint: `Read contracts.package_versions.accepted from \`${cavelonCommand("status", "--json")}\`, or pull the package again.`,
|
|
179
187
|
});
|
|
180
188
|
}
|
|
181
189
|
return null;
|
|
@@ -187,7 +195,7 @@ export class Contracts {
|
|
|
187
195
|
const state = await readJsonFile(path.join(this.root, "state.json"));
|
|
188
196
|
if (!state)
|
|
189
197
|
return undefined;
|
|
190
|
-
const target = path.join(this.versionDir(state.version), file);
|
|
198
|
+
const target = path.join(this.versionDir(state.version), this.cacheName(file));
|
|
191
199
|
const text = await readTextFile(target);
|
|
192
200
|
if (text === undefined)
|
|
193
201
|
return undefined;
|
|
@@ -198,7 +206,7 @@ export class Contracts {
|
|
|
198
206
|
catch {
|
|
199
207
|
return undefined;
|
|
200
208
|
}
|
|
201
|
-
const meta =
|
|
209
|
+
const meta = await readJsonFile(`${target}.meta.json`);
|
|
202
210
|
return {
|
|
203
211
|
value,
|
|
204
212
|
version: state.version,
|
|
@@ -211,8 +219,26 @@ export class Contracts {
|
|
|
211
219
|
static packageSchemaFile(version) {
|
|
212
220
|
return `package-schema-${version.replace(/[^A-Za-z0-9._-]+/g, "_")}.json`;
|
|
213
221
|
}
|
|
222
|
+
audience() {
|
|
223
|
+
const { token = "", tenantId = "" } = this.client.target;
|
|
224
|
+
const tenant = token.startsWith("cbp_") ? "" : tenantId;
|
|
225
|
+
return createHash("sha256").update(`cavelon-audience\0${token}\0${tenant}`).digest("hex").slice(0, 16);
|
|
226
|
+
}
|
|
227
|
+
tenantKey() {
|
|
228
|
+
const { token = "", tenantId = "" } = this.client.target;
|
|
229
|
+
if (!tenantId || token.startsWith("cbp_"))
|
|
230
|
+
return this.audience();
|
|
231
|
+
return createHash("sha256").update(`cavelon-tenant\0${tenantId}`).digest("hex").slice(0, 16);
|
|
232
|
+
}
|
|
233
|
+
cacheName(file) {
|
|
234
|
+
return file === "capabilities.json" ? Contracts.keyedName(file, this.tenantKey()) : file;
|
|
235
|
+
}
|
|
236
|
+
static keyedName(file, key) {
|
|
237
|
+
const dot = file.lastIndexOf(".");
|
|
238
|
+
return dot > 0 ? `${file.slice(0, dot)}.${key}${file.slice(dot)}` : `${file}.${key}`;
|
|
239
|
+
}
|
|
214
240
|
async text(file, load, options = {}) {
|
|
215
|
-
return this.cached(file, async () => {
|
|
241
|
+
return this.cached(Contracts.keyedName(file, this.audience()), async () => {
|
|
216
242
|
const text = await load();
|
|
217
243
|
return { value: text, serialized: text };
|
|
218
244
|
}, (text) => text, options);
|