context-doctor 0.48.0 → 0.49.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 +15 -14
- package/dist/abclaude.js +1 -1
- package/dist/budget.d.ts +5 -2
- package/dist/budget.js +21 -7
- package/dist/cache.js +3 -3
- package/dist/cachemisses.d.ts +3 -0
- package/dist/cachemisses.js +8 -0
- package/dist/cachettl.js +6 -2
- package/dist/ccost.d.ts +160 -0
- package/dist/ccost.js +304 -0
- package/dist/cli.js +135 -32
- package/dist/cline.d.ts +41 -0
- package/dist/cline.js +174 -0
- package/dist/coldresume.d.ts +11 -0
- package/dist/coldresume.js +3 -3
- package/dist/coldreturns.d.ts +145 -0
- package/dist/coldreturns.js +282 -0
- package/dist/compactcost.d.ts +10 -4
- package/dist/compactcost.js +12 -7
- package/dist/compactwindow.js +2 -2
- package/dist/copilotusage.d.ts +78 -0
- package/dist/copilotusage.js +193 -0
- package/dist/doctor.d.ts +6 -0
- package/dist/doctor.js +17 -4
- package/dist/fix.d.ts +28 -2
- package/dist/fix.js +49 -5
- package/dist/limits.d.ts +222 -14
- package/dist/limits.js +684 -33
- package/dist/mcp.js +1 -1
- package/dist/mcpdefer.d.ts +47 -0
- package/dist/mcpdefer.js +91 -0
- package/dist/mod/api.d.ts +72 -2
- package/dist/mod/api.js +5 -1
- package/dist/mod/logic.d.ts +281 -0
- package/dist/mod/logic.js +336 -0
- package/dist/mod/register.d.ts +35 -2
- package/dist/mod/register.js +283 -6
- package/dist/modmeasure.d.ts +6 -4
- package/dist/modmeasure.js +8 -4
- package/dist/opencode.d.ts +57 -0
- package/dist/opencode.js +234 -0
- package/dist/orgrates.d.ts +7 -0
- package/dist/orgrates.js +19 -0
- package/dist/overhead.d.ts +3 -0
- package/dist/overhead.js +5 -1
- package/dist/pricing.d.ts +59 -2
- package/dist/pricing.js +125 -10
- package/dist/proxy.d.ts +8 -1
- package/dist/proxy.js +13 -1
- package/dist/savings.d.ts +5 -1
- package/dist/savings.js +11 -5
- package/dist/scan.d.ts +3 -1
- package/dist/scan.js +8 -1
- package/dist/sessionprice.d.ts +5 -0
- package/dist/sessionprice.js +5 -1
- package/dist/spend.d.ts +86 -3
- package/dist/spend.js +240 -23
- package/dist/spendplace.d.ts +40 -0
- package/dist/spendplace.js +93 -0
- package/dist/spendteam.d.ts +160 -0
- package/dist/spendteam.js +286 -0
- package/dist/starts.d.ts +106 -0
- package/dist/starts.js +406 -0
- package/dist/statusline.d.ts +2 -2
- package/dist/statusline.js +2 -2
- package/dist/subagentmodel.js +9 -7
- package/dist/subagentpay.d.ts +31 -2
- package/dist/subagentpay.js +232 -68
- package/dist/subagents.js +3 -3
- package/dist/tasks.js +3 -2
- package/dist/tooloutput.js +5 -5
- package/dist/usagepane.d.ts +77 -0
- package/dist/usagepane.js +287 -0
- package/package.json +1 -1
package/dist/opencode.js
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenCode's record of what it sent: each assistant message's `tokens`.
|
|
3
|
+
* Checked 2026-11-15 against ccusage's OpenCode loader (rust/adapters/opencode)
|
|
4
|
+
* and its docs. OpenCode keeps its data in `${XDG_DATA_HOME:-~/.local/share}/opencode`
|
|
5
|
+
* (`OPENCODE_DATA_DIR`, a comma list, instead), in one of three places:
|
|
6
|
+
*
|
|
7
|
+
* - `storage/message/<sessionID>/<messageID>.json` (before its SQLite store):
|
|
8
|
+
* `{id, sessionID, role, modelID, providerID, time: {created}, tokens:
|
|
9
|
+
* {input, output, reasoning, cache: {read, write}, total}, path: {cwd, root}}`.
|
|
10
|
+
* - `opencode.db`, table `message`: the same object in `data`.
|
|
11
|
+
* - `opencode.db`, table `session_message` (its v2 store): rows of `type`
|
|
12
|
+
* "assistant" or "compaction" (a compaction is billed apart; only a
|
|
13
|
+
* "completed" one), the model as `model: {id, providerID}`. A forked
|
|
14
|
+
* session starts with a copy of its parent's rows, new ids and the same
|
|
15
|
+
* `seq`; `session_v2.fork_boundary` says up to which (its "through" or
|
|
16
|
+
* "before" a parent message): those copies are not counted again.
|
|
17
|
+
*
|
|
18
|
+
* `tokens.input` is the uncached input; reasoning bills as output, and a
|
|
19
|
+
* `total` above the parts is output too (as ccusage counts it). A message
|
|
20
|
+
* on OpenCode's `claude-agent` provider ran inside Claude Code, whose own
|
|
21
|
+
* transcript `spend` already reads: not counted here. The same message in
|
|
22
|
+
* the JSON files and the database (a store that was migrated) is counted once.
|
|
23
|
+
*/
|
|
24
|
+
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
25
|
+
import { homedir } from "node:os";
|
|
26
|
+
import { join } from "node:path";
|
|
27
|
+
import { queryRows, SqliteUnavailableError } from "./cursor.js";
|
|
28
|
+
/** OpenCode's data folders: $OPENCODE_DATA_DIR's (when `home` is this user's), else <XDG data>/opencode. */
|
|
29
|
+
export function opencodeDataDirs(home = homedir()) {
|
|
30
|
+
const own = home === homedir();
|
|
31
|
+
if (own && process.env.OPENCODE_DATA_DIR)
|
|
32
|
+
return process.env.OPENCODE_DATA_DIR.split(",").map((s) => s.trim()).filter(Boolean);
|
|
33
|
+
return [join(own && process.env.XDG_DATA_HOME ? process.env.XDG_DATA_HOME : join(home, ".local", "share"), "opencode")];
|
|
34
|
+
}
|
|
35
|
+
const num = (v) => {
|
|
36
|
+
const n = typeof v === "string" ? Number(v) : v;
|
|
37
|
+
return typeof n === "number" && Number.isFinite(n) && n > 0 ? n : 0;
|
|
38
|
+
};
|
|
39
|
+
const text = (v) => (typeof v === "string" && v.trim() ? v.trim() : undefined);
|
|
40
|
+
const parse = (v) => {
|
|
41
|
+
if (typeof v !== "string")
|
|
42
|
+
return v;
|
|
43
|
+
try {
|
|
44
|
+
return JSON.parse(v);
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return undefined;
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
/** The counts of one message's `tokens`, as billed: reasoning, and a total above the parts, as output. */
|
|
51
|
+
export function opencodeTokens(t) {
|
|
52
|
+
if (!t || typeof t !== "object")
|
|
53
|
+
return undefined;
|
|
54
|
+
const input = num(t.input), read = num(t.cache?.read), write = num(t.cache?.write);
|
|
55
|
+
let output = num(t.output) + num(t.reasoning);
|
|
56
|
+
const missing = num(t.total) - (input + read + write + output);
|
|
57
|
+
if (missing > 0)
|
|
58
|
+
output += missing;
|
|
59
|
+
return input + read + write + output > 0 ? { input, read, write, output } : undefined;
|
|
60
|
+
}
|
|
61
|
+
/** A message object (a JSON file's, or a database row's `data`) as a call; undefined when it is not one. */
|
|
62
|
+
function fromMessage(m, id, session, created) {
|
|
63
|
+
if (!m || typeof m !== "object")
|
|
64
|
+
return undefined;
|
|
65
|
+
if (m.role !== undefined && m.role !== "assistant")
|
|
66
|
+
return undefined;
|
|
67
|
+
const tokens = opencodeTokens(m.tokens);
|
|
68
|
+
if (!tokens)
|
|
69
|
+
return undefined;
|
|
70
|
+
const model = text(m.model?.id) ?? text(m.model?.modelID) ?? text(m.modelID);
|
|
71
|
+
const provider = text(m.model?.providerID) ?? text(m.providerID);
|
|
72
|
+
const ts = num(m.time?.created) || num(created);
|
|
73
|
+
if (!ts)
|
|
74
|
+
return undefined;
|
|
75
|
+
const c = { id, ts, session, ...tokens };
|
|
76
|
+
if (model)
|
|
77
|
+
c.model = model;
|
|
78
|
+
if (provider)
|
|
79
|
+
c.provider = provider;
|
|
80
|
+
if (text(m.path?.cwd))
|
|
81
|
+
c.cwd = m.path.cwd;
|
|
82
|
+
if (text(m.path?.root) && m.path.root !== "/")
|
|
83
|
+
c.root = m.path.root;
|
|
84
|
+
return c;
|
|
85
|
+
}
|
|
86
|
+
/** The JSON files' messages written since `since`. */
|
|
87
|
+
function jsonCalls(dir, since, out, dirs) {
|
|
88
|
+
const sessionsRoot = join(dir, "storage", "session");
|
|
89
|
+
if (existsSync(sessionsRoot)) {
|
|
90
|
+
for (const project of safeList(sessionsRoot))
|
|
91
|
+
for (const f of safeList(join(sessionsRoot, project))) {
|
|
92
|
+
if (!f.endsWith(".json"))
|
|
93
|
+
continue;
|
|
94
|
+
try {
|
|
95
|
+
const s = JSON.parse(readFileSync(join(sessionsRoot, project, f), "utf8"));
|
|
96
|
+
if (text(s?.id) && text(s?.directory))
|
|
97
|
+
dirs.set(s.id, s.directory);
|
|
98
|
+
}
|
|
99
|
+
catch { /* not a session */ }
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
const root = join(dir, "storage", "message");
|
|
103
|
+
for (const session of safeList(root)) {
|
|
104
|
+
const folder = join(root, session);
|
|
105
|
+
for (const f of safeList(folder)) {
|
|
106
|
+
if (!f.endsWith(".json"))
|
|
107
|
+
continue;
|
|
108
|
+
const file = join(folder, f);
|
|
109
|
+
try {
|
|
110
|
+
if (statSync(file).mtimeMs < since)
|
|
111
|
+
continue;
|
|
112
|
+
const m = JSON.parse(readFileSync(file, "utf8"));
|
|
113
|
+
const id = text(m?.id) ?? f.slice(0, -5);
|
|
114
|
+
const c = fromMessage(m, id, text(m?.sessionID) ?? session);
|
|
115
|
+
if (c && !out.has(id))
|
|
116
|
+
out.set(id, c);
|
|
117
|
+
}
|
|
118
|
+
catch { /* unreadable: skipped */ }
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
function safeList(dir) {
|
|
123
|
+
try {
|
|
124
|
+
return readdirSync(dir);
|
|
125
|
+
}
|
|
126
|
+
catch {
|
|
127
|
+
return [];
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
/** A query that may fail on an older schema (no such table or column): undefined. SQLite missing altogether still throws. */
|
|
131
|
+
function tryRows(db, sql) {
|
|
132
|
+
try {
|
|
133
|
+
return queryRows(db, sql);
|
|
134
|
+
}
|
|
135
|
+
catch (e) {
|
|
136
|
+
if (e instanceof SqliteUnavailableError)
|
|
137
|
+
throw e;
|
|
138
|
+
return undefined;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
const rows = (db, sql) => tryRows(db, sql) ?? [];
|
|
142
|
+
/**
|
|
143
|
+
* A WHERE on `time_created` for rows since `since`, a day early, when the
|
|
144
|
+
* column is there and holds milliseconds (its largest value); else none,
|
|
145
|
+
* and the message's own time decides.
|
|
146
|
+
*/
|
|
147
|
+
function windowClause(db, table, since) {
|
|
148
|
+
const max = tryRows(db, `SELECT MAX(time_created) AS m FROM ${table}`)?.[0]?.m;
|
|
149
|
+
return typeof max === "number" && max > 1e11 ? ` AND time_created >= ${Math.floor(since) - 86_400_000}` : "";
|
|
150
|
+
}
|
|
151
|
+
/** For each forked v2 session, the last `seq` that is a copy of its parent's history. */
|
|
152
|
+
function forkCutoffs(db) {
|
|
153
|
+
const cut = new Map();
|
|
154
|
+
for (const f of rows(db, "SELECT id, fork_session_id AS parent, fork_boundary AS boundary FROM session_v2 WHERE fork_session_id IS NOT NULL AND fork_boundary IS NOT NULL")) {
|
|
155
|
+
const b = parse(f.boundary);
|
|
156
|
+
const parent = text(f.parent), mid = text(b?.messageID);
|
|
157
|
+
if (!text(f.id) || !parent || !mid || (b.type !== "through" && b.type !== "before"))
|
|
158
|
+
continue;
|
|
159
|
+
const esc = (s) => s.replace(/'/g, "''");
|
|
160
|
+
const at = rows(db, `SELECT seq FROM session_message WHERE session_id = '${esc(parent)}' AND id = '${esc(mid)}' LIMIT 1`)[0]?.seq;
|
|
161
|
+
if (typeof at !== "number")
|
|
162
|
+
continue;
|
|
163
|
+
if (b.type === "through")
|
|
164
|
+
cut.set(f.id, at);
|
|
165
|
+
else {
|
|
166
|
+
const before = rows(db, `SELECT MAX(seq) AS seq FROM session_message WHERE session_id = '${esc(parent)}' AND seq < ${at}`)[0]?.seq;
|
|
167
|
+
if (typeof before === "number")
|
|
168
|
+
cut.set(f.id, before);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return cut;
|
|
172
|
+
}
|
|
173
|
+
/** The database's messages since `since` (both tables), and each session's folder. */
|
|
174
|
+
function dbCalls(db, since, out, dirs) {
|
|
175
|
+
for (const table of ["session", "session_v2"])
|
|
176
|
+
for (const s of rows(db, `SELECT id, directory FROM ${table}`))
|
|
177
|
+
if (text(s.id) && text(s.directory))
|
|
178
|
+
dirs.set(s.id, s.directory);
|
|
179
|
+
// Only the fields read, projected in SQL: a row's data can be large.
|
|
180
|
+
const fields = "json_extract(data, '$.role') AS role, json_extract(data, '$.modelID') AS modelID, json_extract(data, '$.providerID') AS providerID, json_extract(data, '$.model') AS model, json_extract(data, '$.tokens') AS tokens, json_extract(data, '$.time.created') AS created, json_extract(data, '$.path') AS path";
|
|
181
|
+
for (const r of rows(db, `SELECT id, session_id, ${fields} FROM message WHERE 1${windowClause(db, "message", since)}`)) {
|
|
182
|
+
const c = fromMessage({ role: r.role, modelID: r.modelID, providerID: r.providerID, model: parse(r.model), tokens: parse(r.tokens), time: { created: r.created }, path: parse(r.path) }, String(r.id), String(r.session_id));
|
|
183
|
+
if (c && !out.has(c.id))
|
|
184
|
+
out.set(c.id, c);
|
|
185
|
+
}
|
|
186
|
+
const cut = forkCutoffs(db);
|
|
187
|
+
const win = windowClause(db, "session_message", since);
|
|
188
|
+
const v2sql = (seq) => `SELECT id, session_id, type, time_created${seq ? ", seq" : ""}, json_extract(data, '$.status') AS status, ${fields} FROM session_message WHERE type IN ('assistant', 'compaction')${win}`;
|
|
189
|
+
for (const r of tryRows(db, v2sql(true)) ?? rows(db, v2sql(false))) {
|
|
190
|
+
const session = String(r.session_id);
|
|
191
|
+
const c0 = cut.get(session);
|
|
192
|
+
if (c0 !== undefined && typeof r.seq === "number" && r.seq <= c0)
|
|
193
|
+
continue;
|
|
194
|
+
const compaction = r.type === "compaction";
|
|
195
|
+
if (compaction && r.status !== "completed")
|
|
196
|
+
continue;
|
|
197
|
+
const c = fromMessage({ modelID: r.modelID, providerID: r.providerID, model: parse(r.model), tokens: parse(r.tokens), time: { created: r.created }, path: parse(r.path) }, String(r.id), session, num(r.time_created));
|
|
198
|
+
if (!c || out.has(c.id))
|
|
199
|
+
continue;
|
|
200
|
+
if (compaction)
|
|
201
|
+
c.compaction = true;
|
|
202
|
+
out.set(c.id, c);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* Every OpenCode model call between `since` and `until`, each once, less
|
|
207
|
+
* those on the claude-agent provider. `sqlite`: false when an opencode.db
|
|
208
|
+
* was there and this runtime cannot read SQLite.
|
|
209
|
+
*/
|
|
210
|
+
export function opencodeCalls(since, until = Infinity, home = homedir()) {
|
|
211
|
+
const out = new Map();
|
|
212
|
+
const dirs = new Map();
|
|
213
|
+
let sqlite = true;
|
|
214
|
+
for (const dir of opencodeDataDirs(home)) {
|
|
215
|
+
if (!existsSync(dir))
|
|
216
|
+
continue;
|
|
217
|
+
const db = join(dir, "opencode.db");
|
|
218
|
+
if (existsSync(db)) {
|
|
219
|
+
try {
|
|
220
|
+
dbCalls(db, since, out, dirs);
|
|
221
|
+
}
|
|
222
|
+
catch (e) {
|
|
223
|
+
if (e instanceof SqliteUnavailableError)
|
|
224
|
+
sqlite = false;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
jsonCalls(dir, since, out, dirs);
|
|
228
|
+
}
|
|
229
|
+
const calls = [...out.values()].filter((c) => c.ts >= since && c.ts <= until && c.provider !== "claude-agent");
|
|
230
|
+
for (const c of calls)
|
|
231
|
+
if (!c.cwd && dirs.has(c.session))
|
|
232
|
+
c.cwd = dirs.get(c.session);
|
|
233
|
+
return { calls: calls.sort((a, b) => a.ts - b.ts), sqlite };
|
|
234
|
+
}
|
package/dist/orgrates.d.ts
CHANGED
|
@@ -56,6 +56,13 @@ export declare function readOrgRatesFrom(paths: string[]): OrgRates | undefined;
|
|
|
56
56
|
* stat of the managed folder and its drop-in folder, once.
|
|
57
57
|
*/
|
|
58
58
|
export declare function orgRates(env?: NodeJS.ProcessEnv): OrgRates | undefined;
|
|
59
|
+
/**
|
|
60
|
+
* `fn` with the organization's rates read once: every request a report
|
|
61
|
+
* prices asks for them (rateCard), and reading the two variables that move
|
|
62
|
+
* them is most of that (285 ms of a 1.5 s `subagents` on the author's
|
|
63
|
+
* machine, about 150k requests). Nothing in a report's run changes them.
|
|
64
|
+
*/
|
|
65
|
+
export declare function withOrgRatesHeld<T>(fn: () => T): T;
|
|
59
66
|
/** Forget what orgRates read (tests that rewrite a managed file in place). */
|
|
60
67
|
export declare function resetOrgRates(): void;
|
|
61
68
|
/** The row that prices `model`: its exact key first, then its Claude model's. */
|
package/dist/orgrates.js
CHANGED
|
@@ -119,11 +119,30 @@ let cache;
|
|
|
119
119
|
* stat of the managed folder and its drop-in folder, once.
|
|
120
120
|
*/
|
|
121
121
|
export function orgRates(env = process.env) {
|
|
122
|
+
if (held && env === process.env)
|
|
123
|
+
return held.rates;
|
|
122
124
|
const k = `${env.CONTEXT_DOCTOR_NO_MANAGED_SETTINGS ?? ""}\u0000${env.CLAUDE_CODE_MANAGED_SETTINGS_PATH ?? ""}`;
|
|
123
125
|
if (cache?.env !== k)
|
|
124
126
|
cache = { env: k, rates: readOrgRates(env) };
|
|
125
127
|
return cache.rates;
|
|
126
128
|
}
|
|
129
|
+
let held;
|
|
130
|
+
/**
|
|
131
|
+
* `fn` with the organization's rates read once: every request a report
|
|
132
|
+
* prices asks for them (rateCard), and reading the two variables that move
|
|
133
|
+
* them is most of that (285 ms of a 1.5 s `subagents` on the author's
|
|
134
|
+
* machine, about 150k requests). Nothing in a report's run changes them.
|
|
135
|
+
*/
|
|
136
|
+
export function withOrgRatesHeld(fn) {
|
|
137
|
+
const was = held;
|
|
138
|
+
held = { rates: orgRates() };
|
|
139
|
+
try {
|
|
140
|
+
return fn();
|
|
141
|
+
}
|
|
142
|
+
finally {
|
|
143
|
+
held = was;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
127
146
|
/** Forget what orgRates read (tests that rewrite a managed file in place). */
|
|
128
147
|
export function resetOrgRates() {
|
|
129
148
|
cache = undefined;
|
package/dist/overhead.d.ts
CHANGED
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
* priced per month from the user's own request and cold-start counts.
|
|
16
16
|
*/
|
|
17
17
|
import { type McpServerConfig, type McpServerSize, type McpUsage } from "./mcpschema.js";
|
|
18
|
+
import { type StartsReport } from "./starts.js";
|
|
18
19
|
export type Agent = "Claude Code" | "Codex" | "Cursor" | "Gemini CLI";
|
|
19
20
|
export interface MemoryFile {
|
|
20
21
|
agent: Agent;
|
|
@@ -53,6 +54,8 @@ export interface OverheadReport {
|
|
|
53
54
|
files: MemoryFile[];
|
|
54
55
|
findings: OverheadFinding[];
|
|
55
56
|
mcp: McpSection;
|
|
57
|
+
/** Each session's and subagent's first request, per entrypoint and subagent type, priced across the period (starts.ts). */
|
|
58
|
+
starts?: StartsReport;
|
|
56
59
|
}
|
|
57
60
|
export interface McpSection {
|
|
58
61
|
configs: McpServerConfig[];
|
package/dist/overhead.js
CHANGED
|
@@ -28,6 +28,7 @@ import { claudeDir } from "./claudedir.js";
|
|
|
28
28
|
import { mcpjsonServerApproved } from "./prune.js";
|
|
29
29
|
import { REQUEST_ROWS } from "./coldresume.js";
|
|
30
30
|
import { rowsOf } from "./scan.js";
|
|
31
|
+
import { measureStarts, renderStarts } from "./starts.js";
|
|
31
32
|
const TTL_MS = 3_600_000;
|
|
32
33
|
const CLAUDE = "claude-opus-5"; // Claude's tokenizer ratios; the model only picks the provider here.
|
|
33
34
|
function readText(path) {
|
|
@@ -421,7 +422,8 @@ export function overheadReport(opts = {}) {
|
|
|
421
422
|
// MCP usage comes from Claude Code transcripts only (the tool-name scheme is theirs).
|
|
422
423
|
const claudePaths = opts.paths?.filter((p) => !isGeminiChat(p) && !/[\\/]\.codex[\\/]/.test(p));
|
|
423
424
|
const mcp = { configs: claudeMcpConfigs(cwd, home), usage: mcpUsage(opts.days ?? 30, claudePaths, tick("mcp")) };
|
|
424
|
-
|
|
425
|
+
const starts = measureStarts({ days: opts.days ?? 30, paths: claudePaths, cwd, home });
|
|
426
|
+
return { cwd, baseline, baselines, files, findings: overheadFindings(files, baselines), mcp, starts };
|
|
425
427
|
}
|
|
426
428
|
/**
|
|
427
429
|
* Launch each configured server and size its tool definitions, then add the
|
|
@@ -486,6 +488,8 @@ export function renderOverhead(r, home = homedir()) {
|
|
|
486
488
|
? ` Each 1k tokens ~${formatUsd(o.usdPerKPerMonth)} a month (${o.requests.toLocaleString("en-US")} requests, ${o.coldStarts.toLocaleString("en-US")} cold starts, ${o.model} ${priceBasis().replace(/^at /, "")}).`
|
|
487
489
|
: ""));
|
|
488
490
|
}
|
|
491
|
+
if (r.starts)
|
|
492
|
+
out.push(...renderStarts(r.starts));
|
|
489
493
|
out.push(...renderMcp(r));
|
|
490
494
|
out.push("", "Memory files loaded in this directory", "─".repeat(56));
|
|
491
495
|
if (r.files.length === 0)
|
package/dist/pricing.d.ts
CHANGED
|
@@ -48,7 +48,8 @@ export declare const CACHE_WRITE_OPENAI_12H = 2.5;
|
|
|
48
48
|
* keeps per request (the budget's, a session's price) were priced by the
|
|
49
49
|
* table of the context-doctor that read them: under another table (an
|
|
50
50
|
* upgrade that corrected a price, as 0.46 did Fable 5.2's) they are stale
|
|
51
|
-
* and read again, not carried to the period's end.
|
|
51
|
+
* and read again, not carried to the period's end. So are those priced by
|
|
52
|
+
* rules that changed what a request costs (BILLING_RULES).
|
|
52
53
|
*/
|
|
53
54
|
export declare function priceTableKey(): string;
|
|
54
55
|
/** A model's list row, as the page lists it today (no tier, mode or date applied). */
|
|
@@ -101,6 +102,8 @@ export interface RecordedUsage {
|
|
|
101
102
|
web_fetch_requests?: unknown;
|
|
102
103
|
code_execution_requests?: unknown;
|
|
103
104
|
} | null;
|
|
105
|
+
/** The request's inner calls, each with its own tokens (and `model` where it differs): see extraIterations. */
|
|
106
|
+
iterations?: unknown;
|
|
104
107
|
}
|
|
105
108
|
export interface UsageCost {
|
|
106
109
|
/** Uncached input. */
|
|
@@ -231,9 +234,63 @@ export declare function addModifiers(a: Modifiers, b: Readonly<Modifiers>): Modi
|
|
|
231
234
|
export declare function priceChange(model?: string): {
|
|
232
235
|
on: string;
|
|
233
236
|
then?: ModelPricing;
|
|
237
|
+
routes?: string;
|
|
234
238
|
} | undefined;
|
|
235
|
-
/** "
|
|
239
|
+
/** "ended" for a row whose price stops with no price published after it (a promotion), "changed" otherwise: what a report's short label says. */
|
|
240
|
+
export declare function priceEndWord(model?: string): "ended" | "changed";
|
|
241
|
+
/**
|
|
242
|
+
* Said for the models priced past their row's date: which price ended,
|
|
243
|
+
* when, and the price each request was priced at instead, an estimate
|
|
244
|
+
* either way (a scheduled price can be called off, a promotion extended).
|
|
245
|
+
*/
|
|
236
246
|
export declare function priceChangedText(models: Array<[model: string, on: string]>): string;
|
|
247
|
+
/**
|
|
248
|
+
* One iteration of a request's `usage.iterations` that the request's
|
|
249
|
+
* top-level usage does not count: billed on top of it, at its own model's
|
|
250
|
+
* rates (`model`: the iteration's, else the request's).
|
|
251
|
+
*/
|
|
252
|
+
export interface ExtraIteration {
|
|
253
|
+
/** "advisor_message", "message" (an attempt a fallback replaced), "fallback_message", "compaction"... */
|
|
254
|
+
type: string;
|
|
255
|
+
model?: string;
|
|
256
|
+
usage: RecordedUsage;
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* The iterations of a request billed beyond its top-level usage. The API
|
|
260
|
+
* itemizes one request's inner calls in `usage.iterations`, each with its
|
|
261
|
+
* own tokens (and `model` where it differs), and its top-level usage counts
|
|
262
|
+
* only some of them:
|
|
263
|
+
* - the advisor tool: top-level usage is the sum of the executor's
|
|
264
|
+
* iterations ("message"); each `advisor_message` is billed on top, at the
|
|
265
|
+
* advisor model's rates (Anthropic, "Advisor tool", Usage and billing);
|
|
266
|
+
* - server-side fallbacks: top-level usage is the attempt that produced the
|
|
267
|
+
* message, the last; each earlier attempt (the declined model's, its own
|
|
268
|
+
* `model`) is billed on top (refusals and fallback: "usage.iterations is
|
|
269
|
+
* the per-attempt source of truth"). On the author's machine 34 replies
|
|
270
|
+
* carry one: claude-fable-5 declined after reading 294k tokens, and
|
|
271
|
+
* claude-opus-4-8 answered.
|
|
272
|
+
* Which is which is checked on the tokens, never assumed from the types:
|
|
273
|
+
* the iterations other than the advisor's must add up to the top-level
|
|
274
|
+
* prompt (input, cache reads and writes), or the last of them must equal
|
|
275
|
+
* it. A shape that is neither has only its advisor iterations added (never
|
|
276
|
+
* in the top-level, whatever the rest), so nothing is counted twice.
|
|
277
|
+
* Empty for the common request, one iteration that is the request itself.
|
|
278
|
+
*/
|
|
279
|
+
export declare function extraIterations(usage: RecordedUsage | undefined | null): ExtraIteration[];
|
|
280
|
+
/**
|
|
281
|
+
* What a request cost with the iterations its top-level usage leaves out
|
|
282
|
+
* (extraIterations), each priced by requestCost at its own model and the
|
|
283
|
+
* request's time: the parts and modifiers added up, `rates` the request's
|
|
284
|
+
* own. `extra` is what those iterations added; absent when none. Undefined
|
|
285
|
+
* when the request's own model has no price.
|
|
286
|
+
*/
|
|
287
|
+
export declare function billedCost(model: string | undefined, usage: RecordedUsage | undefined | null, at?: number): (RequestCost & {
|
|
288
|
+
extra?: {
|
|
289
|
+
usd: number;
|
|
290
|
+
iterations: number;
|
|
291
|
+
unpriced: number;
|
|
292
|
+
};
|
|
293
|
+
}) | undefined;
|
|
237
294
|
/**
|
|
238
295
|
* OpenAI usage, in any of its shapes, as RecordedUsage: Responses
|
|
239
296
|
* (`input_tokens`, `input_tokens_details.cached_tokens`, `cache_write_tokens`
|
package/dist/pricing.js
CHANGED
|
@@ -233,16 +233,19 @@ const PRICING = [
|
|
|
233
233
|
[/gemini.*pro/i, rate(1.25, 5, 0.31), FALLBACK],
|
|
234
234
|
];
|
|
235
235
|
let tableKey;
|
|
236
|
+
/** Bumped when what a request costs changes beyond the table: 2, the iterations its top-level usage leaves out (billedCost); 3, a compaction's context read from the cache however long the idle (compactcost.ts). */
|
|
237
|
+
const BILLING_RULES = 3;
|
|
236
238
|
/**
|
|
237
239
|
* A fingerprint of this table and its billing constants. Dollars a ledger
|
|
238
240
|
* keeps per request (the budget's, a session's price) were priced by the
|
|
239
241
|
* table of the context-doctor that read them: under another table (an
|
|
240
242
|
* upgrade that corrected a price, as 0.46 did Fable 5.2's) they are stale
|
|
241
|
-
* and read again, not carried to the period's end.
|
|
243
|
+
* and read again, not carried to the period's end. So are those priced by
|
|
244
|
+
* rules that changed what a request costs (BILLING_RULES).
|
|
242
245
|
*/
|
|
243
246
|
export function priceTableKey() {
|
|
244
247
|
tableKey ??= createHash("sha1")
|
|
245
|
-
.update(JSON.stringify([PRICING.map(([re, p, b]) => [re.source, re.flags, p, b ?? null]), CACHE_WRITE_5M, CACHE_WRITE_1H, CACHE_WRITE_OPENAI_30M, CACHE_WRITE_OPENAI_12H, US_ONLY_MULTIPLIER, WEB_SEARCH_USD]))
|
|
248
|
+
.update(JSON.stringify([PRICING.map(([re, p, b]) => [re.source, re.flags, p, b ?? null]), CACHE_WRITE_5M, CACHE_WRITE_1H, CACHE_WRITE_OPENAI_30M, CACHE_WRITE_OPENAI_12H, US_ONLY_MULTIPLIER, WEB_SEARCH_USD, BILLING_RULES]))
|
|
246
249
|
.digest("hex")
|
|
247
250
|
.slice(0, 12);
|
|
248
251
|
return tableKey;
|
|
@@ -459,17 +462,129 @@ export function addModifiers(a, b) {
|
|
|
459
462
|
*/
|
|
460
463
|
export function priceChange(model) {
|
|
461
464
|
const b = row(model)?.[2];
|
|
462
|
-
return b?.changes ? { on: b.changes, ...(b.then ? { then: b.then } : {}) } : undefined;
|
|
465
|
+
return b?.changes ? { on: b.changes, ...(b.then ? { then: b.then } : {}), ...(b.routes ? { routes: b.routes } : {}) } : undefined;
|
|
463
466
|
}
|
|
464
|
-
/** "
|
|
467
|
+
/** "ended" for a row whose price stops with no price published after it (a promotion), "changed" otherwise: what a report's short label says. */
|
|
468
|
+
export function priceEndWord(model) {
|
|
469
|
+
const c = priceChange(model);
|
|
470
|
+
return c && !c.then && !c.routes ? "ended" : "changed";
|
|
471
|
+
}
|
|
472
|
+
/** "$4 in / $20 out per M": a price as the notes quote it. */
|
|
473
|
+
const perMText = (p) => `$${+p.inputPerM.toFixed(4)} in / $${+p.outputPerM.toFixed(4)} out per M`;
|
|
474
|
+
/**
|
|
475
|
+
* What a request priced past its row's date (rateCard's `changedOn`) was
|
|
476
|
+
* priced at, in words: the price the page said would follow, the model it
|
|
477
|
+
* is billed as from then, or, when the page named nothing (gpt-5.6-sol's
|
|
478
|
+
* promotion), the price that ended. Never silent about which.
|
|
479
|
+
*/
|
|
480
|
+
function priceUsedText(model, on) {
|
|
481
|
+
const b = row(model)?.[2];
|
|
482
|
+
if (b?.routes && b.changes !== undefined && b.changes < on) {
|
|
483
|
+
// Billed as another model whose own price changed later: that model's change is the one in force.
|
|
484
|
+
return `${model} is billed as ${b.routes} from ${b.changes}; ${priceUsedText(b.routes, on)}`;
|
|
485
|
+
}
|
|
486
|
+
if (b?.routes)
|
|
487
|
+
return `${model}'s price ended on ${on}: from then it is billed as ${b.routes}, priced at ${b.routes}'s rates`;
|
|
488
|
+
if (b?.then)
|
|
489
|
+
return `${model}'s price changed on ${on}: priced at the price the page said would follow (${perMText(b.then)})`;
|
|
490
|
+
const was = pricingFor(model);
|
|
491
|
+
return `${model}'s price ended on ${on} and no later price is published: priced at the one that ended${was ? ` (${perMText(was)})` : ""}`;
|
|
492
|
+
}
|
|
493
|
+
/**
|
|
494
|
+
* Said for the models priced past their row's date: which price ended,
|
|
495
|
+
* when, and the price each request was priced at instead, an estimate
|
|
496
|
+
* either way (a scheduled price can be called off, a promotion extended).
|
|
497
|
+
*/
|
|
465
498
|
export function priceChangedText(models) {
|
|
466
|
-
const
|
|
467
|
-
for (const [m, on] of models)
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
499
|
+
const seen = new Map();
|
|
500
|
+
for (const [m, on] of models)
|
|
501
|
+
if (!seen.has(`${m}\u0000${on}`))
|
|
502
|
+
seen.set(`${m}\u0000${on}`, priceUsedText(m, on));
|
|
503
|
+
const parts = [...seen.values()];
|
|
504
|
+
const open = [...seen.keys()].some((k) => { const [m] = k.split("\u0000"); const b = row(m)?.[2]; return !b?.then && !b?.routes; });
|
|
505
|
+
return `${parts.slice(0, 3).join("; ")}${parts.length > 3 ? `; and ${parts.length - 3} more` : ""}; an estimate${open ? "; a newer context-doctor may know the price that followed" : ""}`;
|
|
506
|
+
}
|
|
507
|
+
const promptOf = (u) => count(u?.input_tokens) + count(u?.cache_read_input_tokens) + count(u?.cache_creation_input_tokens);
|
|
508
|
+
/**
|
|
509
|
+
* The iterations of a request billed beyond its top-level usage. The API
|
|
510
|
+
* itemizes one request's inner calls in `usage.iterations`, each with its
|
|
511
|
+
* own tokens (and `model` where it differs), and its top-level usage counts
|
|
512
|
+
* only some of them:
|
|
513
|
+
* - the advisor tool: top-level usage is the sum of the executor's
|
|
514
|
+
* iterations ("message"); each `advisor_message` is billed on top, at the
|
|
515
|
+
* advisor model's rates (Anthropic, "Advisor tool", Usage and billing);
|
|
516
|
+
* - server-side fallbacks: top-level usage is the attempt that produced the
|
|
517
|
+
* message, the last; each earlier attempt (the declined model's, its own
|
|
518
|
+
* `model`) is billed on top (refusals and fallback: "usage.iterations is
|
|
519
|
+
* the per-attempt source of truth"). On the author's machine 34 replies
|
|
520
|
+
* carry one: claude-fable-5 declined after reading 294k tokens, and
|
|
521
|
+
* claude-opus-4-8 answered.
|
|
522
|
+
* Which is which is checked on the tokens, never assumed from the types:
|
|
523
|
+
* the iterations other than the advisor's must add up to the top-level
|
|
524
|
+
* prompt (input, cache reads and writes), or the last of them must equal
|
|
525
|
+
* it. A shape that is neither has only its advisor iterations added (never
|
|
526
|
+
* in the top-level, whatever the rest), so nothing is counted twice.
|
|
527
|
+
* Empty for the common request, one iteration that is the request itself.
|
|
528
|
+
*/
|
|
529
|
+
export function extraIterations(usage) {
|
|
530
|
+
const its = usage?.iterations;
|
|
531
|
+
if (!Array.isArray(its) || its.length < 2)
|
|
532
|
+
return [];
|
|
533
|
+
const list = its.filter((t) => !!t && typeof t === "object" && !Array.isArray(t));
|
|
534
|
+
const extra = (t) => ({
|
|
535
|
+
type: typeof t.type === "string" ? t.type : "message",
|
|
536
|
+
...(typeof t.model === "string" && t.model ? { model: t.model } : {}),
|
|
537
|
+
usage: {
|
|
538
|
+
input_tokens: count(t.input_tokens), cache_read_input_tokens: count(t.cache_read_input_tokens), cache_creation_input_tokens: count(t.cache_creation_input_tokens), output_tokens: count(t.output_tokens),
|
|
539
|
+
...(t.cache_creation && typeof t.cache_creation === "object" ? { cache_creation: t.cache_creation } : {}),
|
|
540
|
+
// The request's own modifiers: where it ran (US-only) and its speed hold for every call in it.
|
|
541
|
+
...(usage?.inference_geo === "us" ? { inference_geo: "us" } : {}),
|
|
542
|
+
...(usage?.speed === "fast" ? { speed: "fast" } : {}),
|
|
543
|
+
},
|
|
544
|
+
});
|
|
545
|
+
const advisor = list.filter((t) => t.type === "advisor_message");
|
|
546
|
+
const rest = list.filter((t) => t.type !== "advisor_message");
|
|
547
|
+
const top = promptOf(usage);
|
|
548
|
+
if (rest.length <= 1 || rest.reduce((n, t) => n + promptOf(t), 0) === top)
|
|
549
|
+
return advisor.map(extra);
|
|
550
|
+
if (promptOf(rest[rest.length - 1]) === top)
|
|
551
|
+
return [...rest.slice(0, -1), ...advisor].map(extra);
|
|
552
|
+
return advisor.map(extra);
|
|
553
|
+
}
|
|
554
|
+
/**
|
|
555
|
+
* What a request cost with the iterations its top-level usage leaves out
|
|
556
|
+
* (extraIterations), each priced by requestCost at its own model and the
|
|
557
|
+
* request's time: the parts and modifiers added up, `rates` the request's
|
|
558
|
+
* own. `extra` is what those iterations added; absent when none. Undefined
|
|
559
|
+
* when the request's own model has no price.
|
|
560
|
+
*/
|
|
561
|
+
export function billedCost(model, usage, at = Date.now()) {
|
|
562
|
+
const c = requestCost(model, usage, at);
|
|
563
|
+
const extras = extraIterations(usage);
|
|
564
|
+
if (!c || !extras.length)
|
|
565
|
+
return c;
|
|
566
|
+
const out = { ...c, modifiers: { ...c.modifiers }, extra: { usd: 0, iterations: 0, unpriced: 0 } };
|
|
567
|
+
for (const x of extras) {
|
|
568
|
+
const e = requestCost(x.model ?? model, x.usage, at);
|
|
569
|
+
if (!e) {
|
|
570
|
+
out.extra.unpriced++;
|
|
571
|
+
continue;
|
|
572
|
+
}
|
|
573
|
+
out.inputUsd += e.inputUsd;
|
|
574
|
+
out.writeUsd += e.writeUsd;
|
|
575
|
+
out.readUsd += e.readUsd;
|
|
576
|
+
out.outputUsd += e.outputUsd;
|
|
577
|
+
out.promptUsd += e.promptUsd;
|
|
578
|
+
out.totalUsd += e.totalUsd;
|
|
579
|
+
addModifiers(out.modifiers, e.modifiers);
|
|
580
|
+
out.extra.usd += e.totalUsd;
|
|
581
|
+
out.extra.iterations++;
|
|
582
|
+
if (e.estimated)
|
|
583
|
+
out.estimated = true;
|
|
584
|
+
if (e.changedOn && !out.changedOn)
|
|
585
|
+
out.changedOn = e.changedOn;
|
|
471
586
|
}
|
|
472
|
-
return
|
|
587
|
+
return out;
|
|
473
588
|
}
|
|
474
589
|
/**
|
|
475
590
|
* OpenAI usage, in any of its shapes, as RecordedUsage: Responses
|
package/dist/proxy.d.ts
CHANGED
|
@@ -72,11 +72,18 @@ export interface ProxyOptions extends OptimizeOptions {
|
|
|
72
72
|
* than taking the proxy (and every agent behind it) down.
|
|
73
73
|
*/
|
|
74
74
|
maxBodyBytes?: number;
|
|
75
|
+
/**
|
|
76
|
+
* Where the plan's rate-limit readings from Anthropic's replies go (the
|
|
77
|
+
* `anthropic-ratelimit-unified-5h-*` / `-7d-*` headers a claude.ai sign-in
|
|
78
|
+
* gets): the limits ledger `context-doctor limits` reads, by default.
|
|
79
|
+
* CONTEXT_DOCTOR_NO_LIMITS_LOG=1 keeps none.
|
|
80
|
+
*/
|
|
81
|
+
limitsLogPath?: string;
|
|
75
82
|
}
|
|
76
83
|
/** Default request body cap: far above any real request (a 1M-token context is ~4 MB of JSON, images aside). */
|
|
77
84
|
export declare const DEFAULT_MAX_BODY_BYTES: number;
|
|
78
85
|
/** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
|
|
79
|
-
export declare const PROXY_VERSION = "0.
|
|
86
|
+
export declare const PROXY_VERSION = "0.49.0";
|
|
80
87
|
/**
|
|
81
88
|
* Remove a leading `/t/<token>` from a request path, or return undefined when
|
|
82
89
|
* the prefix is absent or the token differs. The comparison is constant time
|
package/dist/proxy.js
CHANGED
|
@@ -25,7 +25,7 @@ import { makeGuard, refusal } from "./httpguard.js";
|
|
|
25
25
|
/** Default request body cap: far above any real request (a 1M-token context is ~4 MB of JSON, images aside). */
|
|
26
26
|
export const DEFAULT_MAX_BODY_BYTES = 100 * 1024 * 1024;
|
|
27
27
|
/** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
|
|
28
|
-
export const PROXY_VERSION = "0.
|
|
28
|
+
export const PROXY_VERSION = "0.49.0";
|
|
29
29
|
/** Connection-level headers that must not be forwarded. */
|
|
30
30
|
const SKIP_REQUEST_HEADERS = new Set(["host", "content-length", "connection", "transfer-encoding", "accept-encoding", "expect"]);
|
|
31
31
|
const SKIP_RESPONSE_HEADERS = new Set(["content-length", "content-encoding", "transfer-encoding", "connection"]);
|
|
@@ -566,6 +566,18 @@ export function startProxy(opts = {}) {
|
|
|
566
566
|
upstream = new Response(text, { status: upstream.status, statusText: upstream.statusText, headers: upstream.headers });
|
|
567
567
|
}
|
|
568
568
|
}
|
|
569
|
+
// The plan's windows, as Claude Code reads them from the same headers:
|
|
570
|
+
// into the limits ledger, after the reply is on its way (recordLimits
|
|
571
|
+
// writes only a change, at most once a minute, and never throws).
|
|
572
|
+
if (upstreamBase === (opts.anthropicUpstream ?? "https://api.anthropic.com") && process.env.CONTEXT_DOCTOR_NO_LIMITS_LOG !== "1" && (upstream.headers.has("anthropic-ratelimit-unified-7d-utilization") || upstream.headers.has("anthropic-ratelimit-unified-5h-utilization"))) {
|
|
573
|
+
const got = upstream.headers;
|
|
574
|
+
// Loaded on first use: limits.ts reads transcripts and imports this module's version.
|
|
575
|
+
void import("./limits.js").then((m) => {
|
|
576
|
+
const rl = m.rateLimitsFromHeaders((n) => got.get(n));
|
|
577
|
+
if (rl)
|
|
578
|
+
m.recordLimits(rl, Date.now(), opts.limitsLogPath, "proxy");
|
|
579
|
+
}).catch(() => undefined);
|
|
580
|
+
}
|
|
569
581
|
console.error(`[context-doctor] ${req.method} ${logUrl(url)} → ${upstream.status} in ${Date.now() - upstreamStart}ms | ${note}` +
|
|
570
582
|
(stats.tokensSaved > 0 ? ` | session total: ${formatTokens(stats.tokensSaved)} tokens ≈ ${formatUsd(stats.estUsdSaved)} saved` : ""));
|
|
571
583
|
res.statusCode = upstream.status;
|
package/dist/savings.d.ts
CHANGED
|
@@ -90,7 +90,11 @@ export interface CompactWindowLine {
|
|
|
90
90
|
nowPerWeek: number;
|
|
91
91
|
isCurrent: boolean;
|
|
92
92
|
}
|
|
93
|
-
export declare function renderSavings(r: SavingsReport, autopilotOn?: boolean, cw?: CompactWindowLine, missLines?: string[], limitLines?: string[], lensLines?: string[]
|
|
93
|
+
export declare function renderSavings(r: SavingsReport, autopilotOn?: boolean, cw?: CompactWindowLine, missLines?: string[], limitLines?: string[], lensLines?: string[], keepWarm?: {
|
|
94
|
+
hours: number;
|
|
95
|
+
netUsd: number;
|
|
96
|
+
pingUsd: number;
|
|
97
|
+
}): string;
|
|
94
98
|
/**
|
|
95
99
|
* `savings --share`: a few lines people can paste or screenshot. Totals only:
|
|
96
100
|
* no project names, paths or session ids, so sharing it leaks nothing.
|