passcontrol 1.4.0 → 1.5.1

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.
@@ -158,3 +158,182 @@ export function removeClaudeCodeStatusLine({ target }) {
158
158
  save(target, rest, true);
159
159
  return { changed: true };
160
160
  }
161
+
162
+ // ── Subscription mode ─────────────────────────────────────────────────────────
163
+ //
164
+ // A Pro/Max login talks to Anthropic directly, and Anthropic's terms forbid
165
+ // intermediating it, so nothing here touches ANTHROPIC_BASE_URL. Instead Claude
166
+ // Code is told to report to the sidecar and to ask it before acting:
167
+ // * its OpenTelemetry LOG export (http/json) goes to the sidecar's receiver
168
+ // (cli/otlp-logs.mjs). Only the logs-specific variables are written, so a
169
+ // metrics or traces export the user runs is left alone;
170
+ // * three http hooks go to the sidecar's stop gate (cli/subscription-gate.mjs),
171
+ // each with a 5 s timeout: a hook that cannot connect or times out lets the
172
+ // action go ahead, which is the fail-open the owner chose;
173
+ // * the status line carries the usage window (cli/usage-window.mjs);
174
+ // * PASSCONTROL_SIDECAR_URL tells `/passcontrol` which sidecar to ask.
175
+ // Only the user settings: Claude Code ignores telemetry settings in a project's file.
176
+
177
+ const LOOPBACK_BASE = "http://127.0.0.1:";
178
+ const OUR_LOGS_ENDPOINT = /^http:\/\/127\.0\.0\.1:\d{1,5}\/_passcontrol\/otlp\/v1\/logs$/;
179
+ const OUR_HOOK_URL = /^http:\/\/127\.0\.0\.1:\d{1,5}\/_passcontrol\/hook(\?t=\d{1,4})?$/;
180
+ const OUR_SIDECAR_URL = /^http:\/\/127\.0\.0\.1:\d{1,5}$/;
181
+ const GATED_EVENTS = ["UserPromptSubmit", "PreToolUse", "PostToolBatch"];
182
+ // The log-export settings this mode owns, with the value it writes.
183
+ const LOGS_ENV = {
184
+ OTEL_LOGS_EXPORTER: "otlp",
185
+ OTEL_EXPORTER_OTLP_LOGS_PROTOCOL: "http/json",
186
+ // The 5 s default would make the board's rows lag the session.
187
+ OTEL_LOGS_EXPORT_INTERVAL: "1000",
188
+ };
189
+
190
+ export function subscriptionEnv(port) {
191
+ return {
192
+ CLAUDE_CODE_ENABLE_TELEMETRY: "1",
193
+ ...LOGS_ENV,
194
+ OTEL_EXPORTER_OTLP_LOGS_ENDPOINT: `${LOOPBACK_BASE}${port}/_passcontrol/otlp/v1/logs`,
195
+ PASSCONTROL_SIDECAR_URL: `${LOOPBACK_BASE}${port}`,
196
+ };
197
+ }
198
+
199
+ function gateHook(port) {
200
+ return { type: "http", url: `${LOOPBACK_BASE}${port}/_passcontrol/hook`, timeout: 5 };
201
+ }
202
+
203
+ // PreToolUse may hold a tool while the owner is asked (Phase 2), and Claude Code lets
204
+ // a tool RUN when its http hook times out. So this one gets Claude Code's own 600 s
205
+ // default, and says so in its URL: the sidecar always answers inside the time it is
206
+ // told, and a Phase 1 hook (no `t`, 5 s) refuses a tool that would need the owner
207
+ // instead of letting it through on the timeout.
208
+ export const TOOL_HOOK_TIMEOUT_S = 600;
209
+ function toolHook(port) {
210
+ return { type: "http", url: `${LOOPBACK_BASE}${port}/_passcontrol/hook?t=${TOOL_HOOK_TIMEOUT_S}`, timeout: TOOL_HOOK_TIMEOUT_S };
211
+ }
212
+
213
+ export function subscriptionHooks(port) {
214
+ const hook = gateHook(port);
215
+ return {
216
+ UserPromptSubmit: [{ hooks: [hook] }],
217
+ PreToolUse: [{ matcher: "*", hooks: [toolHook(port)] }],
218
+ PostToolBatch: [{ hooks: [hook] }],
219
+ };
220
+ }
221
+
222
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
223
+ const isOurHook = (h) => isObject(h) && h.type === "http" && typeof h.url === "string" && OUR_HOOK_URL.test(h.url);
224
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
225
+
226
+ /** `hooks` with every hook this mode wrote taken out, and groups left empty dropped. */
227
+ function withoutOurHooks(hooks) {
228
+ if (!isObject(hooks)) return hooks;
229
+ const next = {};
230
+ for (const [event, groups] of Object.entries(hooks)) {
231
+ if (!Array.isArray(groups)) {
232
+ next[event] = groups;
233
+ continue;
234
+ }
235
+ const kept = [];
236
+ for (const group of groups) {
237
+ if (!isObject(group) || !Array.isArray(group.hooks) || !group.hooks.some(isOurHook)) {
238
+ kept.push(group);
239
+ continue;
240
+ }
241
+ const rest = group.hooks.filter((h) => !isOurHook(h));
242
+ if (rest.length) kept.push({ ...group, hooks: rest });
243
+ }
244
+ if (kept.length) next[event] = kept;
245
+ }
246
+ return next;
247
+ }
248
+
249
+ /** `hooks` with exactly this port's gate hooks, leaving them where they are when already right. */
250
+ function withOurHooks(hooks, port) {
251
+ const ours = subscriptionHooks(port);
252
+ const base = isObject(hooks) ? hooks : {};
253
+ const next = withoutOurHooks(base);
254
+ for (const event of GATED_EVENTS) {
255
+ const current = Array.isArray(base[event]) ? base[event] : [];
256
+ const already = current.filter((g) => isObject(g) && Array.isArray(g.hooks) && g.hooks.some(isOurHook));
257
+ if (already.length === 1 && same(already[0], ours[event][0])) next[event] = current;
258
+ else next[event] = [...(next[event] ?? []), ...ours[event]];
259
+ }
260
+ return next;
261
+ }
262
+
263
+ // `allowedHttpHookUrls`, when set at any level, runs only the http hooks it matches.
264
+ function urlAllowed(patterns, url) {
265
+ return patterns.some((p) => {
266
+ if (typeof p !== "string") return false;
267
+ const re = new RegExp(`^${p.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*")}$`);
268
+ return re.test(url);
269
+ });
270
+ }
271
+
272
+ /**
273
+ * Subscription mode's settings, in one save. Throws, writing nothing, when the
274
+ * user already exports Claude Code's logs somewhere else and `force` is not set.
275
+ */
276
+ export function writeClaudeCodeSubscription({ target, port, statusLineCommand, force = false }) {
277
+ const { exists, value } = readSettings(target);
278
+ const env = isObject(value.env) ? value.env : {};
279
+ const endpoint = env.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT;
280
+ const ourEndpoint = typeof endpoint === "string" && OUR_LOGS_ENDPOINT.test(endpoint);
281
+ const theirs = [];
282
+ if (endpoint !== undefined && !ourEndpoint) theirs.push("OTEL_EXPORTER_OTLP_LOGS_ENDPOINT");
283
+ if (env.OTEL_LOGS_EXPORTER !== undefined && !ourEndpoint) theirs.push("OTEL_LOGS_EXPORTER");
284
+ if (theirs.length && !force) {
285
+ throw new Error(
286
+ `${target} already exports Claude Code's logs (${theirs.join(", ")}). Subscription mode would send them to the sidecar instead. Re-run with --force to do that; nothing was written.`
287
+ );
288
+ }
289
+ let next = { ...value, env: { ...env, ...subscriptionEnv(port) }, hooks: withOurHooks(value.hooks, port) };
290
+ let statusLine;
291
+ if (statusLineCommand) {
292
+ const line = withStatusLine(next, statusLineCommand);
293
+ next = line.value;
294
+ statusLine = line.existing !== undefined ? { changed: false, existing: line.existing } : { changed: line.changed };
295
+ }
296
+ const changed = !same(next, value);
297
+ const backupPath = changed ? save(target, next, exists) : null;
298
+ const allowlist = Array.isArray(value.allowedHttpHookUrls) ? value.allowedHttpHookUrls : null;
299
+ return {
300
+ changed,
301
+ backupPath,
302
+ ...(statusLine ? { statusLine } : {}),
303
+ hookUrlsBlocked: Boolean(allowlist && [gateHook(port), toolHook(port)].some((h) => !urlAllowed(allowlist, h.url))),
304
+ routed: env.ANTHROPIC_AUTH_TOKEN === CLAUDE_CODE_AUTH_PLACEHOLDER && typeof env.ANTHROPIC_BASE_URL === "string",
305
+ };
306
+ }
307
+
308
+ /**
309
+ * Takes out what `writeClaudeCodeSubscription` wrote: its hooks, its status line, its
310
+ * sidecar address, and the logs export only when it points at a sidecar. The
311
+ * telemetry switch stays while any other OTEL_ setting still needs it.
312
+ */
313
+ export function removeClaudeCodeSubscription({ target }) {
314
+ if (!fs.existsSync(target)) return { changed: false };
315
+ const { value } = readSettings(target);
316
+ let next = { ...value };
317
+ if (isObject(value.env)) {
318
+ const env = { ...value.env };
319
+ if (typeof env.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT === "string" && OUR_LOGS_ENDPOINT.test(env.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT)) {
320
+ delete env.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT;
321
+ for (const [key, ours] of Object.entries(LOGS_ENV)) if (env[key] === ours) delete env[key];
322
+ if (env.CLAUDE_CODE_ENABLE_TELEMETRY === "1" && !Object.keys(env).some((k) => k.startsWith("OTEL_"))) {
323
+ delete env.CLAUDE_CODE_ENABLE_TELEMETRY;
324
+ }
325
+ }
326
+ if (typeof env.PASSCONTROL_SIDECAR_URL === "string" && OUR_SIDECAR_URL.test(env.PASSCONTROL_SIDECAR_URL)) delete env.PASSCONTROL_SIDECAR_URL;
327
+ if (Object.keys(env).length) next.env = env;
328
+ else delete next.env;
329
+ }
330
+ if (isObject(value.hooks)) {
331
+ const hooks = withoutOurHooks(value.hooks);
332
+ if (Object.keys(hooks).length) next.hooks = hooks;
333
+ else delete next.hooks;
334
+ }
335
+ if (isOurStatusLine(next.statusLine)) delete next.statusLine;
336
+ if (same(next, value)) return { changed: false };
337
+ save(target, next, true);
338
+ return { changed: true };
339
+ }
@@ -0,0 +1,212 @@
1
+ // Subscription mode, Phase 1b: the model calls Claude Code REPORTS to the sidecar
2
+ // (cli/otlp-logs.mjs) are uploaded to the gateway's POST /api/v1/client-events, so
3
+ // they reach the agent's dashboard page and not only this machine's `watch`.
4
+ //
5
+ // The OTLP answer never waits for this: `add` only queues, and a timer flushes in
6
+ // batches. Each event gets its key once, when it is queued, and every retry sends the
7
+ // same key, so the gateway (0084, unique per agent and key) stores it once however
8
+ // often it is sent. The queue is bounded and drops the oldest.
9
+ //
10
+ // What each answer means:
11
+ // 200 sent; the gateway counted what it took
12
+ // 403 the agent is stopped: what it reports is not recorded, so drop
13
+ // 400, 413 the batch will never be accepted as it is, so drop it
14
+ // 503 `client_events_unavailable`: the gateway's database predates 0084
15
+ // 404, 405 the gateway predates the endpoint (npm, the Cloud deploy and
16
+ // `passcontrol update` ship at different times)
17
+ // → for both: drop everything and stop for a while
18
+ // 429 wait as long as the gateway asks
19
+ // anything else, or no answer: keep the events, back off, retry, and give a batch
20
+ // up after `maxAttempts`, so one that always fails cannot pin the queue
21
+ //
22
+ // Phase 2 queues the tool rules' decisions here too (cli/tool-gate.mjs): the tool's
23
+ // name and the decision, never the command, path or URL it was about.
24
+ //
25
+ // Only the fields the gateway stores are sent. The reported cost is what the call
26
+ // would have cost on the API, never money spent: the gateway keeps it apart from
27
+ // every budget.
28
+
29
+ import { randomBytes } from "node:crypto";
30
+
31
+ export const CLIENT_EVENTS_PATH = "/api/v1/client-events";
32
+ export const CLIENT_EVENTS_SOURCE = "claude_code_otel";
33
+
34
+ const UNAVAILABLE_PAUSE_MS = 10 * 60_000;
35
+ const BACKOFF_FIRST_MS = 2_000;
36
+ const BACKOFF_MAX_MS = 60_000;
37
+
38
+ const newKey = () => `evt_${randomBytes(16).toString("base64url")}`;
39
+
40
+ /** One event from readClaudeCodeEvents, as the gateway takes it. Absent fields are left out. */
41
+ function toWire(event, key) {
42
+ if (event.kind === "tool_decision") return toolDecisionWire(event, key);
43
+ const wire = {
44
+ key,
45
+ kind: event.kind === "api_error" ? "model_error" : "model_call",
46
+ session: event.session,
47
+ agent: event.agent,
48
+ at: event.at,
49
+ model: event.model,
50
+ cost_usd_micros: event.kind === "api_error" ? null : event.costMicros,
51
+ input_tokens: event.inputTokens,
52
+ output_tokens: event.outputTokens,
53
+ cache_read_tokens: event.cacheReadTokens,
54
+ cache_creation_tokens: event.cacheCreationTokens,
55
+ duration_ms: event.durationMs,
56
+ status: event.kind === "api_error" ? event.status : null,
57
+ };
58
+ for (const name of Object.keys(wire)) if (wire[name] === null || wire[name] === undefined) delete wire[name];
59
+ return wire;
60
+ }
61
+
62
+ function toolDecisionWire(event, key) {
63
+ const wire = {
64
+ key,
65
+ kind: "tool_decision",
66
+ session: event.session,
67
+ agent: event.agent,
68
+ at: event.at,
69
+ tool: event.tool,
70
+ decision: event.decision,
71
+ rule_index: event.ruleIndex,
72
+ duration_ms: event.waitMs,
73
+ };
74
+ for (const name of Object.keys(wire)) if (wire[name] === null || wire[name] === undefined) delete wire[name];
75
+ return wire;
76
+ }
77
+
78
+ /**
79
+ * @param {{
80
+ * send: (events: object[]) => Promise<{ status: number, error?: string, retryAfterS?: number }>,
81
+ * now?: () => number,
82
+ * setTimer?: (fn: () => unknown, ms: number) => unknown,
83
+ * clearTimer?: (timer: unknown) => void,
84
+ * maxQueue?: number,
85
+ * batchSize?: number,
86
+ * flushMs?: number,
87
+ * maxAttempts?: number,
88
+ * }} options
89
+ */
90
+ export function createCallUploader({
91
+ send,
92
+ now = () => Date.now(),
93
+ setTimer = (fn, ms) => {
94
+ const timer = setTimeout(fn, ms);
95
+ timer.unref?.();
96
+ return timer;
97
+ },
98
+ clearTimer = (timer) => clearTimeout(timer),
99
+ maxQueue = 1_000,
100
+ batchSize = 50,
101
+ // Every 10 s: the gateway allows 30 uploads a minute per agent, and two sidecars on
102
+ // one agent should still fit.
103
+ flushMs = 10_000,
104
+ maxAttempts = 8,
105
+ }) {
106
+ let queue = [];
107
+ let sent = 0;
108
+ let dropped = 0;
109
+ let timer = null;
110
+ let inflight = null;
111
+ let waitUntil = 0;
112
+ let unavailableUntil = 0;
113
+ let backoffMs = 0;
114
+ let closed = false;
115
+ // Failed sends per queued event (transient failures only).
116
+ const attempts = new WeakMap();
117
+
118
+ function schedule(delayMs) {
119
+ if (closed || queue.length === 0) return;
120
+ if (timer) clearTimer(timer);
121
+ const ms = Math.max(delayMs, waitUntil - now(), 0);
122
+ timer = setTimer(() => {
123
+ timer = null;
124
+ return flush();
125
+ }, ms);
126
+ }
127
+
128
+ function add(event) {
129
+ if (closed) return;
130
+ if (unavailableUntil > now()) {
131
+ dropped += 1;
132
+ return;
133
+ }
134
+ queue.push(toWire(event, newKey()));
135
+ if (queue.length > maxQueue) {
136
+ queue.shift();
137
+ dropped += 1;
138
+ }
139
+ if (inflight) return;
140
+ if (queue.length >= batchSize) schedule(0);
141
+ else if (!timer) schedule(flushMs);
142
+ }
143
+
144
+ async function flushOnce() {
145
+ const batch = queue.slice(0, batchSize);
146
+ if (batch.length === 0) return;
147
+ let answer;
148
+ try {
149
+ answer = await send(batch);
150
+ } catch {
151
+ answer = { status: 0 };
152
+ }
153
+ const taken = new Set(batch);
154
+ const status = answer?.status ?? 0;
155
+ if (status === 200) {
156
+ queue = queue.filter((e) => !taken.has(e));
157
+ sent += batch.length;
158
+ backoffMs = 0;
159
+ return;
160
+ }
161
+ if ((status === 503 && answer.error === "client_events_unavailable") || status === 404 || status === 405) {
162
+ dropped += queue.length;
163
+ queue = [];
164
+ unavailableUntil = now() + UNAVAILABLE_PAUSE_MS;
165
+ return;
166
+ }
167
+ if (status === 403 || status === 400 || status === 413) {
168
+ queue = queue.filter((e) => !taken.has(e));
169
+ dropped += batch.length;
170
+ return;
171
+ }
172
+ if (status === 429) {
173
+ const seconds = Number(answer.retryAfterS);
174
+ waitUntil = now() + (Number.isFinite(seconds) && seconds > 0 ? seconds * 1_000 : BACKOFF_MAX_MS);
175
+ return;
176
+ }
177
+ for (const e of batch) attempts.set(e, (attempts.get(e) ?? 0) + 1);
178
+ const spent = batch.filter((e) => attempts.get(e) >= maxAttempts);
179
+ if (spent.length > 0) {
180
+ const gone = new Set(spent);
181
+ queue = queue.filter((e) => !gone.has(e));
182
+ dropped += spent.length;
183
+ }
184
+ backoffMs = backoffMs ? Math.min(backoffMs * 2, BACKOFF_MAX_MS) : BACKOFF_FIRST_MS;
185
+ waitUntil = now() + backoffMs;
186
+ }
187
+
188
+ /** Sends one batch now (one at a time), then schedules whatever is left. */
189
+ function flush() {
190
+ if (inflight) return inflight;
191
+ inflight = (async () => {
192
+ try {
193
+ await flushOnce();
194
+ } finally {
195
+ inflight = null;
196
+ if (queue.length >= batchSize && waitUntil <= now()) schedule(0);
197
+ else schedule(flushMs);
198
+ }
199
+ })();
200
+ return inflight;
201
+ }
202
+
203
+ function close() {
204
+ closed = true;
205
+ if (timer) clearTimer(timer);
206
+ timer = null;
207
+ }
208
+
209
+ const stats = () => ({ queued: queue.length, sent, dropped });
210
+
211
+ return { add, flush, close, stats };
212
+ }
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 };