@cavelon/cli 0.1.10 → 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/commands/api.js +38 -19
- package/dist/commands/chat.js +10 -5
- package/dist/commands/db.js +367 -0
- package/dist/commands/docs.js +83 -7
- package/dist/commands/index.js +6 -0
- package/dist/commands/limits-set.js +4 -2
- package/dist/commands/loops.js +60 -5
- package/dist/commands/models.js +2 -1
- package/dist/commands/sandboxes.js +7 -2
- package/dist/commands/session.js +107 -22
- package/dist/commands/solution.js +144 -32
- package/dist/commands/tenants.js +44 -8
- package/dist/commands/values.js +50 -9
- package/dist/commands/work.js +13 -5
- package/dist/confirm-token.js +12 -4
- package/dist/context.js +3 -1
- package/dist/contracts.js +37 -12
- package/dist/database-queries.js +301 -0
- package/dist/fsutil.js +14 -0
- package/dist/http.js +36 -2
- package/dist/invoke.js +4 -0
- package/dist/kit-codes.js +5 -0
- package/dist/mcp.js +69 -10
- package/dist/package-check.js +19 -0
- package/dist/preview-report.js +2 -2
- package/dist/principal.js +24 -2
- package/dist/secret-access.js +16 -4
- package/dist/session.js +36 -8
- package/dist/skills/cavelon-authoring/SKILL.md +79 -2
- package/dist/skills/cavelon-long-running/SKILL.md +8 -2
- package/dist/skills/cavelon-loop/SKILL.md +71 -16
- package/dist/skills/cavelon-testing/SKILL.md +28 -1
- package/dist/trace-view.js +10 -0
- package/dist/update-check.js +2 -2
- package/dist/user-config.js +24 -0
- package/package.json +1 -1
package/dist/commands/values.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { boolOption, CURSOR_OPTION, intOption, LIMIT_OPTION, pageOf, positional, stringOption, } from "../command.js";
|
|
2
|
+
import { refuseForAgent } from "../agent-env.js";
|
|
2
3
|
import { confirmation } from "../confirm-token.js";
|
|
3
4
|
import { CavelonError, ExitCode, usageError, validationError } from "../errors.js";
|
|
4
5
|
import { clip, keyValues, moreHint, table } from "../format.js";
|
|
@@ -6,7 +7,7 @@ import { callStable, workflowOperation } from "../invoke.js";
|
|
|
6
7
|
import { readAll } from "../io.js";
|
|
7
8
|
import { schemaErrors } from "../openapi.js";
|
|
8
9
|
import { readPrincipal } from "../principal.js";
|
|
9
|
-
import { permissionsNamed, SECRETS_PERMISSIONS, secretsPermissionMissing } from "../secret-access.js";
|
|
10
|
+
import { permissionsNamed, SECRETS_PERMISSIONS, secretsPermissionMissing, variablesPermissionMissing } from "../secret-access.js";
|
|
10
11
|
import { readHidden } from "../prompt.js";
|
|
11
12
|
import { readPackage } from "../package-files.js";
|
|
12
13
|
import { requireToken } from "../session.js";
|
|
@@ -108,12 +109,16 @@ export const variablesGet = {
|
|
|
108
109
|
};
|
|
109
110
|
export const variablesSet = {
|
|
110
111
|
name: "variables set",
|
|
111
|
-
summary: "Create or replace
|
|
112
|
+
summary: "Create a tenant variable, or replace one (previews first, --confirm replaces it).",
|
|
112
113
|
description: "The value is plain text that anyone who may view the tenant's settings reads; never put a credential into a variable,\n" +
|
|
113
|
-
"use `cavelon secrets set` (a person runs it). --stdin reads the value from standard input instead of the argument
|
|
114
|
+
"use `cavelon secrets set` (a person runs it). --stdin reads the value from standard input instead of the argument.\n" +
|
|
115
|
+
"A new variable is created at once. Replacing another value needs --confirm: without it nothing changes, and the preview\n" +
|
|
116
|
+
"shows the old and the new value. A variable is tenant-wide, so every solution that names it, active ones included, reads\n" +
|
|
117
|
+
"the new value: show the preview to a person and confirm only with their yes.",
|
|
114
118
|
readOnly: false,
|
|
115
119
|
idempotent: true,
|
|
116
120
|
mcpTool: "variables_set",
|
|
121
|
+
operations: ["PUT /api/v1/variables/{name}"],
|
|
117
122
|
positionals: [
|
|
118
123
|
{ name: "name", description: "The variable's name, as {{var:<name>}} uses it.", required: true },
|
|
119
124
|
{ name: "value", description: "The value (plain text, not a credential)." },
|
|
@@ -121,8 +126,14 @@ export const variablesSet = {
|
|
|
121
126
|
options: {
|
|
122
127
|
stdin: { type: "boolean", description: "Read the value from standard input.", cliOnly: true },
|
|
123
128
|
env: ENV_OPTION,
|
|
129
|
+
confirm: { type: "boolean", mcpToken: true, description: "Replace an existing value (after a person saw the preview); a new variable needs none." },
|
|
124
130
|
},
|
|
125
|
-
examples: [
|
|
131
|
+
examples: [
|
|
132
|
+
"cavelon variables set crm_base_url https://crm.example.com",
|
|
133
|
+
"cavelon variables set greeting --stdin < greeting.txt",
|
|
134
|
+
"cavelon variables set crm_base_url https://crm2.example.com --confirm",
|
|
135
|
+
"cavelon variables set crm_base_url https://crm2.example.com --confirm <token>",
|
|
136
|
+
],
|
|
126
137
|
async run(ctx, input) {
|
|
127
138
|
const name = positional(input, "name");
|
|
128
139
|
const argument = positional(input, "value");
|
|
@@ -137,9 +148,27 @@ export const variablesSet = {
|
|
|
137
148
|
}
|
|
138
149
|
await checkName(ctx, "PUT", "/api/v1/variables/{name}", "setting tenant variables", name);
|
|
139
150
|
const previous = await readVariable(ctx, name);
|
|
151
|
+
if (previous && previous.value !== value) {
|
|
152
|
+
const gate = await confirmation(ctx, input, "variables_set", { name, previous: previous.value, value });
|
|
153
|
+
if (!gate.confirmed) {
|
|
154
|
+
const confirm = gate.confirm(cavelonCommand("variables", "set", name, ...(fromStdin ? ["--stdin"] : [value]), "--confirm"));
|
|
155
|
+
return {
|
|
156
|
+
data: { name, changed: false, created: false, would: "replace", previous: previous.value, value, confirm, ...gate.fields },
|
|
157
|
+
text: [
|
|
158
|
+
`Variable ${name}: ${JSON.stringify(clip(previous.value, LIST_VALUE_CHARS))} → ${JSON.stringify(clip(value, LIST_VALUE_CHARS))}.`,
|
|
159
|
+
"It is tenant-wide: every solution of the tenant that names {{var:" + name + "}}, active ones included, reads the new value.",
|
|
160
|
+
gate.where, ...(gate.mismatch ? [gate.mismatch] : []),
|
|
161
|
+
`Nothing was changed. Show this to a person; with their yes: ${confirm}${fromStdin ? " (with the same value on standard input)" : ""}`,
|
|
162
|
+
].join("\n"),
|
|
163
|
+
...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
}
|
|
140
167
|
const saved = await callStable(ctx, "PUT", "/api/v1/variables/{name}", "setting tenant variables", {
|
|
141
168
|
params: { name: [name] },
|
|
142
169
|
body: { value },
|
|
170
|
+
}).catch((error) => {
|
|
171
|
+
throw variablesRefusedForRole(error, "set", name, fromStdin ? undefined : value);
|
|
143
172
|
});
|
|
144
173
|
const changed = previous?.value !== saved.value;
|
|
145
174
|
let text = `Variable ${saved.name} already had this value.`;
|
|
@@ -171,7 +200,7 @@ export const variablesDelete = {
|
|
|
171
200
|
const confirm = gate.confirm(cavelonCommand("variables", "delete", name, "--confirm"));
|
|
172
201
|
return {
|
|
173
202
|
data: { name, deleted: false, existed: true, value: current.value, confirm, ...gate.fields },
|
|
174
|
-
text: `Variable ${name} = ${JSON.stringify(clip(current.value, LIST_VALUE_CHARS))}.\n${gate.mismatch ? `${gate.mismatch}\n` : ""}Nothing was deleted. Delete it with: ${confirm}`,
|
|
203
|
+
text: `Variable ${name} = ${JSON.stringify(clip(current.value, LIST_VALUE_CHARS))}.\n${gate.where}\n${gate.mismatch ? `${gate.mismatch}\n` : ""}Nothing was deleted. Delete it with: ${confirm}`,
|
|
175
204
|
...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
|
|
176
205
|
};
|
|
177
206
|
}
|
|
@@ -180,7 +209,7 @@ export const variablesDelete = {
|
|
|
180
209
|
}
|
|
181
210
|
catch (error) {
|
|
182
211
|
if (!notFound(error))
|
|
183
|
-
throw error;
|
|
212
|
+
throw variablesRefusedForRole(error, "delete", name);
|
|
184
213
|
return { data: { name, deleted: false, existed: false }, text: `This tenant has no variable "${name}"; nothing to delete.` };
|
|
185
214
|
}
|
|
186
215
|
return { data: { name, deleted: true, existed: true, value: current.value }, text: `Deleted variable ${name}.` };
|
|
@@ -210,6 +239,14 @@ function refusedForRole(error, verb, name) {
|
|
|
210
239
|
return error;
|
|
211
240
|
return secretsPermissionMissing(verb, name, named.length ? named : SECRETS_PERMISSIONS);
|
|
212
241
|
}
|
|
242
|
+
function variablesRefusedForRole(error, verb, name, value) {
|
|
243
|
+
if (!(error instanceof CavelonError) || error.status !== 403)
|
|
244
|
+
return error;
|
|
245
|
+
const named = permissionsNamed(error.message);
|
|
246
|
+
if (!named.length && error.code !== "forbidden")
|
|
247
|
+
return error;
|
|
248
|
+
return variablesPermissionMissing(verb, name, named.length ? named : SECRETS_PERMISSIONS, value);
|
|
249
|
+
}
|
|
213
250
|
function withoutLineEnd(text) {
|
|
214
251
|
if (text.endsWith("\r\n"))
|
|
215
252
|
return text.slice(0, -2);
|
|
@@ -351,7 +388,8 @@ export const secretsSet = {
|
|
|
351
388
|
summary: "Set a secret's value (a person runs this, never the agent).",
|
|
352
389
|
description: "Asks for the value without echoing it, or reads it from standard input when that is piped (one trailing line break is\n" +
|
|
353
390
|
"dropped). The value is never an argument, never printed and never read back. A tenant API key cannot set a secret,\n" +
|
|
354
|
-
"nor can a role the instance does not allow to manage secrets (a Builder): its refusal then names who can, a tenant Owner
|
|
391
|
+
"nor can a role the instance does not allow to manage secrets (a Builder): its refusal then names who can, a tenant Owner.\n" +
|
|
392
|
+
"Run by a coding agent in its shell, it is refused before it reads a value (operation_for_a_person).",
|
|
355
393
|
readOnly: false,
|
|
356
394
|
idempotent: true,
|
|
357
395
|
mcpTool: false,
|
|
@@ -361,6 +399,7 @@ export const secretsSet = {
|
|
|
361
399
|
preprocess: refuseValueArgument,
|
|
362
400
|
async run(ctx, input) {
|
|
363
401
|
const name = positional(input, "name");
|
|
402
|
+
refuseForAgent(ctx, "Setting a secret's value", secretSetCommand(name));
|
|
364
403
|
await requirePerson(ctx, "set", name);
|
|
365
404
|
await checkName(ctx, "PUT", "/api/v1/secrets/{name}", "setting secrets", name);
|
|
366
405
|
const value = await readSecretValue(ctx, name);
|
|
@@ -379,7 +418,8 @@ export const secretsDelete = {
|
|
|
379
418
|
name: "secrets delete",
|
|
380
419
|
summary: "Delete a secret's value (needs --confirm; a person runs this).",
|
|
381
420
|
description: "Without --confirm, shows the secret's status and deletes nothing. A tool or prompt that names it fails until a person\n" +
|
|
382
|
-
"sets it again. A tenant API key cannot delete a secret."
|
|
421
|
+
"sets it again. A tenant API key cannot delete a secret. Run by a coding agent in its shell, it is refused, with or without\n" +
|
|
422
|
+
"--confirm (operation_for_a_person).",
|
|
383
423
|
readOnly: false,
|
|
384
424
|
destructive: true,
|
|
385
425
|
idempotent: true,
|
|
@@ -389,6 +429,7 @@ export const secretsDelete = {
|
|
|
389
429
|
examples: ["cavelon secrets delete old_token", "cavelon secrets delete old_token --confirm", "cavelon secrets delete old_token --confirm <token>"],
|
|
390
430
|
async run(ctx, input) {
|
|
391
431
|
const name = positional(input, "name");
|
|
432
|
+
refuseForAgent(ctx, "Deleting a secret's value", cavelonCommand("secrets", "delete", name));
|
|
392
433
|
await requirePerson(ctx, "delete", name);
|
|
393
434
|
const current = secretView(await callStable(ctx, "GET", "/api/v1/secrets/{name}", "tenant secrets", { params: { name: [name] } }));
|
|
394
435
|
const nothing = { data: { ...current, deleted: false }, text: `Secret ${name} has no value; nothing to delete.` };
|
|
@@ -399,7 +440,7 @@ export const secretsDelete = {
|
|
|
399
440
|
const confirm = gate.confirm(cavelonCommand("secrets", "delete", name, "--confirm"));
|
|
400
441
|
return {
|
|
401
442
|
data: { ...current, deleted: false, confirm, ...gate.fields },
|
|
402
|
-
text: `Secret ${name} is set${changedNote(current.changed_at)}.\n${gate.mismatch ? `${gate.mismatch}\n` : ""}Nothing was deleted. Delete it with: ${confirm}`,
|
|
443
|
+
text: `Secret ${name} is set${changedNote(current.changed_at)}.\n${gate.where}\n${gate.mismatch ? `${gate.mismatch}\n` : ""}Nothing was deleted. Delete it with: ${confirm}`,
|
|
403
444
|
...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
|
|
404
445
|
};
|
|
405
446
|
}
|
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";
|
|
@@ -412,6 +412,7 @@ export const kbUpload = {
|
|
|
412
412
|
"instance publishes its documents' file hashes.",
|
|
413
413
|
readOnly: false,
|
|
414
414
|
mcpTool: "kb_upload",
|
|
415
|
+
operations: ["POST /api/v1/knowledge-bases/{kb_id}/documents/upload"],
|
|
415
416
|
positionals: [{ name: "dir", description: "Folder (or single file) to upload.", required: true }],
|
|
416
417
|
options: {
|
|
417
418
|
kb: { type: "string", value: "<kb>", description: "Knowledge base name or id (required)." },
|
|
@@ -500,7 +501,7 @@ export const kbUpload = {
|
|
|
500
501
|
text: [
|
|
501
502
|
`--replace uploads ${fileCount(rel.length)} and then deactivates ${deactivations.length} document${deactivations.length === 1 ? "" : "s"} the instance's upload does not replace itself:`,
|
|
502
503
|
...matches.map(plannedLine),
|
|
503
|
-
...(gate.mismatch ? [gate.mismatch] : []),
|
|
504
|
+
gate.where, ...(gate.mismatch ? [gate.mismatch] : []),
|
|
504
505
|
`Nothing was sent. Upload and deactivate with: ${confirm}`,
|
|
505
506
|
].join("\n"),
|
|
506
507
|
...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
|
|
@@ -654,6 +655,7 @@ export const testRun = {
|
|
|
654
655
|
"5 when answers wait for a manual verdict or a value a case needs.",
|
|
655
656
|
readOnly: false,
|
|
656
657
|
mcpTool: "test_run",
|
|
658
|
+
operations: ["POST /api/v1/test-suites/{suite_id}/runs"],
|
|
657
659
|
options: {
|
|
658
660
|
suite: { type: "string", multiple: true, value: "<suite>", description: "Suite name or id." },
|
|
659
661
|
harness: { type: "string", value: "<harness>", description: "The solution to run against: its name, slug or id." },
|
|
@@ -802,6 +804,7 @@ function knowledgeOutcomes(spans) {
|
|
|
802
804
|
}
|
|
803
805
|
function summarizeSpan(s, outcomes) {
|
|
804
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);
|
|
805
808
|
return {
|
|
806
809
|
span_id: s.id,
|
|
807
810
|
seq: s.sequence ?? null,
|
|
@@ -811,6 +814,8 @@ function summarizeSpan(s, outcomes) {
|
|
|
811
814
|
status: s.status ?? null,
|
|
812
815
|
duration_ms: s.duration_ms ?? null,
|
|
813
816
|
knowledge_outcome: outcomeOf(s) ?? outcomes?.get(s.id) ?? null,
|
|
817
|
+
...(s.tool_type ? { tool_type: s.tool_type } : {}),
|
|
818
|
+
...(code ? { error_code: code } : {}),
|
|
814
819
|
error,
|
|
815
820
|
};
|
|
816
821
|
}
|
|
@@ -1047,16 +1052,19 @@ export const trace = {
|
|
|
1047
1052
|
tokens: span.token_usage_json ?? null,
|
|
1048
1053
|
error: span.error_json ?? null,
|
|
1049
1054
|
};
|
|
1050
|
-
|
|
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 };
|
|
1051
1058
|
}
|
|
1052
1059
|
const page = pageOf(spans.map((s) => summarizeSpan(s, outcomes)), limit, cursor);
|
|
1053
1060
|
const words = ["trace", id, ...(kind ? ["--kind", kind] : []), "--trace", traceId];
|
|
1054
1061
|
const base = cavelonCommand(...words);
|
|
1055
|
-
const open = suggestedSpan(spans);
|
|
1062
|
+
const open = suggestedSpan(spans.map((s) => (queryErrorCode(s) ? { ...s, status: "error" } : s)));
|
|
1063
|
+
const codes = page.items.some((s) => "error_code" in s);
|
|
1056
1064
|
return {
|
|
1057
1065
|
data: { trace: summarizeTrace(detail), spans: page },
|
|
1058
1066
|
text: `${keyValues(Object.entries(summarizeTrace(detail)))}\n\n` +
|
|
1059
|
-
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"]) +
|
|
1060
1068
|
moreHint(page.next_cursor, base) +
|
|
1061
1069
|
(open ? `\n\nOne span in full (${spanPick(open)}), by the span_id in its row: ${cavelonCommand(...words, "--span", open.id)}` : ""),
|
|
1062
1070
|
};
|
package/dist/confirm-token.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
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";
|
|
@@ -23,7 +24,14 @@ export function withToken(printed, token) {
|
|
|
23
24
|
return `${command.slice(0, at)} --confirm ${token}${command.slice(at + " --confirm".length)}`;
|
|
24
25
|
return `${command} --confirm ${token}`;
|
|
25
26
|
}
|
|
26
|
-
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) {
|
|
27
35
|
const given = input.options.confirm;
|
|
28
36
|
const driven = drivenByAgent(ctx);
|
|
29
37
|
const tokenGiven = typeof given === "string" && given !== "";
|
|
@@ -39,7 +47,7 @@ export async function confirmation(ctx, input, tool, change) {
|
|
|
39
47
|
confirmed: false,
|
|
40
48
|
fields: { confirm_token: token, token_required: true },
|
|
41
49
|
confirm,
|
|
42
|
-
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.`,
|
|
43
51
|
exitCode: ExitCode.needsAction,
|
|
44
52
|
};
|
|
45
53
|
}
|
|
@@ -55,10 +63,10 @@ export async function confirmation(ctx, input, tool, change) {
|
|
|
55
63
|
exitCode: ExitCode.conflict,
|
|
56
64
|
};
|
|
57
65
|
}
|
|
58
|
-
export function shellTokenRequired(command
|
|
66
|
+
export function shellTokenRequired(command) {
|
|
59
67
|
return new CavelonError(ExitCode.needsAction, {
|
|
60
68
|
code: "confirm_token_required",
|
|
61
|
-
message:
|
|
69
|
+
message: "--confirm alone does not confirm when a coding agent runs cavelon; nothing was changed.",
|
|
62
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.`,
|
|
63
71
|
});
|
|
64
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
|
@@ -4,7 +4,7 @@ import { CavelonError, ExitCode } from "./errors.js";
|
|
|
4
4
|
import { NOT_HERE } from "./http.js";
|
|
5
5
|
import { cacheDir, instanceKey } from "./paths.js";
|
|
6
6
|
import { cavelonCommand } from "./printed.js";
|
|
7
|
-
import { readJsonFile, readTextFile,
|
|
7
|
+
import { readJsonFile, readTextFile, writePrivateFile } from "./fsutil.js";
|
|
8
8
|
import { SUPPORTED_CONTRACTS } from "./version.js";
|
|
9
9
|
const NOT_MODIFIED = Symbol("not modified");
|
|
10
10
|
const RELEASE_TTL_SECONDS = 3600;
|
|
@@ -37,6 +37,9 @@ export class Contracts {
|
|
|
37
37
|
static isDevelopment(version) {
|
|
38
38
|
return version === "unknown" || /dev|snapshot|local/i.test(version);
|
|
39
39
|
}
|
|
40
|
+
async write(file, content) {
|
|
41
|
+
await writePrivateFile(cacheDir(this.env), file, content);
|
|
42
|
+
}
|
|
40
43
|
versionDir(version) {
|
|
41
44
|
return path.join(this.root, version.replace(/[^A-Za-z0-9._-]+/g, "_"));
|
|
42
45
|
}
|
|
@@ -49,12 +52,14 @@ export class Contracts {
|
|
|
49
52
|
if (this.caps !== undefined && !options.refresh)
|
|
50
53
|
return this.caps;
|
|
51
54
|
const state = await readJsonFile(path.join(this.root, "state.json"));
|
|
52
|
-
if (!options.refresh && state
|
|
53
|
-
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;
|
|
54
59
|
if (cached) {
|
|
55
60
|
this.caps = cached;
|
|
56
61
|
this.versionValue = state.version;
|
|
57
|
-
this.cachedAt =
|
|
62
|
+
this.cachedAt = meta?.fetched_at;
|
|
58
63
|
return cached;
|
|
59
64
|
}
|
|
60
65
|
}
|
|
@@ -76,9 +81,11 @@ export class Contracts {
|
|
|
76
81
|
else {
|
|
77
82
|
this.caps = response.data;
|
|
78
83
|
this.versionValue = response.data.instance.version || "unknown";
|
|
79
|
-
|
|
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 }));
|
|
80
87
|
}
|
|
81
|
-
await
|
|
88
|
+
await this.write(path.join(this.root, "state.json"), JSON.stringify({ version: this.versionValue, checked_at: now }, null, 2));
|
|
82
89
|
return this.caps;
|
|
83
90
|
}
|
|
84
91
|
async liveCapabilities() {
|
|
@@ -112,11 +119,11 @@ export class Contracts {
|
|
|
112
119
|
if (loaded === NOT_MODIFIED) {
|
|
113
120
|
if (!cached)
|
|
114
121
|
throw new Error(`${file}: the instance answered 304 Not Modified without being sent an ETag.`);
|
|
115
|
-
await
|
|
122
|
+
await this.write(metaFile, JSON.stringify({ ...meta, fetched_at: fetchedAt }));
|
|
116
123
|
return cached.value;
|
|
117
124
|
}
|
|
118
|
-
await
|
|
119
|
-
await
|
|
125
|
+
await this.write(target, loaded.serialized);
|
|
126
|
+
await this.write(metaFile, JSON.stringify({ fetched_at: fetchedAt, ...(loaded.etag ? { etag: loaded.etag } : {}) }));
|
|
120
127
|
return loaded.value;
|
|
121
128
|
}
|
|
122
129
|
async getJson(route, etag, options = {}) {
|
|
@@ -188,7 +195,7 @@ export class Contracts {
|
|
|
188
195
|
const state = await readJsonFile(path.join(this.root, "state.json"));
|
|
189
196
|
if (!state)
|
|
190
197
|
return undefined;
|
|
191
|
-
const target = path.join(this.versionDir(state.version), file);
|
|
198
|
+
const target = path.join(this.versionDir(state.version), this.cacheName(file));
|
|
192
199
|
const text = await readTextFile(target);
|
|
193
200
|
if (text === undefined)
|
|
194
201
|
return undefined;
|
|
@@ -199,7 +206,7 @@ export class Contracts {
|
|
|
199
206
|
catch {
|
|
200
207
|
return undefined;
|
|
201
208
|
}
|
|
202
|
-
const meta =
|
|
209
|
+
const meta = await readJsonFile(`${target}.meta.json`);
|
|
203
210
|
return {
|
|
204
211
|
value,
|
|
205
212
|
version: state.version,
|
|
@@ -212,8 +219,26 @@ export class Contracts {
|
|
|
212
219
|
static packageSchemaFile(version) {
|
|
213
220
|
return `package-schema-${version.replace(/[^A-Za-z0-9._-]+/g, "_")}.json`;
|
|
214
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
|
+
}
|
|
215
240
|
async text(file, load, options = {}) {
|
|
216
|
-
return this.cached(file, async () => {
|
|
241
|
+
return this.cached(Contracts.keyedName(file, this.audience()), async () => {
|
|
217
242
|
const text = await load();
|
|
218
243
|
return { value: text, serialized: text };
|
|
219
244
|
}, (text) => text, options);
|