@cavelon/cli 0.0.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +697 -3
- package/dist/LICENSE +201 -0
- package/dist/agents.js +91 -0
- package/dist/branches.js +61 -0
- package/dist/capacity.js +162 -0
- package/dist/cli.js +4 -0
- package/dist/command.js +62 -0
- package/dist/commands/api.js +243 -0
- package/dist/commands/async.js +207 -0
- package/dist/commands/docs.js +158 -0
- package/dist/commands/index.js +112 -0
- package/dist/commands/init.js +452 -0
- package/dist/commands/inventory.js +56 -0
- package/dist/commands/limits-set.js +624 -0
- package/dist/commands/limits.js +156 -0
- package/dist/commands/loops.js +792 -0
- package/dist/commands/models.js +197 -0
- package/dist/commands/sandboxes.js +667 -0
- package/dist/commands/session.js +476 -0
- package/dist/commands/solution.js +760 -0
- package/dist/commands/tenants.js +266 -0
- package/dist/commands/values.js +383 -0
- package/dist/commands/work.js +744 -0
- package/dist/context.js +56 -0
- package/dist/contracts.js +189 -0
- package/dist/credentials.js +134 -0
- package/dist/errors.js +64 -0
- package/dist/features.js +37 -0
- package/dist/format.js +36 -0
- package/dist/fsutil.js +40 -0
- package/dist/git.js +41 -0
- package/dist/http.js +286 -0
- package/dist/invoke.js +161 -0
- package/dist/io.js +49 -0
- package/dist/limits.js +299 -0
- package/dist/local-state.js +60 -0
- package/dist/main.js +227 -0
- package/dist/markers.js +113 -0
- package/dist/mcp.js +130 -0
- package/dist/openapi.js +223 -0
- package/dist/operations.js +107 -0
- package/dist/package-check.js +342 -0
- package/dist/package-files.js +329 -0
- package/dist/pair-order.js +39 -0
- package/dist/paths.js +28 -0
- package/dist/principal.js +33 -0
- package/dist/project.js +138 -0
- package/dist/prompt.js +34 -0
- package/dist/results.js +66 -0
- package/dist/session.js +166 -0
- package/dist/shell.js +41 -0
- package/dist/skills/cavelon-authoring/SKILL.md +214 -0
- package/dist/skills/cavelon-long-running/SKILL.md +181 -0
- package/dist/skills/cavelon-loop/SKILL.md +158 -0
- package/dist/skills/cavelon-testing/SKILL.md +90 -0
- package/dist/sse.js +44 -0
- package/dist/tar.js +172 -0
- package/dist/user-config.js +36 -0
- package/dist/version.js +17 -0
- package/dist/zip.js +132 -0
- package/package.json +40 -4
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
import { boolOption, CURSOR_OPTION, intOption, LIMIT_OPTION, pageOf, positional, stringOption, } from "../command.js";
|
|
2
|
+
import { CavelonError, ExitCode, usageError } from "../errors.js";
|
|
3
|
+
import { keyValues, moreHint, table } from "../format.js";
|
|
4
|
+
import { callStable } from "../invoke.js";
|
|
5
|
+
import { formatQuota, limitError, limitsOrWarn, readQuotas } from "../limits.js";
|
|
6
|
+
import { isUuid, requireInstance } from "../session.js";
|
|
7
|
+
import { cavelonCommand } from "../shell.js";
|
|
8
|
+
import { rememberTenant } from "./session.js";
|
|
9
|
+
function idempotency(key) {
|
|
10
|
+
return key ? { "Idempotency-Key": key } : undefined;
|
|
11
|
+
}
|
|
12
|
+
const IDEMPOTENCY_OPTION = {
|
|
13
|
+
type: "string",
|
|
14
|
+
value: "<key>",
|
|
15
|
+
description: "Send an Idempotency-Key, so a retry does not create a second one.",
|
|
16
|
+
};
|
|
17
|
+
export const tenantCreate = {
|
|
18
|
+
name: "tenant create",
|
|
19
|
+
summary: "Create a tenant (personal access token in Platform mode with tenants.manage).",
|
|
20
|
+
description: "A tenant API key never can. Inviting people and assigning roles stay in the Admin.",
|
|
21
|
+
readOnly: false,
|
|
22
|
+
mcpTool: "tenant_create",
|
|
23
|
+
positionals: [{ name: "slug", description: "Lower-case letters, digits and dashes.", required: true }],
|
|
24
|
+
options: {
|
|
25
|
+
name: { type: "string", value: "<name>", description: "Display name (default: the slug)." },
|
|
26
|
+
plan: { type: "string", value: "<plan>", description: "Licence plan, when the instance knows several." },
|
|
27
|
+
use: { type: "boolean", description: "Switch to the new tenant afterwards (`cavelon use`)." },
|
|
28
|
+
"idempotency-key": IDEMPOTENCY_OPTION,
|
|
29
|
+
},
|
|
30
|
+
async run(ctx, input) {
|
|
31
|
+
const session = await ctx.session();
|
|
32
|
+
if (session.tokenKind === "api_key") {
|
|
33
|
+
throw new CavelonError(ExitCode.unauthorized, {
|
|
34
|
+
code: "api_key_cannot_create_tenants",
|
|
35
|
+
message: "A tenant API key can never create a tenant.",
|
|
36
|
+
hint: "Use a personal access token that allows Platform mode, owned by someone with tenants.manage.",
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
const slug = positional(input, "slug");
|
|
40
|
+
const body = { slug, name: stringOption(input, "name") ?? slug };
|
|
41
|
+
const plan = stringOption(input, "plan");
|
|
42
|
+
if (plan)
|
|
43
|
+
body.plan = plan;
|
|
44
|
+
const tenant = await callStable(ctx, "POST", "/api/v1/tenants", "creating tenants", {
|
|
45
|
+
body,
|
|
46
|
+
sendTenant: false,
|
|
47
|
+
headers: idempotency(stringOption(input, "idempotency-key")),
|
|
48
|
+
});
|
|
49
|
+
if (boolOption(input, "use"))
|
|
50
|
+
await rememberTenant(ctx, requireInstance(session), { ref: tenant.slug, id: tenant.id, name: tenant.name });
|
|
51
|
+
return {
|
|
52
|
+
data: tenant,
|
|
53
|
+
text: `Created tenant ${tenant.name} (${tenant.slug}, ${tenant.id}).${boolOption(input, "use") ? " Now using it." : " Switch with: " + cavelonCommand("use", tenant.slug)}`,
|
|
54
|
+
};
|
|
55
|
+
},
|
|
56
|
+
};
|
|
57
|
+
export const tenantList = {
|
|
58
|
+
name: "tenant list",
|
|
59
|
+
summary: "List the tenants this token can see.",
|
|
60
|
+
readOnly: true,
|
|
61
|
+
idempotent: true,
|
|
62
|
+
mcpTool: "tenant_list",
|
|
63
|
+
options: {
|
|
64
|
+
search: { type: "string", value: "<text>", description: "Only tenants whose name or slug contains the text." },
|
|
65
|
+
limit: LIMIT_OPTION,
|
|
66
|
+
cursor: CURSOR_OPTION,
|
|
67
|
+
},
|
|
68
|
+
async run(ctx, input) {
|
|
69
|
+
const session = await ctx.session();
|
|
70
|
+
if (session.tokenKind === "api_key") {
|
|
71
|
+
throw usageError("A tenant API key sees only its own tenant.", "`cavelon whoami` shows it.");
|
|
72
|
+
}
|
|
73
|
+
const limit = intOption(input, "limit", { min: 1, max: 200, fallback: 50 });
|
|
74
|
+
const cursor = stringOption(input, "cursor");
|
|
75
|
+
const offset = cursor === undefined ? 0 : Number(cursor);
|
|
76
|
+
if (!Number.isInteger(offset) || offset < 0)
|
|
77
|
+
throw usageError(`--cursor "${cursor}" is not a cursor from a previous page.`);
|
|
78
|
+
const client = await ctx.client({ tenant: false });
|
|
79
|
+
const listing = await client.get("/api/v1/tenants", {
|
|
80
|
+
query: { limit, offset, search: stringOption(input, "search") },
|
|
81
|
+
sendTenant: false,
|
|
82
|
+
allow: [403],
|
|
83
|
+
});
|
|
84
|
+
let page;
|
|
85
|
+
if (listing.status === 200) {
|
|
86
|
+
const items = listing.data.items.map((t) => ({ id: t.id, slug: t.slug, name: t.name, status: t.status ?? null, plan: t.plan ?? null }));
|
|
87
|
+
page = {
|
|
88
|
+
items,
|
|
89
|
+
next_cursor: offset + items.length < listing.data.total ? String(offset + items.length) : null,
|
|
90
|
+
total: listing.data.total,
|
|
91
|
+
source: "platform",
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
else {
|
|
95
|
+
const me = await client.get("/api/v1/auth/me", { sendTenant: false });
|
|
96
|
+
const search = stringOption(input, "search")?.toLowerCase();
|
|
97
|
+
const all = (me.data.memberships ?? [])
|
|
98
|
+
.filter((m) => !search || m.tenant_name.toLowerCase().includes(search))
|
|
99
|
+
.map((m) => ({ id: m.tenant_id, slug: null, name: m.tenant_name, role: m.role ?? null }));
|
|
100
|
+
page = { ...pageOf(all, limit, cursor), source: "memberships" };
|
|
101
|
+
}
|
|
102
|
+
const columns = page.source === "platform" ? ["slug", "name", "status", "id"] : ["name", "role", "id"];
|
|
103
|
+
return {
|
|
104
|
+
data: page,
|
|
105
|
+
text: (table(page.items, columns) || "No tenants.") + moreHint(page.next_cursor, "cavelon tenant list"),
|
|
106
|
+
};
|
|
107
|
+
},
|
|
108
|
+
};
|
|
109
|
+
export const harnessList = {
|
|
110
|
+
name: "harness list",
|
|
111
|
+
summary: "List the tenant's solutions (harnesses).",
|
|
112
|
+
readOnly: true,
|
|
113
|
+
idempotent: true,
|
|
114
|
+
mcpTool: "harness_list",
|
|
115
|
+
options: {
|
|
116
|
+
readiness: { type: "boolean", description: "Include whether each one is ready to activate (slower)." },
|
|
117
|
+
limit: LIMIT_OPTION,
|
|
118
|
+
cursor: CURSOR_OPTION,
|
|
119
|
+
},
|
|
120
|
+
async run(ctx, input) {
|
|
121
|
+
const harnesses = await callStable(ctx, "GET", "/api/v1/harnesses", "listing solutions", {
|
|
122
|
+
query: { include_readiness: boolOption(input, "readiness") ? true : undefined },
|
|
123
|
+
});
|
|
124
|
+
const limit = intOption(input, "limit", { min: 1, max: 500, fallback: 50 });
|
|
125
|
+
const page = pageOf(harnesses.map((h) => ({
|
|
126
|
+
id: h.id,
|
|
127
|
+
slug: h.slug,
|
|
128
|
+
name: h.name,
|
|
129
|
+
status: h.status,
|
|
130
|
+
is_default: h.is_default ?? false,
|
|
131
|
+
...(h.readiness ? { ready_to_activate: h.readiness.ready_to_activate ?? null } : {}),
|
|
132
|
+
})), limit, stringOption(input, "cursor"));
|
|
133
|
+
const columns = ["slug", "name", "status", ...(boolOption(input, "readiness") ? ["ready_to_activate"] : []), "id"];
|
|
134
|
+
return {
|
|
135
|
+
data: page,
|
|
136
|
+
text: (table(page.items, columns) || "No solutions yet. Create one: cavelon harness new <slug>") + moreHint(page.next_cursor, "cavelon harness list"),
|
|
137
|
+
};
|
|
138
|
+
},
|
|
139
|
+
};
|
|
140
|
+
const HARNESS_QUOTA = "harnesses";
|
|
141
|
+
async function checkHarnessCapacity(ctx, slug) {
|
|
142
|
+
const published = await limitsOrWarn(ctx);
|
|
143
|
+
if (!published?.published)
|
|
144
|
+
return;
|
|
145
|
+
const licence = published.byKey.get("licence_max_harnesses");
|
|
146
|
+
const cap = typeof licence?.value === "number" ? licence.value : undefined;
|
|
147
|
+
const quotas = published.tenantQuotas ? await readQuotas(ctx, published).catch(() => undefined) : undefined;
|
|
148
|
+
const quota = quotas?.items.find((q) => q.key === HARNESS_QUOTA);
|
|
149
|
+
const quotaFull = (quota?.ratio ?? 0) >= 1;
|
|
150
|
+
if (!quotaFull && cap === undefined)
|
|
151
|
+
return;
|
|
152
|
+
const harnesses = await callStable(ctx, "GET", "/api/v1/harnesses", "listing solutions");
|
|
153
|
+
if (harnesses.some((h) => h.slug === slug))
|
|
154
|
+
return;
|
|
155
|
+
if (quota && quotas && quotaFull) {
|
|
156
|
+
throw new CavelonError(ExitCode.validation, {
|
|
157
|
+
code: "tenant_quota_reached",
|
|
158
|
+
message: `This tenant has used ${formatQuota(quota)} of its solution quota, so nothing was sent.`,
|
|
159
|
+
hint: `A platform administrator raises the tenant's quotas; \`cavelon limits\` shows them${quotas.docs ? ` (docs: ${quotas.docs})` : ""}. Archiving an unused solution frees one.`,
|
|
160
|
+
docs: quotas.docs ?? undefined,
|
|
161
|
+
details: { quota: { key: quota.key, current: quota.current, limit: quota.limit, path: quotas.path }, sent: false },
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
if (licence && cap !== undefined) {
|
|
165
|
+
const active = harnesses.filter((h) => h.status !== "archived").length;
|
|
166
|
+
if (active >= cap) {
|
|
167
|
+
throw limitError({
|
|
168
|
+
code: "license_limit_reached",
|
|
169
|
+
exitCode: ExitCode.unauthorized,
|
|
170
|
+
message: `The licence allows ${cap} solutions that are not archived on the whole instance, and this tenant alone has ${active}, ` +
|
|
171
|
+
"so nothing was sent.",
|
|
172
|
+
limits: [licence],
|
|
173
|
+
details: { active_in_tenant: active },
|
|
174
|
+
hint: "Archive an unused solution, or ask the operator for a renewed licence.",
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
export const harnessNew = {
|
|
180
|
+
name: "harness new",
|
|
181
|
+
summary: "Create an empty draft solution (harness).",
|
|
182
|
+
readOnly: false,
|
|
183
|
+
mcpTool: "harness_new",
|
|
184
|
+
positionals: [{ name: "slug", description: "The new solution's slug.", required: true }],
|
|
185
|
+
options: {
|
|
186
|
+
name: { type: "string", value: "<name>", description: "Display name (default: the slug)." },
|
|
187
|
+
description: { type: "string", value: "<text>", description: "What the solution is for." },
|
|
188
|
+
"idempotency-key": IDEMPOTENCY_OPTION,
|
|
189
|
+
},
|
|
190
|
+
async run(ctx, input) {
|
|
191
|
+
const slug = positional(input, "slug");
|
|
192
|
+
const body = { slug, name: stringOption(input, "name") ?? slug };
|
|
193
|
+
const description = stringOption(input, "description");
|
|
194
|
+
if (description)
|
|
195
|
+
body.description = description;
|
|
196
|
+
await checkHarnessCapacity(ctx, slug);
|
|
197
|
+
const harness = await callStable(ctx, "POST", "/api/v1/harnesses", "creating solutions", {
|
|
198
|
+
body,
|
|
199
|
+
headers: idempotency(stringOption(input, "idempotency-key")),
|
|
200
|
+
});
|
|
201
|
+
return {
|
|
202
|
+
data: harness,
|
|
203
|
+
text: keyValues([
|
|
204
|
+
["created", `${harness.name} (${harness.slug})`],
|
|
205
|
+
["id", harness.id],
|
|
206
|
+
["status", harness.status],
|
|
207
|
+
]),
|
|
208
|
+
};
|
|
209
|
+
},
|
|
210
|
+
};
|
|
211
|
+
export async function resolveHarnessId(ctx, ref) {
|
|
212
|
+
if (isUuid(ref))
|
|
213
|
+
return ref;
|
|
214
|
+
const harness = await callStable(ctx, "GET", "/api/v1/harnesses/by-slug/{slug}", "finding solutions by slug", {
|
|
215
|
+
params: { slug: [ref] },
|
|
216
|
+
});
|
|
217
|
+
return harness.id;
|
|
218
|
+
}
|
|
219
|
+
export const harnessClone = {
|
|
220
|
+
name: "harness clone",
|
|
221
|
+
summary: "Copy a solution into a new draft solution.",
|
|
222
|
+
readOnly: false,
|
|
223
|
+
mcpTool: "harness_clone",
|
|
224
|
+
positionals: [{ name: "source", description: "Slug or id of the solution to copy.", required: true }],
|
|
225
|
+
options: {
|
|
226
|
+
slug: { type: "string", value: "<slug>", description: "The copy's slug." },
|
|
227
|
+
name: { type: "string", value: "<name>", description: "The copy's display name." },
|
|
228
|
+
description: { type: "string", value: "<text>", description: "The copy's description." },
|
|
229
|
+
suffix: { type: "string", value: "<suffix>", description: "Appended to the slugs of copied elements." },
|
|
230
|
+
"no-tests": { type: "boolean", description: "Do not copy the test suites." },
|
|
231
|
+
"no-triggers": { type: "boolean", description: "Do not copy the triggers." },
|
|
232
|
+
"idempotency-key": IDEMPOTENCY_OPTION,
|
|
233
|
+
},
|
|
234
|
+
async run(ctx, input) {
|
|
235
|
+
const source = positional(input, "source");
|
|
236
|
+
const id = await resolveHarnessId(ctx, source);
|
|
237
|
+
const body = {};
|
|
238
|
+
for (const [option, field] of [
|
|
239
|
+
["slug", "slug"],
|
|
240
|
+
["name", "name"],
|
|
241
|
+
["description", "description"],
|
|
242
|
+
["suffix", "element_slug_suffix"],
|
|
243
|
+
]) {
|
|
244
|
+
const value = stringOption(input, option);
|
|
245
|
+
if (value !== undefined)
|
|
246
|
+
body[field] = value;
|
|
247
|
+
}
|
|
248
|
+
if (boolOption(input, "no-tests"))
|
|
249
|
+
body.include_tests = false;
|
|
250
|
+
if (boolOption(input, "no-triggers"))
|
|
251
|
+
body.include_triggers = false;
|
|
252
|
+
const harness = await callStable(ctx, "POST", "/api/v1/harnesses/{harness_id}/clone", "cloning solutions", {
|
|
253
|
+
params: { harness_id: [id] },
|
|
254
|
+
body,
|
|
255
|
+
headers: idempotency(stringOption(input, "idempotency-key")),
|
|
256
|
+
});
|
|
257
|
+
return {
|
|
258
|
+
data: harness,
|
|
259
|
+
text: keyValues([
|
|
260
|
+
["cloned", `${source} → ${harness.name} (${harness.slug})`],
|
|
261
|
+
["id", harness.id],
|
|
262
|
+
["status", harness.status],
|
|
263
|
+
]),
|
|
264
|
+
};
|
|
265
|
+
},
|
|
266
|
+
};
|
|
@@ -0,0 +1,383 @@
|
|
|
1
|
+
import { boolOption, CURSOR_OPTION, intOption, LIMIT_OPTION, pageOf, positional, stringOption, } from "../command.js";
|
|
2
|
+
import { CavelonError, ExitCode, usageError, validationError } from "../errors.js";
|
|
3
|
+
import { clip, keyValues, moreHint, table } from "../format.js";
|
|
4
|
+
import { callStable, workflowOperation } from "../invoke.js";
|
|
5
|
+
import { readAll } from "../io.js";
|
|
6
|
+
import { schemaErrors } from "../openapi.js";
|
|
7
|
+
import { readPrincipal } from "../principal.js";
|
|
8
|
+
import { readHidden } from "../prompt.js";
|
|
9
|
+
import { requireToken } from "../session.js";
|
|
10
|
+
import { shellWord } from "../shell.js";
|
|
11
|
+
export const ENV_OPTION = { type: "string", value: "<name>", description: "Act in the tenant that env/<name>.yaml names." };
|
|
12
|
+
const CONFIRM_OPTION = { type: "boolean", description: "Delete it; without this nothing is deleted." };
|
|
13
|
+
const TOKEN_PREFIXES = ["cbp_", "cvpat_"];
|
|
14
|
+
const LIST_VALUE_CHARS = 200;
|
|
15
|
+
export function targetFlags(session) {
|
|
16
|
+
if (session.envFile)
|
|
17
|
+
return ` --env ${shellWord(session.envFile.name)}`;
|
|
18
|
+
if (session.tenantSource === "option" && session.tenant)
|
|
19
|
+
return ` --tenant ${shellWord(session.tenant)}`;
|
|
20
|
+
return "";
|
|
21
|
+
}
|
|
22
|
+
export function secretSetCommand(name, flags = "") {
|
|
23
|
+
return `cavelon secrets set ${shellWord(name)}${flags}`;
|
|
24
|
+
}
|
|
25
|
+
export function variableSetCommand(name, flags = "") {
|
|
26
|
+
return `cavelon variables set ${shellWord(name)} <value>${flags}`;
|
|
27
|
+
}
|
|
28
|
+
async function checkName(ctx, method, template, what, name) {
|
|
29
|
+
const { doc, op } = await workflowOperation(ctx, method, template, what);
|
|
30
|
+
const param = op.parameters.find((p) => p.name === "name");
|
|
31
|
+
if (!doc || !param?.schema)
|
|
32
|
+
return;
|
|
33
|
+
const errors = schemaErrors(doc, param.schema, name);
|
|
34
|
+
if (errors.length) {
|
|
35
|
+
throw validationError(`"${name}" is not a name this instance accepts: ${errors.map((e) => e.replace("(body) ", "")).join("; ")}.`, { name, schema: param.schema }, param.description);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
function notFound(error) {
|
|
39
|
+
return error instanceof CavelonError && error.status === 404;
|
|
40
|
+
}
|
|
41
|
+
async function readVariable(ctx, name) {
|
|
42
|
+
try {
|
|
43
|
+
return await callStable(ctx, "GET", "/api/v1/variables/{name}", "tenant variables", { params: { name: [name] } });
|
|
44
|
+
}
|
|
45
|
+
catch (error) {
|
|
46
|
+
if (notFound(error))
|
|
47
|
+
return undefined;
|
|
48
|
+
throw error;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
function variableNotSet(name, flags) {
|
|
52
|
+
return new CavelonError(ExitCode.failure, {
|
|
53
|
+
code: "variable_not_set",
|
|
54
|
+
status: 404,
|
|
55
|
+
message: `This tenant has no variable "${name}".`,
|
|
56
|
+
hint: `\`cavelon variables list\` shows them; \`${variableSetCommand(name, flags)}\` sets it.`,
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
export const variablesList = {
|
|
60
|
+
name: "variables list",
|
|
61
|
+
summary: "List the tenant's variables ({{var:…}}) with their values.",
|
|
62
|
+
description: "Variables are plain text: anyone who may view the tenant's settings reads them. A credential belongs in a secret.\n" +
|
|
63
|
+
`A value longer than ${LIST_VALUE_CHARS} characters is cut here; \`cavelon variables get <name>\` returns it whole.`,
|
|
64
|
+
readOnly: true,
|
|
65
|
+
idempotent: true,
|
|
66
|
+
mcpTool: "variables_list",
|
|
67
|
+
options: { limit: LIMIT_OPTION, cursor: CURSOR_OPTION, env: ENV_OPTION },
|
|
68
|
+
examples: ["cavelon variables list", "cavelon variables list --env prod --json"],
|
|
69
|
+
async run(ctx, input) {
|
|
70
|
+
const limit = intOption(input, "limit", { min: 1, max: 500, fallback: 50 });
|
|
71
|
+
const all = (await callStable(ctx, "GET", "/api/v1/variables", "tenant variables")).items ?? [];
|
|
72
|
+
const page = pageOf(all, limit, stringOption(input, "cursor"));
|
|
73
|
+
const items = page.items.map((v) => ({
|
|
74
|
+
name: v.name,
|
|
75
|
+
value: v.value.length > LIST_VALUE_CHARS ? v.value.slice(0, LIST_VALUE_CHARS) : v.value,
|
|
76
|
+
...(v.value.length > LIST_VALUE_CHARS ? { value_truncated: true } : {}),
|
|
77
|
+
source: v.source ?? null,
|
|
78
|
+
}));
|
|
79
|
+
const flags = targetFlags(await ctx.session());
|
|
80
|
+
const text = items.length
|
|
81
|
+
? table(items.map((v) => ({ ...v, source: v.source ?? "" })), ["name", "value", "source"], 60) + moreHint(page.next_cursor, `cavelon variables list${flags}`)
|
|
82
|
+
: `No variables in this tenant. Set one with: cavelon variables set <name> <value>${flags}`;
|
|
83
|
+
return { data: { items, next_cursor: page.next_cursor, total: page.total }, text };
|
|
84
|
+
},
|
|
85
|
+
};
|
|
86
|
+
export const variablesGet = {
|
|
87
|
+
name: "variables get",
|
|
88
|
+
summary: "Show one tenant variable with its whole value.",
|
|
89
|
+
readOnly: true,
|
|
90
|
+
idempotent: true,
|
|
91
|
+
mcpTool: "variables_get",
|
|
92
|
+
positionals: [{ name: "name", description: "The variable's name, as {{var:<name>}} uses it.", required: true }],
|
|
93
|
+
options: { env: ENV_OPTION },
|
|
94
|
+
async run(ctx, input) {
|
|
95
|
+
const name = positional(input, "name");
|
|
96
|
+
const variable = await readVariable(ctx, name);
|
|
97
|
+
if (!variable)
|
|
98
|
+
throw variableNotSet(name, targetFlags(await ctx.session()));
|
|
99
|
+
const data = { name: variable.name, value: variable.value, source: variable.source ?? null };
|
|
100
|
+
return {
|
|
101
|
+
data,
|
|
102
|
+
text: keyValues([
|
|
103
|
+
["name", data.name],
|
|
104
|
+
["value", data.value],
|
|
105
|
+
["source", data.source ? `the setting ${data.source} (change it there)` : undefined],
|
|
106
|
+
]),
|
|
107
|
+
};
|
|
108
|
+
},
|
|
109
|
+
};
|
|
110
|
+
export const variablesSet = {
|
|
111
|
+
name: "variables set",
|
|
112
|
+
summary: "Create or replace a tenant variable.",
|
|
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" +
|
|
114
|
+
"use `cavelon secrets set` (a person runs it). --stdin reads the value from standard input instead of the argument.",
|
|
115
|
+
readOnly: false,
|
|
116
|
+
idempotent: true,
|
|
117
|
+
mcpTool: "variables_set",
|
|
118
|
+
positionals: [
|
|
119
|
+
{ name: "name", description: "The variable's name, as {{var:<name>}} uses it.", required: true },
|
|
120
|
+
{ name: "value", description: "The value (plain text, not a credential)." },
|
|
121
|
+
],
|
|
122
|
+
options: {
|
|
123
|
+
stdin: { type: "boolean", description: "Read the value from standard input.", cliOnly: true },
|
|
124
|
+
env: ENV_OPTION,
|
|
125
|
+
},
|
|
126
|
+
examples: ["cavelon variables set crm_base_url https://crm.example.com", "cavelon variables set greeting --stdin < greeting.txt"],
|
|
127
|
+
async run(ctx, input) {
|
|
128
|
+
const name = positional(input, "name");
|
|
129
|
+
const argument = positional(input, "value");
|
|
130
|
+
const fromStdin = boolOption(input, "stdin");
|
|
131
|
+
if (argument !== undefined && fromStdin)
|
|
132
|
+
throw usageError("Pass the value as an argument or with --stdin, not both.");
|
|
133
|
+
if (argument === undefined && !fromStdin)
|
|
134
|
+
throw usageError("Missing <value>.", "Usage: cavelon variables set <name> <value> (or --stdin)");
|
|
135
|
+
const value = argument ?? withoutLineEnd(await readAll(ctx.io.stdin));
|
|
136
|
+
if (TOKEN_PREFIXES.some((prefix) => value.startsWith(prefix))) {
|
|
137
|
+
throw usageError("That value looks like a key or token. A variable is plain text anyone with settings access reads; nothing was sent.", `Keep credentials in a secret, which a person sets: ${secretSetCommand(name)}. If this was a real token, revoke it.`);
|
|
138
|
+
}
|
|
139
|
+
await checkName(ctx, "PUT", "/api/v1/variables/{name}", "setting tenant variables", name);
|
|
140
|
+
const previous = await readVariable(ctx, name);
|
|
141
|
+
const saved = await callStable(ctx, "PUT", "/api/v1/variables/{name}", "setting tenant variables", {
|
|
142
|
+
params: { name: [name] },
|
|
143
|
+
body: { value },
|
|
144
|
+
});
|
|
145
|
+
const changed = previous?.value !== saved.value;
|
|
146
|
+
let text = `Variable ${saved.name} already had this value.`;
|
|
147
|
+
if (!previous)
|
|
148
|
+
text = `Created variable ${saved.name}.`;
|
|
149
|
+
else if (changed)
|
|
150
|
+
text = `Replaced variable ${saved.name} (it was ${JSON.stringify(clip(previous.value, LIST_VALUE_CHARS))}).`;
|
|
151
|
+
return { data: { name: saved.name, value: saved.value, created: !previous, changed, previous: previous ? previous.value : null }, text };
|
|
152
|
+
},
|
|
153
|
+
};
|
|
154
|
+
export const variablesDelete = {
|
|
155
|
+
name: "variables delete",
|
|
156
|
+
summary: "Delete a tenant variable (needs --confirm).",
|
|
157
|
+
description: "Without --confirm, shows the variable and deletes nothing. A prompt or tool that names it gets no value afterwards.",
|
|
158
|
+
readOnly: false,
|
|
159
|
+
destructive: true,
|
|
160
|
+
idempotent: true,
|
|
161
|
+
mcpTool: false,
|
|
162
|
+
positionals: [{ name: "name", description: "The variable's name.", required: true }],
|
|
163
|
+
options: { confirm: CONFIRM_OPTION, env: ENV_OPTION },
|
|
164
|
+
examples: ["cavelon variables delete old_url", "cavelon variables delete old_url --confirm"],
|
|
165
|
+
async run(ctx, input) {
|
|
166
|
+
const name = positional(input, "name");
|
|
167
|
+
const flags = targetFlags(await ctx.session());
|
|
168
|
+
const current = await readVariable(ctx, name);
|
|
169
|
+
if (!current)
|
|
170
|
+
return { data: { name, deleted: false, existed: false }, text: `This tenant has no variable "${name}"; nothing to delete.` };
|
|
171
|
+
if (!boolOption(input, "confirm")) {
|
|
172
|
+
const confirm = `cavelon variables delete ${shellWord(name)}${flags} --confirm`;
|
|
173
|
+
return {
|
|
174
|
+
data: { name, deleted: false, existed: true, value: current.value, confirm },
|
|
175
|
+
text: `Variable ${name} = ${JSON.stringify(clip(current.value, LIST_VALUE_CHARS))}.\nNothing was deleted. Delete it with: ${confirm}`,
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
try {
|
|
179
|
+
await callStable(ctx, "DELETE", "/api/v1/variables/{name}", "deleting tenant variables", { params: { name: [name] } });
|
|
180
|
+
}
|
|
181
|
+
catch (error) {
|
|
182
|
+
if (!notFound(error))
|
|
183
|
+
throw error;
|
|
184
|
+
return { data: { name, deleted: false, existed: false }, text: `This tenant has no variable "${name}"; nothing to delete.` };
|
|
185
|
+
}
|
|
186
|
+
return { data: { name, deleted: true, existed: true, value: current.value }, text: `Deleted variable ${name}.` };
|
|
187
|
+
},
|
|
188
|
+
};
|
|
189
|
+
async function requirePerson(ctx, verb, name) {
|
|
190
|
+
const session = await ctx.session();
|
|
191
|
+
requireToken(session);
|
|
192
|
+
let apiKey = session.tokenKind === "api_key";
|
|
193
|
+
if (!apiKey && session.tokenKind !== "personal_access_token")
|
|
194
|
+
apiKey = (await readPrincipal(await ctx.client()))?.kind === "api_key";
|
|
195
|
+
if (!apiKey)
|
|
196
|
+
return;
|
|
197
|
+
const fromEnv = session.tokenSource === "CAVELON_TOKEN" ? "CAVELON_TOKEN holds a tenant API key. " : "";
|
|
198
|
+
throw new CavelonError(ExitCode.unauthorized, {
|
|
199
|
+
code: "secret_needs_a_person",
|
|
200
|
+
message: `A tenant API key cannot ${verb} a secret, so nothing was sent: ${verb === "set" ? "setting" : "deleting"} a secret needs a person (a dashboard session or a personal access token).`,
|
|
201
|
+
hint: `${fromEnv}A person logs in with a personal access token (\`cavelon login\`) and runs \`cavelon secrets ${verb} ${shellWord(name)}\`, or does it in the Admin.`,
|
|
202
|
+
details: { sent: false, credential: "api_key" },
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
function withoutLineEnd(text) {
|
|
206
|
+
if (text.endsWith("\r\n"))
|
|
207
|
+
return text.slice(0, -2);
|
|
208
|
+
if (text.endsWith("\n"))
|
|
209
|
+
return text.slice(0, -1);
|
|
210
|
+
return text;
|
|
211
|
+
}
|
|
212
|
+
const OPTIONS_WITH_VALUE = new Set(["--instance", "--tenant", "--env"]);
|
|
213
|
+
function refuseValueArgument(args) {
|
|
214
|
+
let positionals = 0;
|
|
215
|
+
for (let i = 0; i < args.length; i++) {
|
|
216
|
+
const arg = args[i];
|
|
217
|
+
if (arg === "--") {
|
|
218
|
+
positionals += args.length - i - 1;
|
|
219
|
+
break;
|
|
220
|
+
}
|
|
221
|
+
if (OPTIONS_WITH_VALUE.has(arg))
|
|
222
|
+
i++;
|
|
223
|
+
else if (!arg.startsWith("-"))
|
|
224
|
+
positionals++;
|
|
225
|
+
}
|
|
226
|
+
if (positionals > 1) {
|
|
227
|
+
throw usageError("cavelon secrets set never takes the value as an argument: it would stay in the shell history. Nothing was sent.", "Run `cavelon secrets set <name>` and type the value when asked, or pipe it in. If that was a real secret, rotate it.");
|
|
228
|
+
}
|
|
229
|
+
return args;
|
|
230
|
+
}
|
|
231
|
+
async function readSecretValue(ctx, name) {
|
|
232
|
+
const { io } = ctx;
|
|
233
|
+
const usage = `A person runs \`${secretSetCommand(name)}\` in a terminal and types it, or pipes it in: \`op read … | ${secretSetCommand(name)}\`.`;
|
|
234
|
+
let value;
|
|
235
|
+
if (io.stdin.isTTY) {
|
|
236
|
+
if (!io.stderr.isTTY)
|
|
237
|
+
throw usageError(`No terminal to ask for the value of ${name} on; nothing was sent.`, usage);
|
|
238
|
+
value = await readHidden(io, `Value of secret ${name} (input hidden): `, `Nothing was set; secret ${name} is unchanged.`);
|
|
239
|
+
}
|
|
240
|
+
else {
|
|
241
|
+
value = withoutLineEnd(await readAll(io.stdin));
|
|
242
|
+
}
|
|
243
|
+
if (!value)
|
|
244
|
+
throw usageError(`No value for secret ${name} on standard input; nothing was sent.`, usage);
|
|
245
|
+
return value;
|
|
246
|
+
}
|
|
247
|
+
function withoutValue(error, value) {
|
|
248
|
+
const scrub = (item) => {
|
|
249
|
+
if (typeof item === "string")
|
|
250
|
+
return item.replaceAll(value, "[secret value]");
|
|
251
|
+
if (Array.isArray(item))
|
|
252
|
+
return item.map(scrub);
|
|
253
|
+
if (item && typeof item === "object")
|
|
254
|
+
return Object.fromEntries(Object.entries(item).map(([k, v]) => [k, scrub(v)]));
|
|
255
|
+
return item;
|
|
256
|
+
};
|
|
257
|
+
if (error instanceof CavelonError) {
|
|
258
|
+
return new CavelonError(error.exitCode, {
|
|
259
|
+
code: error.code,
|
|
260
|
+
message: scrub(error.message),
|
|
261
|
+
hint: error.hint === undefined ? undefined : scrub(error.hint),
|
|
262
|
+
docs: error.docs,
|
|
263
|
+
status: error.status,
|
|
264
|
+
details: scrub(error.details),
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
return new Error(scrub(error instanceof Error ? error.message : String(error)));
|
|
268
|
+
}
|
|
269
|
+
function changedNote(changedAt) {
|
|
270
|
+
return changedAt ? " (changed " + changedAt + ")" : "";
|
|
271
|
+
}
|
|
272
|
+
function secretView(status) {
|
|
273
|
+
return {
|
|
274
|
+
name: status.name,
|
|
275
|
+
status: status.status,
|
|
276
|
+
changed_at: status.changed_at ?? null,
|
|
277
|
+
declared: Boolean(status.declared),
|
|
278
|
+
description: status.description ?? null,
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
export const secretsList = {
|
|
282
|
+
name: "secrets list",
|
|
283
|
+
summary: "List the tenant's secret names ({{secret:…}}) with whether each is set; never a value.",
|
|
284
|
+
description: "Lists every secret that has a value or that an imported package declared. A person sets a missing one with\n" +
|
|
285
|
+
"`cavelon secrets set <name>`; an agent never sets or reads a secret value.",
|
|
286
|
+
readOnly: true,
|
|
287
|
+
idempotent: true,
|
|
288
|
+
mcpTool: "secrets_list",
|
|
289
|
+
options: {
|
|
290
|
+
missing: { type: "boolean", description: "Only the secrets that are not set." },
|
|
291
|
+
limit: LIMIT_OPTION,
|
|
292
|
+
cursor: CURSOR_OPTION,
|
|
293
|
+
env: ENV_OPTION,
|
|
294
|
+
},
|
|
295
|
+
examples: ["cavelon secrets list", "cavelon secrets list --missing --json"],
|
|
296
|
+
async run(ctx, input) {
|
|
297
|
+
const limit = intOption(input, "limit", { min: 1, max: 500, fallback: 50 });
|
|
298
|
+
const flags = targetFlags(await ctx.session());
|
|
299
|
+
const all = ((await callStable(ctx, "GET", "/api/v1/secrets", "tenant secrets")).items ?? []).map(secretView);
|
|
300
|
+
const wanted = boolOption(input, "missing") ? all.filter((s) => s.status !== "set") : all;
|
|
301
|
+
const page = pageOf(wanted, limit, stringOption(input, "cursor"));
|
|
302
|
+
const items = page.items.map((s) => (s.status === "set" ? s : { ...s, set_by_person: secretSetCommand(s.name, flags) }));
|
|
303
|
+
const missing = all.filter((s) => s.status !== "set").length;
|
|
304
|
+
const onlyMissing = boolOption(input, "missing");
|
|
305
|
+
let text = onlyMissing ? "Every secret this tenant knows is set." : "This tenant has no secrets and no package declared one.";
|
|
306
|
+
if (items.length) {
|
|
307
|
+
const rows = items.map((s) => ({ ...s, declared: s.declared ? "yes" : "", changed_at: s.changed_at ?? "", description: s.description ?? "" }));
|
|
308
|
+
const next = moreHint(page.next_cursor, `cavelon secrets list${onlyMissing ? " --missing" : ""}${flags}`);
|
|
309
|
+
const howTo = missing ? `\n\n${missing} not set. A person sets each with: cavelon secrets set <name>${flags}` : "";
|
|
310
|
+
text = table(rows, ["name", "status", "declared", "changed_at", "description"], 50) + next + howTo;
|
|
311
|
+
}
|
|
312
|
+
return { data: { items, next_cursor: page.next_cursor, total: page.total, not_set: missing }, text };
|
|
313
|
+
},
|
|
314
|
+
};
|
|
315
|
+
export const secretsSet = {
|
|
316
|
+
name: "secrets set",
|
|
317
|
+
summary: "Set a secret's value (a person runs this, never the agent).",
|
|
318
|
+
description: "Asks for the value without echoing it, or reads it from standard input when that is piped (one trailing line break is\n" +
|
|
319
|
+
"dropped). The value is never an argument, never printed and never read back. A tenant API key cannot set a secret.",
|
|
320
|
+
readOnly: false,
|
|
321
|
+
idempotent: true,
|
|
322
|
+
mcpTool: false,
|
|
323
|
+
positionals: [{ name: "name", description: "The secret's name, as {{secret:<name>}} uses it.", required: true }],
|
|
324
|
+
options: { env: ENV_OPTION },
|
|
325
|
+
examples: ["cavelon secrets set crm_api_token", "op read op://dev/crm/token | cavelon secrets set crm_api_token"],
|
|
326
|
+
preprocess: refuseValueArgument,
|
|
327
|
+
async run(ctx, input) {
|
|
328
|
+
const name = positional(input, "name");
|
|
329
|
+
await requirePerson(ctx, "set", name);
|
|
330
|
+
await checkName(ctx, "PUT", "/api/v1/secrets/{name}", "setting secrets", name);
|
|
331
|
+
const value = await readSecretValue(ctx, name);
|
|
332
|
+
let status;
|
|
333
|
+
try {
|
|
334
|
+
status = await callStable(ctx, "PUT", "/api/v1/secrets/{name}", "setting secrets", { params: { name: [name] }, body: { value } });
|
|
335
|
+
}
|
|
336
|
+
catch (error) {
|
|
337
|
+
throw withoutValue(error, value);
|
|
338
|
+
}
|
|
339
|
+
const data = secretView(status);
|
|
340
|
+
return { data, text: `Secret ${data.name} is set${changedNote(data.changed_at)}. Its value is never shown.` };
|
|
341
|
+
},
|
|
342
|
+
};
|
|
343
|
+
export const secretsDelete = {
|
|
344
|
+
name: "secrets delete",
|
|
345
|
+
summary: "Delete a secret's value (needs --confirm; a person runs this).",
|
|
346
|
+
description: "Without --confirm, shows the secret's status and deletes nothing. A tool or prompt that names it fails until a person\n" +
|
|
347
|
+
"sets it again. A tenant API key cannot delete a secret.",
|
|
348
|
+
readOnly: false,
|
|
349
|
+
destructive: true,
|
|
350
|
+
idempotent: true,
|
|
351
|
+
mcpTool: false,
|
|
352
|
+
positionals: [{ name: "name", description: "The secret's name.", required: true }],
|
|
353
|
+
options: { confirm: CONFIRM_OPTION, env: ENV_OPTION },
|
|
354
|
+
examples: ["cavelon secrets delete old_token", "cavelon secrets delete old_token --confirm"],
|
|
355
|
+
async run(ctx, input) {
|
|
356
|
+
const name = positional(input, "name");
|
|
357
|
+
await requirePerson(ctx, "delete", name);
|
|
358
|
+
const flags = targetFlags(await ctx.session());
|
|
359
|
+
const current = secretView(await callStable(ctx, "GET", "/api/v1/secrets/{name}", "tenant secrets", { params: { name: [name] } }));
|
|
360
|
+
const nothing = { data: { ...current, deleted: false }, text: `Secret ${name} has no value; nothing to delete.` };
|
|
361
|
+
if (current.status !== "set")
|
|
362
|
+
return nothing;
|
|
363
|
+
if (!boolOption(input, "confirm")) {
|
|
364
|
+
const confirm = `cavelon secrets delete ${shellWord(name)}${flags} --confirm`;
|
|
365
|
+
return {
|
|
366
|
+
data: { ...current, deleted: false, confirm },
|
|
367
|
+
text: `Secret ${name} is set${changedNote(current.changed_at)}.\nNothing was deleted. Delete it with: ${confirm}`,
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
try {
|
|
371
|
+
await callStable(ctx, "DELETE", "/api/v1/secrets/{name}", "deleting secrets", { params: { name: [name] } });
|
|
372
|
+
}
|
|
373
|
+
catch (error) {
|
|
374
|
+
if (notFound(error))
|
|
375
|
+
return nothing;
|
|
376
|
+
throw error;
|
|
377
|
+
}
|
|
378
|
+
return {
|
|
379
|
+
data: { ...current, status: "not_set", deleted: true },
|
|
380
|
+
text: `Deleted the value of secret ${name}. A person sets it again with: ${secretSetCommand(name, flags)}`,
|
|
381
|
+
};
|
|
382
|
+
},
|
|
383
|
+
};
|