passcontrol 1.5.1 → 1.7.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 +106 -6
- package/cli/agent-note.mjs +169 -0
- package/cli/budget-format.mjs +101 -8
- package/cli/claude-code.mjs +92 -18
- package/cli/client-events-upload.mjs +22 -0
- package/cli/codex-hooks.mjs +282 -0
- package/cli/config.mjs +3 -0
- package/cli/injection-hold.d.mts +7 -0
- package/cli/injection-hold.mjs +30 -0
- package/cli/injection-scan.d.mts +11 -0
- package/cli/injection-scan.mjs +405 -0
- package/cli/injection-sidecar.mjs +78 -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 +92 -8
- package/cli/statusline.mjs +2 -2
- package/cli/subscription-gate.mjs +77 -3
- package/cli/tool-gate.mjs +76 -14
- package/cli/watch-feed.mjs +39 -0
- package/cli/watch.mjs +46 -5
- package/package.json +1 -1
- package/sdk/verify.d.ts +13 -0
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
|
@@ -92,6 +92,7 @@ import { dashboardOriginForOffset, portHolders, stackPortConflictMessage } from
|
|
|
92
92
|
import { startSidecar } from "../cli/sidecar.mjs";
|
|
93
93
|
import { listProfiles, profilePath, readProfile, TOOL_PROFILE_PORTS, writeProfile } from "../cli/profiles.mjs";
|
|
94
94
|
import {
|
|
95
|
+
apiToolHooks,
|
|
95
96
|
claudeCodeEnv,
|
|
96
97
|
claudeCodeSettingsPath,
|
|
97
98
|
removeClaudeCodeSettings,
|
|
@@ -111,6 +112,15 @@ import {
|
|
|
111
112
|
} from "../cli/statusline.mjs";
|
|
112
113
|
import { runWatch } from "../cli/watch.mjs";
|
|
113
114
|
import { CODEX_PROFILE, codexProfilePath, codexProfileToml, codexStoresApiKey, removeCodexProfile, writeCodexProfile } from "../cli/codex.mjs";
|
|
115
|
+
import {
|
|
116
|
+
codexHookCommand,
|
|
117
|
+
codexHookEntries,
|
|
118
|
+
codexHooksPath,
|
|
119
|
+
probeCodexHookCommand,
|
|
120
|
+
removeCodexHooks,
|
|
121
|
+
runCodexHook,
|
|
122
|
+
writeCodexHooks,
|
|
123
|
+
} from "../cli/codex-hooks.mjs";
|
|
114
124
|
import { waitForGateway as awaitGateway } from "../cli/gateway-wait.mjs";
|
|
115
125
|
import { loginCommand } from "../cli/login.mjs";
|
|
116
126
|
import { logoutCommand } from "../cli/logout.mjs";
|
|
@@ -273,8 +283,14 @@ ${heading("Integrate")}
|
|
|
273
283
|
${cmd} env [integration] print settings without writing anything
|
|
274
284
|
${cmd} configure <integration> [--write] [--force] [--dedicated]
|
|
275
285
|
preview or write integration config
|
|
286
|
+
${cmd} configure claude-code --write
|
|
287
|
+
route model calls; tools ask the sidecar first
|
|
276
288
|
${cmd} configure claude-code --subscription [--write|--remove]
|
|
277
289
|
a Pro/Max login: stops, calls, usage window
|
|
290
|
+
${cmd} configure codex --subscription [--write|--remove]
|
|
291
|
+
a ChatGPT plan in Codex: stops and tool rules
|
|
292
|
+
${cmd} configure claude-code --write --agent-note
|
|
293
|
+
tell the agent its own limits, only when they change
|
|
278
294
|
integrations: ${integrationChoices()}
|
|
279
295
|
|
|
280
296
|
${heading("Trust")}
|
|
@@ -2771,7 +2787,7 @@ function aiderConfig(opts = {}) {
|
|
|
2771
2787
|
/**
|
|
2772
2788
|
* Claude Code's own model calls, through the sidecar (cli/claude-code.mjs). The
|
|
2773
2789
|
* project's settings by default; `--global` for every session; `--remove` takes
|
|
2774
|
-
* PassControl's
|
|
2790
|
+
* PassControl's env keys and tool hook back out. The MCP chat tool stays a separate command
|
|
2775
2791
|
* Claude Code owns.
|
|
2776
2792
|
*/
|
|
2777
2793
|
function configureClaudeCode(opts = {}) {
|
|
@@ -2785,21 +2801,27 @@ function configureClaudeCode(opts = {}) {
|
|
|
2785
2801
|
return;
|
|
2786
2802
|
}
|
|
2787
2803
|
const { baseUrl, port } = sidecarBaseUrl({ ...opts, provider: "anthropic" });
|
|
2788
|
-
|
|
2804
|
+
const note = Boolean(opts.agentNote);
|
|
2805
|
+
const preview = { env: claudeCodeEnv(baseUrl), hooks: apiToolHooks(port) };
|
|
2806
|
+
if (note) preview.hooks = { ...preview.hooks, UserPromptSubmit: [{ hooks: [{ type: "http", url: `http://127.0.0.1:${port}/_passcontrol/hook?note=only`, timeout: 5 }] }] };
|
|
2807
|
+
console.log(`Preview: ${target}\n\n${JSON.stringify(preview, null, 2)}`);
|
|
2789
2808
|
if (!opts.write) {
|
|
2790
|
-
step(`Dry run only. Re-run with \`--write\` to merge these
|
|
2809
|
+
step(`Dry run only. Re-run with \`--write\` to merge these env keys and the tool hook${scope === "project" ? " (or --write --global for every session)" : ""}.`);
|
|
2791
2810
|
} else {
|
|
2792
2811
|
const result = writeClaudeCodeSettings({
|
|
2793
2812
|
target,
|
|
2794
2813
|
baseUrl,
|
|
2795
2814
|
force: Boolean(opts.force),
|
|
2796
2815
|
statusLineCommand: opts.statusline ? statusLineSettingsCommand(port) : null,
|
|
2816
|
+
noteHookPort: note ? port : null,
|
|
2817
|
+
toolHookPort: port,
|
|
2797
2818
|
});
|
|
2798
2819
|
if (!result.changed) ok(`${target} already routes Claude Code through PassControl`);
|
|
2799
2820
|
else {
|
|
2800
2821
|
if (result.backupPath) step(`backed up ${result.backupPath}`);
|
|
2801
2822
|
ok(`wrote ${target}`);
|
|
2802
2823
|
}
|
|
2824
|
+
ok("Claude Code’s tools now ask the sidecar first for the agent’s tool rules and the injection guard’s hold.");
|
|
2803
2825
|
if (result.statusLine?.existing) {
|
|
2804
2826
|
warn(`${target} already has a status line (${result.statusLine.existing}); it was left as it is. To show the budget there, add \`${statusLineSettingsCommand(port)}\` to it yourself.`);
|
|
2805
2827
|
} else if (result.statusLine?.changed) ok("added the agent's budget to Claude Code's status line");
|
|
@@ -2812,6 +2834,11 @@ function configureClaudeCode(opts = {}) {
|
|
|
2812
2834
|
} else if (!opts.statusline) {
|
|
2813
2835
|
step(`Optional, the agent's budget in Claude Code's status line: ${cliCommand(`configure claude-code --write --statusline${scope === "user" ? " --global" : ""}`)}`);
|
|
2814
2836
|
}
|
|
2837
|
+
if (note) {
|
|
2838
|
+
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.");
|
|
2839
|
+
} else {
|
|
2840
|
+
step(`Optional, tell the agent its own budget, only when it changes: ${cliCommand(`configure claude-code --write --agent-note${scope === "user" ? " --global" : ""}`)}`);
|
|
2841
|
+
}
|
|
2815
2842
|
step(`Start the sidecar before Claude Code: ${cliCommand(port === 8788 ? "sidecar" : `sidecar --port ${port}`)}`);
|
|
2816
2843
|
step("The agent's Anthropic scope must allow the models Claude Code uses (its main model, and Haiku for small tasks).");
|
|
2817
2844
|
step(`Optional, the chat tool as well: ${CLAUDE_CODE_ADD_COMMAND}`);
|
|
@@ -2833,12 +2860,13 @@ function configureClaudeCodeSubscription(opts = {}) {
|
|
|
2833
2860
|
else step(`${target} has no PassControl subscription settings; nothing to remove.`);
|
|
2834
2861
|
return;
|
|
2835
2862
|
}
|
|
2836
|
-
const
|
|
2863
|
+
const note = Boolean(opts.agentNote);
|
|
2864
|
+
const preview = { env: subscriptionEnv(port), hooks: subscriptionHooks(port, { note }), statusLine: { type: "command", command: statusLineSettingsCommand(port) } };
|
|
2837
2865
|
console.log(`Preview: ${target}\n\n${JSON.stringify(preview, null, 2)}`);
|
|
2838
2866
|
if (!opts.write) {
|
|
2839
2867
|
step("Dry run only. Re-run with `--write` to merge these into your Claude Code user settings (anything of yours is kept).");
|
|
2840
2868
|
} else {
|
|
2841
|
-
const result = writeClaudeCodeSubscription({ target, port, statusLineCommand: statusLineSettingsCommand(port), force: Boolean(opts.force) });
|
|
2869
|
+
const result = writeClaudeCodeSubscription({ target, port, statusLineCommand: statusLineSettingsCommand(port), force: Boolean(opts.force), note });
|
|
2842
2870
|
if (!result.changed) ok(`${target} already has PassControl's subscription mode`);
|
|
2843
2871
|
else {
|
|
2844
2872
|
if (result.backupPath) step(`backed up ${result.backupPath}`);
|
|
@@ -2856,6 +2884,11 @@ function configureClaudeCodeSubscription(opts = {}) {
|
|
|
2856
2884
|
}
|
|
2857
2885
|
step(`Start the sidecar before Claude Code: ${cliCommand(port === 8788 ? "sidecar" : `sidecar --port ${port}`)}`);
|
|
2858
2886
|
step("Your Pro/Max login stays between Claude Code and Anthropic. PassControl never sees it or sits in the path.");
|
|
2887
|
+
if (note) {
|
|
2888
|
+
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.");
|
|
2889
|
+
} else {
|
|
2890
|
+
step(`Optional, tell the agent its tool rules, only when they change: ${cliCommand("configure claude-code --subscription --write --agent-note")}`);
|
|
2891
|
+
}
|
|
2859
2892
|
step("If the sidecar is not running, Claude Code still works: stops are not checked and calls are not shown until it is.");
|
|
2860
2893
|
step(`Watch the calls: ${cliCommand("watch")}`);
|
|
2861
2894
|
step(
|
|
@@ -2951,7 +2984,52 @@ function profileCommand(rest, opts) {
|
|
|
2951
2984
|
for (const r of rows) console.log(`${r.profile.padEnd(20)} passport ${r.passport.padEnd(10)} port ${r.port}`);
|
|
2952
2985
|
}
|
|
2953
2986
|
|
|
2987
|
+
/**
|
|
2988
|
+
* Subscription mode for Codex (cli/codex-hooks.mjs): a ChatGPT login keeps talking
|
|
2989
|
+
* to OpenAI directly; PassControl's stops and tool rules reach the session through
|
|
2990
|
+
* three hooks in $CODEX_HOME/hooks.json, next to anyone else's.
|
|
2991
|
+
*/
|
|
2992
|
+
function configureCodexSubscription(opts = {}) {
|
|
2993
|
+
const target = codexHooksPath();
|
|
2994
|
+
const port = sidecarPort(opts);
|
|
2995
|
+
if (opts.remove) {
|
|
2996
|
+
const result = removeCodexHooks({ target });
|
|
2997
|
+
if (result.changed) ok(`removed PassControl's hooks from ${target}`);
|
|
2998
|
+
else step(`${target} has no PassControl hooks; nothing to remove.`);
|
|
2999
|
+
return;
|
|
3000
|
+
}
|
|
3001
|
+
// node and this file by absolute path (cli/codex-hooks.mjs): PATH must not decide
|
|
3002
|
+
// whether a stop reaches Codex. The same string on every run, so trust holds.
|
|
3003
|
+
const command = codexHookCommand({ port, entry: fs.realpathSync(CLI_ENTRY) });
|
|
3004
|
+
console.log(`Preview: added to ${target} (anything already there is kept)\n\n${JSON.stringify(codexHookEntries(command), null, 2)}`);
|
|
3005
|
+
if (!opts.write) {
|
|
3006
|
+
step("Dry run only. Re-run with `--write` to add these three hooks.");
|
|
3007
|
+
} else {
|
|
3008
|
+
const result = writeCodexHooks({ target, command });
|
|
3009
|
+
if (!result.changed) ok(`${target} already has PassControl's hooks`);
|
|
3010
|
+
else {
|
|
3011
|
+
if (result.backupPath) step(`backed up ${result.backupPath}`);
|
|
3012
|
+
ok(`wrote ${target}`);
|
|
3013
|
+
warn("Not on yet: Codex runs a hook only after you trust it. Open Codex, type /hooks, and trust PassControl's three hooks (any you trusted before stay trusted). Until then they are skipped without a word.");
|
|
3014
|
+
}
|
|
3015
|
+
const probe = probeCodexHookCommand(command);
|
|
3016
|
+
if (probe.ok) ok("the hook command runs on its own, without your shell's PATH");
|
|
3017
|
+
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.`);
|
|
3018
|
+
}
|
|
3019
|
+
step(`Start the sidecar before Codex: ${cliCommand(port === 8788 ? "sidecar" : `sidecar --port ${port}`)}`);
|
|
3020
|
+
step("Your ChatGPT login stays between Codex and OpenAI. PassControl never sees it or sits in the path.");
|
|
3021
|
+
step("What Codex's tools return is also scanned on this machine for the injection guard (the PostToolUse hook). That hook never blocks a tool or changes what it returned.");
|
|
3022
|
+
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.");
|
|
3023
|
+
step("What it cannot do, plainly:");
|
|
3024
|
+
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).");
|
|
3025
|
+
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.");
|
|
3026
|
+
step(" An \"ask\" rule cannot ask in Codex, so it refuses instead.");
|
|
3027
|
+
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.");
|
|
3028
|
+
step(`To undo: ${cliCommand("configure codex --subscription --remove")}`);
|
|
3029
|
+
}
|
|
3030
|
+
|
|
2954
3031
|
function configureCodex(opts = {}) {
|
|
3032
|
+
if (opts.subscription) return configureCodexSubscription(opts);
|
|
2955
3033
|
const target = codexProfilePath();
|
|
2956
3034
|
if (opts.remove) {
|
|
2957
3035
|
const result = removeCodexProfile({ target });
|
|
@@ -3403,14 +3481,20 @@ async function verifyCommand(rest, opts) {
|
|
|
3403
3481
|
// Lineage is DECLARED by the client: any local process can send those
|
|
3404
3482
|
// headers. Say so on the same line, so nobody reads it as passport-proven.
|
|
3405
3483
|
// Printable ASCII only: a signed value is still not a terminal's to obey.
|
|
3484
|
+
const shown = (v) => String(v).replace(/[^\x20-\x7e]/g, "?").slice(0, 128);
|
|
3406
3485
|
if (c.ctx?.ses) {
|
|
3407
|
-
const shown = (v) => String(v).replace(/[^\x20-\x7e]/g, "?").slice(0, 128);
|
|
3408
3486
|
const who = c.ctx.agt
|
|
3409
3487
|
? `sub-agent ${shown(c.ctx.agt)}${c.ctx.par ? `, spawned by ${shown(c.ctx.par)}` : ""}`
|
|
3410
3488
|
: "main agent";
|
|
3411
3489
|
step(`Session: ${shown(c.ctx.ses)} · ${who}`);
|
|
3412
3490
|
step(` declared by the client (${shown(c.ctx.cli ?? "unknown")}), not verified`);
|
|
3413
3491
|
}
|
|
3492
|
+
const inj = c.inj;
|
|
3493
|
+
if (typeof inj === "object" && inj !== null && !Array.isArray(inj) &&
|
|
3494
|
+
typeof inj.d === "string" && inj.d && Number.isSafeInteger(inj.n) && inj.n >= 1 && Array.isArray(inj.f)) {
|
|
3495
|
+
step(`Injection: ${inj.n} block(s) of tool output carried injection tells (${shown(inj.d)})`);
|
|
3496
|
+
step(` kinds: ${inj.f.slice(0, 16).map(shown).join(", ")}`);
|
|
3497
|
+
}
|
|
3414
3498
|
}
|
|
3415
3499
|
if (c.own) {
|
|
3416
3500
|
step(
|
|
@@ -4447,6 +4531,22 @@ async function main(argv = process.argv.slice(2), runtime = {}) {
|
|
|
4447
4531
|
return;
|
|
4448
4532
|
}
|
|
4449
4533
|
|
|
4534
|
+
// Codex's hook relay (cli/codex-hooks.mjs), before the update check for the same
|
|
4535
|
+
// reason: on a prompt, everything it prints becomes context for the model. It
|
|
4536
|
+
// prints its answer or nothing, and exits 0 whatever happens.
|
|
4537
|
+
if (command === "codex-hook") {
|
|
4538
|
+
let input = "";
|
|
4539
|
+
try {
|
|
4540
|
+
for await (const chunk of process.stdin) input += chunk;
|
|
4541
|
+
const port = sidecarPort(opts);
|
|
4542
|
+
const out = await runCodexHook({ input, port });
|
|
4543
|
+
if (out) process.stdout.write(`${out}\n`);
|
|
4544
|
+
} catch {
|
|
4545
|
+
// Nothing: a hook that cannot run lets Codex go ahead, as a failed hook would.
|
|
4546
|
+
}
|
|
4547
|
+
return;
|
|
4548
|
+
}
|
|
4549
|
+
|
|
4450
4550
|
// Also before the update check: a full-screen board owns the terminal from its
|
|
4451
4551
|
// first frame, and the check's cache would be the one file `watch` ever wrote.
|
|
4452
4552
|
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
|
|