passcontrol 1.3.0 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/passcontrol.mjs +264 -6
- package/cli/budget-format.mjs +76 -0
- package/cli/claude-code.mjs +80 -16
- package/cli/config.mjs +1 -1
- package/cli/declared-session.mjs +33 -0
- package/cli/journal.mjs +84 -0
- package/cli/mcp/README.md +4 -1
- package/cli/mcp/gateway.mjs +13 -0
- package/cli/mcp/server.mjs +27 -0
- package/cli/menu.mjs +3 -0
- package/cli/protocols.d.mts +2 -0
- package/cli/protocols.mjs +14 -0
- package/cli/sidecar.mjs +42 -5
- package/cli/statusline.mjs +89 -0
- package/cli/verify.mjs +215 -5
- package/package.json +1 -1
- package/sdk/verify.d.ts +108 -0
- package/sdk/verify.js +219 -1
package/cli/journal.mjs
ADDED
|
@@ -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 `
|
|
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.
|
package/cli/mcp/gateway.mjs
CHANGED
|
@@ -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
|
}
|
package/cli/mcp/server.mjs
CHANGED
|
@@ -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/protocols.d.mts
CHANGED
|
@@ -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) =>
|
package/cli/sidecar.mjs
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
1
2
|
import http from "node:http";
|
|
2
3
|
import net from "node:net";
|
|
3
4
|
import { Readable } from "node:stream";
|
|
4
5
|
import { bareGatewayOrigin, fail, ok, step, warn } from "./config.mjs";
|
|
5
6
|
import { classifyConnect, classifyProxyRequest, isLoopbackBindHost } from "./proxy-policy.mjs";
|
|
6
7
|
import { createVisaClient } from "./visa-client.mjs";
|
|
8
|
+
import { declaredSession } from "./declared-session.mjs";
|
|
9
|
+
import { defaultJournalDir, openJournal } from "./journal.mjs";
|
|
7
10
|
|
|
8
11
|
// Hop-by-hop headers plus the ones the sidecar rebuilds itself. `proxy-connection`
|
|
9
12
|
// and friends only appear once something is used as a FORWARD proxy, which is
|
|
@@ -107,6 +110,11 @@ export function createSidecar({
|
|
|
107
110
|
refreshSkewSeconds = 30,
|
|
108
111
|
allowConnectHosts = [],
|
|
109
112
|
onRefusal = (verdict) => warn(`${verdict.code}: ${verdict.message} → ${verdict.help}`),
|
|
113
|
+
// This run's id: stamped on every forwarded request as `x-passcontrol-run`, the
|
|
114
|
+
// fallback session for a client that declares none (lib/client-lineage.ts).
|
|
115
|
+
runId = randomUUID(),
|
|
116
|
+
// cli/journal.mjs, or null for `--no-journal`.
|
|
117
|
+
journal = null,
|
|
110
118
|
}) {
|
|
111
119
|
// The upstream URL below is built from this, not from the argument: the
|
|
112
120
|
// sidecar forwards a bearer visa on every proxied request, so its destination
|
|
@@ -143,6 +151,8 @@ export function createSidecar({
|
|
|
143
151
|
if (!isStripped(k) && typeof v === "string") headers[k] = v;
|
|
144
152
|
}
|
|
145
153
|
headers["authorization"] = `Bearer ${visa}`;
|
|
154
|
+
// Set after the copy, so a client cannot name the run: only the sidecar can.
|
|
155
|
+
headers["x-passcontrol-run"] = runId;
|
|
146
156
|
headers["x-passcontrol-proof"] = visas.createProof(visa, req.method, new URL(path, origin));
|
|
147
157
|
headers["accept-encoding"] = "identity";
|
|
148
158
|
return fetch(`${origin}${path}`, { method: req.method, headers, body: body ?? undefined });
|
|
@@ -155,7 +165,19 @@ export function createSidecar({
|
|
|
155
165
|
// URL — codeload for an archive download — passes through untouched.
|
|
156
166
|
const toLocal = (value) => value.split(`${origin}/api/v1/`).join(`${localBaseUrl()}/api/v1/`);
|
|
157
167
|
|
|
158
|
-
function writeResponse(res, upstream) {
|
|
168
|
+
function writeResponse(res, upstream, reqHeaders) {
|
|
169
|
+
// At the headers, not at the end of the body: a streamed call whose client
|
|
170
|
+
// disconnects mid-stream still produced a receipt, and the user's record of
|
|
171
|
+
// it must not depend on how long they kept reading. With the session the call
|
|
172
|
+
// declared, read as the gateway reads it, so a seal is checked against its own.
|
|
173
|
+
journal?.record(
|
|
174
|
+
upstream.headers.get("x-passcontrol-receipt-id"),
|
|
175
|
+
upstream.status,
|
|
176
|
+
declaredSession((name) => {
|
|
177
|
+
const v = reqHeaders?.[name];
|
|
178
|
+
return Array.isArray(v) ? v[0] : v;
|
|
179
|
+
}, runId)
|
|
180
|
+
);
|
|
159
181
|
const outHeaders = {};
|
|
160
182
|
upstream.headers.forEach((v, k) => {
|
|
161
183
|
const name = k.toLowerCase();
|
|
@@ -181,7 +203,7 @@ export function createSidecar({
|
|
|
181
203
|
try {
|
|
182
204
|
const body = await readBody(req);
|
|
183
205
|
const upstream = await visas.fetchWithVisa((visa) => fetchUpstream(req, verdict.path, body, visa));
|
|
184
|
-
writeResponse(res, upstream);
|
|
206
|
+
writeResponse(res, upstream, req.headers);
|
|
185
207
|
} catch (e) {
|
|
186
208
|
if (!res.headersSent) {
|
|
187
209
|
res.writeHead(502, { "content-type": "application/json" });
|
|
@@ -227,7 +249,7 @@ export function createSidecar({
|
|
|
227
249
|
await upstream.body?.cancel().catch(() => {});
|
|
228
250
|
return;
|
|
229
251
|
}
|
|
230
|
-
writeResponse(res, upstream);
|
|
252
|
+
writeResponse(res, upstream, req.headers);
|
|
231
253
|
} catch (e) {
|
|
232
254
|
if (!res.headersSent) {
|
|
233
255
|
res.writeHead(502, { "content-type": "application/json" });
|
|
@@ -280,7 +302,7 @@ export function createSidecar({
|
|
|
280
302
|
clientSocket.on("close", () => upstream.destroy());
|
|
281
303
|
});
|
|
282
304
|
|
|
283
|
-
return { server, ollamaServer, getVisa: visas.getVisa };
|
|
305
|
+
return { server, ollamaServer, getVisa: visas.getVisa, runId };
|
|
284
306
|
}
|
|
285
307
|
|
|
286
308
|
/**
|
|
@@ -303,7 +325,17 @@ export function assertBindHost(host, allowNonLoopback = false) {
|
|
|
303
325
|
export function startSidecar(opts) {
|
|
304
326
|
const { gateway, port = 8788, host = "127.0.0.1", allowNonLoopback = false, allowConnectHosts = [], ollamaPort = null } = opts;
|
|
305
327
|
assertBindHost(host, allowNonLoopback);
|
|
306
|
-
const
|
|
328
|
+
const runId = randomUUID();
|
|
329
|
+
// On unless the operator said --no-journal (D3). See cli/journal.mjs.
|
|
330
|
+
const journal = opts.noJournal
|
|
331
|
+
? null
|
|
332
|
+
: openJournal({
|
|
333
|
+
dir: opts.journalDir ?? defaultJournalDir(),
|
|
334
|
+
runId,
|
|
335
|
+
onError: (e) =>
|
|
336
|
+
warn(`journal: could not write ${journal.path} (${e.message}). Calls are unaffected; this run is no longer being recorded.`),
|
|
337
|
+
});
|
|
338
|
+
const { server, ollamaServer, getVisa } = createSidecar({ ...opts, runId, journal });
|
|
307
339
|
if (ollamaPort != null) {
|
|
308
340
|
ollamaServer.listen(ollamaPort, host, () => {
|
|
309
341
|
step(`Ollama API (local models) on http://${host}:${ollamaPort}: set OLLAMA_HOST=${host}:${ollamaPort}`);
|
|
@@ -314,6 +346,11 @@ export function startSidecar(opts) {
|
|
|
314
346
|
step(`Listening on http://${host}:${port}`);
|
|
315
347
|
step(`Point your agent at: http://${host}:${port}/api/v1/anthropic (or /api/v1/openai)`);
|
|
316
348
|
step("API key = anything (ignored). Visa is minted + refreshed automatically.");
|
|
349
|
+
step(
|
|
350
|
+
journal
|
|
351
|
+
? `Journal: ${journal.path} (receipt ids, times, statuses and declared sessions only; --no-journal turns it off)`
|
|
352
|
+
: "Journal: off (--no-journal). Session seals cannot be checked against this run."
|
|
353
|
+
);
|
|
317
354
|
// Said at startup rather than only in a refusal, because the whole point of
|
|
318
355
|
// HTTPS_PROXY is that nobody reads the docs first.
|
|
319
356
|
step("HTTPS_PROXY: CONNECT to a provider is refused, not tunnelled — PassControl cannot");
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
// `passcontrol statusline`: the agent's budget as one line in Claude Code's status
|
|
2
|
+
// line (1.4.0 candidate 2).
|
|
3
|
+
//
|
|
4
|
+
// Claude Code runs the command after every assistant message, debounced 300ms, and
|
|
5
|
+
// cancels a run still going when the next one starts (code.claude.com/docs/en/statusline,
|
|
6
|
+
// read 2026-10-08). So:
|
|
7
|
+
// * a good answer is cached for TTL_MS and reused, so a busy session asks the
|
|
8
|
+
// gateway a few times a minute rather than every message;
|
|
9
|
+
// * it asks through the running sidecar, which already holds a warm visa: minting
|
|
10
|
+
// a visa per run would spend the passport's challenge allowance (20 a window),
|
|
11
|
+
// the same allowance the sidecar refreshes from;
|
|
12
|
+
// * it never throws. Every outcome is one line, and the caller exits 0.
|
|
13
|
+
// Only a good answer is cached. A failure is shown as the failure, never as an
|
|
14
|
+
// older budget that might read as current.
|
|
15
|
+
import fs from "node:fs";
|
|
16
|
+
import path from "node:path";
|
|
17
|
+
import { statusLine } from "./budget-format.mjs";
|
|
18
|
+
|
|
19
|
+
export const STATUSLINE_TTL_MS = 20_000;
|
|
20
|
+
const TIMEOUT_MS = 1_500;
|
|
21
|
+
|
|
22
|
+
function readCache(file, nowMs, ttlMs) {
|
|
23
|
+
try {
|
|
24
|
+
const cached = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
25
|
+
if (typeof cached?.line === "string" && typeof cached.at === "number" && nowMs - cached.at >= 0 && nowMs - cached.at < ttlMs) {
|
|
26
|
+
return cached.line;
|
|
27
|
+
}
|
|
28
|
+
} catch {
|
|
29
|
+
// No cache, or an unreadable one: ask.
|
|
30
|
+
}
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function writeCache(file, nowMs, line) {
|
|
35
|
+
try {
|
|
36
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
37
|
+
fs.writeFileSync(file, JSON.stringify({ at: nowMs, line }), { mode: 0o600 });
|
|
38
|
+
fs.chmodSync(file, 0o600);
|
|
39
|
+
} catch {
|
|
40
|
+
// A cache that cannot be written only costs the next run a request.
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The line to print. Never throws. */
|
|
45
|
+
export async function statuslineText({
|
|
46
|
+
port,
|
|
47
|
+
host = "127.0.0.1",
|
|
48
|
+
cacheFile,
|
|
49
|
+
now = () => Date.now(),
|
|
50
|
+
fetch: fetchImpl = globalThis.fetch,
|
|
51
|
+
timeoutMs = TIMEOUT_MS,
|
|
52
|
+
ttlMs = STATUSLINE_TTL_MS,
|
|
53
|
+
}) {
|
|
54
|
+
const cached = readCache(cacheFile, now(), ttlMs);
|
|
55
|
+
if (cached) return cached;
|
|
56
|
+
|
|
57
|
+
const controller = new AbortController();
|
|
58
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
59
|
+
try {
|
|
60
|
+
let response;
|
|
61
|
+
try {
|
|
62
|
+
response = await fetchImpl(`http://${host}:${port}/api/v1/self`, {
|
|
63
|
+
headers: { accept: "application/json" },
|
|
64
|
+
signal: controller.signal,
|
|
65
|
+
});
|
|
66
|
+
} catch {
|
|
67
|
+
return controller.signal.aborted
|
|
68
|
+
? "PassControl · no answer from the sidecar"
|
|
69
|
+
: `PassControl · sidecar not running on port ${port}`;
|
|
70
|
+
}
|
|
71
|
+
// The gateway's opaque refusal covers both a suspended agent and a kill switch.
|
|
72
|
+
if (response.status === 403) return "PassControl · agent stopped";
|
|
73
|
+
if (!response.ok) return `PassControl · unavailable (HTTP ${response.status})`;
|
|
74
|
+
let self;
|
|
75
|
+
try {
|
|
76
|
+
self = await response.json();
|
|
77
|
+
} catch {
|
|
78
|
+
return controller.signal.aborted ? "PassControl · no answer from the sidecar" : "PassControl · unreadable answer";
|
|
79
|
+
}
|
|
80
|
+
if (typeof self?.budget !== "object" || self.budget === null) return "PassControl · unreadable answer";
|
|
81
|
+
const line = statusLine(self);
|
|
82
|
+
writeCache(cacheFile, now(), line);
|
|
83
|
+
return line;
|
|
84
|
+
} catch {
|
|
85
|
+
return "PassControl · unavailable";
|
|
86
|
+
} finally {
|
|
87
|
+
clearTimeout(timer);
|
|
88
|
+
}
|
|
89
|
+
}
|