@cavelon/cli 0.1.4 → 0.1.5

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.
@@ -0,0 +1,193 @@
1
+ import { stringify } from "yaml";
2
+ import { boolOption, positional } from "../command.js";
3
+ import { CavelonError, ExitCode, usageError } from "../errors.js";
4
+ import { clip, keyValues, table } from "../format.js";
5
+ import { deref, schemaTypes } from "../openapi.js";
6
+ import { DEFAULT_LAYOUT } from "../package-files.js";
7
+ import { requireInstance } from "../session.js";
8
+ import { schemaFor } from "./solution.js";
9
+ const EXAMPLE_DEPTH = 4;
10
+ function resolve(schema, node) {
11
+ return (deref(schema, node) ?? {});
12
+ }
13
+ function nonNull(schema, node) {
14
+ const resolved = resolve(schema, node);
15
+ for (const key of ["anyOf", "oneOf"]) {
16
+ const branches = resolved[key]?.map((b) => resolve(schema, b)).filter((b) => b.type !== "null");
17
+ if (branches?.length === 1)
18
+ return { ...resolved, ...branches[0], [key]: undefined };
19
+ }
20
+ return resolved;
21
+ }
22
+ function refName(node) {
23
+ return typeof node.$ref === "string" ? node.$ref.split("/").pop() : undefined;
24
+ }
25
+ function entryOf(schema, section) {
26
+ const resolved = nonNull(schema, section);
27
+ if (schemaTypes(resolved).includes("array") && resolved.items)
28
+ return { list: true, entry: nonNull(schema, resolved.items) };
29
+ return { list: false, entry: resolved };
30
+ }
31
+ function namedType(schema, raw) {
32
+ if (refName(raw))
33
+ return refName(raw);
34
+ const resolved = resolve(schema, raw);
35
+ for (const key of ["anyOf", "oneOf"]) {
36
+ const named = (resolved[key] ?? []).filter((b) => resolve(schema, b).type !== "null").map(refName);
37
+ if (named.length === 1 && named[0])
38
+ return named[0];
39
+ }
40
+ return undefined;
41
+ }
42
+ function typeOf(schema, raw) {
43
+ const node = nonNull(schema, raw);
44
+ const ref = namedType(schema, raw);
45
+ const types = schemaTypes(node).filter((t) => t !== "null");
46
+ if (types.includes("array") && node.items) {
47
+ const item = node.items;
48
+ return `list of ${refName(item) ?? (schemaTypes(resolve(schema, item)).join("|") || "any")}`;
49
+ }
50
+ return ref ?? (types.join("|") || "object");
51
+ }
52
+ function fieldsOf(schema, entry) {
53
+ const props = (entry.properties ?? {});
54
+ const required = new Set(entry.required ?? []);
55
+ return Object.entries(props).map(([name, raw]) => {
56
+ const node = nonNull(schema, raw);
57
+ const description = (raw.description ?? node.description);
58
+ return {
59
+ name,
60
+ type: typeOf(schema, raw),
61
+ required: required.has(name),
62
+ description: description ? clip(description, 160) : null,
63
+ ...(Array.isArray(node.enum) ? { enum: node.enum } : {}),
64
+ ...(node.default !== undefined && node.default !== null ? { default: node.default } : {}),
65
+ };
66
+ });
67
+ }
68
+ function sample(schema, raw, name, depth) {
69
+ const node = nonNull(schema, raw);
70
+ if (node.const !== undefined)
71
+ return node.const;
72
+ if (node.default !== undefined && node.default !== null)
73
+ return node.default;
74
+ if (Array.isArray(node.enum) && node.enum.length)
75
+ return node.enum[0];
76
+ const types = schemaTypes(node).filter((t) => t !== "null");
77
+ if (types.includes("array"))
78
+ return [];
79
+ if (types.includes("boolean"))
80
+ return false;
81
+ if (types.includes("integer") || types.includes("number"))
82
+ return typeof node.minimum === "number" ? node.minimum : 0;
83
+ if (node.properties || types.includes("object"))
84
+ return depth < EXAMPLE_DEPTH ? minimal(schema, node, depth + 1) : {};
85
+ return `<${name}>`;
86
+ }
87
+ function minimal(schema, entry, depth = 0) {
88
+ const props = (entry.properties ?? {});
89
+ const out = {};
90
+ for (const name of entry.required ?? []) {
91
+ out[name] = props[name] ? sample(schema, props[name], name, depth) : `<${name}>`;
92
+ }
93
+ return out;
94
+ }
95
+ function fileOf(layout, section) {
96
+ const folder = layout.items[section];
97
+ return folder ? `${folder}/<one file per entry>.yaml` : `${layout.package}/${section}.yaml`;
98
+ }
99
+ function sourceLine(used) {
100
+ const from = used.source === "instance" ? "read from the instance now" : `cached at ${used.fetched_at ?? "an unknown time"}`;
101
+ return `package format ${used.package_version ?? "?"}, ${from}${used.instance_version ? ` (instance ${used.instance_version})` : ""}`;
102
+ }
103
+ export const schema = {
104
+ name: "schema",
105
+ summary: "Show the package schema the instance publishes: its sections, or one section's fields with a minimal example.",
106
+ description: "Without a section, lists the sections with the file each is kept in. With one, lists its fields (type, required,\n" +
107
+ "allowed values, default) and prints the smallest entry that has every required field, ready to copy into the file.\n" +
108
+ "Placeholders are written <field>. Reads the schema as `validate` does: the cached copy first, the instance otherwise.",
109
+ readOnly: true,
110
+ idempotent: true,
111
+ mcpTool: "package_schema",
112
+ positionals: [{ name: "section", description: "A section of the package, such as agents or knowledge_bases." }],
113
+ options: { offline: { type: "boolean", description: "Use only the cached schema; never contact the instance." } },
114
+ examples: ["cavelon schema", "cavelon schema agents", "cavelon schema knowledge_bases --json"],
115
+ async run(ctx, input) {
116
+ const session = await ctx.session();
117
+ requireInstance(session);
118
+ const offline = boolOption(input, "offline");
119
+ const { schema: published, used } = await schemaFor(ctx, session.project?.packageVersion, offline);
120
+ if (!published?.properties) {
121
+ throw new CavelonError(ExitCode.failure, {
122
+ code: "package_schema_unavailable",
123
+ message: "No package schema is cached for this instance, and it was not read.",
124
+ hint: offline
125
+ ? "Run `cavelon schema` once without --offline while the instance is reachable."
126
+ : "The instance does not publish its package schema (/api/v1/meta/package-schema).",
127
+ });
128
+ }
129
+ const layout = session.project?.layout ?? DEFAULT_LAYOUT;
130
+ const required = new Set(published.required ?? []);
131
+ const sections = Object.keys(published.properties);
132
+ const name = positional(input, "section");
133
+ if (!name) {
134
+ const items = sections.map((section) => {
135
+ const node = published.properties[section];
136
+ const { list } = entryOf(published, node);
137
+ const description = (node.description ?? node.title ?? resolve(published, node).title);
138
+ return { section, kind: list ? "list" : "object", required: required.has(section), file: fileOf(layout, section), title: description ? clip(description, 80) : null };
139
+ });
140
+ return {
141
+ data: { schema: used, sections: items },
142
+ text: [
143
+ `Package schema: ${sourceLine(used)}.`,
144
+ "",
145
+ table(items, ["section", "kind", "required", "file"]),
146
+ "",
147
+ "One section's fields and a minimal example: cavelon schema <section>",
148
+ ].join("\n"),
149
+ };
150
+ }
151
+ const node = published.properties[name];
152
+ if (!node) {
153
+ const near = sections.filter((s) => s.includes(name) || name.includes(s)).slice(0, 5);
154
+ throw usageError(`The package schema has no section "${name}".`, near.length ? `Did you mean: ${near.join(", ")}? (\`cavelon schema\` lists them)` : "`cavelon schema` lists the sections.");
155
+ }
156
+ const { list, entry } = entryOf(published, node);
157
+ const fields = fieldsOf(published, entry);
158
+ const one = minimal(published, entry);
159
+ const example = list ? [one] : one;
160
+ const exampleYaml = stringify(example, { lineWidth: 0 });
161
+ const data = {
162
+ schema: used,
163
+ section: name,
164
+ kind: list ? "list" : "object",
165
+ required: required.has(name),
166
+ file: fileOf(layout, name),
167
+ entry: (list ? namedType(published, nonNull(published, node).items) : namedType(published, node)) ?? null,
168
+ fields,
169
+ example,
170
+ };
171
+ const rows = fields.map((f) => ({
172
+ field: f.name,
173
+ type: f.type,
174
+ required: f.required ? "yes" : "",
175
+ notes: [f.enum ? `one of ${f.enum.map(String).join(", ")}` : "", f.default !== undefined ? `default ${JSON.stringify(f.default)}` : "", f.description ?? ""]
176
+ .filter(Boolean)
177
+ .join("; "),
178
+ }));
179
+ const text = [
180
+ keyValues([
181
+ ["section", `${name} (${list ? "a list of entries" : "one object"}${data.entry ? `, each a ${data.entry}` : ""})`],
182
+ ["file", data.file],
183
+ ["schema", sourceLine(used)],
184
+ ]),
185
+ "",
186
+ rows.length ? table(rows, ["field", "type", "required", "notes"]) : "No fields are published for this section.",
187
+ "",
188
+ Object.keys(one).length ? "Minimal example (required fields only):" : "No field is required; the smallest entry is empty:",
189
+ exampleYaml.trimEnd(),
190
+ ].join("\n");
191
+ return { data, text };
192
+ },
193
+ };
@@ -8,6 +8,7 @@ import { formatQuota, formatValue, limitRef, readLimits, readQuotas } from "../l
8
8
  import { ApiClient, tokensDisabledError } from "../http.js";
9
9
  import { readAll } from "../io.js";
10
10
  import { listPreviews, readPull } from "../local-state.js";
11
+ import { solutionState, solutionStateLines } from "./solution.js";
11
12
  import { expiryOf, readPrincipal, readTenantless } from "../principal.js";
12
13
  import { readHidden } from "../prompt.js";
13
14
  import { isUuid, lookupTenantId, requireInstance, requireToken, tenantRequiredError } from "../session.js";
@@ -73,7 +74,7 @@ export const login = {
73
74
  "The token is kept in the operating system's credential store, or in a file only you can read.\n" +
74
75
  "Without --tenant, login finds the tenants the token reaches: one is used; from several, a person chooses on a terminal by number or name; " +
75
76
  "without a terminal the token is stored and login prints one `cavelon use` line per tenant (exit 2). " +
76
- "An operator's token that reaches every tenant asks for part of the tenant's name. " +
77
+ "An operator's token that reaches every tenant asks for part of the tenant's name to start in; Enter leaves the choice for later (`cavelon use`). " +
77
78
  "--tenant takes the tenant's name, slug or id. An older instance that lists no tenants places the token itself, or needs --tenant <tenant-id>.",
78
79
  readOnly: false,
79
80
  mcpTool: false,
@@ -116,8 +117,9 @@ export const login = {
116
117
  throw tenantRequiredError(url, tenantless.said, "No tenant was given");
117
118
  const reach = listsTenants(tenantless) && !tenantless.platform ? tenantless : undefined;
118
119
  let open = false;
120
+ let later = false;
119
121
  if (reach) {
120
- const choice = await chooseTenant(ctx, client, reach);
122
+ const choice = await chooseTenant(ctx, client, reach, { later: true });
121
123
  if (choice.kind === "none")
122
124
  throw noTenantError(url);
123
125
  if (choice.kind === "chosen") {
@@ -126,8 +128,10 @@ export const login = {
126
128
  chosen = choice.how;
127
129
  client.target.tenantId = t.id;
128
130
  }
129
- else if (!reach.tenantId)
131
+ else if (!reach.tenantId) {
130
132
  open = true;
133
+ later = choice.kind === "later";
134
+ }
131
135
  }
132
136
  const me = open ? undefined : await readMe(client);
133
137
  const { caps, needsTenant } = open ? { caps: null, needsTenant: false } : await readCapabilities(contracts, true);
@@ -163,8 +167,15 @@ export const login = {
163
167
  ctx.warn("CAVELON_TOKEN is set and takes precedence over this login.");
164
168
  if (store.kind === "file")
165
169
  ctx.warn("No operating-system credential store; the token is in a file only you can read (0600).");
166
- if (open)
170
+ if (open && !later)
167
171
  throw tenantOpenError(url, reach, `The token is stored for ${url}, but no tenant is chosen yet. `);
172
+ if (later) {
173
+ return {
174
+ data: { instance: url, credential: { kind, store: store.kind }, owner: null, tenant: null, instance_version: null, contracts: null },
175
+ text: `Logged in to ${url}. Token stored in the ${store.kind === "keyring" ? "credential store" : "user-only file"}. ` +
176
+ "No tenant is chosen yet: `cavelon use <name or slug>` chooses one; `cavelon tenant list --search <part of the name>` finds its slug.",
177
+ };
178
+ }
168
179
  if (needsTenant) {
169
180
  ctx.warn("This token works in Platform mode; choose a tenant with `cavelon use <tenant>` before tenant commands.");
170
181
  }
@@ -262,6 +273,19 @@ function credentialSource(session) {
262
273
  return "CAVELON_TOKEN";
263
274
  return session.tokenStore === "file" ? "login (user-only file)" : "login (credential store)";
264
275
  }
276
+ function platformModeText(token) {
277
+ const ceiling = token.ceiling_role ? ` (ceiling ${token.ceiling_role})` : "";
278
+ return token.platform_mode_allowed
279
+ ? `allowed${ceiling}`
280
+ : `not allowed${ceiling}; creating tenants and other platform routes need a token that allows it`;
281
+ }
282
+ function reachText(reach) {
283
+ if (reach.reachesAll) {
284
+ const own = reach.tenants.length;
285
+ return `every tenant (as operator; ${own ? `${own} membership${own === 1 ? "" : "s"} of your own` : "no memberships of your own"})`;
286
+ }
287
+ return `${reach.tenants.length} tenant${reach.tenants.length === 1 ? "" : "s"} (\`cavelon tenant list\`)`;
288
+ }
265
289
  export const whoami = {
266
290
  name: "whoami",
267
291
  summary: "Show who the token acts as, in which tenant, and where the token came from.",
@@ -283,7 +307,9 @@ export const whoami = {
283
307
  }
284
308
  const nowhere = Boolean(reach && !reach.tenantId && !reach.platform);
285
309
  const me = nowhere ? undefined : await readMe(client);
286
- const { caps, needsTenant } = nowhere ? { caps: null, needsTenant: false } : await readCapabilities(await ctx.contracts(), false);
310
+ const contracts = await ctx.contracts();
311
+ const { caps, needsTenant } = nowhere ? { caps: null, needsTenant: false } : await readCapabilities(contracts, false);
312
+ const versionCachedAt = caps ? contracts.cachedAt : undefined;
287
313
  const principal = needsTenant ? undefined : await readPrincipal(client);
288
314
  const contextTenant = me?.context?.tenant_id ?? principal?.tenant_id ?? client.target.tenantId ?? null;
289
315
  const tenants = [...(me?.memberships ?? []), ...(me?.accessible_tenants ?? [])];
@@ -293,6 +319,11 @@ export const whoami = {
293
319
  if (listsTenants(tenantless))
294
320
  reach = tenantless;
295
321
  }
322
+ if (pat && !reach) {
323
+ const tenantless = await readTenantless(client).catch(() => undefined);
324
+ if (listsTenants(tenantless))
325
+ reach = tenantless;
326
+ }
296
327
  const listed = reach?.tenants.find((t) => t.id === contextTenant);
297
328
  const stored = session.settings.tenant_id === contextTenant ? session.settings : undefined;
298
329
  const tenantName = listed?.name ?? membership?.tenant_name ?? stored?.tenant_name ?? null;
@@ -306,7 +337,12 @@ export const whoami = {
306
337
  if (expiry.warning)
307
338
  ctx.warn(expiry.warning);
308
339
  const data = {
309
- instance: { url: session.url, source: session.urlSource, version: caps?.instance.version ?? null },
340
+ instance: {
341
+ url: session.url,
342
+ source: session.urlSource,
343
+ version: caps?.instance.version ?? null,
344
+ ...(versionCachedAt ? { version_cached_at: versionCachedAt } : {}),
345
+ },
310
346
  credential: {
311
347
  kind: principal?.kind ?? session.tokenKind,
312
348
  source: session.tokenSource,
@@ -317,6 +353,7 @@ export const whoami = {
317
353
  expires_in_days: expiry.days_left,
318
354
  may_activate: principal?.token ? principal.token.may_activate : null,
319
355
  ceiling_role: principal?.token?.ceiling_role ?? null,
356
+ platform_mode_allowed: principal?.token?.platform_mode_allowed ?? null,
320
357
  scopes: principal?.api_key?.scopes ?? null,
321
358
  published: Boolean(principal),
322
359
  },
@@ -362,7 +399,9 @@ export const whoami = {
362
399
  ["credential", `${session.tokenKind === "api_key" ? "tenant API key" : session.tokenKind === "personal_access_token" ? "personal access token" : "token"}${tokenName} from ${credentialSource(session)}`],
363
400
  ["expires", expires],
364
401
  ["may activate", principal?.token ? (principal.token.may_activate ? "yes" : "no (a person activates in the Admin)") : undefined],
365
- ["version", data.instance.version ?? undefined],
402
+ ["platform mode", typeof principal?.token?.platform_mode_allowed === "boolean" ? platformModeText(principal.token) : undefined],
403
+ ["reaches", reach ? reachText(reach) : undefined],
404
+ ["version", data.instance.version ? `${data.instance.version}${versionCachedAt ? ` (cached at ${versionCachedAt})` : ""}` : undefined],
366
405
  ]),
367
406
  };
368
407
  },
@@ -414,7 +453,7 @@ export const use = {
414
453
  const choice = await chooseTenant(ctx, client, tenantless);
415
454
  if (choice.kind === "none")
416
455
  throw noTenantError(url, false);
417
- if (choice.kind === "open")
456
+ if (choice.kind !== "chosen")
418
457
  throw tenantOpenError(url, tenantless, "");
419
458
  const t = choice.tenant;
420
459
  ref = tenantRef(t);
@@ -474,9 +513,10 @@ function limitsLine(state, near) {
474
513
  return `not readable: ${state.unavailable}`;
475
514
  if (!state.published)
476
515
  return "not published by this instance";
516
+ const quotas = state.quotas_unavailable ? `\n quotas not readable: ${state.quotas_unavailable}` : "";
477
517
  if (!near.length)
478
- return "none close to a quota (`cavelon limits` lists them)";
479
- return `close to a quota: ${near.map((q) => `${q.key} ${formatQuota(q)}`).join("; ")}`;
518
+ return `${state.quotas_unavailable ? "quotas unknown" : "none close to a quota"} (\`cavelon limits\` lists them)${quotas}`;
519
+ return `close to a quota: ${near.map((q) => `${q.key} ${formatQuota(q)}`).join("; ")}${quotas}`;
480
520
  }
481
521
  export const status = {
482
522
  name: "status",
@@ -511,13 +551,22 @@ export const status = {
511
551
  let published;
512
552
  let reachError;
513
553
  let client;
554
+ if (offline && session.url) {
555
+ const cached = await new Contracts(new ApiClient({ url: session.url }, ctx.io.env), ctx.io.env, ctx.io.now)
556
+ .cachedOnly("capabilities.json")
557
+ .catch(() => undefined);
558
+ if (cached?.value?.instance?.version) {
559
+ data.instance_version = cached.value.instance.version;
560
+ data.instance_version_cached_at = cached.fetched_at;
561
+ }
562
+ }
514
563
  if (!offline && session.url && session.token) {
515
564
  try {
516
565
  client = await ctx.client();
517
566
  if (client.target.tenantId)
518
567
  data.tenant.id = client.target.tenantId;
519
568
  const contracts = await ctx.contracts();
520
- const caps = await contracts.capabilities();
569
+ const caps = await contracts.liveCapabilities();
521
570
  data.instance_version = caps?.instance.version ?? null;
522
571
  if (contracts.needsTenant) {
523
572
  data.operations = { unavailable: "No tenant chosen; operations belong to a tenant." };
@@ -541,6 +590,9 @@ export const status = {
541
590
  capacity = limits.capacity;
542
591
  published = limits.published;
543
592
  data.limits = limits.data;
593
+ const ref = session.envFile?.harness ?? session.project?.harness;
594
+ if (session.project && ref)
595
+ data.solution.state = await solutionState(ctx, ref);
544
596
  }
545
597
  }
546
598
  catch (error) {
@@ -563,6 +615,8 @@ export const status = {
563
615
  const solution = data.solution;
564
616
  if (session.project.harness)
565
617
  lines.push(["harness", session.project.harness]);
618
+ if (solution.state)
619
+ lines.push(...solutionStateLines(solution.state));
566
620
  lines.push(["last pull", solution.last_pull ? `${solution.last_pull.at}${solution.last_pull.harness ? ` (${solution.last_pull.harness.slug})` : ""}` : "never"]);
567
621
  lines.push([
568
622
  "open previews",
@@ -571,8 +625,10 @@ export const status = {
571
625
  : "none",
572
626
  ]);
573
627
  }
574
- if (data.instance_version)
575
- lines.push(["version", data.instance_version]);
628
+ if (data.instance_version) {
629
+ const cachedAt = data.instance_version_cached_at;
630
+ lines.push(["version", `${data.instance_version}${cachedAt !== undefined ? ` (cached at ${cachedAt ?? "an unknown time"}; not read now)` : ""}`]);
631
+ }
576
632
  if (data.limits)
577
633
  lines.push(["limits", limitsLine(data.limits, near ?? [])]);
578
634
  if (capacity.length)