passcontrol 1.3.0 → 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/bin/passcontrol.mjs +264 -6
- package/cli/budget-format.mjs +76 -0
- package/cli/claude-code.mjs +80 -16
- package/cli/config.mjs +1 -1
- package/cli/declared-session.mjs +33 -0
- package/cli/journal.mjs +84 -0
- package/cli/mcp/README.md +4 -1
- package/cli/mcp/gateway.mjs +13 -0
- package/cli/mcp/server.mjs +27 -0
- package/cli/menu.mjs +3 -0
- package/cli/protocols.d.mts +2 -0
- package/cli/protocols.mjs +14 -0
- package/cli/sidecar.mjs +42 -5
- package/cli/statusline.mjs +89 -0
- package/cli/verify.mjs +215 -5
- package/package.json +1 -1
- package/sdk/verify.d.ts +108 -0
- package/sdk/verify.js +219 -1
package/bin/passcontrol.mjs
CHANGED
|
@@ -90,7 +90,13 @@ 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 {
|
|
93
|
+
import {
|
|
94
|
+
claudeCodeEnv,
|
|
95
|
+
claudeCodeSettingsPath,
|
|
96
|
+
removeClaudeCodeSettings,
|
|
97
|
+
writeClaudeCodeSettings,
|
|
98
|
+
} from "../cli/claude-code.mjs";
|
|
99
|
+
import { statuslineText } from "../cli/statusline.mjs";
|
|
94
100
|
import { CODEX_PROFILE, codexProfilePath, codexProfileToml, codexStoresApiKey, removeCodexProfile, writeCodexProfile } from "../cli/codex.mjs";
|
|
95
101
|
import { waitForGateway as awaitGateway } from "../cli/gateway-wait.mjs";
|
|
96
102
|
import { loginCommand } from "../cli/login.mjs";
|
|
@@ -102,7 +108,7 @@ import {
|
|
|
102
108
|
instanceKidFromSeed,
|
|
103
109
|
retiredKeyEntry,
|
|
104
110
|
} from "../cli/instance-key.mjs";
|
|
105
|
-
import { FAILURE_REASONS, verifyAgentToken, verifyReceipt, verifyStatement } from "../cli/verify.mjs";
|
|
111
|
+
import { FAILURE_REASONS, verifyAgentToken, verifyReceipt, verifySession, verifyStatement } from "../cli/verify.mjs";
|
|
106
112
|
import { compareProtocolSets } from "../cli/protocols.mjs";
|
|
107
113
|
import { defaultAllowedModelForProvider } from "../cli/integration-defaults.mjs";
|
|
108
114
|
import {
|
|
@@ -200,7 +206,7 @@ ${heading("Quick start")}
|
|
|
200
206
|
${cmd} login [--project] sign in through your browser and set this machine up
|
|
201
207
|
${cmd} call "hi" mint a visa and make a governed model call
|
|
202
208
|
${cmd} mcp passport identity for Claude Desktop, Cursor, Claude Code
|
|
203
|
-
${cmd} sidecar [--port 8788] [--allow-connect host[,host]] [--ollama-port 11435]
|
|
209
|
+
${cmd} sidecar [--port 8788] [--allow-connect host[,host]] [--ollama-port 11435] [--no-journal]
|
|
204
210
|
passport identity for any tool that takes an api_key
|
|
205
211
|
|
|
206
212
|
${heading("Operate")}
|
|
@@ -231,6 +237,11 @@ ${heading("Manage")}
|
|
|
231
237
|
show governed call logs
|
|
232
238
|
${cmd} statements [--limit 20] [--json]
|
|
233
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
|
|
234
245
|
${cmd} kill on|off toggle the tenant kill switch
|
|
235
246
|
${cmd} export [--out FILE] save a workspace configuration snapshot
|
|
236
247
|
${cmd} import <file> [--confirm IMPORT]
|
|
@@ -2382,6 +2393,10 @@ async function sidecarCommand(rest, opts) {
|
|
|
2382
2393
|
.map((entry) => entry.trim())
|
|
2383
2394
|
.filter(Boolean),
|
|
2384
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),
|
|
2385
2400
|
});
|
|
2386
2401
|
|
|
2387
2402
|
if (opts.for) {
|
|
@@ -2405,6 +2420,27 @@ function sidecarPort(opts = {}) {
|
|
|
2405
2420
|
return port;
|
|
2406
2421
|
}
|
|
2407
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
|
+
|
|
2408
2444
|
function sidecarBaseUrl(opts = {}) {
|
|
2409
2445
|
const provider = String(opts.provider || config.provider);
|
|
2410
2446
|
assertProvider(provider);
|
|
@@ -2619,16 +2655,29 @@ function configureClaudeCode(opts = {}) {
|
|
|
2619
2655
|
if (!opts.write) {
|
|
2620
2656
|
step(`Dry run only. Re-run with \`--write\` to merge these two keys${scope === "project" ? " (or --write --global for every session)" : ""}.`);
|
|
2621
2657
|
} else {
|
|
2622
|
-
const result = writeClaudeCodeSettings({
|
|
2658
|
+
const result = writeClaudeCodeSettings({
|
|
2659
|
+
target,
|
|
2660
|
+
baseUrl,
|
|
2661
|
+
force: Boolean(opts.force),
|
|
2662
|
+
statusLineCommand: opts.statusline ? statusLineSettingsCommand(port) : null,
|
|
2663
|
+
});
|
|
2623
2664
|
if (!result.changed) ok(`${target} already routes Claude Code through PassControl`);
|
|
2624
2665
|
else {
|
|
2625
2666
|
if (result.backupPath) step(`backed up ${result.backupPath}`);
|
|
2626
2667
|
ok(`wrote ${target}`);
|
|
2627
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");
|
|
2628
2672
|
if (result.rawKeyFound) {
|
|
2629
2673
|
warn(`${target} also holds a raw ANTHROPIC_API_KEY. PassControl does not need it there; remove it so no key sits on disk.`);
|
|
2630
2674
|
}
|
|
2631
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
|
+
}
|
|
2632
2681
|
step(`Start the sidecar before Claude Code: ${cliCommand(port === 8788 ? "sidecar" : `sidecar --port ${port}`)}`);
|
|
2633
2682
|
step("The agent's Anthropic scope must allow the models Claude Code uses (its main model, and Haiku for small tasks).");
|
|
2634
2683
|
step(`Optional, the chat tool as well: ${CLAUDE_CODE_ADD_COMMAND}`);
|
|
@@ -3033,11 +3082,12 @@ async function verifyCommand(rest, opts) {
|
|
|
3033
3082
|
const artifact = rest[1];
|
|
3034
3083
|
const issuer = String(opts.issuer || process.env.PASSCONTROL_ISSUER || "");
|
|
3035
3084
|
|
|
3036
|
-
if ((what !== "token" && what !== "receipt" && what !== "statement") || !artifact) {
|
|
3085
|
+
if ((what !== "token" && what !== "receipt" && what !== "statement" && what !== "session") || !artifact) {
|
|
3037
3086
|
throw new Error(
|
|
3038
3087
|
"Usage: passcontrol verify token <jwt> --audience <aud> --issuer <origin>\n" +
|
|
3039
3088
|
" passcontrol verify receipt <jws> --issuer <origin>\n" +
|
|
3040
|
-
" 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>"
|
|
3041
3091
|
);
|
|
3042
3092
|
}
|
|
3043
3093
|
if (!issuer) {
|
|
@@ -3047,6 +3097,11 @@ async function verifyCommand(rest, opts) {
|
|
|
3047
3097
|
);
|
|
3048
3098
|
}
|
|
3049
3099
|
|
|
3100
|
+
if (what === "session") {
|
|
3101
|
+
await verifySessionCommand(artifact, opts, issuer);
|
|
3102
|
+
return;
|
|
3103
|
+
}
|
|
3104
|
+
|
|
3050
3105
|
const result =
|
|
3051
3106
|
what === "token"
|
|
3052
3107
|
? await verifyAgentToken(artifact, { issuer, audience: String(opts.audience || "") })
|
|
@@ -3096,6 +3151,17 @@ async function verifyCommand(rest, opts) {
|
|
|
3096
3151
|
step(`Verdict: ${c.res?.status} (HTTP ${c.res?.http})`);
|
|
3097
3152
|
step(`Usage: ${c.use?.in ?? 0} in / ${c.use?.out ?? 0} out · ${c.cost ?? 0} µ¢`);
|
|
3098
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
|
+
}
|
|
3099
3165
|
}
|
|
3100
3166
|
if (c.own) {
|
|
3101
3167
|
step(
|
|
@@ -3104,6 +3170,184 @@ async function verifyCommand(rest, opts) {
|
|
|
3104
3170
|
}
|
|
3105
3171
|
}
|
|
3106
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
|
+
|
|
3107
3351
|
/**
|
|
3108
3352
|
* The chain of signed spend statements for this workspace.
|
|
3109
3353
|
*
|
|
@@ -3946,6 +4190,14 @@ async function main(argv = process.argv.slice(2), runtime = {}) {
|
|
|
3946
4190
|
const { opts, rest } = parseArgv(argv);
|
|
3947
4191
|
const [command, ...commandRest] = rest;
|
|
3948
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
|
+
|
|
3949
4201
|
// Started here and awaited at the very end, so the registry lookup overlaps
|
|
3950
4202
|
// the command instead of being tacked onto the exit. On anything that touches
|
|
3951
4203
|
// the network — which is most of this CLI — it costs nothing measurable, and
|
|
@@ -4075,6 +4327,12 @@ async function main(argv = process.argv.slice(2), runtime = {}) {
|
|
|
4075
4327
|
case "statements":
|
|
4076
4328
|
await statementsCommand(opts);
|
|
4077
4329
|
break;
|
|
4330
|
+
case "sessions":
|
|
4331
|
+
await sessionsCommand(opts);
|
|
4332
|
+
break;
|
|
4333
|
+
case "seal":
|
|
4334
|
+
await sealCommand(commandRest, opts);
|
|
4335
|
+
break;
|
|
4078
4336
|
case "kill":
|
|
4079
4337
|
await killCommand(commandRest);
|
|
4080
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
|
+
}
|
package/cli/claude-code.mjs
CHANGED
|
@@ -6,10 +6,12 @@
|
|
|
6
6
|
// Bearer token with no "use this API key?" prompt. The sidecar strips it and the
|
|
7
7
|
// gateway injects the real key, so Claude Code never holds one.
|
|
8
8
|
//
|
|
9
|
-
// The settings file belongs to the user. Only these two keys
|
|
10
|
-
//
|
|
11
|
-
//
|
|
12
|
-
//
|
|
9
|
+
// The settings file belongs to the user. Only these two keys, and with
|
|
10
|
+
// --statusline a `statusLine` running `passcontrol statusline`, are written or
|
|
11
|
+
// removed, in one save; the previous file is backed up, a file that is not a JSON
|
|
12
|
+
// object is refused rather than overwritten, a different gateway already
|
|
13
|
+
// configured is not replaced without --force, and a status line the user already
|
|
14
|
+
// has is never replaced at all.
|
|
13
15
|
import fs from "node:fs";
|
|
14
16
|
import os from "node:os";
|
|
15
17
|
import path from "node:path";
|
|
@@ -63,34 +65,96 @@ function save(target, value, exists) {
|
|
|
63
65
|
return backupPath;
|
|
64
66
|
}
|
|
65
67
|
|
|
66
|
-
|
|
68
|
+
/**
|
|
69
|
+
* The env keys, and with `statusLineCommand` the status line too, in ONE save:
|
|
70
|
+
* two saves would back up the first save's output and lose the user's original.
|
|
71
|
+
*/
|
|
72
|
+
export function writeClaudeCodeSettings({ target, baseUrl, force = false, statusLineCommand = null }) {
|
|
67
73
|
const { exists, value } = readSettings(target);
|
|
68
74
|
const env = typeof value.env === "object" && value.env !== null && !Array.isArray(value.env) ? value.env : {};
|
|
69
75
|
const rawKeyFound = typeof env.ANTHROPIC_API_KEY === "string" && env.ANTHROPIC_API_KEY.length > 0;
|
|
70
76
|
const current = env.ANTHROPIC_BASE_URL;
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
}
|
|
74
|
-
if (typeof current === "string" && current && current !== baseUrl && !force) {
|
|
77
|
+
const envDone = current === baseUrl && env.ANTHROPIC_AUTH_TOKEN === CLAUDE_CODE_AUTH_PLACEHOLDER;
|
|
78
|
+
if (!envDone && typeof current === "string" && current && current !== baseUrl && !force) {
|
|
75
79
|
throw new Error(
|
|
76
80
|
`${target} already points Claude Code at ${current}. Re-run with --force to replace that address with PassControl's.`
|
|
77
81
|
);
|
|
78
82
|
}
|
|
79
|
-
|
|
80
|
-
|
|
83
|
+
let next = envDone ? value : { ...value, env: { ...env, ...claudeCodeEnv(baseUrl) } };
|
|
84
|
+
let statusLine;
|
|
85
|
+
if (statusLineCommand) {
|
|
86
|
+
const line = withStatusLine(next, statusLineCommand);
|
|
87
|
+
next = line.value;
|
|
88
|
+
statusLine = line.existing !== undefined ? { changed: false, existing: line.existing } : { changed: line.changed };
|
|
89
|
+
}
|
|
90
|
+
const changed = !envDone || Boolean(statusLine?.changed);
|
|
91
|
+
const backupPath = changed ? save(target, next, exists) : null;
|
|
92
|
+
return { changed, backupPath, rawKeyFound, ...(statusLine ? { statusLine } : {}) };
|
|
81
93
|
}
|
|
82
94
|
|
|
95
|
+
/** PassControl's two env keys and its status line, in one save. */
|
|
83
96
|
export function removeClaudeCodeSettings({ target }) {
|
|
84
97
|
if (!fs.existsSync(target)) return { changed: false };
|
|
85
98
|
const { value } = readSettings(target);
|
|
99
|
+
let next = value;
|
|
86
100
|
const env = typeof value.env === "object" && value.env !== null && !Array.isArray(value.env) ? value.env : null;
|
|
87
101
|
// Only an address this command could have written: a gateway someone else set
|
|
88
102
|
// up is not ours to remove.
|
|
89
|
-
if (
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
103
|
+
if (env && env.ANTHROPIC_AUTH_TOKEN === CLAUDE_CODE_AUTH_PLACEHOLDER) {
|
|
104
|
+
const { ANTHROPIC_BASE_URL: _url, ANTHROPIC_AUTH_TOKEN: _token, ...rest } = env;
|
|
105
|
+
next = { ...value };
|
|
106
|
+
if (Object.keys(rest).length) next.env = rest;
|
|
107
|
+
else delete next.env;
|
|
108
|
+
}
|
|
109
|
+
if (isOurStatusLine(next.statusLine)) {
|
|
110
|
+
const { statusLine: _ours, ...rest } = next;
|
|
111
|
+
next = rest;
|
|
112
|
+
}
|
|
113
|
+
if (next === value) return { changed: false };
|
|
94
114
|
save(target, next, true);
|
|
95
115
|
return { changed: true };
|
|
96
116
|
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Whether a status line is one `configure claude-code --statusline` wrote: the
|
|
120
|
+
* installed `passcontrol` binary, or this repo's own bin run through node.
|
|
121
|
+
*/
|
|
122
|
+
function isOurStatusLine(statusLine) {
|
|
123
|
+
const command = typeof statusLine?.command === "string" ? statusLine.command : "";
|
|
124
|
+
return /^(passcontrol|node "[^"]*passcontrol\.mjs") statusline\b/.test(command);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* `value` with PassControl's status line set, unless the user already has one of
|
|
129
|
+
* their own: then `existing` names it and `value` is unchanged.
|
|
130
|
+
*/
|
|
131
|
+
function withStatusLine(value, command) {
|
|
132
|
+
const current = value.statusLine;
|
|
133
|
+
if (current && !isOurStatusLine(current)) {
|
|
134
|
+
return { value, changed: false, existing: typeof current.command === "string" ? current.command : "(not a command)" };
|
|
135
|
+
}
|
|
136
|
+
if (current && current.type === "command" && current.command === command) return { value, changed: false };
|
|
137
|
+
return { value: { ...value, statusLine: { type: "command", command } }, changed: true };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* The agent's budget in Claude Code's status line, on its own. A status line the
|
|
142
|
+
* user already has is never replaced: the answer names it and nothing is written.
|
|
143
|
+
*/
|
|
144
|
+
export function writeClaudeCodeStatusLine({ target, command }) {
|
|
145
|
+
const { exists, value } = readSettings(target);
|
|
146
|
+
const line = withStatusLine(value, command);
|
|
147
|
+
if (line.existing !== undefined) return { changed: false, existing: line.existing };
|
|
148
|
+
if (!line.changed) return { changed: false };
|
|
149
|
+
save(target, line.value, exists);
|
|
150
|
+
return { changed: true };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export function removeClaudeCodeStatusLine({ target }) {
|
|
154
|
+
if (!fs.existsSync(target)) return { changed: false };
|
|
155
|
+
const { value } = readSettings(target);
|
|
156
|
+
if (!isOurStatusLine(value.statusLine)) return { changed: false };
|
|
157
|
+
const { statusLine: _ours, ...rest } = value;
|
|
158
|
+
save(target, rest, true);
|
|
159
|
+
return { changed: true };
|
|
160
|
+
}
|
package/cli/config.mjs
CHANGED
|
@@ -671,7 +671,7 @@ export function formatProxyError(status, body) {
|
|
|
671
671
|
return `${blocked}\n→ The workspace has no provider key stored for this provider.\n→ Fix: add one under Settings → Provider credentials in the dashboard.`;
|
|
672
672
|
}
|
|
673
673
|
if (status === 400 && error === "server_side_tools_unsupported") {
|
|
674
|
-
return `${blocked}\n→ The request uses a hosted tool PassControl does not price, such as image generation or an
|
|
674
|
+
return `${blocked}\n→ The request uses a hosted tool PassControl does not price, such as image generation, an MCP server, or Claude Code's advisor with an unpriced model.\n→ Fix: remove that tool, or call it outside PassControl (Claude Code: /advisor → No advisor). Priced tools such as web search pass.`;
|
|
675
675
|
}
|
|
676
676
|
// 402 is also how the gateway refuses a call it cannot price under a dollar
|
|
677
677
|
// limit; a bigger budget fixes none of those, so each gets its own advice.
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// The session a relayed call declares, exactly as the gateway reads it from the request
|
|
2
|
+
// headers (lib/client-lineage.ts `readClientLineage`, which the proxy calls without the
|
|
3
|
+
// body): Claude Code's session header, else a Codex session its headers agree on, else
|
|
4
|
+
// this sidecar run's own id (`x-passcontrol-run`, which the sidecar sets on every call).
|
|
5
|
+
//
|
|
6
|
+
// A second copy because the sidecar is plain ESM and cannot import the gateway's
|
|
7
|
+
// TypeScript. tests/declared-session-parity.test.ts runs both over every captured
|
|
8
|
+
// Claude Code and Codex request and fails the day they disagree: the journal is
|
|
9
|
+
// filtered by this value, so a mismatch could hide a real omission.
|
|
10
|
+
|
|
11
|
+
const DECLARED = /^[A-Za-z0-9._:-]{1,128}$/;
|
|
12
|
+
const declared = (value) => (typeof value === "string" && DECLARED.test(value) ? value : null);
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* @param {(name: string) => string | null | undefined} header lower-case header lookup
|
|
16
|
+
* @param {string} runId this sidecar run's id
|
|
17
|
+
*/
|
|
18
|
+
export function declaredSession(header, runId) {
|
|
19
|
+
const claude = declared(header("x-claude-code-session-id"));
|
|
20
|
+
if (claude) return claude;
|
|
21
|
+
|
|
22
|
+
const isCodex =
|
|
23
|
+
/^codex/i.test(header("originator") ?? "") ||
|
|
24
|
+
header("x-codex-turn-metadata") != null ||
|
|
25
|
+
header("x-codex-window-id") != null ||
|
|
26
|
+
header("x-codex-parent-thread-id") != null;
|
|
27
|
+
if (isCodex) {
|
|
28
|
+
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];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
return declared(runId);
|
|
33
|
+
}
|