@cavelon/cli 0.0.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +713 -3
  2. package/dist/LICENSE +201 -0
  3. package/dist/agents.js +107 -0
  4. package/dist/branches.js +61 -0
  5. package/dist/capacity.js +162 -0
  6. package/dist/cli.js +4 -0
  7. package/dist/command.js +62 -0
  8. package/dist/commands/api.js +313 -0
  9. package/dist/commands/async.js +207 -0
  10. package/dist/commands/docs.js +158 -0
  11. package/dist/commands/index.js +112 -0
  12. package/dist/commands/init.js +481 -0
  13. package/dist/commands/inventory.js +56 -0
  14. package/dist/commands/limits-set.js +633 -0
  15. package/dist/commands/limits.js +156 -0
  16. package/dist/commands/loops.js +798 -0
  17. package/dist/commands/models.js +197 -0
  18. package/dist/commands/sandboxes.js +674 -0
  19. package/dist/commands/session.js +480 -0
  20. package/dist/commands/solution.js +830 -0
  21. package/dist/commands/tenants.js +266 -0
  22. package/dist/commands/values.js +386 -0
  23. package/dist/commands/work.js +761 -0
  24. package/dist/context.js +60 -0
  25. package/dist/contracts.js +234 -0
  26. package/dist/credentials.js +134 -0
  27. package/dist/errors.js +64 -0
  28. package/dist/features.js +52 -0
  29. package/dist/format.js +36 -0
  30. package/dist/fsutil.js +43 -0
  31. package/dist/git.js +41 -0
  32. package/dist/http.js +304 -0
  33. package/dist/invoke.js +165 -0
  34. package/dist/io.js +49 -0
  35. package/dist/limits.js +307 -0
  36. package/dist/local-state.js +78 -0
  37. package/dist/main.js +227 -0
  38. package/dist/markers.js +113 -0
  39. package/dist/mcp.js +137 -0
  40. package/dist/openapi.js +233 -0
  41. package/dist/operations.js +107 -0
  42. package/dist/package-check.js +342 -0
  43. package/dist/package-files.js +394 -0
  44. package/dist/pair-order.js +39 -0
  45. package/dist/paths.js +77 -0
  46. package/dist/principal.js +33 -0
  47. package/dist/project.js +157 -0
  48. package/dist/prompt.js +34 -0
  49. package/dist/results.js +104 -0
  50. package/dist/session.js +190 -0
  51. package/dist/shell.js +41 -0
  52. package/dist/skills/cavelon-authoring/SKILL.md +224 -0
  53. package/dist/skills/cavelon-long-running/SKILL.md +185 -0
  54. package/dist/skills/cavelon-loop/SKILL.md +159 -0
  55. package/dist/skills/cavelon-testing/SKILL.md +97 -0
  56. package/dist/sse.js +44 -0
  57. package/dist/tar.js +172 -0
  58. package/dist/user-config.js +36 -0
  59. package/dist/version.js +17 -0
  60. package/dist/zip.js +132 -0
  61. package/package.json +40 -4
@@ -0,0 +1,60 @@
1
+ import { Contracts } from "./contracts.js";
2
+ import { ApiClient } from "./http.js";
3
+ import { colorEnabled, styleFor } from "./io.js";
4
+ import { requireInstance, requireToken, resolveSession, resolveTenantId } from "./session.js";
5
+ import { detectShell, useShell } from "./shell.js";
6
+ export function createContext(io, globals, mode = "cli") {
7
+ const warnings = [];
8
+ useShell(detectShell(io.env));
9
+ let sessionPromise;
10
+ let clientPromise;
11
+ let contractsPromise;
12
+ const ctx = {
13
+ io,
14
+ json: globals.json,
15
+ style: styleFor(colorEnabled(io, globals.json)),
16
+ globals,
17
+ mode,
18
+ warnings,
19
+ warn(message) {
20
+ if (!warnings.includes(message))
21
+ warnings.push(message);
22
+ },
23
+ session() {
24
+ sessionPromise ??= resolveSession(io.env, io.cwd, globals);
25
+ return sessionPromise;
26
+ },
27
+ async client(options = {}) {
28
+ if (options.tenant === false) {
29
+ const session = await ctx.session();
30
+ return new ApiClient({ url: requireInstance(session), token: requireToken(session) }, io.env);
31
+ }
32
+ clientPromise ??= (async () => {
33
+ const session = await ctx.session();
34
+ const client = new ApiClient({ url: requireInstance(session), token: requireToken(session) }, io.env);
35
+ client.target.tenantId = await resolveTenantId(io.env, session, client);
36
+ return client;
37
+ })();
38
+ return clientPromise;
39
+ },
40
+ async optionalClient() {
41
+ const session = await ctx.session();
42
+ if (session.token)
43
+ return ctx.client();
44
+ return new ApiClient({ url: requireInstance(session) }, io.env);
45
+ },
46
+ contracts() {
47
+ contractsPromise ??= (async () => new Contracts(await ctx.optionalClient(), io.env, io.now))();
48
+ return contractsPromise;
49
+ },
50
+ };
51
+ return ctx;
52
+ }
53
+ export function withWarnings(data, warnings) {
54
+ const own = Array.isArray(data.warnings) ? data.warnings : [];
55
+ const messageOf = (entry) => (entry && typeof entry === "object" ? entry.message : entry);
56
+ const seen = new Set(own.map(messageOf));
57
+ const objects = own.some((entry) => entry && typeof entry === "object");
58
+ const added = warnings.filter((w) => !seen.has(w)).map((message) => (objects ? { code: null, message } : message));
59
+ return { ...data, warnings: [...own, ...added] };
60
+ }
@@ -0,0 +1,234 @@
1
+ import { createHash } from "node:crypto";
2
+ import path from "node:path";
3
+ import { CavelonError, ExitCode } from "./errors.js";
4
+ import { NOT_HERE } from "./http.js";
5
+ import { cacheDir, instanceKey } from "./paths.js";
6
+ import { readJsonFile, readTextFile, writeFileAtomic } from "./fsutil.js";
7
+ import { SUPPORTED_CONTRACTS } from "./version.js";
8
+ const NOT_MODIFIED = Symbol("not modified");
9
+ const RELEASE_TTL_SECONDS = 3600;
10
+ const DEVELOPMENT_TTL_SECONDS = 60;
11
+ const OPENAPI_PATHS = ["/openapi.json", "/api/v1/openapi.json"];
12
+ export class Contracts {
13
+ client;
14
+ env;
15
+ now;
16
+ caps;
17
+ live = false;
18
+ versionValue;
19
+ needsTenant = false;
20
+ constructor(client, env, now) {
21
+ this.client = client;
22
+ this.env = env;
23
+ this.now = now;
24
+ }
25
+ get root() {
26
+ return path.join(cacheDir(this.env), instanceKey(this.client.url));
27
+ }
28
+ ttlSeconds(version) {
29
+ const raw = this.env.CAVELON_CONTRACT_TTL_SECONDS;
30
+ const seconds = Number(raw);
31
+ if (raw !== undefined && raw !== "" && Number.isFinite(seconds) && seconds >= 0)
32
+ return seconds;
33
+ return Contracts.isDevelopment(version) ? DEVELOPMENT_TTL_SECONDS : RELEASE_TTL_SECONDS;
34
+ }
35
+ static isDevelopment(version) {
36
+ return version === "unknown" || /dev|snapshot|local/i.test(version);
37
+ }
38
+ versionDir(version) {
39
+ return path.join(this.root, version.replace(/[^A-Za-z0-9._-]+/g, "_"));
40
+ }
41
+ fresh(fetchedAt, version) {
42
+ if (!fetchedAt)
43
+ return false;
44
+ return this.now().getTime() - new Date(fetchedAt).getTime() < this.ttlSeconds(version) * 1000;
45
+ }
46
+ async capabilities(options = {}) {
47
+ if (this.caps !== undefined && !options.refresh)
48
+ return this.caps;
49
+ const state = await readJsonFile(path.join(this.root, "state.json"));
50
+ if (!options.refresh && state && this.fresh(state.checked_at, state.version)) {
51
+ const cached = await readJsonFile(path.join(this.versionDir(state.version), "capabilities.json"));
52
+ if (cached) {
53
+ this.caps = cached;
54
+ this.versionValue = state.version;
55
+ return cached;
56
+ }
57
+ }
58
+ const response = await this.client.get("/api/v1/meta/capabilities", { allow: [400, 404] });
59
+ this.live = true;
60
+ if (response.status === 400) {
61
+ this.needsTenant = true;
62
+ this.caps = null;
63
+ this.versionValue = state?.version ?? "unknown";
64
+ return null;
65
+ }
66
+ this.needsTenant = false;
67
+ const now = this.now().toISOString();
68
+ if (response.status === 404 || !response.data?.instance) {
69
+ this.caps = null;
70
+ this.versionValue = "unknown";
71
+ }
72
+ else {
73
+ this.caps = response.data;
74
+ this.versionValue = response.data.instance.version || "unknown";
75
+ await writeFileAtomic(path.join(this.versionDir(this.versionValue), "capabilities.json"), JSON.stringify(response.data, null, 2));
76
+ }
77
+ await writeFileAtomic(path.join(this.root, "state.json"), JSON.stringify({ version: this.versionValue, checked_at: now }, null, 2));
78
+ return this.caps;
79
+ }
80
+ async liveCapabilities() {
81
+ if (this.live && this.caps !== undefined)
82
+ return this.caps;
83
+ return this.capabilities({ refresh: true });
84
+ }
85
+ async version() {
86
+ if (this.versionValue === undefined)
87
+ await this.capabilities();
88
+ return this.versionValue ?? "unknown";
89
+ }
90
+ async cached(file, load, parse, options = {}) {
91
+ const version = await this.version();
92
+ const target = path.join(this.versionDir(version), file);
93
+ const metaFile = path.join(this.versionDir(version), `${file}.meta.json`);
94
+ const text = await readTextFile(target);
95
+ const meta = await readJsonFile(metaFile);
96
+ let cached;
97
+ if (text !== undefined) {
98
+ try {
99
+ cached = { value: parse(text) };
100
+ }
101
+ catch {
102
+ }
103
+ }
104
+ if (cached && !options.refresh && (!Contracts.isDevelopment(version) || this.fresh(meta?.fetched_at, version)))
105
+ return cached.value;
106
+ const loaded = await load(cached ? meta?.etag : undefined);
107
+ const fetchedAt = this.now().toISOString();
108
+ if (loaded === NOT_MODIFIED) {
109
+ if (!cached)
110
+ throw new Error(`${file}: the instance answered 304 Not Modified without being sent an ETag.`);
111
+ await writeFileAtomic(metaFile, JSON.stringify({ ...meta, fetched_at: fetchedAt }));
112
+ return cached.value;
113
+ }
114
+ await writeFileAtomic(target, loaded.serialized);
115
+ await writeFileAtomic(metaFile, JSON.stringify({ fetched_at: fetchedAt, ...(loaded.etag ? { etag: loaded.etag } : {}) }));
116
+ return loaded.value;
117
+ }
118
+ async getJson(route, etag, options = {}) {
119
+ const response = await this.client.get(route, {
120
+ query: options.query,
121
+ timeoutMs: options.timeoutMs,
122
+ allow: [...(options.allow ?? []), ...(etag ? [304] : [])],
123
+ headers: etag ? { "If-None-Match": etag } : undefined,
124
+ });
125
+ if (etag && response.status === 304)
126
+ return NOT_MODIFIED;
127
+ if (response.status < 200 || response.status >= 300)
128
+ return undefined;
129
+ return { value: response.data, serialized: response.text, etag: response.headers.get("etag") ?? undefined };
130
+ }
131
+ async getRequired(route, etag, query) {
132
+ const loaded = await this.getJson(route, etag, { query });
133
+ if (!loaded)
134
+ throw new Error(`${route} answered neither a body nor an error.`);
135
+ return loaded;
136
+ }
137
+ async openapi(options = {}) {
138
+ return this.cached("openapi.json", async (etag) => {
139
+ for (const candidate of OPENAPI_PATHS) {
140
+ const loaded = await this.getJson(candidate, etag, { allow: NOT_HERE, timeoutMs: 120_000 });
141
+ if (loaded === NOT_MODIFIED)
142
+ return loaded;
143
+ if (loaded?.value && typeof loaded.value === "object" && "paths" in loaded.value)
144
+ return loaded;
145
+ }
146
+ throw new CavelonError(ExitCode.failure, {
147
+ code: "openapi_unavailable",
148
+ message: `${this.client.url} does not serve its OpenAPI at ${OPENAPI_PATHS.join(" or ")}.`,
149
+ hint: "`cavelon api` needs the instance's OpenAPI; ask the instance's operator to route it.",
150
+ });
151
+ }, (text) => JSON.parse(text), options);
152
+ }
153
+ async errorCatalog(options = {}) {
154
+ try {
155
+ return await this.cached("error-catalog.json", (etag) => this.getRequired("/api/v1/meta/error-catalog", etag), (text) => JSON.parse(text), options);
156
+ }
157
+ catch (error) {
158
+ if (error instanceof CavelonError && error.status === 404)
159
+ return null;
160
+ throw error;
161
+ }
162
+ }
163
+ async packageSchema(version, options = {}) {
164
+ const wanted = version ?? (await this.capabilities())?.contracts?.package_versions?.current;
165
+ const file = Contracts.packageSchemaFile(wanted ?? "current");
166
+ try {
167
+ return await this.cached(file, (etag) => this.getRequired("/api/v1/meta/package-schema", etag, { version: wanted }), (text) => JSON.parse(text), options);
168
+ }
169
+ catch (error) {
170
+ if (error instanceof CavelonError && error.status === 404) {
171
+ if (error.message.includes("package_version_unsupported") || error.code === "package_version_unsupported") {
172
+ throw new CavelonError(ExitCode.validation, {
173
+ code: "package_version_unsupported",
174
+ message: `${this.client.url} does not accept package version ${wanted}.`,
175
+ hint: "Read contracts.package_versions.accepted from `cavelon status --json`, or pull the package again.",
176
+ });
177
+ }
178
+ return null;
179
+ }
180
+ throw error;
181
+ }
182
+ }
183
+ async cachedOnly(file) {
184
+ const state = await readJsonFile(path.join(this.root, "state.json"));
185
+ if (!state)
186
+ return undefined;
187
+ const target = path.join(this.versionDir(state.version), file);
188
+ const text = await readTextFile(target);
189
+ if (text === undefined)
190
+ return undefined;
191
+ let value;
192
+ try {
193
+ value = JSON.parse(text);
194
+ }
195
+ catch {
196
+ return undefined;
197
+ }
198
+ const meta = file === "capabilities.json" ? { fetched_at: state.checked_at } : await readJsonFile(`${target}.meta.json`);
199
+ return {
200
+ value,
201
+ version: state.version,
202
+ fetched_at: meta?.fetched_at ?? null,
203
+ etag: meta?.etag ?? null,
204
+ sha256: createHash("sha256").update(text).digest("hex").slice(0, 12),
205
+ stale: Contracts.isDevelopment(state.version) && !this.fresh(meta?.fetched_at, state.version),
206
+ };
207
+ }
208
+ static packageSchemaFile(version) {
209
+ return `package-schema-${version.replace(/[^A-Za-z0-9._-]+/g, "_")}.json`;
210
+ }
211
+ async text(file, load, options = {}) {
212
+ return this.cached(file, async () => {
213
+ const text = await load();
214
+ return { value: text, serialized: text };
215
+ }, (text) => text, options);
216
+ }
217
+ }
218
+ export function compareContracts(caps) {
219
+ if (!caps) {
220
+ return ["The instance does not publish /api/v1/meta/capabilities; the kit cannot check that it understands this instance's contracts."];
221
+ }
222
+ const warnings = [];
223
+ const api = caps.contracts?.api_version;
224
+ if (api && !SUPPORTED_CONTRACTS.api_versions.includes(api)) {
225
+ warnings.push(`The instance speaks API ${api}; this cavelon understands ${SUPPORTED_CONTRACTS.api_versions.join(", ")}. Update cavelon.`);
226
+ }
227
+ const pkg = caps.contracts?.package_versions;
228
+ if (pkg?.current && !SUPPORTED_CONTRACTS.package_versions.includes(pkg.current)) {
229
+ const overlap = pkg.accepted?.filter((v) => SUPPORTED_CONTRACTS.package_versions.includes(v)) ?? [];
230
+ warnings.push(`The instance writes package format ${pkg.current}; this cavelon understands ${SUPPORTED_CONTRACTS.package_versions.join(", ")}` +
231
+ (overlap.length ? ` (the instance still accepts ${overlap.join(", ")}).` : ". Update cavelon."));
232
+ }
233
+ return warnings;
234
+ }
@@ -0,0 +1,134 @@
1
+ import path from "node:path";
2
+ import { promises as fs } from "node:fs";
3
+ import { configDir } from "./paths.js";
4
+ import { readJsonFile, writeFileAtomic } from "./fsutil.js";
5
+ const SERVICE = "cavelon";
6
+ export class KeyringStore {
7
+ entry;
8
+ kind = "keyring";
9
+ constructor(entry) {
10
+ this.entry = entry;
11
+ }
12
+ async get(url) {
13
+ return this.entry(SERVICE, url).getPassword() ?? undefined;
14
+ }
15
+ async set(url, token) {
16
+ this.entry(SERVICE, url).setPassword(token);
17
+ if (this.entry(SERVICE, url).getPassword() !== token)
18
+ throw new Error("the credential store did not keep the token");
19
+ }
20
+ async delete(url) {
21
+ try {
22
+ return this.entry(SERVICE, url).deletePassword() !== false;
23
+ }
24
+ catch {
25
+ return false;
26
+ }
27
+ }
28
+ }
29
+ export class FileStore {
30
+ env;
31
+ kind = "file";
32
+ constructor(env) {
33
+ this.env = env;
34
+ }
35
+ get file() {
36
+ return path.join(configDir(this.env), "credentials.json");
37
+ }
38
+ async read() {
39
+ const raw = await readJsonFile(this.file);
40
+ return { tokens: raw?.tokens ?? {} };
41
+ }
42
+ async write(content) {
43
+ if (Object.keys(content.tokens).length === 0) {
44
+ await fs.rm(this.file, { force: true });
45
+ return;
46
+ }
47
+ await writeFileAtomic(this.file, JSON.stringify(content, null, 2) + "\n", 0o600, 0o700);
48
+ }
49
+ async get(url) {
50
+ return (await this.read()).tokens[url];
51
+ }
52
+ async set(url, token) {
53
+ const content = await this.read();
54
+ content.tokens[url] = token;
55
+ await this.write(content);
56
+ }
57
+ async delete(url) {
58
+ const content = await this.read();
59
+ if (!(url in content.tokens))
60
+ return false;
61
+ delete content.tokens[url];
62
+ await this.write(content);
63
+ return true;
64
+ }
65
+ }
66
+ let keyringFactory;
67
+ async function loadKeyring() {
68
+ if (keyringFactory !== undefined)
69
+ return keyringFactory;
70
+ try {
71
+ const mod = (await import("@napi-rs/keyring"));
72
+ keyringFactory = (service, account) => new mod.Entry(service, account);
73
+ }
74
+ catch {
75
+ keyringFactory = null;
76
+ }
77
+ return keyringFactory;
78
+ }
79
+ export function setKeyringFactoryForTests(factory) {
80
+ keyringFactory = factory;
81
+ }
82
+ export async function credentialStores(env) {
83
+ const file = new FileStore(env);
84
+ if (env.CAVELON_CREDENTIAL_STORE === "file")
85
+ return [file];
86
+ const factory = await loadKeyring();
87
+ return factory ? [new KeyringStore(factory), file] : [file];
88
+ }
89
+ export async function storeFor(env, kind) {
90
+ const stores = await credentialStores(env);
91
+ if (!kind)
92
+ return stores;
93
+ const preferred = stores.filter((s) => s.kind === kind);
94
+ return [...preferred, ...stores.filter((s) => s.kind !== kind)];
95
+ }
96
+ export async function saveToken(env, url, token) {
97
+ const errors = [];
98
+ for (const store of await credentialStores(env)) {
99
+ try {
100
+ await store.set(url, token);
101
+ for (const other of await credentialStores(env))
102
+ if (other.kind !== store.kind)
103
+ await other.delete(url);
104
+ return store;
105
+ }
106
+ catch (error) {
107
+ errors.push(`${store.kind}: ${error instanceof Error ? error.message : String(error)}`);
108
+ }
109
+ }
110
+ throw new Error(`No credential store kept the token (${errors.join("; ")})`);
111
+ }
112
+ export async function readToken(env, url, preferred) {
113
+ for (const store of await storeFor(env, preferred)) {
114
+ try {
115
+ const token = await store.get(url);
116
+ if (token)
117
+ return { token, store: store.kind };
118
+ }
119
+ catch {
120
+ }
121
+ }
122
+ return undefined;
123
+ }
124
+ export async function deleteToken(env, url) {
125
+ let deleted = false;
126
+ for (const store of await credentialStores(env)) {
127
+ try {
128
+ deleted = (await store.delete(url)) || deleted;
129
+ }
130
+ catch {
131
+ }
132
+ }
133
+ return deleted;
134
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,64 @@
1
+ export const ExitCode = {
2
+ ok: 0,
3
+ failure: 1,
4
+ usage: 2,
5
+ validation: 3,
6
+ conflict: 4,
7
+ needsAction: 5,
8
+ timeout: 6,
9
+ unauthorized: 7,
10
+ server: 8,
11
+ };
12
+ export class CavelonError extends Error {
13
+ exitCode;
14
+ code;
15
+ hint;
16
+ docs;
17
+ status;
18
+ details;
19
+ blockers;
20
+ constructor(exitCode, details) {
21
+ super(details.message);
22
+ this.name = "CavelonError";
23
+ this.exitCode = exitCode;
24
+ this.code = details.code;
25
+ this.hint = details.hint;
26
+ this.docs = details.docs;
27
+ this.status = details.status;
28
+ this.details = details.details;
29
+ this.blockers = details.blockers;
30
+ }
31
+ toJSON() {
32
+ const out = { code: this.code, message: this.message, exit_code: this.exitCode };
33
+ if (this.hint)
34
+ out.hint = this.hint;
35
+ if (this.docs)
36
+ out.docs = this.docs;
37
+ if (this.status !== undefined)
38
+ out.status = this.status;
39
+ if (this.details !== undefined)
40
+ out.details = this.details;
41
+ if (this.blockers?.length)
42
+ out.blockers = this.blockers;
43
+ return out;
44
+ }
45
+ }
46
+ export function usageError(message, hint) {
47
+ return new CavelonError(ExitCode.usage, { code: "usage", message, hint });
48
+ }
49
+ export function validationError(message, details, hint) {
50
+ return new CavelonError(ExitCode.validation, { code: "validation_failed", message, details, hint });
51
+ }
52
+ export function notLoggedIn(url) {
53
+ return new CavelonError(ExitCode.unauthorized, {
54
+ code: "not_logged_in",
55
+ message: url ? `No token for ${url}.` : "No instance and no token.",
56
+ hint: "A person runs `cavelon login` (or sets CAVELON_URL and CAVELON_TOKEN); the agent never handles the token.",
57
+ });
58
+ }
59
+ export function asCavelonError(error) {
60
+ if (error instanceof CavelonError)
61
+ return error;
62
+ const message = error instanceof Error ? error.message : String(error);
63
+ return new CavelonError(ExitCode.failure, { code: "internal_error", message });
64
+ }
@@ -0,0 +1,52 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { stringOption } from "./command.js";
3
+ import { CavelonError, ExitCode, usageError } from "./errors.js";
4
+ import { isUuid } from "./session.js";
5
+ export async function requireFeature(ctx, feature, code, what) {
6
+ const caps = await (await ctx.contracts()).capabilities();
7
+ if (caps?.features?.[feature] === false) {
8
+ throw new CavelonError(ExitCode.failure, {
9
+ code,
10
+ message: `This instance has ${what} switched off.`,
11
+ hint: `Its operator switches it on (${feature.toUpperCase()}); \`cavelon status\` shows the instance.`,
12
+ });
13
+ }
14
+ }
15
+ export async function instanceModes(ctx) {
16
+ const caps = await (await ctx.contracts()).capabilities();
17
+ const sandbox = caps?.sandbox;
18
+ return Array.isArray(sandbox?.execution_modes) ? sandbox.execution_modes.map(String) : undefined;
19
+ }
20
+ export const UUID_KEY_OPTION = {
21
+ type: "string",
22
+ value: "<uuid>",
23
+ description: "The Idempotency-Key to send (a UUID), so a retry of the same call does nothing twice.",
24
+ };
25
+ export function idempotencyKey(input) {
26
+ const given = stringOption(input, "idempotency-key");
27
+ if (given === undefined)
28
+ return randomUUID();
29
+ if (!isUuid(given))
30
+ throw usageError("--idempotency-key must be a UUID.");
31
+ return given.toLowerCase();
32
+ }
33
+ export function withRetryKey(error, key) {
34
+ if (!(error instanceof CavelonError) || error.exitCode !== ExitCode.server)
35
+ return error;
36
+ const rest = error.hint?.replace(/^Retry[;.]\s*/, "");
37
+ const details = error.details && typeof error.details === "object" && !Array.isArray(error.details) ? error.details : {};
38
+ return new CavelonError(error.exitCode, {
39
+ code: error.code,
40
+ message: error.message,
41
+ hint: [`Retry with --idempotency-key ${key}, so the instance does not do it twice.`, rest ? rest[0].toUpperCase() + rest.slice(1) : ""].filter(Boolean).join(" "),
42
+ docs: error.docs,
43
+ status: error.status,
44
+ details: { ...details, idempotency_key: key },
45
+ blockers: error.blockers,
46
+ });
47
+ }
48
+ export function stableKey(seed) {
49
+ const hex = createHash("sha256").update(seed).digest("hex");
50
+ const variant = ((Number.parseInt(hex[16], 16) & 0x3) | 0x8).toString(16);
51
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-5${hex.slice(13, 16)}-${variant}${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
52
+ }
package/dist/format.js ADDED
@@ -0,0 +1,36 @@
1
+ import { shellWord } from "./shell.js";
2
+ export function table(rows, columns, maxWidth = 60) {
3
+ if (rows.length === 0)
4
+ return "";
5
+ const cell = (value) => {
6
+ const text = value === null || value === undefined ? "" : typeof value === "object" ? JSON.stringify(value) : String(value);
7
+ const oneLine = text.replace(/\s+/g, " ");
8
+ return oneLine.length > maxWidth ? `${oneLine.slice(0, maxWidth - 1)}…` : oneLine;
9
+ };
10
+ const cells = rows.map((row) => columns.map((c) => cell(row[c])));
11
+ const widths = columns.map((c, i) => Math.max(c.length, ...cells.map((r) => r[i].length)));
12
+ const line = (values) => values
13
+ .map((v, i) => (i === values.length - 1 ? v : v.padEnd(widths[i])))
14
+ .join(" ")
15
+ .trimEnd();
16
+ return [line(columns.map((c) => c.toUpperCase())), ...cells.map(line)].join("\n");
17
+ }
18
+ export function keyValues(pairs) {
19
+ const shown = pairs.filter(([, v]) => v !== undefined);
20
+ const width = Math.max(0, ...shown.map(([k]) => k.length));
21
+ return shown
22
+ .map(([k, v]) => `${`${k}:`.padEnd(width + 1)} ${v === null ? "-" : typeof v === "object" ? JSON.stringify(v) : String(v)}`)
23
+ .join("\n");
24
+ }
25
+ export function moreHint(nextCursor, command) {
26
+ return nextCursor ? `\nMore: ${command} --cursor ${shellWord(nextCursor)}` : "";
27
+ }
28
+ export function clip(text, max) {
29
+ if (text.length <= max)
30
+ return text;
31
+ return `${text.slice(0, max)}… (${text.length - max} more characters)`;
32
+ }
33
+ export function blockerLines(blockers, max = 10) {
34
+ const shown = blockers.slice(0, max).map((b) => `\n - ${clip(b, 400)}`);
35
+ return `blockers:${shown.join("")}${blockers.length > max ? `\n … ${blockers.length - max} more (--json)` : ""}`;
36
+ }
package/dist/fsutil.js ADDED
@@ -0,0 +1,43 @@
1
+ import { promises as fs } from "node:fs";
2
+ import path from "node:path";
3
+ import { randomBytes } from "node:crypto";
4
+ export async function readJsonFile(file) {
5
+ try {
6
+ return JSON.parse(await fs.readFile(file, "utf8"));
7
+ }
8
+ catch (error) {
9
+ if (error.code === "ENOENT")
10
+ return undefined;
11
+ if (error instanceof SyntaxError)
12
+ return undefined;
13
+ throw error;
14
+ }
15
+ }
16
+ export async function readTextFile(file) {
17
+ try {
18
+ return await fs.readFile(file, "utf8");
19
+ }
20
+ catch (error) {
21
+ if (error.code === "ENOENT")
22
+ return undefined;
23
+ throw error;
24
+ }
25
+ }
26
+ export function withoutBom(text) {
27
+ return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
28
+ }
29
+ export async function writeFileAtomic(file, content, mode = 0o644, dirMode = 0o755) {
30
+ await fs.mkdir(path.dirname(file), { recursive: true, mode: dirMode });
31
+ const tmp = `${file}.${randomBytes(6).toString("hex")}.tmp`;
32
+ const handle = await fs.open(tmp, "w", mode);
33
+ try {
34
+ await handle.writeFile(content, "utf8");
35
+ }
36
+ finally {
37
+ await handle.close();
38
+ }
39
+ const existing = await fs.stat(file).then((st) => st.mode & 0o777, () => undefined);
40
+ if (existing !== undefined)
41
+ await fs.chmod(tmp, existing & mode).catch(() => undefined);
42
+ await fs.rename(tmp, file);
43
+ }
package/dist/git.js ADDED
@@ -0,0 +1,41 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promises as fs } from "node:fs";
3
+ import path from "node:path";
4
+ export async function resolveGit(env = process.env, platform = process.platform) {
5
+ const windows = platform === "win32";
6
+ const pathApi = windows ? path.win32 : path.posix;
7
+ const search = (windows ? (env.PATH ?? env.Path) : env.PATH) ?? "";
8
+ const name = windows ? "git.exe" : "git";
9
+ for (const entry of search.split(pathApi.delimiter)) {
10
+ const dir = windows && entry.length > 1 && entry.startsWith('"') && entry.endsWith('"') ? entry.slice(1, -1) : entry;
11
+ if (!dir || !pathApi.isAbsolute(dir))
12
+ continue;
13
+ const candidate = pathApi.join(dir, name);
14
+ const found = await fs
15
+ .stat(candidate)
16
+ .then((st) => st.isFile() && (windows || (st.mode & 0o111) !== 0))
17
+ .catch(() => false);
18
+ if (found)
19
+ return candidate;
20
+ }
21
+ return undefined;
22
+ }
23
+ export async function git(args, cwd) {
24
+ const executable = await resolveGit();
25
+ if (!executable)
26
+ return undefined;
27
+ return new Promise((resolve) => {
28
+ execFile(executable, args, { cwd, timeout: 10_000, windowsHide: true, encoding: "utf8" }, (error, stdout) => {
29
+ resolve(error ? undefined : stdout);
30
+ });
31
+ });
32
+ }
33
+ export async function uncommitted(cwd, paths) {
34
+ const out = await git(["status", "--porcelain", "--untracked-files=all", "--", ...paths], cwd);
35
+ if (out === undefined)
36
+ return undefined;
37
+ return out
38
+ .split("\n")
39
+ .map((line) => line.slice(3).trim())
40
+ .filter(Boolean);
41
+ }