passcontrol 1.4.0 → 1.5.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/LICENSE CHANGED
@@ -8,7 +8,9 @@ License text copyright © 2017 MariaDB Corporation Ab, All Rights Reserved.
8
8
  Parameters
9
9
 
10
10
  Licensor: Kristiyan Ivanov, operating under the Vertias name
11
- Licensed Work: PassControl
11
+ Licensed Work: PassControl, excluding the plugins/passcontrol/ directory,
12
+ which is licensed under the MIT License (see the
13
+ LICENSE file in that directory).
12
14
  The Licensed Work is © 2026 Kristiyan Ivanov.
13
15
  Additional Use Grant: You may make production use of the Licensed Work, provided
14
16
  that you do not offer the Licensed Work to third parties as
package/README.md CHANGED
@@ -19,7 +19,8 @@ not passport-signed. Both go through gateway controls.
19
19
 
20
20
  Built by one developer under [Vertias](https://vertias.eu). Early software, **not
21
21
  independently audited**. Start with a non-critical provider key. Source-available under
22
- [BSL 1.1](./LICENSE).
22
+ [BSL 1.1](./LICENSE), except the Claude Code plugin in
23
+ [`plugins/passcontrol/`](https://github.com/Vertias3u/PassControl/tree/main/plugins/passcontrol), which is MIT.
23
24
 
24
25
  ## Cloud
25
26
 
@@ -129,6 +130,7 @@ its scope and suitable budgets. Choose by what your client supports:
129
130
  | Your JS/TS code | `PassControl` from `passcontrol/sdk`; [SDK guide](https://github.com/Vertias3u/PassControl/blob/main/docs/integrations/passport-sdk.md) |
130
131
  | Static-key client needing Passport | `passcontrol sidecar`, then `passcontrol env <integration>` |
131
132
  | MCP client | `passcontrol mcp`; configure as below |
133
+ | Coding agent | [Claude Code](https://github.com/Vertias3u/PassControl/blob/main/docs/integrations/claude-code.md), [Codex](https://github.com/Vertias3u/PassControl/blob/main/docs/integrations/codex.md), [OpenRouter](https://github.com/Vertias3u/PassControl/blob/main/docs/integrations/openrouter.md), [Ollama](https://github.com/Vertias3u/PassControl/blob/main/docs/integrations/ollama.md) |
132
134
 
133
135
  Direct Agent Keys point the client at the PassControl gateway origin. Passport Sidecar clients
134
136
  point at loopback with a provider path (for example `http://127.0.0.1:8788/api/v1/anthropic`) and the sidecar forwards to the gateway.
@@ -161,6 +163,13 @@ API key. Treat access to that local listener as access to the configured agent.
161
163
  not a sandbox against other processes running as you. Its provider CONNECT requests are
162
164
  refused; use base URLs rather than TLS interception.
163
165
 
166
+ To see each call as it happens, run `passcontrol watch` beside the agent (`--port` for a
167
+ sidecar that is not on 8788). It is a read-only, full-screen board: one row per call the
168
+ sidecar relays, with its time, declared session and sub-agent, model, BOARDED or DENIED
169
+ (with the gateway's refusal code), and latency, under the agent's budget. It reads a feed
170
+ on the sidecar's own loopback port, held in memory and never written to disk. A call that
171
+ does not go through that sidecar is not on it, and the board cannot stop anything.
172
+
164
173
  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
174
  supported paths. [Hermes configuration](https://github.com/Vertias3u/PassControl/blob/main/docs/integrations/hermes.md).
166
175
 
@@ -90,13 +90,15 @@ 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 { listProfiles, profilePath, readProfile, TOOL_PROFILE_PORTS, writeProfile } from "../cli/profiles.mjs";
93
94
  import {
94
95
  claudeCodeEnv,
95
96
  claudeCodeSettingsPath,
96
97
  removeClaudeCodeSettings,
97
98
  writeClaudeCodeSettings,
98
99
  } from "../cli/claude-code.mjs";
99
- import { statuslineText } from "../cli/statusline.mjs";
100
+ import { notInPathText, sidecarFromBaseUrl, statusPanelText, statuslineText } from "../cli/statusline.mjs";
101
+ import { runWatch } from "../cli/watch.mjs";
100
102
  import { CODEX_PROFILE, codexProfilePath, codexProfileToml, codexStoresApiKey, removeCodexProfile, writeCodexProfile } from "../cli/codex.mjs";
101
103
  import { waitForGateway as awaitGateway } from "../cli/gateway-wait.mjs";
102
104
  import { loginCommand } from "../cli/login.mjs";
@@ -208,6 +210,8 @@ ${heading("Quick start")}
208
210
  ${cmd} mcp passport identity for Claude Desktop, Cursor, Claude Code
209
211
  ${cmd} sidecar [--port 8788] [--allow-connect host[,host]] [--ollama-port 11435] [--no-journal]
210
212
  passport identity for any tool that takes an api_key
213
+ ${cmd} sidecar --profile <name> | --profiles a,b
214
+ run a coding tool's own sidecar (or several, one process)
211
215
 
212
216
  ${heading("Operate")}
213
217
  ${cmd} status [--no-network] [--json]
@@ -223,6 +227,7 @@ ${heading("Operate")}
223
227
 
224
228
  ${heading("Manage")}
225
229
  ${cmd} agent list [--json] list agents
230
+ ${cmd} profile list [--json] show the profiles: one identity per coding tool
226
231
  ${cmd} agent create <name> [--write]
227
232
  create an agent passport (--write saves it here)
228
233
  ${cmd} agent rotate <id> [--grace <seconds>]
@@ -230,6 +235,10 @@ ${heading("Manage")}
230
235
  ${cmd} agent suspend <id> suspend an agent
231
236
  ${cmd} agent resume <id> resume an agent
232
237
  ${cmd} agent revoke <id> permanently revoke an agent
238
+ ${cmd} agent delegations <id> [--json]
239
+ list the delegations its workers have used
240
+ ${cmd} agent revoke-delegation <id> <jti>|--all
241
+ permanently revoke one delegation, or all before now
233
242
  ${cmd} spend [--json] show fleet and per-agent spend
234
243
  ${cmd} audit [--limit 20] [--json]
235
244
  show operator audit history
@@ -240,8 +249,10 @@ ${heading("Manage")}
240
249
  ${cmd} sessions [--agent ID] [--limit 20] [--json]
241
250
  list Claude Code / Codex sessions (declared by the client)
242
251
  ${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
252
  sign one session; save the seal and its receipts
253
+ ${cmd} statusline [--port 8788] one line for Claude Code's status line (configure claude-code --statusline)
254
+ ${cmd} statusline --panel [--session <id>] the longer view the Claude Code plugin's /passcontrol shows
255
+ ${cmd} watch [--port 8788] a live board of each call the sidecar relays (read-only)
245
256
  ${cmd} kill on|off toggle the tenant kill switch
246
257
  ${cmd} export [--out FILE] save a workspace configuration snapshot
247
258
  ${cmd} import <file> [--confirm IMPORT]
@@ -249,7 +260,7 @@ ${heading("Manage")}
249
260
 
250
261
  ${heading("Integrate")}
251
262
  ${cmd} env [integration] print settings without writing anything
252
- ${cmd} configure <integration> [--write] [--force]
263
+ ${cmd} configure <integration> [--write] [--force] [--dedicated]
253
264
  preview or write integration config
254
265
  integrations: ${integrationChoices()}
255
266
 
@@ -302,6 +313,8 @@ ${heading("Usage:")}
302
313
  ${cmd} agent suspend <id>
303
314
  ${cmd} agent resume <id>
304
315
  ${cmd} agent revoke <id>
316
+ ${cmd} agent delegations <id> [--json]
317
+ ${cmd} agent revoke-delegation <id> <jti>|--all
305
318
 
306
319
  ${heading("Examples")}
307
320
  ${cmd} agent create prod-summarizer --provider anthropic --scope 'claude-*'
@@ -373,6 +386,7 @@ async function printCockpit({ noNetwork = false, json = false } = {}) {
373
386
  app: { state: app },
374
387
  config: {
375
388
  source: configFile,
389
+ profile: config.profile,
376
390
  provider: config.provider,
377
391
  model: config.model,
378
392
  passport_configured: passportConfigured,
@@ -2273,9 +2287,66 @@ async function agentCommand(rest, opts) {
2273
2287
  step("passport instead, and leaves this one working everywhere it already runs.");
2274
2288
  break;
2275
2289
  }
2290
+ // An agent's signed delegations to its workers (Bet D). A delegation is made
2291
+ // offline, so the gateway knows a link only once a worker has exchanged it; the
2292
+ // listing says so, and --all is the tool that reaches the ones never seen.
2293
+ case "delegations": {
2294
+ if (!args[0]) throw new Error("Usage: passcontrol agent delegations <agent-id> [--json]");
2295
+ const rows = await api("GET", `/agents/${encodeURIComponent(args[0])}/delegations`);
2296
+ if (opts.json) {
2297
+ console.log(JSON.stringify(rows, null, 2));
2298
+ break;
2299
+ }
2300
+ step("Only delegations a worker has used appear here. A delegation is signed offline, so the");
2301
+ step("gateway learns of it at its first exchange; `revoke-delegation --all` also reaches unseen ones.");
2302
+ if (!Array.isArray(rows) || rows.length === 0) {
2303
+ step("No worker has used a delegation from this agent yet.");
2304
+ break;
2305
+ }
2306
+ // Server text reaches a terminal: keep it to printable ASCII.
2307
+ const printable = (v) => String(v ?? "").replace(/[^\x20-\x7e]/g, "?").slice(0, 64);
2308
+ const now = Date.now();
2309
+ console.table(
2310
+ rows.map((d) => ({
2311
+ jti: printable(d.jti),
2312
+ depth: d.depth,
2313
+ status: d.revoked ? "revoked" : Date.parse(d.expires_at) <= now ? "expired" : "active",
2314
+ worker: `${printable(d.worker_key).slice(0, 12)}…`,
2315
+ cap: usd(d.cap_microcents),
2316
+ models: Array.isArray(d.scope)
2317
+ ? d.scope.map((s) => `${printable(s?.provider)}:${(Array.isArray(s?.models) ? s.models : []).map(printable).join("|")}`).join(", ")
2318
+ : "",
2319
+ expires: printable(d.expires_at).slice(0, 19),
2320
+ "first used": printable(d.first_exchanged_at).slice(0, 19),
2321
+ }))
2322
+ );
2323
+ break;
2324
+ }
2325
+ case "revoke-delegation": {
2326
+ const usage = "Usage: passcontrol agent revoke-delegation <agent-id> <jti>|--all";
2327
+ const [agentId, jti] = args;
2328
+ const all = opts.all === true;
2329
+ if (!agentId || all === Boolean(jti)) throw new Error(usage);
2330
+ const result = await api(
2331
+ "POST",
2332
+ `/agents/${encodeURIComponent(agentId)}/delegations/revoke`,
2333
+ all ? { all: true } : { jti }
2334
+ );
2335
+ ok(
2336
+ all
2337
+ ? `revoked every delegation agent ${agentId} issued before now, seen or not`
2338
+ : `revoked delegation ${jti} and every delegation under it`
2339
+ );
2340
+ step("This is permanent. To let a worker go on, the agent delegates to it again.");
2341
+ if (result?.immediate === false) {
2342
+ step("Recorded, but the gateway's fast copy could not be written: a worker holding a current");
2343
+ step("visa can keep calling until that visa expires (5 minutes by default).");
2344
+ }
2345
+ break;
2346
+ }
2276
2347
  default:
2277
2348
  throw new Error(
2278
- "Usage: passcontrol agent list|create <name>|suspend <id>|resume <id>|revoke <id>|rotate <id> [--grace <seconds>]"
2349
+ "Usage: passcontrol agent list|create <name>|suspend <id>|resume <id>|revoke <id>|rotate <id> [--grace <seconds>]|delegations <id>|revoke-delegation <id> <jti>|--all"
2279
2350
  );
2280
2351
  }
2281
2352
  }
@@ -2368,6 +2439,31 @@ async function sidecarCommand(rest, opts) {
2368
2439
  // sidecar mints on demand for the lifetime of the process, so a bad
2369
2440
  // destination has to be refused at start, not at the first proxied request.
2370
2441
  const gateway = requirePassportGateway(config);
2442
+ if (opts.profiles) {
2443
+ // Several identities, one process: one listener per profile, each with its own
2444
+ // passport, visa and journal (candidate 4). One terminal, one Ctrl-C.
2445
+ const names = String(opts.profiles).split(",").map((n) => n.trim()).filter(Boolean);
2446
+ for (const name of names) {
2447
+ const values = readProfile(name);
2448
+ if (!values?.PASSPORT_ID || !values?.PASSPORT_SECRET) {
2449
+ throw new Error(`Profile ${name} has no passport. Create it with ${cliCommand(`configure ${name} --dedicated --write`)}.`);
2450
+ }
2451
+ step(`Profile ${name}:`);
2452
+ startSidecar({
2453
+ gateway,
2454
+ passportId: values.PASSPORT_ID,
2455
+ passportSecret: values.PASSPORT_SECRET,
2456
+ keyStorage: null,
2457
+ port: sidecarPort({ port: values.SIDECAR_PORT }),
2458
+ host: String(opts.host ?? process.env.SIDECAR_HOST ?? "127.0.0.1"),
2459
+ allowNonLoopback: Boolean(opts.allowNonLoopback),
2460
+ allowConnectHosts: [],
2461
+ refreshSkewSeconds: Number(opts.refreshSkewSeconds ?? process.env.REFRESH_SKEW_SECONDS ?? 30),
2462
+ noJournal: opts.journal === false || Boolean(opts.noJournal),
2463
+ });
2464
+ }
2465
+ return;
2466
+ }
2371
2467
  const { passportId, passportSecret, keyStorage } = requirePassport(config);
2372
2468
  startSidecar({
2373
2469
  gateway,
@@ -2427,6 +2523,17 @@ function sidecarPort(opts = {}) {
2427
2523
  async function statuslineCommand(opts) {
2428
2524
  try {
2429
2525
  const port = sidecarPort(opts);
2526
+ // `--panel`: the several-line view `/passcontrol` shows in Claude Code (F3).
2527
+ // Without --port, the sidecar Claude Code's own ANTHROPIC_BASE_URL names.
2528
+ if (opts.panel) {
2529
+ const route = opts.port === undefined ? sidecarFromBaseUrl(process.env.ANTHROPIC_BASE_URL) : null;
2530
+ if (route?.remote) return notInPathText(route.remote);
2531
+ return await statusPanelText({
2532
+ port: route?.port ?? port,
2533
+ gateway: config.gateway,
2534
+ session: typeof opts.session === "string" ? opts.session : null,
2535
+ });
2536
+ }
2430
2537
  const cacheFile = path.join(path.dirname(globalConfigPath()), `statusline-${port}.json`);
2431
2538
  return await statuslineText({ port, cacheFile });
2432
2539
  } catch (error) {
@@ -2482,7 +2589,9 @@ function passControlMcpEntry() {
2482
2589
  }
2483
2590
 
2484
2591
  function printMcpPreset(integration, opts = {}) {
2485
- requireGlobalMcpPassport();
2592
+ // Claude Code's lines only point it at the sidecar, which holds the passport (as in
2593
+ // configureMcpClient); the MCP clients below launch `passcontrol mcp`, which needs it.
2594
+ if (integration !== "claude-code") requireGlobalMcpPassport();
2486
2595
  if (integration === "claude-code") {
2487
2596
  const { baseUrl } = sidecarBaseUrl({ ...opts, provider: "anthropic" });
2488
2597
  console.log("# Route Claude Code's model calls through the sidecar (start it first):");
@@ -2709,6 +2818,68 @@ function printCodexPreset(opts = {}) {
2709
2818
  * Codex layers over its config when started with `--profile passcontrol`.
2710
2819
  * `--remove` deletes that file, and only when PassControl wrote it.
2711
2820
  */
2821
+ // ── One identity per coding tool (candidate 4, plans/one-identity-per-tool.md) ──
2822
+ //
2823
+ // `configure <tool> --dedicated` gives Claude Code or Codex its OWN agent: its own
2824
+ // passport, budget, scope and kill switch, served by its own sidecar port, kept in
2825
+ // a named profile (cli/profiles.mjs). Re-running reuses the profile; it never
2826
+ // creates a second agent.
2827
+ async function prepareDedicatedProfile(tool, opts) {
2828
+ const port = TOOL_PROFILE_PORTS[tool];
2829
+ opts.port = port;
2830
+ const existing = readProfile(tool);
2831
+ if (existing?.PASSPORT_ID && existing?.PASSPORT_SECRET) {
2832
+ opts.port = Number(existing.SIDECAR_PORT || port);
2833
+ step(`Using the ${tool} profile's own agent (passport …${existing.PASSPORT_ID.slice(-8)}), sidecar port ${opts.port}.`);
2834
+ return;
2835
+ }
2836
+ const label = tool === "claude-code" ? "Claude Code" : "Codex";
2837
+ const provider = tool === "claude-code" ? "anthropic" : "openai";
2838
+ const name = `${label} @ ${os.hostname().split(".")[0] || "this machine"}`;
2839
+ if (!opts.write) {
2840
+ step(`With --write: creates the agent "${name}" with its own passport, saved in the ${tool} profile, served on sidecar port ${port}.`);
2841
+ return;
2842
+ }
2843
+ requireControlApiKey(config);
2844
+ // The keypair is made here and only the public half leaves, as in `agent create`.
2845
+ // The profile is written FIRST, so a created agent never exists without its key on
2846
+ // this machine; if creating it fails, the profile is removed again.
2847
+ const priv = ed25519.utils.randomPrivateKey();
2848
+ const passportId = b64url(ed25519.getPublicKey(priv));
2849
+ writeProfile(tool, { PASSPORT_ID: passportId, PASSPORT_SECRET: b64url(priv), PASSPORT_KEY_STORAGE: "", SIDECAR_PORT: String(port) });
2850
+ let created;
2851
+ try {
2852
+ created = await api("POST", "/agents", {
2853
+ name,
2854
+ passportPubkey: passportId,
2855
+ scopes: [{ provider, models: [defaultAllowedModelForProvider(provider)] }],
2856
+ });
2857
+ } catch (error) {
2858
+ fs.rmSync(profilePath(tool), { force: true });
2859
+ throw error;
2860
+ }
2861
+ ok(`created agent ${created.id} (${created.name}); its passport is in the ${tool} profile and was not printed`);
2862
+ }
2863
+
2864
+ function dedicatedSidecarHint(tool) {
2865
+ step(`Run its own sidecar: ${cliCommand(`sidecar --profile ${tool}`)}`);
2866
+ step(`Both coding tools at once, each as its own agent: ${cliCommand("sidecar --profiles claude-code,codex")}`);
2867
+ }
2868
+
2869
+ function profileCommand(rest, opts) {
2870
+ if (rest[0] !== "list") throw new Error("Usage: passcontrol profile list");
2871
+ const rows = listProfiles().map((p) => ({ profile: p.name, passport: p.passportId ? `…${p.passportId.slice(-8)}` : "none", port: p.port || "-" }));
2872
+ if (opts.json) {
2873
+ console.log(JSON.stringify(rows, null, 2));
2874
+ return;
2875
+ }
2876
+ if (!rows.length) {
2877
+ step(`No profiles yet. Give a coding tool its own agent: ${cliCommand("configure claude-code --dedicated --write")}`);
2878
+ return;
2879
+ }
2880
+ for (const r of rows) console.log(`${r.profile.padEnd(20)} passport ${r.passport.padEnd(10)} port ${r.port}`);
2881
+ }
2882
+
2712
2883
  function configureCodex(opts = {}) {
2713
2884
  const target = codexProfilePath();
2714
2885
  if (opts.remove) {
@@ -2739,11 +2910,13 @@ function configureCodex(opts = {}) {
2739
2910
  }
2740
2911
 
2741
2912
  function configureMcpClient(integration, opts = {}) {
2742
- requireGlobalMcpPassport();
2913
+ // Claude Code's settings only point it at the sidecar, which holds the passport
2914
+ // itself; requiring one here also stopped `--remove` once the config was gone.
2743
2915
  if (integration === "claude-code") {
2744
2916
  configureClaudeCode(opts);
2745
2917
  return;
2746
2918
  }
2919
+ requireGlobalMcpPassport();
2747
2920
 
2748
2921
  const target = mcpClientConfigPath(integration);
2749
2922
  const entry = passControlMcpEntry();
@@ -2775,12 +2948,17 @@ async function configureCommand(rest, opts = {}) {
2775
2948
  `Unknown integration "${integration}". Use one of: ${integrationChoices()}.`
2776
2949
  );
2777
2950
  }
2951
+ if (opts.dedicated && (integration === "claude-code" || integration === "codex")) {
2952
+ await prepareDedicatedProfile(integration, opts);
2953
+ }
2778
2954
  if (integration === "codex") {
2779
2955
  configureCodex(opts);
2956
+ if (opts.dedicated) dedicatedSidecarHint(integration);
2780
2957
  return;
2781
2958
  }
2782
2959
  if (isMcpIntegration(integration)) {
2783
2960
  configureMcpClient(integration, opts);
2961
+ if (opts.dedicated && integration === "claude-code") dedicatedSidecarHint(integration);
2784
2962
  return;
2785
2963
  }
2786
2964
  if (!supportsWrite(integration)) {
@@ -4198,6 +4376,12 @@ async function main(argv = process.argv.slice(2), runtime = {}) {
4198
4376
  return;
4199
4377
  }
4200
4378
 
4379
+ // Also before the update check: a full-screen board owns the terminal from its
4380
+ // first frame, and the check's cache would be the one file `watch` ever wrote.
4381
+ if (command === "watch" && !opts.help) {
4382
+ process.exit(await runWatch({ port: sidecarPort(opts) }));
4383
+ }
4384
+
4201
4385
  // Started here and awaited at the very end, so the registry lookup overlaps
4202
4386
  // the command instead of being tacked onto the exit. On anything that touches
4203
4387
  // the network — which is most of this CLI — it costs nothing measurable, and
@@ -4299,6 +4483,9 @@ async function main(argv = process.argv.slice(2), runtime = {}) {
4299
4483
  " `passcontrol login` now does the same thing with YOUR agent rather than a\n" +
4300
4484
  " shared demo one: a governed call and a signed receipt you can verify."
4301
4485
  );
4486
+ case "profile":
4487
+ profileCommand(commandRest, opts);
4488
+ break;
4302
4489
  case "sidecar":
4303
4490
  await sidecarCommand(commandRest, opts);
4304
4491
  break;
@@ -74,3 +74,40 @@ export function budgetLines(self) {
74
74
  if (lines.length === 0) lines.push("No spending or token limit is set for this agent.");
75
75
  return lines;
76
76
  }
77
+
78
+ /**
79
+ * Every limit as a [label, value] row, for the `/passcontrol` panel in Claude Code
80
+ * (`passcontrol statusline --panel`): "Today", "$0.42 of $10.00 · $9.58 left · resets in 7h".
81
+ */
82
+ export function panelRows(self) {
83
+ const b = self?.budget ?? {};
84
+ const rows = [];
85
+ if (b.period && b.period.unknown) {
86
+ rows.push(["Limit", "could not be read right now"]);
87
+ } else if (b.period) {
88
+ const reset = resetsIn(b.period.resets_in_seconds);
89
+ rows.push([
90
+ PERIOD_LABEL[b.period.kind] ?? "This period",
91
+ `${formatUsd(b.period.used_microcents)} of ${formatUsd(b.period.limit_microcents)} · ${formatUsd(b.period.remaining_microcents)} left${reset ? ` · resets in ${reset}` : ""}`,
92
+ ]);
93
+ }
94
+ if (b.cost) {
95
+ rows.push(["Lifetime", `${formatUsd(b.cost.used_microcents)} of ${formatUsd(b.cost.limit_microcents)} · ${formatUsd(b.cost.remaining_microcents)} left`]);
96
+ }
97
+ if (b.tokens) {
98
+ rows.push(["Tokens", `${formatTokens(b.tokens.used)} of ${formatTokens(b.tokens.limit)} · ${formatTokens(b.tokens.remaining)} left`]);
99
+ }
100
+ if (rows.length === 0) rows.push(["Limit", "none set"]);
101
+ return rows;
102
+ }
103
+
104
+ /** Whether a limit has nothing left, so the gateway refuses calls until it resets or is raised. */
105
+ export function limitReached(self) {
106
+ const b = self?.budget ?? {};
107
+ const spent = (left) => left !== null && left !== undefined && Number.isFinite(Number(left)) && Number(left) <= 0;
108
+ return Boolean(
109
+ (b.period && !b.period.unknown && spent(b.period.remaining_microcents)) ||
110
+ (b.cost && spent(b.cost.remaining_microcents)) ||
111
+ (b.tokens && spent(b.tokens.remaining))
112
+ );
113
+ }
package/cli/config.mjs CHANGED
@@ -3,6 +3,7 @@ import os from "node:os";
3
3
  import path from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import { WORKSPACE_EXPORT_PROTOCOL } from "./protocols.mjs";
6
+ import { profilePath, readProfile, selectedProfile } from "./profiles.mjs";
6
7
  import {
7
8
  createPassportCredentialStore,
8
9
  keyStorageDeclaration,
@@ -164,7 +165,10 @@ export function loadConfigSources({ cwd = process.cwd(), env = process.env } = {
164
165
  */
165
166
  export const configInjectedKeys = new Set();
166
167
 
167
- export function applyConfigSourcesToEnv({ cwd = process.cwd(), env = process.env } = {}) {
168
+ export function applyConfigSourcesToEnv({ cwd = process.cwd(), env = process.env, argv = process.argv } = {}) {
169
+ // The profile is chosen BEFORE any file lands in the environment: a project's
170
+ // `.passcontrol` must not pick which identity this machine speaks as.
171
+ const profile = selectedProfile(argv, env);
168
172
  const sources = loadConfigSources({ cwd, env });
169
173
  const merged = {};
170
174
  for (const source of sources) Object.assign(merged, source.values);
@@ -174,6 +178,21 @@ export function applyConfigSourcesToEnv({ cwd = process.cwd(), env = process.env
174
178
  configInjectedKeys.add(key);
175
179
  }
176
180
  }
181
+ if (profile !== null) {
182
+ // One identity per coding tool (cli/profiles.mjs). The named profile beats the
183
+ // config FILES (naming it is the more specific statement); the operator's shell
184
+ // still beats everything.
185
+ const file = profilePath(profile, env);
186
+ const values = readProfile(profile, env);
187
+ if (!values) throw new Error(`No profile named ${profile}. List them with \`passcontrol profile list\`.`);
188
+ for (const [key, value] of Object.entries(values)) {
189
+ if (env[key] === undefined || configInjectedKeys.has(key)) {
190
+ env[key] = value;
191
+ configInjectedKeys.add(key);
192
+ }
193
+ }
194
+ sources.push({ type: "profile", name: profile, path: file, values });
195
+ }
177
196
  return sources;
178
197
  }
179
198
 
@@ -286,12 +305,15 @@ function currentConfig() {
286
305
  provider,
287
306
  model: resolveModel(provider),
288
307
  sources: configSources,
308
+ profile: configSources.find((source) => source.type === "profile")?.name ?? null,
289
309
  };
290
310
  }
291
311
 
292
312
  export const config = currentConfig();
293
313
 
294
314
  export function configPathLabel(sources = configSources) {
315
+ const profile = sources.find((source) => source.type === "profile");
316
+ if (profile) return profile.path;
295
317
  const project = sources.find((source) => source.type === "project");
296
318
  const global = sources.find((source) => source.type === "global");
297
319
  if (project) return project.path;
@@ -655,6 +677,18 @@ export function formatProxyError(status, body) {
655
677
  if (status === 402 && error === "blocked_budget_period") {
656
678
  return `${blocked}\n→ The agent's daily or monthly limit is spent; it resets at the next UTC day or month (see the retry-after header).\n→ Fix: wait for the reset, or raise the limit in the dashboard.`;
657
679
  }
680
+ if (status === 402 && error === "blocked_budget_delegation") {
681
+ return `${blocked}\n→ This worker's delegation (or one above it) used its spending cap.\n→ Fix: ask the agent that delegated to it for a new delegation with a larger cap.`;
682
+ }
683
+ if (status === 403 && error === "delegation_revoked") {
684
+ return `${blocked}\n→ The owner revoked this worker's delegation, or every delegation issued before a point in time.\n→ Fix: ask the agent that delegated to it for a new one.`;
685
+ }
686
+ if (status === 503 && error === "delegation_state_unavailable") {
687
+ return `${blocked}\n→ PassControl could not confirm this delegation is still valid, so it refused rather than guess.\n→ Fix: retry shortly; if it persists, ask for a new delegation.`;
688
+ }
689
+ if (status === 402 && error === "blocked_budget_subagent") {
690
+ return `${blocked}\n→ A sub-agent used the per-session cap the agent's policy sets for each sub-agent. The main agent and other sub-agents keep running.\n→ Fix: start a new session, or raise subagent_session_cap_cents in the agent's policy.`;
691
+ }
658
692
  if (status === 403 && error === "blocked_policy" && rule === "max_output_tokens") {
659
693
  const ceiling = Number.isSafeInteger(limit) ? ` (${limit})` : "";
660
694
  return reason === "missing"
@@ -12,12 +12,23 @@ const DECLARED = /^[A-Za-z0-9._:-]{1,128}$/;
12
12
  const declared = (value) => (typeof value === "string" && DECLARED.test(value) ? value : null);
13
13
 
14
14
  /**
15
+ * The session a call declares, and the sub-agent inside it: what `passcontrol watch`
16
+ * puts on a call's row (F6). The gateway's own rules, mirrored: the CLI's agent ids
17
+ * count only next to the CLI's own session; when the run id stands in, they name
18
+ * agents inside a session we could not read, so they are dropped, and the client's
19
+ * own `x-passcontrol-agent` / `x-passcontrol-parent` are read instead. A parent with
20
+ * no agent describes nobody.
21
+ *
15
22
  * @param {(name: string) => string | null | undefined} header lower-case header lookup
16
23
  * @param {string} runId this sidecar run's id
24
+ * @returns {{ session: string, agent: string | null, parent: string | null } | null}
17
25
  */
18
- export function declaredSession(header, runId) {
26
+ export function declaredLineage(header, runId) {
19
27
  const claude = declared(header("x-claude-code-session-id"));
20
- if (claude) return claude;
28
+ if (claude) {
29
+ const agent = declared(header("x-claude-code-agent-id"));
30
+ return { session: claude, agent, parent: agent ? declared(header("x-claude-code-parent-agent-id")) : null };
31
+ }
21
32
 
22
33
  const isCodex =
23
34
  /^codex/i.test(header("originator") ?? "") ||
@@ -26,8 +37,25 @@ export function declaredSession(header, runId) {
26
37
  header("x-codex-parent-thread-id") != null;
27
38
  if (isCodex) {
28
39
  const raw = [header("session-id"), header("session_id")].filter((v) => v !== null && v !== undefined);
29
- if (raw.length > 0 && raw.every((v) => declared(v) !== null) && raw.every((v) => v === raw[0])) return raw[0];
40
+ if (raw.length > 0 && raw.every((v) => declared(v) !== null) && raw.every((v) => v === raw[0])) {
41
+ const session = raw[0];
42
+ const spawned = header("x-codex-parent-thread-id") != null || header("x-openai-subagent") != null;
43
+ const agent = spawned ? declared(header("thread-id")) : null;
44
+ const parentThread = agent ? declared(header("x-codex-parent-thread-id")) : null;
45
+ return { session, agent, parent: parentThread === session ? null : parentThread };
46
+ }
30
47
  }
31
48
 
32
- return declared(runId);
49
+ const run = declared(runId);
50
+ if (!run) return null;
51
+ const agent = declared(header("x-passcontrol-agent"));
52
+ return { session: run, agent, parent: agent ? declared(header("x-passcontrol-parent")) : null };
53
+ }
54
+
55
+ /**
56
+ * @param {(name: string) => string | null | undefined} header lower-case header lookup
57
+ * @param {string} runId this sidecar run's id
58
+ */
59
+ export function declaredSession(header, runId) {
60
+ return declaredLineage(header, runId)?.session ?? null;
33
61
  }
@@ -0,0 +1,60 @@
1
+ export const DELEGATION_TYP: "passcontrol-delegation+jws";
2
+ export const DELEGATION_MAX_DEPTH: number;
3
+ export const DELEGATION_MAX_LIFETIME_S: number;
4
+
5
+ export interface DelegationScopeEntry {
6
+ provider: string;
7
+ models: string[];
8
+ }
9
+
10
+ export interface CreateDelegationLinkOptions {
11
+ /** The signer's private key: the agent's passport secret, or a worker's own key. */
12
+ signerPrivateKey: string;
13
+ /** Defaults to the signer's public key; must equal it unless `unchecked`. */
14
+ signerKeyId?: string;
15
+ /** The gateway's issuer origin, e.g. https://passcontrol.vertias.eu. */
16
+ audience: string;
17
+ workerPublicKey: string;
18
+ scope: DelegationScopeEntry[];
19
+ capMicrocents: number;
20
+ ttlSeconds: number;
21
+ /** false: the worker may not delegate on. Default true (depth 2 at most). */
22
+ allowFurtherDelegation?: boolean;
23
+ /** The signer's own chain, when a worker delegates on. */
24
+ parentChain?: string[];
25
+ jti?: string;
26
+ nowMs?: number;
27
+ /** Tests only: skip the local checks. The gateway still refuses. */
28
+ unchecked?: boolean;
29
+ }
30
+
31
+ export interface DelegationLinkView {
32
+ jti: string;
33
+ iss: string;
34
+ sub: string;
35
+ iat: number;
36
+ exp: number;
37
+ dep: number;
38
+ max: number;
39
+ cap: number;
40
+ scope: DelegationScopeEntry[];
41
+ }
42
+
43
+ export type DelegationCheck =
44
+ | { ok: true; leaf: DelegationLinkView; links: DelegationLinkView[]; chainHash: string }
45
+ | { ok: false; reason: string };
46
+
47
+ export function delegationChainHash(chain: readonly string[]): string;
48
+ export function generateWorkerKey(): { publicKey: string; privateKey: string };
49
+ export function createDelegationLink(opts: CreateDelegationLinkOptions): string;
50
+ export function checkDelegationChain(input: {
51
+ chain: unknown;
52
+ rootPassportId: string;
53
+ audience?: string;
54
+ nowSeconds?: number;
55
+ }): DelegationCheck;
56
+ export function verifyReceiptDelegation(
57
+ claims: { iss?: string; sub: string; auth?: unknown },
58
+ chain: readonly string[],
59
+ options?: { audience?: string; nowSeconds?: number }
60
+ ): { ok: true; chain: DelegationCheck & { ok: true } } | { ok: false; reason: string };