passcontrol 1.5.0 → 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 +164 -5
- package/cli/agent-note.mjs +169 -0
- package/cli/budget-format.mjs +101 -8
- package/cli/claude-code.mjs +226 -2
- package/cli/client-events-upload.mjs +212 -0
- 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/otlp-logs.mjs +96 -0
- package/cli/selftest.mjs +10 -0
- package/cli/sidecar.mjs +301 -5
- package/cli/statusline.mjs +107 -9
- package/cli/subscription-gate.mjs +270 -0
- package/cli/tool-gate.mjs +157 -0
- package/cli/tool-rules.d.mts +28 -0
- package/cli/tool-rules.mjs +206 -0
- package/cli/usage-window.mjs +66 -0
- package/cli/watch-feed.mjs +77 -7
- package/cli/watch.mjs +56 -12
- 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
|
@@ -95,11 +95,31 @@ import {
|
|
|
95
95
|
claudeCodeEnv,
|
|
96
96
|
claudeCodeSettingsPath,
|
|
97
97
|
removeClaudeCodeSettings,
|
|
98
|
+
removeClaudeCodeSubscription,
|
|
99
|
+
subscriptionEnv,
|
|
100
|
+
subscriptionHooks,
|
|
98
101
|
writeClaudeCodeSettings,
|
|
102
|
+
writeClaudeCodeSubscription,
|
|
99
103
|
} from "../cli/claude-code.mjs";
|
|
100
|
-
import {
|
|
104
|
+
import {
|
|
105
|
+
notInPathText,
|
|
106
|
+
readStatusInput,
|
|
107
|
+
sidecarFromBaseUrl,
|
|
108
|
+
statusPanelText,
|
|
109
|
+
statuslineText,
|
|
110
|
+
statuslineWithWindow,
|
|
111
|
+
} from "../cli/statusline.mjs";
|
|
101
112
|
import { runWatch } from "../cli/watch.mjs";
|
|
102
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";
|
|
103
123
|
import { waitForGateway as awaitGateway } from "../cli/gateway-wait.mjs";
|
|
104
124
|
import { loginCommand } from "../cli/login.mjs";
|
|
105
125
|
import { logoutCommand } from "../cli/logout.mjs";
|
|
@@ -208,7 +228,7 @@ ${heading("Quick start")}
|
|
|
208
228
|
${cmd} login [--project] sign in through your browser and set this machine up
|
|
209
229
|
${cmd} call "hi" mint a visa and make a governed model call
|
|
210
230
|
${cmd} mcp passport identity for Claude Desktop, Cursor, Claude Code
|
|
211
|
-
${cmd} sidecar [--port 8788] [--allow-connect host[,host]] [--ollama-port 11435] [--no-journal]
|
|
231
|
+
${cmd} sidecar [--port 8788] [--allow-connect host[,host]] [--ollama-port 11435] [--no-journal] [--no-report-calls]
|
|
212
232
|
passport identity for any tool that takes an api_key
|
|
213
233
|
${cmd} sidecar --profile <name> | --profiles a,b
|
|
214
234
|
run a coding tool's own sidecar (or several, one process)
|
|
@@ -262,6 +282,12 @@ ${heading("Integrate")}
|
|
|
262
282
|
${cmd} env [integration] print settings without writing anything
|
|
263
283
|
${cmd} configure <integration> [--write] [--force] [--dedicated]
|
|
264
284
|
preview or write integration config
|
|
285
|
+
${cmd} configure claude-code --subscription [--write|--remove]
|
|
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
|
|
265
291
|
integrations: ${integrationChoices()}
|
|
266
292
|
|
|
267
293
|
${heading("Trust")}
|
|
@@ -2460,6 +2486,7 @@ async function sidecarCommand(rest, opts) {
|
|
|
2460
2486
|
allowConnectHosts: [],
|
|
2461
2487
|
refreshSkewSeconds: Number(opts.refreshSkewSeconds ?? process.env.REFRESH_SKEW_SECONDS ?? 30),
|
|
2462
2488
|
noJournal: opts.journal === false || Boolean(opts.noJournal),
|
|
2489
|
+
reportCalls: !(opts.reportCalls === false || Boolean(opts.noReportCalls)),
|
|
2463
2490
|
});
|
|
2464
2491
|
}
|
|
2465
2492
|
return;
|
|
@@ -2493,6 +2520,9 @@ async function sidecarCommand(rest, opts) {
|
|
|
2493
2520
|
// A flag only, like --allow-non-loopback: whether this machine keeps a record
|
|
2494
2521
|
// is the operator's to state, not a config file's.
|
|
2495
2522
|
noJournal: opts.journal === false || Boolean(opts.noJournal),
|
|
2523
|
+
// Subscription mode: the calls Claude Code reports go to the agent's page. On
|
|
2524
|
+
// unless the flag says off, like the journal.
|
|
2525
|
+
reportCalls: !(opts.reportCalls === false || Boolean(opts.noReportCalls)),
|
|
2496
2526
|
});
|
|
2497
2527
|
|
|
2498
2528
|
if (opts.for) {
|
|
@@ -2528,14 +2558,21 @@ async function statuslineCommand(opts) {
|
|
|
2528
2558
|
if (opts.panel) {
|
|
2529
2559
|
const route = opts.port === undefined ? sidecarFromBaseUrl(process.env.ANTHROPIC_BASE_URL) : null;
|
|
2530
2560
|
if (route?.remote) return notInPathText(route.remote);
|
|
2561
|
+
// Subscription mode (cli/subscription-gate.mjs): no ANTHROPIC_BASE_URL, since
|
|
2562
|
+
// the calls go to Anthropic directly; `configure claude-code --subscription`
|
|
2563
|
+
// names the sidecar the hooks and telemetry use instead.
|
|
2564
|
+
const reported = !route && opts.port === undefined ? sidecarFromBaseUrl(process.env.PASSCONTROL_SIDECAR_URL) : null;
|
|
2531
2565
|
return await statusPanelText({
|
|
2532
|
-
port: route?.port ?? port,
|
|
2566
|
+
port: route?.port ?? reported?.port ?? port,
|
|
2533
2567
|
gateway: config.gateway,
|
|
2534
2568
|
session: typeof opts.session === "string" ? opts.session : null,
|
|
2569
|
+
subscription: Boolean(reported?.port),
|
|
2535
2570
|
});
|
|
2536
2571
|
}
|
|
2537
2572
|
const cacheFile = path.join(path.dirname(globalConfigPath()), `statusline-${port}.json`);
|
|
2538
|
-
|
|
2573
|
+
// On a Pro/Max login Claude Code adds the usage window to its input (cli/usage-window.mjs).
|
|
2574
|
+
const input = await readStatusInput();
|
|
2575
|
+
return await statuslineWithWindow({ input, port, budgetLine: () => statuslineText({ port, cacheFile }) });
|
|
2539
2576
|
} catch (error) {
|
|
2540
2577
|
return `PassControl · ${error instanceof Error && /--port/.test(error.message) ? "bad --port" : "unavailable"}`;
|
|
2541
2578
|
}
|
|
@@ -2751,6 +2788,7 @@ function aiderConfig(opts = {}) {
|
|
|
2751
2788
|
* Claude Code owns.
|
|
2752
2789
|
*/
|
|
2753
2790
|
function configureClaudeCode(opts = {}) {
|
|
2791
|
+
if (opts.subscription) return configureClaudeCodeSubscription(opts);
|
|
2754
2792
|
const scope = opts.global ? "user" : "project";
|
|
2755
2793
|
const target = claudeCodeSettingsPath({ scope });
|
|
2756
2794
|
if (opts.remove) {
|
|
@@ -2760,7 +2798,10 @@ function configureClaudeCode(opts = {}) {
|
|
|
2760
2798
|
return;
|
|
2761
2799
|
}
|
|
2762
2800
|
const { baseUrl, port } = sidecarBaseUrl({ ...opts, provider: "anthropic" });
|
|
2763
|
-
|
|
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)}`);
|
|
2764
2805
|
if (!opts.write) {
|
|
2765
2806
|
step(`Dry run only. Re-run with \`--write\` to merge these two keys${scope === "project" ? " (or --write --global for every session)" : ""}.`);
|
|
2766
2807
|
} else {
|
|
@@ -2769,6 +2810,7 @@ function configureClaudeCode(opts = {}) {
|
|
|
2769
2810
|
baseUrl,
|
|
2770
2811
|
force: Boolean(opts.force),
|
|
2771
2812
|
statusLineCommand: opts.statusline ? statusLineSettingsCommand(port) : null,
|
|
2813
|
+
noteHookPort: note ? port : null,
|
|
2772
2814
|
});
|
|
2773
2815
|
if (!result.changed) ok(`${target} already routes Claude Code through PassControl`);
|
|
2774
2816
|
else {
|
|
@@ -2787,12 +2829,69 @@ function configureClaudeCode(opts = {}) {
|
|
|
2787
2829
|
} else if (!opts.statusline) {
|
|
2788
2830
|
step(`Optional, the agent's budget in Claude Code's status line: ${cliCommand(`configure claude-code --write --statusline${scope === "user" ? " --global" : ""}`)}`);
|
|
2789
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
|
+
}
|
|
2790
2837
|
step(`Start the sidecar before Claude Code: ${cliCommand(port === 8788 ? "sidecar" : `sidecar --port ${port}`)}`);
|
|
2791
2838
|
step("The agent's Anthropic scope must allow the models Claude Code uses (its main model, and Haiku for small tasks).");
|
|
2792
2839
|
step(`Optional, the chat tool as well: ${CLAUDE_CODE_ADD_COMMAND}`);
|
|
2793
2840
|
step(`To undo: ${cliCommand(`configure claude-code --remove${scope === "user" ? " --global" : ""}`)}`);
|
|
2794
2841
|
}
|
|
2795
2842
|
|
|
2843
|
+
/**
|
|
2844
|
+
* Subscription mode (cli/claude-code.mjs): a Claude
|
|
2845
|
+
* Pro/Max login keeps talking to Anthropic directly. PassControl is told about each
|
|
2846
|
+
* call, asked before each prompt and tool, and shown the usage window. Always the
|
|
2847
|
+
* user settings: Claude Code ignores telemetry settings in a project's file.
|
|
2848
|
+
*/
|
|
2849
|
+
function configureClaudeCodeSubscription(opts = {}) {
|
|
2850
|
+
const target = claudeCodeSettingsPath({ scope: "user" });
|
|
2851
|
+
const port = sidecarPort(opts);
|
|
2852
|
+
if (opts.remove) {
|
|
2853
|
+
const result = removeClaudeCodeSubscription({ target });
|
|
2854
|
+
if (result.changed) ok(`removed PassControl's subscription mode from ${target}`);
|
|
2855
|
+
else step(`${target} has no PassControl subscription settings; nothing to remove.`);
|
|
2856
|
+
return;
|
|
2857
|
+
}
|
|
2858
|
+
const note = Boolean(opts.agentNote);
|
|
2859
|
+
const preview = { env: subscriptionEnv(port), hooks: subscriptionHooks(port, { note }), statusLine: { type: "command", command: statusLineSettingsCommand(port) } };
|
|
2860
|
+
console.log(`Preview: ${target}\n\n${JSON.stringify(preview, null, 2)}`);
|
|
2861
|
+
if (!opts.write) {
|
|
2862
|
+
step("Dry run only. Re-run with `--write` to merge these into your Claude Code user settings (anything of yours is kept).");
|
|
2863
|
+
} else {
|
|
2864
|
+
const result = writeClaudeCodeSubscription({ target, port, statusLineCommand: statusLineSettingsCommand(port), force: Boolean(opts.force), note });
|
|
2865
|
+
if (!result.changed) ok(`${target} already has PassControl's subscription mode`);
|
|
2866
|
+
else {
|
|
2867
|
+
if (result.backupPath) step(`backed up ${result.backupPath}`);
|
|
2868
|
+
ok(`wrote ${target}`);
|
|
2869
|
+
}
|
|
2870
|
+
if (result.statusLine?.existing) {
|
|
2871
|
+
warn(`${target} already has a status line (${result.statusLine.existing}); it was left as it is, so the usage window is not shown. To show it, have yours pipe its input to \`${statusLineSettingsCommand(port)}\`.`);
|
|
2872
|
+
}
|
|
2873
|
+
if (result.hookUrlsBlocked) {
|
|
2874
|
+
warn(`${target} sets allowedHttpHookUrls, which does not include http://127.0.0.1:${port}/_passcontrol/hook and its tool hook (…/_passcontrol/hook?t=600): Claude Code will not run them until you add both, for example http://127.0.0.1:${port}/_passcontrol/hook*.`);
|
|
2875
|
+
}
|
|
2876
|
+
if (result.routed) {
|
|
2877
|
+
warn(`${target} also routes Claude Code through the sidecar with PassControl's API key (ANTHROPIC_BASE_URL). Those sessions do not use your subscription. To use the subscription, run ${cliCommand("configure claude-code --remove --global")}.`);
|
|
2878
|
+
}
|
|
2879
|
+
}
|
|
2880
|
+
step(`Start the sidecar before Claude Code: ${cliCommand(port === 8788 ? "sidecar" : `sidecar --port ${port}`)}`);
|
|
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
|
+
}
|
|
2887
|
+
step("If the sidecar is not running, Claude Code still works: stops are not checked and calls are not shown until it is.");
|
|
2888
|
+
step(`Watch the calls: ${cliCommand("watch")}`);
|
|
2889
|
+
step(
|
|
2890
|
+
`The sidecar also uploads each reported call (model, session, tokens, time, API-equivalent cost; never your email or account ids) to the agent's dashboard page, marked as reported, not proxied. To keep them on this machine only: ${cliCommand("sidecar --no-report-calls")}`
|
|
2891
|
+
);
|
|
2892
|
+
step(`To undo: ${cliCommand("configure claude-code --subscription --remove")}`);
|
|
2893
|
+
}
|
|
2894
|
+
|
|
2796
2895
|
/**
|
|
2797
2896
|
* Codex speaks only OpenAI's Responses API, so its profile always points at the
|
|
2798
2897
|
* sidecar's OpenAI route. A model is written only when one is named with
|
|
@@ -2880,7 +2979,51 @@ function profileCommand(rest, opts) {
|
|
|
2880
2979
|
for (const r of rows) console.log(`${r.profile.padEnd(20)} passport ${r.passport.padEnd(10)} port ${r.port}`);
|
|
2881
2980
|
}
|
|
2882
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
|
+
|
|
2883
3025
|
function configureCodex(opts = {}) {
|
|
3026
|
+
if (opts.subscription) return configureCodexSubscription(opts);
|
|
2884
3027
|
const target = codexProfilePath();
|
|
2885
3028
|
if (opts.remove) {
|
|
2886
3029
|
const result = removeCodexProfile({ target });
|
|
@@ -4376,6 +4519,22 @@ async function main(argv = process.argv.slice(2), runtime = {}) {
|
|
|
4376
4519
|
return;
|
|
4377
4520
|
}
|
|
4378
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
|
+
|
|
4379
4538
|
// Also before the update check: a full-screen board owns the terminal from its
|
|
4380
4539
|
// first frame, and the check's cache would be the one file `watch` ever wrote.
|
|
4381
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
|
|