@geslar/cli 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,7 +10,7 @@ geslar run -e DB_PASSWORD=geslar://Work/Database/password -- ./start-server.sh
10
10
 
11
11
  The server never sees which vault, item, or field a reference asks for — resolution happens locally, after decrypting on your machine.
12
12
 
13
- Full docs: install (including standalone Windows/Linux binaries), quickstart, the `geslar://` reference syntax, and known limitations — see the `docs/` directory in the [geslar-suite](https://github.com/StudioIT/geslar-suite) repository (`docs/cli/`) until docs.geslar.app is live.
13
+ Full docs: install (including standalone Windows/Linux binaries), quickstart, the `geslar://` reference syntax, agent profiles, and known limitations — see [docs.geslar.app/cli/reference](https://docs.geslar.app/cli/reference) or the `docs/cli/` directory in the [geslar-suite](https://github.com/StudioIT/geslar-suite) repository.
14
14
 
15
15
  ## License
16
16
 
package/dist/index.js CHANGED
@@ -1065,7 +1065,7 @@ async function pollDeviceFlow(baseUrl, start, fetchImpl = fetch, opts = {}) {
1065
1065
  }
1066
1066
 
1067
1067
  // src/commands/signin.ts
1068
- var CLI_VERSION = "0.1.0";
1068
+ var CLI_VERSION = "0.2.0";
1069
1069
  async function signinCommand(opts) {
1070
1070
  const config = await loadOrInitConfig();
1071
1071
  const baseUrl = opts.api ?? config.apiBase;
@@ -1385,6 +1385,29 @@ var ApiClient = class {
1385
1385
  getVaultKeyMaterial() {
1386
1386
  return this.request("/v1/account/vault-key-material", { method: "GET" });
1387
1387
  }
1388
+ // ── Access core (M4.5) — agent principals ─────────────────────────────────
1389
+ // spec-access-core.md REV 1.2 §3. Human-session-only except getAgentWhoami,
1390
+ // which is the one route an agent bearer token may itself call.
1391
+ /** Human session + fresh TOTP required server-side. Returns the plaintext
1392
+ * token exactly once — the caller must persist it immediately. */
1393
+ createAgent(body) {
1394
+ return this.request("/v1/agents", {
1395
+ method: "POST",
1396
+ body: JSON.stringify(body)
1397
+ });
1398
+ }
1399
+ listAgents() {
1400
+ return this.request("/v1/agents", { method: "GET" });
1401
+ }
1402
+ revokeAgent(id) {
1403
+ return this.request(`/v1/agents/${encodeURIComponent(id)}`, { method: "DELETE" });
1404
+ }
1405
+ /** Reachable by both a human session AND an agent bearer token — the CLI
1406
+ * uses this under GESLAR_AGENT context to read live capabilities (never
1407
+ * guessed/cached locally, spec §4). */
1408
+ getAgentWhoami() {
1409
+ return this.request("/v1/agents/whoami", { method: "GET" });
1410
+ }
1388
1411
  /**
1389
1412
  * Create an account. All crypto happens in @geslar/core/crypto
1390
1413
  * (prepareRegistration) — this only ships auth_hash + opaque wrapped blobs.
@@ -2291,6 +2314,49 @@ async function whoamiCommand() {
2291
2314
  }
2292
2315
 
2293
2316
  // src/lib/prompt.ts
2317
+ var TOTP_CTRL_C = "";
2318
+ var TOTP_CTRL_D = "";
2319
+ var TOTP_BACKSPACE = "\x7F";
2320
+ function promptTotpCode(promptText, ttyError) {
2321
+ return new Promise((resolve, reject) => {
2322
+ if (!process.stdin.isTTY) {
2323
+ reject(ttyError);
2324
+ return;
2325
+ }
2326
+ process.stdout.write(promptText);
2327
+ const stdin = process.stdin;
2328
+ stdin.setRawMode(true);
2329
+ stdin.resume();
2330
+ stdin.setEncoding("utf8");
2331
+ let input = "";
2332
+ const onData = (chunk) => {
2333
+ const char = chunk.toString();
2334
+ if (char === "\n" || char === "\r" || char === TOTP_CTRL_D) {
2335
+ cleanup();
2336
+ process.stdout.write("\n");
2337
+ resolve(input.trim());
2338
+ return;
2339
+ }
2340
+ if (char === TOTP_CTRL_C) {
2341
+ cleanup();
2342
+ process.stdout.write("\n");
2343
+ reject(new CliError(EXIT.GENERAL, "Aborted"));
2344
+ return;
2345
+ }
2346
+ if (char === TOTP_BACKSPACE || char === "\b") {
2347
+ input = input.slice(0, -1);
2348
+ return;
2349
+ }
2350
+ input += char;
2351
+ };
2352
+ function cleanup() {
2353
+ stdin.setRawMode(false);
2354
+ stdin.pause();
2355
+ stdin.removeListener("data", onData);
2356
+ }
2357
+ stdin.on("data", onData);
2358
+ });
2359
+ }
2294
2360
  var CTRL_C = "";
2295
2361
  var CTRL_D = "";
2296
2362
  var BACKSPACE = "\x7F";
@@ -2470,6 +2536,58 @@ async function listVaultHandles(api, unlocked) {
2470
2536
  return handles;
2471
2537
  }
2472
2538
 
2539
+ // src/vault/agent-vaults.ts
2540
+ async function listAgentVaultHandles(api, unlocked, grantedVaults) {
2541
+ const handles = [];
2542
+ const personalGrant = grantedVaults.find((v) => v.kind === "personal");
2543
+ if (personalGrant) {
2544
+ handles.push({
2545
+ id: personalGrant.id,
2546
+ name: PERSONAL_VAULT_NAME,
2547
+ kind: "personal",
2548
+ orgId: null,
2549
+ orgType: null,
2550
+ isDefault: true,
2551
+ dekMap: /* @__PURE__ */ new Map([[1, await import_vault_cloud_crypto.default.importVaultKey(unlocked.dekRaw)]])
2552
+ });
2553
+ }
2554
+ const hasCollectionGrant = grantedVaults.some((v) => v.kind === "collection");
2555
+ if (hasCollectionGrant && unlocked.ecdhPrivRaw) {
2556
+ const { collections } = await api.getCollections();
2557
+ for (const c of collections) {
2558
+ if (!c.can_view || !c.name) continue;
2559
+ const isDefault = c.is_default === true;
2560
+ const name = isDefault ? c.org_name ?? c.name : c.name;
2561
+ const dekMap = await buildCollectionDekMap2(c, unlocked.ecdhPrivRaw);
2562
+ if (dekMap.size === 0) continue;
2563
+ handles.push({
2564
+ id: c.vault_id,
2565
+ name,
2566
+ kind: "collection",
2567
+ orgId: c.org_id,
2568
+ // getOrgs() isn't on the agent allowlist — org type (needed only for
2569
+ // the family/company/work semantic tokens) is unavailable under
2570
+ // agent context; direct vault-name addressing is unaffected.
2571
+ orgType: null,
2572
+ isDefault,
2573
+ dekMap
2574
+ });
2575
+ }
2576
+ }
2577
+ return handles;
2578
+ }
2579
+ async function buildCollectionDekMap2(c, ecdhPrivRaw) {
2580
+ const source = c.keys && c.keys.length > 0 ? c.keys.map((k) => ({ key_version: k.key_version, encrypted_key: k.encrypted_key, ecdh_public_key: k.wrapped_by?.ecdh_public_key ?? null })) : c.encrypted_key ? [{ key_version: c.key_version, encrypted_key: c.encrypted_key, ecdh_public_key: c.wrapper_ecdh_pub }] : [];
2581
+ const map = /* @__PURE__ */ new Map();
2582
+ for (const k of source) {
2583
+ if (!k.encrypted_key || !k.ecdh_public_key) continue;
2584
+ const wrapperPub = import_vault_crypto.default.base64ToBuf(k.ecdh_public_key);
2585
+ const dekRaw = await import_vault_cloud_crypto.default.unwrapSharedVaultKey(ecdhPrivRaw, wrapperPub, k.encrypted_key);
2586
+ map.set(k.key_version, await import_vault_cloud_crypto.default.importVaultKey(dekRaw));
2587
+ }
2588
+ return map;
2589
+ }
2590
+
2473
2591
  // src/vault/totp.ts
2474
2592
  var B32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
2475
2593
  function base32Decode(input) {
@@ -2728,22 +2846,93 @@ async function resolveRef(ref, ctx) {
2728
2846
  return { vault, entry, field: parsed.field, value };
2729
2847
  }
2730
2848
 
2849
+ // src/agent/token-store.ts
2850
+ async function loadAll() {
2851
+ const backend = await selectBackend("agent-token");
2852
+ const raw = await backend.load();
2853
+ if (!raw) return {};
2854
+ try {
2855
+ return JSON.parse(raw);
2856
+ } catch {
2857
+ return {};
2858
+ }
2859
+ }
2860
+ async function saveAgentToken(name, record) {
2861
+ const backend = await selectBackend("agent-token");
2862
+ const map = await loadAll();
2863
+ map[name] = record;
2864
+ await backend.save(JSON.stringify(map));
2865
+ }
2866
+ async function loadAgentToken(name) {
2867
+ const map = await loadAll();
2868
+ return map[name] ?? null;
2869
+ }
2870
+ async function clearAgentToken(name) {
2871
+ const backend = await selectBackend("agent-token");
2872
+ const map = await loadAll();
2873
+ if (!(name in map)) return;
2874
+ delete map[name];
2875
+ if (Object.keys(map).length === 0) {
2876
+ await backend.clear();
2877
+ } else {
2878
+ await backend.save(JSON.stringify(map));
2879
+ }
2880
+ }
2881
+
2882
+ // src/lib/agent-context.ts
2883
+ function resolveAgentName(cliAgentOpt) {
2884
+ return cliAgentOpt || process.env["GESLAR_AGENT"] || null;
2885
+ }
2886
+ function agentTokenStore(token) {
2887
+ const current = { access_token: token, refresh_token: "" };
2888
+ return {
2889
+ get: () => current,
2890
+ set: () => {
2891
+ }
2892
+ };
2893
+ }
2894
+ async function resolveApiContext(baseUrl, agentOpt) {
2895
+ const agentName = resolveAgentName(agentOpt);
2896
+ if (agentName) {
2897
+ const record = await loadAgentToken(agentName);
2898
+ if (!record) {
2899
+ throw new CliError(
2900
+ EXIT.AUTH,
2901
+ `No local token for agent profile "${agentName}" \u2014 run \`geslar agent create ${agentName} ...\` on this machine, or check the name with \`geslar agent list\``
2902
+ );
2903
+ }
2904
+ const api2 = buildApiClient(baseUrl, agentTokenStore(record.token));
2905
+ return { api: api2, isAgent: true, agentName, flush: async () => void 0 };
2906
+ }
2907
+ const backend = await selectBackend();
2908
+ const tokenStore = await createCliTokenStore(backend);
2909
+ if (!tokenStore.get()) {
2910
+ throw new CliError(EXIT.AUTH, "not signed in \u2014 run `geslar signin`");
2911
+ }
2912
+ const api = buildApiClient(baseUrl, tokenStore);
2913
+ return { api, isAgent: false, agentName: null, flush: () => tokenStore.flush() };
2914
+ }
2915
+ function requireHumanContext(agentOpt, action) {
2916
+ const agentName = resolveAgentName(agentOpt);
2917
+ if (agentName) {
2918
+ throw new CliError(
2919
+ EXIT.GENERAL,
2920
+ `\`geslar agent ${action}\` is a human action \u2014 cannot run under agent context (GESLAR_AGENT=${agentName})`
2921
+ );
2922
+ }
2923
+ }
2924
+
2731
2925
  // src/commands/list.ts
2732
2926
  async function listCommand(vaultFilter) {
2733
2927
  try {
2734
2928
  const config = await loadOrInitConfig();
2735
2929
  const session = await loadSession();
2736
2930
  const baseUrl = session?.apiBase ?? config.apiBase;
2737
- const backend = await selectBackend();
2738
- const tokenStore = await createCliTokenStore(backend);
2739
- if (!tokenStore.get()) {
2740
- printErr("not signed in \u2014 run `geslar signin`");
2741
- return EXIT.AUTH;
2742
- }
2743
- const api = buildApiClient(baseUrl, tokenStore);
2931
+ const apiCtx = await resolveApiContext(baseUrl);
2932
+ const api = apiCtx.api;
2744
2933
  const unlocked = await obtainUnlockedKeys(api);
2745
- await tokenStore.flush();
2746
- const vaults = await listVaultHandles(api, unlocked);
2934
+ await apiCtx.flush();
2935
+ const vaults = apiCtx.isAgent ? await listAgentVaultHandles(api, unlocked, (await loadAgentToken(apiCtx.agentName))?.vaults ?? []) : await listVaultHandles(api, unlocked);
2747
2936
  const targets = vaultFilter ? [resolveVaultByQuery(vaultFilter, vaults)] : vaults;
2748
2937
  for (const vault of targets) {
2749
2938
  print(`${vault.name} (${vault.id})`);
@@ -2806,17 +2995,22 @@ async function readCommand(ref, opts) {
2806
2995
  const config = await loadOrInitConfig();
2807
2996
  const session = await loadSession();
2808
2997
  const baseUrl = session?.apiBase ?? config.apiBase;
2809
- const backend = await selectBackend();
2810
- const tokenStore = await createCliTokenStore(backend);
2811
- if (!tokenStore.get()) {
2812
- printErr("not signed in \u2014 run `geslar signin`");
2813
- return EXIT.AUTH;
2998
+ const ctx = await resolveApiContext(baseUrl);
2999
+ const { api } = ctx;
3000
+ if (ctx.isAgent) {
3001
+ const whoami = await api.getAgentWhoami();
3002
+ if (whoami.type === "agent" && !whoami.capabilities.includes("read")) {
3003
+ throw new CliError(
3004
+ EXIT.GRANT_DENIED,
3005
+ "This agent profile doesn't have the 'read' capability \u2014 recreate it with `geslar agent create ... --allow-read` to permit printing secret values (default profiles are run+inject only, by design)."
3006
+ );
3007
+ }
3008
+ } else {
3009
+ await requireAgenticCli(api);
2814
3010
  }
2815
- const api = buildApiClient(baseUrl, tokenStore);
2816
- await requireAgenticCli(api);
2817
3011
  const unlocked = await obtainUnlockedKeys(api);
2818
- await tokenStore.flush();
2819
- const vaults = await listVaultHandles(api, unlocked);
3012
+ await ctx.flush();
3013
+ const vaults = ctx.isAgent ? await listAgentVaultHandles(api, unlocked, (await loadAgentToken(ctx.agentName))?.vaults ?? []) : await listVaultHandles(api, unlocked);
2820
3014
  const resolved = await resolveRef(ref, createResolveContext(api, vaults));
2821
3015
  registerSecret(resolved.value);
2822
3016
  if (opts.output) {
@@ -2921,19 +3115,14 @@ async function runCommand(command, args, opts) {
2921
3115
  const config = await loadOrInitConfig();
2922
3116
  const session = await loadSession();
2923
3117
  const baseUrl = session?.apiBase ?? config.apiBase;
2924
- const backend = await selectBackend();
2925
- const tokenStore = await createCliTokenStore(backend);
2926
- if (!tokenStore.get()) {
2927
- printErr("not signed in \u2014 run `geslar signin`");
2928
- return EXIT.AUTH;
2929
- }
2930
- const api = buildApiClient(baseUrl, tokenStore);
2931
- await requireAgenticCli(api);
3118
+ const apiCtx = await resolveApiContext(baseUrl);
3119
+ const api = apiCtx.api;
3120
+ if (!apiCtx.isAgent) await requireAgenticCli(api);
2932
3121
  const unlocked = await obtainUnlockedKeys(api);
2933
- await tokenStore.flush();
2934
- const vaults = await listVaultHandles(api, unlocked);
2935
- const ctx = createResolveContext(api, vaults);
2936
- const resolvedEnv = await resolveRefsOrLiteral(values, ctx);
3122
+ await apiCtx.flush();
3123
+ const vaults = apiCtx.isAgent ? await listAgentVaultHandles(api, unlocked, (await loadAgentToken(apiCtx.agentName))?.vaults ?? []) : await listVaultHandles(api, unlocked);
3124
+ const resolveCtx = createResolveContext(api, vaults);
3125
+ const resolvedEnv = await resolveRefsOrLiteral(values, resolveCtx);
2937
3126
  return await spawnChild(command, args, resolvedEnv);
2938
3127
  } catch (err) {
2939
3128
  if (err instanceof CliError) {
@@ -3025,6 +3214,77 @@ async function injectCommand(opts) {
3025
3214
  const config = await loadOrInitConfig();
3026
3215
  const session = await loadSession();
3027
3216
  const baseUrl = session?.apiBase ?? config.apiBase;
3217
+ const apiCtx = await resolveApiContext(baseUrl);
3218
+ const api = apiCtx.api;
3219
+ if (!apiCtx.isAgent) await requireAgenticCli(api);
3220
+ const unlocked = await obtainUnlockedKeys(api);
3221
+ await apiCtx.flush();
3222
+ const vaults = apiCtx.isAgent ? await listAgentVaultHandles(api, unlocked, (await loadAgentToken(apiCtx.agentName))?.vaults ?? []) : await listVaultHandles(api, unlocked);
3223
+ const resolveCtx = createResolveContext(api, vaults);
3224
+ const uniqueRefs = {};
3225
+ for (const ref of new Set(refByPlaceholder.values())) uniqueRefs[ref] = ref;
3226
+ const resolved = await resolveRefsOrLiteral(uniqueRefs, resolveCtx);
3227
+ let output = template;
3228
+ for (const [placeholder, ref] of refByPlaceholder) {
3229
+ output = output.split(placeholder).join(resolved[ref]);
3230
+ }
3231
+ await writeFile7(opts.output, output, { mode: 384 });
3232
+ print(`Written to ${opts.output}`);
3233
+ return EXIT.OK;
3234
+ } catch (err) {
3235
+ if (err instanceof CliError) {
3236
+ printErr(err.message);
3237
+ return err.exitCode;
3238
+ }
3239
+ printErr(err.message);
3240
+ return EXIT.GENERAL;
3241
+ }
3242
+ }
3243
+
3244
+ // src/commands/agent-create.ts
3245
+ import { createInterface } from "node:readline/promises";
3246
+ var NO_TTY_ERROR = new CliError(
3247
+ EXIT.GENERAL,
3248
+ "geslar agent create requires an interactive terminal (TTY) \u2014 TOTP entry cannot be scripted"
3249
+ );
3250
+ function validateExpires(expires) {
3251
+ if (expires === void 0) return void 0;
3252
+ if (expires === "never") return expires;
3253
+ if (/^[1-9]\d{0,3}d$/.test(expires)) return expires;
3254
+ throw new CliError(EXIT.GENERAL, `Invalid --expires value "${expires}" \u2014 use e.g. 90d, or "never"`);
3255
+ }
3256
+ async function confirmAllowRead() {
3257
+ print(
3258
+ "By default, agent profiles get run+inject only \u2014 they can USE a secret\n(spawn a process with it in env, substitute it into a template) but never\nprint it. --allow-read additionally grants the read capability, so\n`geslar read` under this profile WILL print the secret value to stdout."
3259
+ );
3260
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
3261
+ try {
3262
+ const answer = await rl.question('Type "yes" to create this profile with read access: ');
3263
+ return answer.trim().toLowerCase() === "yes";
3264
+ } finally {
3265
+ rl.close();
3266
+ }
3267
+ }
3268
+ async function agentCreateCommand(name, opts) {
3269
+ try {
3270
+ requireHumanContext(opts.agent, "create");
3271
+ if (!process.stdin.isTTY) {
3272
+ throw NO_TTY_ERROR;
3273
+ }
3274
+ if (opts.vault.length === 0) {
3275
+ throw new CliError(EXIT.GENERAL, "At least one --vault <name> is required");
3276
+ }
3277
+ const expires = validateExpires(opts.expires);
3278
+ if (opts.allowRead) {
3279
+ const confirmed = await confirmAllowRead();
3280
+ if (!confirmed) {
3281
+ printErr("Aborted \u2014 profile not created");
3282
+ return EXIT.GENERAL;
3283
+ }
3284
+ }
3285
+ const config = await loadOrInitConfig();
3286
+ const session = await loadSession();
3287
+ const baseUrl = session?.apiBase ?? config.apiBase;
3028
3288
  const backend = await selectBackend();
3029
3289
  const tokenStore = await createCliTokenStore(backend);
3030
3290
  if (!tokenStore.get()) {
@@ -3036,16 +3296,137 @@ async function injectCommand(opts) {
3036
3296
  const unlocked = await obtainUnlockedKeys(api);
3037
3297
  await tokenStore.flush();
3038
3298
  const vaults = await listVaultHandles(api, unlocked);
3039
- const ctx = createResolveContext(api, vaults);
3040
- const uniqueRefs = {};
3041
- for (const ref of new Set(refByPlaceholder.values())) uniqueRefs[ref] = ref;
3042
- const resolved = await resolveRefsOrLiteral(uniqueRefs, ctx);
3043
- let output = template;
3044
- for (const [placeholder, ref] of refByPlaceholder) {
3045
- output = output.split(placeholder).join(resolved[ref]);
3299
+ const resolvedVaults = opts.vault.map((v) => resolveVaultByQuery(v, vaults));
3300
+ const vaultRefs = resolvedVaults.map((v) => ({ id: v.id, name: v.name, kind: v.kind }));
3301
+ const capabilities = opts.allowRead ? ["run", "inject", "read"] : ["run", "inject"];
3302
+ print("Fresh TOTP code required to create an agent profile (recovery codes are not accepted).");
3303
+ const totpCode = await promptTotpCode("TOTP code: ", NO_TTY_ERROR);
3304
+ let created;
3305
+ try {
3306
+ created = await api.createAgent({
3307
+ name,
3308
+ vault_ids: resolvedVaults.map((v) => v.id),
3309
+ capabilities,
3310
+ expires,
3311
+ totp_code: totpCode
3312
+ });
3313
+ } catch (err) {
3314
+ throw mapCreateError(err);
3315
+ }
3316
+ await saveAgentToken(name, {
3317
+ token: created.token,
3318
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
3319
+ vaults: vaultRefs,
3320
+ allowRead: !!opts.allowRead
3321
+ });
3322
+ print(`Agent profile "${created.name}" created (${created.capabilities.join("+")}).`);
3323
+ print(`Vaults: ${vaultRefs.map((v) => v.name).join(", ")}`);
3324
+ print(`Expires: ${created.expires_at ?? "never"}`);
3325
+ print(`Token stored locally (namespace: agent-token). Activate with GESLAR_AGENT=${created.name} or --agent ${created.name}.`);
3326
+ if (opts.showToken) {
3327
+ printErr("WARNING: printing the plaintext token \u2014 it will not be shown again. Treat it like a password.");
3328
+ process.stdout.write(`${created.token}
3329
+ `);
3330
+ }
3331
+ return EXIT.OK;
3332
+ } catch (err) {
3333
+ if (err instanceof CliError) {
3334
+ printErr(err.message);
3335
+ return err.exitCode;
3336
+ }
3337
+ printErr(err.message);
3338
+ return EXIT.GENERAL;
3339
+ }
3340
+ }
3341
+ function mapCreateError(err) {
3342
+ if (!(err instanceof ApiError)) {
3343
+ return new CliError(EXIT.GENERAL, err.message);
3344
+ }
3345
+ switch (err.code) {
3346
+ case "licence/feature-locked":
3347
+ return new CliError(EXIT.ENTITLEMENT, err.message);
3348
+ case "agent/name-exists":
3349
+ return new CliError(EXIT.GENERAL, err.message);
3350
+ case "agent/limit-reached":
3351
+ return new CliError(EXIT.GENERAL, err.message);
3352
+ case "mfa/setup-required":
3353
+ return new CliError(EXIT.AUTH, `${err.message} \u2014 enroll a TOTP authenticator first (console: Security settings)`);
3354
+ case "auth/mfa-invalid":
3355
+ return new CliError(EXIT.AUTH, "Invalid or expired TOTP code");
3356
+ case "vault/not-found":
3357
+ return new CliError(EXIT.UNRESOLVABLE_REF, err.message);
3358
+ default:
3359
+ return new CliError(EXIT.GENERAL, err.message);
3360
+ }
3361
+ }
3362
+
3363
+ // src/commands/agent-list.ts
3364
+ async function agentListCommand(opts) {
3365
+ try {
3366
+ requireHumanContext(opts.agent, "list");
3367
+ const config = await loadOrInitConfig();
3368
+ const session = await loadSession();
3369
+ const baseUrl = session?.apiBase ?? config.apiBase;
3370
+ const backend = await selectBackend();
3371
+ const tokenStore = await createCliTokenStore(backend);
3372
+ if (!tokenStore.get()) {
3373
+ printErr("not signed in \u2014 run `geslar signin`");
3374
+ return EXIT.AUTH;
3375
+ }
3376
+ const api = buildApiClient(baseUrl, tokenStore);
3377
+ const { agents } = await api.listAgents();
3378
+ await tokenStore.flush();
3379
+ if (agents.length === 0) {
3380
+ print("No agent profiles. Create one with `geslar agent create <name> --vault <name>`.");
3381
+ return EXIT.OK;
3382
+ }
3383
+ for (const a of agents) {
3384
+ const local = await loadAgentToken(a.name);
3385
+ const vaultsText = local ? local.vaults.map((v) => v.name).join(", ") : `${a.scoped_vault_count} vault(s) (not stored on this machine)`;
3386
+ const scopeNote = a.has_active_scope ? "" : " [no active scope]";
3387
+ print(`${a.name} (${a.status})${scopeNote}`);
3388
+ print(` Vaults: ${vaultsText}`);
3389
+ print(` Capabilities: ${a.capabilities.join("+")}`);
3390
+ print(` Expires: ${a.expires_at ?? "never"}`);
3391
+ print(` Last used: ${a.last_used_at ?? "(never)"}`);
3046
3392
  }
3047
- await writeFile7(opts.output, output, { mode: 384 });
3048
- print(`Written to ${opts.output}`);
3393
+ return EXIT.OK;
3394
+ } catch (err) {
3395
+ if (err instanceof CliError) {
3396
+ printErr(err.message);
3397
+ return err.exitCode;
3398
+ }
3399
+ printErr(err.message);
3400
+ return EXIT.GENERAL;
3401
+ }
3402
+ }
3403
+
3404
+ // src/commands/agent-revoke.ts
3405
+ async function agentRevokeCommand(name, opts) {
3406
+ try {
3407
+ requireHumanContext(opts.agent, "revoke");
3408
+ const config = await loadOrInitConfig();
3409
+ const session = await loadSession();
3410
+ const baseUrl = session?.apiBase ?? config.apiBase;
3411
+ const backend = await selectBackend();
3412
+ const tokenStore = await createCliTokenStore(backend);
3413
+ if (!tokenStore.get()) {
3414
+ printErr("not signed in \u2014 run `geslar signin`");
3415
+ return EXIT.AUTH;
3416
+ }
3417
+ const api = buildApiClient(baseUrl, tokenStore);
3418
+ const { agents } = await api.listAgents();
3419
+ await tokenStore.flush();
3420
+ const match = agents.find((a) => a.name === name);
3421
+ if (!match) {
3422
+ throw new CliError(EXIT.GENERAL, `No agent profile named "${name}" \u2014 run \`geslar agent list\` to see your profiles`);
3423
+ }
3424
+ try {
3425
+ await api.revokeAgent(match.id);
3426
+ } finally {
3427
+ await clearAgentToken(name);
3428
+ }
3429
+ print(`Agent profile "${name}" revoked. Local token cleared.`);
3049
3430
  return EXIT.OK;
3050
3431
  } catch (err) {
3051
3432
  if (err instanceof CliError) {
@@ -3059,7 +3440,11 @@ async function injectCommand(opts) {
3059
3440
 
3060
3441
  // src/index.ts
3061
3442
  var program = new Command();
3062
- program.name("geslar").description("Geslar Agentic Access CLI").enablePositionalOptions().version(CLI_VERSION);
3443
+ program.name("geslar").description("Geslar Agentic Access CLI").enablePositionalOptions().option("--agent <name>", "operate as this agent profile instead of your own account (spec-access-core.md \xA74)").version(CLI_VERSION);
3444
+ program.hook("preAction", (thisCommand) => {
3445
+ const agentOpt = thisCommand.opts()["agent"];
3446
+ if (agentOpt) process.env["GESLAR_AGENT"] = agentOpt;
3447
+ });
3063
3448
  program.command("signin").description("Sign in via device-flow (opens a code to enter at the console)").option("--api <url>", "override the API base URL").action(async (opts) => {
3064
3449
  process.exitCode = await signinCommand(opts);
3065
3450
  });
@@ -3092,6 +3477,16 @@ program.command("run").description("Run a command with geslar:// references reso
3092
3477
  program.command("inject").description("Substitute {{ geslar://... }} placeholders in a template file (fail-closed)").requiredOption("-i, --input <file>", "template file").requiredOption("-o, --output <file>", "output file (mode 0600)").action(async (opts) => {
3093
3478
  process.exitCode = await injectCommand(opts);
3094
3479
  });
3480
+ var agent = program.command("agent").description("Manage agent profiles \u2014 scoped machine credentials (spec-access-core.md)");
3481
+ agent.command("create").argument("<name>", "profile name").description("Create an agent profile scoped to one or more vaults (TTY required, fresh TOTP)").option("--vault <name>", "vault to grant access to (repeatable)", (val, prev) => [...prev, val], []).option("--allow-read", "opt-in: also grant the read capability (default is run+inject only)").option("--expires <duration>", 'e.g. 90d, or "never" (default: 90d)').option("--show-token", "print the plaintext token once (otherwise it only goes to local storage)").action(async (name, opts) => {
3482
+ process.exitCode = await agentCreateCommand(name, opts);
3483
+ });
3484
+ agent.command("list").description("List your agent profiles").action(async () => {
3485
+ process.exitCode = await agentListCommand({});
3486
+ });
3487
+ agent.command("revoke").argument("<name>", "profile name").description("Revoke an agent profile and clear its local token").action(async (name) => {
3488
+ process.exitCode = await agentRevokeCommand(name, {});
3489
+ });
3095
3490
  void (async () => {
3096
3491
  try {
3097
3492
  await program.parseAsync(process.argv);