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
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
// Subscription mode for Codex (1.6.0, L5).
|
|
2
|
+
//
|
|
3
|
+
// A Codex session signed in with a ChatGPT plan talks to OpenAI directly, so the
|
|
4
|
+
// gateway cannot refuse its calls, as with a Claude Pro/Max login
|
|
5
|
+
// (cli/subscription-gate.mjs). The stops and tool rules still reach it through
|
|
6
|
+
// Codex's hooks: `passcontrol configure codex --subscription` adds two to
|
|
7
|
+
// `$CODEX_HOME/hooks.json`, each running `passcontrol codex-hook`, which hands
|
|
8
|
+
// Codex's input to the sidecar's hook endpoint (the one Claude Code calls) and
|
|
9
|
+
// answers in Codex's terms:
|
|
10
|
+
//
|
|
11
|
+
// UserPromptSubmit a stopped agent's prompt is blocked and the turn ends
|
|
12
|
+
// PreToolUse a stopped agent's tools, and the tool rules' denials, are refused
|
|
13
|
+
//
|
|
14
|
+
// Codex has command hooks only (no http hook), hence the relay. Three differences
|
|
15
|
+
// from Claude Code are handled here, not in the sidecar:
|
|
16
|
+
// * hooks.json is SHARED (Peras writes into it), unlike the profile file
|
|
17
|
+
// cli/codex.mjs writes. Only entries whose command is PassControl's are added,
|
|
18
|
+
// replaced or removed (Peras's `ours()` rule), and the file is backed up the first
|
|
19
|
+
// time PassControl writes into one it did not create;
|
|
20
|
+
// * on PreToolUse, Codex takes `continue`, `stopReason`, `suppressOutput` and
|
|
21
|
+
// `permissionDecision: "ask"` as a FAILED hook and runs the tool. The sidecar's
|
|
22
|
+
// answers carry `continue: false` with every stop, so Codex's answer is rebuilt
|
|
23
|
+
// from an allow-list, and an "ask" rule becomes a refusal that says why;
|
|
24
|
+
// * Codex runs a hook only once the user has trusted it in `/hooks`, by its hash.
|
|
25
|
+
// The command is the same string on every run of configure, so a trusted hook
|
|
26
|
+
// stays trusted;
|
|
27
|
+
// * the command names node and the CLI by absolute path, like Peras's. A bare
|
|
28
|
+
// `passcontrol` failed both ways on the owner's Mac: "command not found" under a
|
|
29
|
+
// GUI app's minimal PATH, and "Unknown command" from an older CLI on PATH. Either
|
|
30
|
+
// is a failed hook, so configure runs the exact command once under a bare PATH
|
|
31
|
+
// before saying it is set up.
|
|
32
|
+
//
|
|
33
|
+
// Honest limits, said in the CLI too: Codex has no strict hook mode, so a hook that
|
|
34
|
+
// fails or is not trusted lets the action go ahead; the tool rules' path rules (Read,
|
|
35
|
+
// Write, Edit) and domain rules (WebFetch) name Claude Code's tools, which Codex does
|
|
36
|
+
// not have, so only command rules (Bash) and MCP tool rules can match; and a session
|
|
37
|
+
// cannot be stopped on its own, since its calls never pass the gateway.
|
|
38
|
+
import { spawnSync } from "node:child_process";
|
|
39
|
+
import fs from "node:fs";
|
|
40
|
+
import os from "node:os";
|
|
41
|
+
import path from "node:path";
|
|
42
|
+
|
|
43
|
+
import { GATE_HOOK_TIMEOUT_S, HOOK_PATH } from "./subscription-gate.mjs";
|
|
44
|
+
|
|
45
|
+
/** Codex's timeout for the tool hook: an "ask the owner" rule holds it while the owner answers. */
|
|
46
|
+
export const CODEX_TOOL_HOOK_TIMEOUT_S = 600;
|
|
47
|
+
const PROMPT_RELAY_MS = GATE_HOOK_TIMEOUT_S * 1000 - 500;
|
|
48
|
+
const TOOL_RELAY_MS = (CODEX_TOOL_HOOK_TIMEOUT_S - 10) * 1000;
|
|
49
|
+
const EVENTS = ["UserPromptSubmit", "PreToolUse"];
|
|
50
|
+
const BACKUP_SUFFIX = ".passcontrol-backup";
|
|
51
|
+
|
|
52
|
+
const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
53
|
+
const text = (v) => (typeof v === "string" && v.length > 0 ? v : null);
|
|
54
|
+
|
|
55
|
+
export function codexHooksPath({ env = process.env } = {}) {
|
|
56
|
+
return path.join(env.CODEX_HOME || path.join(env.HOME || os.homedir(), ".codex"), "hooks.json");
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** PassControl's own entry: `passcontrol codex-hook …`, or `node ".../passcontrol.mjs" codex-hook …`. */
|
|
60
|
+
export function isPassControlCodexHook(hook) {
|
|
61
|
+
return isObject(hook) && hook.type === "command" && typeof hook.command === "string" && /(^|[\s"/])passcontrol(\.mjs)?"?\s+codex-hook(\s|$)/u.test(hook.command);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* The command both hooks run: node and the CLI by absolute path, so PATH never
|
|
66
|
+
* decides whether it runs. Refuses a path a shell would read differently.
|
|
67
|
+
*/
|
|
68
|
+
export function codexHookCommand({ port, node = process.execPath, entry }) {
|
|
69
|
+
for (const p of [node, entry]) {
|
|
70
|
+
if (typeof p !== "string" || !p || /["$`]/u.test(p)) {
|
|
71
|
+
throw new Error(`The path ${JSON.stringify(String(p))} cannot be quoted safely for Codex's hook command.`);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return `"${node}" "${entry}" codex-hook --port ${port}`;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Runs the exact command as Codex would, under a bare PATH, with an input it answers
|
|
79
|
+
* with nothing. Not on Windows, where Codex runs hooks through its own shell.
|
|
80
|
+
*/
|
|
81
|
+
export function probeCodexHookCommand(command) {
|
|
82
|
+
if (process.platform === "win32") return { ok: true };
|
|
83
|
+
const run = spawnSync("/bin/sh", ["-c", command], {
|
|
84
|
+
input: JSON.stringify({ hook_event_name: "SessionStart" }),
|
|
85
|
+
env: { PATH: "/usr/bin:/bin", HOME: os.homedir(), PASSCONTROL_NO_UPDATE_CHECK: "1" },
|
|
86
|
+
encoding: "utf8",
|
|
87
|
+
timeout: 15_000,
|
|
88
|
+
});
|
|
89
|
+
if (run.status !== 0) return { ok: false, why: `it ended with exit ${run.status ?? "none"}${run.stderr ? `: ${run.stderr.trim().slice(0, 200)}` : ""}` };
|
|
90
|
+
if (run.stdout.trim()) return { ok: false, why: `it printed output it should not: ${run.stdout.trim().slice(0, 200)}` };
|
|
91
|
+
return { ok: true };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** The two entries PassControl adds, as a hooks file of their own. */
|
|
95
|
+
export function codexHookEntries(command) {
|
|
96
|
+
return {
|
|
97
|
+
hooks: {
|
|
98
|
+
UserPromptSubmit: [{ hooks: [{ type: "command", command, timeout: GATE_HOOK_TIMEOUT_S }] }],
|
|
99
|
+
PreToolUse: [{ matcher: ".*", hooks: [{ type: "command", command, timeout: CODEX_TOOL_HOOK_TIMEOUT_S }] }],
|
|
100
|
+
},
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function readHooksFile(target) {
|
|
105
|
+
if (!fs.existsSync(target)) return { value: {}, exists: false };
|
|
106
|
+
let value;
|
|
107
|
+
try {
|
|
108
|
+
value = JSON.parse(fs.readFileSync(target, "utf8"));
|
|
109
|
+
} catch {
|
|
110
|
+
value = null;
|
|
111
|
+
}
|
|
112
|
+
if (!isObject(value) || (value.hooks !== undefined && !isObject(value.hooks))) {
|
|
113
|
+
throw new Error(`${target} is not a hooks object; nothing was written.`);
|
|
114
|
+
}
|
|
115
|
+
return { value, exists: true };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Each event's groups with PassControl's hooks taken out; a group left empty goes. */
|
|
119
|
+
function withoutOurs(hooks) {
|
|
120
|
+
const next = { ...hooks };
|
|
121
|
+
for (const event of Object.keys(next)) {
|
|
122
|
+
if (!Array.isArray(next[event])) continue;
|
|
123
|
+
next[event] = next[event].flatMap((group) => {
|
|
124
|
+
if (!isObject(group) || !Array.isArray(group.hooks)) return [group];
|
|
125
|
+
const rest = group.hooks.filter((h) => !isPassControlCodexHook(h));
|
|
126
|
+
if (rest.length === group.hooks.length) return [group];
|
|
127
|
+
return rest.length ? [{ ...group, hooks: rest }] : [];
|
|
128
|
+
});
|
|
129
|
+
if (next[event].length === 0) delete next[event];
|
|
130
|
+
}
|
|
131
|
+
return next;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const hasOurs = (hooks) =>
|
|
135
|
+
Object.values(hooks ?? {}).some((groups) => Array.isArray(groups) && groups.some((g) => isObject(g) && Array.isArray(g.hooks) && g.hooks.some(isPassControlCodexHook)));
|
|
136
|
+
|
|
137
|
+
function save(target, value) {
|
|
138
|
+
fs.mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
|
|
139
|
+
const temp = `${target}.${process.pid}.tmp`;
|
|
140
|
+
fs.writeFileSync(temp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
|
|
141
|
+
fs.renameSync(temp, target);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Add PassControl's two hooks, replacing any earlier ones of its own and nobody else's. */
|
|
145
|
+
export function writeCodexHooks({ target, command }) {
|
|
146
|
+
const { value, exists } = readHooksFile(target);
|
|
147
|
+
const hooks = withoutOurs(value.hooks ?? {});
|
|
148
|
+
for (const [event, groups] of Object.entries(codexHookEntries(command).hooks)) {
|
|
149
|
+
hooks[event] = [...(Array.isArray(hooks[event]) ? hooks[event] : []), ...groups];
|
|
150
|
+
}
|
|
151
|
+
const next = { ...value, hooks };
|
|
152
|
+
if (JSON.stringify(next) === JSON.stringify(value)) return { changed: false, backupPath: null };
|
|
153
|
+
let backupPath = null;
|
|
154
|
+
if (exists && !hasOurs(value.hooks)) {
|
|
155
|
+
backupPath = `${target}${BACKUP_SUFFIX}`;
|
|
156
|
+
fs.copyFileSync(target, backupPath);
|
|
157
|
+
fs.chmodSync(backupPath, 0o600);
|
|
158
|
+
}
|
|
159
|
+
save(target, next);
|
|
160
|
+
return { changed: true, backupPath };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Take PassControl's hooks back out; everything else stays as it was. */
|
|
164
|
+
export function removeCodexHooks({ target }) {
|
|
165
|
+
if (!fs.existsSync(target)) return { changed: false };
|
|
166
|
+
const { value } = readHooksFile(target);
|
|
167
|
+
if (!hasOurs(value.hooks)) return { changed: false };
|
|
168
|
+
const hooks = withoutOurs(value.hooks);
|
|
169
|
+
const { hooks: _old, ...rest } = value;
|
|
170
|
+
save(target, Object.keys(hooks).length ? { ...rest, hooks } : rest);
|
|
171
|
+
return { changed: true };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const ASK_IN_CODEX =
|
|
175
|
+
" Codex cannot ask here, so PassControl refuses it: the user can run it themselves, or the agent's owner can change the rule on the agent's page.";
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* The sidecar's answer (Claude Code's hook output) as Codex must get it, built from
|
|
179
|
+
* an allow-list: on PreToolUse, a field Codex does not support there fails the hook,
|
|
180
|
+
* and a failed hook lets the tool run.
|
|
181
|
+
*/
|
|
182
|
+
export function codexHookAnswer(event, out) {
|
|
183
|
+
const o = isObject(out) ? out : {};
|
|
184
|
+
const systemMessage = text(o.systemMessage);
|
|
185
|
+
const warning = systemMessage ? { systemMessage } : {};
|
|
186
|
+
if (event === "PreToolUse") {
|
|
187
|
+
const hso = isObject(o.hookSpecificOutput) ? o.hookSpecificOutput : {};
|
|
188
|
+
const stopped = o.continue === false || o.decision === "block";
|
|
189
|
+
const said = text(hso.permissionDecisionReason) ?? text(o.stopReason) ?? text(o.reason);
|
|
190
|
+
let reason = null;
|
|
191
|
+
if (hso.permissionDecision === "deny" || stopped) reason = said ?? "PassControl refused this tool call.";
|
|
192
|
+
else if (hso.permissionDecision === "ask") reason = `${said ?? "PassControl: the agent's tool rules ask the user to confirm this."}${ASK_IN_CODEX}`;
|
|
193
|
+
if (reason === null) return warning;
|
|
194
|
+
return { hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: reason }, ...warning };
|
|
195
|
+
}
|
|
196
|
+
if (event === "UserPromptSubmit") {
|
|
197
|
+
const answer = {};
|
|
198
|
+
if (o.continue === false) answer.continue = false;
|
|
199
|
+
if (text(o.stopReason)) answer.stopReason = o.stopReason;
|
|
200
|
+
if (o.decision === "block") answer.decision = "block";
|
|
201
|
+
if (text(o.reason)) answer.reason = o.reason;
|
|
202
|
+
const context = isObject(o.hookSpecificOutput) ? text(o.hookSpecificOutput.additionalContext) : null;
|
|
203
|
+
if (context) answer.hookSpecificOutput = { hookEventName: "UserPromptSubmit", additionalContext: context };
|
|
204
|
+
return { ...answer, ...warning };
|
|
205
|
+
}
|
|
206
|
+
return {};
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* What `passcontrol codex-hook` prints for one hook run: Codex's input in, the
|
|
211
|
+
* sidecar's answer out, or nothing. Never throws, and never blocks on its own
|
|
212
|
+
* failure: a sidecar that is down or slow lets the action go ahead, with a warning.
|
|
213
|
+
*/
|
|
214
|
+
export async function runCodexHook({ input, port, fetchImpl = fetch, promptTimeoutMs = PROMPT_RELAY_MS, toolTimeoutMs = TOOL_RELAY_MS }) {
|
|
215
|
+
let parsed;
|
|
216
|
+
try {
|
|
217
|
+
parsed = JSON.parse(input);
|
|
218
|
+
} catch {
|
|
219
|
+
return "";
|
|
220
|
+
}
|
|
221
|
+
const event = isObject(parsed) ? parsed.hook_event_name : null;
|
|
222
|
+
if (!EVENTS.includes(event)) return "";
|
|
223
|
+
const tool = event === "PreToolUse";
|
|
224
|
+
const controller = new AbortController();
|
|
225
|
+
const timer = setTimeout(() => controller.abort(), tool ? toolTimeoutMs : promptTimeoutMs);
|
|
226
|
+
const warn = (why) => JSON.stringify({ systemMessage: `PassControl: ${why}, so this goes ahead unchecked.` });
|
|
227
|
+
try {
|
|
228
|
+
const url = `http://127.0.0.1:${port}${HOOK_PATH}${tool ? `?t=${CODEX_TOOL_HOOK_TIMEOUT_S}` : ""}`;
|
|
229
|
+
const response = await fetchImpl(url, {
|
|
230
|
+
method: "POST",
|
|
231
|
+
headers: { "content-type": "application/json" },
|
|
232
|
+
body: input,
|
|
233
|
+
signal: controller.signal,
|
|
234
|
+
});
|
|
235
|
+
if (!response.ok) return warn(`the sidecar on port ${port} refused the hook (HTTP ${response.status})`);
|
|
236
|
+
const out = await response.json().catch(() => null);
|
|
237
|
+
if (!isObject(out)) return warn(`the sidecar on port ${port} gave an answer that cannot be read`);
|
|
238
|
+
const answer = codexHookAnswer(event, out);
|
|
239
|
+
return Object.keys(answer).length ? JSON.stringify(answer) : "";
|
|
240
|
+
} catch {
|
|
241
|
+
if (controller.signal.aborted) return warn(`the sidecar on port ${port} did not answer in time`);
|
|
242
|
+
return warn(`no sidecar answered on port ${port} (start it: passcontrol sidecar --port ${port})`);
|
|
243
|
+
} finally {
|
|
244
|
+
clearTimeout(timer);
|
|
245
|
+
}
|
|
246
|
+
}
|
package/cli/config.mjs
CHANGED
|
@@ -677,6 +677,9 @@ export function formatProxyError(status, body) {
|
|
|
677
677
|
if (status === 402 && error === "blocked_budget_period") {
|
|
678
678
|
return `${blocked}\n→ The agent's daily or monthly limit is spent; it resets at the next UTC day or month (see the retry-after header).\n→ Fix: wait for the reset, or raise the limit in the dashboard.`;
|
|
679
679
|
}
|
|
680
|
+
if (status === 402 && error === "blocked_budget_pause") {
|
|
681
|
+
return `${blocked}\n→ The agent reached the pause line its owner set on its spending limit; the limit itself is not used up.\n→ Fix: let it go on for an hour from the agent's page in the dashboard, or raise the pause line.`;
|
|
682
|
+
}
|
|
680
683
|
if (status === 402 && error === "blocked_budget_delegation") {
|
|
681
684
|
return `${blocked}\n→ This worker's delegation (or one above it) used its spending cap.\n→ Fix: ask the agent that delegated to it for a new delegation with a larger cap.`;
|
|
682
685
|
}
|
package/cli/login.mjs
CHANGED
|
@@ -281,7 +281,14 @@ async function control(origin, apiKey, method, path, body, fetchImpl = fetch) {
|
|
|
281
281
|
});
|
|
282
282
|
const parsed = await res.json().catch(() => null);
|
|
283
283
|
if (!res.ok) {
|
|
284
|
-
|
|
284
|
+
// The control API answers { error: { code, message } }, and the message is
|
|
285
|
+
// what tells someone at a limit whether to revoke an agent or wait. Printed
|
|
286
|
+
// on one line and clipped, because it is the gateway's text, not ours.
|
|
287
|
+
const code = typeof parsed?.error?.code === "string" ? parsed.error.code.replace(/[^a-z0-9_]/gu, "").slice(0, 64) : "";
|
|
288
|
+
const message = typeof parsed?.error?.message === "string" ? parsed.error.message.replace(/\s+/gu, " ").trim().slice(0, 240) : "";
|
|
289
|
+
throw new Error(
|
|
290
|
+
`Control plane refused ${method} ${path} (${res.status}${code ? ` ${code}` : ""})${message ? `: ${message}` : "."}`
|
|
291
|
+
);
|
|
285
292
|
}
|
|
286
293
|
// Every control route answers `{ data: ... }` (lib/control/respond.ts), and
|
|
287
294
|
// bin/passcontrol.mjs's own `api()` has always unwrapped it. This helper did
|
|
@@ -549,7 +556,15 @@ export async function loginCommand(opts = {}, deps = {}) {
|
|
|
549
556
|
warnIfShadowed(target);
|
|
550
557
|
|
|
551
558
|
step("");
|
|
559
|
+
// An agent this command created has the demo scope (above). A reused one has
|
|
560
|
+
// whatever its owner gave it; when its listed scopes leave out `demo`, the
|
|
561
|
+
// demo call would be refused and recorded, so the proof stops at the visa.
|
|
562
|
+
// Not in the list (or no scopes field) means unknown, and the call is tried.
|
|
563
|
+
const reused = Array.isArray(agents) ? agents.find((agent) => agent?.id === agentId) : undefined;
|
|
564
|
+
const demoCall = !(reused && Array.isArray(reused.allowed_scopes))
|
|
565
|
+
|| reused.allowed_scopes.some((scope) => scope?.provider === "demo");
|
|
552
566
|
const proof = await proveItWorks({
|
|
567
|
+
demoCall,
|
|
553
568
|
origin,
|
|
554
569
|
passportId,
|
|
555
570
|
passportSecret,
|
package/cli/mcp/README.md
CHANGED
|
@@ -66,7 +66,8 @@ config contains a passport secret or provider key.
|
|
|
66
66
|
therefore refuses it; use off/observe for this client. `list_models` reads model patterns
|
|
67
67
|
from the visa scope, not a live upstream model catalog; a wildcard is not a callable model.
|
|
68
68
|
`budget` reads the agent's own limits from the gateway (`GET /api/v1/self`): what is used,
|
|
69
|
-
what is left,
|
|
69
|
+
what is left, when a daily or monthly limit resets, and when the first limit runs out at the
|
|
70
|
+
current rate. It spends nothing and writes no log
|
|
70
71
|
row; like `chat`, it sends a bearer visa, so required sender-proof mode refuses it.
|
|
71
72
|
Providers: OpenAI, Anthropic, Groq, Mistral, Together, DeepSeek, and Gemini (OpenAI-compatible).
|
|
72
73
|
The global profile can use the CLI OS credential store (`passcontrol key status`) rather
|
package/cli/menu.mjs
CHANGED
|
@@ -268,6 +268,7 @@ export const HIDDEN = {
|
|
|
268
268
|
try: "kept as an explanatory compatibility error, but no longer performs an operation",
|
|
269
269
|
seal: "needs a session and an agent, both named by `sessions`, which is listed under Money",
|
|
270
270
|
statusline: "Claude Code runs it, not a person; `configure claude-code --statusline` installs it",
|
|
271
|
+
"codex-hook": "Codex runs it, not a person; `configure codex --subscription` installs it",
|
|
271
272
|
};
|
|
272
273
|
|
|
273
274
|
/** Every top-level command name the menu can reach, flattened. */
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// Subscription mode's eyes (Phase 1): Claude Code's own
|
|
2
|
+
// OpenTelemetry log export, received on the sidecar's loopback listener.
|
|
3
|
+
//
|
|
4
|
+
// A Pro/Max session talks to Anthropic directly, so no call passes the sidecar. Claude
|
|
5
|
+
// Code reports each one itself when `CLAUDE_CODE_ENABLE_TELEMETRY=1` and its log
|
|
6
|
+
// exporter points here (OTLP http/json): `claude_code.api_request` with the model,
|
|
7
|
+
// tokens, API-equivalent cost and duration, and `claude_code.api_error` with the
|
|
8
|
+
// status. Prompts and tool inputs are redacted by Claude Code by default.
|
|
9
|
+
//
|
|
10
|
+
// Every record also carries the user's email, account id and organisation id. This
|
|
11
|
+
// parser copies an ALLOWLIST of fields and nothing else, so those never reach the
|
|
12
|
+
// board, a log line or a later upload. Each copied value is held to a pattern.
|
|
13
|
+
//
|
|
14
|
+
// What a reported call is NOT: a call PassControl saw. It is what the client says it
|
|
15
|
+
// did. The board shows it as SEEN, never BOARDED, and its cost as API-equivalent:
|
|
16
|
+
// a subscription pays a flat fee, and nothing here is ever charged to a budget.
|
|
17
|
+
|
|
18
|
+
export const OTLP_LOGS_PATH = "/_passcontrol/otlp/v1/logs";
|
|
19
|
+
|
|
20
|
+
const SERVICE = "claude-code";
|
|
21
|
+
const KINDS = { "claude_code.api_request": "api_request", "claude_code.api_error": "api_error" };
|
|
22
|
+
// The same patterns the watch feed holds its fields to (cli/watch-feed.mjs).
|
|
23
|
+
const DECLARED = /^[A-Za-z0-9._:-]{1,128}$/;
|
|
24
|
+
const MODEL = /^[A-Za-z0-9._:/@-]{1,100}$/;
|
|
25
|
+
|
|
26
|
+
const held = (pattern, value) => (typeof value === "string" && pattern.test(value) ? value : null);
|
|
27
|
+
|
|
28
|
+
/** An OTLP AnyValue as a JS value: string, number, or null. int64 may arrive as a string. */
|
|
29
|
+
function scalar(value) {
|
|
30
|
+
if (!value || typeof value !== "object") return null;
|
|
31
|
+
if (typeof value.stringValue === "string") return value.stringValue;
|
|
32
|
+
if (value.intValue !== undefined) {
|
|
33
|
+
const n = typeof value.intValue === "string" ? Number(value.intValue) : value.intValue;
|
|
34
|
+
return Number.isFinite(n) ? n : null;
|
|
35
|
+
}
|
|
36
|
+
if (typeof value.doubleValue === "number" && Number.isFinite(value.doubleValue)) return value.doubleValue;
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function attributeMap(attributes) {
|
|
41
|
+
const map = new Map();
|
|
42
|
+
if (!Array.isArray(attributes)) return map;
|
|
43
|
+
for (const a of attributes) {
|
|
44
|
+
if (a && typeof a.key === "string") map.set(a.key, scalar(a.value));
|
|
45
|
+
}
|
|
46
|
+
return map;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const count = (v) => (typeof v === "number" && Number.isInteger(v) && v >= 0 && v < 2 ** 53 ? v : null);
|
|
50
|
+
const status = (v) => (typeof v === "number" && Number.isInteger(v) && v >= 100 && v < 600 ? v : null);
|
|
51
|
+
|
|
52
|
+
function timeMs(record) {
|
|
53
|
+
const raw = record?.timeUnixNano ?? record?.observedTimeUnixNano;
|
|
54
|
+
const n = typeof raw === "string" ? Number(raw.slice(0, -6) || "0") : typeof raw === "number" ? Math.floor(raw / 1e6) : NaN;
|
|
55
|
+
return Number.isFinite(n) && n > 0 ? n : null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* The model calls in one OTLP ExportLogsServiceRequest (JSON). Never throws.
|
|
60
|
+
* @returns {Array<{ kind: "api_request" | "api_error", session: string | null, at: number | null, model: string | null,
|
|
61
|
+
* costMicros: number | null, inputTokens: number | null, outputTokens: number | null, cacheReadTokens: number | null,
|
|
62
|
+
* cacheCreationTokens: number | null, durationMs: number | null, status: number | null, agent: string | null }>}
|
|
63
|
+
*/
|
|
64
|
+
export function readClaudeCodeEvents(body) {
|
|
65
|
+
const events = [];
|
|
66
|
+
try {
|
|
67
|
+
if (!body || typeof body !== "object" || !Array.isArray(body.resourceLogs)) return events;
|
|
68
|
+
for (const resourceLog of body.resourceLogs) {
|
|
69
|
+
if (attributeMap(resourceLog?.resource?.attributes).get("service.name") !== SERVICE) continue;
|
|
70
|
+
for (const scopeLog of Array.isArray(resourceLog.scopeLogs) ? resourceLog.scopeLogs : []) {
|
|
71
|
+
for (const record of Array.isArray(scopeLog?.logRecords) ? scopeLog.logRecords : []) {
|
|
72
|
+
const kind = KINDS[scalar(record?.body)];
|
|
73
|
+
if (!kind) continue;
|
|
74
|
+
const a = attributeMap(record.attributes);
|
|
75
|
+
events.push({
|
|
76
|
+
kind,
|
|
77
|
+
session: held(DECLARED, a.get("session.id")),
|
|
78
|
+
at: timeMs(record),
|
|
79
|
+
model: held(MODEL, a.get("model")),
|
|
80
|
+
costMicros: kind === "api_request" ? count(a.get("cost_usd_micros")) : null,
|
|
81
|
+
inputTokens: count(a.get("input_tokens")),
|
|
82
|
+
outputTokens: count(a.get("output_tokens")),
|
|
83
|
+
cacheReadTokens: count(a.get("cache_read_tokens")),
|
|
84
|
+
cacheCreationTokens: count(a.get("cache_creation_tokens")),
|
|
85
|
+
durationMs: count(a.get("duration_ms")),
|
|
86
|
+
status: kind === "api_error" ? status(a.get("status_code")) : null,
|
|
87
|
+
agent: held(DECLARED, a.get("agent.name")),
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
} catch {
|
|
93
|
+
// A malformed export shows nothing rather than breaking the sidecar.
|
|
94
|
+
}
|
|
95
|
+
return events;
|
|
96
|
+
}
|
package/cli/selftest.mjs
CHANGED
|
@@ -99,6 +99,9 @@ export async function proveItWorks({
|
|
|
99
99
|
apiKey,
|
|
100
100
|
fetchImpl,
|
|
101
101
|
wait = sleep,
|
|
102
|
+
// False for an agent whose scopes are known to exclude `demo`: the call could
|
|
103
|
+
// only be refused, and a refusal is recorded on the agent's page.
|
|
104
|
+
demoCall = true,
|
|
102
105
|
}) {
|
|
103
106
|
const proof = { visa: false, call: false, receipt: null };
|
|
104
107
|
try {
|
|
@@ -113,6 +116,13 @@ export async function proveItWorks({
|
|
|
113
116
|
proof.visa = true;
|
|
114
117
|
ok("minted a visa with this passport");
|
|
115
118
|
|
|
119
|
+
if (!demoCall) {
|
|
120
|
+
proof.reason = "no_demo_scope";
|
|
121
|
+
step("This agent has no access to the keyless demo model, so no test call was made: it could only be");
|
|
122
|
+
step('refused. Its model access is set on its page in the dashboard; then: passcontrol call "hi"');
|
|
123
|
+
return proof;
|
|
124
|
+
}
|
|
125
|
+
|
|
116
126
|
const res = await fetchImpl(`${origin}/api/v1/demo/chat/completions`, {
|
|
117
127
|
method: "POST",
|
|
118
128
|
headers: { "content-type": "application/json", authorization: `Bearer ${visa}` },
|