context-doctor 0.36.0 → 0.38.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.
Files changed (62) hide show
  1. package/README.md +25 -15
  2. package/dist/autoclear.d.ts +11 -4
  3. package/dist/autoclear.js +52 -6
  4. package/dist/autopilot.d.ts +24 -0
  5. package/dist/autopilot.js +108 -0
  6. package/dist/cachemisses.d.ts +104 -2
  7. package/dist/cachemisses.js +199 -11
  8. package/dist/cli.js +172 -12
  9. package/dist/compact.d.ts +36 -0
  10. package/dist/compact.js +144 -0
  11. package/dist/compactwindow.d.ts +1 -1
  12. package/dist/compactwindow.js +6 -1
  13. package/dist/doctor.js +58 -1
  14. package/dist/extract.d.ts +23 -0
  15. package/dist/extract.js +121 -4
  16. package/dist/fanout.d.ts +131 -0
  17. package/dist/fanout.js +317 -0
  18. package/dist/fileparams.d.ts +61 -0
  19. package/dist/fileparams.js +308 -0
  20. package/dist/handoff.d.ts +143 -0
  21. package/dist/handoff.js +539 -0
  22. package/dist/hook.js +15 -0
  23. package/dist/httpguard.d.ts +56 -0
  24. package/dist/httpguard.js +141 -0
  25. package/dist/install.js +17 -5
  26. package/dist/ledger.d.ts +2 -0
  27. package/dist/ledger.js +44 -7
  28. package/dist/lens.d.ts +56 -0
  29. package/dist/lens.js +213 -0
  30. package/dist/limits.d.ts +229 -0
  31. package/dist/limits.js +869 -0
  32. package/dist/mcp.d.ts +3 -0
  33. package/dist/mcp.js +79 -56
  34. package/dist/mcpschema.d.ts +25 -1
  35. package/dist/mcpschema.js +78 -25
  36. package/dist/overhead.js +7 -6
  37. package/dist/pack.d.ts +20 -0
  38. package/dist/pack.js +29 -1
  39. package/dist/precompact.js +8 -7
  40. package/dist/preferences.d.ts +3 -1
  41. package/dist/preferences.js +8 -6
  42. package/dist/pricing.d.ts +29 -2
  43. package/dist/pricing.js +46 -8
  44. package/dist/proxy.d.ts +5 -3
  45. package/dist/proxy.js +12 -7
  46. package/dist/prune.d.ts +116 -0
  47. package/dist/prune.js +428 -0
  48. package/dist/recall.d.ts +104 -0
  49. package/dist/recall.js +393 -0
  50. package/dist/rules.d.ts +7 -4
  51. package/dist/rules.js +12 -8
  52. package/dist/savings.d.ts +1 -1
  53. package/dist/savings.js +11 -1
  54. package/dist/session.js +6 -13
  55. package/dist/sketch.d.ts +5 -1
  56. package/dist/sketch.js +23 -7
  57. package/dist/statusline.d.ts +6 -0
  58. package/dist/statusline.js +9 -0
  59. package/dist/subagentpay.d.ts +11 -0
  60. package/dist/subagentpay.js +1 -1
  61. package/package.json +1 -1
  62. package/skills/context-doctor/SKILL.md +3 -0
@@ -0,0 +1,141 @@
1
+ /**
2
+ * Guards for the MCP server's --http mode, kept apart from mcp.ts (which
3
+ * starts a server on import) so they can be tested directly.
4
+ *
5
+ * A server on 127.0.0.1 is still reachable from a browser: a page can POST to
6
+ * it (a cross-origin "simple" request needs no preflight), and with DNS
7
+ * rebinding a page on attacker.example can even make the browser treat the
8
+ * server as same-origin. A QA pass did exactly that: a foreign origin saved
9
+ * 101 handoffs through --store-handoffs, evicted the user's own and planted
10
+ * handoff://latest. So every /mcp request is checked:
11
+ *
12
+ * - Host must name this server: localhost, 127.0.0.1, [::1], the --host it
13
+ * was given, or a name in --allowed-hosts (a tunnel's host name, say).
14
+ * `--allowed-hosts '*'` turns the check off, explicitly.
15
+ * - Origin, when a browser sends one, must be a loopback origin, one whose
16
+ * host is allowed above, or one in --allowed-origins. ChatGPT's own
17
+ * origins are allowed by default; requests without an Origin (servers,
18
+ * CLIs, ChatGPT's connector backend) are not affected.
19
+ * - The body is read here, capped (10 MB, else 413), and parsed (else 400),
20
+ * then handed to the transport, so no request can make the server buffer
21
+ * an unbounded body.
22
+ */
23
+ export const HTTP_LIMITS = { bodyBytes: 10 * 1024 * 1024, bodyMs: 30_000 };
24
+ /** Origins a browser may call from without being listed: ChatGPT's. */
25
+ export const DEFAULT_ALLOWED_ORIGINS = ["https://chatgpt.com", "https://chat.openai.com"];
26
+ const LOOPBACK_HOSTS = ["localhost", "127.0.0.1", "::1"];
27
+ function list(value) {
28
+ return (value ?? "").split(",").map((x) => x.trim()).filter(Boolean);
29
+ }
30
+ /** A Host header's or URL's host name: lowercase, no port, no brackets, no trailing dot. */
31
+ export function hostName(hostHeader) {
32
+ let h = hostHeader.trim().toLowerCase();
33
+ if (h.startsWith("["))
34
+ h = h.slice(1, h.indexOf("]") > 0 ? h.indexOf("]") : undefined);
35
+ else if (h.split(":").length === 2)
36
+ h = h.split(":")[0];
37
+ return h.replace(/\.$/, "");
38
+ }
39
+ /**
40
+ * The guard for a server bound to `bindHost`, from --allowed-hosts and
41
+ * --allowed-origins (comma lists) and the CONTEXT_DOCTOR_ALLOWED_HOSTS and
42
+ * CONTEXT_DOCTOR_ALLOWED_ORIGINS environment variables.
43
+ */
44
+ export function makeGuard(bindHost, allowedHosts, allowedOrigins, env = process.env) {
45
+ const extra = [...list(allowedHosts), ...list(env.CONTEXT_DOCTOR_ALLOWED_HOSTS)];
46
+ const origins = new Set([...DEFAULT_ALLOWED_ORIGINS, ...list(allowedOrigins), ...list(env.CONTEXT_DOCTOR_ALLOWED_ORIGINS)].map((o) => o.toLowerCase().replace(/\/+$/, "")));
47
+ if (extra.includes("*"))
48
+ return { hosts: "*", origins };
49
+ const bind = hostName(bindHost);
50
+ const hosts = new Set([...LOOPBACK_HOSTS, ...extra.map(hostName)]);
51
+ // A specific bind address or name is one the server answers to; a wildcard is not a name.
52
+ if (bind && bind !== "0.0.0.0" && bind !== "::")
53
+ hosts.add(bind);
54
+ return { hosts, origins };
55
+ }
56
+ /** Why this request may not reach /mcp, or undefined when it may. */
57
+ export function refusal(guard, headers) {
58
+ if (guard.hosts !== "*") {
59
+ const host = hostName(String(headers.host ?? ""));
60
+ if (!host)
61
+ return "the request has no Host header";
62
+ if (!guard.hosts.has(host)) {
63
+ return `Host "${host}" is not one this server answers to. Behind a tunnel or under a host name, start it with --allowed-hosts ${host}`;
64
+ }
65
+ }
66
+ const origin = headers.origin;
67
+ if (origin !== undefined) {
68
+ const o = String(origin).toLowerCase().replace(/\/+$/, "");
69
+ if (guard.origins.has(o))
70
+ return undefined;
71
+ let url;
72
+ try {
73
+ url = new URL(o);
74
+ }
75
+ catch {
76
+ return `Origin "${o}" is not allowed`;
77
+ }
78
+ const h = hostName(url.host);
79
+ const ok = LOOPBACK_HOSTS.includes(h) || (guard.hosts !== "*" && guard.hosts.has(h));
80
+ if (!ok)
81
+ return `Origin "${o}" is not allowed. To let a web page call this server, start it with --allowed-origins ${o}`;
82
+ }
83
+ return undefined;
84
+ }
85
+ /**
86
+ * The request body as JSON, at most `limit` bytes and within `ms` (a client
87
+ * that declares more than it sends must not hold a request open); otherwise
88
+ * the status and reason to answer with.
89
+ */
90
+ export function readJsonBody(req, limit = HTTP_LIMITS.bodyBytes, ms = HTTP_LIMITS.bodyMs) {
91
+ return new Promise((resolve) => {
92
+ let done = false;
93
+ const timer = setTimeout(() => {
94
+ if (done)
95
+ return;
96
+ done = true;
97
+ resolve({ status: 408, code: -32600, message: `the request body did not arrive within ${Math.round(ms / 1000)} s` });
98
+ }, ms);
99
+ const settle = (r) => {
100
+ clearTimeout(timer);
101
+ resolve(r);
102
+ };
103
+ const tooLarge = { status: 413, code: -32600, message: `request body over ${Math.round(limit / 1024 / 1024)} MB` };
104
+ const declared = Number(req.headers["content-length"]);
105
+ if (Number.isFinite(declared) && declared > limit) {
106
+ req.resume();
107
+ return settle(tooLarge);
108
+ }
109
+ const parts = [];
110
+ let size = 0;
111
+ req.on("data", (d) => {
112
+ if (done)
113
+ return;
114
+ size += d.length;
115
+ if (size > limit) {
116
+ done = true;
117
+ parts.length = 0;
118
+ req.resume();
119
+ return settle(tooLarge);
120
+ }
121
+ parts.push(d);
122
+ });
123
+ req.on("end", () => {
124
+ if (done)
125
+ return;
126
+ done = true;
127
+ try {
128
+ settle({ value: JSON.parse(Buffer.concat(parts).toString("utf8")) });
129
+ }
130
+ catch {
131
+ settle({ status: 400, code: -32700, message: "Parse error: the body is not JSON" });
132
+ }
133
+ });
134
+ req.on("error", () => {
135
+ if (done)
136
+ return;
137
+ done = true;
138
+ settle({ status: 400, code: -32700, message: "the request body could not be read" });
139
+ });
140
+ });
141
+ }
package/dist/install.js CHANGED
@@ -12,6 +12,7 @@ import { delimiter, dirname, join, sep } from "node:path";
12
12
  import { fileURLToPath } from "node:url";
13
13
  import { selfCommand, withInvocation } from "./invocation.js";
14
14
  import { claudeCodeInstalls, describeInstalls, modelSwitchReadiness, PRE_MODEL_SWITCH_SINCE } from "./modelswitch.js";
15
+ import { FANOUT_MATCHER } from "./fanout.js";
15
16
  import { COPILOT_HOOK_EVENT, copilotHome, copilotHookFilePath, copilotMcpConfigPath, isOurCopilotEntry, vsCodePresent } from "./copilot.js";
16
17
  function claudeDesktopConfigPath() {
17
18
  switch (platform()) {
@@ -137,7 +138,7 @@ export function claudeInstalledCopies(home = homedir()) {
137
138
  catch { /* unreadable: not ours to judge here */ }
138
139
  try {
139
140
  const hooks = readJson(join(home, ".claude", "settings.json")).hooks ?? {};
140
- if (["UserPromptSubmit", "PreCompact", "SessionStart", "PreModelSwitch"].some((ev) => (hooks[ev] ?? []).some?.(isOurHookEntry)))
141
+ if (["UserPromptSubmit", "PreCompact", "SessionStart", "PreModelSwitch", "PreToolUse"].some((ev) => (hooks[ev] ?? []).some?.(isOurHookEntry)))
141
142
  found.push("hooks in ~/.claude/settings.json");
142
143
  }
143
144
  catch { /* unreadable */ }
@@ -313,6 +314,10 @@ function installHook() {
313
314
  if (path) {
314
315
  installHookInto(settings, join(homedir(), ".claude"), "PreCompact");
315
316
  installHookInto(settings, join(homedir(), ".claude"), "SessionStart");
317
+ // Before a subagent starts: its price. PreToolUse is in every Claude Code
318
+ // with hooks (2.1.62's event list has it), so no version guard is needed,
319
+ // and a timeout never blocks the call. "Task" is the tool's name before 2.1.63.
320
+ installHookInto(settings, join(homedir(), ".claude"), "PreToolUse", { matcher: FANOUT_MATCHER, timeout: 10 });
316
321
  }
317
322
  return path;
318
323
  }
@@ -322,25 +327,29 @@ function installHook() {
322
327
  * ({hooks:{UserPromptSubmit:[{hooks:[{type:"command",command}]}]}}), so one
323
328
  * writer serves both; only the path differs.
324
329
  */
325
- function installHookInto(settingsPath, gateDir, event = "UserPromptSubmit") {
330
+ function installHookInto(settingsPath, gateDir, event = "UserPromptSubmit", opts = {}) {
326
331
  if (!existsSync(gateDir))
327
332
  return null; // that app is not on this machine
328
333
  const settings = readJson(settingsPath);
329
334
  settings.hooks = settings.hooks ?? {};
330
335
  const entries = settings.hooks[event] ?? [];
331
336
  const want = hookCommand();
337
+ const entry = () => ({
338
+ ...(opts.matcher ? { matcher: opts.matcher } : {}),
339
+ hooks: [{ type: "command", command: want, ...(opts.timeout ? { timeout: opts.timeout } : {}) }],
340
+ });
332
341
  // Re-running install must REPAIR a stale entry, not skip it. Earlier versions
333
342
  // wrote a version-pinned node binary; if we only checked "is it present?" an
334
343
  // upgrade would leave that broken command in place forever.
335
344
  const ours = entries.filter(isOurHookEntry);
336
345
  const current = ours[0]?.hooks?.[0]?.command;
337
346
  if (ours.length === 0) {
338
- entries.push({ hooks: [{ type: "command", command: want }] });
347
+ entries.push(entry());
339
348
  }
340
- else if (current !== want) {
349
+ else if (current !== want || (ours[0]?.matcher ?? undefined) !== opts.matcher) {
341
350
  // Replace every entry of ours with exactly one correct entry.
342
351
  const others = entries.filter((e) => !isOurHookEntry(e));
343
- others.push({ hooks: [{ type: "command", command: want }] });
352
+ others.push(entry());
344
353
  settings.hooks[event] = others;
345
354
  writeJsonWithBackup(settingsPath, settings);
346
355
  return settingsPath;
@@ -359,6 +368,7 @@ function uninstallHook(attempt) {
359
368
  attempt("Claude Code compaction hook", () => uninstallHookFrom(claude, "Claude Code compaction hook", "PreCompact"));
360
369
  attempt("Claude Code session-start hook", () => uninstallHookFrom(claude, "Claude Code session-start hook", "SessionStart"));
361
370
  attempt("Claude Code model-switch warning", () => uninstallHookFrom(claude, "Claude Code model-switch warning", "PreModelSwitch"));
371
+ attempt("Claude Code subagent price", () => uninstallHookFrom(claude, "Claude Code subagent price", "PreToolUse"));
362
372
  attempt("Codex every-prompt hook", () => uninstallHookFrom(join(homedir(), ".codex", "hooks.json"), "Codex every-prompt hook"));
363
373
  attempt("Gemini CLI every-prompt hook", () => uninstallHookFrom(geminiSettingsPath(), "Gemini CLI every-prompt hook", "BeforeAgent"));
364
374
  attempt("Cursor hooks", () => uninstallCursorHook());
@@ -1188,6 +1198,8 @@ const OUR_CLAUDE_FILES = [
1188
1198
  ".context-doctor-autopilot-paused",
1189
1199
  ".context-doctor-proxy.log",
1190
1200
  ".context-doctor-proxy-restart",
1201
+ ".context-doctor-limits.jsonl",
1202
+ ".context-doctor-subagent-costs.json",
1191
1203
  ];
1192
1204
  export async function runUninstall() {
1193
1205
  changes = 0;
package/dist/ledger.d.ts CHANGED
@@ -57,5 +57,7 @@ export interface CarriedTotals {
57
57
  export declare function foldTotals(entries: LedgerEntry[]): CarriedTotals;
58
58
  export declare function statePath(): string;
59
59
  export declare function ledgerPath(): string;
60
+ /** Longest string field kept in a ledger entry (a model name, a session id). */
61
+ export declare const LEDGER_STRING_MAX = 100;
60
62
  export declare function recordLedger(entry: Omit<LedgerEntry, "ts">): void;
61
63
  export declare function readLedger(): LedgerEntry[];
package/dist/ledger.js CHANGED
@@ -84,16 +84,32 @@ export function statePath() {
84
84
  export function ledgerPath() {
85
85
  return join(dirname(statePath()), ".context-doctor-ledger.jsonl");
86
86
  }
87
+ /** Longest string field kept in a ledger entry (a model name, a session id). */
88
+ export const LEDGER_STRING_MAX = 100;
89
+ /** On rotation: what is kept, by bytes and by entries; longer lines are folded, not kept. */
90
+ const LEDGER_ROTATE_AT = 256 * 1024;
91
+ const LEDGER_KEEP_BYTES = 128 * 1024;
92
+ const LEDGER_KEEP_LINES = 500;
93
+ const LEDGER_LINE_MAX = 4 * 1024;
94
+ /** A string field as the ledger keeps it: no control characters, at most LEDGER_STRING_MAX. */
95
+ function cap(v) {
96
+ if (typeof v !== "string")
97
+ return undefined;
98
+ // eslint-disable-next-line no-control-regex
99
+ const clean = v.replace(/[\u0000-\u001f\u007f-\u009f]/g, "");
100
+ return clean.length > LEDGER_STRING_MAX ? clean.slice(0, LEDGER_STRING_MAX) : clean;
101
+ }
87
102
  export function recordLedger(entry) {
88
103
  const path = ledgerPath();
89
104
  try {
90
105
  // Claude-Desktop-only machines have no ~/.claude — create it so their
91
106
  // optimize events count in `context-doctor report` too.
92
107
  mkdirSync(dirname(path), { recursive: true });
93
- // Cap growth: past ~256KB keep the most recent 500 entries — but fold the
94
- // dropped ones into a rollup first, or every lifetime total in the reports
95
- // silently shrinks the moment a heavy user crosses the cap.
96
- if (existsSync(path) && statSync(path).size > 256 * 1024) {
108
+ // Cap growth by bytes, not lines: past 256KB keep the newest entries that
109
+ // fit 128KB (at most 500), and fold the rest into a rollup first, or every
110
+ // lifetime total in the reports silently shrinks the moment a heavy user
111
+ // crosses the cap. A line too long to be a real entry is folded, never kept.
112
+ if (existsSync(path) && statSync(path).size > LEDGER_ROTATE_AT) {
97
113
  const lines = readFileSync(path, "utf8").trimEnd().split("\n");
98
114
  const parse = (line) => {
99
115
  try {
@@ -103,13 +119,34 @@ export function recordLedger(entry) {
103
119
  return [];
104
120
  }
105
121
  };
106
- const kept = lines.slice(-500);
107
- const dropped = lines.slice(0, -500).flatMap(parse);
122
+ const keptAt = new Set();
123
+ let bytes = 0;
124
+ for (let i = lines.length - 1; i >= 0 && keptAt.size < LEDGER_KEEP_LINES; i--) {
125
+ const n = Buffer.byteLength(lines[i]) + 1;
126
+ if (n > LEDGER_LINE_MAX)
127
+ continue;
128
+ if (bytes + n > LEDGER_KEEP_BYTES)
129
+ break;
130
+ keptAt.add(i);
131
+ bytes += n;
132
+ }
133
+ const kept = lines.filter((_, i) => keptAt.has(i));
134
+ const dropped = lines.filter((_, i) => !keptAt.has(i)).flatMap(parse);
108
135
  const carried = foldTotals(dropped);
109
136
  const rollup = { ts: Date.now(), ev: "rollup", carried };
110
137
  writeFileSync(path, [JSON.stringify(rollup), ...kept].join("\n") + "\n");
111
138
  }
112
- appendFileSync(path, JSON.stringify({ ts: Date.now(), ...entry }) + "\n");
139
+ const clean = { ...entry };
140
+ for (const k of ["model", "sid", "cv", "app"]) {
141
+ if (k in clean) {
142
+ const v = cap(clean[k]);
143
+ if (v === undefined)
144
+ delete clean[k];
145
+ else
146
+ clean[k] = v;
147
+ }
148
+ }
149
+ appendFileSync(path, JSON.stringify({ ts: Date.now(), ...clean }) + "\n");
113
150
  }
114
151
  catch {
115
152
  /* best-effort */
package/dist/lens.d.ts ADDED
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Two costs the other reports do not show: the output side of the bill, and
3
+ * polling.
4
+ *
5
+ * - Output and reasoning: what share of a session's (or a period's) cost is
6
+ * output tokens, and of those the reasoning (Claude's
7
+ * `output_tokens_details.thinking_tokens`, Codex's
8
+ * `reasoning_output_tokens`), per model. Only shown: whether shorter output
9
+ * keeps quality is a question for `context-doctor ab`, so no saving is
10
+ * claimed here.
11
+ * - Polling: a tool call identical to the one before it (same tool, same
12
+ * input), as a wait-and-check loop makes (BashOutput on one shell, Codex's
13
+ * `wait` or `write_stdin` with nothing to write, `sleep 30 && tail log`).
14
+ * Each repeat is a whole request that re-reads the context; it is priced
15
+ * at that request's billed cost.
16
+ */
17
+ export interface ModelOutput {
18
+ model: string;
19
+ requests: number;
20
+ outputTokens: number;
21
+ /** Reasoning (thinking) tokens within the output, where the usage records them. */
22
+ reasoningTokens: number;
23
+ outputUsd: number;
24
+ totalUsd: number;
25
+ }
26
+ export interface PollStats {
27
+ /** Calls identical to the call before them. */
28
+ repeats: number;
29
+ /** The requests that issued them, at list price. */
30
+ usd: number;
31
+ /** Context those requests re-read. */
32
+ contextTokens: number;
33
+ byTool: Array<{
34
+ tool: string;
35
+ repeats: number;
36
+ usd: number;
37
+ }>;
38
+ }
39
+ export interface Lens {
40
+ sessions: number;
41
+ byModel: ModelOutput[];
42
+ polls: PollStats;
43
+ totalUsd: number;
44
+ }
45
+ /** One session transcript (Claude Code or Codex). */
46
+ export declare function sessionLens(path: string, since?: number): Lens;
47
+ /** Every Claude Code (and, unless `claudeOnly`, Codex) session touched in the last `days`. */
48
+ export declare function lensOverSessions(days?: number, opts?: {
49
+ claudeOnly?: boolean;
50
+ paths?: string[];
51
+ now?: number;
52
+ }): Lens;
53
+ /** Lines for `session` and `savings` (within 60 columns), or none when nothing is priced. */
54
+ export declare function renderLens(l: Lens, opts?: {
55
+ heading?: boolean;
56
+ }): string[];
package/dist/lens.js ADDED
@@ -0,0 +1,213 @@
1
+ /**
2
+ * Two costs the other reports do not show: the output side of the bill, and
3
+ * polling.
4
+ *
5
+ * - Output and reasoning: what share of a session's (or a period's) cost is
6
+ * output tokens, and of those the reasoning (Claude's
7
+ * `output_tokens_details.thinking_tokens`, Codex's
8
+ * `reasoning_output_tokens`), per model. Only shown: whether shorter output
9
+ * keeps quality is a question for `context-doctor ab`, so no saving is
10
+ * claimed here.
11
+ * - Polling: a tool call identical to the one before it (same tool, same
12
+ * input), as a wait-and-check loop makes (BashOutput on one shell, Codex's
13
+ * `wait` or `write_stdin` with nothing to write, `sleep 30 && tail log`).
14
+ * Each repeat is a whole request that re-reads the context; it is priced
15
+ * at that request's billed cost.
16
+ */
17
+ import { forEachLine, listSessions, replyCounter } from "./session.js";
18
+ import { openAIUsage, pricingFor, usageCost } from "./pricing.js";
19
+ import { formatTokens, realModel } from "./tokens.js";
20
+ const num = (v) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0);
21
+ class Acc {
22
+ models = new Map();
23
+ polls = new Map();
24
+ pollContext = 0;
25
+ sessions = 0;
26
+ request(model, u, reasoning) {
27
+ const name = model ?? "unknown";
28
+ const m = this.models.get(name) ?? { model: name, requests: 0, outputTokens: 0, reasoningTokens: 0, outputUsd: 0, totalUsd: 0 };
29
+ const price = pricingFor(model);
30
+ const cost = price ? usageCost(u, price) : undefined;
31
+ m.requests++;
32
+ m.outputTokens += num(u.output_tokens);
33
+ m.reasoningTokens += Math.min(num(u.output_tokens), reasoning);
34
+ m.outputUsd += cost?.outputUsd ?? 0;
35
+ m.totalUsd += cost?.totalUsd ?? 0;
36
+ this.models.set(name, m);
37
+ return cost?.totalUsd ?? 0;
38
+ }
39
+ poll(tool, usd, context) {
40
+ const p = this.polls.get(tool) ?? { repeats: 0, usd: 0 };
41
+ p.repeats++;
42
+ p.usd += usd;
43
+ this.polls.set(tool, p);
44
+ this.pollContext += context;
45
+ }
46
+ result() {
47
+ const byModel = [...this.models.values()].filter((m) => m.requests > 0).sort((a, b) => b.totalUsd - a.totalUsd);
48
+ const byTool = [...this.polls.entries()].map(([tool, p]) => ({ tool, ...p })).sort((a, b) => b.usd - a.usd || b.repeats - a.repeats);
49
+ return {
50
+ sessions: this.sessions,
51
+ byModel,
52
+ polls: { repeats: byTool.reduce((n, t) => n + t.repeats, 0), usd: byTool.reduce((n, t) => n + t.usd, 0), contextTokens: this.pollContext, byTool },
53
+ totalUsd: byModel.reduce((n, m) => n + m.totalUsd, 0),
54
+ };
55
+ }
56
+ }
57
+ /** A call's identity: its tool and its exact input. */
58
+ const callKey = (name, input) => `${name}\u0000${typeof input === "string" ? input : JSON.stringify(input ?? null)}`;
59
+ function scanClaude(path, acc, since, runRows) {
60
+ const sighting = replyCounter(runRows);
61
+ const costOf = new Map();
62
+ let prevCall;
63
+ forEachLine(path, (line) => {
64
+ const prompt = line.includes('"type":"user"') && !line.includes('"tool_result"');
65
+ if (!prompt && !line.includes('"usage"') && !line.includes('"tool_use"'))
66
+ return;
67
+ let e;
68
+ try {
69
+ e = JSON.parse(line);
70
+ }
71
+ catch {
72
+ return;
73
+ }
74
+ // A prompt the user typed between two identical calls makes the second a
75
+ // new request, not a poll (the same check, asked for again).
76
+ if (e?.type === "user" && !e.isSidechain && !e.isMeta && !(Array.isArray(e.message?.content) && e.message.content.some((b) => b?.type === "tool_result"))) {
77
+ prevCall = undefined;
78
+ return;
79
+ }
80
+ if (e?.type !== "assistant" || e.isSidechain || !e.message)
81
+ return;
82
+ const m = e.message;
83
+ const at = Date.parse(String(e.timestamp ?? ""));
84
+ const inPeriod = !(Number.isFinite(at) && at < since);
85
+ const id = typeof m.id === "string" ? m.id : undefined;
86
+ if (m.usage && realModel(m.model)) {
87
+ const seen = sighting(e);
88
+ if (seen === "new" && inPeriod) {
89
+ const u = m.usage;
90
+ const usd = acc.request(realModel(m.model), u, num(u.output_tokens_details?.thinking_tokens));
91
+ if (id)
92
+ costOf.set(id, { usd, context: num(u.input_tokens) + num(u.cache_read_input_tokens) + num(u.cache_creation_input_tokens) });
93
+ }
94
+ }
95
+ if (!Array.isArray(m.content))
96
+ return;
97
+ for (const b of m.content) {
98
+ if (b?.type !== "tool_use" || typeof b.name !== "string")
99
+ continue;
100
+ const key = callKey(b.name, b.input);
101
+ if (key === prevCall && inPeriod) {
102
+ // One reply's cost once, however many identical calls it holds.
103
+ const c = id ? costOf.get(id) : undefined;
104
+ acc.poll(b.name, c?.usd ?? 0, c?.context ?? 0);
105
+ if (id && c)
106
+ costOf.set(id, { usd: 0, context: 0 });
107
+ }
108
+ prevCall = key;
109
+ }
110
+ });
111
+ }
112
+ function scanCodex(path, acc, since) {
113
+ let model;
114
+ let prevCall;
115
+ /** Repeats waiting for the token_count of the response that made them. */
116
+ let pending = [];
117
+ let total = -1;
118
+ forEachLine(path, (line) => {
119
+ let e;
120
+ try {
121
+ e = JSON.parse(line);
122
+ }
123
+ catch {
124
+ return;
125
+ }
126
+ const p = e?.payload;
127
+ if (!p || typeof p !== "object")
128
+ return;
129
+ const at = Date.parse(String(e.timestamp ?? ""));
130
+ const inPeriod = !(Number.isFinite(at) && at < since);
131
+ if (e.type === "turn_context" && typeof p.model === "string")
132
+ model = p.model;
133
+ if (e.type === "response_item" && p.type === "message" && p.role === "user")
134
+ prevCall = undefined;
135
+ if (e.type === "response_item" && (p.type === "function_call" || p.type === "custom_tool_call" || p.type === "local_shell_call")) {
136
+ const name = String(p.name ?? (p.type === "local_shell_call" ? "shell" : p.type));
137
+ const key = callKey(name, p.arguments ?? p.input ?? p.action);
138
+ if (key === prevCall && inPeriod)
139
+ pending.push(name);
140
+ prevCall = key;
141
+ }
142
+ if (e.type === "event_msg" && p.type === "token_count") {
143
+ const last = p.info?.last_token_usage;
144
+ const runTotal = num(p.info?.total_token_usage?.total_tokens);
145
+ if (!last || !(num(last.input_tokens) > 0) || (runTotal !== 0 && runTotal === total))
146
+ return;
147
+ total = runTotal;
148
+ if (!inPeriod) {
149
+ pending = [];
150
+ return;
151
+ }
152
+ const u = openAIUsage(last);
153
+ const usd = acc.request(model, u, num(last.reasoning_output_tokens));
154
+ pending.forEach((name, i) => acc.poll(name, i === 0 ? usd : 0, i === 0 ? num(last.input_tokens) : 0));
155
+ pending = [];
156
+ }
157
+ });
158
+ }
159
+ /** One session transcript (Claude Code or Codex). */
160
+ export function sessionLens(path, since = 0) {
161
+ const acc = new Acc();
162
+ acc.sessions = 1;
163
+ if (/[\\/]\.codex[\\/]/.test(path) || /rollout-[^\\/]*\.jsonl$/.test(path))
164
+ scanCodex(path, acc, since);
165
+ else
166
+ scanClaude(path, acc, since);
167
+ return acc.result();
168
+ }
169
+ /** Every Claude Code (and, unless `claudeOnly`, Codex) session touched in the last `days`. */
170
+ export function lensOverSessions(days = 30, opts = {}) {
171
+ const since = (opts.now ?? Date.now()) - days * 86_400_000;
172
+ const files = opts.paths ?? listSessions(10_000).filter((s) => s.modifiedAt.getTime() >= since && (s.path.includes(".claude") || (!opts.claudeOnly && s.project === "codex"))).map((s) => s.path);
173
+ const acc = new Acc();
174
+ const runRows = new Set();
175
+ for (const f of files) {
176
+ try {
177
+ if (/[\\/]\.codex[\\/]/.test(f))
178
+ scanCodex(f, acc, since);
179
+ else
180
+ scanClaude(f, acc, since, runRows);
181
+ acc.sessions++;
182
+ }
183
+ catch { /* skip */ }
184
+ }
185
+ return acc.result();
186
+ }
187
+ const pct = (x) => `${Math.round(x * 100)}%`;
188
+ const usd = (n) => (n >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : n >= 0.01 ? `$${n.toFixed(2)}` : n > 0 ? "<$0.01" : "$0");
189
+ /** A tool as people say it: an MCP tool by its own name, without the server prefix. */
190
+ const toolName = (t) => /^mcp__.+?__(.+)$/.exec(t)?.[1] ?? t;
191
+ /** Lines for `session` and `savings` (within 60 columns), or none when nothing is priced. */
192
+ export function renderLens(l, opts = {}) {
193
+ const priced = l.byModel.filter((m) => m.totalUsd > 0);
194
+ if (!priced.length)
195
+ return [];
196
+ const out = [];
197
+ if (opts.heading !== false)
198
+ out.push("Output and polling (at list price; shown, not a lever)");
199
+ const all = priced.reduce((a, m) => ({ out: a.out + m.outputUsd, total: a.total + m.totalUsd, tokens: a.tokens + m.outputTokens, reasoning: a.reasoning + m.reasoningTokens }), { out: 0, total: 0, tokens: 0, reasoning: 0 });
200
+ out.push(` Output: ${pct(all.out / all.total)} of ${usd(all.total)}` + (all.reasoning > 0 ? `; reasoning ${pct(all.reasoning / Math.max(1, all.tokens))} of output tokens.` : "."));
201
+ if (priced.length > 1) {
202
+ for (const m of priced.slice(0, 4)) {
203
+ out.push(` ${m.model.slice(0, 20).padEnd(20)} ${pct(m.outputUsd / m.totalUsd).padStart(4)} of ${usd(m.totalUsd).padStart(7)}${m.reasoningTokens > 0 ? `, reasoning ${pct(m.reasoningTokens / Math.max(1, m.outputTokens))}` : ""}`);
204
+ }
205
+ }
206
+ if (l.polls.repeats > 0) {
207
+ const top = l.polls.byTool.slice(0, 3).map((t) => `${toolName(t.tool).slice(0, 18)} ${t.repeats}`).join(", ");
208
+ out.push(` ${l.polls.repeats} repeated identical tool call${l.polls.repeats === 1 ? "" : "s"} (polling) re-read`);
209
+ out.push(` ~${formatTokens(l.polls.contextTokens)} tokens: ${usd(l.polls.usd)}. Most: ${top}.`);
210
+ }
211
+ out.push(" Does shorter output keep quality? context-doctor ab");
212
+ return out;
213
+ }