passcontrol 1.5.1 → 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -4
- package/bin/passcontrol.mjs +91 -3
- package/cli/agent-note.mjs +169 -0
- package/cli/budget-format.mjs +101 -8
- package/cli/claude-code.mjs +57 -12
- package/cli/codex-hooks.mjs +246 -0
- package/cli/config.mjs +3 -0
- package/cli/login.mjs +16 -1
- package/cli/mcp/README.md +2 -1
- package/cli/menu.mjs +1 -0
- package/cli/selftest.mjs +10 -0
- package/cli/sidecar.mjs +20 -7
- package/cli/statusline.mjs +2 -2
- package/cli/subscription-gate.mjs +59 -2
- package/cli/tool-gate.mjs +8 -3
- package/cli/watch.mjs +7 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -411,12 +411,13 @@ applies migrations, and seeds a local account. It writes `.env.docker`; use
|
|
|
411
411
|
There are no shared default credentials. `passcontrol setup --app-dir <path>` selects a
|
|
412
412
|
checkout; `passcontrol unlink` forgets a remembered one.
|
|
413
413
|
|
|
414
|
-
|
|
415
|
-
gateway. `setup`, `start`, and `restart` verify PassControl at `/api/version` and require
|
|
416
|
-
launcher to remain alive before switching the global active gateway. `status` reports the active
|
|
414
|
+
By default, local lifecycle commands manage `http://localhost:3000` independently from the active
|
|
415
|
+
Cloud API gateway. `setup`, `start`, and `restart` verify PassControl at `/api/version` and require
|
|
416
|
+
the launcher to remain alive before switching the global active gateway. `status` reports the active
|
|
417
417
|
API gateway and CLI-managed local dashboard separately; `open` opens the active gateway. Explicit
|
|
418
418
|
loopback ports remain supported, but a portless local URL is rejected instead of becoming port 80.
|
|
419
|
-
`--port-offset` moves
|
|
419
|
+
`--port-offset N` moves the whole local stack, including the dashboard to port `3000 + N`.
|
|
420
|
+
For example, `passcontrol setup --port-offset 100` puts the dashboard at `http://localhost:3100`.
|
|
420
421
|
|
|
421
422
|
Switching from a credentialed remote gateway clears gateway-bound local credentials only—it does
|
|
422
423
|
not revoke the remote key or Passport. Interactive use requires a separate confirmation;
|
package/bin/passcontrol.mjs
CHANGED
|
@@ -111,6 +111,15 @@ import {
|
|
|
111
111
|
} from "../cli/statusline.mjs";
|
|
112
112
|
import { runWatch } from "../cli/watch.mjs";
|
|
113
113
|
import { CODEX_PROFILE, codexProfilePath, codexProfileToml, codexStoresApiKey, removeCodexProfile, writeCodexProfile } from "../cli/codex.mjs";
|
|
114
|
+
import {
|
|
115
|
+
codexHookCommand,
|
|
116
|
+
codexHookEntries,
|
|
117
|
+
codexHooksPath,
|
|
118
|
+
probeCodexHookCommand,
|
|
119
|
+
removeCodexHooks,
|
|
120
|
+
runCodexHook,
|
|
121
|
+
writeCodexHooks,
|
|
122
|
+
} from "../cli/codex-hooks.mjs";
|
|
114
123
|
import { waitForGateway as awaitGateway } from "../cli/gateway-wait.mjs";
|
|
115
124
|
import { loginCommand } from "../cli/login.mjs";
|
|
116
125
|
import { logoutCommand } from "../cli/logout.mjs";
|
|
@@ -275,6 +284,10 @@ ${heading("Integrate")}
|
|
|
275
284
|
preview or write integration config
|
|
276
285
|
${cmd} configure claude-code --subscription [--write|--remove]
|
|
277
286
|
a Pro/Max login: stops, calls, usage window
|
|
287
|
+
${cmd} configure codex --subscription [--write|--remove]
|
|
288
|
+
a ChatGPT plan in Codex: stops and tool rules
|
|
289
|
+
${cmd} configure claude-code --write --agent-note
|
|
290
|
+
tell the agent its own limits, only when they change
|
|
278
291
|
integrations: ${integrationChoices()}
|
|
279
292
|
|
|
280
293
|
${heading("Trust")}
|
|
@@ -2785,7 +2798,10 @@ function configureClaudeCode(opts = {}) {
|
|
|
2785
2798
|
return;
|
|
2786
2799
|
}
|
|
2787
2800
|
const { baseUrl, port } = sidecarBaseUrl({ ...opts, provider: "anthropic" });
|
|
2788
|
-
|
|
2801
|
+
const note = Boolean(opts.agentNote);
|
|
2802
|
+
const preview = { env: claudeCodeEnv(baseUrl) };
|
|
2803
|
+
if (note) preview.hooks = { UserPromptSubmit: [{ hooks: [{ type: "http", url: `http://127.0.0.1:${port}/_passcontrol/hook?note=only`, timeout: 5 }] }] };
|
|
2804
|
+
console.log(`Preview: ${target}\n\n${JSON.stringify(preview, null, 2)}`);
|
|
2789
2805
|
if (!opts.write) {
|
|
2790
2806
|
step(`Dry run only. Re-run with \`--write\` to merge these two keys${scope === "project" ? " (or --write --global for every session)" : ""}.`);
|
|
2791
2807
|
} else {
|
|
@@ -2794,6 +2810,7 @@ function configureClaudeCode(opts = {}) {
|
|
|
2794
2810
|
baseUrl,
|
|
2795
2811
|
force: Boolean(opts.force),
|
|
2796
2812
|
statusLineCommand: opts.statusline ? statusLineSettingsCommand(port) : null,
|
|
2813
|
+
noteHookPort: note ? port : null,
|
|
2797
2814
|
});
|
|
2798
2815
|
if (!result.changed) ok(`${target} already routes Claude Code through PassControl`);
|
|
2799
2816
|
else {
|
|
@@ -2812,6 +2829,11 @@ function configureClaudeCode(opts = {}) {
|
|
|
2812
2829
|
} else if (!opts.statusline) {
|
|
2813
2830
|
step(`Optional, the agent's budget in Claude Code's status line: ${cliCommand(`configure claude-code --write --statusline${scope === "user" ? " --global" : ""}`)}`);
|
|
2814
2831
|
}
|
|
2832
|
+
if (note) {
|
|
2833
|
+
step("The agent's note: on a prompt, Claude Code is told how much of its budget is left and when it runs out at this rate. It is sent only when it changes (a quarter of the budget used, the reset close, the rate turning), so it costs almost no context.");
|
|
2834
|
+
} else {
|
|
2835
|
+
step(`Optional, tell the agent its own budget, only when it changes: ${cliCommand(`configure claude-code --write --agent-note${scope === "user" ? " --global" : ""}`)}`);
|
|
2836
|
+
}
|
|
2815
2837
|
step(`Start the sidecar before Claude Code: ${cliCommand(port === 8788 ? "sidecar" : `sidecar --port ${port}`)}`);
|
|
2816
2838
|
step("The agent's Anthropic scope must allow the models Claude Code uses (its main model, and Haiku for small tasks).");
|
|
2817
2839
|
step(`Optional, the chat tool as well: ${CLAUDE_CODE_ADD_COMMAND}`);
|
|
@@ -2833,12 +2855,13 @@ function configureClaudeCodeSubscription(opts = {}) {
|
|
|
2833
2855
|
else step(`${target} has no PassControl subscription settings; nothing to remove.`);
|
|
2834
2856
|
return;
|
|
2835
2857
|
}
|
|
2836
|
-
const
|
|
2858
|
+
const note = Boolean(opts.agentNote);
|
|
2859
|
+
const preview = { env: subscriptionEnv(port), hooks: subscriptionHooks(port, { note }), statusLine: { type: "command", command: statusLineSettingsCommand(port) } };
|
|
2837
2860
|
console.log(`Preview: ${target}\n\n${JSON.stringify(preview, null, 2)}`);
|
|
2838
2861
|
if (!opts.write) {
|
|
2839
2862
|
step("Dry run only. Re-run with `--write` to merge these into your Claude Code user settings (anything of yours is kept).");
|
|
2840
2863
|
} else {
|
|
2841
|
-
const result = writeClaudeCodeSubscription({ target, port, statusLineCommand: statusLineSettingsCommand(port), force: Boolean(opts.force) });
|
|
2864
|
+
const result = writeClaudeCodeSubscription({ target, port, statusLineCommand: statusLineSettingsCommand(port), force: Boolean(opts.force), note });
|
|
2842
2865
|
if (!result.changed) ok(`${target} already has PassControl's subscription mode`);
|
|
2843
2866
|
else {
|
|
2844
2867
|
if (result.backupPath) step(`backed up ${result.backupPath}`);
|
|
@@ -2856,6 +2879,11 @@ function configureClaudeCodeSubscription(opts = {}) {
|
|
|
2856
2879
|
}
|
|
2857
2880
|
step(`Start the sidecar before Claude Code: ${cliCommand(port === 8788 ? "sidecar" : `sidecar --port ${port}`)}`);
|
|
2858
2881
|
step("Your Pro/Max login stays between Claude Code and Anthropic. PassControl never sees it or sits in the path.");
|
|
2882
|
+
if (note) {
|
|
2883
|
+
step("The agent's note: on a prompt, Claude Code is told this agent's tool rules (and any PassControl budget, which this plan's own calls do not count against). It is sent only when it changes.");
|
|
2884
|
+
} else {
|
|
2885
|
+
step(`Optional, tell the agent its tool rules, only when they change: ${cliCommand("configure claude-code --subscription --write --agent-note")}`);
|
|
2886
|
+
}
|
|
2859
2887
|
step("If the sidecar is not running, Claude Code still works: stops are not checked and calls are not shown until it is.");
|
|
2860
2888
|
step(`Watch the calls: ${cliCommand("watch")}`);
|
|
2861
2889
|
step(
|
|
@@ -2951,7 +2979,51 @@ function profileCommand(rest, opts) {
|
|
|
2951
2979
|
for (const r of rows) console.log(`${r.profile.padEnd(20)} passport ${r.passport.padEnd(10)} port ${r.port}`);
|
|
2952
2980
|
}
|
|
2953
2981
|
|
|
2982
|
+
/**
|
|
2983
|
+
* Subscription mode for Codex (cli/codex-hooks.mjs): a ChatGPT login keeps talking
|
|
2984
|
+
* to OpenAI directly; PassControl's stops and tool rules reach the session through
|
|
2985
|
+
* two hooks in $CODEX_HOME/hooks.json, next to anyone else's.
|
|
2986
|
+
*/
|
|
2987
|
+
function configureCodexSubscription(opts = {}) {
|
|
2988
|
+
const target = codexHooksPath();
|
|
2989
|
+
const port = sidecarPort(opts);
|
|
2990
|
+
if (opts.remove) {
|
|
2991
|
+
const result = removeCodexHooks({ target });
|
|
2992
|
+
if (result.changed) ok(`removed PassControl's hooks from ${target}`);
|
|
2993
|
+
else step(`${target} has no PassControl hooks; nothing to remove.`);
|
|
2994
|
+
return;
|
|
2995
|
+
}
|
|
2996
|
+
// node and this file by absolute path (cli/codex-hooks.mjs): PATH must not decide
|
|
2997
|
+
// whether a stop reaches Codex. The same string on every run, so trust holds.
|
|
2998
|
+
const command = codexHookCommand({ port, entry: fs.realpathSync(CLI_ENTRY) });
|
|
2999
|
+
console.log(`Preview: added to ${target} (anything already there is kept)\n\n${JSON.stringify(codexHookEntries(command), null, 2)}`);
|
|
3000
|
+
if (!opts.write) {
|
|
3001
|
+
step("Dry run only. Re-run with `--write` to add these two hooks.");
|
|
3002
|
+
} else {
|
|
3003
|
+
const result = writeCodexHooks({ target, command });
|
|
3004
|
+
if (!result.changed) ok(`${target} already has PassControl's hooks`);
|
|
3005
|
+
else {
|
|
3006
|
+
if (result.backupPath) step(`backed up ${result.backupPath}`);
|
|
3007
|
+
ok(`wrote ${target}`);
|
|
3008
|
+
warn("Not on yet: Codex runs a hook only after you trust it. Open Codex, type /hooks, and trust PassControl's two hooks. Until then they are skipped without a word.");
|
|
3009
|
+
}
|
|
3010
|
+
const probe = probeCodexHookCommand(command);
|
|
3011
|
+
if (probe.ok) ok("the hook command runs on its own, without your shell's PATH");
|
|
3012
|
+
else warn(`The hook command did not run cleanly on its own (${probe.why}). Codex would treat that as a failed hook and go ahead. If you move Node or this CLI, run this again.`);
|
|
3013
|
+
}
|
|
3014
|
+
step(`Start the sidecar before Codex: ${cliCommand(port === 8788 ? "sidecar" : `sidecar --port ${port}`)}`);
|
|
3015
|
+
step("Your ChatGPT login stays between Codex and OpenAI. PassControl never sees it or sits in the path.");
|
|
3016
|
+
step("What it does: a suspended agent, or the kill switch, blocks the next prompt and refuses tools. The agent's tool rules refuse what they deny; an \"ask the owner\" rule waits for the owner's answer.");
|
|
3017
|
+
step("What it cannot do, plainly:");
|
|
3018
|
+
step(" Codex has no strict hook mode. If the sidecar is not running, or a hook fails, Codex goes ahead (with a warning when the sidecar is down).");
|
|
3019
|
+
step(" Tool rules on paths (Read, Write, Edit) and web domains (WebFetch) name Claude Code's tools, which Codex does not have, so they do not apply here. Command rules (Bash) and MCP tool rules do.");
|
|
3020
|
+
step(" An \"ask\" rule cannot ask in Codex, so it refuses instead.");
|
|
3021
|
+
step(" Codex's calls are not shown on the agent's page, and a single Codex session cannot be stopped from the dashboard: suspend the agent instead.");
|
|
3022
|
+
step(`To undo: ${cliCommand("configure codex --subscription --remove")}`);
|
|
3023
|
+
}
|
|
3024
|
+
|
|
2954
3025
|
function configureCodex(opts = {}) {
|
|
3026
|
+
if (opts.subscription) return configureCodexSubscription(opts);
|
|
2955
3027
|
const target = codexProfilePath();
|
|
2956
3028
|
if (opts.remove) {
|
|
2957
3029
|
const result = removeCodexProfile({ target });
|
|
@@ -4447,6 +4519,22 @@ async function main(argv = process.argv.slice(2), runtime = {}) {
|
|
|
4447
4519
|
return;
|
|
4448
4520
|
}
|
|
4449
4521
|
|
|
4522
|
+
// Codex's hook relay (cli/codex-hooks.mjs), before the update check for the same
|
|
4523
|
+
// reason: on a prompt, everything it prints becomes context for the model. It
|
|
4524
|
+
// prints its answer or nothing, and exits 0 whatever happens.
|
|
4525
|
+
if (command === "codex-hook") {
|
|
4526
|
+
let input = "";
|
|
4527
|
+
try {
|
|
4528
|
+
for await (const chunk of process.stdin) input += chunk;
|
|
4529
|
+
const port = sidecarPort(opts);
|
|
4530
|
+
const out = await runCodexHook({ input, port });
|
|
4531
|
+
if (out) process.stdout.write(`${out}\n`);
|
|
4532
|
+
} catch {
|
|
4533
|
+
// Nothing: a hook that cannot run lets Codex go ahead, as a failed hook would.
|
|
4534
|
+
}
|
|
4535
|
+
return;
|
|
4536
|
+
}
|
|
4537
|
+
|
|
4450
4538
|
// Also before the update check: a full-screen board owns the terminal from its
|
|
4451
4539
|
// first frame, and the check's cache would be the one file `watch` ever wrote.
|
|
4452
4540
|
if (command === "watch" && !opts.help) {
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
// The agent's own note (1.6.0): what Claude Code is told about its PassControl limits
|
|
2
|
+
// when a prompt is sent. Opt-in (`configure claude-code --agent-note`), off by default.
|
|
3
|
+
//
|
|
4
|
+
// The sidecar's prompt hook returns it as `additionalContext`, and only when its
|
|
5
|
+
// signature changes: the limit crossing a band (25/50/75/90 %, used up), the reset
|
|
6
|
+
// coming within the hour, the pace turning to reach the limit before the reset or
|
|
7
|
+
// away from it, the tool rules changing. So it costs the session almost no context.
|
|
8
|
+
//
|
|
9
|
+
// Two setups, two notes, because they are different facts:
|
|
10
|
+
// * "api": Claude Code's calls go through the sidecar, so the budget is the one the
|
|
11
|
+
// gateway enforces on them, and how much is left and when it runs out at this
|
|
12
|
+
// rate (`pace`, from GET /api/v1/self) lets the agent plan before it is refused.
|
|
13
|
+
// Tool rules are left out: nothing in this setup enforces them.
|
|
14
|
+
// * "subscription": the calls go to Anthropic directly and never count against the
|
|
15
|
+
// budget (migration 0084), so the note leads with the tool rules, which do apply,
|
|
16
|
+
// and names any budget for what it covers.
|
|
17
|
+
import { formatTokens, formatUsd, when } from "./budget-format.mjs";
|
|
18
|
+
|
|
19
|
+
const BANDS = [0.25, 0.5, 0.75, 0.9, 1];
|
|
20
|
+
const MAX_RULES = 6;
|
|
21
|
+
const MAX_PATTERN = 60;
|
|
22
|
+
const EFFECT_TEXT = { deny: "is refused", ask_owner: "waits for the owner's approval", ask: "asks in the terminal" };
|
|
23
|
+
const PERIOD_WORD = { day: "today", month: "this month" };
|
|
24
|
+
|
|
25
|
+
const num = (v) => (v === null || v === undefined || !Number.isFinite(Number(v)) ? null : Number(v));
|
|
26
|
+
|
|
27
|
+
/** The limit the note speaks about: the period's, else the overall cost, else tokens. */
|
|
28
|
+
function bindingLimit(budget) {
|
|
29
|
+
if (!budget || typeof budget !== "object") return null;
|
|
30
|
+
const p = budget.period;
|
|
31
|
+
if (p && !p.unknown) {
|
|
32
|
+
const used = num(p.used_microcents);
|
|
33
|
+
const limit = num(p.limit_microcents);
|
|
34
|
+
if (used === null || !limit) return null;
|
|
35
|
+
return { kind: "period", period: p.kind, used, limit, left: Math.max(0, limit - used), resetsIn: num(p.resets_in_seconds) };
|
|
36
|
+
}
|
|
37
|
+
if (p?.unknown) return null;
|
|
38
|
+
if (budget.cost) {
|
|
39
|
+
const used = num(budget.cost.used_microcents);
|
|
40
|
+
const limit = num(budget.cost.limit_microcents);
|
|
41
|
+
if (used === null || !limit) return null;
|
|
42
|
+
return { kind: "cost", used, limit, left: Math.max(0, limit - used) };
|
|
43
|
+
}
|
|
44
|
+
if (budget.tokens) {
|
|
45
|
+
const used = num(budget.tokens.used);
|
|
46
|
+
const limit = num(budget.tokens.limit);
|
|
47
|
+
if (used === null || !limit) return null;
|
|
48
|
+
return { kind: "tokens", used, limit, left: Math.max(0, limit - used) };
|
|
49
|
+
}
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function band(limit) {
|
|
54
|
+
const f = limit.used / limit.limit;
|
|
55
|
+
const i = BANDS.findIndex((b) => f < b);
|
|
56
|
+
return i === -1 ? BANDS.length : i;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function amounts(limit) {
|
|
60
|
+
if (limit.kind === "tokens") return `${formatTokens(limit.left)} of ${formatTokens(limit.limit)} tokens left`;
|
|
61
|
+
const where = limit.kind === "period" ? PERIOD_WORD[limit.period] ?? "this period" : "in total";
|
|
62
|
+
return `${formatUsd(limit.left)} of ${formatUsd(limit.limit)} left ${where}`;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function resetAt(limit, nowMs, timeZone) {
|
|
66
|
+
return limit.kind === "period" && limit.resetsIn ? when(nowMs + limit.resetsIn * 1000, nowMs, timeZone) : null;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function apiBudgetText(limit, pace, pause, nowMs, timeZone) {
|
|
70
|
+
const reset = resetAt(limit, nowMs, timeZone);
|
|
71
|
+
if (limit.used >= limit.limit) {
|
|
72
|
+
const what = limit.kind === "period" ? `the budget for ${PERIOD_WORD[limit.period] ?? "this period"}` : "the total budget";
|
|
73
|
+
return `${what} is used up; PassControl refuses model calls until ${reset ? `it resets ${reset}` : "the owner raises it"}.`;
|
|
74
|
+
}
|
|
75
|
+
let text = `${amounts(limit)}${reset ? `; it resets ${reset}` : ""}.`;
|
|
76
|
+
// The soft pause (1.6.0, L4c): while paused every call is refused, so no pace.
|
|
77
|
+
if (pause.state === "paused") {
|
|
78
|
+
return `${text} PassControl has paused this agent at its ${pause.percent}% line and refuses its model calls until the owner lets it go on.`;
|
|
79
|
+
}
|
|
80
|
+
if (pause.state === "lifted") text += ` Its owner let it go on past its ${pause.percent}% pause line until ${pause.until}.`;
|
|
81
|
+
if (pause.state === "switched") {
|
|
82
|
+
text += ` Past its ${pause.percent}% line, PassControl sends its ${pause.provider} calls to ${pause.model} instead of the model it asks for; calls to any other provider are paused.`;
|
|
83
|
+
}
|
|
84
|
+
if (pace && typeof pace === "object") {
|
|
85
|
+
const at = pace.reaches_limit_at ? Date.parse(pace.reaches_limit_at) : null;
|
|
86
|
+
if (at !== null && Number.isFinite(at)) text += ` At this rate it runs out ${when(at, nowMs, timeZone)}.`;
|
|
87
|
+
else if (pace.reaches_limit_at === null) text += limit.kind === "period" ? " At this rate it lasts until the reset." : " At this rate it is not running out.";
|
|
88
|
+
}
|
|
89
|
+
return text;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function subscriptionBudgetText(limit, pause) {
|
|
93
|
+
if (limit.used < limit.limit && pause.state === "switched") {
|
|
94
|
+
return `calls made through PassControl (not this Claude plan) to ${pause.provider} go to ${pause.model} past this agent's ${pause.percent}% line.`;
|
|
95
|
+
}
|
|
96
|
+
if (limit.used < limit.limit && pause.state === "paused") {
|
|
97
|
+
return `calls made through PassControl (not this Claude plan) are paused at this agent's ${pause.percent}% line until the owner lets them go on.`;
|
|
98
|
+
}
|
|
99
|
+
if (limit.used >= limit.limit) {
|
|
100
|
+
return `calls made through PassControl (not this Claude plan) have used up their budget${limit.kind === "period" ? ` for ${PERIOD_WORD[limit.period] ?? "this period"}` : ""}.`;
|
|
101
|
+
}
|
|
102
|
+
return `calls made through PassControl (not this Claude plan) have ${amounts(limit)}.`;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function ruleList(rules) {
|
|
106
|
+
if (!rules || rules.state !== "ok" || !Array.isArray(rules.document?.rules)) return null;
|
|
107
|
+
const list = rules.document.rules.filter((r) => r && typeof r.tool === "string" && EFFECT_TEXT[r.effect]);
|
|
108
|
+
return list.length ? list : null;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function rulesText(list) {
|
|
112
|
+
const shown = list.slice(0, MAX_RULES).map((r) => {
|
|
113
|
+
const raw = [r.command, r.path, r.domain].find((v) => typeof v === "string" && v.length);
|
|
114
|
+
const pattern = raw ? ` \`${raw.length > MAX_PATTERN ? `${raw.slice(0, MAX_PATTERN)}…` : raw}\`` : "";
|
|
115
|
+
return `${r.tool}${pattern} ${EFFECT_TEXT[r.effect]}`;
|
|
116
|
+
});
|
|
117
|
+
const more = list.length - shown.length;
|
|
118
|
+
return `this agent's tool rules are ${shown.join("; ")}${more > 0 ? `; and ${more} more` : ""}. They are set on the agent's page.`;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const capital = (s) => s.charAt(0).toUpperCase() + s.slice(1);
|
|
122
|
+
|
|
123
|
+
/** The pause from GET /api/v1/self, as the note needs it: paused, switched (to what), lifted (until when), or neither. */
|
|
124
|
+
function pauseOf(self, nowMs, timeZone) {
|
|
125
|
+
const p = self?.pause;
|
|
126
|
+
const percent = Number(p?.percent);
|
|
127
|
+
if (!p || typeof p !== "object" || !Number.isInteger(percent)) return { state: "" };
|
|
128
|
+
if (p.paused === true) return { state: "paused", percent };
|
|
129
|
+
// L7 (0088): on the owner's cheaper model past the line. Printed into the agent's
|
|
130
|
+
// context, so only plain printable names are used.
|
|
131
|
+
const sw = p.switch_to;
|
|
132
|
+
const plain = (v) => typeof v === "string" && /^[\x20-\x7e]{1,200}$/u.test(v);
|
|
133
|
+
if (sw && sw.active === true && plain(sw.provider) && plain(sw.model)) return { state: "switched", percent, provider: sw.provider, model: sw.model };
|
|
134
|
+
const end = p.lifted_until ? Date.parse(p.lifted_until) : NaN;
|
|
135
|
+
if (Number.isFinite(end)) return { state: "lifted", percent, until: when(end, nowMs, timeZone).replace(/^at /, "") };
|
|
136
|
+
return { state: "" };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* The note for one prompt, or null when there is nothing to say.
|
|
141
|
+
* @param {{ self: object | null, rules: object | null, mode: "api" | "subscription", nowMs: number, timeZone?: string }} input
|
|
142
|
+
* @returns {{ text: string, signature: string } | null}
|
|
143
|
+
*/
|
|
144
|
+
export function agentNote({ self, rules, mode, nowMs, timeZone }) {
|
|
145
|
+
const limit = bindingLimit(self?.budget);
|
|
146
|
+
const pace = self?.pace ?? null;
|
|
147
|
+
const pause = pauseOf(self, nowMs, timeZone);
|
|
148
|
+
const parts = [];
|
|
149
|
+
let rulesSig = "";
|
|
150
|
+
|
|
151
|
+
if (mode === "subscription") {
|
|
152
|
+
const list = ruleList(rules);
|
|
153
|
+
if (list) {
|
|
154
|
+
parts.push(rulesText(list));
|
|
155
|
+
rulesSig = JSON.stringify(list.map((r) => [r.tool, r.command, r.path, r.domain, r.effect]));
|
|
156
|
+
}
|
|
157
|
+
if (limit) parts.push(subscriptionBudgetText(limit, pause));
|
|
158
|
+
} else if (limit) {
|
|
159
|
+
parts.push(apiBudgetText(limit, pace, pause, nowMs, timeZone));
|
|
160
|
+
}
|
|
161
|
+
if (parts.length === 0) return null;
|
|
162
|
+
|
|
163
|
+
const head = mode === "subscription" ? "PassControl note (sent when it changes): " : "PassControl budget note (sent when it changes): ";
|
|
164
|
+
const text = head + parts.map((p, i) => (i === 0 ? p : capital(p))).join(" ");
|
|
165
|
+
const resetNear = limit?.kind === "period" && limit.resetsIn !== null && limit.resetsIn <= 3600;
|
|
166
|
+
const paceReaches = mode === "api" && pace && typeof pace === "object" ? (pace.reaches_limit_at ? "reaches" : "lasts") : "";
|
|
167
|
+
const signature = [mode, limit ? `${limit.kind}:${limit.period ?? ""}:${band(limit)}` : "-", resetNear ? "reset-near" : "", paceReaches, rulesSig, pause.state].join("|");
|
|
168
|
+
return { text, signature };
|
|
169
|
+
}
|
package/cli/budget-format.mjs
CHANGED
|
@@ -17,7 +17,7 @@ export function formatUsd(microcents) {
|
|
|
17
17
|
}
|
|
18
18
|
|
|
19
19
|
/** A token count the way a status line has room for: 950, 12.3k, 1.2M. */
|
|
20
|
-
function formatTokens(n) {
|
|
20
|
+
export function formatTokens(n) {
|
|
21
21
|
if (n === null || n === undefined || !Number.isFinite(Number(n))) return "?";
|
|
22
22
|
const v = Number(n);
|
|
23
23
|
if (v >= 1_000_000) return `${trim(v / 1_000_000)}M`;
|
|
@@ -37,21 +37,84 @@ function resetsIn(seconds) {
|
|
|
37
37
|
const PERIOD_WORD = { day: "today", month: "this month" };
|
|
38
38
|
const PERIOD_LABEL = { day: "Today", month: "This month" };
|
|
39
39
|
|
|
40
|
-
/**
|
|
41
|
-
export function
|
|
40
|
+
/** "at 16:00" within a day, "Sat 12:00" within a week, "on 1 Nov" past that, in local time. */
|
|
41
|
+
export function when(ms, nowMs, timeZone) {
|
|
42
|
+
const d = new Date(ms);
|
|
43
|
+
const time = d.toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit", hour12: false, timeZone });
|
|
44
|
+
if (ms - nowMs < 86_400_000) return `at ${time}`;
|
|
45
|
+
if (ms - nowMs < 7 * 86_400_000) return `${d.toLocaleDateString("en-GB", { weekday: "short", timeZone })} ${time}`;
|
|
46
|
+
return `on ${d.toLocaleDateString("en-GB", { day: "numeric", month: "short", timeZone })}`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// The pace (GET /api/v1/self, 1.6.0): when the first limit runs out at the current rate.
|
|
50
|
+
const PACE_NAME = { cost: "the total budget", tokens: "the token limit" };
|
|
51
|
+
function paceOf(self, { nowMs = Date.now(), timeZone } = {}) {
|
|
52
|
+
const pace = self?.pace;
|
|
53
|
+
if (!pace || typeof pace !== "object" || !["period", "cost", "tokens"].includes(pace.limit)) return null;
|
|
54
|
+
const kind = self?.budget?.period?.kind;
|
|
55
|
+
const name = pace.limit === "period" ? `${kind === "month" ? "this month's" : "today's"} limit` : PACE_NAME[pace.limit];
|
|
56
|
+
const at = pace.reaches_limit_at ? Date.parse(pace.reaches_limit_at) : NaN;
|
|
57
|
+
if (Number.isFinite(at)) return { limit: pace.limit, name, runsOut: when(at, nowMs, timeZone) };
|
|
58
|
+
if (pace.reaches_limit_at === null) return { limit: pace.limit, name, runsOut: null };
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
// The soft pause (GET /api/v1/self `pause`, 1.6.0): while the agent is paused every
|
|
62
|
+
// call is refused, so the pause replaces the pace wherever both would be said.
|
|
63
|
+
|
|
64
|
+
/** Whether /self says the gateway is refusing this agent's calls for its pause line. */
|
|
65
|
+
export function paused(self) {
|
|
66
|
+
return self?.pause?.paused === true && Number.isFinite(Number(self.pause.percent));
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** The lift's end as `when` says it, or null with no readable lift. */
|
|
70
|
+
function liftedUntil(self, { nowMs = Date.now(), timeZone } = {}) {
|
|
71
|
+
const at = self?.pause?.lifted_until ? Date.parse(self.pause.lifted_until) : NaN;
|
|
72
|
+
return Number.isFinite(at) && !paused(self) ? when(at, nowMs, timeZone).replace(/^at /, "") : null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// L7 (0088): the owner's cheaper model at the line, when /self names one. Printed
|
|
76
|
+
// in a terminal and an agent's context, so only a plain printable name is used.
|
|
77
|
+
const printable = (v) => typeof v === "string" && /^[\x20-\x7e]{1,200}$/u.test(v);
|
|
78
|
+
function switchOf(self) {
|
|
79
|
+
const s = self?.pause?.switch_to;
|
|
80
|
+
return s && printable(s.provider) && printable(s.model) ? { provider: s.provider, model: s.model, active: s.active === true } : null;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const pausePercent = (self) => {
|
|
84
|
+
const p = Number(self?.pause?.percent);
|
|
85
|
+
return Number.isInteger(p) && p >= 1 && p <= 99 ? p : null;
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
const paceSentence = (p) =>
|
|
89
|
+
p.runsOut ? `${p.name} runs out ${p.runsOut}` : `${p.name} ${p.limit === "period" ? "lasts until it resets" : "is not running out"}`;
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* One line for Claude Code's status line. The most pressing limit wins, and when the
|
|
93
|
+
* pace says that limit runs out, when.
|
|
94
|
+
*/
|
|
95
|
+
export function statusLine(self, opts = {}) {
|
|
42
96
|
const b = self?.budget ?? {};
|
|
43
97
|
const prefix = "PassControl · ";
|
|
44
98
|
if (b.period && b.period.unknown) return `${prefix}limit unknown`;
|
|
99
|
+
const pace = paused(self) ? null : paceOf(self, opts);
|
|
100
|
+
const runsOut = (kind) => (pace?.limit === kind && pace.runsOut ? ` · runs out ${pace.runsOut}` : "");
|
|
101
|
+
const sw = switchOf(self);
|
|
102
|
+
const line = pausePercent(self);
|
|
103
|
+
const head = paused(self)
|
|
104
|
+
? `${prefix}paused at its ${self.pause.percent}% line · `
|
|
105
|
+
: sw?.active && line !== null
|
|
106
|
+
? `${prefix}on ${sw.model} past its ${line}% line · `
|
|
107
|
+
: prefix;
|
|
45
108
|
if (b.period) {
|
|
46
|
-
return `${
|
|
109
|
+
return `${head}${formatUsd(b.period.used_microcents)} of ${formatUsd(b.period.limit_microcents)} ${PERIOD_WORD[b.period.kind] ?? ""}`.trimEnd() + runsOut("period");
|
|
47
110
|
}
|
|
48
|
-
if (b.cost) return `${
|
|
49
|
-
if (b.tokens) return `${
|
|
111
|
+
if (b.cost) return `${head}${formatUsd(b.cost.used_microcents)} of ${formatUsd(b.cost.limit_microcents)} total${runsOut("cost")}`;
|
|
112
|
+
if (b.tokens) return `${head}${formatTokens(b.tokens.used)} of ${formatTokens(b.tokens.limit)} tokens${runsOut("tokens")}`;
|
|
50
113
|
return `${prefix}no limit`;
|
|
51
114
|
}
|
|
52
115
|
|
|
53
116
|
/** Every limit, with what is left: the MCP tool's text answer. */
|
|
54
|
-
export function budgetLines(self) {
|
|
117
|
+
export function budgetLines(self, opts = {}) {
|
|
55
118
|
const b = self?.budget ?? {};
|
|
56
119
|
const lines = [];
|
|
57
120
|
if (b.period && b.period.unknown) {
|
|
@@ -72,6 +135,23 @@ export function budgetLines(self) {
|
|
|
72
135
|
lines.push(`Tokens: ${formatTokens(b.tokens.used)} of ${formatTokens(b.tokens.limit)} used, ${formatTokens(b.tokens.remaining)} left.`);
|
|
73
136
|
}
|
|
74
137
|
if (lines.length === 0) lines.push("No spending or token limit is set for this agent.");
|
|
138
|
+
const line = pausePercent(self);
|
|
139
|
+
const lifted = liftedUntil(self, opts);
|
|
140
|
+
if (paused(self)) {
|
|
141
|
+
lines.push(`PassControl has paused this agent at its ${line}% line: it refuses model calls until the owner lets it go on from the agent's page.`);
|
|
142
|
+
return lines;
|
|
143
|
+
}
|
|
144
|
+
const sw = switchOf(self);
|
|
145
|
+
if (line !== null && sw?.active) {
|
|
146
|
+
lines.push(
|
|
147
|
+
`Past its ${line}% line, PassControl sends this agent's ${sw.provider} calls to ${sw.model} instead of the model asked for; calls to any other provider are paused.`
|
|
148
|
+
);
|
|
149
|
+
} else if (line !== null && lifted) lines.push(`Its owner let it go on past its ${line}% pause line until ${lifted}.`);
|
|
150
|
+
else if (line !== null && !self.pause.limit && sw) {
|
|
151
|
+
lines.push(`At ${line}% of any limit, PassControl switches this agent's ${sw.provider} calls to ${sw.model} instead of pausing them.`);
|
|
152
|
+
} else if (line !== null && !self.pause.limit) lines.push(`PassControl pauses it at ${line}% of any limit, before the limit itself is reached.`);
|
|
153
|
+
const pace = paceOf(self, opts);
|
|
154
|
+
if (pace) lines.push(`At this rate, ${paceSentence(pace)}.`);
|
|
75
155
|
return lines;
|
|
76
156
|
}
|
|
77
157
|
|
|
@@ -79,7 +159,7 @@ export function budgetLines(self) {
|
|
|
79
159
|
* Every limit as a [label, value] row, for the `/passcontrol` panel in Claude Code
|
|
80
160
|
* (`passcontrol statusline --panel`): "Today", "$0.42 of $10.00 · $9.58 left · resets in 7h".
|
|
81
161
|
*/
|
|
82
|
-
export function panelRows(self) {
|
|
162
|
+
export function panelRows(self, opts = {}) {
|
|
83
163
|
const b = self?.budget ?? {};
|
|
84
164
|
const rows = [];
|
|
85
165
|
if (b.period && b.period.unknown) {
|
|
@@ -98,6 +178,19 @@ export function panelRows(self) {
|
|
|
98
178
|
rows.push(["Tokens", `${formatTokens(b.tokens.used)} of ${formatTokens(b.tokens.limit)} · ${formatTokens(b.tokens.remaining)} left`]);
|
|
99
179
|
}
|
|
100
180
|
if (rows.length === 0) rows.push(["Limit", "none set"]);
|
|
181
|
+
const line = pausePercent(self);
|
|
182
|
+
const lifted = liftedUntil(self, opts);
|
|
183
|
+
if (paused(self)) {
|
|
184
|
+
rows.push(["Paused", `at its ${line}% line · the owner can let it go on from the agent's page`]);
|
|
185
|
+
return rows;
|
|
186
|
+
}
|
|
187
|
+
const sw = switchOf(self);
|
|
188
|
+
if (line !== null && sw?.active) rows.push(["Switched", `to ${sw.model} past its ${line}% line · other providers paused`]);
|
|
189
|
+
else if (line !== null && lifted) rows.push(["Pause", `lifted until ${lifted} · line at ${line}%`]);
|
|
190
|
+
else if (line !== null && !self.pause.limit && sw) rows.push(["Pause", `at ${line}% of any limit · switches ${sw.provider} to ${sw.model}`]);
|
|
191
|
+
else if (line !== null && !self.pause.limit) rows.push(["Pause", `at ${line}% of any limit`]);
|
|
192
|
+
const pace = paceOf(self, opts);
|
|
193
|
+
if (pace) rows.push(["Pace", paceSentence(pace)]);
|
|
101
194
|
return rows;
|
|
102
195
|
}
|
|
103
196
|
|
package/cli/claude-code.mjs
CHANGED
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
import fs from "node:fs";
|
|
16
16
|
import os from "node:os";
|
|
17
17
|
import path from "node:path";
|
|
18
|
+
import { GATE_HOOK_TIMEOUT_S } from "./subscription-gate.mjs";
|
|
18
19
|
|
|
19
20
|
/** Not a secret: the sidecar discards whatever arrives in this header. */
|
|
20
21
|
export const CLAUDE_CODE_AUTH_PLACEHOLDER = "passcontrol-sidecar";
|
|
@@ -65,11 +66,37 @@ function save(target, value, exists) {
|
|
|
65
66
|
return backupPath;
|
|
66
67
|
}
|
|
67
68
|
|
|
69
|
+
/**
|
|
70
|
+
* `hooks` with API mode's note-only prompt hook for `port`, or without it when `port`
|
|
71
|
+
* is null. Every other hook, subscription mode's included, is left as it is.
|
|
72
|
+
*/
|
|
73
|
+
function withNoteOnlyHook(hooks, port) {
|
|
74
|
+
const isNoteOnly = (h) => isObject(h) && h.type === "http" && typeof h.url === "string" && OUR_NOTE_ONLY_URL.test(h.url);
|
|
75
|
+
const base = isObject(hooks) ? hooks : null;
|
|
76
|
+
const groups = Array.isArray(base?.UserPromptSubmit) ? base.UserPromptSubmit : [];
|
|
77
|
+
const kept = [];
|
|
78
|
+
for (const group of groups) {
|
|
79
|
+
if (!isObject(group) || !Array.isArray(group.hooks) || !group.hooks.some(isNoteOnly)) kept.push(group);
|
|
80
|
+
else {
|
|
81
|
+
const rest = group.hooks.filter((h) => !isNoteOnly(h));
|
|
82
|
+
if (rest.length) kept.push({ ...group, hooks: rest });
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
const ours = { hooks: [{ type: "http", url: `${LOOPBACK_BASE}${port}/_passcontrol/hook?note=only`, timeout: GATE_HOOK_TIMEOUT_S }] };
|
|
86
|
+
if (port !== null && groups.length === kept.length + 1 && groups.some((g) => same(g, ours))) return hooks;
|
|
87
|
+
if (port !== null) kept.push(ours);
|
|
88
|
+
if (!base && !kept.length) return hooks;
|
|
89
|
+
const next = { ...(base ?? {}) };
|
|
90
|
+
if (kept.length) next.UserPromptSubmit = kept;
|
|
91
|
+
else delete next.UserPromptSubmit;
|
|
92
|
+
return next;
|
|
93
|
+
}
|
|
94
|
+
|
|
68
95
|
/**
|
|
69
96
|
* The env keys, and with `statusLineCommand` the status line too, in ONE save:
|
|
70
97
|
* two saves would back up the first save's output and lose the user's original.
|
|
71
98
|
*/
|
|
72
|
-
export function writeClaudeCodeSettings({ target, baseUrl, force = false, statusLineCommand = null }) {
|
|
99
|
+
export function writeClaudeCodeSettings({ target, baseUrl, force = false, statusLineCommand = null, noteHookPort = null }) {
|
|
73
100
|
const { exists, value } = readSettings(target);
|
|
74
101
|
const env = typeof value.env === "object" && value.env !== null && !Array.isArray(value.env) ? value.env : {};
|
|
75
102
|
const rawKeyFound = typeof env.ANTHROPIC_API_KEY === "string" && env.ANTHROPIC_API_KEY.length > 0;
|
|
@@ -87,7 +114,14 @@ export function writeClaudeCodeSettings({ target, baseUrl, force = false, status
|
|
|
87
114
|
next = line.value;
|
|
88
115
|
statusLine = line.existing !== undefined ? { changed: false, existing: line.existing } : { changed: line.changed };
|
|
89
116
|
}
|
|
90
|
-
const
|
|
117
|
+
const hooks = withNoteOnlyHook(value.hooks, noteHookPort);
|
|
118
|
+
const hooksChanged = !same(hooks ?? null, value.hooks ?? null);
|
|
119
|
+
if (hooksChanged) {
|
|
120
|
+
next = { ...next };
|
|
121
|
+
if (hooks && Object.keys(hooks).length) next.hooks = hooks;
|
|
122
|
+
else delete next.hooks;
|
|
123
|
+
}
|
|
124
|
+
const changed = !envDone || Boolean(statusLine?.changed) || hooksChanged;
|
|
91
125
|
const backupPath = changed ? save(target, next, exists) : null;
|
|
92
126
|
return { changed, backupPath, rawKeyFound, ...(statusLine ? { statusLine } : {}) };
|
|
93
127
|
}
|
|
@@ -110,6 +144,14 @@ export function removeClaudeCodeSettings({ target }) {
|
|
|
110
144
|
const { statusLine: _ours, ...rest } = next;
|
|
111
145
|
next = rest;
|
|
112
146
|
}
|
|
147
|
+
if (isObject(next.hooks)) {
|
|
148
|
+
const hooks = withNoteOnlyHook(next.hooks, null);
|
|
149
|
+
if (!same(hooks, next.hooks)) {
|
|
150
|
+
next = { ...next };
|
|
151
|
+
if (Object.keys(hooks).length) next.hooks = hooks;
|
|
152
|
+
else delete next.hooks;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
113
155
|
if (next === value) return { changed: false };
|
|
114
156
|
save(target, next, true);
|
|
115
157
|
return { changed: true };
|
|
@@ -176,7 +218,9 @@ export function removeClaudeCodeStatusLine({ target }) {
|
|
|
176
218
|
|
|
177
219
|
const LOOPBACK_BASE = "http://127.0.0.1:";
|
|
178
220
|
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})?$/;
|
|
221
|
+
const OUR_HOOK_URL = /^http:\/\/127\.0\.0\.1:\d{1,5}\/_passcontrol\/hook(\?(t=\d{1,4}|note=1))?$/;
|
|
222
|
+
// API mode's own prompt hook, for the agent's note only (1.6.0): never a stop.
|
|
223
|
+
const OUR_NOTE_ONLY_URL = /^http:\/\/127\.0\.0\.1:\d{1,5}\/_passcontrol\/hook\?note=only$/;
|
|
180
224
|
const OUR_SIDECAR_URL = /^http:\/\/127\.0\.0\.1:\d{1,5}$/;
|
|
181
225
|
const GATED_EVENTS = ["UserPromptSubmit", "PreToolUse", "PostToolBatch"];
|
|
182
226
|
// The log-export settings this mode owns, with the value it writes.
|
|
@@ -196,8 +240,8 @@ export function subscriptionEnv(port) {
|
|
|
196
240
|
};
|
|
197
241
|
}
|
|
198
242
|
|
|
199
|
-
function gateHook(port) {
|
|
200
|
-
return { type: "http", url: `${LOOPBACK_BASE}${port}/_passcontrol/hook`, timeout:
|
|
243
|
+
function gateHook(port, note = false) {
|
|
244
|
+
return { type: "http", url: `${LOOPBACK_BASE}${port}/_passcontrol/hook${note ? "?note=1" : ""}`, timeout: GATE_HOOK_TIMEOUT_S };
|
|
201
245
|
}
|
|
202
246
|
|
|
203
247
|
// PreToolUse may hold a tool while the owner is asked (Phase 2), and Claude Code lets
|
|
@@ -210,10 +254,11 @@ function toolHook(port) {
|
|
|
210
254
|
return { type: "http", url: `${LOOPBACK_BASE}${port}/_passcontrol/hook?t=${TOOL_HOOK_TIMEOUT_S}`, timeout: TOOL_HOOK_TIMEOUT_S };
|
|
211
255
|
}
|
|
212
256
|
|
|
213
|
-
|
|
257
|
+
/** `note`: the agent's opt-in note rides on the prompt hook (`--agent-note`). */
|
|
258
|
+
export function subscriptionHooks(port, { note = false } = {}) {
|
|
214
259
|
const hook = gateHook(port);
|
|
215
260
|
return {
|
|
216
|
-
UserPromptSubmit: [{ hooks: [
|
|
261
|
+
UserPromptSubmit: [{ hooks: [gateHook(port, note)] }],
|
|
217
262
|
PreToolUse: [{ matcher: "*", hooks: [toolHook(port)] }],
|
|
218
263
|
PostToolBatch: [{ hooks: [hook] }],
|
|
219
264
|
};
|
|
@@ -247,8 +292,8 @@ function withoutOurHooks(hooks) {
|
|
|
247
292
|
}
|
|
248
293
|
|
|
249
294
|
/** `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);
|
|
295
|
+
function withOurHooks(hooks, port, note = false) {
|
|
296
|
+
const ours = subscriptionHooks(port, { note });
|
|
252
297
|
const base = isObject(hooks) ? hooks : {};
|
|
253
298
|
const next = withoutOurHooks(base);
|
|
254
299
|
for (const event of GATED_EVENTS) {
|
|
@@ -273,7 +318,7 @@ function urlAllowed(patterns, url) {
|
|
|
273
318
|
* Subscription mode's settings, in one save. Throws, writing nothing, when the
|
|
274
319
|
* user already exports Claude Code's logs somewhere else and `force` is not set.
|
|
275
320
|
*/
|
|
276
|
-
export function writeClaudeCodeSubscription({ target, port, statusLineCommand, force = false }) {
|
|
321
|
+
export function writeClaudeCodeSubscription({ target, port, statusLineCommand, force = false, note = false }) {
|
|
277
322
|
const { exists, value } = readSettings(target);
|
|
278
323
|
const env = isObject(value.env) ? value.env : {};
|
|
279
324
|
const endpoint = env.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT;
|
|
@@ -286,7 +331,7 @@ export function writeClaudeCodeSubscription({ target, port, statusLineCommand, f
|
|
|
286
331
|
`${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
332
|
);
|
|
288
333
|
}
|
|
289
|
-
let next = { ...value, env: { ...env, ...subscriptionEnv(port) }, hooks: withOurHooks(value.hooks, port) };
|
|
334
|
+
let next = { ...value, env: { ...env, ...subscriptionEnv(port) }, hooks: withOurHooks(value.hooks, port, note) };
|
|
290
335
|
let statusLine;
|
|
291
336
|
if (statusLineCommand) {
|
|
292
337
|
const line = withStatusLine(next, statusLineCommand);
|
|
@@ -300,7 +345,7 @@ export function writeClaudeCodeSubscription({ target, port, statusLineCommand, f
|
|
|
300
345
|
changed,
|
|
301
346
|
backupPath,
|
|
302
347
|
...(statusLine ? { statusLine } : {}),
|
|
303
|
-
hookUrlsBlocked: Boolean(allowlist && [gateHook(port), toolHook(port)].some((h) => !urlAllowed(allowlist, h.url))),
|
|
348
|
+
hookUrlsBlocked: Boolean(allowlist && [gateHook(port), gateHook(port, note), toolHook(port)].some((h) => !urlAllowed(allowlist, h.url))),
|
|
304
349
|
routed: env.ANTHROPIC_AUTH_TOKEN === CLAUDE_CODE_AUTH_PLACEHOLDER && typeof env.ANTHROPIC_BASE_URL === "string",
|
|
305
350
|
};
|
|
306
351
|
}
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
// Subscription mode for Codex (1.6.0, L5).
|
|
2
|
+
//
|
|
3
|
+
// A Codex session signed in with a ChatGPT plan talks to OpenAI directly, so the
|
|
4
|
+
// gateway cannot refuse its calls, as with a Claude Pro/Max login
|
|
5
|
+
// (cli/subscription-gate.mjs). The stops and tool rules still reach it through
|
|
6
|
+
// Codex's hooks: `passcontrol configure codex --subscription` adds two to
|
|
7
|
+
// `$CODEX_HOME/hooks.json`, each running `passcontrol codex-hook`, which hands
|
|
8
|
+
// Codex's input to the sidecar's hook endpoint (the one Claude Code calls) and
|
|
9
|
+
// answers in Codex's terms:
|
|
10
|
+
//
|
|
11
|
+
// UserPromptSubmit a stopped agent's prompt is blocked and the turn ends
|
|
12
|
+
// PreToolUse a stopped agent's tools, and the tool rules' denials, are refused
|
|
13
|
+
//
|
|
14
|
+
// Codex has command hooks only (no http hook), hence the relay. Three differences
|
|
15
|
+
// from Claude Code are handled here, not in the sidecar:
|
|
16
|
+
// * hooks.json is SHARED (Peras writes into it), unlike the profile file
|
|
17
|
+
// cli/codex.mjs writes. Only entries whose command is PassControl's are added,
|
|
18
|
+
// replaced or removed (Peras's `ours()` rule), and the file is backed up the first
|
|
19
|
+
// time PassControl writes into one it did not create;
|
|
20
|
+
// * on PreToolUse, Codex takes `continue`, `stopReason`, `suppressOutput` and
|
|
21
|
+
// `permissionDecision: "ask"` as a FAILED hook and runs the tool. The sidecar's
|
|
22
|
+
// answers carry `continue: false` with every stop, so Codex's answer is rebuilt
|
|
23
|
+
// from an allow-list, and an "ask" rule becomes a refusal that says why;
|
|
24
|
+
// * Codex runs a hook only once the user has trusted it in `/hooks`, by its hash.
|
|
25
|
+
// The command is the same string on every run of configure, so a trusted hook
|
|
26
|
+
// stays trusted;
|
|
27
|
+
// * the command names node and the CLI by absolute path, like Peras's. A bare
|
|
28
|
+
// `passcontrol` failed both ways on the owner's Mac: "command not found" under a
|
|
29
|
+
// GUI app's minimal PATH, and "Unknown command" from an older CLI on PATH. Either
|
|
30
|
+
// is a failed hook, so configure runs the exact command once under a bare PATH
|
|
31
|
+
// before saying it is set up.
|
|
32
|
+
//
|
|
33
|
+
// Honest limits, said in the CLI too: Codex has no strict hook mode, so a hook that
|
|
34
|
+
// fails or is not trusted lets the action go ahead; the tool rules' path rules (Read,
|
|
35
|
+
// Write, Edit) and domain rules (WebFetch) name Claude Code's tools, which Codex does
|
|
36
|
+
// not have, so only command rules (Bash) and MCP tool rules can match; and a session
|
|
37
|
+
// cannot be stopped on its own, since its calls never pass the gateway.
|
|
38
|
+
import { spawnSync } from "node:child_process";
|
|
39
|
+
import fs from "node:fs";
|
|
40
|
+
import os from "node:os";
|
|
41
|
+
import path from "node:path";
|
|
42
|
+
|
|
43
|
+
import { GATE_HOOK_TIMEOUT_S, HOOK_PATH } from "./subscription-gate.mjs";
|
|
44
|
+
|
|
45
|
+
/** Codex's timeout for the tool hook: an "ask the owner" rule holds it while the owner answers. */
|
|
46
|
+
export const CODEX_TOOL_HOOK_TIMEOUT_S = 600;
|
|
47
|
+
const PROMPT_RELAY_MS = GATE_HOOK_TIMEOUT_S * 1000 - 500;
|
|
48
|
+
const TOOL_RELAY_MS = (CODEX_TOOL_HOOK_TIMEOUT_S - 10) * 1000;
|
|
49
|
+
const EVENTS = ["UserPromptSubmit", "PreToolUse"];
|
|
50
|
+
const BACKUP_SUFFIX = ".passcontrol-backup";
|
|
51
|
+
|
|
52
|
+
const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
53
|
+
const text = (v) => (typeof v === "string" && v.length > 0 ? v : null);
|
|
54
|
+
|
|
55
|
+
export function codexHooksPath({ env = process.env } = {}) {
|
|
56
|
+
return path.join(env.CODEX_HOME || path.join(env.HOME || os.homedir(), ".codex"), "hooks.json");
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** PassControl's own entry: `passcontrol codex-hook …`, or `node ".../passcontrol.mjs" codex-hook …`. */
|
|
60
|
+
export function isPassControlCodexHook(hook) {
|
|
61
|
+
return isObject(hook) && hook.type === "command" && typeof hook.command === "string" && /(^|[\s"/])passcontrol(\.mjs)?"?\s+codex-hook(\s|$)/u.test(hook.command);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* The command both hooks run: node and the CLI by absolute path, so PATH never
|
|
66
|
+
* decides whether it runs. Refuses a path a shell would read differently.
|
|
67
|
+
*/
|
|
68
|
+
export function codexHookCommand({ port, node = process.execPath, entry }) {
|
|
69
|
+
for (const p of [node, entry]) {
|
|
70
|
+
if (typeof p !== "string" || !p || /["$`]/u.test(p)) {
|
|
71
|
+
throw new Error(`The path ${JSON.stringify(String(p))} cannot be quoted safely for Codex's hook command.`);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return `"${node}" "${entry}" codex-hook --port ${port}`;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Runs the exact command as Codex would, under a bare PATH, with an input it answers
|
|
79
|
+
* with nothing. Not on Windows, where Codex runs hooks through its own shell.
|
|
80
|
+
*/
|
|
81
|
+
export function probeCodexHookCommand(command) {
|
|
82
|
+
if (process.platform === "win32") return { ok: true };
|
|
83
|
+
const run = spawnSync("/bin/sh", ["-c", command], {
|
|
84
|
+
input: JSON.stringify({ hook_event_name: "SessionStart" }),
|
|
85
|
+
env: { PATH: "/usr/bin:/bin", HOME: os.homedir(), PASSCONTROL_NO_UPDATE_CHECK: "1" },
|
|
86
|
+
encoding: "utf8",
|
|
87
|
+
timeout: 15_000,
|
|
88
|
+
});
|
|
89
|
+
if (run.status !== 0) return { ok: false, why: `it ended with exit ${run.status ?? "none"}${run.stderr ? `: ${run.stderr.trim().slice(0, 200)}` : ""}` };
|
|
90
|
+
if (run.stdout.trim()) return { ok: false, why: `it printed output it should not: ${run.stdout.trim().slice(0, 200)}` };
|
|
91
|
+
return { ok: true };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** The two entries PassControl adds, as a hooks file of their own. */
|
|
95
|
+
export function codexHookEntries(command) {
|
|
96
|
+
return {
|
|
97
|
+
hooks: {
|
|
98
|
+
UserPromptSubmit: [{ hooks: [{ type: "command", command, timeout: GATE_HOOK_TIMEOUT_S }] }],
|
|
99
|
+
PreToolUse: [{ matcher: ".*", hooks: [{ type: "command", command, timeout: CODEX_TOOL_HOOK_TIMEOUT_S }] }],
|
|
100
|
+
},
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function readHooksFile(target) {
|
|
105
|
+
if (!fs.existsSync(target)) return { value: {}, exists: false };
|
|
106
|
+
let value;
|
|
107
|
+
try {
|
|
108
|
+
value = JSON.parse(fs.readFileSync(target, "utf8"));
|
|
109
|
+
} catch {
|
|
110
|
+
value = null;
|
|
111
|
+
}
|
|
112
|
+
if (!isObject(value) || (value.hooks !== undefined && !isObject(value.hooks))) {
|
|
113
|
+
throw new Error(`${target} is not a hooks object; nothing was written.`);
|
|
114
|
+
}
|
|
115
|
+
return { value, exists: true };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Each event's groups with PassControl's hooks taken out; a group left empty goes. */
|
|
119
|
+
function withoutOurs(hooks) {
|
|
120
|
+
const next = { ...hooks };
|
|
121
|
+
for (const event of Object.keys(next)) {
|
|
122
|
+
if (!Array.isArray(next[event])) continue;
|
|
123
|
+
next[event] = next[event].flatMap((group) => {
|
|
124
|
+
if (!isObject(group) || !Array.isArray(group.hooks)) return [group];
|
|
125
|
+
const rest = group.hooks.filter((h) => !isPassControlCodexHook(h));
|
|
126
|
+
if (rest.length === group.hooks.length) return [group];
|
|
127
|
+
return rest.length ? [{ ...group, hooks: rest }] : [];
|
|
128
|
+
});
|
|
129
|
+
if (next[event].length === 0) delete next[event];
|
|
130
|
+
}
|
|
131
|
+
return next;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const hasOurs = (hooks) =>
|
|
135
|
+
Object.values(hooks ?? {}).some((groups) => Array.isArray(groups) && groups.some((g) => isObject(g) && Array.isArray(g.hooks) && g.hooks.some(isPassControlCodexHook)));
|
|
136
|
+
|
|
137
|
+
function save(target, value) {
|
|
138
|
+
fs.mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
|
|
139
|
+
const temp = `${target}.${process.pid}.tmp`;
|
|
140
|
+
fs.writeFileSync(temp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
|
|
141
|
+
fs.renameSync(temp, target);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Add PassControl's two hooks, replacing any earlier ones of its own and nobody else's. */
|
|
145
|
+
export function writeCodexHooks({ target, command }) {
|
|
146
|
+
const { value, exists } = readHooksFile(target);
|
|
147
|
+
const hooks = withoutOurs(value.hooks ?? {});
|
|
148
|
+
for (const [event, groups] of Object.entries(codexHookEntries(command).hooks)) {
|
|
149
|
+
hooks[event] = [...(Array.isArray(hooks[event]) ? hooks[event] : []), ...groups];
|
|
150
|
+
}
|
|
151
|
+
const next = { ...value, hooks };
|
|
152
|
+
if (JSON.stringify(next) === JSON.stringify(value)) return { changed: false, backupPath: null };
|
|
153
|
+
let backupPath = null;
|
|
154
|
+
if (exists && !hasOurs(value.hooks)) {
|
|
155
|
+
backupPath = `${target}${BACKUP_SUFFIX}`;
|
|
156
|
+
fs.copyFileSync(target, backupPath);
|
|
157
|
+
fs.chmodSync(backupPath, 0o600);
|
|
158
|
+
}
|
|
159
|
+
save(target, next);
|
|
160
|
+
return { changed: true, backupPath };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Take PassControl's hooks back out; everything else stays as it was. */
|
|
164
|
+
export function removeCodexHooks({ target }) {
|
|
165
|
+
if (!fs.existsSync(target)) return { changed: false };
|
|
166
|
+
const { value } = readHooksFile(target);
|
|
167
|
+
if (!hasOurs(value.hooks)) return { changed: false };
|
|
168
|
+
const hooks = withoutOurs(value.hooks);
|
|
169
|
+
const { hooks: _old, ...rest } = value;
|
|
170
|
+
save(target, Object.keys(hooks).length ? { ...rest, hooks } : rest);
|
|
171
|
+
return { changed: true };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const ASK_IN_CODEX =
|
|
175
|
+
" Codex cannot ask here, so PassControl refuses it: the user can run it themselves, or the agent's owner can change the rule on the agent's page.";
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* The sidecar's answer (Claude Code's hook output) as Codex must get it, built from
|
|
179
|
+
* an allow-list: on PreToolUse, a field Codex does not support there fails the hook,
|
|
180
|
+
* and a failed hook lets the tool run.
|
|
181
|
+
*/
|
|
182
|
+
export function codexHookAnswer(event, out) {
|
|
183
|
+
const o = isObject(out) ? out : {};
|
|
184
|
+
const systemMessage = text(o.systemMessage);
|
|
185
|
+
const warning = systemMessage ? { systemMessage } : {};
|
|
186
|
+
if (event === "PreToolUse") {
|
|
187
|
+
const hso = isObject(o.hookSpecificOutput) ? o.hookSpecificOutput : {};
|
|
188
|
+
const stopped = o.continue === false || o.decision === "block";
|
|
189
|
+
const said = text(hso.permissionDecisionReason) ?? text(o.stopReason) ?? text(o.reason);
|
|
190
|
+
let reason = null;
|
|
191
|
+
if (hso.permissionDecision === "deny" || stopped) reason = said ?? "PassControl refused this tool call.";
|
|
192
|
+
else if (hso.permissionDecision === "ask") reason = `${said ?? "PassControl: the agent's tool rules ask the user to confirm this."}${ASK_IN_CODEX}`;
|
|
193
|
+
if (reason === null) return warning;
|
|
194
|
+
return { hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: reason }, ...warning };
|
|
195
|
+
}
|
|
196
|
+
if (event === "UserPromptSubmit") {
|
|
197
|
+
const answer = {};
|
|
198
|
+
if (o.continue === false) answer.continue = false;
|
|
199
|
+
if (text(o.stopReason)) answer.stopReason = o.stopReason;
|
|
200
|
+
if (o.decision === "block") answer.decision = "block";
|
|
201
|
+
if (text(o.reason)) answer.reason = o.reason;
|
|
202
|
+
const context = isObject(o.hookSpecificOutput) ? text(o.hookSpecificOutput.additionalContext) : null;
|
|
203
|
+
if (context) answer.hookSpecificOutput = { hookEventName: "UserPromptSubmit", additionalContext: context };
|
|
204
|
+
return { ...answer, ...warning };
|
|
205
|
+
}
|
|
206
|
+
return {};
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* What `passcontrol codex-hook` prints for one hook run: Codex's input in, the
|
|
211
|
+
* sidecar's answer out, or nothing. Never throws, and never blocks on its own
|
|
212
|
+
* failure: a sidecar that is down or slow lets the action go ahead, with a warning.
|
|
213
|
+
*/
|
|
214
|
+
export async function runCodexHook({ input, port, fetchImpl = fetch, promptTimeoutMs = PROMPT_RELAY_MS, toolTimeoutMs = TOOL_RELAY_MS }) {
|
|
215
|
+
let parsed;
|
|
216
|
+
try {
|
|
217
|
+
parsed = JSON.parse(input);
|
|
218
|
+
} catch {
|
|
219
|
+
return "";
|
|
220
|
+
}
|
|
221
|
+
const event = isObject(parsed) ? parsed.hook_event_name : null;
|
|
222
|
+
if (!EVENTS.includes(event)) return "";
|
|
223
|
+
const tool = event === "PreToolUse";
|
|
224
|
+
const controller = new AbortController();
|
|
225
|
+
const timer = setTimeout(() => controller.abort(), tool ? toolTimeoutMs : promptTimeoutMs);
|
|
226
|
+
const warn = (why) => JSON.stringify({ systemMessage: `PassControl: ${why}, so this goes ahead unchecked.` });
|
|
227
|
+
try {
|
|
228
|
+
const url = `http://127.0.0.1:${port}${HOOK_PATH}${tool ? `?t=${CODEX_TOOL_HOOK_TIMEOUT_S}` : ""}`;
|
|
229
|
+
const response = await fetchImpl(url, {
|
|
230
|
+
method: "POST",
|
|
231
|
+
headers: { "content-type": "application/json" },
|
|
232
|
+
body: input,
|
|
233
|
+
signal: controller.signal,
|
|
234
|
+
});
|
|
235
|
+
if (!response.ok) return warn(`the sidecar on port ${port} refused the hook (HTTP ${response.status})`);
|
|
236
|
+
const out = await response.json().catch(() => null);
|
|
237
|
+
if (!isObject(out)) return warn(`the sidecar on port ${port} gave an answer that cannot be read`);
|
|
238
|
+
const answer = codexHookAnswer(event, out);
|
|
239
|
+
return Object.keys(answer).length ? JSON.stringify(answer) : "";
|
|
240
|
+
} catch {
|
|
241
|
+
if (controller.signal.aborted) return warn(`the sidecar on port ${port} did not answer in time`);
|
|
242
|
+
return warn(`no sidecar answered on port ${port} (start it: passcontrol sidecar --port ${port})`);
|
|
243
|
+
} finally {
|
|
244
|
+
clearTimeout(timer);
|
|
245
|
+
}
|
|
246
|
+
}
|
package/cli/config.mjs
CHANGED
|
@@ -677,6 +677,9 @@ export function formatProxyError(status, body) {
|
|
|
677
677
|
if (status === 402 && error === "blocked_budget_period") {
|
|
678
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.`;
|
|
679
679
|
}
|
|
680
|
+
if (status === 402 && error === "blocked_budget_pause") {
|
|
681
|
+
return `${blocked}\n→ The agent reached the pause line its owner set on its spending limit; the limit itself is not used up.\n→ Fix: let it go on for an hour from the agent's page in the dashboard, or raise the pause line.`;
|
|
682
|
+
}
|
|
680
683
|
if (status === 402 && error === "blocked_budget_delegation") {
|
|
681
684
|
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
685
|
}
|
package/cli/login.mjs
CHANGED
|
@@ -281,7 +281,14 @@ async function control(origin, apiKey, method, path, body, fetchImpl = fetch) {
|
|
|
281
281
|
});
|
|
282
282
|
const parsed = await res.json().catch(() => null);
|
|
283
283
|
if (!res.ok) {
|
|
284
|
-
|
|
284
|
+
// The control API answers { error: { code, message } }, and the message is
|
|
285
|
+
// what tells someone at a limit whether to revoke an agent or wait. Printed
|
|
286
|
+
// on one line and clipped, because it is the gateway's text, not ours.
|
|
287
|
+
const code = typeof parsed?.error?.code === "string" ? parsed.error.code.replace(/[^a-z0-9_]/gu, "").slice(0, 64) : "";
|
|
288
|
+
const message = typeof parsed?.error?.message === "string" ? parsed.error.message.replace(/\s+/gu, " ").trim().slice(0, 240) : "";
|
|
289
|
+
throw new Error(
|
|
290
|
+
`Control plane refused ${method} ${path} (${res.status}${code ? ` ${code}` : ""})${message ? `: ${message}` : "."}`
|
|
291
|
+
);
|
|
285
292
|
}
|
|
286
293
|
// Every control route answers `{ data: ... }` (lib/control/respond.ts), and
|
|
287
294
|
// bin/passcontrol.mjs's own `api()` has always unwrapped it. This helper did
|
|
@@ -549,7 +556,15 @@ export async function loginCommand(opts = {}, deps = {}) {
|
|
|
549
556
|
warnIfShadowed(target);
|
|
550
557
|
|
|
551
558
|
step("");
|
|
559
|
+
// An agent this command created has the demo scope (above). A reused one has
|
|
560
|
+
// whatever its owner gave it; when its listed scopes leave out `demo`, the
|
|
561
|
+
// demo call would be refused and recorded, so the proof stops at the visa.
|
|
562
|
+
// Not in the list (or no scopes field) means unknown, and the call is tried.
|
|
563
|
+
const reused = Array.isArray(agents) ? agents.find((agent) => agent?.id === agentId) : undefined;
|
|
564
|
+
const demoCall = !(reused && Array.isArray(reused.allowed_scopes))
|
|
565
|
+
|| reused.allowed_scopes.some((scope) => scope?.provider === "demo");
|
|
552
566
|
const proof = await proveItWorks({
|
|
567
|
+
demoCall,
|
|
553
568
|
origin,
|
|
554
569
|
passportId,
|
|
555
570
|
passportSecret,
|
package/cli/mcp/README.md
CHANGED
|
@@ -66,7 +66,8 @@ config contains a passport secret or provider key.
|
|
|
66
66
|
therefore refuses it; use off/observe for this client. `list_models` reads model patterns
|
|
67
67
|
from the visa scope, not a live upstream model catalog; a wildcard is not a callable model.
|
|
68
68
|
`budget` reads the agent's own limits from the gateway (`GET /api/v1/self`): what is used,
|
|
69
|
-
what is left,
|
|
69
|
+
what is left, when a daily or monthly limit resets, and when the first limit runs out at the
|
|
70
|
+
current rate. It spends nothing and writes no log
|
|
70
71
|
row; like `chat`, it sends a bearer visa, so required sender-proof mode refuses it.
|
|
71
72
|
Providers: OpenAI, Anthropic, Groq, Mistral, Together, DeepSeek, and Gemini (OpenAI-compatible).
|
|
72
73
|
The global profile can use the CLI OS credential store (`passcontrol key status`) rather
|
package/cli/menu.mjs
CHANGED
|
@@ -268,6 +268,7 @@ export const HIDDEN = {
|
|
|
268
268
|
try: "kept as an explanatory compatibility error, but no longer performs an operation",
|
|
269
269
|
seal: "needs a session and an agent, both named by `sessions`, which is listed under Money",
|
|
270
270
|
statusline: "Claude Code runs it, not a person; `configure claude-code --statusline` installs it",
|
|
271
|
+
"codex-hook": "Codex runs it, not a person; `configure codex --subscription` installs it",
|
|
271
272
|
};
|
|
272
273
|
|
|
273
274
|
/** Every top-level command name the menu can reach, flattened. */
|
package/cli/selftest.mjs
CHANGED
|
@@ -99,6 +99,9 @@ export async function proveItWorks({
|
|
|
99
99
|
apiKey,
|
|
100
100
|
fetchImpl,
|
|
101
101
|
wait = sleep,
|
|
102
|
+
// False for an agent whose scopes are known to exclude `demo`: the call could
|
|
103
|
+
// only be refused, and a refusal is recorded on the agent's page.
|
|
104
|
+
demoCall = true,
|
|
102
105
|
}) {
|
|
103
106
|
const proof = { visa: false, call: false, receipt: null };
|
|
104
107
|
try {
|
|
@@ -113,6 +116,13 @@ export async function proveItWorks({
|
|
|
113
116
|
proof.visa = true;
|
|
114
117
|
ok("minted a visa with this passport");
|
|
115
118
|
|
|
119
|
+
if (!demoCall) {
|
|
120
|
+
proof.reason = "no_demo_scope";
|
|
121
|
+
step("This agent has no access to the keyless demo model, so no test call was made: it could only be");
|
|
122
|
+
step('refused. Its model access is set on its page in the dashboard; then: passcontrol call "hi"');
|
|
123
|
+
return proof;
|
|
124
|
+
}
|
|
125
|
+
|
|
116
126
|
const res = await fetchImpl(`${origin}/api/v1/demo/chat/completions`, {
|
|
117
127
|
method: "POST",
|
|
118
128
|
headers: { "content-type": "application/json", authorization: `Bearer ${visa}` },
|
package/cli/sidecar.mjs
CHANGED
|
@@ -8,7 +8,7 @@ import { createVisaClient } from "./visa-client.mjs";
|
|
|
8
8
|
import { declaredLineage, declaredSession } from "./declared-session.mjs";
|
|
9
9
|
import { defaultJournalDir, openJournal } from "./journal.mjs";
|
|
10
10
|
import { answer, createWatchFeed, isNotACall, isLocalCaller, LOCAL_PREFIX, peekText, providerOf, refusalCode, requestModel } from "./watch-feed.mjs";
|
|
11
|
-
import { createStopGate, HOOK_PATH, selfAnswerState } from "./subscription-gate.mjs";
|
|
11
|
+
import { createStopGate, HOOK_PATH, SELF_READ_TIMEOUT_MS, selfAnswerState } from "./subscription-gate.mjs";
|
|
12
12
|
import { createToolGate } from "./tool-gate.mjs";
|
|
13
13
|
import { OTLP_LOGS_PATH, readClaudeCodeEvents } from "./otlp-logs.mjs";
|
|
14
14
|
import { CLIENT_EVENTS_PATH, CLIENT_EVENTS_SOURCE, createCallUploader } from "./client-events-upload.mjs";
|
|
@@ -67,6 +67,12 @@ function hookTimeoutS(url) {
|
|
|
67
67
|
const t = new URL(url ?? "/", "http://127.0.0.1").searchParams.get("t");
|
|
68
68
|
return t !== null && /^\d{1,4}$/.test(t) && Number(t) > 0 ? Number(t) : null;
|
|
69
69
|
}
|
|
70
|
+
// The agent's opt-in note (1.6.0): `?note=1` on subscription mode's prompt hook,
|
|
71
|
+
// `?note=only` on API mode's, which only ever adds the note.
|
|
72
|
+
function hookNote(url) {
|
|
73
|
+
const note = new URL(url ?? "/", "http://127.0.0.1").searchParams.get("note");
|
|
74
|
+
return note === "1" ? "subscription" : note === "only" ? "api" : null;
|
|
75
|
+
}
|
|
70
76
|
// A usage window is two numbers and two times.
|
|
71
77
|
const WINDOW_BODY_LIMIT = 4 * 1024;
|
|
72
78
|
|
|
@@ -172,10 +178,17 @@ export function createSidecar({
|
|
|
172
178
|
// Subscription mode's Stop (cli/subscription-gate.mjs): Claude Code's hooks ask
|
|
173
179
|
// here, and the answer comes from the gateway's /api/v1/self, read with this
|
|
174
180
|
// sidecar's visa and the session the hook names.
|
|
175
|
-
const SELF_TIMEOUT_MS = 2_000;
|
|
176
181
|
async function readSelf(session) {
|
|
182
|
+
// One deadline over the whole read, a visa mint included: past the hook's own
|
|
183
|
+
// timeout the action goes ahead with no warning. A mint cut short here is not
|
|
184
|
+
// aborted (the proxy shares it); it finishes and is cached for the next read.
|
|
185
|
+
const signal = AbortSignal.timeout(SELF_READ_TIMEOUT_MS);
|
|
186
|
+
const deadline = new Promise((_, reject) => {
|
|
187
|
+
signal.addEventListener("abort", () => reject(signal.reason), { once: true });
|
|
188
|
+
});
|
|
189
|
+
deadline.catch(() => {});
|
|
177
190
|
try {
|
|
178
|
-
const response = await visas.fetchWithVisa((visa) => {
|
|
191
|
+
const response = await Promise.race([deadline, visas.fetchWithVisa((visa) => {
|
|
179
192
|
// The tool rules ride on every gate read (Phase 2): no call of their own.
|
|
180
193
|
const path = "/api/v1/self?include=tool_rules";
|
|
181
194
|
const headers = {
|
|
@@ -186,9 +199,9 @@ export function createSidecar({
|
|
|
186
199
|
"accept-encoding": "identity",
|
|
187
200
|
};
|
|
188
201
|
if (session) headers["x-claude-code-session-id"] = session;
|
|
189
|
-
return fetch(`${origin}${path}`, { headers, signal
|
|
190
|
-
});
|
|
191
|
-
return await selfAnswerState(response);
|
|
202
|
+
return fetch(`${origin}${path}`, { headers, signal });
|
|
203
|
+
})]);
|
|
204
|
+
return await Promise.race([deadline, selfAnswerState(response)]);
|
|
192
205
|
} catch (error) {
|
|
193
206
|
return { state: "unknown", reason: error?.name === "TimeoutError" ? "the gateway did not answer in time" : (error?.message ?? "error") };
|
|
194
207
|
}
|
|
@@ -397,7 +410,7 @@ export function createSidecar({
|
|
|
397
410
|
}
|
|
398
411
|
let out;
|
|
399
412
|
try {
|
|
400
|
-
out = await stopGate.decide(input);
|
|
413
|
+
out = await stopGate.decide(input, { note: hookNote(req.url) });
|
|
401
414
|
} catch {
|
|
402
415
|
out = {};
|
|
403
416
|
}
|
package/cli/statusline.mjs
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
// older budget that might read as current.
|
|
15
15
|
import fs from "node:fs";
|
|
16
16
|
import path from "node:path";
|
|
17
|
-
import { limitReached, panelRows, statusLine } from "./budget-format.mjs";
|
|
17
|
+
import { limitReached, panelRows, paused, statusLine } from "./budget-format.mjs";
|
|
18
18
|
import { heldUsageWindow, readUsageWindow, usageWindowText, WINDOW_PATH } from "./usage-window.mjs";
|
|
19
19
|
|
|
20
20
|
export const STATUSLINE_TTL_MS = 20_000;
|
|
@@ -292,7 +292,7 @@ export async function statusPanelText({
|
|
|
292
292
|
}
|
|
293
293
|
if (typeof self?.budget !== "object" || self.budget === null) return "PassControl · unreadable answer";
|
|
294
294
|
const agentId = typeof self.agent_id === "string" && UUID.test(self.agent_id) ? self.agent_id : null;
|
|
295
|
-
const title = `PassControl${agentId ? ` · agent ${agentId.slice(0, 8)}` : ""}${limitReached(self) ? " · LIMIT REACHED" : ""}`;
|
|
295
|
+
const title = `PassControl${agentId ? ` · agent ${agentId.slice(0, 8)}` : ""}${limitReached(self) ? " · LIMIT REACHED" : paused(self) ? " · PAUSED" : ""}`;
|
|
296
296
|
const window = subscription ? await readSidecarWindow({ host, port, fetch: fetchImpl, signal: controller.signal }) : "";
|
|
297
297
|
return [
|
|
298
298
|
title,
|
|
@@ -34,15 +34,30 @@
|
|
|
34
34
|
// A refusal carries no rules, so a PreToolUse refreshes them with the agent-wide ask
|
|
35
35
|
// once they are `freshMs` old.
|
|
36
36
|
//
|
|
37
|
+
// The agent's own note (1.6.0, cli/agent-note.mjs) rides on the prompt hook when its
|
|
38
|
+
// URL opts in: `?note=1` in this mode, `?note=only` when Claude Code goes through the
|
|
39
|
+
// sidecar with an API key, where the gateway already enforces and the hook only ever
|
|
40
|
+
// adds the note. It is built from the latest answer and sent per session only when
|
|
41
|
+
// its signature changes; a stop always wins over it.
|
|
42
|
+
//
|
|
37
43
|
// Honest limit: hooks run inside Claude Code, so this is a guard rail for the user's
|
|
38
44
|
// own sessions, not a boundary against a client that skips them.
|
|
39
45
|
|
|
46
|
+
import { agentNote } from "./agent-note.mjs";
|
|
47
|
+
|
|
40
48
|
export const HOOK_PATH = "/_passcontrol/hook";
|
|
41
49
|
|
|
42
50
|
const GATED = new Set(["UserPromptSubmit", "PreToolUse", "PostToolBatch"]);
|
|
43
51
|
// What the gateway accepts as a declared session (lib/client-lineage.ts).
|
|
44
52
|
const DECLARED_SESSION = /^[A-Za-z0-9._:-]{1,128}$/;
|
|
45
53
|
|
|
54
|
+
// Claude Code's timeout on the prompt and next-model-call hooks (cli/claude-code.mjs).
|
|
55
|
+
// Past it the action goes ahead with no warning at all, so the sidecar's read of
|
|
56
|
+
// /api/v1/self ends a second earlier and says why. 2 s was too short: a Cloud answer
|
|
57
|
+
// on a cold start took longer, and a stop was missed with "did not answer in time".
|
|
58
|
+
export const GATE_HOOK_TIMEOUT_S = 5;
|
|
59
|
+
export const SELF_READ_TIMEOUT_MS = (GATE_HOOK_TIMEOUT_S - 1) * 1000;
|
|
60
|
+
|
|
46
61
|
export const GATE_FRESH_MS = 5_000;
|
|
47
62
|
export const GATE_SESSION_FRESH_MS = 15_000;
|
|
48
63
|
export const GATE_MAX_STALE_MS = 60_000;
|
|
@@ -94,6 +109,9 @@ export function createStopGate({
|
|
|
94
109
|
let agent = null;
|
|
95
110
|
// The agent's tool rules as the last answer that carried them gave them.
|
|
96
111
|
let rules = null;
|
|
112
|
+
// The limits from the latest open answer, for the note; and each session's last note.
|
|
113
|
+
let latest = null;
|
|
114
|
+
const noted = new Map();
|
|
97
115
|
const sessions = new Map();
|
|
98
116
|
const inflight = new Map();
|
|
99
117
|
const warnedAt = new Map();
|
|
@@ -124,6 +142,7 @@ export function createStopGate({
|
|
|
124
142
|
answer = { state: "unknown", reason: error?.message ?? "error" };
|
|
125
143
|
}
|
|
126
144
|
answer ??= { state: "unknown", reason: "no answer" };
|
|
145
|
+
if (answer.state === "open" && answer.self) latest = { self: answer.self, at: now() };
|
|
127
146
|
if (answer.state === "open") {
|
|
128
147
|
rules = { read: answer.toolRules && typeof answer.toolRules === "object" ? answer.toolRules : { state: "none" }, at: now() };
|
|
129
148
|
}
|
|
@@ -151,8 +170,40 @@ export function createStopGate({
|
|
|
151
170
|
|
|
152
171
|
const age = (entry) => (entry ? now() - entry.at : Infinity);
|
|
153
172
|
|
|
154
|
-
|
|
173
|
+
/** The note for this session's prompt, when it opted in and something changed since the last. */
|
|
174
|
+
function noteFor(sessionKey, mode) {
|
|
175
|
+
if (!latest || age(latest) > maxStaleMs) return null;
|
|
176
|
+
const freshRules = rules && age(rules) <= maxStaleMs ? rules.read : null;
|
|
177
|
+
const n = agentNote({ self: latest.self, rules: freshRules, mode, nowMs: now() });
|
|
178
|
+
if (!n || noted.get(sessionKey) === n.signature) return null;
|
|
179
|
+
remember(noted, sessionKey, n.signature);
|
|
180
|
+
return { hookEventName: "UserPromptSubmit", additionalContext: n.text };
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* @param {object} input Claude Code's hook input.
|
|
185
|
+
* @param {{ note?: "api" | "subscription" | null }} [options] the prompt hook's opt-in.
|
|
186
|
+
*/
|
|
187
|
+
async function decide(input, { note = null } = {}) {
|
|
155
188
|
const event = input?.hook_event_name;
|
|
189
|
+
if (note === "api") {
|
|
190
|
+
// Only the note, never a stop or a warning: the gateway refuses these calls itself.
|
|
191
|
+
if (event !== "UserPromptSubmit") return {};
|
|
192
|
+
if (age(latest) >= freshMs) await ask(null);
|
|
193
|
+
const session = typeof input.session_id === "string" && DECLARED_SESSION.test(input.session_id) ? input.session_id : "";
|
|
194
|
+
const out = noteFor(session, "api");
|
|
195
|
+
return out ? { hookSpecificOutput: out } : {};
|
|
196
|
+
}
|
|
197
|
+
const out = await gateDecision(input, event);
|
|
198
|
+
if (note === "subscription" && event === "UserPromptSubmit" && out.continue !== false) {
|
|
199
|
+
const session = typeof input.session_id === "string" && DECLARED_SESSION.test(input.session_id) ? input.session_id : "";
|
|
200
|
+
const extra = noteFor(session, "subscription");
|
|
201
|
+
if (extra) return { ...out, hookSpecificOutput: extra };
|
|
202
|
+
}
|
|
203
|
+
return out;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
async function gateDecision(input, event) {
|
|
156
207
|
if (!GATED.has(event)) return {};
|
|
157
208
|
const session = typeof input.session_id === "string" && DECLARED_SESSION.test(input.session_id) ? input.session_id : null;
|
|
158
209
|
|
|
@@ -201,7 +252,13 @@ export async function selfAnswerState(response) {
|
|
|
201
252
|
if (response.ok) {
|
|
202
253
|
const body = await response.json().catch(() => null);
|
|
203
254
|
const toolRules = body && typeof body === "object" ? body.tool_rules : undefined;
|
|
204
|
-
|
|
255
|
+
const answer = toolRules && typeof toolRules === "object" ? { state: "open", toolRules } : { state: "open" };
|
|
256
|
+
// The limits and the soft pause, for the agent's note; nothing else from the answer is kept.
|
|
257
|
+
if (body && typeof body === "object" && body.budget && typeof body.budget === "object") {
|
|
258
|
+
const kept = (v) => (v && typeof v === "object" ? v : null);
|
|
259
|
+
answer.self = { budget: body.budget, pace: kept(body.pace), pause: kept(body.pause) };
|
|
260
|
+
}
|
|
261
|
+
return answer;
|
|
205
262
|
}
|
|
206
263
|
if (response.status === 403) {
|
|
207
264
|
const body = await response.json().catch(() => ({}));
|
package/cli/tool-gate.mjs
CHANGED
|
@@ -53,6 +53,11 @@ function verdict(permissionDecision, reason) {
|
|
|
53
53
|
export function createToolGate({ askOwner, onDecision = () => {}, now = () => Date.now(), dashboardUrl = "" }) {
|
|
54
54
|
let warnedAt = null;
|
|
55
55
|
const where = dashboardUrl ? ` on ${dashboardUrl}` : " on the agent's dashboard page";
|
|
56
|
+
// Said with every rule's refusal: told only "the tool rules refuse this", Claude
|
|
57
|
+
// Code went looking for the rule in the local PassControl config, which has none.
|
|
58
|
+
const rulesLive = dashboardUrl
|
|
59
|
+
? `Tool rules are set on the agent's page at ${dashboardUrl}, not on this machine.`
|
|
60
|
+
: "Tool rules are set on the agent's dashboard page, not on this machine.";
|
|
56
61
|
|
|
57
62
|
function record(input, decision, ruleIndex, waitMs) {
|
|
58
63
|
try {
|
|
@@ -99,11 +104,11 @@ export function createToolGate({ askOwner, onDecision = () => {}, now = () => Da
|
|
|
99
104
|
const rule = `rule ${hit.ruleIndex + 1}`;
|
|
100
105
|
if (hit.effect === "deny") {
|
|
101
106
|
record(input, "deny", hit.ruleIndex, 0);
|
|
102
|
-
return verdict("deny", `PassControl: the agent's tool rules refuse this (${rule}: ${short(hit.subject)})
|
|
107
|
+
return verdict("deny", `PassControl: the agent's tool rules refuse this (${rule}: ${short(hit.subject)}). ${rulesLive}`);
|
|
103
108
|
}
|
|
104
109
|
if (hit.effect === "ask") {
|
|
105
110
|
record(input, "ask", hit.ruleIndex, 0);
|
|
106
|
-
return verdict("ask", `PassControl: the agent's tool rules ask you to confirm this (${rule}: ${short(hit.subject)})
|
|
111
|
+
return verdict("ask", `PassControl: the agent's tool rules ask you to confirm this (${rule}: ${short(hit.subject)}). ${rulesLive}`);
|
|
107
112
|
}
|
|
108
113
|
|
|
109
114
|
// ask_owner
|
|
@@ -129,7 +134,7 @@ export function createToolGate({ askOwner, onDecision = () => {}, now = () => Da
|
|
|
129
134
|
return {};
|
|
130
135
|
case "denied":
|
|
131
136
|
record(input, "owner_denied", hit.ruleIndex, waited);
|
|
132
|
-
return verdict("deny", `PassControl: the agent's owner said no to this (${rule})
|
|
137
|
+
return verdict("deny", `PassControl: the agent's owner said no to this (${rule}). ${rulesLive}`);
|
|
133
138
|
case "timeout":
|
|
134
139
|
record(input, "owner_timeout", hit.ruleIndex, waited);
|
|
135
140
|
return verdict("deny", `PassControl: the agent's owner did not answer within ${waitS} s, so this was not run (${rule}).`);
|
package/cli/watch.mjs
CHANGED
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
// fields are held to the feed's own patterns on arrival, and every cell is stripped
|
|
17
17
|
// of control characters again before it is drawn.
|
|
18
18
|
import http from "node:http";
|
|
19
|
-
import { formatUsd, limitReached, panelRows } from "./budget-format.mjs";
|
|
19
|
+
import { formatUsd, limitReached, panelRows, paused } from "./budget-format.mjs";
|
|
20
20
|
import { WATCH_PATH } from "./watch-feed.mjs";
|
|
21
21
|
import { heldUsageWindow, resetTime, usageWindowText } from "./usage-window.mjs";
|
|
22
22
|
|
|
@@ -313,7 +313,12 @@ function budgetLine(budget, width, { color, formatTime }) {
|
|
|
313
313
|
const style = fraction >= 1 ? "red" : fraction >= 0.8 ? "yellow" : "green";
|
|
314
314
|
bar = `[${paint(color, style, "█".repeat(filled))}${"░".repeat(barWidth - filled)}] `;
|
|
315
315
|
}
|
|
316
|
-
|
|
316
|
+
// A pause is the owner's line doing its job, so not the red of a spent limit.
|
|
317
|
+
const reached = limitReached(budget.self)
|
|
318
|
+
? ` · ${paint(color, "red", "LIMIT REACHED")}`
|
|
319
|
+
: paused(budget.self)
|
|
320
|
+
? ` · ${paint(color, "yellow", "PAUSED")}`
|
|
321
|
+
: "";
|
|
317
322
|
const line = `${clean(label).padEnd(9)} ${bar}${clean(value)}${reached}`;
|
|
318
323
|
// When it was asked is the first thing to go when the line is too long.
|
|
319
324
|
const checked = budget.checkedAt ? ` · checked ${formatTime(budget.checkedAt)}` : "";
|
package/package.json
CHANGED