@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,394 @@
1
+ import { promises as fs } from "node:fs";
2
+ import path from "node:path";
3
+ import { LineCounter, parseDocument, stringify } from "yaml";
4
+ import { CavelonError, ExitCode } from "./errors.js";
5
+ import { readTextFile, withoutBom, writeFileAtomic } from "./fsutil.js";
6
+ export const DEFAULT_LAYOUT = { package: "package", items: {} };
7
+ const PACKAGE_FILE = /\.(ya?ml|json)$/i;
8
+ export function layoutFrom(raw) {
9
+ const value = raw.layout;
10
+ if (!value || typeof value !== "object" || Array.isArray(value))
11
+ return { ...DEFAULT_LAYOUT, items: {} };
12
+ const map = value;
13
+ const items = {};
14
+ if (map.items && typeof map.items === "object" && !Array.isArray(map.items)) {
15
+ for (const [section, folder] of Object.entries(map.items)) {
16
+ if (typeof folder === "string" && safeFolder(folder))
17
+ items[section] = folder;
18
+ }
19
+ }
20
+ const pkg = typeof map.package === "string" && safeFolder(map.package) ? map.package : DEFAULT_LAYOUT.package;
21
+ return { package: pkg, items };
22
+ }
23
+ function safeFolder(folder) {
24
+ const normalized = path.posix.normalize(folder.replace(/\\/g, "/"));
25
+ return normalized !== "." && !normalized.startsWith("..") && !path.isAbsolute(folder) && !normalized.startsWith("/");
26
+ }
27
+ export function defaultLayoutFor(schema) {
28
+ const items = {};
29
+ const suites = schema?.properties?.test_suites;
30
+ if (suites && suites.type === "array")
31
+ items.test_suites = "tests";
32
+ return { package: DEFAULT_LAYOUT.package, items };
33
+ }
34
+ export function schemaSections(schema) {
35
+ return Object.keys(schema?.properties ?? {});
36
+ }
37
+ function rel(root, file) {
38
+ return path.relative(root, file).split(path.sep).join("/");
39
+ }
40
+ async function listFiles(dir) {
41
+ try {
42
+ const entries = await fs.readdir(dir, { withFileTypes: true });
43
+ const names = [];
44
+ for (const e of entries) {
45
+ if (e.name.startsWith(".") || !PACKAGE_FILE.test(e.name))
46
+ continue;
47
+ if (e.isFile())
48
+ names.push(e.name);
49
+ else if (e.isSymbolicLink() && !(await fs.stat(path.join(dir, e.name)).then((st) => st.isDirectory(), () => false)))
50
+ names.push(e.name);
51
+ }
52
+ return names.sort((a, b) => a.localeCompare(b, "en"));
53
+ }
54
+ catch (error) {
55
+ if (error.code === "ENOENT")
56
+ return [];
57
+ throw error;
58
+ }
59
+ }
60
+ export async function contentPath(root, file) {
61
+ let real;
62
+ try {
63
+ real = await fs.realpath(file);
64
+ }
65
+ catch {
66
+ return file;
67
+ }
68
+ const relative = path.relative(await fs.realpath(root).catch(() => root), real);
69
+ return relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative) ? real : undefined;
70
+ }
71
+ async function readSource(root, file) {
72
+ const relative = rel(root, file);
73
+ const target = await contentPath(root, file);
74
+ const invalid = (message, hint) => ({
75
+ finding: { code: "package_file_invalid", severity: "error", file: relative, message, hint },
76
+ });
77
+ if (target === undefined) {
78
+ return invalid("It is a link to a file outside the solution folder.", "Move the file into the solution folder and link to it there, or copy it in.");
79
+ }
80
+ const text = await readTextFile(target);
81
+ if (text === undefined)
82
+ return invalid("It is a link to a file that does not exist.", "Point the link at an existing file, or remove it.");
83
+ return { text: withoutBom(text) };
84
+ }
85
+ async function exists(dir) {
86
+ try {
87
+ return (await fs.stat(dir)).isDirectory();
88
+ }
89
+ catch {
90
+ return false;
91
+ }
92
+ }
93
+ function parseFile(root, file, text) {
94
+ const relative = rel(root, file);
95
+ if (/\.json$/i.test(file)) {
96
+ try {
97
+ return { value: JSON.parse(text), source: { file: relative } };
98
+ }
99
+ catch (error) {
100
+ return {
101
+ source: { file: relative },
102
+ finding: { code: "package_file_invalid", severity: "error", file: relative, message: `Not valid JSON: ${error.message}` },
103
+ };
104
+ }
105
+ }
106
+ const lines = new LineCounter();
107
+ const doc = parseDocument(text, { lineCounter: lines, uniqueKeys: true, prettyErrors: false });
108
+ if (doc.errors.length) {
109
+ const first = doc.errors[0];
110
+ return {
111
+ source: { file: relative },
112
+ finding: {
113
+ code: "package_file_invalid",
114
+ severity: "error",
115
+ file: relative,
116
+ line: first.linePos?.[0]?.line,
117
+ message: `Not valid YAML: ${first.message.split("\n")[0]}`,
118
+ },
119
+ };
120
+ }
121
+ return { value: doc.toJS({ maxAliasCount: 1000 }), source: { file: relative, doc, lines } };
122
+ }
123
+ export async function readPackage(root, layout) {
124
+ const pkg = {};
125
+ const sources = {};
126
+ const findings = [];
127
+ const dir = path.join(root, layout.package);
128
+ let empty = true;
129
+ for (const name of await listFiles(dir)) {
130
+ empty = false;
131
+ const section = name.replace(PACKAGE_FILE, "");
132
+ const file = path.join(dir, name);
133
+ if (section in sources) {
134
+ findings.push({
135
+ code: "package_file_duplicate",
136
+ severity: "error",
137
+ file: rel(root, file),
138
+ message: `Section "${section}" has two files; keep one of them.`,
139
+ });
140
+ continue;
141
+ }
142
+ const read = await readSource(root, file);
143
+ if ("finding" in read) {
144
+ sources[section] = { file: rel(root, file) };
145
+ findings.push(read.finding);
146
+ continue;
147
+ }
148
+ const parsed = parseFile(root, file, read.text);
149
+ sources[section] = parsed.source;
150
+ if (parsed.finding)
151
+ findings.push(parsed.finding);
152
+ else
153
+ pkg[section] = parsed.value;
154
+ }
155
+ for (const [section, folder] of Object.entries(layout.items)) {
156
+ const itemDir = path.join(root, folder);
157
+ if (!(await exists(itemDir)))
158
+ continue;
159
+ const names = await listFiles(itemDir);
160
+ if (names.length)
161
+ empty = false;
162
+ else if (section in sources)
163
+ continue;
164
+ if (section in sources) {
165
+ findings.push({
166
+ code: "package_file_duplicate",
167
+ severity: "error",
168
+ file: rel(root, itemDir),
169
+ message: `Section "${section}" is both in ${layout.package}/ and in ${folder}/; keep one of them.`,
170
+ });
171
+ continue;
172
+ }
173
+ const items = [];
174
+ const itemSources = [];
175
+ for (const name of names) {
176
+ const file = path.join(itemDir, name);
177
+ const read = await readSource(root, file);
178
+ if ("finding" in read) {
179
+ itemSources.push({ file: rel(root, file) });
180
+ findings.push(read.finding);
181
+ continue;
182
+ }
183
+ const parsed = parseFile(root, file, read.text);
184
+ itemSources.push(parsed.source);
185
+ if (parsed.finding)
186
+ findings.push(parsed.finding);
187
+ else
188
+ items.push(parsed.value);
189
+ }
190
+ sources[section] = itemSources;
191
+ pkg[section] = items;
192
+ }
193
+ return { package: pkg, sources, findings, empty };
194
+ }
195
+ export function locate(disk, pointer) {
196
+ const keys = pointer
197
+ .split("/")
198
+ .slice(1)
199
+ .map((k) => k.replace(/~1/g, "/").replace(/~0/g, "~"));
200
+ const section = keys[0];
201
+ const display = keys.slice(1).reduce((acc, key) => (/^\d+$/.test(key) ? `${acc}[${key}]` : `${acc}.${key}`), section ?? "");
202
+ if (section === undefined)
203
+ return { path: "(package)" };
204
+ const source = disk.sources[section];
205
+ if (!source)
206
+ return { path: display };
207
+ let target;
208
+ let inner;
209
+ if (Array.isArray(source)) {
210
+ const index = Number(keys[1]);
211
+ if (!Number.isInteger(index) || !source[index])
212
+ return { file: source[0]?.file, path: display };
213
+ target = source[index];
214
+ inner = keys.slice(2);
215
+ }
216
+ else {
217
+ target = source;
218
+ inner = keys.slice(1);
219
+ }
220
+ return { file: target.file, line: lineOf(target, inner), path: display };
221
+ }
222
+ function lineOf(source, keys) {
223
+ if (!source.doc || !source.lines)
224
+ return undefined;
225
+ for (let n = keys.length; n >= 0; n--) {
226
+ const path = keys.slice(0, n).map((k) => (/^\d+$/.test(k) ? Number(k) : k));
227
+ const node = n === 0 ? source.doc.contents : source.doc.getIn(path, true);
228
+ const range = node?.range;
229
+ if (range)
230
+ return source.lines.linePos(range[0]).line;
231
+ }
232
+ return undefined;
233
+ }
234
+ export function safeSectionName(section) {
235
+ return /^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}$/.test(section) && !section.includes("..");
236
+ }
237
+ export function canonical(value) {
238
+ return JSON.stringify(value, (_key, v) => {
239
+ if (v && typeof v === "object" && !Array.isArray(v)) {
240
+ return Object.fromEntries(Object.entries(v).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
241
+ }
242
+ return v;
243
+ });
244
+ }
245
+ export function toYaml(value) {
246
+ return stringify(value, { lineWidth: 0, aliasDuplicateObjects: false });
247
+ }
248
+ async function readValue(root, file) {
249
+ const target = await contentPath(root, file);
250
+ const text = target === undefined ? undefined : await readTextFile(target);
251
+ if (text === undefined)
252
+ return { ok: false };
253
+ try {
254
+ const plain = withoutBom(text);
255
+ const value = /\.json$/i.test(file) ? JSON.parse(plain) : parseDocument(plain, { uniqueKeys: true }).toJS({ maxAliasCount: 1000 });
256
+ return { value, ok: true };
257
+ }
258
+ catch {
259
+ return { ok: false };
260
+ }
261
+ }
262
+ function itemFileName(item, index, taken) {
263
+ const record = item && typeof item === "object" && !Array.isArray(item) ? item : {};
264
+ const label = [record.slug, record.name, record.key].find((v) => typeof v === "string" && v.trim() !== "");
265
+ const base = trimDashesAndDots((label ?? `item-${index + 1}`)
266
+ .toLowerCase()
267
+ .normalize("NFKD")
268
+ .replace(/[^a-z0-9._-]+/g, "-")).slice(0, 80) || `item-${index + 1}`;
269
+ let name = `${base}.yaml`;
270
+ let n = 1;
271
+ while (taken.has(name))
272
+ name = `${base}-${++n}.yaml`;
273
+ taken.add(name);
274
+ return name;
275
+ }
276
+ export async function writePackage(root, layout, pkg, schema, options = {}) {
277
+ const dryRun = options.dryRun === true;
278
+ const report = { written: [], unchanged: [], removed: [], kept: [], refused: [] };
279
+ const known = new Set(schemaSections(schema));
280
+ const required = new Set(schema?.required ?? []);
281
+ const dir = path.join(root, layout.package);
282
+ const existing = new Map();
283
+ for (const name of await listFiles(dir))
284
+ existing.set(name.replace(PACKAGE_FILE, ""), name);
285
+ const plans = [];
286
+ const same = [];
287
+ const removals = [];
288
+ for (const [section, value] of Object.entries(pkg)) {
289
+ if (section in layout.items && Array.isArray(value))
290
+ continue;
291
+ if (!safeSectionName(section)) {
292
+ report.refused.push(section);
293
+ continue;
294
+ }
295
+ const current = existing.get(section);
296
+ const file = path.join(dir, current ?? `${section}.yaml`);
297
+ const old = await readValue(root, file);
298
+ if (old.ok && canonical(old.value) === canonical(value))
299
+ same.push({ file, section });
300
+ else
301
+ plans.push({ file, section, content: /\.json$/i.test(file) ? JSON.stringify(value, null, 2) + "\n" : toYaml(value) });
302
+ }
303
+ for (const [section, folder] of Object.entries(layout.items)) {
304
+ const value = pkg[section];
305
+ if (!Array.isArray(value))
306
+ continue;
307
+ const itemDir = path.join(root, folder);
308
+ const before = new Map();
309
+ for (const name of await listFiles(itemDir)) {
310
+ const old = await readValue(root, path.join(itemDir, name));
311
+ if (old.ok)
312
+ before.set(name, old.value);
313
+ }
314
+ const taken = new Set();
315
+ const unclaimed = new Map(before);
316
+ const placed = value.map((item) => {
317
+ for (const [name, old] of unclaimed) {
318
+ if (canonical(old) === canonical(item)) {
319
+ unclaimed.delete(name);
320
+ taken.add(name);
321
+ return name;
322
+ }
323
+ }
324
+ return undefined;
325
+ });
326
+ value.forEach((item, index) => {
327
+ const name = placed[index];
328
+ if (name) {
329
+ same.push({ file: path.join(itemDir, name), section });
330
+ return;
331
+ }
332
+ plans.push({ file: path.join(itemDir, itemFileName(item, index, taken)), section, content: toYaml(item) });
333
+ });
334
+ for (const name of before.keys())
335
+ if (!taken.has(name))
336
+ removals.push(path.join(itemDir, name));
337
+ if (!dryRun)
338
+ await fs.mkdir(itemDir, { recursive: true });
339
+ }
340
+ for (const [section, name] of existing) {
341
+ if (section in pkg)
342
+ continue;
343
+ const file = path.join(dir, name);
344
+ if (known.has(section))
345
+ removals.push(file);
346
+ else
347
+ report.kept.push(rel(root, file));
348
+ }
349
+ const othersChanged = plans.some((p) => !required.has(p.section));
350
+ const writes = [];
351
+ const outside = [];
352
+ for (const plan of plans) {
353
+ if (required.has(plan.section) && !othersChanged && existing.has(plan.section)) {
354
+ same.push({ file: plan.file, section: plan.section });
355
+ continue;
356
+ }
357
+ const target = await contentPath(root, plan.file);
358
+ if (target === undefined)
359
+ outside.push(rel(root, plan.file));
360
+ else
361
+ writes.push({ file: plan.file, target, content: plan.content });
362
+ }
363
+ if (outside.length) {
364
+ throw new CavelonError(ExitCode.conflict, {
365
+ code: "package_file_outside",
366
+ message: `${outside.join(", ")} ${outside.length === 1 ? "is a link" : "are links"} to a file outside the solution folder; nothing was written.`,
367
+ hint: "Move the file into the solution folder and link to it there, or replace the link with the file.",
368
+ details: { files: outside },
369
+ });
370
+ }
371
+ for (const write of writes) {
372
+ if (!dryRun)
373
+ await writeFileAtomic(write.target, write.content);
374
+ report.written.push(rel(root, write.file));
375
+ }
376
+ for (const file of removals) {
377
+ if (!dryRun)
378
+ await fs.rm(file, { force: true });
379
+ report.removed.push(rel(root, file));
380
+ }
381
+ report.unchanged.push(...same.map((s) => rel(root, s.file)));
382
+ for (const list of Object.values(report))
383
+ list.sort();
384
+ return report;
385
+ }
386
+ function trimDashesAndDots(text) {
387
+ let start = 0;
388
+ let end = text.length;
389
+ while (start < end && (text[start] === "-" || text[start] === "."))
390
+ start++;
391
+ while (end > start && (text[end - 1] === "-" || text[end - 1] === "."))
392
+ end--;
393
+ return text.slice(start, end);
394
+ }
@@ -0,0 +1,39 @@
1
+ import { catalogEntry } from "./package-check.js";
2
+ export const PAIR_ORDER = [
3
+ "apply the iteration solution",
4
+ "apply the parent",
5
+ "run the parent's loop suite",
6
+ "activate the iteration solution",
7
+ "activate the parent",
8
+ ];
9
+ export const DRAFT_ITERATION_NEEDS_DRAFT_PARENT = "runtime_draft_iteration_needs_draft_parent";
10
+ export const ITERATION_UNAVAILABLE = "runtime_external_iteration_harness_unavailable";
11
+ export const ITERATION_DRAFT = "masterloop_iteration_harness_draft";
12
+ const POINTERS = {
13
+ [ITERATION_UNAVAILABLE]: "Step 1 comes first: `cavelon apply` the iteration solution into its own solution, bind that solution's id " +
14
+ "under runtime_bindings in the parent's env/<name>.yaml, then apply the parent (step 2).",
15
+ [DRAFT_ITERATION_NEEDS_DRAFT_PARENT]: "Step 2 binds a draft iteration only into a draft parent: apply the parent into a draft solution " +
16
+ "(a new one, or `cavelon harness new <slug>`), or activate the iteration solution first (step 4).",
17
+ [ITERATION_DRAFT]: "Step 4 comes before step 5: once the parent's loop suite passed, `cavelon activate` the iteration solution, " +
18
+ "then activate the parent.",
19
+ };
20
+ export const PAIR_ORDER_CODES = Object.keys(POINTERS);
21
+ export function pairOrderText() {
22
+ return `The order that needs no override: ${PAIR_ORDER.map((step, i) => `${i + 1}. ${step}`).join("; ")}. \`cavelon activate\` never forces.`;
23
+ }
24
+ export function pairOrderPointer(code) {
25
+ const pointer = POINTERS[code];
26
+ return pointer ? `${pointer} ${pairOrderText()}` : undefined;
27
+ }
28
+ export function pairOrderHint(catalog, texts) {
29
+ const said = texts.filter((t) => typeof t === "string" && t !== "");
30
+ for (const code of PAIR_ORDER_CODES) {
31
+ const entry = catalogEntry(catalog, code);
32
+ const named = new RegExp(`\\b${code}\\b`);
33
+ if (!said.some((t) => named.test(t) || (entry?.message ? t.includes(entry.message) : false)))
34
+ continue;
35
+ const catalogSentence = entry ? [entry.message, entry.hint].filter(Boolean).join(" ") : "";
36
+ return { code, hint: [`${code}:`, catalogSentence, pairOrderPointer(code)].filter(Boolean).join(" ") };
37
+ }
38
+ return undefined;
39
+ }
package/dist/paths.js ADDED
@@ -0,0 +1,77 @@
1
+ import { createHash } from "node:crypto";
2
+ import { promises as fs } from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { CavelonError, ExitCode } from "./errors.js";
6
+ import { findProject } from "./project.js";
7
+ function home(env) {
8
+ return env.HOME || env.USERPROFILE || os.homedir();
9
+ }
10
+ export function configDir(env) {
11
+ if (env.CAVELON_CONFIG_DIR)
12
+ return env.CAVELON_CONFIG_DIR;
13
+ if (env.XDG_CONFIG_HOME)
14
+ return path.join(env.XDG_CONFIG_HOME, "cavelon");
15
+ if (process.platform === "win32" && env.APPDATA)
16
+ return path.join(env.APPDATA, "cavelon");
17
+ return path.join(home(env), ".config", "cavelon");
18
+ }
19
+ export function cacheDir(env) {
20
+ if (env.CAVELON_CACHE_DIR)
21
+ return env.CAVELON_CACHE_DIR;
22
+ if (env.XDG_CACHE_HOME)
23
+ return path.join(env.XDG_CACHE_HOME, "cavelon");
24
+ if (process.platform === "win32" && env.LOCALAPPDATA)
25
+ return path.join(env.LOCALAPPDATA, "cavelon", "cache");
26
+ return path.join(home(env), ".cache", "cavelon");
27
+ }
28
+ export function instanceKey(url) {
29
+ const parsed = new URL(url);
30
+ const parts = [parsed.hostname, parsed.port, parsed.pathname.replace(/^\/+|\/+$/g, "")].filter(Boolean);
31
+ const readable = parts.join("_").replace(/[^A-Za-z0-9._-]+/g, "_");
32
+ return `${readable}-${createHash("sha256").update(url).digest("hex").slice(0, 8)}`;
33
+ }
34
+ export async function confinedPath(ctx, raw, what) {
35
+ const resolved = path.resolve(ctx.io.cwd, raw);
36
+ if (ctx.mode !== "mcp")
37
+ return resolved;
38
+ const root = (await findProject(ctx.io.cwd))?.root ?? ctx.io.cwd;
39
+ const real = await realPath(resolved);
40
+ if (!within(await realPath(root), real)) {
41
+ throw new CavelonError(ExitCode.usage, {
42
+ code: "path_outside_solution",
43
+ message: `${what} ${raw} is outside the solution folder ${root}; over MCP a tool reads and writes only there.`,
44
+ hint: "Name a file inside the solution folder, or ask the person to run the command in their terminal.",
45
+ });
46
+ }
47
+ for (const dir of [configDir(ctx.io.env), cacheDir(ctx.io.env)]) {
48
+ if (within(await realPath(path.resolve(ctx.io.cwd, dir)), real, true)) {
49
+ throw new CavelonError(ExitCode.usage, {
50
+ code: "path_in_kit_directory",
51
+ message: `${what} ${raw} is in cavelon's own directory ${dir}, which holds its login and cache; no tool reads or writes there.`,
52
+ });
53
+ }
54
+ }
55
+ return resolved;
56
+ }
57
+ export async function realPath(file) {
58
+ const rest = [];
59
+ let current = file;
60
+ for (;;) {
61
+ try {
62
+ return path.join(await fs.realpath(current), ...rest.reverse());
63
+ }
64
+ catch (error) {
65
+ const parent = path.dirname(current);
66
+ if (error.code !== "ENOENT" || parent === current)
67
+ throw error;
68
+ rest.push(path.basename(current));
69
+ current = parent;
70
+ }
71
+ }
72
+ }
73
+ export function within(dir, file, fold = false) {
74
+ const norm = (p) => (fold && (process.platform === "win32" || process.platform === "darwin") ? p.toLowerCase() : p);
75
+ const rel = path.relative(norm(dir), norm(file));
76
+ return rel === "" || (rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel));
77
+ }
@@ -0,0 +1,33 @@
1
+ export async function readPrincipal(client, options = {}) {
2
+ const response = await client.get("/api/v1/meta/principal", { allow: [400, 403, 404, 405], sendTenant: options.sendTenant });
3
+ if (response.status !== 200 || !response.data?.kind)
4
+ return undefined;
5
+ const { permissions, ...rest } = response.data;
6
+ return Array.isArray(permissions) ? { ...rest, permissions: permissions.filter((p) => typeof p === "string") } : rest;
7
+ }
8
+ export async function readGlobalRole(client) {
9
+ const response = await client.get("/api/v1/auth/me", { allow: [400, 401, 403, 404], sendTenant: false });
10
+ if (response.status !== 200 || !response.data)
11
+ return undefined;
12
+ const role = response.data.global_role;
13
+ return typeof role === "string" && role ? role : null;
14
+ }
15
+ export const EXPIRY_WARNING_DAYS = 7;
16
+ export function expiryOf(principal, now) {
17
+ const expiresAt = principal?.token?.expires_at ?? principal?.api_key?.expires_at ?? null;
18
+ if (!expiresAt)
19
+ return { expires_at: null, days_left: null };
20
+ const ms = new Date(expiresAt).getTime() - now.getTime();
21
+ const days = Math.floor(ms / 86_400_000);
22
+ const what = principal?.token ? `The personal access token "${principal.token.name}"` : `The API key "${principal?.api_key?.name}"`;
23
+ if (ms <= 0)
24
+ return { expires_at: expiresAt, days_left: days, warning: `${what} has expired.` };
25
+ if (ms <= EXPIRY_WARNING_DAYS * 86_400_000) {
26
+ const when = days < 1 ? "within a day" : `in ${days} day${days === 1 ? "" : "s"}`;
27
+ const renew = principal?.token
28
+ ? "A person creates a new one on /account/access-tokens and runs `cavelon login`."
29
+ : "A tenant administrator issues a new key in Settings → API keys.";
30
+ return { expires_at: expiresAt, days_left: days, warning: `${what} expires ${when} (${expiresAt}). ${renew}` };
31
+ }
32
+ return { expires_at: expiresAt, days_left: days };
33
+ }