@cavelon/cli 0.1.2 → 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.
@@ -8,9 +8,11 @@ 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 { expiryOf, readPrincipal } from "../principal.js";
11
+ import { expiryOf, readPrincipal, readTenantless } from "../principal.js";
12
12
  import { readHidden } from "../prompt.js";
13
- import { lookupTenantId, requireInstance, requireToken, TENANT_REF_HINT } from "../session.js";
13
+ import { isUuid, lookupTenantId, requireInstance, requireToken, tenantRequiredError } from "../session.js";
14
+ import { cavelonCommand } from "../shell.js";
15
+ import { choicesOf, chooseTenant, commandLines, listsTenants, noTenantError, tenantOpenError, tenantRef, tenantTitle } from "../tenant-choice.js";
14
16
  import { loadUserConfig, saveUserConfig, tokenKind, updateInstance } from "../user-config.js";
15
17
  async function readCapabilities(contracts, refresh) {
16
18
  const caps = await contracts.capabilities({ refresh });
@@ -30,8 +32,20 @@ async function readMe(client) {
30
32
  hint: "It may be expired or revoked; a person creates a new one on /account/access-tokens and runs `cavelon login`.",
31
33
  });
32
34
  }
35
+ if (response.status === 403 && !client.target.tenantId) {
36
+ const detail = response.data?.detail;
37
+ throw tenantRequiredError(client.url, typeof detail === "string" ? detail : "403 Forbidden");
38
+ }
33
39
  return response.status === 200 ? response.data : undefined;
34
40
  }
41
+ function actingTenant(tenantless, me) {
42
+ const id = tenantless && !tenantless.refused ? tenantless.tenantId : (me?.context?.tenant_id ?? undefined);
43
+ if (!id)
44
+ return undefined;
45
+ const tenants = [...(me?.memberships ?? []), ...(me?.accessible_tenants ?? [])];
46
+ const others = [...new Set(tenants.filter((t) => t.tenant_id !== id).map((t) => t.tenant_name || t.tenant_id))];
47
+ return { id, name: tenants.find((t) => t.tenant_id === id)?.tenant_name, others };
48
+ }
35
49
  async function readToken(ctx, fromStdin) {
36
50
  let token;
37
51
  if (fromStdin) {
@@ -56,13 +70,21 @@ export const login = {
56
70
  summary: "Store a token for an instance (a person runs this, never the agent).",
57
71
  description: "Asks for the token without echoing it, or reads it from standard input with --token-stdin. It is never an argument.\n" +
58
72
  "Create a personal access token (cvpat_…) on /account/access-tokens; a tenant API key (cbp_…) also works.\n" +
59
- "The token is kept in the operating system's credential store, or in a file only you can read.",
73
+ "The token is kept in the operating system's credential store, or in a file only you can read.\n" +
74
+ "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
+ "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
+ "--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>.",
60
78
  readOnly: false,
61
79
  mcpTool: false,
62
80
  options: {
63
81
  "token-stdin": { type: "boolean", description: "Read the token from standard input." },
64
82
  },
65
- examples: ["cavelon login --instance https://cavelon.example.com", "op read op://dev/cavelon/token | cavelon login --token-stdin"],
83
+ examples: [
84
+ "cavelon login --instance https://cavelon.example.com",
85
+ "cavelon login --instance https://cavelon.example.com --tenant \"Acme Support\"",
86
+ "op read op://dev/cavelon/token | cavelon login --token-stdin --tenant acme-support",
87
+ ],
66
88
  async run(ctx, input) {
67
89
  const session = await ctx.session();
68
90
  const url = session.url;
@@ -75,38 +97,86 @@ export const login = {
75
97
  const client = new ApiClient({ url, token }, ctx.io.env);
76
98
  const contracts = new Contracts(client, ctx.io.env, ctx.io.now);
77
99
  let tenant;
100
+ let chosen;
78
101
  if (session.tenant && kind !== "api_key") {
79
- const found = await lookupTenantId(client, session.tenant);
80
- if (!found) {
81
- throw new CavelonError(ExitCode.failure, { code: "tenant_not_found", message: `No tenant "${session.tenant}" for this token.`, hint: TENANT_REF_HINT });
102
+ try {
103
+ const found = await lookupTenantId(client, session.tenant);
104
+ tenant = { ref: session.tenant, ...found };
105
+ chosen = session.tenantSource === "option" ? "option" : undefined;
106
+ client.target.tenantId = found.id;
107
+ }
108
+ catch (error) {
109
+ if (session.tenantSource !== "use" || !(error instanceof CavelonError) || error.code !== "tenant_not_found")
110
+ throw error;
111
+ ctx.warn(`The tenant chosen before (${session.tenant}) is not one this token reaches; choosing again.`);
112
+ }
113
+ }
114
+ const tenantless = !tenant && kind === "personal_access_token" ? await readTenantless(client) : undefined;
115
+ if (tenantless?.refused)
116
+ throw tenantRequiredError(url, tenantless.said, "No tenant was given");
117
+ const reach = listsTenants(tenantless) && !tenantless.platform ? tenantless : undefined;
118
+ let open = false;
119
+ if (reach) {
120
+ const choice = await chooseTenant(ctx, client, reach);
121
+ if (choice.kind === "none")
122
+ throw noTenantError(url);
123
+ if (choice.kind === "chosen") {
124
+ const t = choice.tenant;
125
+ tenant = { ref: tenantRef(t), id: t.id, ...(t.name ? { name: t.name } : {}), ...(t.slug ? { slug: t.slug } : {}) };
126
+ chosen = choice.how;
127
+ client.target.tenantId = t.id;
82
128
  }
83
- tenant = { ref: session.tenant, ...found };
84
- client.target.tenantId = found.id;
129
+ else if (!reach.tenantId)
130
+ open = true;
85
131
  }
86
- const { caps, needsTenant } = await readCapabilities(contracts, true);
87
- const me = await readMe(client);
88
- if (!caps && !needsTenant && !me) {
132
+ const me = open ? undefined : await readMe(client);
133
+ const { caps, needsTenant } = open ? { caps: null, needsTenant: false } : await readCapabilities(contracts, true);
134
+ const acting = tenant || open ? undefined : actingTenant(tenantless, me);
135
+ if (!open && !caps && !needsTenant && !me) {
89
136
  await client.get("/api/v1/knowledge-bases", { query: { page_size: 1 }, allow: [400, 403, 404, 422] });
90
137
  }
91
138
  if (needsTenant && !me) {
92
- throw new CavelonError(ExitCode.validation, {
139
+ throw new CavelonError(ExitCode.usage, {
93
140
  code: "tenant_required",
94
141
  message: "The instance needs a tenant for this token.",
95
- hint: "Pass --tenant <slug-or-id>.",
142
+ hint: "Pass --tenant <name, slug or id>.",
96
143
  });
97
144
  }
98
145
  const store = await saveToken(ctx.io.env, url, token);
146
+ const remember = tenant && chosen;
99
147
  await updateInstance(ctx.io.env, url, (current) => ({
100
148
  ...current,
101
149
  credential_store: store.kind,
102
150
  token_kind: kind,
103
151
  logged_in_at: ctx.io.now().toISOString(),
104
- ...(tenant && session.tenantSource === "option" ? { tenant: tenant.ref, tenant_id: tenant.id, tenant_name: tenant.name } : {}),
152
+ ...(remember
153
+ ? {
154
+ tenant: tenant.slug ?? tenant.ref,
155
+ tenant_id: tenant.id,
156
+ tenant_name: tenant.name,
157
+ tenant_slug: tenant.slug,
158
+ tenant_ids: { ...current.tenant_ids, [tenant.ref]: tenant.id, ...(tenant.slug ? { [tenant.slug]: tenant.id } : {}) },
159
+ }
160
+ : {}),
105
161
  }), { makeCurrent: true });
162
+ if (ctx.io.env.CAVELON_TOKEN)
163
+ ctx.warn("CAVELON_TOKEN is set and takes precedence over this login.");
164
+ if (store.kind === "file")
165
+ ctx.warn("No operating-system credential store; the token is in a file only you can read (0600).");
166
+ if (open)
167
+ throw tenantOpenError(url, reach, `The token is stored for ${url}, but no tenant is chosen yet. `);
106
168
  if (needsTenant) {
107
169
  ctx.warn("This token works in Platform mode; choose a tenant with `cavelon use <tenant>` before tenant commands.");
108
170
  }
109
171
  else {
172
+ if (acting && reach) {
173
+ const others = reach.tenants.filter((t) => t.id !== acting.id);
174
+ if (others.length)
175
+ ctx.warn(`Without a tenant this token acts in ${acting.name ?? acting.id}. To work in another tenant, run:\n${commandLines(others, (r) => cavelonCommand("use", r))}`);
176
+ }
177
+ else if (acting && acting.others.length) {
178
+ ctx.warn(`Without a tenant this token acts in ${acting.name ?? acting.id}. Your other tenants: ${acting.others.join(", ")}; \`cavelon use <tenant>\` chooses one this token reaches.`);
179
+ }
110
180
  for (const warning of compareContracts(caps))
111
181
  ctx.warn(warning);
112
182
  try {
@@ -127,22 +197,32 @@ export const login = {
127
197
  if (expiry.warning)
128
198
  ctx.warn(expiry.warning);
129
199
  }
130
- if (ctx.io.env.CAVELON_TOKEN)
131
- ctx.warn("CAVELON_TOKEN is set and takes precedence over this login.");
132
- if (store.kind === "file")
133
- ctx.warn("No operating-system credential store; the token is in a file only you can read (0600).");
200
+ const actingNamed = acting && reach ? reach.tenants.find((t) => t.id === acting.id) : undefined;
134
201
  const data = {
135
202
  instance: url,
136
203
  credential: { kind, store: store.kind },
137
204
  owner: me ? { email: me.email, name: me.display_name ?? null } : null,
138
- tenant: tenant ? { ref: tenant.ref, id: tenant.id, name: tenant.name ?? null } : null,
205
+ tenant: tenant
206
+ ? { ref: tenant.ref, id: tenant.id, name: tenant.name ?? null, slug: tenant.slug ?? null, chosen: chosen ?? session.tenantSource ?? null }
207
+ : acting
208
+ ? { ref: null, id: acting.id, name: acting.name ?? actingNamed?.name ?? null, slug: actingNamed?.slug ?? null, chosen: "instance" }
209
+ : null,
139
210
  instance_version: caps?.instance.version ?? null,
140
211
  contracts: caps?.contracts ?? null,
141
212
  };
142
213
  const who = me?.email ? ` as ${me.email}` : kind === "api_key" ? " with a tenant API key" : "";
214
+ let where = "";
215
+ if (tenant && chosen === "only")
216
+ where = ` Using tenant ${tenantTitle(tenant)}, the only one this token reaches.`;
217
+ else if (tenant && chosen === "picked")
218
+ where = ` Using tenant ${tenantTitle(tenant)}; \`cavelon use\` chooses another.`;
219
+ else if (acting) {
220
+ const named = { id: acting.id, name: acting.name ?? actingNamed?.name, slug: actingNamed?.slug };
221
+ where = ` Acting in tenant ${tenantTitle(named)}, the one the instance chooses for this token.`;
222
+ }
143
223
  return {
144
224
  data,
145
- text: `Logged in to ${url}${who}. Token stored in the ${store.kind === "keyring" ? "credential store" : "user-only file"}.`,
225
+ text: `Logged in to ${url}${who}. Token stored in the ${store.kind === "keyring" ? "credential store" : "user-only file"}.${where}`,
146
226
  };
147
227
  },
148
228
  };
@@ -192,12 +272,36 @@ export const whoami = {
192
272
  const session = await ctx.session();
193
273
  requireToken(session);
194
274
  const client = await ctx.client();
195
- const { caps, needsTenant } = await readCapabilities(await ctx.contracts(), false);
196
- const me = await readMe(client);
275
+ const pat = session.tokenKind === "personal_access_token";
276
+ let reach;
277
+ if (!client.target.tenantId && pat) {
278
+ const tenantless = await readTenantless(client);
279
+ if (tenantless?.refused)
280
+ throw tenantRequiredError(client.url, tenantless.said);
281
+ if (listsTenants(tenantless))
282
+ reach = tenantless;
283
+ }
284
+ const nowhere = Boolean(reach && !reach.tenantId && !reach.platform);
285
+ const me = nowhere ? undefined : await readMe(client);
286
+ const { caps, needsTenant } = nowhere ? { caps: null, needsTenant: false } : await readCapabilities(await ctx.contracts(), false);
197
287
  const principal = needsTenant ? undefined : await readPrincipal(client);
198
288
  const contextTenant = me?.context?.tenant_id ?? principal?.tenant_id ?? client.target.tenantId ?? null;
199
289
  const tenants = [...(me?.memberships ?? []), ...(me?.accessible_tenants ?? [])];
200
- const tenantName = tenants.find((t) => t.tenant_id === contextTenant)?.tenant_name ?? session.settings.tenant_name ?? null;
290
+ const membership = tenants.find((t) => t.tenant_id === contextTenant);
291
+ if (contextTenant && pat && !reach && !membership?.tenant_slug && session.settings.tenant_id !== contextTenant) {
292
+ const tenantless = await readTenantless(client);
293
+ if (listsTenants(tenantless))
294
+ reach = tenantless;
295
+ }
296
+ const listed = reach?.tenants.find((t) => t.id === contextTenant);
297
+ const stored = session.settings.tenant_id === contextTenant ? session.settings : undefined;
298
+ const tenantName = listed?.name ?? membership?.tenant_name ?? stored?.tenant_name ?? null;
299
+ const tenantSlug = listed?.slug ?? membership?.tenant_slug ?? stored?.tenant_slug ?? null;
300
+ if (nowhere && reach) {
301
+ ctx.warn(reach.tenants.length
302
+ ? `No tenant is chosen. Choose one with \`cavelon use\`, or run the line for the tenant you want:\n${commandLines(reach.tenants, (r) => cavelonCommand("use", r))}`
303
+ : "No tenant is chosen. This token reaches every tenant: `cavelon use <name or slug>` chooses one.");
304
+ }
201
305
  const expiry = expiryOf(principal, ctx.io.now());
202
306
  if (expiry.warning)
203
307
  ctx.warn(expiry.warning);
@@ -224,10 +328,12 @@ export const whoami = {
224
328
  tenant: {
225
329
  id: contextTenant,
226
330
  name: tenantName,
331
+ slug: tenantSlug,
227
332
  ref: session.tenant ?? null,
228
333
  source: session.tenant ? session.tenantSource : null,
229
- mode: me?.context?.mode ?? principal?.mode ?? (session.tokenKind === "api_key" ? "tenant" : null),
334
+ mode: nowhere ? "none" : (me?.context?.mode ?? principal?.mode ?? (session.tokenKind === "api_key" ? "tenant" : null)),
230
335
  },
336
+ ...(reach ? { reaches: { tenants: reach.tenants.length, every_tenant: reach.reachesAll } } : {}),
231
337
  role: me?.context?.effective_role ?? me?.role ?? null,
232
338
  };
233
339
  if (needsTenant)
@@ -250,8 +356,8 @@ export const whoami = {
250
356
  text: keyValues([
251
357
  ["instance", `${session.url} (${session.urlSource})`],
252
358
  ["acting as", owner],
253
- ["tenant", contextTenant ? `${tenantName ?? contextTenant}${tenantName ? ` (${contextTenant})` : ""}` : "none (Platform mode)"],
254
- ["tenant from", session.tenant ? session.tenantSource : "the token's default"],
359
+ ["tenant", contextTenant ? tenantTitle({ id: contextTenant, name: tenantName, slug: tenantSlug }) : nowhere ? "none chosen (`cavelon use` chooses one)" : "none (Platform mode)"],
360
+ ["tenant from", session.tenant ? session.tenantSource : nowhere ? undefined : "the token's default"],
255
361
  ["role", data.role ?? undefined],
256
362
  ["credential", `${session.tokenKind === "api_key" ? "tenant API key" : session.tokenKind === "personal_access_token" ? "personal access token" : "token"}${tokenName} from ${credentialSource(session)}`],
257
363
  ["expires", expires],
@@ -264,50 +370,73 @@ export const whoami = {
264
370
  export const use = {
265
371
  name: "use",
266
372
  summary: "Choose the tenant this instance's commands act in.",
267
- description: "Stored per instance for your user. CAVELON_TENANT, --tenant and a cavelon.yaml tenant take precedence over it.",
373
+ description: "Stored per instance for your user. CAVELON_TENANT, --tenant and a cavelon.yaml tenant take precedence over it.\n" +
374
+ "Without a tenant, it lists the tenants the token reaches: a person chooses one on a terminal by number or part of its name; " +
375
+ "without a terminal it prints one `cavelon use` line per tenant, and as an MCP tool it returns them as choices and changes nothing.",
268
376
  readOnly: false,
269
377
  idempotent: true,
270
378
  mcpTool: "use_tenant",
271
- positionals: [{ name: "tenant", description: "Tenant slug, name or id.", required: false }],
379
+ positionals: [{ name: "tenant", description: "The tenant's name, slug or id; leave it out to choose from a list.", required: false }],
272
380
  options: { clear: { type: "boolean", description: "Forget the chosen tenant." } },
381
+ examples: ["cavelon use", "cavelon use acme-support", "cavelon use \"Acme Support\""],
273
382
  async run(ctx, input) {
274
383
  const session = await ctx.session();
275
384
  const url = requireInstance(session);
276
385
  requireToken(session);
277
386
  if (boolOption(input, "clear")) {
278
- await updateInstance(ctx.io.env, url, (c) => ({ ...c, tenant: undefined, tenant_id: undefined, tenant_name: undefined }));
387
+ await updateInstance(ctx.io.env, url, (c) => ({ ...c, tenant: undefined, tenant_id: undefined, tenant_name: undefined, tenant_slug: undefined }));
279
388
  return { data: { instance: url, tenant: null }, text: `No tenant chosen for ${url}.` };
280
389
  }
281
- const ref = positional(input, "tenant");
282
- if (!ref)
283
- throw usageError("Missing <tenant>.", "Usage: cavelon use <tenant> (or --clear)");
284
390
  if (session.tokenKind === "api_key") {
285
391
  throw usageError("A tenant API key is bound to its own tenant; `use` applies to personal access tokens.");
286
392
  }
287
393
  const client = await ctx.client({ tenant: false });
288
- const found = await lookupTenantId(client, ref);
289
- if (!found) {
290
- throw new CavelonError(ExitCode.failure, {
291
- code: "tenant_not_found",
292
- message: `No tenant "${ref}" that this token can see.`,
293
- hint: TENANT_REF_HINT,
294
- });
394
+ let ref = positional(input, "tenant");
395
+ let found;
396
+ if (ref) {
397
+ found = await lookupTenantId(client, ref);
398
+ }
399
+ else {
400
+ const tenantless = await readTenantless(client);
401
+ if (!listsTenants(tenantless)) {
402
+ throw usageError("Which tenant? This instance does not list the tenants a token reaches.", "Run `cavelon use <name, slug or id>`; `cavelon tenant list` shows the tenants this token can see.");
403
+ }
404
+ const command = (r) => cavelonCommand("use", r);
405
+ if (ctx.mode === "mcp" && (tenantless.reachesAll || tenantless.tenants.length !== 1)) {
406
+ const choices = choicesOf(tenantless.tenants, command);
407
+ return {
408
+ data: { instance: url, tenant: null, chosen: false, choices, reaches_all_tenants: tenantless.reachesAll },
409
+ text: tenantless.reachesAll
410
+ ? "Nothing changed: this token reaches every tenant; call use_tenant again with the tenant's name or slug (tenant_list with search finds it)."
411
+ : "Nothing changed: choose one of the tenants and call use_tenant again with its slug.",
412
+ };
413
+ }
414
+ const choice = await chooseTenant(ctx, client, tenantless);
415
+ if (choice.kind === "none")
416
+ throw noTenantError(url, false);
417
+ if (choice.kind === "open")
418
+ throw tenantOpenError(url, tenantless, "");
419
+ const t = choice.tenant;
420
+ ref = tenantRef(t);
421
+ found = { id: t.id, ...(t.name ? { name: t.name } : {}), ...(t.slug ? { slug: t.slug } : {}) };
295
422
  }
296
423
  const probe = new ApiClient({ ...client.target, tenantId: found.id }, ctx.io.env);
297
424
  await probe.get("/api/v1/meta/capabilities", { allow: [404] });
425
+ const stored = found.slug ?? ref;
298
426
  await updateInstance(ctx.io.env, url, (c) => ({
299
427
  ...c,
300
- tenant: ref,
428
+ tenant: stored,
301
429
  tenant_id: found.id,
302
- tenant_name: found.name ?? c.tenant_name,
303
- tenant_ids: { ...c.tenant_ids, [ref]: found.id },
430
+ tenant_name: found.name ?? (c.tenant_id === found.id ? c.tenant_name : undefined),
431
+ tenant_slug: found.slug ?? (c.tenant_id === found.id ? c.tenant_slug : undefined),
432
+ tenant_ids: { ...c.tenant_ids, [ref]: found.id, [stored]: found.id },
304
433
  }));
305
434
  if (session.tenantSource && session.tenantSource !== "use") {
306
435
  ctx.warn(`${session.tenantSource} names tenant "${session.tenant}" and takes precedence over \`use\` here.`);
307
436
  }
308
437
  return {
309
- data: { instance: url, tenant: { ref, id: found.id, name: found.name ?? null } },
310
- text: `Using tenant ${found.name ?? ref} (${found.id}) on ${url}.`,
438
+ data: { instance: url, tenant: { ref: stored, id: found.id, name: found.name ?? null, slug: found.slug ?? null } },
439
+ text: `Using tenant ${tenantTitle({ id: found.id, name: found.name, slug: found.slug ?? (isUuid(ref) ? undefined : ref) })} on ${url}.`,
311
440
  };
312
441
  },
313
442
  };
@@ -423,7 +552,7 @@ export const status = {
423
552
  ? `${session.tenant} (${session.tenantSource})`
424
553
  : session.tokenKind === "api_key"
425
554
  ? "the API key's tenant"
426
- : "not chosen (`cavelon use <tenant>`)";
555
+ : "not chosen (`cavelon use` lists your tenants to choose from)";
427
556
  const lines = [
428
557
  ["instance", session.url ? `${session.url} (${session.urlSource})` : "none (`cavelon login --instance <url>`)"],
429
558
  ["credential", session.token ? `${session.tokenKind} from ${credentialSource(session)}` : "none"],
@@ -475,6 +604,7 @@ export async function rememberTenant(ctx, url, tenant) {
475
604
  tenant: tenant.ref,
476
605
  tenant_id: tenant.id,
477
606
  tenant_name: tenant.name,
607
+ tenant_slug: tenant.slug,
478
608
  tenant_ids: { ...c.tenant_ids, [tenant.ref]: tenant.id },
479
609
  }));
480
610
  }