passcontrol 1.2.1 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,160 @@
1
+ // Route Claude Code's own model calls through the PassControl sidecar.
2
+ //
3
+ // Claude Code reads an `env` block from its settings files wherever it is
4
+ // started (verified 2026-10-07, Claude Code 2.1.292): ANTHROPIC_BASE_URL sends
5
+ // its calls to the sidecar, and ANTHROPIC_AUTH_TOKEN, a placeholder, rides as a
6
+ // Bearer token with no "use this API key?" prompt. The sidecar strips it and the
7
+ // gateway injects the real key, so Claude Code never holds one.
8
+ //
9
+ // The settings file belongs to the user. Only these two keys, and with
10
+ // --statusline a `statusLine` running `passcontrol statusline`, are written or
11
+ // removed, in one save; the previous file is backed up, a file that is not a JSON
12
+ // object is refused rather than overwritten, a different gateway already
13
+ // configured is not replaced without --force, and a status line the user already
14
+ // has is never replaced at all.
15
+ import fs from "node:fs";
16
+ import os from "node:os";
17
+ import path from "node:path";
18
+
19
+ /** Not a secret: the sidecar discards whatever arrives in this header. */
20
+ export const CLAUDE_CODE_AUTH_PLACEHOLDER = "passcontrol-sidecar";
21
+
22
+ export function claudeCodeEnv(baseUrl) {
23
+ return { ANTHROPIC_BASE_URL: baseUrl, ANTHROPIC_AUTH_TOKEN: CLAUDE_CODE_AUTH_PLACEHOLDER };
24
+ }
25
+
26
+ /**
27
+ * `project`: this directory's `.claude/settings.local.json`, the file Claude Code
28
+ * keeps out of git. `user`: every Claude Code session, under CLAUDE_CONFIG_DIR
29
+ * when set, as Claude Code itself resolves it.
30
+ */
31
+ export function claudeCodeSettingsPath({ scope, cwd = process.cwd(), env = process.env }) {
32
+ if (scope === "user") {
33
+ const dir = env.CLAUDE_CONFIG_DIR || path.join(env.HOME || os.homedir(), ".claude");
34
+ return path.join(dir, "settings.json");
35
+ }
36
+ return path.join(cwd, ".claude", "settings.local.json");
37
+ }
38
+
39
+ function readSettings(target) {
40
+ if (!fs.existsSync(target)) return { exists: false, value: {} };
41
+ const text = fs.readFileSync(target, "utf8");
42
+ if (!text.trim()) return { exists: true, value: {} };
43
+ let value;
44
+ try {
45
+ value = JSON.parse(text);
46
+ } catch {
47
+ throw new Error(`${target} is not valid JSON; fix or move it, then run this again. Nothing was written.`);
48
+ }
49
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
50
+ throw new Error(`${target} is not a JSON object; nothing was written.`);
51
+ }
52
+ return { exists: true, value };
53
+ }
54
+
55
+ function save(target, value, exists) {
56
+ fs.mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
57
+ let backupPath = null;
58
+ if (exists) {
59
+ backupPath = `${target}.bak`;
60
+ fs.copyFileSync(target, backupPath);
61
+ fs.chmodSync(backupPath, 0o600);
62
+ }
63
+ fs.writeFileSync(target, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
64
+ fs.chmodSync(target, 0o600);
65
+ return backupPath;
66
+ }
67
+
68
+ /**
69
+ * The env keys, and with `statusLineCommand` the status line too, in ONE save:
70
+ * two saves would back up the first save's output and lose the user's original.
71
+ */
72
+ export function writeClaudeCodeSettings({ target, baseUrl, force = false, statusLineCommand = null }) {
73
+ const { exists, value } = readSettings(target);
74
+ const env = typeof value.env === "object" && value.env !== null && !Array.isArray(value.env) ? value.env : {};
75
+ const rawKeyFound = typeof env.ANTHROPIC_API_KEY === "string" && env.ANTHROPIC_API_KEY.length > 0;
76
+ const current = env.ANTHROPIC_BASE_URL;
77
+ const envDone = current === baseUrl && env.ANTHROPIC_AUTH_TOKEN === CLAUDE_CODE_AUTH_PLACEHOLDER;
78
+ if (!envDone && typeof current === "string" && current && current !== baseUrl && !force) {
79
+ throw new Error(
80
+ `${target} already points Claude Code at ${current}. Re-run with --force to replace that address with PassControl's.`
81
+ );
82
+ }
83
+ let next = envDone ? value : { ...value, env: { ...env, ...claudeCodeEnv(baseUrl) } };
84
+ let statusLine;
85
+ if (statusLineCommand) {
86
+ const line = withStatusLine(next, statusLineCommand);
87
+ next = line.value;
88
+ statusLine = line.existing !== undefined ? { changed: false, existing: line.existing } : { changed: line.changed };
89
+ }
90
+ const changed = !envDone || Boolean(statusLine?.changed);
91
+ const backupPath = changed ? save(target, next, exists) : null;
92
+ return { changed, backupPath, rawKeyFound, ...(statusLine ? { statusLine } : {}) };
93
+ }
94
+
95
+ /** PassControl's two env keys and its status line, in one save. */
96
+ export function removeClaudeCodeSettings({ target }) {
97
+ if (!fs.existsSync(target)) return { changed: false };
98
+ const { value } = readSettings(target);
99
+ let next = value;
100
+ const env = typeof value.env === "object" && value.env !== null && !Array.isArray(value.env) ? value.env : null;
101
+ // Only an address this command could have written: a gateway someone else set
102
+ // up is not ours to remove.
103
+ if (env && env.ANTHROPIC_AUTH_TOKEN === CLAUDE_CODE_AUTH_PLACEHOLDER) {
104
+ const { ANTHROPIC_BASE_URL: _url, ANTHROPIC_AUTH_TOKEN: _token, ...rest } = env;
105
+ next = { ...value };
106
+ if (Object.keys(rest).length) next.env = rest;
107
+ else delete next.env;
108
+ }
109
+ if (isOurStatusLine(next.statusLine)) {
110
+ const { statusLine: _ours, ...rest } = next;
111
+ next = rest;
112
+ }
113
+ if (next === value) return { changed: false };
114
+ save(target, next, true);
115
+ return { changed: true };
116
+ }
117
+
118
+ /**
119
+ * Whether a status line is one `configure claude-code --statusline` wrote: the
120
+ * installed `passcontrol` binary, or this repo's own bin run through node.
121
+ */
122
+ function isOurStatusLine(statusLine) {
123
+ const command = typeof statusLine?.command === "string" ? statusLine.command : "";
124
+ return /^(passcontrol|node "[^"]*passcontrol\.mjs") statusline\b/.test(command);
125
+ }
126
+
127
+ /**
128
+ * `value` with PassControl's status line set, unless the user already has one of
129
+ * their own: then `existing` names it and `value` is unchanged.
130
+ */
131
+ function withStatusLine(value, command) {
132
+ const current = value.statusLine;
133
+ if (current && !isOurStatusLine(current)) {
134
+ return { value, changed: false, existing: typeof current.command === "string" ? current.command : "(not a command)" };
135
+ }
136
+ if (current && current.type === "command" && current.command === command) return { value, changed: false };
137
+ return { value: { ...value, statusLine: { type: "command", command } }, changed: true };
138
+ }
139
+
140
+ /**
141
+ * The agent's budget in Claude Code's status line, on its own. A status line the
142
+ * user already has is never replaced: the answer names it and nothing is written.
143
+ */
144
+ export function writeClaudeCodeStatusLine({ target, command }) {
145
+ const { exists, value } = readSettings(target);
146
+ const line = withStatusLine(value, command);
147
+ if (line.existing !== undefined) return { changed: false, existing: line.existing };
148
+ if (!line.changed) return { changed: false };
149
+ save(target, line.value, exists);
150
+ return { changed: true };
151
+ }
152
+
153
+ export function removeClaudeCodeStatusLine({ target }) {
154
+ if (!fs.existsSync(target)) return { changed: false };
155
+ const { value } = readSettings(target);
156
+ if (!isOurStatusLine(value.statusLine)) return { changed: false };
157
+ const { statusLine: _ours, ...rest } = value;
158
+ save(target, rest, true);
159
+ return { changed: true };
160
+ }
package/cli/codex.mjs ADDED
@@ -0,0 +1,102 @@
1
+ // Route Codex's own model calls through the PassControl sidecar.
2
+ //
3
+ // Codex takes a custom model provider only from user-level config: a project's
4
+ // `.codex/config.toml` cannot set one, and the old `profile = "..."` selector is
5
+ // refused (verified 2026-10-07, Codex CLI 0.160.1). So this writes a profile file,
6
+ // `$CODEX_HOME/passcontrol.config.toml`, which Codex layers over config.toml when
7
+ // started with `codex --profile passcontrol`. With no key configured for the
8
+ // provider, Codex sends no Authorization header at all (captured); the sidecar
9
+ // adds the agent's credential and the gateway injects the real OpenAI key.
10
+ //
11
+ // config.toml is never opened: the Codex app shares it, and PassControl would
12
+ // need a TOML parser to edit it safely. The profile file is PassControl's own,
13
+ // marked on its first line, so a file at that path without the marker is someone
14
+ // else's and is not replaced without --force, nor ever removed.
15
+ import fs from "node:fs";
16
+ import os from "node:os";
17
+ import path from "node:path";
18
+
19
+ export const CODEX_PROFILE = "passcontrol";
20
+ export const CODEX_PROFILE_MARKER = "# Written by `passcontrol configure codex`.";
21
+
22
+ function codexHome(env) {
23
+ return env.CODEX_HOME || path.join(env.HOME || os.homedir(), ".codex");
24
+ }
25
+
26
+ export function codexProfilePath({ env = process.env } = {}) {
27
+ return path.join(codexHome(env), `${CODEX_PROFILE}.config.toml`);
28
+ }
29
+
30
+ /**
31
+ * Whether Codex keeps an OpenAI API key of its own (`codex login --api-key`, in
32
+ * auth.json). The profile never sends it, but plain `codex` does. True or false
33
+ * only: the value is never returned, and an unreadable file counts as no key.
34
+ */
35
+ export function codexStoresApiKey({ env = process.env } = {}) {
36
+ try {
37
+ const auth = JSON.parse(fs.readFileSync(path.join(codexHome(env), "auth.json"), "utf8"));
38
+ return typeof auth?.OPENAI_API_KEY === "string" && auth.OPENAI_API_KEY.length > 0;
39
+ } catch {
40
+ return false;
41
+ }
42
+ }
43
+
44
+ // A TOML basic string. JSON's escapes (\" \\ \n \uXXXX …) are all valid TOML
45
+ // escapes, so a value cannot close its string and start a key of its own.
46
+ const tomlString = (value) => JSON.stringify(String(value));
47
+
48
+ export function codexProfileToml({ baseUrl, model }) {
49
+ let url;
50
+ try {
51
+ url = new URL(baseUrl);
52
+ } catch {
53
+ url = null;
54
+ }
55
+ if (!url || (url.protocol !== "http:" && url.protocol !== "https:")) {
56
+ throw new Error(`The sidecar address must be an http(s) URL, not ${JSON.stringify(String(baseUrl))}.`);
57
+ }
58
+ return [
59
+ CODEX_PROFILE_MARKER,
60
+ `# Use it with: codex --profile ${CODEX_PROFILE}`,
61
+ "# Codex's model calls go to the PassControl sidecar, which must be running. No OpenAI",
62
+ "# key belongs here: the gateway adds the real one. Undo: passcontrol configure codex --remove",
63
+ ...(model ? [`model = ${tomlString(model)}`] : []),
64
+ `model_provider = ${tomlString(CODEX_PROFILE)}`,
65
+ "",
66
+ `[model_providers.${CODEX_PROFILE}]`,
67
+ 'name = "PassControl"',
68
+ `base_url = ${tomlString(baseUrl)}`,
69
+ 'wire_api = "responses"',
70
+ "",
71
+ ].join("\n");
72
+ }
73
+
74
+ const isOurs = (text) => text.startsWith(CODEX_PROFILE_MARKER);
75
+
76
+ export function writeCodexProfile({ target, baseUrl, model, force = false }) {
77
+ const next = codexProfileToml({ baseUrl, model });
78
+ const exists = fs.existsSync(target);
79
+ let backupPath = null;
80
+ if (exists) {
81
+ const current = fs.readFileSync(target, "utf8");
82
+ if (current === next) return { changed: false, backupPath: null };
83
+ if (!isOurs(current) && !force) {
84
+ throw new Error(
85
+ `${target} exists and was not written by PassControl. Re-run with --force to replace it (a backup is kept).`
86
+ );
87
+ }
88
+ backupPath = `${target}.bak`;
89
+ fs.copyFileSync(target, backupPath);
90
+ fs.chmodSync(backupPath, 0o600);
91
+ }
92
+ fs.mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
93
+ fs.writeFileSync(target, next, { mode: 0o600 });
94
+ fs.chmodSync(target, 0o600);
95
+ return { changed: true, backupPath };
96
+ }
97
+
98
+ export function removeCodexProfile({ target }) {
99
+ if (!fs.existsSync(target) || !isOurs(fs.readFileSync(target, "utf8"))) return { changed: false };
100
+ fs.rmSync(target);
101
+ return { changed: true };
102
+ }
package/cli/config.mjs CHANGED
@@ -28,8 +28,8 @@ export const PACKAGE_VERSION = (() => {
28
28
  // second numeric copy that can drift from system-health capability reporting.
29
29
  export const WORKSPACE_IMPORT_MAX_VERSION = WORKSPACE_EXPORT_PROTOCOL.maximum;
30
30
 
31
- export const PROVIDERS = ["openai", "anthropic", "groq", "mistral", "together", "deepseek", "gemini", "xai", "azure", "local"];
32
- export const OPENAI_SHAPE_PROVIDERS = new Set(["openai", "groq", "mistral", "together", "deepseek", "gemini", "azure", "local"]);
31
+ export const PROVIDERS = ["openai", "anthropic", "groq", "mistral", "together", "deepseek", "gemini", "xai", "openrouter", "azure", "local"];
32
+ export const OPENAI_SHAPE_PROVIDERS = new Set(["openai", "groq", "mistral", "together", "deepseek", "gemini", "openrouter", "azure", "local"]);
33
33
 
34
34
  const DEFAULT_GATEWAY = "http://localhost:3000";
35
35
 
@@ -671,7 +671,7 @@ export function formatProxyError(status, body) {
671
671
  return `${blocked}\n→ The workspace has no provider key stored for this provider.\n→ Fix: add one under Settings → Provider credentials in the dashboard.`;
672
672
  }
673
673
  if (status === 400 && error === "server_side_tools_unsupported") {
674
- return `${blocked}\n→ The request uses a hosted tool (such as web search) that the provider bills outside tokens, which no budget here can hold.\n→ Fix: remove the hosted tool, or call that feature outside PassControl.`;
674
+ return `${blocked}\n→ The request uses a hosted tool PassControl does not price, such as image generation, an MCP server, or Claude Code's advisor with an unpriced model.\n→ Fix: remove that tool, or call it outside PassControl (Claude Code: /advisor → No advisor). Priced tools such as web search pass.`;
675
675
  }
676
676
  // 402 is also how the gateway refuses a call it cannot price under a dollar
677
677
  // limit; a bigger budget fixes none of those, so each gets its own advice.
@@ -0,0 +1,33 @@
1
+ // The session a relayed call declares, exactly as the gateway reads it from the request
2
+ // headers (lib/client-lineage.ts `readClientLineage`, which the proxy calls without the
3
+ // body): Claude Code's session header, else a Codex session its headers agree on, else
4
+ // this sidecar run's own id (`x-passcontrol-run`, which the sidecar sets on every call).
5
+ //
6
+ // A second copy because the sidecar is plain ESM and cannot import the gateway's
7
+ // TypeScript. tests/declared-session-parity.test.ts runs both over every captured
8
+ // Claude Code and Codex request and fails the day they disagree: the journal is
9
+ // filtered by this value, so a mismatch could hide a real omission.
10
+
11
+ const DECLARED = /^[A-Za-z0-9._:-]{1,128}$/;
12
+ const declared = (value) => (typeof value === "string" && DECLARED.test(value) ? value : null);
13
+
14
+ /**
15
+ * @param {(name: string) => string | null | undefined} header lower-case header lookup
16
+ * @param {string} runId this sidecar run's id
17
+ */
18
+ export function declaredSession(header, runId) {
19
+ const claude = declared(header("x-claude-code-session-id"));
20
+ if (claude) return claude;
21
+
22
+ const isCodex =
23
+ /^codex/i.test(header("originator") ?? "") ||
24
+ header("x-codex-turn-metadata") != null ||
25
+ header("x-codex-window-id") != null ||
26
+ header("x-codex-parent-thread-id") != null;
27
+ if (isCodex) {
28
+ const raw = [header("session-id"), header("session_id")].filter((v) => v !== null && v !== undefined);
29
+ if (raw.length > 0 && raw.every((v) => declared(v) !== null) && raw.every((v) => v === raw[0])) return raw[0];
30
+ }
31
+
32
+ return declared(runId);
33
+ }
@@ -7,6 +7,7 @@ export type IntegrationProvider =
7
7
  | "deepseek"
8
8
  | "gemini"
9
9
  | "xai"
10
+ | "openrouter"
10
11
  | "azure"
11
12
  | "local";
12
13
 
@@ -13,6 +13,9 @@ export const DEFAULT_ALLOWED_MODELS = Object.freeze({
13
13
  deepseek: "deepseek-*",
14
14
  gemini: "gemini-*",
15
15
  xai: "grok-*",
16
+ // OpenRouter's free router: it only ever picks a $0 model, so the default grant
17
+ // spends nothing. A paid model is a scope the operator widens on purpose.
18
+ openrouter: "openrouter/free",
16
19
  // An Azure `model` is a DEPLOYMENT name the customer chose, not a model id.
17
20
  // `gpt-*` covers deployments named after their model and nothing wider: a bare
18
21
  // `*` would widen an allowlist to whatever a resource ever deploys. An operator
@@ -35,6 +38,8 @@ export const DEFAULT_CLIENT_MODELS = Object.freeze({
35
38
  // The cheapest listed model that does not reason (docs.x.ai/developers/models.md,
36
39
  // 2026-09-27): xAI's reasoning models cannot turn reasoning off.
37
40
  xai: "grok-4.20-0309-non-reasoning",
41
+ // Stable, where individual `:free` model ids come and go.
42
+ openrouter: "openrouter/free",
38
43
  // A deployment name, so only a guess until the operator names theirs.
39
44
  azure: "gpt-4.1-mini",
40
45
  // Ollama's most-pulled small model. Only a guess: the dashboard offers the
@@ -0,0 +1,84 @@
1
+ // The sidecar's journal: the user's own list of the receipt ids their calls produced.
2
+ //
3
+ // WHY IT EXISTS. A session seal (`passcontrol verify session`) proves the issuer
4
+ // committed to a set of receipts. The journal is what lets the user check that set
5
+ // against an INDEPENDENT record: every id here must be in the seal's bundle, so a
6
+ // call left out of the seal is caught. Without it a seal is no stronger than a
7
+ // statement (sdk/verify.ts, verifySession).
8
+ //
9
+ // WHAT IT HOLDS: one JSON line per relayed call — `{ id, t, s }`, the receipt id,
10
+ // the time in epoch milliseconds, and the HTTP status. Nothing else, ever: no
11
+ // prompt, no model, no header, no body. The id is already shown to the client in
12
+ // `x-passcontrol-receipt-id`; the journal only keeps it.
13
+ //
14
+ // One file per sidecar run, named by start time and run id, owner-only (0600 in a
15
+ // 0700 directory). Created on the first call that returns a receipt, so a sidecar
16
+ // that relays nothing leaves nothing behind. On by default; `--no-journal` turns it
17
+ // off (D3, 2026-10-08).
18
+ //
19
+ // A journal failure NEVER breaks a call: the call has already happened, and the
20
+ // worst a lost line can do is make a later seal check report that receipt as
21
+ // "in the seal, not in your journal", which is never a failure. It warns once.
22
+ import fs from "node:fs";
23
+ import path from "node:path";
24
+ import { globalConfigPath } from "./config.mjs";
25
+
26
+ const RECEIPT_ID = /^[A-Za-z0-9._:-]{1,128}$/;
27
+
28
+ /** `<config dir>/journal`, beside the CLI's own config file. */
29
+ export function defaultJournalDir(env = process.env) {
30
+ return path.join(path.dirname(globalConfigPath(env)), "journal");
31
+ }
32
+
33
+ /** `2026-10-08T03-21-00Z`: sortable, and legal in a filename on every platform. */
34
+ function stamp(ms) {
35
+ return new Date(ms).toISOString().replace(/\.\d{3}Z$/, "Z").replace(/:/g, "-");
36
+ }
37
+
38
+ export function openJournal({ dir = defaultJournalDir(), runId, now = Date.now, onError = () => {} }) {
39
+ const file = path.join(dir, `${stamp(now())}-${runId}.jsonl`);
40
+ let fd = null;
41
+ let broken = false;
42
+
43
+ function ensureOpen() {
44
+ if (fd !== null) return fd;
45
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
46
+ // mkdir's mode is filtered by the umask, and an existing directory keeps
47
+ // whatever it had. This one holds a record of the user's calls: owner-only.
48
+ fs.chmodSync(dir, 0o700);
49
+ fd = fs.openSync(file, "a", 0o600);
50
+ fs.fchmodSync(fd, 0o600);
51
+ return fd;
52
+ }
53
+
54
+ return {
55
+ path: file,
56
+ /**
57
+ * Record one relayed call. Never throws. `session` is the session the call
58
+ * declared (cli/declared-session.mjs): one sidecar run serves many sessions, and
59
+ * a seal is checked against its own session's lines only.
60
+ */
61
+ record(id, status, session) {
62
+ if (broken || typeof id !== "string" || !RECEIPT_ID.test(id)) return;
63
+ try {
64
+ const entry = { id, t: now(), s: Number.isInteger(status) ? status : 0 };
65
+ if (typeof session === "string" && RECEIPT_ID.test(session)) entry.ses = session;
66
+ const line = JSON.stringify(entry) + "\n";
67
+ fs.writeSync(ensureOpen(), line);
68
+ } catch (e) {
69
+ broken = true;
70
+ onError(e);
71
+ }
72
+ },
73
+ close() {
74
+ if (fd !== null) {
75
+ try {
76
+ fs.closeSync(fd);
77
+ } catch {
78
+ // Already closed, or the process is exiting: nothing to keep.
79
+ }
80
+ fd = null;
81
+ }
82
+ },
83
+ };
84
+ }
package/cli/mcp/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # PassControl MCP server
2
2
 
3
- `passcontrol mcp` starts a local stdio MCP server with `chat` and `list_models`.
3
+ `passcontrol mcp` starts a local stdio MCP server with `chat`, `list_models` and `budget`.
4
4
  It reads the same environment, nearest `.passcontrol`, and global
5
5
  `~/.config/passcontrol/config` sources as the rest of the CLI. MCP client setup requires a
6
6
  passport in the global profile so clients can launch from any working directory without
@@ -65,6 +65,9 @@ config contains a passport secret or provider key.
65
65
  `chat` sends a bearer visa, without a sender proof. Required sender-proof mode
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
+ `budget` reads the agent's own limits from the gateway (`GET /api/v1/self`): what is used,
69
+ what is left, and when a daily or monthly limit resets. It spends nothing and writes no log
70
+ row; like `chat`, it sends a bearer visa, so required sender-proof mode refuses it.
68
71
  Providers: OpenAI, Anthropic, Groq, Mistral, Together, DeepSeek, and Gemini (OpenAI-compatible).
69
72
  The global profile can use the CLI OS credential store (`passcontrol key status`) rather
70
73
  than containing the Passport secret. Custody declarations do not prove storage.
@@ -156,5 +156,18 @@ export function createGatewayClient({
156
156
  async listModels() {
157
157
  return modelsFromVisa(await visas.getVisa());
158
158
  },
159
+
160
+ /** The agent's own scope and limits (GET /api/v1/self). Reads; spends nothing. */
161
+ async self() {
162
+ const response = await visas.fetchWithVisa((visa) =>
163
+ fetchImpl(`${baseUrl}/api/v1/self`, { method: "GET", headers: { authorization: `Bearer ${visa}` } })
164
+ );
165
+ if (!response.ok) throw new Error(proxyError(response.status, await response.text()));
166
+ try {
167
+ return await response.json();
168
+ } catch {
169
+ throw new Error("Gateway returned a non-JSON answer for the agent's limits.");
170
+ }
171
+ },
159
172
  };
160
173
  }
@@ -2,6 +2,7 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
2
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
3
  import { z } from "zod/v4";
4
4
  import { PACKAGE_VERSION, PROVIDERS } from "../config.mjs";
5
+ import { budgetLines } from "../budget-format.mjs";
5
6
  import { createGatewayClient } from "./gateway.mjs";
6
7
 
7
8
  const messageSchema = z.object({
@@ -104,6 +105,32 @@ export function createMcpServer(options) {
104
105
  }
105
106
  );
106
107
 
108
+ server.registerTool(
109
+ "budget",
110
+ {
111
+ title: "Budget and limits",
112
+ description:
113
+ "Read this agent's own spending and token limits: what is used, what is left, and when a daily or monthly limit resets. Check it before an expensive call; a cheaper model may fit where this one would be refused.",
114
+ annotations: {
115
+ readOnlyHint: true,
116
+ destructiveHint: false,
117
+ idempotentHint: true,
118
+ openWorldHint: false,
119
+ },
120
+ },
121
+ async () => {
122
+ try {
123
+ const self = await gateway.self();
124
+ return {
125
+ content: [{ type: "text", text: budgetLines(self).join("\n") }],
126
+ structuredContent: self,
127
+ };
128
+ } catch (error) {
129
+ return toolError(error);
130
+ }
131
+ }
132
+ );
133
+
107
134
  return server;
108
135
  }
109
136
 
package/cli/menu.mjs CHANGED
@@ -171,6 +171,7 @@ export const GROUPS = [
171
171
  // reading of it is a money question. Verifying somebody ELSE's statement
172
172
  // is the evidence question, and that one sits with the other verifiers.
173
173
  command({ id: "statements", label: "Signed spend statements", run: ["statements"], detail: "statements", description: "Show the daily chain committing to every receipt in each window.", network: "gateway" }),
174
+ command({ id: "sessions", label: "Coding sessions", run: ["sessions"], detail: "sessions", description: "Claude Code and Codex sessions: sub-agents and spend, as declared.", network: "gateway" }),
174
175
  ],
175
176
  },
176
177
  {
@@ -261,6 +262,8 @@ export const HIDDEN = {
261
262
  keygen: "reached through its `instance` subcommand under Trust",
262
263
  verify: "reached through its subcommands under Evidence",
263
264
  try: "kept as an explanatory compatibility error, but no longer performs an operation",
265
+ seal: "needs a session and an agent, both named by `sessions`, which is listed under Money",
266
+ statusline: "Claude Code runs it, not a person; `configure claude-code --statusline` installs it",
264
267
  };
265
268
 
266
269
  /** Every top-level command name the menu can reach, flattened. */
package/cli/presets.mjs CHANGED
@@ -98,6 +98,8 @@ export function isServicePreset(name) {
98
98
  /** Presets that print settings pointing an agent at the local sidecar bridge. */
99
99
  export const SIDECAR_PRESETS = [
100
100
  "generic",
101
+ // Apps that only take OLLAMA_HOST: the sidecar's Ollama listener (`--ollama-port`).
102
+ "ollama",
101
103
  "openhands",
102
104
  "litellm",
103
105
  "aider",
@@ -106,19 +108,27 @@ export const SIDECAR_PRESETS = [
106
108
  ...SERVICE_PRESETS,
107
109
  ];
108
110
 
111
+ /**
112
+ * Coding agents configured by a file of their own rather than by a base URL and
113
+ * a model: Codex reads a profile (cli/codex.mjs). Kept apart from SIDECAR_PRESETS,
114
+ * whose members take any provider; Codex speaks only OpenAI's Responses API.
115
+ */
116
+ export const AGENT_CLI_PRESETS = ["codex"];
117
+
109
118
  /** MCP client targets. Shares the set the MCP config writer dispatches on. */
110
119
  export const MCP_PRESETS = [...MCP_INTEGRATIONS];
111
120
 
112
121
  /** Everything both commands accept. */
113
- export const INTEGRATIONS = [...SIDECAR_PRESETS, ...MCP_PRESETS];
122
+ export const INTEGRATIONS = [...SIDECAR_PRESETS, ...AGENT_CLI_PRESETS, ...MCP_PRESETS];
114
123
 
115
124
  /**
116
125
  * Integrations where `configure --write` actually writes a file. Everything else
117
- * is UI- or project-schema-specific (or, for claude-code, owned by that client's
118
- * own CLI), so `--write` is refused with the real instruction instead of being
119
- * accepted and silently doing nothing.
126
+ * is UI- or project-schema-specific, so `--write` is refused with the real
127
+ * instruction instead of being accepted and silently doing nothing. claude-code
128
+ * writes Claude Code's settings (cli/claude-code.mjs); its MCP registry stays
129
+ * owned by Claude Code's own CLI. codex writes a Codex profile (cli/codex.mjs).
120
130
  */
121
- export const WRITABLE_INTEGRATIONS = ["aider", "claude-desktop", "cursor"];
131
+ export const WRITABLE_INTEGRATIONS = ["aider", "claude-desktop", "cursor", "claude-code", "codex"];
122
132
 
123
133
  export function isIntegration(name) {
124
134
  return INTEGRATIONS.includes(String(name ?? "").toLowerCase());
@@ -11,6 +11,8 @@ export const WORKSPACE_EXPORT_PROTOCOL: ProtocolRange;
11
11
  // Signed spend statements. Its own version line, and part of CLIENT_PROTOCOLS
12
12
  // since the format was published — see the note in protocols.mjs.
13
13
  export const STATEMENT_PROTOCOL: ProtocolRange;
14
+ // Session seals. Its own line; in CLIENT_PROTOCOLS since the seal route shipped.
15
+ export const SESSION_PROTOCOL: ProtocolRange;
14
16
  export const CLIENT_PROTOCOLS: Readonly<Record<string, ProtocolRange>>;
15
17
  export function compareProtocolRanges(client: ProtocolRange, server: unknown): "compatible" | "partial" | "update-required" | "unavailable";
16
18
  export function compareProtocolSets(serverProtocols: unknown): {
package/cli/protocols.mjs CHANGED
@@ -29,6 +29,19 @@ export const WORKSPACE_EXPORT_PROTOCOL = { minimum: 1, maximum: 1 };
29
29
  */
30
30
  export const STATEMENT_PROTOCOL = { minimum: 1, maximum: 1 };
31
31
 
32
+ /**
33
+ * Session seals (`passcontrol-session+jws`): one signed commitment over every
34
+ * receipt in one working session. Its own version line for the statement's
35
+ * reason: a seal carries `v`, and gating it on another artifact's maximum would
36
+ * let a newer seal through a verifier that only understands v1.
37
+ *
38
+ * In CLIENT_PROTOCOLS since the seal route (/api/control/v1/sessions/{id}/seal)
39
+ * shipped with it. KNOWN CONSEQUENCE, the statement's: this CLI reports a gateway
40
+ * that predates seals as "unavailable", which is true — `verify session` has
41
+ * nothing to verify there — and the release note must say so.
42
+ */
43
+ export const SESSION_PROTOCOL = { minimum: 1, maximum: 1 };
44
+
32
45
  export const CLIENT_PROTOCOLS = Object.freeze({
33
46
  control_api: CONTROL_API_PROTOCOL,
34
47
  gateway_api: GATEWAY_API_PROTOCOL,
@@ -36,6 +49,7 @@ export const CLIENT_PROTOCOLS = Object.freeze({
36
49
  agent_token: AGENT_TOKEN_PROTOCOL,
37
50
  workspace_export: WORKSPACE_EXPORT_PROTOCOL,
38
51
  statement: STATEMENT_PROTOCOL,
52
+ session: SESSION_PROTOCOL,
39
53
  });
40
54
 
41
55
  const validRange = (value) =>
@@ -43,6 +43,7 @@ export const PROVIDER_UPSTREAMS = {
43
43
  // permanently ineligible for `--allow-connect`.
44
44
  gemini: { hostname: "generativelanguage.googleapis.com", basePath: "/v1beta/openai" },
45
45
  xai: { hostname: "api.x.ai", basePath: "" },
46
+ openrouter: { hostname: "openrouter.ai", basePath: "/api" },
46
47
  };
47
48
 
48
49
  /**