@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.
- package/README.md +50 -20
- package/dist/agents.js +43 -19
- package/dist/choose.js +112 -0
- package/dist/command.js +1 -1
- package/dist/commands/api.js +76 -6
- package/dist/commands/index.js +2 -0
- package/dist/commands/init.js +196 -29
- package/dist/commands/limits-set.js +17 -8
- package/dist/commands/limits.js +2 -2
- package/dist/commands/loops.js +12 -6
- package/dist/commands/sandboxes.js +27 -20
- package/dist/commands/session.js +179 -45
- package/dist/commands/setup.js +426 -0
- package/dist/commands/solution.js +137 -91
- package/dist/commands/tenants.js +33 -22
- package/dist/commands/values.js +8 -5
- package/dist/commands/work.js +33 -16
- package/dist/context.js +5 -1
- package/dist/contracts.js +83 -38
- package/dist/embedded.js +7 -0
- package/dist/features.js +15 -0
- package/dist/fsutil.js +3 -0
- package/dist/git.js +14 -9
- package/dist/harness-ref.js +54 -0
- package/dist/http.js +44 -18
- package/dist/install.js +94 -0
- package/dist/invoke.js +17 -13
- package/dist/limits.js +9 -1
- package/dist/local-state.js +18 -0
- package/dist/main.js +31 -2
- package/dist/markers.js +53 -0
- package/dist/mcp.js +9 -2
- package/dist/openapi.js +10 -0
- package/dist/operations.js +1 -1
- package/dist/package-check.js +1 -1
- package/dist/package-files.js +103 -38
- package/dist/paths.js +53 -4
- package/dist/principal.js +43 -0
- package/dist/project.js +23 -4
- package/dist/prompt.js +55 -11
- package/dist/results.js +47 -9
- package/dist/run-program.js +92 -0
- package/dist/session.js +100 -19
- package/dist/setup-agents.js +544 -0
- package/dist/skills/cavelon-authoring/SKILL.md +13 -3
- package/dist/skills/cavelon-long-running/SKILL.md +5 -1
- package/dist/skills/cavelon-loop/SKILL.md +15 -9
- package/dist/skills/cavelon-testing/SKILL.md +9 -2
- package/dist/tenant-choice.js +93 -0
- package/dist/update-check.js +118 -0
- package/dist/version.js +2 -1
- package/package.json +5 -2
package/dist/commands/init.js
CHANGED
|
@@ -4,15 +4,22 @@ import { parseDocument } from "yaml";
|
|
|
4
4
|
import { boolOption, listOption, stringOption } from "../command.js";
|
|
5
5
|
import { AGENTS, bundledSkills, generatedCopy, parseAgents, SKILL_ROOTS } from "../agents.js";
|
|
6
6
|
import { CavelonError, ExitCode, usageError } from "../errors.js";
|
|
7
|
-
import {
|
|
7
|
+
import { confinedPath, realPath, within } from "../paths.js";
|
|
8
|
+
import { readTextFile, withoutBom, writeFileAtomic } from "../fsutil.js";
|
|
8
9
|
import { git } from "../git.js";
|
|
9
10
|
import { ensureStateDir, STATE_DIR } from "../local-state.js";
|
|
10
11
|
import { isGenerated, upsertBlock, upsertJsonEntry } from "../markers.js";
|
|
11
12
|
import { packageVersionOf } from "../package-check.js";
|
|
12
13
|
import { defaultLayoutFor, safeSectionName, schemaSections, toYaml, writePackage } from "../package-files.js";
|
|
13
|
-
import { readPrincipal } from "../principal.js";
|
|
14
|
+
import { readPrincipal, readTenantless } from "../principal.js";
|
|
14
15
|
import { ENV_DIR, parseProject, PROJECT_FILE } from "../project.js";
|
|
15
|
-
import {
|
|
16
|
+
import { canAsk, readLine } from "../prompt.js";
|
|
17
|
+
import { pick } from "../choose.js";
|
|
18
|
+
import { harnessNotFoundError, listHarnesses, lookupHarness } from "../harness-ref.js";
|
|
19
|
+
import { lookupTenantId, requireInstance, requireToken, tenantRequiredError } from "../session.js";
|
|
20
|
+
import { cavelonCommand } from "../shell.js";
|
|
21
|
+
import { chooseTenant, listsTenants, noTenantError, tenantOpenError, tenantRef, tenantTitle } from "../tenant-choice.js";
|
|
22
|
+
import { createHarness } from "./tenants.js";
|
|
16
23
|
import { schemaFor, setProjectKey } from "./solution.js";
|
|
17
24
|
const HOOK_LINES = (prefix) => [
|
|
18
25
|
"# Check the Cavelon package before each commit (`cavelon init --hook`).",
|
|
@@ -117,6 +124,8 @@ async function writeSkills(root, roots) {
|
|
|
117
124
|
async function writeMcp(root, target, onlyExisting) {
|
|
118
125
|
const file = path.join(root, target.file);
|
|
119
126
|
const existing = await readTextFile(file);
|
|
127
|
+
if (existing !== undefined && holdsOtherForm(existing, target))
|
|
128
|
+
return { file: target.file, action: "unchanged" };
|
|
120
129
|
if (target.format === "toml")
|
|
121
130
|
return applyBlock(root, file, upsertBlock(existing, target.block, "hash", { onlyExisting }));
|
|
122
131
|
if (onlyExisting) {
|
|
@@ -136,6 +145,20 @@ async function writeMcp(root, target, onlyExisting) {
|
|
|
136
145
|
}
|
|
137
146
|
return applyBlock(root, file, result);
|
|
138
147
|
}
|
|
148
|
+
function holdsOtherForm(existing, target) {
|
|
149
|
+
if (target.format === "toml") {
|
|
150
|
+
const text = existing.replace(/\r\n/g, "\n");
|
|
151
|
+
return target.others.some((block) => text.includes(`# cavelon:begin\n${block}\n# cavelon:end`));
|
|
152
|
+
}
|
|
153
|
+
let current;
|
|
154
|
+
try {
|
|
155
|
+
current = target.keys.reduce((node, key) => (node && typeof node === "object" ? node[key] : undefined), JSON.parse(existing));
|
|
156
|
+
}
|
|
157
|
+
catch {
|
|
158
|
+
return false;
|
|
159
|
+
}
|
|
160
|
+
return target.others.some((entry) => JSON.stringify(entry) === JSON.stringify(current));
|
|
161
|
+
}
|
|
139
162
|
async function installedFallback(root) {
|
|
140
163
|
const skillRoots = [];
|
|
141
164
|
for (const skillRoot of SKILL_ROOTS) {
|
|
@@ -168,6 +191,18 @@ async function installHook(root, onlyExisting) {
|
|
|
168
191
|
return { file: ".git/hooks/pre-commit", action: "skipped", reason: "this folder is not in a git repository" };
|
|
169
192
|
}
|
|
170
193
|
const file = path.resolve(root, hooks, "pre-commit");
|
|
194
|
+
const top = (await git(["rev-parse", "--show-toplevel"], root))?.trim();
|
|
195
|
+
const common = (await git(["rev-parse", "--git-common-dir"], root))?.trim();
|
|
196
|
+
const own = [top, common].filter((dir) => Boolean(dir)).map((dir) => path.resolve(root, dir));
|
|
197
|
+
const hooksDir = await realPath(path.dirname(file));
|
|
198
|
+
const inside = await Promise.all(own.map(async (dir) => within(await realPath(dir), hooksDir)));
|
|
199
|
+
if (!inside.includes(true)) {
|
|
200
|
+
return {
|
|
201
|
+
file: rel(root, file),
|
|
202
|
+
action: "skipped",
|
|
203
|
+
reason: `core.hooksPath points to ${path.dirname(file)}, outside this repository, where other repositories' hooks may be; add the block yourself if you want it there`,
|
|
204
|
+
};
|
|
205
|
+
}
|
|
171
206
|
const body = HOOK_LINES(prefix).join("\n");
|
|
172
207
|
const existing = await readTextFile(file);
|
|
173
208
|
let result = upsertBlock(existing, body, "hash", { onlyExisting, afterShebang: true });
|
|
@@ -181,18 +216,133 @@ async function installHook(root, onlyExisting) {
|
|
|
181
216
|
}
|
|
182
217
|
return action;
|
|
183
218
|
}
|
|
184
|
-
function solutionYaml(values) {
|
|
219
|
+
function solutionYaml(values, tenantNote) {
|
|
220
|
+
let body = toYaml(values).trimEnd();
|
|
221
|
+
if (tenantNote)
|
|
222
|
+
body = body.split("\n").map((line) => (line.startsWith("tenant: ") ? `${line} # ${tenantNote}` : line)).join("\n");
|
|
185
223
|
return [
|
|
186
224
|
"# A Cavelon solution. `cavelon` finds this file from the working directory upwards;",
|
|
187
225
|
"# it names the instance, tenant and solution, never a token.",
|
|
188
|
-
|
|
226
|
+
body,
|
|
189
227
|
"",
|
|
190
228
|
].join("\n");
|
|
191
229
|
}
|
|
230
|
+
function commentText(text) {
|
|
231
|
+
return [...text].map((c) => (c < " " || c === "\u007f" ? " " : c)).join("").trim();
|
|
232
|
+
}
|
|
233
|
+
export function slugFromName(name) {
|
|
234
|
+
const plain = name.normalize("NFKD").replace(/[\u0300-\u036f]/g, "").toLowerCase();
|
|
235
|
+
let slug = plain.replace(/[^a-z0-9]+/g, "-");
|
|
236
|
+
while (slug.startsWith("-"))
|
|
237
|
+
slug = slug.slice(1);
|
|
238
|
+
while (slug.endsWith("-"))
|
|
239
|
+
slug = slug.slice(0, -1);
|
|
240
|
+
slug = slug.slice(0, 60);
|
|
241
|
+
while (slug.endsWith("-"))
|
|
242
|
+
slug = slug.slice(0, -1);
|
|
243
|
+
return slug;
|
|
244
|
+
}
|
|
245
|
+
const SLUG = /^[a-z0-9][a-z0-9-]*$/;
|
|
246
|
+
async function initTenant(ctx, session) {
|
|
247
|
+
if (session.tokenKind === "api_key")
|
|
248
|
+
return session.tenant ? { ref: session.tenant } : undefined;
|
|
249
|
+
const client = await ctx.client({ tenant: false });
|
|
250
|
+
const pat = session.tokenKind === "personal_access_token";
|
|
251
|
+
const tenantless = pat ? await readTenantless(client) : undefined;
|
|
252
|
+
const reach = listsTenants(tenantless) ? tenantless : undefined;
|
|
253
|
+
if (session.tenant) {
|
|
254
|
+
const found = await lookupTenantId(client, session.tenant, session.tenantSource);
|
|
255
|
+
const listed = reach?.tenants.find((t) => t.id === found.id);
|
|
256
|
+
const name = found.name ?? listed?.name ?? undefined;
|
|
257
|
+
const slug = found.slug ?? listed?.slug ?? undefined;
|
|
258
|
+
return { ref: slug ?? session.tenant, id: found.id, name, slug };
|
|
259
|
+
}
|
|
260
|
+
if (tenantless?.refused)
|
|
261
|
+
throw tenantRequiredError(client.url, tenantless.said);
|
|
262
|
+
if (reach && !reach.platform && (canAsk(ctx) || !reach.tenantId)) {
|
|
263
|
+
const choice = await chooseTenant(ctx, client, reach);
|
|
264
|
+
if (choice.kind === "none")
|
|
265
|
+
throw noTenantError(client.url, false);
|
|
266
|
+
if (choice.kind === "open") {
|
|
267
|
+
throw tenantOpenError(client.url, reach, "A solution belongs to one tenant. ", {
|
|
268
|
+
line: (ref) => cavelonCommand("init", "--tenant", ref),
|
|
269
|
+
template: "cavelon init --tenant <name or slug>",
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
const t = choice.tenant;
|
|
273
|
+
if (choice.how === "picked")
|
|
274
|
+
ctx.io.stderr.write(`Using tenant ${tenantTitle(t)}.\n`);
|
|
275
|
+
return { ref: tenantRef(t), id: t.id, name: t.name ?? undefined, slug: t.slug ?? undefined };
|
|
276
|
+
}
|
|
277
|
+
const placed = reach?.tenantId ?? (tenantless && !tenantless.refused ? tenantless.tenantId : null) ?? (await readPrincipal(await ctx.client()))?.tenant_id;
|
|
278
|
+
if (!placed)
|
|
279
|
+
return undefined;
|
|
280
|
+
const listed = reach?.tenants.find((t) => t.id === placed);
|
|
281
|
+
return { ref: listed?.slug ?? placed, id: placed, name: listed?.name ?? undefined, slug: listed?.slug ?? undefined };
|
|
282
|
+
}
|
|
283
|
+
async function initHarness(ctx, given) {
|
|
284
|
+
if (given) {
|
|
285
|
+
let lookup;
|
|
286
|
+
try {
|
|
287
|
+
lookup = await lookupHarness(ctx, given);
|
|
288
|
+
}
|
|
289
|
+
catch (error) {
|
|
290
|
+
ctx.warn(`Could not check solution "${given}" on the instance: ${error instanceof Error ? error.message : String(error)}`);
|
|
291
|
+
return { slug: given };
|
|
292
|
+
}
|
|
293
|
+
if (lookup.harness)
|
|
294
|
+
return { slug: lookup.harness.slug };
|
|
295
|
+
if (SLUG.test(given))
|
|
296
|
+
return { slug: given, missing: true };
|
|
297
|
+
throw harnessNotFoundError(given, lookup.candidates, undefined, (slug) => cavelonCommand("init", "--harness", slug));
|
|
298
|
+
}
|
|
299
|
+
let all;
|
|
300
|
+
try {
|
|
301
|
+
all = await listHarnesses(ctx);
|
|
302
|
+
}
|
|
303
|
+
catch {
|
|
304
|
+
return {};
|
|
305
|
+
}
|
|
306
|
+
const choices = all.map((h) => ({ id: h.id, slug: h.slug, name: h.name, status: h.status }));
|
|
307
|
+
if (!canAsk(ctx))
|
|
308
|
+
return { choices };
|
|
309
|
+
const write = (text) => ctx.io.stderr.write(`${text}\n`);
|
|
310
|
+
let name;
|
|
311
|
+
if (all.length) {
|
|
312
|
+
const picked = await pick(ctx, {
|
|
313
|
+
intro: `This tenant has ${all.length} solution${all.length === 1 ? "" : "s"}:`,
|
|
314
|
+
question: "Which solution does this folder hold?",
|
|
315
|
+
items: all,
|
|
316
|
+
extra: (h) => h.status,
|
|
317
|
+
other: { label: "a new solution (or type new)", word: "new" },
|
|
318
|
+
});
|
|
319
|
+
if ("item" in picked)
|
|
320
|
+
return { slug: picked.item.slug };
|
|
321
|
+
name = await readLine(ctx.io, "Name of the new solution: ");
|
|
322
|
+
}
|
|
323
|
+
else {
|
|
324
|
+
write("This tenant has no solutions yet.");
|
|
325
|
+
name = await readLine(ctx.io, "Name of the new solution (press Enter to decide later): ");
|
|
326
|
+
if (!name)
|
|
327
|
+
return {};
|
|
328
|
+
}
|
|
329
|
+
let base = slugFromName(name);
|
|
330
|
+
while (!base) {
|
|
331
|
+
write("The name needs at least one letter or digit.");
|
|
332
|
+
name = await readLine(ctx.io, "Name of the new solution: ");
|
|
333
|
+
base = slugFromName(name);
|
|
334
|
+
}
|
|
335
|
+
let slug = base;
|
|
336
|
+
for (let n = 2; all.some((h) => h.slug === slug); n++)
|
|
337
|
+
slug = `${base}-${n}`;
|
|
338
|
+
const created = await createHarness(ctx, { slug, name: name.slice(0, 255) });
|
|
339
|
+
write(`Created the draft solution ${created.name} (${created.slug}).`);
|
|
340
|
+
return { slug: created.slug, created: true };
|
|
341
|
+
}
|
|
192
342
|
function envYaml(name, harness) {
|
|
193
343
|
return [
|
|
194
344
|
`# Where \`cavelon apply --env ${name}\` goes. Never a token or a secret value.`,
|
|
195
|
-
"# tenant: <slug or id>
|
|
345
|
+
"# tenant: <name, slug or id> # default: the tenant in cavelon.yaml",
|
|
196
346
|
harness ? `harness: ${harness}` : "# harness: <slug> # created as a draft when it does not exist yet",
|
|
197
347
|
"# mode: overwrite # or replace",
|
|
198
348
|
"# runtime_bindings: # the package's runtime requirement key -> this tenant's resource id",
|
|
@@ -216,14 +366,14 @@ function importFileError(from, reason, hint) {
|
|
|
216
366
|
hint: hint ?? "Pass a package export: a JSON or YAML file with one key per section (manifest, harnesses, agents, …).",
|
|
217
367
|
});
|
|
218
368
|
}
|
|
219
|
-
async function readImportFile(
|
|
220
|
-
const file =
|
|
369
|
+
async function readImportFile(ctx, from) {
|
|
370
|
+
const file = await confinedPath(ctx, from, "The package file");
|
|
221
371
|
const stat = await fs.stat(file).catch(() => undefined);
|
|
222
372
|
if (!stat?.isFile())
|
|
223
373
|
throw usageError(`No file ${from}.`, "Pass the path of a package export (JSON or YAML) to --from.");
|
|
224
374
|
if (stat.size > MAX_PACKAGE_FILE_BYTES)
|
|
225
375
|
throw importFileError(from, `it is larger than ${MAX_PACKAGE_FILE_BYTES / 1024 / 1024} MB`);
|
|
226
|
-
const text = (await readTextFile(file)) ?? "";
|
|
376
|
+
const text = withoutBom((await readTextFile(file)) ?? "");
|
|
227
377
|
let value;
|
|
228
378
|
if (/\.json$/i.test(file)) {
|
|
229
379
|
try {
|
|
@@ -297,7 +447,7 @@ async function runInit(ctx, input) {
|
|
|
297
447
|
throw usageError("--from and --update do not go together.", "Run `cavelon init --from <file>` and `cavelon init --update` one after the other.");
|
|
298
448
|
if (boolOption(input, "force") && !from)
|
|
299
449
|
throw usageError("--force only applies to --from.");
|
|
300
|
-
const imported = from ? await readImportFile(ctx
|
|
450
|
+
const imported = from ? await readImportFile(ctx, from) : undefined;
|
|
301
451
|
if (update) {
|
|
302
452
|
if (!session.project)
|
|
303
453
|
throw usageError("No cavelon.yaml here or above.", "Run `cavelon init` first.");
|
|
@@ -319,6 +469,7 @@ async function runInit(ctx, input) {
|
|
|
319
469
|
return { root, actions: actions.filter((a) => !(a.action === "skipped" && /does not exist|no cavelon (block|entry)/.test(a.reason ?? ""))), next, imported: undefined };
|
|
320
470
|
}
|
|
321
471
|
const packageHarness = imported ? onlyHarnessSlug(imported) : undefined;
|
|
472
|
+
let chosenHarness;
|
|
322
473
|
const root = ctx.io.cwd;
|
|
323
474
|
const existing = await readTextFile(path.join(root, PROJECT_FILE));
|
|
324
475
|
if (existing !== undefined) {
|
|
@@ -327,35 +478,38 @@ async function runInit(ctx, input) {
|
|
|
327
478
|
else {
|
|
328
479
|
const url = requireInstance(session);
|
|
329
480
|
requireToken(session);
|
|
481
|
+
const tenant = await initTenant(ctx, session);
|
|
482
|
+
if (tenant?.id)
|
|
483
|
+
[session.tenant, session.tenantSource] = [tenant.id, session.tenantSource ?? "option"];
|
|
330
484
|
const contracts = await ctx.contracts();
|
|
331
485
|
const caps = await contracts.capabilities();
|
|
332
486
|
if (contracts.needsTenant) {
|
|
333
487
|
throw new CavelonError(ExitCode.usage, {
|
|
334
488
|
code: "tenant_required",
|
|
335
489
|
message: "A solution belongs to one tenant, and none is chosen.",
|
|
336
|
-
hint: "Pass --tenant <slug>, or run `cavelon use
|
|
490
|
+
hint: "Pass --tenant <name or slug>, or run `cavelon use` first to choose one.",
|
|
337
491
|
});
|
|
338
492
|
}
|
|
339
493
|
const schema = await contracts.packageSchema();
|
|
340
494
|
await contracts.errorCatalog().catch(() => null);
|
|
341
495
|
if (!schema)
|
|
342
496
|
ctx.warn("The instance does not publish its package schema; `validate` will have nothing to check against.");
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
const harness = stringOption(input, "harness") ?? packageHarness;
|
|
497
|
+
const decided = stringOption(input, "harness") ? await initHarness(ctx, stringOption(input, "harness")) : packageHarness ? { slug: packageHarness } : await initHarness(ctx, undefined);
|
|
498
|
+
chosenHarness = decided;
|
|
499
|
+
const harness = decided.slug;
|
|
500
|
+
if (decided.missing)
|
|
501
|
+
next.push(`Solution ${harness} is not on the instance yet: \`cavelon apply --env test\` creates it as a draft.`);
|
|
349
502
|
const values = { instance: url };
|
|
350
503
|
if (tenant)
|
|
351
|
-
values.tenant = tenant;
|
|
504
|
+
values.tenant = tenant.ref;
|
|
352
505
|
if (harness)
|
|
353
506
|
values.harness = harness;
|
|
354
507
|
const version = caps?.contracts?.package_versions?.current ?? schema?.["x-package-version"];
|
|
355
508
|
if (version)
|
|
356
509
|
values.package_version = version;
|
|
357
510
|
values.layout = defaultLayoutFor(schema);
|
|
358
|
-
|
|
511
|
+
const note = tenant && (tenant.name || tenant.id !== tenant.ref) ? commentText([tenant.name, tenant.id !== tenant.ref ? tenant.id : undefined].filter(Boolean).join(", ")) : undefined;
|
|
512
|
+
await writeFileAtomic(path.join(root, PROJECT_FILE), solutionYaml(values, note));
|
|
359
513
|
actions.push({ file: PROJECT_FILE, action: "created" });
|
|
360
514
|
}
|
|
361
515
|
const project = parseProject(path.join(root, PROJECT_FILE), (await readTextFile(path.join(root, PROJECT_FILE))));
|
|
@@ -388,14 +542,21 @@ async function runInit(ctx, input) {
|
|
|
388
542
|
result = await importPackage(ctx, project, from, imported, boolOption(input, "force"));
|
|
389
543
|
if (packageHarness && !project.harness && !stringOption(input, "harness"))
|
|
390
544
|
await setProjectKey(project, "harness", packageHarness);
|
|
391
|
-
next.unshift("Check it offline: cavelon validate", `Preview it on the instance: cavelon apply${harness ? " --env test" : " --harness <slug>"}`);
|
|
545
|
+
next.unshift("Check it offline: cavelon validate", `Preview it on the instance: cavelon apply${harness ? " --env test" : " --harness <name or slug>"}`);
|
|
392
546
|
}
|
|
393
547
|
else if (!(await hasPackageFiles(root, project.layout.package))) {
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
548
|
+
const choices = chosenHarness?.choices ?? [];
|
|
549
|
+
if (chosenHarness?.created || chosenHarness?.missing)
|
|
550
|
+
next.unshift("Write the package files in package/, then: cavelon validate");
|
|
551
|
+
else if (harness)
|
|
552
|
+
next.unshift(`Bring the solution into package/: cavelon pull`);
|
|
553
|
+
else if (choices.length) {
|
|
554
|
+
next.unshift("Bring one of this tenant's solutions into package/ (or write package files, then cavelon validate):", ...choices.slice(0, 10).map((h) => ` ${cavelonCommand("pull", "--harness", h.slug)}${h.name !== h.slug ? ` ${h.name}` : ""}`), ...(choices.length > 10 ? [` … and ${choices.length - 10} more (\`cavelon harness list\`)`] : []));
|
|
555
|
+
}
|
|
556
|
+
else
|
|
557
|
+
next.unshift("Bring an existing solution into package/: cavelon pull --harness <name or slug> (or write package files, then cavelon validate)");
|
|
397
558
|
}
|
|
398
|
-
return { root, actions, next, imported: result };
|
|
559
|
+
return { root, actions, next, imported: result, harness: chosenHarness };
|
|
399
560
|
}
|
|
400
561
|
export const init = {
|
|
401
562
|
name: "init",
|
|
@@ -411,26 +572,31 @@ export const init = {
|
|
|
411
572
|
idempotent: true,
|
|
412
573
|
mcpTool: "init",
|
|
413
574
|
options: {
|
|
414
|
-
harness: {
|
|
575
|
+
harness: {
|
|
576
|
+
type: "string",
|
|
577
|
+
value: "<harness>",
|
|
578
|
+
description: "The solution (harness) this folder holds, by name, slug or id; its slug goes into cavelon.yaml. Without it, init asks on a terminal.",
|
|
579
|
+
},
|
|
415
580
|
agents: {
|
|
416
581
|
type: "string",
|
|
417
582
|
value: "<list>",
|
|
418
583
|
multiple: true,
|
|
419
584
|
description: `Write the fallback for these agents: ${AGENTS.map((a) => a.name).join(", ")} or all (comma-separated).`,
|
|
420
585
|
},
|
|
421
|
-
hook: { type: "boolean", description: "Add a git pre-commit hook that runs `cavelon validate
|
|
586
|
+
hook: { type: "boolean", description: "Add a git pre-commit hook that runs `cavelon validate`; never in a hooks folder outside the repository." },
|
|
422
587
|
update: { type: "boolean", description: "Only bring the marked blocks and fallback files to this version." },
|
|
423
588
|
from: { type: "string", value: "<file>", description: "Write this package file (a JSON or YAML export) into package/ and tests/." },
|
|
424
589
|
force: { type: "boolean", description: "With --from: replace package files that hold something else." },
|
|
425
590
|
},
|
|
426
591
|
examples: [
|
|
427
|
-
"cavelon init
|
|
592
|
+
"cavelon init",
|
|
593
|
+
"cavelon init --instance https://cavelon.example.com --tenant \"Acme Support\" --harness \"Support FAQ\"",
|
|
428
594
|
"cavelon init --agents codex,cursor --hook",
|
|
429
595
|
"cavelon init --update",
|
|
430
596
|
"cavelon init --instance https://cavelon.example.com --tenant acme --from ./blueprint.json",
|
|
431
597
|
],
|
|
432
598
|
async run(ctx, input) {
|
|
433
|
-
const { root, actions, next, imported } = await runInit(ctx, input);
|
|
599
|
+
const { root, actions, next, imported, harness } = await runInit(ctx, input);
|
|
434
600
|
const changed = actions.filter((a) => a.action !== "unchanged");
|
|
435
601
|
const skipped = actions.filter((a) => a.action === "skipped");
|
|
436
602
|
for (const s of skipped)
|
|
@@ -447,6 +613,7 @@ export const init = {
|
|
|
447
613
|
lines.length ? lines.join("\n") : "Nothing to change.",
|
|
448
614
|
...(next.length ? ["", "Next:", ...next.map((n) => ` ${n}`)] : []),
|
|
449
615
|
].join("\n");
|
|
450
|
-
|
|
616
|
+
const choices = harness?.choices && !harness.slug ? { solutions: harness.choices } : {};
|
|
617
|
+
return { data: { solution: root, files: actions, ...(imported ? { imported } : {}), ...choices, next }, text };
|
|
451
618
|
},
|
|
452
619
|
};
|
|
@@ -349,7 +349,7 @@ async function pathParams(ctx, change, principal) {
|
|
|
349
349
|
}
|
|
350
350
|
const tenantId = (await ctx.client()).target.tenantId ?? principal?.tenant_id ?? undefined;
|
|
351
351
|
if (!tenantId)
|
|
352
|
-
throw usageError("Which tenant? Choose one with `cavelon use
|
|
352
|
+
throw usageError("Which tenant? Choose one with `cavelon use` (it lists your tenants) or --tenant.");
|
|
353
353
|
params[name] = [tenantId];
|
|
354
354
|
}
|
|
355
355
|
return params;
|
|
@@ -389,10 +389,10 @@ async function previousValue(ctx, published, target) {
|
|
|
389
389
|
if (target.flag)
|
|
390
390
|
return target.flag.enabled;
|
|
391
391
|
if (target.kind === "quota") {
|
|
392
|
+
if (target.quota)
|
|
393
|
+
return capValue(target.quota.value);
|
|
392
394
|
const row = await quotaSetting(ctx, published, target.key).catch(() => undefined);
|
|
393
|
-
|
|
394
|
-
return row.value;
|
|
395
|
-
return target.quota ? target.quota.value : undefined;
|
|
395
|
+
return row && (typeof row.value === "number" || row.value === null) ? row.value : undefined;
|
|
396
396
|
}
|
|
397
397
|
const limit = target.limit;
|
|
398
398
|
if (target.scope === "one_tenant")
|
|
@@ -401,11 +401,16 @@ async function previousValue(ctx, published, target) {
|
|
|
401
401
|
return limit.source === "tenant" ? undefined : limit.value;
|
|
402
402
|
return limit.value;
|
|
403
403
|
}
|
|
404
|
+
function capValue(value) {
|
|
405
|
+
return typeof value === "number" && value <= 0 ? null : value;
|
|
406
|
+
}
|
|
404
407
|
function noChange(target, previous, value, from) {
|
|
405
408
|
if (target.flag)
|
|
406
409
|
return previous === value ? `${target.key} is already ${from} (${target.flag.setting})` : undefined;
|
|
407
|
-
if (target.kind === "quota")
|
|
408
|
-
|
|
410
|
+
if (target.kind === "quota") {
|
|
411
|
+
const wanted = target.quota ? capValue(value) : value;
|
|
412
|
+
return previous !== undefined && sameValue(previous, wanted) ? `${target.key} is already ${from}` : undefined;
|
|
413
|
+
}
|
|
409
414
|
const limit = target.limit;
|
|
410
415
|
if (target.scope === "one_tenant") {
|
|
411
416
|
if (value === null && previous === null)
|
|
@@ -449,6 +454,10 @@ function answeredValue(target, data, sent) {
|
|
|
449
454
|
const own = changed.find((c) => c?.setting === target.limit?.setting);
|
|
450
455
|
return { value: own && "new" in own ? own.new : sent, changed };
|
|
451
456
|
}
|
|
457
|
+
function reportsChange(changes) {
|
|
458
|
+
const pairs = changes.filter((c) => typeof c === "object" && c !== null && "old" in c && "new" in c);
|
|
459
|
+
return pairs.length < changes.length || changes.length === 0 || pairs.some((c) => !sameValue(c.old, c.new));
|
|
460
|
+
}
|
|
452
461
|
function explicitTenant(session) {
|
|
453
462
|
return session.tenantSource === "option" && Boolean(session.tenant);
|
|
454
463
|
}
|
|
@@ -496,7 +505,7 @@ export const limitsSet = {
|
|
|
496
505
|
throw new CavelonError(ExitCode.usage, {
|
|
497
506
|
code: "tenant_required",
|
|
498
507
|
message: "Limits belong to a tenant, and none is chosen.",
|
|
499
|
-
hint: "Choose one with `cavelon use
|
|
508
|
+
hint: "Choose one with `cavelon use` (it lists your tenants) or pass --tenant; an operator's change reads the limits of any tenant and sends in Platform mode.",
|
|
500
509
|
});
|
|
501
510
|
}
|
|
502
511
|
if (!published.published) {
|
|
@@ -615,7 +624,7 @@ export const limitsSet = {
|
|
|
615
624
|
...(answered.source ? { source: answered.source } : {}),
|
|
616
625
|
...(answered.origin ? { origin: answered.origin } : {}),
|
|
617
626
|
changes: answered.changed,
|
|
618
|
-
changed:
|
|
627
|
+
changed: reportsChange(answered.changed),
|
|
619
628
|
sent: true,
|
|
620
629
|
},
|
|
621
630
|
text: `Changed ${key}: ${from} → ${now}${where}.`,
|
package/dist/commands/limits.js
CHANGED
|
@@ -56,13 +56,13 @@ export const limits = {
|
|
|
56
56
|
throw new CavelonError(ExitCode.usage, {
|
|
57
57
|
code: "tenant_required",
|
|
58
58
|
message: "Limits belong to a tenant, and none is chosen.",
|
|
59
|
-
hint: "Choose one with `cavelon use
|
|
59
|
+
hint: "Choose one with `cavelon use` (it lists your tenants) or pass --tenant <name or slug>.",
|
|
60
60
|
});
|
|
61
61
|
}
|
|
62
62
|
if (!published.published) {
|
|
63
63
|
ctx.warn("This instance does not publish its limits (it is older than the limits in /api/v1/meta/capabilities); none is assumed.");
|
|
64
64
|
return {
|
|
65
|
-
data: { published: false, groups: [], tenant_quotas: null, near: [], branch_concurrency: null },
|
|
65
|
+
data: { published: false, groups: [], tenant_quotas: null, quota_values: [], near: [], branch_concurrency: null },
|
|
66
66
|
text: "This instance does not publish its limits. Commands send as they are, and the instance answers for itself.",
|
|
67
67
|
};
|
|
68
68
|
}
|
package/dist/commands/loops.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { noteLines, runCapacityNote } from "../capacity.js";
|
|
2
2
|
import { boolOption, CURSOR_OPTION, intOption, LIMIT_OPTION, positional, stringOption, } from "../command.js";
|
|
3
3
|
import { CavelonError, ExitCode, usageError } from "../errors.js";
|
|
4
|
-
import { idempotencyKey, requireFeature, UUID_KEY_OPTION } from "../features.js";
|
|
4
|
+
import { idempotencyKey, requireFeature, UUID_KEY_OPTION, withRetryKey } from "../features.js";
|
|
5
5
|
import { clip, keyValues, moreHint, table } from "../format.js";
|
|
6
6
|
import { callStable } from "../invoke.js";
|
|
7
7
|
import { catalogEntry } from "../package-check.js";
|
|
@@ -179,6 +179,7 @@ export const loopStart = {
|
|
|
179
179
|
input: { type: "string", value: "<json|@file|->", description: "The run's payload: JSON, @file.json or - for stdin." },
|
|
180
180
|
wait: WAIT_OPTION,
|
|
181
181
|
timeout: TIMEOUT_OPTION,
|
|
182
|
+
"idempotency-key": UUID_KEY_OPTION,
|
|
182
183
|
},
|
|
183
184
|
examples: ["cavelon loop start counter", "cavelon loop start orders --input @orders-request.json --json"],
|
|
184
185
|
async run(ctx, input) {
|
|
@@ -188,13 +189,17 @@ export const loopStart = {
|
|
|
188
189
|
const payload = raw === undefined ? {} : await readBody(ctx, raw);
|
|
189
190
|
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
190
191
|
throw usageError("--input must be a JSON object.");
|
|
192
|
+
const key = idempotencyKey(input);
|
|
191
193
|
const run = await callStable(ctx, "POST", "/api/v1/triggers/{trigger_id}/run", "starting triggers", {
|
|
192
194
|
params: { trigger_id: [trigger.id] },
|
|
195
|
+
headers: { "Idempotency-Key": key },
|
|
193
196
|
body: { payload },
|
|
197
|
+
}).catch((error) => {
|
|
198
|
+
throw withRetryKey(error, key);
|
|
194
199
|
});
|
|
195
200
|
if (!trigger.is_active)
|
|
196
201
|
ctx.warn(`Trigger "${trigger.slug}" is not active: its schedule and webhook start no runs, though this manual start did.`);
|
|
197
|
-
const started = { trigger: { id: trigger.id, slug: trigger.slug }, ...runSummary(run) };
|
|
202
|
+
const started = { trigger: { id: trigger.id, slug: trigger.slug }, ...runSummary(run), idempotency_key: key };
|
|
198
203
|
if (boolOption(input, "wait") && ctx.mode === "cli" && run.operation_id) {
|
|
199
204
|
const waited = await waitAndReport(ctx, [run.operation_id], timeoutMs(ctx, stringOption(input, "timeout")));
|
|
200
205
|
const text = `Started run ${run.id} of ${trigger.slug}.\n${waited.text}`;
|
|
@@ -601,13 +606,14 @@ function controlCommand(action) {
|
|
|
601
606
|
let receipt;
|
|
602
607
|
try {
|
|
603
608
|
receipt = await callStable(ctx, "POST", `/api/v1/triggers/runs/{run_id}/loops/{loop_id}/${action}`, `${action} loops`, {
|
|
604
|
-
params: { run_id: [loop.owner_run_id], loop_id: [loop.id]
|
|
609
|
+
params: { run_id: [loop.owner_run_id], loop_id: [loop.id] },
|
|
610
|
+
headers: { "Idempotency-Key": key },
|
|
605
611
|
body: { expected_version: loop.version, ...(reason ? { reviewed_reason: reason } : {}) },
|
|
606
612
|
});
|
|
607
613
|
}
|
|
608
614
|
catch (error) {
|
|
609
|
-
if (pausing || !(error instanceof CavelonError))
|
|
610
|
-
throw error;
|
|
615
|
+
if (pausing || !(error instanceof CavelonError) || error.exitCode === ExitCode.server)
|
|
616
|
+
throw withRetryKey(error, key);
|
|
611
617
|
throw await resumeRefused(ctx, error, loop, reason);
|
|
612
618
|
}
|
|
613
619
|
const text = pausing
|
|
@@ -685,7 +691,7 @@ async function resolveApiKey(ctx, ref) {
|
|
|
685
691
|
const client = await ctx.client();
|
|
686
692
|
const tenantId = client.target.tenantId ?? (await readPrincipal(client))?.tenant_id ?? undefined;
|
|
687
693
|
if (!tenantId)
|
|
688
|
-
throw usageError("Which tenant's API keys? Choose one with `cavelon use
|
|
694
|
+
throw usageError("Which tenant's API keys? Choose one with `cavelon use` (it lists your tenants) or --tenant, or pass the key's id.");
|
|
689
695
|
const keys = [];
|
|
690
696
|
for (let offset = 0; offset < 1000; offset += 100) {
|
|
691
697
|
const page = await callStable(ctx, "GET", "/api/v1/tenants/{tenant_id}/api-keys", "API keys", {
|
|
@@ -3,14 +3,16 @@ import { promises as fs } from "node:fs";
|
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { boolOption, CURSOR_OPTION, intOption, LIMIT_OPTION, listOption, positional, stringOption, } from "../command.js";
|
|
5
5
|
import { CavelonError, ExitCode, usageError } from "../errors.js";
|
|
6
|
-
import {
|
|
6
|
+
import { confinedPath } from "../paths.js";
|
|
7
|
+
import { idempotencyKey, instanceModes, requireFeature, stableKey, UUID_KEY_OPTION, withRetryKey } from "../features.js";
|
|
7
8
|
import { clip, keyValues, moreHint, table } from "../format.js";
|
|
9
|
+
import { bodyBytes } from "../http.js";
|
|
8
10
|
import { buildRequest, callStable, workflowOperation } from "../invoke.js";
|
|
9
11
|
import { isUuid } from "../session.js";
|
|
10
12
|
import { cavelonCommand } from "../shell.js";
|
|
11
13
|
import { archiveFrom } from "../tar.js";
|
|
12
14
|
import { TIMEOUT_OPTION, timeoutMs, waitAndReport } from "./async.js";
|
|
13
|
-
import { resolveHarnessId } from "
|
|
15
|
+
import { resolveHarnessId } from "../harness-ref.js";
|
|
14
16
|
const MODES = {
|
|
15
17
|
isolated_container: {
|
|
16
18
|
offers: ["archive", "receipt"],
|
|
@@ -25,7 +27,7 @@ const WAIT_OPTION = { type: "boolean", description: "Wait for the job to finish
|
|
|
25
27
|
const HARNESS_OPTION = {
|
|
26
28
|
type: "string",
|
|
27
29
|
value: "<harness>",
|
|
28
|
-
description: "The solution the Sandbox is read for (default: cavelon.yaml's, or the Sandbox's only allowed one).",
|
|
30
|
+
description: "The solution the Sandbox is read for, by name, slug or id (default: cavelon.yaml's, or the Sandbox's only allowed one).",
|
|
29
31
|
};
|
|
30
32
|
const REVISION_OPTION = {
|
|
31
33
|
type: "string",
|
|
@@ -170,7 +172,8 @@ export const sandboxValidate = {
|
|
|
170
172
|
async run(ctx, input) {
|
|
171
173
|
const sandbox = await resolveSandbox(ctx, positional(input, "sandbox"));
|
|
172
174
|
const result = await callStable(ctx, "POST", "/api/v1/sandboxes/{sandbox_id}/validate", "validating Sandboxes", {
|
|
173
|
-
params: { sandbox_id: [sandbox.id]
|
|
175
|
+
params: { sandbox_id: [sandbox.id] },
|
|
176
|
+
headers: { "If-Match": `"${sandbox.config_version}"` },
|
|
174
177
|
timeoutMs: 90_000,
|
|
175
178
|
});
|
|
176
179
|
const checks = result.readiness?.checks ?? [];
|
|
@@ -386,9 +389,13 @@ export const sandboxRefresh = {
|
|
|
386
389
|
async run(ctx, input) {
|
|
387
390
|
const sandbox = await resolveSandbox(ctx, positional(input, "sandbox"));
|
|
388
391
|
requireOffer(ctx, sandbox, "refresh", "sandbox refresh");
|
|
392
|
+
const key = idempotencyKey(input);
|
|
389
393
|
const result = await callStable(ctx, "POST", "/api/v1/sandboxes/{sandbox_id}/refresh-workspace", "refreshing Sandboxes", {
|
|
390
|
-
params: { sandbox_id: [sandbox.id]
|
|
394
|
+
params: { sandbox_id: [sandbox.id] },
|
|
395
|
+
headers: { "Idempotency-Key": key, "If-Match": `"${sandbox.config_version}"` },
|
|
391
396
|
timeoutMs: 90_000,
|
|
397
|
+
}).catch((error) => {
|
|
398
|
+
throw withRetryKey(error, key);
|
|
392
399
|
});
|
|
393
400
|
return {
|
|
394
401
|
data: { ...sandboxView(result), previous_revision: sandbox.observed_revision },
|
|
@@ -472,7 +479,7 @@ export const sandboxSeed = {
|
|
|
472
479
|
async run(ctx, input) {
|
|
473
480
|
const sandbox = await resolveSandbox(ctx, positional(input, "sandbox"));
|
|
474
481
|
requireOffer(ctx, sandbox, "archive", "sandbox seed");
|
|
475
|
-
const source =
|
|
482
|
+
const source = await confinedPath(ctx, positional(input, "source"), "The source");
|
|
476
483
|
const archive = await archiveFrom(source, await maxArchiveBytes(ctx));
|
|
477
484
|
const harness = await harnessFor(ctx, input, sandbox);
|
|
478
485
|
const revision = await currentRevision(ctx, input, sandbox, harness);
|
|
@@ -499,7 +506,8 @@ export const sandboxSeed = {
|
|
|
499
506
|
}
|
|
500
507
|
const key = stringOption(input, "idempotency-key") !== undefined ? idempotencyKey(input) : stableKey(`seed:${sandbox.id}:${revision}:${archive.sha256}`);
|
|
501
508
|
let job = await callStable(ctx, "POST", "/api/v1/sandboxes/{sandbox_id}/artifact-jobs", "archive jobs", {
|
|
502
|
-
params: { sandbox_id: [sandbox.id]
|
|
509
|
+
params: { sandbox_id: [sandbox.id] },
|
|
510
|
+
headers: { "Idempotency-Key": key },
|
|
503
511
|
body: { harness_id: harness, direction: "import", expected_workspace_revision: revision, sha256: archive.sha256, size_bytes: archive.bytes.length },
|
|
504
512
|
});
|
|
505
513
|
const until = Date.now() + UPLOAD_READY_MS;
|
|
@@ -535,12 +543,9 @@ async function upload(ctx, sandboxId, jobId, bytes) {
|
|
|
535
543
|
const client = await ctx.client();
|
|
536
544
|
const { op } = await workflowOperation(ctx, "PUT", `${JOB_ROUTE}/content`, "archive uploads");
|
|
537
545
|
const { path: target } = buildRequest(op, { params: { sandbox_id: [sandboxId], job_id: [jobId] }, bytes });
|
|
538
|
-
const
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
signal: AbortSignal.timeout(Number(ctx.io.env.CAVELON_HTTP_TIMEOUT_MS) || 120_000),
|
|
542
|
-
});
|
|
543
|
-
const text = await response.text();
|
|
546
|
+
const signal = AbortSignal.timeout(Number(ctx.io.env.CAVELON_HTTP_TIMEOUT_MS) || 120_000);
|
|
547
|
+
const response = await client.fetchRaw("PUT", target, { bytes, headers: { "Content-Type": "application/octet-stream" }, signal });
|
|
548
|
+
const text = new TextDecoder().decode(await bodyBytes(response, client.resolve(target), signal));
|
|
544
549
|
let data = text;
|
|
545
550
|
try {
|
|
546
551
|
data = JSON.parse(text);
|
|
@@ -554,15 +559,13 @@ async function upload(ctx, sandboxId, jobId, bytes) {
|
|
|
554
559
|
async function download(ctx, sandbox, job, out) {
|
|
555
560
|
if (!isUuid(job.id))
|
|
556
561
|
throw new CavelonError(ExitCode.failure, { code: "invalid_job_id", message: `The instance returned an unexpected job id.` });
|
|
557
|
-
const file =
|
|
562
|
+
const file = await confinedPath(ctx, out ?? `sandbox-${job.id}.tar`, "The archive file");
|
|
558
563
|
const client = await ctx.client();
|
|
559
564
|
const { op } = await workflowOperation(ctx, "GET", `${JOB_ROUTE}/content`, "archive downloads");
|
|
560
565
|
const { path: target } = buildRequest(op, { params: { sandbox_id: [sandbox.id], job_id: [job.id] } });
|
|
561
|
-
const
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
});
|
|
565
|
-
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
566
|
+
const signal = AbortSignal.timeout(Number(ctx.io.env.CAVELON_HTTP_TIMEOUT_MS) || 120_000);
|
|
567
|
+
const response = await client.fetchRaw("GET", target, { accept: "application/x-tar", signal });
|
|
568
|
+
const bytes = await bodyBytes(response, client.resolve(target), signal);
|
|
566
569
|
if (!response.ok) {
|
|
567
570
|
const text = new TextDecoder().decode(bytes);
|
|
568
571
|
let data = text;
|
|
@@ -633,9 +636,13 @@ export const artifactsExport = {
|
|
|
633
636
|
const harness = await harnessFor(ctx, input, sandbox);
|
|
634
637
|
const revision = await currentRevision(ctx, input, sandbox, harness);
|
|
635
638
|
const paths = listOption(input, "path");
|
|
639
|
+
const key = idempotencyKey(input);
|
|
636
640
|
job = await callStable(ctx, "POST", "/api/v1/sandboxes/{sandbox_id}/artifact-jobs", "archive jobs", {
|
|
637
|
-
params: { sandbox_id: [sandbox.id]
|
|
641
|
+
params: { sandbox_id: [sandbox.id] },
|
|
642
|
+
headers: { "Idempotency-Key": key },
|
|
638
643
|
body: { harness_id: harness, direction: "export", expected_workspace_revision: revision, ...(paths.length ? { paths } : {}) },
|
|
644
|
+
}).catch((error) => {
|
|
645
|
+
throw withRetryKey(error, key);
|
|
639
646
|
});
|
|
640
647
|
}
|
|
641
648
|
const later = cavelonCommand("artifacts", "export", sandbox.name, "--job", job.id, ...(out ? ["--out", out] : []));
|