passcontrol 1.2.1 → 1.4.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
@@ -154,14 +154,14 @@ in the generated configuration:
154
154
  passcontrol configure claude-desktop --write
155
155
  ```
156
156
 
157
- The cursor preset also writes configuration; claude-code prints its client-managed add command.
157
+ The cursor preset also writes configuration. `passcontrol configure claude-code --write` routes Claude Code's own model calls through the sidecar by merging two keys into its settings. `passcontrol configure codex --write` does the same for Codex with a profile file of its own, used as `codex --profile passcontrol`.
158
158
 
159
159
  The sidecar listens on loopback by default and substitutes a visa for the client's dummy
160
160
  API key. Treat access to that local listener as access to the configured agent. It is
161
161
  not a sandbox against other processes running as you. Its provider CONNECT requests are
162
162
  refused; use base URLs rather than TLS interception.
163
163
 
164
- Presets (from `cli/presets.mjs`): `generic`, `openhands`, `litellm`, `aider`, `hermes`, `cline`, `continue`, `chatbox`, `jan`, `msty`, `cherry-studio`, `open-webui`, `librechat`; service presets: `github`, `telegram`, `brave`, `notion`, `discord`; MCP presets: `claude-desktop`, `cursor`, `claude-code`. Compatibility still depends on the client using
164
+ Presets (from `cli/presets.mjs`): `generic`, `openhands`, `litellm`, `aider`, `hermes`, `cline`, `continue`, `chatbox`, `jan`, `msty`, `cherry-studio`, `open-webui`, `librechat`; service presets: `github`, `telegram`, `brave`, `notion`, `discord`; coding agent: `codex`; MCP presets: `claude-desktop`, `cursor`, `claude-code`. Compatibility still depends on the client using
165
165
  supported paths. [Hermes configuration](https://github.com/Vertias3u/PassControl/blob/main/docs/integrations/hermes.md).
166
166
 
167
167
  ## CLI configuration and key storage
@@ -325,6 +325,7 @@ All paths below are relative to `/api/v1/<provider>`. SDK base URLs and aliases
325
325
  | `deepseek` | OpenAI-compatible Chat Completions | Not proxied |
326
326
  | `gemini` | Google's **OpenAI-compatible** Chat Completions | Models list/detail |
327
327
  | `xai` | **POST Responses** only (legacy Chat Completions refused) | Models list/detail |
328
+ | `openrouter` | OpenRouter's Chat Completions, one key for its whole catalog; charged at the cost OpenRouter reports | Models list |
328
329
  | `azure` | Azure OpenAI v1: Chat Completions, **POST Responses** and **POST Embeddings**, at the resource address stored with the key | Models list |
329
330
  | `local` | A model server you run (Ollama, LM Studio, vLLM): Chat Completions at the address stored with the credential, self-host only | Models list |
330
331
 
@@ -90,6 +90,14 @@ import {
90
90
  import { isLocalGatewayOrigin, probeGatewayVersion, probeTimeoutMs } from "../cli/gateway-probe.mjs";
91
91
  import { dashboardOriginForOffset, portHolders, stackPortConflictMessage } from "../cli/local-stack.mjs";
92
92
  import { startSidecar } from "../cli/sidecar.mjs";
93
+ import {
94
+ claudeCodeEnv,
95
+ claudeCodeSettingsPath,
96
+ removeClaudeCodeSettings,
97
+ writeClaudeCodeSettings,
98
+ } from "../cli/claude-code.mjs";
99
+ import { statuslineText } from "../cli/statusline.mjs";
100
+ import { CODEX_PROFILE, codexProfilePath, codexProfileToml, codexStoresApiKey, removeCodexProfile, writeCodexProfile } from "../cli/codex.mjs";
93
101
  import { waitForGateway as awaitGateway } from "../cli/gateway-wait.mjs";
94
102
  import { loginCommand } from "../cli/login.mjs";
95
103
  import { logoutCommand } from "../cli/logout.mjs";
@@ -100,7 +108,7 @@ import {
100
108
  instanceKidFromSeed,
101
109
  retiredKeyEntry,
102
110
  } from "../cli/instance-key.mjs";
103
- import { FAILURE_REASONS, verifyAgentToken, verifyReceipt, verifyStatement } from "../cli/verify.mjs";
111
+ import { FAILURE_REASONS, verifyAgentToken, verifyReceipt, verifySession, verifyStatement } from "../cli/verify.mjs";
104
112
  import { compareProtocolSets } from "../cli/protocols.mjs";
105
113
  import { defaultAllowedModelForProvider } from "../cli/integration-defaults.mjs";
106
114
  import {
@@ -198,7 +206,7 @@ ${heading("Quick start")}
198
206
  ${cmd} login [--project] sign in through your browser and set this machine up
199
207
  ${cmd} call "hi" mint a visa and make a governed model call
200
208
  ${cmd} mcp passport identity for Claude Desktop, Cursor, Claude Code
201
- ${cmd} sidecar [--port 8788] [--allow-connect host[,host]]
209
+ ${cmd} sidecar [--port 8788] [--allow-connect host[,host]] [--ollama-port 11435] [--no-journal]
202
210
  passport identity for any tool that takes an api_key
203
211
 
204
212
  ${heading("Operate")}
@@ -229,6 +237,11 @@ ${heading("Manage")}
229
237
  show governed call logs
230
238
  ${cmd} statements [--limit 20] [--json]
231
239
  show the chain of signed spend statements
240
+ ${cmd} sessions [--agent ID] [--limit 20] [--json]
241
+ list Claude Code / Codex sessions (declared by the client)
242
+ ${cmd} seal <session> --agent ID [--out FILE]
243
+ ${cmd} statusline [--port 8788] one line for Claude Code's status line (configure claude-code --statusline)
244
+ sign one session; save the seal and its receipts
232
245
  ${cmd} kill on|off toggle the tenant kill switch
233
246
  ${cmd} export [--out FILE] save a workspace configuration snapshot
234
247
  ${cmd} import <file> [--confirm IMPORT]
@@ -2362,6 +2375,7 @@ async function sidecarCommand(rest, opts) {
2362
2375
  passportSecret,
2363
2376
  keyStorage,
2364
2377
  port: sidecarPort(opts),
2378
+ ollamaPort: opts.ollamaPort != null ? ollamaPort(opts) : null,
2365
2379
  host: String(opts.host ?? process.env.SIDECAR_HOST ?? "127.0.0.1"),
2366
2380
  // Named on the command line, never inferred. A sidecar reachable off-host
2367
2381
  // mints visas for whoever connects, so widening the bind is a decision the
@@ -2379,6 +2393,10 @@ async function sidecarCommand(rest, opts) {
2379
2393
  .map((entry) => entry.trim())
2380
2394
  .filter(Boolean),
2381
2395
  refreshSkewSeconds: Number(opts.refreshSkewSeconds ?? process.env.REFRESH_SKEW_SECONDS ?? 30),
2396
+ // The receipt-id journal (cli/journal.mjs) is on unless the flag says off.
2397
+ // A flag only, like --allow-non-loopback: whether this machine keeps a record
2398
+ // is the operator's to state, not a config file's.
2399
+ noJournal: opts.journal === false || Boolean(opts.noJournal),
2382
2400
  });
2383
2401
 
2384
2402
  if (opts.for) {
@@ -2402,6 +2420,27 @@ function sidecarPort(opts = {}) {
2402
2420
  return port;
2403
2421
  }
2404
2422
 
2423
+ /**
2424
+ * The agent's budget as one line, read through the running sidecar (cli/statusline.mjs).
2425
+ * Never throws: whatever happens, Claude Code gets one line and a clean exit.
2426
+ */
2427
+ async function statuslineCommand(opts) {
2428
+ try {
2429
+ const port = sidecarPort(opts);
2430
+ const cacheFile = path.join(path.dirname(globalConfigPath()), `statusline-${port}.json`);
2431
+ return await statuslineText({ port, cacheFile });
2432
+ } catch (error) {
2433
+ return `PassControl · ${error instanceof Error && /--port/.test(error.message) ? "bad --port" : "unavailable"}`;
2434
+ }
2435
+ }
2436
+
2437
+ /** The command Claude Code's settings run: the installed binary, or this checkout's. */
2438
+ function statusLineSettingsCommand(port) {
2439
+ const args = `statusline --port ${port}`;
2440
+ if (process.env.npm_lifecycle_event !== "cli") return `passcontrol ${args}`;
2441
+ return `node ${JSON.stringify(CLI_ENTRY)} ${args}`;
2442
+ }
2443
+
2405
2444
  function sidecarBaseUrl(opts = {}) {
2406
2445
  const provider = String(opts.provider || config.provider);
2407
2446
  assertProvider(provider);
@@ -2442,11 +2481,14 @@ function passControlMcpEntry() {
2442
2481
  return mcpServerEntry({ cliPath: CLI_ENTRY });
2443
2482
  }
2444
2483
 
2445
- function printMcpPreset(integration) {
2484
+ function printMcpPreset(integration, opts = {}) {
2446
2485
  requireGlobalMcpPassport();
2447
2486
  if (integration === "claude-code") {
2448
- console.log("# Add PassControl to Claude Code:");
2449
- console.log(CLAUDE_CODE_ADD_COMMAND);
2487
+ const { baseUrl } = sidecarBaseUrl({ ...opts, provider: "anthropic" });
2488
+ console.log("# Route Claude Code's model calls through the sidecar (start it first):");
2489
+ printExports(Object.entries(claudeCodeEnv(baseUrl)));
2490
+ console.log("# Optional: also add PassControl's chat tool to Claude Code:");
2491
+ console.log(`# ${CLAUDE_CODE_ADD_COMMAND}`);
2450
2492
  return;
2451
2493
  }
2452
2494
 
@@ -2455,10 +2497,40 @@ function printMcpPreset(integration) {
2455
2497
  console.log(JSON.stringify(mcpServersDocument(passControlMcpEntry()), null, 2));
2456
2498
  }
2457
2499
 
2500
+ /** The Ollama listener's port: `--ollama-port N`, or 11435 when the flag has no number. */
2501
+ const DEFAULT_OLLAMA_PORT = 11435;
2502
+ function ollamaPort(opts = {}) {
2503
+ const raw = opts.ollamaPort;
2504
+ if (raw == null || raw === true) return DEFAULT_OLLAMA_PORT;
2505
+ const port = Number(raw);
2506
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
2507
+ throw new Error(`--ollama-port must be a port number (1-65535), not "${raw}".`);
2508
+ }
2509
+ return port;
2510
+ }
2511
+
2512
+ function printOllamaPreset(opts = {}) {
2513
+ const port = ollamaPort(opts);
2514
+ const host = String(opts.host ?? process.env.SIDECAR_HOST ?? "127.0.0.1");
2515
+ console.log("# Apps that only take OLLAMA_HOST: point them at PassControl's Ollama listener.");
2516
+ printExports([["OLLAMA_HOST", `${host}:${port}`]]);
2517
+ console.log(`# Start it with: ${cliCommand(`sidecar --ollama-port${port === DEFAULT_OLLAMA_PORT ? "" : ` ${port}`}`)}`);
2518
+ console.log("# Calls go to the workspace's `local` model server (Settings → Models on this machine).");
2519
+ console.log("# Local models have no price: give the agent a token budget, not a dollar limit.");
2520
+ }
2521
+
2458
2522
  function printAgentPreset(name = "generic", opts = {}) {
2459
2523
  const preset = name.toLowerCase();
2460
2524
  if (isMcpIntegration(preset)) {
2461
- printMcpPreset(preset);
2525
+ printMcpPreset(preset, opts);
2526
+ return;
2527
+ }
2528
+ if (preset === "ollama") {
2529
+ printOllamaPreset(opts);
2530
+ return;
2531
+ }
2532
+ if (preset === "codex") {
2533
+ printCodexPreset(opts);
2462
2534
  return;
2463
2535
  }
2464
2536
 
@@ -2563,19 +2635,113 @@ function aiderConfig(opts = {}) {
2563
2635
  ].join("\n");
2564
2636
  }
2565
2637
 
2638
+ /**
2639
+ * Claude Code's own model calls, through the sidecar (cli/claude-code.mjs). The
2640
+ * project's settings by default; `--global` for every session; `--remove` takes
2641
+ * PassControl's two keys back out. The MCP chat tool stays a separate command
2642
+ * Claude Code owns.
2643
+ */
2644
+ function configureClaudeCode(opts = {}) {
2645
+ const scope = opts.global ? "user" : "project";
2646
+ const target = claudeCodeSettingsPath({ scope });
2647
+ if (opts.remove) {
2648
+ const result = removeClaudeCodeSettings({ target });
2649
+ if (result.changed) ok(`removed PassControl from ${target}`);
2650
+ else step(`${target} has no PassControl entry; nothing to remove.`);
2651
+ return;
2652
+ }
2653
+ const { baseUrl, port } = sidecarBaseUrl({ ...opts, provider: "anthropic" });
2654
+ console.log(`Preview: ${target}\n\n${JSON.stringify({ env: claudeCodeEnv(baseUrl) }, null, 2)}`);
2655
+ if (!opts.write) {
2656
+ step(`Dry run only. Re-run with \`--write\` to merge these two keys${scope === "project" ? " (or --write --global for every session)" : ""}.`);
2657
+ } else {
2658
+ const result = writeClaudeCodeSettings({
2659
+ target,
2660
+ baseUrl,
2661
+ force: Boolean(opts.force),
2662
+ statusLineCommand: opts.statusline ? statusLineSettingsCommand(port) : null,
2663
+ });
2664
+ if (!result.changed) ok(`${target} already routes Claude Code through PassControl`);
2665
+ else {
2666
+ if (result.backupPath) step(`backed up ${result.backupPath}`);
2667
+ ok(`wrote ${target}`);
2668
+ }
2669
+ if (result.statusLine?.existing) {
2670
+ warn(`${target} already has a status line (${result.statusLine.existing}); it was left as it is. To show the budget there, add \`${statusLineSettingsCommand(port)}\` to it yourself.`);
2671
+ } else if (result.statusLine?.changed) ok("added the agent's budget to Claude Code's status line");
2672
+ if (result.rawKeyFound) {
2673
+ warn(`${target} also holds a raw ANTHROPIC_API_KEY. PassControl does not need it there; remove it so no key sits on disk.`);
2674
+ }
2675
+ }
2676
+ if (opts.statusline && !opts.write) {
2677
+ step(`With --write, the status line would run: ${statusLineSettingsCommand(port)}`);
2678
+ } else if (!opts.statusline) {
2679
+ step(`Optional, the agent's budget in Claude Code's status line: ${cliCommand(`configure claude-code --write --statusline${scope === "user" ? " --global" : ""}`)}`);
2680
+ }
2681
+ step(`Start the sidecar before Claude Code: ${cliCommand(port === 8788 ? "sidecar" : `sidecar --port ${port}`)}`);
2682
+ step("The agent's Anthropic scope must allow the models Claude Code uses (its main model, and Haiku for small tasks).");
2683
+ step(`Optional, the chat tool as well: ${CLAUDE_CODE_ADD_COMMAND}`);
2684
+ step(`To undo: ${cliCommand(`configure claude-code --remove${scope === "user" ? " --global" : ""}`)}`);
2685
+ }
2686
+
2687
+ /**
2688
+ * Codex speaks only OpenAI's Responses API, so its profile always points at the
2689
+ * sidecar's OpenAI route. A model is written only when one is named with
2690
+ * --model; otherwise Codex keeps the model its own config chose.
2691
+ */
2692
+ function codexSettings(opts = {}) {
2693
+ if (opts.provider != null && String(opts.provider).toLowerCase() !== "openai") {
2694
+ throw new Error(`Codex goes through PassControl's OpenAI route only, not "${opts.provider}". Drop --provider.`);
2695
+ }
2696
+ const { baseUrl, port } = sidecarBaseUrl({ ...opts, provider: "openai" });
2697
+ const model = typeof opts.model === "string" && opts.model ? opts.model : undefined;
2698
+ return { baseUrl, port, model };
2699
+ }
2700
+
2701
+ function printCodexPreset(opts = {}) {
2702
+ const { baseUrl, model } = codexSettings(opts);
2703
+ console.log(`# Save as ${codexProfilePath()} (or run: ${cliCommand("configure codex --write")}):`);
2704
+ console.log(codexProfileToml({ baseUrl, model }).trimEnd());
2705
+ }
2706
+
2707
+ /**
2708
+ * Codex's own model calls, through the sidecar (cli/codex.mjs): a profile file
2709
+ * Codex layers over its config when started with `--profile passcontrol`.
2710
+ * `--remove` deletes that file, and only when PassControl wrote it.
2711
+ */
2712
+ function configureCodex(opts = {}) {
2713
+ const target = codexProfilePath();
2714
+ if (opts.remove) {
2715
+ const result = removeCodexProfile({ target });
2716
+ if (result.changed) ok(`removed ${target}`);
2717
+ else step(`${target} is not a profile PassControl wrote; nothing to remove.`);
2718
+ return;
2719
+ }
2720
+ const { baseUrl, port, model } = codexSettings(opts);
2721
+ console.log(`Preview: ${target}\n\n${codexProfileToml({ baseUrl, model })}`);
2722
+ if (!opts.write) {
2723
+ step("Dry run only. Re-run with `--write` to create this profile. Codex's config.toml is not touched.");
2724
+ } else {
2725
+ const result = writeCodexProfile({ target, baseUrl, model, force: Boolean(opts.force) });
2726
+ if (!result.changed) ok(`${target} already routes Codex through PassControl`);
2727
+ else {
2728
+ if (result.backupPath) step(`backed up ${result.backupPath}`);
2729
+ ok(`wrote ${target}`);
2730
+ }
2731
+ if (codexStoresApiKey()) {
2732
+ warn("Codex also keeps an OpenAI API key of its own (auth.json). The PassControl profile never sends it, but plain `codex` does; `codex logout` removes it.");
2733
+ }
2734
+ }
2735
+ step(`Start the sidecar first: ${cliCommand(port === 8788 ? "sidecar" : `sidecar --port ${port}`)}`);
2736
+ step(`Then run Codex with the profile: codex --profile ${CODEX_PROFILE} (plain \`codex\` still goes straight to OpenAI)`);
2737
+ step("The agent's OpenAI scope must allow the model Codex uses (set with -m, or `model` in Codex's config).");
2738
+ step(`To undo: ${cliCommand("configure codex --remove")}`);
2739
+ }
2740
+
2566
2741
  function configureMcpClient(integration, opts = {}) {
2567
2742
  requireGlobalMcpPassport();
2568
2743
  if (integration === "claude-code") {
2569
- // Claude Code owns its MCP registry through its own CLI, so there is no
2570
- // config file for us to merge into. `--write` used to be accepted here and
2571
- // silently do nothing — refuse it and hand back the command that works.
2572
- if (opts.write) {
2573
- throw new Error(
2574
- `Claude Code manages MCP servers through its own CLI, so there is no file to write. Run:\n ${CLAUDE_CODE_ADD_COMMAND}`
2575
- );
2576
- }
2577
- console.log("Claude Code manages MCP servers through its CLI. Run:");
2578
- console.log(CLAUDE_CODE_ADD_COMMAND);
2744
+ configureClaudeCode(opts);
2579
2745
  return;
2580
2746
  }
2581
2747
 
@@ -2609,6 +2775,10 @@ async function configureCommand(rest, opts = {}) {
2609
2775
  `Unknown integration "${integration}". Use one of: ${integrationChoices()}.`
2610
2776
  );
2611
2777
  }
2778
+ if (integration === "codex") {
2779
+ configureCodex(opts);
2780
+ return;
2781
+ }
2612
2782
  if (isMcpIntegration(integration)) {
2613
2783
  configureMcpClient(integration, opts);
2614
2784
  return;
@@ -2912,11 +3082,12 @@ async function verifyCommand(rest, opts) {
2912
3082
  const artifact = rest[1];
2913
3083
  const issuer = String(opts.issuer || process.env.PASSCONTROL_ISSUER || "");
2914
3084
 
2915
- if ((what !== "token" && what !== "receipt" && what !== "statement") || !artifact) {
3085
+ if ((what !== "token" && what !== "receipt" && what !== "statement" && what !== "session") || !artifact) {
2916
3086
  throw new Error(
2917
3087
  "Usage: passcontrol verify token <jwt> --audience <aud> --issuer <origin>\n" +
2918
3088
  " passcontrol verify receipt <jws> --issuer <origin>\n" +
2919
- " passcontrol verify statement <jws> --issuer <origin>"
3089
+ " passcontrol verify statement <jws> --issuer <origin>\n" +
3090
+ " passcontrol verify session <seal.json> [--journal <file>[,<file>]] --issuer <origin>"
2920
3091
  );
2921
3092
  }
2922
3093
  if (!issuer) {
@@ -2926,6 +3097,11 @@ async function verifyCommand(rest, opts) {
2926
3097
  );
2927
3098
  }
2928
3099
 
3100
+ if (what === "session") {
3101
+ await verifySessionCommand(artifact, opts, issuer);
3102
+ return;
3103
+ }
3104
+
2929
3105
  const result =
2930
3106
  what === "token"
2931
3107
  ? await verifyAgentToken(artifact, { issuer, audience: String(opts.audience || "") })
@@ -2975,6 +3151,17 @@ async function verifyCommand(rest, opts) {
2975
3151
  step(`Verdict: ${c.res?.status} (HTTP ${c.res?.http})`);
2976
3152
  step(`Usage: ${c.use?.in ?? 0} in / ${c.use?.out ?? 0} out · ${c.cost ?? 0} µ¢`);
2977
3153
  if (c.req) step(`Request: ${c.req.alg} ${c.req.dig} (${c.req.len} bytes)`);
3154
+ // Lineage is DECLARED by the client: any local process can send those
3155
+ // headers. Say so on the same line, so nobody reads it as passport-proven.
3156
+ // Printable ASCII only: a signed value is still not a terminal's to obey.
3157
+ if (c.ctx?.ses) {
3158
+ const shown = (v) => String(v).replace(/[^\x20-\x7e]/g, "?").slice(0, 128);
3159
+ const who = c.ctx.agt
3160
+ ? `sub-agent ${shown(c.ctx.agt)}${c.ctx.par ? `, spawned by ${shown(c.ctx.par)}` : ""}`
3161
+ : "main agent";
3162
+ step(`Session: ${shown(c.ctx.ses)} · ${who}`);
3163
+ step(` declared by the client (${shown(c.ctx.cli ?? "unknown")}), not verified`);
3164
+ }
2978
3165
  }
2979
3166
  if (c.own) {
2980
3167
  step(
@@ -2983,6 +3170,184 @@ async function verifyCommand(rest, opts) {
2983
3170
  }
2984
3171
  }
2985
3172
 
3173
+ // ── Session seals (sprint Q7) ───────────────────────────────────────────────
3174
+
3175
+ const SESSION_ARG_RE = /^[A-Za-z0-9._:-]{1,128}$/;
3176
+ const shown = (v) => String(v ?? "").replace(/[^\x20-\x7e]/g, "?").slice(0, 128);
3177
+
3178
+ /** The journal files the sidecar wrote (cli/journal.mjs): one JSON object per line. */
3179
+ function readJournals(spec) {
3180
+ const entries = [];
3181
+ for (const file of String(spec).split(",").map((f) => f.trim()).filter(Boolean)) {
3182
+ const text = fs.readFileSync(file, "utf8");
3183
+ for (const line of text.split("\n")) {
3184
+ if (!line.trim()) continue;
3185
+ try {
3186
+ entries.push(JSON.parse(line));
3187
+ } catch {
3188
+ // An unreadable line is passed through as-is, so the verifier reports the
3189
+ // journal as malformed instead of this command quietly skipping a call.
3190
+ entries.push(line);
3191
+ }
3192
+ }
3193
+ }
3194
+ return entries;
3195
+ }
3196
+
3197
+ async function verifySessionCommand(file, opts, issuer) {
3198
+ let parsed;
3199
+ try {
3200
+ parsed = JSON.parse(fs.readFileSync(String(file), "utf8"));
3201
+ } catch (e) {
3202
+ fail(`Could not read ${shown(file)}: ${e.message}`);
3203
+ process.exitCode = 1;
3204
+ return;
3205
+ }
3206
+ // Accepts the control API's response as saved ({ data: { seal, bundle } }) or
3207
+ // just { seal, bundle }, which is what `passcontrol seal` writes.
3208
+ const doc = parsed?.data && typeof parsed.data === "object" ? parsed.data : parsed;
3209
+ const journal = opts.journal && opts.journal !== true ? readJournals(opts.journal) : undefined;
3210
+ const r = await verifySession({ seal: doc?.seal, bundle: doc?.bundle, journal }, { issuer });
3211
+
3212
+ if (!r.checks.signature) {
3213
+ fail(`Not valid: ${FAILURE_REASONS[r.reason] ?? r.reason}`);
3214
+ process.exitCode = 1;
3215
+ return;
3216
+ }
3217
+ const c = r.claims;
3218
+ (r.ok ? ok : fail)(r.ok ? "Session seal is valid." : "Session seal did not pass every check.");
3219
+ step(`Issuer: ${shown(c.iss)}`);
3220
+ step(`Agent: ${shown(c.sub)}`);
3221
+ step(`Session: ${shown(c.ses?.id)} · declared by the client (${shown(c.ses?.src)}), not verified`);
3222
+ step(`Window: ${new Date(c.per?.from * 1000).toISOString()} → ${new Date(c.per?.to * 1000).toISOString()}`);
3223
+ step(`Covers: ${c.n} of ${c.nr} logged calls · ${c.cost} µ¢`);
3224
+ if (c.unp) step(` ${c.unp} call(s) could not be priced: that cost is unknown, not zero.`);
3225
+ if (c.unk) step(` ${c.unk} call(s) have no recorded cost and no recorded reason.`);
3226
+ for (const node of Array.isArray(c.tree) ? c.tree : []) {
3227
+ const who = node.agt ? `sub-agent ${shown(node.agt)}${node.par ? ` (spawned by ${shown(node.par)})` : ""}` : "main agent";
3228
+ step(` ${who}: ${node.n} call(s), ${node.cost} µ¢${node.refused ? `, ${node.refused} refused` : ""}`);
3229
+ }
3230
+ step("");
3231
+
3232
+ ok("Signature matches the issuer's published key");
3233
+ if (r.checks.bundle) ok(`Bundle: the root and every total recompute from its ${doc.bundle.length} receipt(s)`);
3234
+ else fail(`Bundle: these do not match the receipts it came with: ${r.mismatched.join(", ") || r.reason}`);
3235
+ if (r.checks.receipts === null) step("Receipts: not checked");
3236
+ else if (r.checks.receipts) ok("Receipts: every one verifies and belongs to this agent, session and window");
3237
+ else {
3238
+ fail(`Receipts: ${r.rejected.length} not accepted`);
3239
+ for (const x of r.rejected) step(` #${x.index} ${shown(x.id ?? "?")}: ${FAILURE_REASONS[x.reason] ?? x.reason}`);
3240
+ }
3241
+
3242
+ if (r.checks.journal === null) {
3243
+ step("No journal given. Without your own record this proves no more than a statement does:");
3244
+ step(" that the issuer committed to these receipts, not that it left none out.");
3245
+ step(" Pass --journal with the file your sidecar printed when it started.");
3246
+ } else if (r.reason === "malformed_journal") {
3247
+ fail("Journal: could not be read as a list of receipt ids.");
3248
+ } else if (r.checks.journal) {
3249
+ ok("Journal: every call your sidecar recorded is in the seal");
3250
+ } else {
3251
+ fail(`Journal: ${r.missing.length} call(s) your sidecar recorded are missing from the seal:`);
3252
+ for (const id of r.missing) step(` ${shown(id)}`);
3253
+ step(" Missing means not in this seal. The gateway's log write can fail on its own,");
3254
+ step(" so a missing call can be a lost record as easily as one left out.");
3255
+ }
3256
+ if (r.otherSessions) {
3257
+ step(`Your journal also holds ${r.otherSessions} call(s) from other sessions of the same sidecar run; not checked against this seal.`);
3258
+ }
3259
+ if (r.unjournaled.length) {
3260
+ step(`In the seal but not in your journal (reported, not a failure): ${r.unjournaled.length}`);
3261
+ for (const x of r.unjournaled) {
3262
+ step(` ${shown(x.id)}${x.why === "failover_predecessor" ? " (an earlier attempt of a failed-over call)" : ""}`);
3263
+ }
3264
+ }
3265
+ if (!r.ok) process.exitCode = 1;
3266
+ }
3267
+
3268
+ async function sealCommand(rest, opts) {
3269
+ const session = rest[0];
3270
+ if (!session || !SESSION_ARG_RE.test(session)) {
3271
+ throw new Error("Usage: passcontrol seal <session> --agent <agent-id> [--out FILE]");
3272
+ }
3273
+ if (!opts.agent || opts.agent === true) {
3274
+ throw new Error("Name the agent: passcontrol seal <session> --agent <agent-id> (see `passcontrol sessions`).");
3275
+ }
3276
+ let data;
3277
+ try {
3278
+ data = await api("POST", `/sessions/${encodeURIComponent(session)}/seal`, { agent_id: String(opts.agent) });
3279
+ } catch (e) {
3280
+ // api() leads with the status, then the error code. The route's own 404 carries
3281
+ // `not_found`; a gateway without the route (self-host: sealing is a hosted
3282
+ // capability, the format and verifier are not) answers with no code at all.
3283
+ const message = String(e?.message || "");
3284
+ if (/^404 not_found\b/.test(message)) {
3285
+ throw new Error(`No session ${session} for agent ${opts.agent} on this gateway (see \`passcontrol sessions\`).`);
3286
+ }
3287
+ if (/^404\b/.test(message)) {
3288
+ throw new Error(
3289
+ "This gateway does not seal sessions. Sealing is a hosted capability; checking a seal works anywhere:\n" +
3290
+ " passcontrol verify session <seal.json> --journal <file> --issuer <origin>"
3291
+ );
3292
+ }
3293
+ throw e;
3294
+ }
3295
+ const file = String(opts.out && opts.out !== true ? opts.out : `session-${session}.seal.json`);
3296
+ // It is spend and call volume: owner-only, like the journal it is checked against.
3297
+ fs.writeFileSync(file, JSON.stringify({ seal: data.seal, bundle: data.bundle }, null, 2) + "\n", { mode: 0o600 });
3298
+ fs.chmodSync(file, 0o600);
3299
+ ok(`Sealed ${data.bundle?.length ?? 0} receipt(s) → ${file}`);
3300
+ // The issuer the seal names, not the gateway just called: the two can differ (a
3301
+ // self-host behind a proxy), and the issuer is the one a verifier must trust.
3302
+ // Read without verifying, only to print a suggestion; `verify session` checks it.
3303
+ let issuer = requireControlGateway(config);
3304
+ try {
3305
+ const claims = JSON.parse(Buffer.from(String(data.seal).split(".")[1] ?? "", "base64url").toString("utf8"));
3306
+ if (typeof claims?.iss === "string") issuer = shown(claims.iss);
3307
+ } catch {
3308
+ // Not a JWS: verify session will say so. Keep the gateway as the suggestion.
3309
+ }
3310
+ step(`Check it: passcontrol verify session ${file} --journal <your sidecar journal> --issuer ${issuer}`);
3311
+ }
3312
+
3313
+ async function sessionsCommand(opts) {
3314
+ let rows;
3315
+ try {
3316
+ rows = await api(
3317
+ "GET",
3318
+ controlPath("/sessions", { agent_id: opts.agent === true ? undefined : opts.agent, limit: safeLimit(opts.limit) })
3319
+ );
3320
+ } catch (e) {
3321
+ if (/^404\b/.test(String(e?.message || ""))) {
3322
+ step("This gateway does not serve sessions. Verifying a seal works anywhere:");
3323
+ step(" passcontrol verify session <seal.json> --journal <file> --issuer <origin>");
3324
+ return;
3325
+ }
3326
+ throw e;
3327
+ }
3328
+ if (opts.json) {
3329
+ console.log(JSON.stringify(rows, null, 2));
3330
+ return;
3331
+ }
3332
+ if (!Array.isArray(rows) || rows.length === 0) {
3333
+ step("No sessions yet. Calls appear here once Claude Code or Codex (or a sidecar run) declares one.");
3334
+ return;
3335
+ }
3336
+ step("Sessions are declared by the client: they group calls, they do not prove who made them.");
3337
+ console.table(
3338
+ rows.map((row) => ({
3339
+ session: shown(row.session_id).slice(0, 36),
3340
+ via: row.client_kind,
3341
+ agent: String(row.agent_id ?? "").slice(0, 8),
3342
+ calls: row.calls,
3343
+ "sub-agents": row.subagents,
3344
+ refused: row.refused,
3345
+ cost: usd(row.cost_microcents) + (Number(row.unknown_cost) ? ` + ${row.unknown_cost} unknown` : ""),
3346
+ last: String(row.last_at ?? "").slice(0, 19),
3347
+ }))
3348
+ );
3349
+ }
3350
+
2986
3351
  /**
2987
3352
  * The chain of signed spend statements for this workspace.
2988
3353
  *
@@ -3825,6 +4190,14 @@ async function main(argv = process.argv.slice(2), runtime = {}) {
3825
4190
  const { opts, rest } = parseArgv(argv);
3826
4191
  const [command, ...commandRest] = rest;
3827
4192
 
4193
+ // First, before the update check or anything else that could print or wait:
4194
+ // Claude Code shows this command's whole stdout as its status line, runs it
4195
+ // after every assistant message, and cancels a run that is still going.
4196
+ if (command === "statusline") {
4197
+ console.log(await statuslineCommand(opts));
4198
+ return;
4199
+ }
4200
+
3828
4201
  // Started here and awaited at the very end, so the registry lookup overlaps
3829
4202
  // the command instead of being tacked onto the exit. On anything that touches
3830
4203
  // the network — which is most of this CLI — it costs nothing measurable, and
@@ -3954,6 +4327,12 @@ async function main(argv = process.argv.slice(2), runtime = {}) {
3954
4327
  case "statements":
3955
4328
  await statementsCommand(opts);
3956
4329
  break;
4330
+ case "sessions":
4331
+ await sessionsCommand(opts);
4332
+ break;
4333
+ case "seal":
4334
+ await sealCommand(commandRest, opts);
4335
+ break;
3957
4336
  case "kill":
3958
4337
  await killCommand(commandRest);
3959
4338
  break;
@@ -0,0 +1,76 @@
1
+ // How an agent's limits read to a person: the MCP `budget` tool and
2
+ // `passcontrol statusline`, both fed by the gateway's GET /api/v1/self.
3
+ //
4
+ // Money arrives as integer microcents (1 USD = 100,000,000). Unknown is "?" and
5
+ // never "$0.00"; no limit says so; a real amount under a cent is "<$0.01".
6
+
7
+ const MICROCENTS_PER_USD = 100_000_000;
8
+ const MICROCENTS_PER_CENT = 1_000_000;
9
+
10
+ /** Microcents as dollars, or "?" when the count could not be read. */
11
+ export function formatUsd(microcents) {
12
+ if (microcents === null || microcents === undefined || !Number.isFinite(Number(microcents))) return "?";
13
+ const value = Number(microcents);
14
+ if (value > 0 && value < MICROCENTS_PER_CENT) return "<$0.01";
15
+ const dollars = Math.round(value / MICROCENTS_PER_CENT) / 100;
16
+ return `$${dollars.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
17
+ }
18
+
19
+ /** A token count the way a status line has room for: 950, 12.3k, 1.2M. */
20
+ function formatTokens(n) {
21
+ if (n === null || n === undefined || !Number.isFinite(Number(n))) return "?";
22
+ const v = Number(n);
23
+ if (v >= 1_000_000) return `${trim(v / 1_000_000)}M`;
24
+ if (v >= 1_000) return `${trim(v / 1_000)}k`;
25
+ return String(v);
26
+ }
27
+ const trim = (v) => (Math.round(v * 10) / 10).toString();
28
+
29
+ function resetsIn(seconds) {
30
+ const s = Number(seconds);
31
+ if (!Number.isFinite(s) || s <= 0) return null;
32
+ if (s >= 86_400) return `${Math.round(s / 86_400)}d`;
33
+ if (s >= 3_600) return `${Math.round(s / 3_600)}h`;
34
+ return `${Math.max(1, Math.round(s / 60))}m`;
35
+ }
36
+
37
+ const PERIOD_WORD = { day: "today", month: "this month" };
38
+ const PERIOD_LABEL = { day: "Today", month: "This month" };
39
+
40
+ /** One line for Claude Code's status line. The most pressing limit wins. */
41
+ export function statusLine(self) {
42
+ const b = self?.budget ?? {};
43
+ const prefix = "PassControl · ";
44
+ if (b.period && b.period.unknown) return `${prefix}limit unknown`;
45
+ if (b.period) {
46
+ return `${prefix}${formatUsd(b.period.used_microcents)} of ${formatUsd(b.period.limit_microcents)} ${PERIOD_WORD[b.period.kind] ?? ""}`.trimEnd();
47
+ }
48
+ if (b.cost) return `${prefix}${formatUsd(b.cost.used_microcents)} of ${formatUsd(b.cost.limit_microcents)} total`;
49
+ if (b.tokens) return `${prefix}${formatTokens(b.tokens.used)} of ${formatTokens(b.tokens.limit)} tokens`;
50
+ return `${prefix}no limit`;
51
+ }
52
+
53
+ /** Every limit, with what is left: the MCP tool's text answer. */
54
+ export function budgetLines(self) {
55
+ const b = self?.budget ?? {};
56
+ const lines = [];
57
+ if (b.period && b.period.unknown) {
58
+ lines.push("The periodic spending limit could not be read right now.");
59
+ } else if (b.period) {
60
+ const reset = resetsIn(b.period.resets_in_seconds);
61
+ lines.push(
62
+ `${PERIOD_LABEL[b.period.kind] ?? "This period"}: ${formatUsd(b.period.used_microcents)} of ${formatUsd(b.period.limit_microcents)} used, ` +
63
+ `${formatUsd(b.period.remaining_microcents)} left${reset ? ` (resets in ${reset})` : ""}.`
64
+ );
65
+ }
66
+ if (b.cost) {
67
+ lines.push(
68
+ `Lifetime: ${formatUsd(b.cost.used_microcents)} of ${formatUsd(b.cost.limit_microcents)} used, ${formatUsd(b.cost.remaining_microcents)} left.`
69
+ );
70
+ }
71
+ if (b.tokens) {
72
+ lines.push(`Tokens: ${formatTokens(b.tokens.used)} of ${formatTokens(b.tokens.limit)} used, ${formatTokens(b.tokens.remaining)} left.`);
73
+ }
74
+ if (lines.length === 0) lines.push("No spending or token limit is set for this agent.");
75
+ return lines;
76
+ }