passcontrol 1.5.0 → 1.5.1
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 +75 -4
- package/cli/claude-code.mjs +179 -0
- package/cli/client-events-upload.mjs +212 -0
- package/cli/otlp-logs.mjs +96 -0
- package/cli/sidecar.mjs +288 -5
- package/cli/statusline.mjs +105 -7
- package/cli/subscription-gate.mjs +213 -0
- package/cli/tool-gate.mjs +152 -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 +49 -10
- package/package.json +1 -1
package/bin/passcontrol.mjs
CHANGED
|
@@ -95,9 +95,20 @@ import {
|
|
|
95
95
|
claudeCodeEnv,
|
|
96
96
|
claudeCodeSettingsPath,
|
|
97
97
|
removeClaudeCodeSettings,
|
|
98
|
+
removeClaudeCodeSubscription,
|
|
99
|
+
subscriptionEnv,
|
|
100
|
+
subscriptionHooks,
|
|
98
101
|
writeClaudeCodeSettings,
|
|
102
|
+
writeClaudeCodeSubscription,
|
|
99
103
|
} from "../cli/claude-code.mjs";
|
|
100
|
-
import {
|
|
104
|
+
import {
|
|
105
|
+
notInPathText,
|
|
106
|
+
readStatusInput,
|
|
107
|
+
sidecarFromBaseUrl,
|
|
108
|
+
statusPanelText,
|
|
109
|
+
statuslineText,
|
|
110
|
+
statuslineWithWindow,
|
|
111
|
+
} from "../cli/statusline.mjs";
|
|
101
112
|
import { runWatch } from "../cli/watch.mjs";
|
|
102
113
|
import { CODEX_PROFILE, codexProfilePath, codexProfileToml, codexStoresApiKey, removeCodexProfile, writeCodexProfile } from "../cli/codex.mjs";
|
|
103
114
|
import { waitForGateway as awaitGateway } from "../cli/gateway-wait.mjs";
|
|
@@ -208,7 +219,7 @@ ${heading("Quick start")}
|
|
|
208
219
|
${cmd} login [--project] sign in through your browser and set this machine up
|
|
209
220
|
${cmd} call "hi" mint a visa and make a governed model call
|
|
210
221
|
${cmd} mcp passport identity for Claude Desktop, Cursor, Claude Code
|
|
211
|
-
${cmd} sidecar [--port 8788] [--allow-connect host[,host]] [--ollama-port 11435] [--no-journal]
|
|
222
|
+
${cmd} sidecar [--port 8788] [--allow-connect host[,host]] [--ollama-port 11435] [--no-journal] [--no-report-calls]
|
|
212
223
|
passport identity for any tool that takes an api_key
|
|
213
224
|
${cmd} sidecar --profile <name> | --profiles a,b
|
|
214
225
|
run a coding tool's own sidecar (or several, one process)
|
|
@@ -262,6 +273,8 @@ ${heading("Integrate")}
|
|
|
262
273
|
${cmd} env [integration] print settings without writing anything
|
|
263
274
|
${cmd} configure <integration> [--write] [--force] [--dedicated]
|
|
264
275
|
preview or write integration config
|
|
276
|
+
${cmd} configure claude-code --subscription [--write|--remove]
|
|
277
|
+
a Pro/Max login: stops, calls, usage window
|
|
265
278
|
integrations: ${integrationChoices()}
|
|
266
279
|
|
|
267
280
|
${heading("Trust")}
|
|
@@ -2460,6 +2473,7 @@ async function sidecarCommand(rest, opts) {
|
|
|
2460
2473
|
allowConnectHosts: [],
|
|
2461
2474
|
refreshSkewSeconds: Number(opts.refreshSkewSeconds ?? process.env.REFRESH_SKEW_SECONDS ?? 30),
|
|
2462
2475
|
noJournal: opts.journal === false || Boolean(opts.noJournal),
|
|
2476
|
+
reportCalls: !(opts.reportCalls === false || Boolean(opts.noReportCalls)),
|
|
2463
2477
|
});
|
|
2464
2478
|
}
|
|
2465
2479
|
return;
|
|
@@ -2493,6 +2507,9 @@ async function sidecarCommand(rest, opts) {
|
|
|
2493
2507
|
// A flag only, like --allow-non-loopback: whether this machine keeps a record
|
|
2494
2508
|
// is the operator's to state, not a config file's.
|
|
2495
2509
|
noJournal: opts.journal === false || Boolean(opts.noJournal),
|
|
2510
|
+
// Subscription mode: the calls Claude Code reports go to the agent's page. On
|
|
2511
|
+
// unless the flag says off, like the journal.
|
|
2512
|
+
reportCalls: !(opts.reportCalls === false || Boolean(opts.noReportCalls)),
|
|
2496
2513
|
});
|
|
2497
2514
|
|
|
2498
2515
|
if (opts.for) {
|
|
@@ -2528,14 +2545,21 @@ async function statuslineCommand(opts) {
|
|
|
2528
2545
|
if (opts.panel) {
|
|
2529
2546
|
const route = opts.port === undefined ? sidecarFromBaseUrl(process.env.ANTHROPIC_BASE_URL) : null;
|
|
2530
2547
|
if (route?.remote) return notInPathText(route.remote);
|
|
2548
|
+
// Subscription mode (cli/subscription-gate.mjs): no ANTHROPIC_BASE_URL, since
|
|
2549
|
+
// the calls go to Anthropic directly; `configure claude-code --subscription`
|
|
2550
|
+
// names the sidecar the hooks and telemetry use instead.
|
|
2551
|
+
const reported = !route && opts.port === undefined ? sidecarFromBaseUrl(process.env.PASSCONTROL_SIDECAR_URL) : null;
|
|
2531
2552
|
return await statusPanelText({
|
|
2532
|
-
port: route?.port ?? port,
|
|
2553
|
+
port: route?.port ?? reported?.port ?? port,
|
|
2533
2554
|
gateway: config.gateway,
|
|
2534
2555
|
session: typeof opts.session === "string" ? opts.session : null,
|
|
2556
|
+
subscription: Boolean(reported?.port),
|
|
2535
2557
|
});
|
|
2536
2558
|
}
|
|
2537
2559
|
const cacheFile = path.join(path.dirname(globalConfigPath()), `statusline-${port}.json`);
|
|
2538
|
-
|
|
2560
|
+
// On a Pro/Max login Claude Code adds the usage window to its input (cli/usage-window.mjs).
|
|
2561
|
+
const input = await readStatusInput();
|
|
2562
|
+
return await statuslineWithWindow({ input, port, budgetLine: () => statuslineText({ port, cacheFile }) });
|
|
2539
2563
|
} catch (error) {
|
|
2540
2564
|
return `PassControl · ${error instanceof Error && /--port/.test(error.message) ? "bad --port" : "unavailable"}`;
|
|
2541
2565
|
}
|
|
@@ -2751,6 +2775,7 @@ function aiderConfig(opts = {}) {
|
|
|
2751
2775
|
* Claude Code owns.
|
|
2752
2776
|
*/
|
|
2753
2777
|
function configureClaudeCode(opts = {}) {
|
|
2778
|
+
if (opts.subscription) return configureClaudeCodeSubscription(opts);
|
|
2754
2779
|
const scope = opts.global ? "user" : "project";
|
|
2755
2780
|
const target = claudeCodeSettingsPath({ scope });
|
|
2756
2781
|
if (opts.remove) {
|
|
@@ -2793,6 +2818,52 @@ function configureClaudeCode(opts = {}) {
|
|
|
2793
2818
|
step(`To undo: ${cliCommand(`configure claude-code --remove${scope === "user" ? " --global" : ""}`)}`);
|
|
2794
2819
|
}
|
|
2795
2820
|
|
|
2821
|
+
/**
|
|
2822
|
+
* Subscription mode (cli/claude-code.mjs): a Claude
|
|
2823
|
+
* Pro/Max login keeps talking to Anthropic directly. PassControl is told about each
|
|
2824
|
+
* call, asked before each prompt and tool, and shown the usage window. Always the
|
|
2825
|
+
* user settings: Claude Code ignores telemetry settings in a project's file.
|
|
2826
|
+
*/
|
|
2827
|
+
function configureClaudeCodeSubscription(opts = {}) {
|
|
2828
|
+
const target = claudeCodeSettingsPath({ scope: "user" });
|
|
2829
|
+
const port = sidecarPort(opts);
|
|
2830
|
+
if (opts.remove) {
|
|
2831
|
+
const result = removeClaudeCodeSubscription({ target });
|
|
2832
|
+
if (result.changed) ok(`removed PassControl's subscription mode from ${target}`);
|
|
2833
|
+
else step(`${target} has no PassControl subscription settings; nothing to remove.`);
|
|
2834
|
+
return;
|
|
2835
|
+
}
|
|
2836
|
+
const preview = { env: subscriptionEnv(port), hooks: subscriptionHooks(port), statusLine: { type: "command", command: statusLineSettingsCommand(port) } };
|
|
2837
|
+
console.log(`Preview: ${target}\n\n${JSON.stringify(preview, null, 2)}`);
|
|
2838
|
+
if (!opts.write) {
|
|
2839
|
+
step("Dry run only. Re-run with `--write` to merge these into your Claude Code user settings (anything of yours is kept).");
|
|
2840
|
+
} else {
|
|
2841
|
+
const result = writeClaudeCodeSubscription({ target, port, statusLineCommand: statusLineSettingsCommand(port), force: Boolean(opts.force) });
|
|
2842
|
+
if (!result.changed) ok(`${target} already has PassControl's subscription mode`);
|
|
2843
|
+
else {
|
|
2844
|
+
if (result.backupPath) step(`backed up ${result.backupPath}`);
|
|
2845
|
+
ok(`wrote ${target}`);
|
|
2846
|
+
}
|
|
2847
|
+
if (result.statusLine?.existing) {
|
|
2848
|
+
warn(`${target} already has a status line (${result.statusLine.existing}); it was left as it is, so the usage window is not shown. To show it, have yours pipe its input to \`${statusLineSettingsCommand(port)}\`.`);
|
|
2849
|
+
}
|
|
2850
|
+
if (result.hookUrlsBlocked) {
|
|
2851
|
+
warn(`${target} sets allowedHttpHookUrls, which does not include http://127.0.0.1:${port}/_passcontrol/hook and its tool hook (…/_passcontrol/hook?t=600): Claude Code will not run them until you add both, for example http://127.0.0.1:${port}/_passcontrol/hook*.`);
|
|
2852
|
+
}
|
|
2853
|
+
if (result.routed) {
|
|
2854
|
+
warn(`${target} also routes Claude Code through the sidecar with PassControl's API key (ANTHROPIC_BASE_URL). Those sessions do not use your subscription. To use the subscription, run ${cliCommand("configure claude-code --remove --global")}.`);
|
|
2855
|
+
}
|
|
2856
|
+
}
|
|
2857
|
+
step(`Start the sidecar before Claude Code: ${cliCommand(port === 8788 ? "sidecar" : `sidecar --port ${port}`)}`);
|
|
2858
|
+
step("Your Pro/Max login stays between Claude Code and Anthropic. PassControl never sees it or sits in the path.");
|
|
2859
|
+
step("If the sidecar is not running, Claude Code still works: stops are not checked and calls are not shown until it is.");
|
|
2860
|
+
step(`Watch the calls: ${cliCommand("watch")}`);
|
|
2861
|
+
step(
|
|
2862
|
+
`The sidecar also uploads each reported call (model, session, tokens, time, API-equivalent cost; never your email or account ids) to the agent's dashboard page, marked as reported, not proxied. To keep them on this machine only: ${cliCommand("sidecar --no-report-calls")}`
|
|
2863
|
+
);
|
|
2864
|
+
step(`To undo: ${cliCommand("configure claude-code --subscription --remove")}`);
|
|
2865
|
+
}
|
|
2866
|
+
|
|
2796
2867
|
/**
|
|
2797
2868
|
* Codex speaks only OpenAI's Responses API, so its profile always points at the
|
|
2798
2869
|
* sidecar's OpenAI route. A model is written only when one is named with
|
package/cli/claude-code.mjs
CHANGED
|
@@ -158,3 +158,182 @@ export function removeClaudeCodeStatusLine({ target }) {
|
|
|
158
158
|
save(target, rest, true);
|
|
159
159
|
return { changed: true };
|
|
160
160
|
}
|
|
161
|
+
|
|
162
|
+
// ── Subscription mode ─────────────────────────────────────────────────────────
|
|
163
|
+
//
|
|
164
|
+
// A Pro/Max login talks to Anthropic directly, and Anthropic's terms forbid
|
|
165
|
+
// intermediating it, so nothing here touches ANTHROPIC_BASE_URL. Instead Claude
|
|
166
|
+
// Code is told to report to the sidecar and to ask it before acting:
|
|
167
|
+
// * its OpenTelemetry LOG export (http/json) goes to the sidecar's receiver
|
|
168
|
+
// (cli/otlp-logs.mjs). Only the logs-specific variables are written, so a
|
|
169
|
+
// metrics or traces export the user runs is left alone;
|
|
170
|
+
// * three http hooks go to the sidecar's stop gate (cli/subscription-gate.mjs),
|
|
171
|
+
// each with a 5 s timeout: a hook that cannot connect or times out lets the
|
|
172
|
+
// action go ahead, which is the fail-open the owner chose;
|
|
173
|
+
// * the status line carries the usage window (cli/usage-window.mjs);
|
|
174
|
+
// * PASSCONTROL_SIDECAR_URL tells `/passcontrol` which sidecar to ask.
|
|
175
|
+
// Only the user settings: Claude Code ignores telemetry settings in a project's file.
|
|
176
|
+
|
|
177
|
+
const LOOPBACK_BASE = "http://127.0.0.1:";
|
|
178
|
+
const OUR_LOGS_ENDPOINT = /^http:\/\/127\.0\.0\.1:\d{1,5}\/_passcontrol\/otlp\/v1\/logs$/;
|
|
179
|
+
const OUR_HOOK_URL = /^http:\/\/127\.0\.0\.1:\d{1,5}\/_passcontrol\/hook(\?t=\d{1,4})?$/;
|
|
180
|
+
const OUR_SIDECAR_URL = /^http:\/\/127\.0\.0\.1:\d{1,5}$/;
|
|
181
|
+
const GATED_EVENTS = ["UserPromptSubmit", "PreToolUse", "PostToolBatch"];
|
|
182
|
+
// The log-export settings this mode owns, with the value it writes.
|
|
183
|
+
const LOGS_ENV = {
|
|
184
|
+
OTEL_LOGS_EXPORTER: "otlp",
|
|
185
|
+
OTEL_EXPORTER_OTLP_LOGS_PROTOCOL: "http/json",
|
|
186
|
+
// The 5 s default would make the board's rows lag the session.
|
|
187
|
+
OTEL_LOGS_EXPORT_INTERVAL: "1000",
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
export function subscriptionEnv(port) {
|
|
191
|
+
return {
|
|
192
|
+
CLAUDE_CODE_ENABLE_TELEMETRY: "1",
|
|
193
|
+
...LOGS_ENV,
|
|
194
|
+
OTEL_EXPORTER_OTLP_LOGS_ENDPOINT: `${LOOPBACK_BASE}${port}/_passcontrol/otlp/v1/logs`,
|
|
195
|
+
PASSCONTROL_SIDECAR_URL: `${LOOPBACK_BASE}${port}`,
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function gateHook(port) {
|
|
200
|
+
return { type: "http", url: `${LOOPBACK_BASE}${port}/_passcontrol/hook`, timeout: 5 };
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// PreToolUse may hold a tool while the owner is asked (Phase 2), and Claude Code lets
|
|
204
|
+
// a tool RUN when its http hook times out. So this one gets Claude Code's own 600 s
|
|
205
|
+
// default, and says so in its URL: the sidecar always answers inside the time it is
|
|
206
|
+
// told, and a Phase 1 hook (no `t`, 5 s) refuses a tool that would need the owner
|
|
207
|
+
// instead of letting it through on the timeout.
|
|
208
|
+
export const TOOL_HOOK_TIMEOUT_S = 600;
|
|
209
|
+
function toolHook(port) {
|
|
210
|
+
return { type: "http", url: `${LOOPBACK_BASE}${port}/_passcontrol/hook?t=${TOOL_HOOK_TIMEOUT_S}`, timeout: TOOL_HOOK_TIMEOUT_S };
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export function subscriptionHooks(port) {
|
|
214
|
+
const hook = gateHook(port);
|
|
215
|
+
return {
|
|
216
|
+
UserPromptSubmit: [{ hooks: [hook] }],
|
|
217
|
+
PreToolUse: [{ matcher: "*", hooks: [toolHook(port)] }],
|
|
218
|
+
PostToolBatch: [{ hooks: [hook] }],
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
223
|
+
const isOurHook = (h) => isObject(h) && h.type === "http" && typeof h.url === "string" && OUR_HOOK_URL.test(h.url);
|
|
224
|
+
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
|
225
|
+
|
|
226
|
+
/** `hooks` with every hook this mode wrote taken out, and groups left empty dropped. */
|
|
227
|
+
function withoutOurHooks(hooks) {
|
|
228
|
+
if (!isObject(hooks)) return hooks;
|
|
229
|
+
const next = {};
|
|
230
|
+
for (const [event, groups] of Object.entries(hooks)) {
|
|
231
|
+
if (!Array.isArray(groups)) {
|
|
232
|
+
next[event] = groups;
|
|
233
|
+
continue;
|
|
234
|
+
}
|
|
235
|
+
const kept = [];
|
|
236
|
+
for (const group of groups) {
|
|
237
|
+
if (!isObject(group) || !Array.isArray(group.hooks) || !group.hooks.some(isOurHook)) {
|
|
238
|
+
kept.push(group);
|
|
239
|
+
continue;
|
|
240
|
+
}
|
|
241
|
+
const rest = group.hooks.filter((h) => !isOurHook(h));
|
|
242
|
+
if (rest.length) kept.push({ ...group, hooks: rest });
|
|
243
|
+
}
|
|
244
|
+
if (kept.length) next[event] = kept;
|
|
245
|
+
}
|
|
246
|
+
return next;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** `hooks` with exactly this port's gate hooks, leaving them where they are when already right. */
|
|
250
|
+
function withOurHooks(hooks, port) {
|
|
251
|
+
const ours = subscriptionHooks(port);
|
|
252
|
+
const base = isObject(hooks) ? hooks : {};
|
|
253
|
+
const next = withoutOurHooks(base);
|
|
254
|
+
for (const event of GATED_EVENTS) {
|
|
255
|
+
const current = Array.isArray(base[event]) ? base[event] : [];
|
|
256
|
+
const already = current.filter((g) => isObject(g) && Array.isArray(g.hooks) && g.hooks.some(isOurHook));
|
|
257
|
+
if (already.length === 1 && same(already[0], ours[event][0])) next[event] = current;
|
|
258
|
+
else next[event] = [...(next[event] ?? []), ...ours[event]];
|
|
259
|
+
}
|
|
260
|
+
return next;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// `allowedHttpHookUrls`, when set at any level, runs only the http hooks it matches.
|
|
264
|
+
function urlAllowed(patterns, url) {
|
|
265
|
+
return patterns.some((p) => {
|
|
266
|
+
if (typeof p !== "string") return false;
|
|
267
|
+
const re = new RegExp(`^${p.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*")}$`);
|
|
268
|
+
return re.test(url);
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* Subscription mode's settings, in one save. Throws, writing nothing, when the
|
|
274
|
+
* user already exports Claude Code's logs somewhere else and `force` is not set.
|
|
275
|
+
*/
|
|
276
|
+
export function writeClaudeCodeSubscription({ target, port, statusLineCommand, force = false }) {
|
|
277
|
+
const { exists, value } = readSettings(target);
|
|
278
|
+
const env = isObject(value.env) ? value.env : {};
|
|
279
|
+
const endpoint = env.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT;
|
|
280
|
+
const ourEndpoint = typeof endpoint === "string" && OUR_LOGS_ENDPOINT.test(endpoint);
|
|
281
|
+
const theirs = [];
|
|
282
|
+
if (endpoint !== undefined && !ourEndpoint) theirs.push("OTEL_EXPORTER_OTLP_LOGS_ENDPOINT");
|
|
283
|
+
if (env.OTEL_LOGS_EXPORTER !== undefined && !ourEndpoint) theirs.push("OTEL_LOGS_EXPORTER");
|
|
284
|
+
if (theirs.length && !force) {
|
|
285
|
+
throw new Error(
|
|
286
|
+
`${target} already exports Claude Code's logs (${theirs.join(", ")}). Subscription mode would send them to the sidecar instead. Re-run with --force to do that; nothing was written.`
|
|
287
|
+
);
|
|
288
|
+
}
|
|
289
|
+
let next = { ...value, env: { ...env, ...subscriptionEnv(port) }, hooks: withOurHooks(value.hooks, port) };
|
|
290
|
+
let statusLine;
|
|
291
|
+
if (statusLineCommand) {
|
|
292
|
+
const line = withStatusLine(next, statusLineCommand);
|
|
293
|
+
next = line.value;
|
|
294
|
+
statusLine = line.existing !== undefined ? { changed: false, existing: line.existing } : { changed: line.changed };
|
|
295
|
+
}
|
|
296
|
+
const changed = !same(next, value);
|
|
297
|
+
const backupPath = changed ? save(target, next, exists) : null;
|
|
298
|
+
const allowlist = Array.isArray(value.allowedHttpHookUrls) ? value.allowedHttpHookUrls : null;
|
|
299
|
+
return {
|
|
300
|
+
changed,
|
|
301
|
+
backupPath,
|
|
302
|
+
...(statusLine ? { statusLine } : {}),
|
|
303
|
+
hookUrlsBlocked: Boolean(allowlist && [gateHook(port), toolHook(port)].some((h) => !urlAllowed(allowlist, h.url))),
|
|
304
|
+
routed: env.ANTHROPIC_AUTH_TOKEN === CLAUDE_CODE_AUTH_PLACEHOLDER && typeof env.ANTHROPIC_BASE_URL === "string",
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* Takes out what `writeClaudeCodeSubscription` wrote: its hooks, its status line, its
|
|
310
|
+
* sidecar address, and the logs export only when it points at a sidecar. The
|
|
311
|
+
* telemetry switch stays while any other OTEL_ setting still needs it.
|
|
312
|
+
*/
|
|
313
|
+
export function removeClaudeCodeSubscription({ target }) {
|
|
314
|
+
if (!fs.existsSync(target)) return { changed: false };
|
|
315
|
+
const { value } = readSettings(target);
|
|
316
|
+
let next = { ...value };
|
|
317
|
+
if (isObject(value.env)) {
|
|
318
|
+
const env = { ...value.env };
|
|
319
|
+
if (typeof env.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT === "string" && OUR_LOGS_ENDPOINT.test(env.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT)) {
|
|
320
|
+
delete env.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT;
|
|
321
|
+
for (const [key, ours] of Object.entries(LOGS_ENV)) if (env[key] === ours) delete env[key];
|
|
322
|
+
if (env.CLAUDE_CODE_ENABLE_TELEMETRY === "1" && !Object.keys(env).some((k) => k.startsWith("OTEL_"))) {
|
|
323
|
+
delete env.CLAUDE_CODE_ENABLE_TELEMETRY;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
if (typeof env.PASSCONTROL_SIDECAR_URL === "string" && OUR_SIDECAR_URL.test(env.PASSCONTROL_SIDECAR_URL)) delete env.PASSCONTROL_SIDECAR_URL;
|
|
327
|
+
if (Object.keys(env).length) next.env = env;
|
|
328
|
+
else delete next.env;
|
|
329
|
+
}
|
|
330
|
+
if (isObject(value.hooks)) {
|
|
331
|
+
const hooks = withoutOurHooks(value.hooks);
|
|
332
|
+
if (Object.keys(hooks).length) next.hooks = hooks;
|
|
333
|
+
else delete next.hooks;
|
|
334
|
+
}
|
|
335
|
+
if (isOurStatusLine(next.statusLine)) delete next.statusLine;
|
|
336
|
+
if (same(next, value)) return { changed: false };
|
|
337
|
+
save(target, next, true);
|
|
338
|
+
return { changed: true };
|
|
339
|
+
}
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
// Subscription mode, Phase 1b: the model calls Claude Code REPORTS to the sidecar
|
|
2
|
+
// (cli/otlp-logs.mjs) are uploaded to the gateway's POST /api/v1/client-events, so
|
|
3
|
+
// they reach the agent's dashboard page and not only this machine's `watch`.
|
|
4
|
+
//
|
|
5
|
+
// The OTLP answer never waits for this: `add` only queues, and a timer flushes in
|
|
6
|
+
// batches. Each event gets its key once, when it is queued, and every retry sends the
|
|
7
|
+
// same key, so the gateway (0084, unique per agent and key) stores it once however
|
|
8
|
+
// often it is sent. The queue is bounded and drops the oldest.
|
|
9
|
+
//
|
|
10
|
+
// What each answer means:
|
|
11
|
+
// 200 sent; the gateway counted what it took
|
|
12
|
+
// 403 the agent is stopped: what it reports is not recorded, so drop
|
|
13
|
+
// 400, 413 the batch will never be accepted as it is, so drop it
|
|
14
|
+
// 503 `client_events_unavailable`: the gateway's database predates 0084
|
|
15
|
+
// 404, 405 the gateway predates the endpoint (npm, the Cloud deploy and
|
|
16
|
+
// `passcontrol update` ship at different times)
|
|
17
|
+
// → for both: drop everything and stop for a while
|
|
18
|
+
// 429 wait as long as the gateway asks
|
|
19
|
+
// anything else, or no answer: keep the events, back off, retry, and give a batch
|
|
20
|
+
// up after `maxAttempts`, so one that always fails cannot pin the queue
|
|
21
|
+
//
|
|
22
|
+
// Phase 2 queues the tool rules' decisions here too (cli/tool-gate.mjs): the tool's
|
|
23
|
+
// name and the decision, never the command, path or URL it was about.
|
|
24
|
+
//
|
|
25
|
+
// Only the fields the gateway stores are sent. The reported cost is what the call
|
|
26
|
+
// would have cost on the API, never money spent: the gateway keeps it apart from
|
|
27
|
+
// every budget.
|
|
28
|
+
|
|
29
|
+
import { randomBytes } from "node:crypto";
|
|
30
|
+
|
|
31
|
+
export const CLIENT_EVENTS_PATH = "/api/v1/client-events";
|
|
32
|
+
export const CLIENT_EVENTS_SOURCE = "claude_code_otel";
|
|
33
|
+
|
|
34
|
+
const UNAVAILABLE_PAUSE_MS = 10 * 60_000;
|
|
35
|
+
const BACKOFF_FIRST_MS = 2_000;
|
|
36
|
+
const BACKOFF_MAX_MS = 60_000;
|
|
37
|
+
|
|
38
|
+
const newKey = () => `evt_${randomBytes(16).toString("base64url")}`;
|
|
39
|
+
|
|
40
|
+
/** One event from readClaudeCodeEvents, as the gateway takes it. Absent fields are left out. */
|
|
41
|
+
function toWire(event, key) {
|
|
42
|
+
if (event.kind === "tool_decision") return toolDecisionWire(event, key);
|
|
43
|
+
const wire = {
|
|
44
|
+
key,
|
|
45
|
+
kind: event.kind === "api_error" ? "model_error" : "model_call",
|
|
46
|
+
session: event.session,
|
|
47
|
+
agent: event.agent,
|
|
48
|
+
at: event.at,
|
|
49
|
+
model: event.model,
|
|
50
|
+
cost_usd_micros: event.kind === "api_error" ? null : event.costMicros,
|
|
51
|
+
input_tokens: event.inputTokens,
|
|
52
|
+
output_tokens: event.outputTokens,
|
|
53
|
+
cache_read_tokens: event.cacheReadTokens,
|
|
54
|
+
cache_creation_tokens: event.cacheCreationTokens,
|
|
55
|
+
duration_ms: event.durationMs,
|
|
56
|
+
status: event.kind === "api_error" ? event.status : null,
|
|
57
|
+
};
|
|
58
|
+
for (const name of Object.keys(wire)) if (wire[name] === null || wire[name] === undefined) delete wire[name];
|
|
59
|
+
return wire;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function toolDecisionWire(event, key) {
|
|
63
|
+
const wire = {
|
|
64
|
+
key,
|
|
65
|
+
kind: "tool_decision",
|
|
66
|
+
session: event.session,
|
|
67
|
+
agent: event.agent,
|
|
68
|
+
at: event.at,
|
|
69
|
+
tool: event.tool,
|
|
70
|
+
decision: event.decision,
|
|
71
|
+
rule_index: event.ruleIndex,
|
|
72
|
+
duration_ms: event.waitMs,
|
|
73
|
+
};
|
|
74
|
+
for (const name of Object.keys(wire)) if (wire[name] === null || wire[name] === undefined) delete wire[name];
|
|
75
|
+
return wire;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* @param {{
|
|
80
|
+
* send: (events: object[]) => Promise<{ status: number, error?: string, retryAfterS?: number }>,
|
|
81
|
+
* now?: () => number,
|
|
82
|
+
* setTimer?: (fn: () => unknown, ms: number) => unknown,
|
|
83
|
+
* clearTimer?: (timer: unknown) => void,
|
|
84
|
+
* maxQueue?: number,
|
|
85
|
+
* batchSize?: number,
|
|
86
|
+
* flushMs?: number,
|
|
87
|
+
* maxAttempts?: number,
|
|
88
|
+
* }} options
|
|
89
|
+
*/
|
|
90
|
+
export function createCallUploader({
|
|
91
|
+
send,
|
|
92
|
+
now = () => Date.now(),
|
|
93
|
+
setTimer = (fn, ms) => {
|
|
94
|
+
const timer = setTimeout(fn, ms);
|
|
95
|
+
timer.unref?.();
|
|
96
|
+
return timer;
|
|
97
|
+
},
|
|
98
|
+
clearTimer = (timer) => clearTimeout(timer),
|
|
99
|
+
maxQueue = 1_000,
|
|
100
|
+
batchSize = 50,
|
|
101
|
+
// Every 10 s: the gateway allows 30 uploads a minute per agent, and two sidecars on
|
|
102
|
+
// one agent should still fit.
|
|
103
|
+
flushMs = 10_000,
|
|
104
|
+
maxAttempts = 8,
|
|
105
|
+
}) {
|
|
106
|
+
let queue = [];
|
|
107
|
+
let sent = 0;
|
|
108
|
+
let dropped = 0;
|
|
109
|
+
let timer = null;
|
|
110
|
+
let inflight = null;
|
|
111
|
+
let waitUntil = 0;
|
|
112
|
+
let unavailableUntil = 0;
|
|
113
|
+
let backoffMs = 0;
|
|
114
|
+
let closed = false;
|
|
115
|
+
// Failed sends per queued event (transient failures only).
|
|
116
|
+
const attempts = new WeakMap();
|
|
117
|
+
|
|
118
|
+
function schedule(delayMs) {
|
|
119
|
+
if (closed || queue.length === 0) return;
|
|
120
|
+
if (timer) clearTimer(timer);
|
|
121
|
+
const ms = Math.max(delayMs, waitUntil - now(), 0);
|
|
122
|
+
timer = setTimer(() => {
|
|
123
|
+
timer = null;
|
|
124
|
+
return flush();
|
|
125
|
+
}, ms);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function add(event) {
|
|
129
|
+
if (closed) return;
|
|
130
|
+
if (unavailableUntil > now()) {
|
|
131
|
+
dropped += 1;
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
queue.push(toWire(event, newKey()));
|
|
135
|
+
if (queue.length > maxQueue) {
|
|
136
|
+
queue.shift();
|
|
137
|
+
dropped += 1;
|
|
138
|
+
}
|
|
139
|
+
if (inflight) return;
|
|
140
|
+
if (queue.length >= batchSize) schedule(0);
|
|
141
|
+
else if (!timer) schedule(flushMs);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async function flushOnce() {
|
|
145
|
+
const batch = queue.slice(0, batchSize);
|
|
146
|
+
if (batch.length === 0) return;
|
|
147
|
+
let answer;
|
|
148
|
+
try {
|
|
149
|
+
answer = await send(batch);
|
|
150
|
+
} catch {
|
|
151
|
+
answer = { status: 0 };
|
|
152
|
+
}
|
|
153
|
+
const taken = new Set(batch);
|
|
154
|
+
const status = answer?.status ?? 0;
|
|
155
|
+
if (status === 200) {
|
|
156
|
+
queue = queue.filter((e) => !taken.has(e));
|
|
157
|
+
sent += batch.length;
|
|
158
|
+
backoffMs = 0;
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
if ((status === 503 && answer.error === "client_events_unavailable") || status === 404 || status === 405) {
|
|
162
|
+
dropped += queue.length;
|
|
163
|
+
queue = [];
|
|
164
|
+
unavailableUntil = now() + UNAVAILABLE_PAUSE_MS;
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
if (status === 403 || status === 400 || status === 413) {
|
|
168
|
+
queue = queue.filter((e) => !taken.has(e));
|
|
169
|
+
dropped += batch.length;
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
if (status === 429) {
|
|
173
|
+
const seconds = Number(answer.retryAfterS);
|
|
174
|
+
waitUntil = now() + (Number.isFinite(seconds) && seconds > 0 ? seconds * 1_000 : BACKOFF_MAX_MS);
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
for (const e of batch) attempts.set(e, (attempts.get(e) ?? 0) + 1);
|
|
178
|
+
const spent = batch.filter((e) => attempts.get(e) >= maxAttempts);
|
|
179
|
+
if (spent.length > 0) {
|
|
180
|
+
const gone = new Set(spent);
|
|
181
|
+
queue = queue.filter((e) => !gone.has(e));
|
|
182
|
+
dropped += spent.length;
|
|
183
|
+
}
|
|
184
|
+
backoffMs = backoffMs ? Math.min(backoffMs * 2, BACKOFF_MAX_MS) : BACKOFF_FIRST_MS;
|
|
185
|
+
waitUntil = now() + backoffMs;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** Sends one batch now (one at a time), then schedules whatever is left. */
|
|
189
|
+
function flush() {
|
|
190
|
+
if (inflight) return inflight;
|
|
191
|
+
inflight = (async () => {
|
|
192
|
+
try {
|
|
193
|
+
await flushOnce();
|
|
194
|
+
} finally {
|
|
195
|
+
inflight = null;
|
|
196
|
+
if (queue.length >= batchSize && waitUntil <= now()) schedule(0);
|
|
197
|
+
else schedule(flushMs);
|
|
198
|
+
}
|
|
199
|
+
})();
|
|
200
|
+
return inflight;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function close() {
|
|
204
|
+
closed = true;
|
|
205
|
+
if (timer) clearTimer(timer);
|
|
206
|
+
timer = null;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const stats = () => ({ queued: queue.length, sent, dropped });
|
|
210
|
+
|
|
211
|
+
return { add, flush, close, stats };
|
|
212
|
+
}
|
|
@@ -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
|
+
}
|