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
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* GitHub Copilot CLI's own record of what it sent: `session.usage_record`
|
|
3
|
+
* events in `~/.copilot/session-state/<session>/events.jsonl` (or
|
|
4
|
+
* `$COPILOT_HOME`), one per model call. Checked 2026-11-15 against the
|
|
5
|
+
* readers that parse them (GitHub's own agent-radar collector in
|
|
6
|
+
* github/awesome-copilot, qualitylayer, tokscale, agentsview) and
|
|
7
|
+
* ccusage#2069 (1,142 records and no shutdown in one user's sessions).
|
|
8
|
+
* GitHub documents none of it; the shape:
|
|
9
|
+
*
|
|
10
|
+
* {"type":"session.usage_record","id":"…","timestamp":"…","data":{"usage":{
|
|
11
|
+
* "model":"claude-opus-4.6-1m","inputTokens":…,"outputTokens":…,
|
|
12
|
+
* "cacheReadTokens":…,"cacheWriteTokens":…,"reasoningTokens":…,
|
|
13
|
+
* "cost":1,"duration":…,"apiCallId":"…","isByok":false,
|
|
14
|
+
* "accounting":{"sourceSessionId":"…","usageId":"…"},
|
|
15
|
+
* "copilotUsage":{"totalNanoAiu":…}}}}
|
|
16
|
+
*
|
|
17
|
+
* - `inputTokens` holds the cached tokens too (read and written): the
|
|
18
|
+
* uncached input is what is left after both.
|
|
19
|
+
* - `reasoningTokens` is part of `outputTokens`, not added again.
|
|
20
|
+
* - `cost` is the request's premium-request multiplier (1, or 14 for a
|
|
21
|
+
* premium model), not dollars. `copilotUsage.totalNanoAiu` is the AI
|
|
22
|
+
* credits it used, in billionths: one credit is $0.01.
|
|
23
|
+
* - The same call can be written twice (Copilot CLI 1.0.108: "count each
|
|
24
|
+
* newly recorded model call once, even when its usage event is received
|
|
25
|
+
* again"): one call is its accounting id, else its API call id, else the
|
|
26
|
+
* event's id.
|
|
27
|
+
* - A compaction (`session.compaction_complete`, `compactionTokensUsed`) is
|
|
28
|
+
* a model call of its own, unless a usage record already names its
|
|
29
|
+
* request.
|
|
30
|
+
* - Where it ran: `session.start` (and `session.resume`) carry
|
|
31
|
+
* `data.context` with `cwd`, `gitRoot`, `branch` and `repository`.
|
|
32
|
+
*
|
|
33
|
+
* Sessions from Copilot CLI versions that write no usage records (only
|
|
34
|
+
* cumulative `session.shutdown` totals) are not read: their per-resume
|
|
35
|
+
* figures cannot be told apart reliably (ccusage's notes on it run a page).
|
|
36
|
+
*/
|
|
37
|
+
import { existsSync, readdirSync, statSync } from "node:fs";
|
|
38
|
+
import { homedir } from "node:os";
|
|
39
|
+
import { join } from "node:path";
|
|
40
|
+
import { pick, rowsOf } from "./scan.js";
|
|
41
|
+
/** Copilot's home: $COPILOT_HOME when set (and `home` is this user's), else <home>/.copilot. */
|
|
42
|
+
export function copilotDataDir(home = homedir()) {
|
|
43
|
+
return home === homedir() && process.env.COPILOT_HOME ? process.env.COPILOT_HOME : join(home, ".copilot");
|
|
44
|
+
}
|
|
45
|
+
const num = (v) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0);
|
|
46
|
+
const text = (v) => (typeof v === "string" && v.trim() ? v.trim() : undefined);
|
|
47
|
+
/** "claude-opus-4.6-1m" -> "claude-opus-4.6"; "<provider uuid>/gpt-x" -> "gpt-x". */
|
|
48
|
+
export function copilotModel(raw) {
|
|
49
|
+
return raw.replace(/^[0-9a-f]{8}-[0-9a-f-]{27}\//i, "").replace(/-1m(?:-internal)?$/i, "");
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* What `spend` takes from a Copilot CLI session: each usage record's
|
|
53
|
+
* numbers and ids, each compaction's, and each start's context. No message
|
|
54
|
+
* text, no tool call.
|
|
55
|
+
*/
|
|
56
|
+
export const COPILOT_USAGE_ROWS = {
|
|
57
|
+
id: "copilot-usage.1",
|
|
58
|
+
init: () => ({}),
|
|
59
|
+
line(line, row, out) {
|
|
60
|
+
if (!line.includes('"session.usage_record"') && !line.includes('"session.compaction_complete"') && !line.includes('"session.start"') && !line.includes('"session.resume"'))
|
|
61
|
+
return;
|
|
62
|
+
let e;
|
|
63
|
+
try {
|
|
64
|
+
e = row();
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
const d = e?.data;
|
|
70
|
+
if (!d || typeof d !== "object")
|
|
71
|
+
return;
|
|
72
|
+
if (e.type === "session.start" || e.type === "session.resume") {
|
|
73
|
+
const c = d.context;
|
|
74
|
+
if (c && typeof c === "object")
|
|
75
|
+
out.push({ k: "ctx", ...pick(c, ["cwd", "gitRoot", "branch", "repository"]) });
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
const ts = typeof e.timestamp === "string" ? e.timestamp : "";
|
|
79
|
+
if (e.type === "session.usage_record") {
|
|
80
|
+
const u = d.usage;
|
|
81
|
+
if (!u || typeof u !== "object")
|
|
82
|
+
return;
|
|
83
|
+
const acc = u.accounting && typeof u.accounting === "object" ? u.accounting : {};
|
|
84
|
+
out.push({
|
|
85
|
+
k: "u", ts, ...(typeof e.id === "string" ? { id: e.id } : {}),
|
|
86
|
+
...pick(u, ["model", "inputTokens", "outputTokens", "cacheReadTokens", "cacheWriteTokens", "cost", "apiCallId", "isByok"]),
|
|
87
|
+
...(text(acc.sourceSessionId) && text(acc.usageId) ? { acc: `${acc.sourceSessionId}\u0000${acc.usageId}`, usageId: acc.usageId } : {}),
|
|
88
|
+
...(typeof u.copilotUsage?.totalNanoAiu === "number" ? { nano: u.copilotUsage.totalNanoAiu } : {}),
|
|
89
|
+
...(u.provider && typeof u.provider === "object" && typeof u.provider.kind === "string" ? { provider: u.provider.kind } : {}),
|
|
90
|
+
});
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
if (e.type === "session.compaction_complete" && d.compactionTokensUsed && typeof d.compactionTokensUsed === "object") {
|
|
94
|
+
const u = d.compactionTokensUsed;
|
|
95
|
+
out.push({
|
|
96
|
+
k: "c", ts, ...(typeof e.id === "string" ? { id: e.id } : {}), ...(text(d.requestId) ? { requestId: d.requestId } : {}),
|
|
97
|
+
...(text(d.behaviorModelId) ? { behavior: d.behaviorModelId } : {}),
|
|
98
|
+
...pick(u, ["model", "inputTokens", "outputTokens", "cacheReadTokens", "cacheWriteTokens"]),
|
|
99
|
+
...(typeof u.copilotUsage?.totalNanoAiu === "number" ? { nano: u.copilotUsage.totalNanoAiu } : {}),
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
},
|
|
103
|
+
};
|
|
104
|
+
/** A record's call, priced by nobody yet. */
|
|
105
|
+
function call(r, session, ctx) {
|
|
106
|
+
const ts = Date.parse(r.ts);
|
|
107
|
+
const model = text(r.model) ?? text(r.behavior);
|
|
108
|
+
if (!Number.isFinite(ts))
|
|
109
|
+
return undefined;
|
|
110
|
+
const read = num(r.cacheReadTokens), write = num(r.cacheWriteTokens);
|
|
111
|
+
const c = { ts, session, model: model ? copilotModel(model) : "unknown", input: Math.max(0, num(r.inputTokens) - read - write), read, write, output: num(r.outputTokens) };
|
|
112
|
+
if (c.input + c.read + c.write + c.output === 0 && !num(r.nano))
|
|
113
|
+
return undefined;
|
|
114
|
+
if (typeof r.nano === "number" && r.nano >= 0)
|
|
115
|
+
c.credits = r.nano / 1e9;
|
|
116
|
+
if (typeof r.cost === "number" && r.cost >= 0)
|
|
117
|
+
c.premium = r.cost;
|
|
118
|
+
if (r.isByok === true || (typeof r.provider === "string" && r.provider !== "copilot" && r.provider !== "loki"))
|
|
119
|
+
c.byok = true;
|
|
120
|
+
if (ctx.cwd)
|
|
121
|
+
c.cwd = ctx.cwd;
|
|
122
|
+
if (ctx.gitRoot)
|
|
123
|
+
c.gitRoot = ctx.gitRoot;
|
|
124
|
+
if (ctx.branch)
|
|
125
|
+
c.branch = ctx.branch;
|
|
126
|
+
return c;
|
|
127
|
+
}
|
|
128
|
+
/** The model calls of one session's events file between `since` and `until`, each once. Throws when it cannot be read. */
|
|
129
|
+
export function copilotFileCalls(file, session, since, until = Infinity) {
|
|
130
|
+
const calls = new Map();
|
|
131
|
+
const compactions = [];
|
|
132
|
+
const named = new Set();
|
|
133
|
+
let ctx = {};
|
|
134
|
+
let anon = 0;
|
|
135
|
+
for (const r of rowsOf(file, COPILOT_USAGE_ROWS)) {
|
|
136
|
+
if (r.k === "ctx") {
|
|
137
|
+
ctx = { ...ctx, ...Object.fromEntries(Object.entries(r).filter(([k, v]) => k !== "k" && typeof v === "string")) };
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
const c = call(r, session, ctx);
|
|
141
|
+
if (r.k === "u") {
|
|
142
|
+
for (const id of [r.apiCallId, r.usageId])
|
|
143
|
+
if (text(id))
|
|
144
|
+
named.add(id);
|
|
145
|
+
if (!c)
|
|
146
|
+
continue;
|
|
147
|
+
// The same call written again replaces the first copy.
|
|
148
|
+
calls.set(r.acc ?? text(r.apiCallId) ?? text(r.id) ?? `#${anon++}`, c);
|
|
149
|
+
}
|
|
150
|
+
else if (r.k === "c" && c)
|
|
151
|
+
compactions.push([text(r.requestId), c]);
|
|
152
|
+
}
|
|
153
|
+
for (const [req, c] of compactions)
|
|
154
|
+
if (!req || !named.has(req))
|
|
155
|
+
calls.set(`compaction\u0000${req ?? anon++}`, c);
|
|
156
|
+
return [...calls.values()].filter((c) => c.ts >= since && c.ts <= until).sort((a, b) => a.ts - b.ts);
|
|
157
|
+
}
|
|
158
|
+
/** Each session's events file written since `since`: `session-state/<id>/events.jsonl`, and the flat `session-state/<id>.jsonl` some versions write. */
|
|
159
|
+
export function copilotSessionFiles(since, home = homedir()) {
|
|
160
|
+
const root = join(copilotDataDir(home), "session-state");
|
|
161
|
+
if (!existsSync(root))
|
|
162
|
+
return [];
|
|
163
|
+
const out = [];
|
|
164
|
+
let names;
|
|
165
|
+
try {
|
|
166
|
+
names = readdirSync(root);
|
|
167
|
+
}
|
|
168
|
+
catch {
|
|
169
|
+
return [];
|
|
170
|
+
}
|
|
171
|
+
for (const name of names) {
|
|
172
|
+
const flat = name.endsWith(".jsonl");
|
|
173
|
+
const file = flat ? join(root, name) : join(root, name, "events.jsonl");
|
|
174
|
+
try {
|
|
175
|
+
const st = statSync(file);
|
|
176
|
+
if (st.isFile() && st.mtimeMs >= since)
|
|
177
|
+
out.push({ file, session: flat ? name.slice(0, -6) : name });
|
|
178
|
+
}
|
|
179
|
+
catch { /* not a session */ }
|
|
180
|
+
}
|
|
181
|
+
return out;
|
|
182
|
+
}
|
|
183
|
+
/** Every Copilot CLI model call between `since` and `until`. An unreadable session is skipped. */
|
|
184
|
+
export function copilotCalls(since, until = Infinity, home = homedir()) {
|
|
185
|
+
const out = [];
|
|
186
|
+
for (const { file, session } of copilotSessionFiles(since, home)) {
|
|
187
|
+
try {
|
|
188
|
+
out.push(...copilotFileCalls(file, session, since, until));
|
|
189
|
+
}
|
|
190
|
+
catch { /* unreadable: skipped */ }
|
|
191
|
+
}
|
|
192
|
+
return out;
|
|
193
|
+
}
|
package/dist/doctor.d.ts
CHANGED
|
@@ -33,6 +33,12 @@ export declare function cacheTtlCheck(home?: string, env?: NodeJS.ProcessEnv): C
|
|
|
33
33
|
* a second doctor cheap. Undefined when nothing ran in the period; ids that
|
|
34
34
|
* are never billed (`<synthetic>`) are not named.
|
|
35
35
|
*/
|
|
36
|
+
/**
|
|
37
|
+
* Our price of Claude Code's sessions against its own figure (ccost.ts):
|
|
38
|
+
* the sessions of the last `days` that recorded one (`cost-state`), each
|
|
39
|
+
* from its start to its last record. Undefined when none did.
|
|
40
|
+
*/
|
|
41
|
+
export declare function claudeCodeCostCheck(days?: number, now?: number): Check | undefined;
|
|
36
42
|
export declare function unpricedModelsCheck(days?: number, now?: number, home?: string): Check | undefined;
|
|
37
43
|
/**
|
|
38
44
|
* Devin (Cognition): the Devin CLI, and Devin Desktop (formerly Windsurf).
|
package/dist/doctor.js
CHANGED
|
@@ -32,6 +32,8 @@ import { codexDir } from "./codexdir.js";
|
|
|
32
32
|
import { periodSpend, readBudget } from "./budget.js";
|
|
33
33
|
import { sessionPriceThresholds } from "./sessionprice.js";
|
|
34
34
|
import { claudeSpend, codexSpend } from "./spend.js";
|
|
35
|
+
import { claudeUsageFiles } from "./limits.js";
|
|
36
|
+
import { compareSessions, comparisonCheck } from "./ccost.js";
|
|
35
37
|
import { hasKnownPrice, isUnbilledModel, priceChangedText } from "./pricing.js";
|
|
36
38
|
import { managedSourcesLine, orgRatesLine } from "./orgrates.js";
|
|
37
39
|
function claudeDesktopConfigPath() {
|
|
@@ -265,7 +267,7 @@ function claudeRouteChecks(layers, plugin, now = Date.now()) {
|
|
|
265
267
|
};
|
|
266
268
|
let mod;
|
|
267
269
|
const act = modActivity();
|
|
268
|
-
const limits = act.limits ? `; limits ledger written ${ago(act.limits, now)}` : "; no limit reading yet (Claude Code hands them over on Pro and
|
|
270
|
+
const limits = act.limits ? `; limits ledger written ${ago(act.limits, now)}` : "; no limit reading yet (Claude Code hands them over on Pro, Max and Ultra plans)";
|
|
269
271
|
if (process.env.CONTEXT_DOCTOR_NO_MOD === "1") {
|
|
270
272
|
mod = { label: "Mod", status: "skip", detail: "off: CONTEXT_DOCTOR_NO_MOD=1" };
|
|
271
273
|
}
|
|
@@ -362,6 +364,17 @@ export function cacheTtlCheck(home = homedir(), env = process.env) {
|
|
|
362
364
|
* a second doctor cheap. Undefined when nothing ran in the period; ids that
|
|
363
365
|
* are never billed (`<synthetic>`) are not named.
|
|
364
366
|
*/
|
|
367
|
+
/**
|
|
368
|
+
* Our price of Claude Code's sessions against its own figure (ccost.ts):
|
|
369
|
+
* the sessions of the last `days` that recorded one (`cost-state`), each
|
|
370
|
+
* from its start to its last record. Undefined when none did.
|
|
371
|
+
*/
|
|
372
|
+
export function claudeCodeCostCheck(days = 30, now = Date.now()) {
|
|
373
|
+
const since = now - days * 86_400_000;
|
|
374
|
+
const items = claudeSpend(since, now);
|
|
375
|
+
const tops = [...new Set(claudeUsageFiles(since).filter((f) => !f.subagent).map((f) => f.top))];
|
|
376
|
+
return comparisonCheck(compareSessions(tops, items, since, now), days);
|
|
377
|
+
}
|
|
365
378
|
export function unpricedModelsCheck(days = 30, now = Date.now(), home = homedir()) {
|
|
366
379
|
const label = "Model prices";
|
|
367
380
|
const since = now - days * 86_400_000;
|
|
@@ -821,14 +834,14 @@ export async function runDoctor() {
|
|
|
821
834
|
/* settings.json unreadable is already reported by the hook check */
|
|
822
835
|
}
|
|
823
836
|
}
|
|
824
|
-
//
|
|
837
|
+
// Our price against Claude Code's own cost: its cost-state records in the transcripts, else what the plugin's mod measured.
|
|
825
838
|
try {
|
|
826
|
-
const c = costCheck();
|
|
839
|
+
const c = claudeCodeCostCheck() ?? costCheck();
|
|
827
840
|
if (c)
|
|
828
841
|
checks.push(c);
|
|
829
842
|
}
|
|
830
843
|
catch {
|
|
831
|
-
/* an unreadable ledger is no finding */
|
|
844
|
+
/* an unreadable transcript or ledger is no finding */
|
|
832
845
|
}
|
|
833
846
|
// Skill
|
|
834
847
|
const skillPath = join(claudeDir(), "skills", "context-doctor", "SKILL.md");
|
package/dist/fix.d.ts
CHANGED
|
@@ -41,13 +41,14 @@
|
|
|
41
41
|
import { type CacheTtlReport, type CurrentTtl } from "./cachettl.js";
|
|
42
42
|
import { type ClaudeCodeInstall } from "./modelswitch.js";
|
|
43
43
|
import { type ProjectPlan } from "./prune.js";
|
|
44
|
+
import { type DeferEntry } from "./mcpdefer.js";
|
|
44
45
|
import { readLedger } from "./ledger.js";
|
|
45
46
|
import { type AbStoredResult } from "./abstore.js";
|
|
46
47
|
import { type SubagentModelReplay } from "./subagentmodel.js";
|
|
47
48
|
import { type ToolOutputReplay } from "./tooloutput.js";
|
|
48
49
|
import { type ProgressSummaryEstimate } from "./progresssummaries.js";
|
|
49
50
|
import { type CodexCompactReport } from "./codexcompact.js";
|
|
50
|
-
export type FixId = "compact-window" | "cache-ttl" | "cache-ttl-subagents" | "autopilot" | "tool-search" | "prune" | "subagent-model" | "tool-output" | "codex-compact" | "progress-summaries";
|
|
51
|
+
export type FixId = "compact-window" | "cache-ttl" | "cache-ttl-subagents" | "autopilot" | "tool-search" | "prune" | "subagent-model" | "tool-output" | "codex-compact" | "progress-summaries" | "mcp-defer";
|
|
51
52
|
export interface Fix {
|
|
52
53
|
id: FixId;
|
|
53
54
|
title: string;
|
|
@@ -127,6 +128,14 @@ export interface FixInputs {
|
|
|
127
128
|
returns: number;
|
|
128
129
|
hooked: boolean;
|
|
129
130
|
};
|
|
131
|
+
/** Keeping the cache warm while away, at the cap that nets most on this history (coldreturns.ts): a per-session command of the plugin's mod, not a setting. */
|
|
132
|
+
keepWarm?: {
|
|
133
|
+
hours: number;
|
|
134
|
+
netUsd: number;
|
|
135
|
+
pingUsd: number;
|
|
136
|
+
keptWarm: number;
|
|
137
|
+
returns: number;
|
|
138
|
+
};
|
|
130
139
|
/** Every Bash and MCP result replayed at lower caps (tooloutput.ts). */
|
|
131
140
|
toolOutput?: ToolOutputReplay;
|
|
132
141
|
/** bashOutputMaxChars in the user's settings.json, or BASH_MAX_OUTPUT_LENGTH as the user set it (the setting would replace it): never overwritten. */
|
|
@@ -151,6 +160,20 @@ export interface FixInputs {
|
|
|
151
160
|
value: string;
|
|
152
161
|
where: string;
|
|
153
162
|
};
|
|
163
|
+
/**
|
|
164
|
+
* MCP servers in the user's own config whose tool definitions went whole
|
|
165
|
+
* into session and subagent starts (starts.ts), each with its share of what
|
|
166
|
+
* re-reading them cost over the period.
|
|
167
|
+
*/
|
|
168
|
+
mcpDefer?: {
|
|
169
|
+
servers: Array<{
|
|
170
|
+
name: string;
|
|
171
|
+
scope: string;
|
|
172
|
+
tokens: number;
|
|
173
|
+
usd: number;
|
|
174
|
+
}>;
|
|
175
|
+
days: number;
|
|
176
|
+
};
|
|
154
177
|
}
|
|
155
178
|
export declare const money: (n: number) => string;
|
|
156
179
|
/** " (48%)", or " (37% of subagents)" for a share of something else. */
|
|
@@ -176,6 +199,8 @@ export interface FixRecord {
|
|
|
176
199
|
oneHourShareBefore?: number;
|
|
177
200
|
/** For prune: the project folder. */
|
|
178
201
|
cwd?: string;
|
|
202
|
+
/** For mcp-defer: each alwaysLoad key it set in ~/.claude.json, and what was there before. */
|
|
203
|
+
entries?: DeferEntry[];
|
|
179
204
|
/** For subagent-model: the models the moved types' subagents ran on before the change, each one's share of their tokens (Sonnet-or-cheaper ones included): the baseline "since" compares against. */
|
|
180
205
|
modelsBefore?: Record<string, number>;
|
|
181
206
|
}
|
|
@@ -217,6 +242,7 @@ export declare function applyFix(fix: Fix, deps?: FixDeps, context?: {
|
|
|
217
242
|
oneHourShare?: number;
|
|
218
243
|
prune?: ProjectPlan;
|
|
219
244
|
modelsBefore?: Record<string, number>;
|
|
245
|
+
mcpDefer?: FixInputs["mcpDefer"];
|
|
220
246
|
}): Promise<{
|
|
221
247
|
ok: boolean;
|
|
222
248
|
lines: string[];
|
|
@@ -272,7 +298,7 @@ export declare function savedSince(records: FixRecord[], opts?: {
|
|
|
272
298
|
}): SinceResult[];
|
|
273
299
|
/** The overlap lines for the priced fixes in a plan, "a and b: why;" each. */
|
|
274
300
|
export declare function overlaps(fixes: Fix[]): string[];
|
|
275
|
-
export declare function renderFixPlan(days: number, billedUsd: number, fixes: Fix[], since: SinceResult[], command?: (s: string) => string, coldResume?: FixInputs["coldResume"], recordProblem?: string, codexBilledUsd?: number): string;
|
|
301
|
+
export declare function renderFixPlan(days: number, billedUsd: number, fixes: Fix[], since: SinceResult[], command?: (s: string) => string, coldResume?: FixInputs["coldResume"], recordProblem?: string, codexBilledUsd?: number, keepWarm?: FixInputs["keepWarm"]): string;
|
|
276
302
|
export declare function renderFixShare(days: number, billedUsd: number, fixes: Fix[], codexBilledUsd?: number): string;
|
|
277
303
|
export declare function parseFixIds(raw: string, fixes: Fix[]): {
|
|
278
304
|
ids: FixId[];
|
package/dist/fix.js
CHANGED
|
@@ -49,8 +49,9 @@ import { adviseTtl, CACHE_TTL_SINCE, estimateCacheTtl, subagentTranscripts } fro
|
|
|
49
49
|
import { compareVersions, describeInstalls } from "./modelswitch.js";
|
|
50
50
|
import { ABSENT, getPath, parseSettingsText, readSettings, removeFile, sameJson, setJsonPath, SettingsError, settingsLockPath, withLock, withSettingsLock, writeAtomic } from "./settingsedit.js";
|
|
51
51
|
import { compactWindowOverrides, effectiveEnv, processEnvWhere, settingsSources, shellSet, ttlOverrides, underClaudeCode } from "./effective.js";
|
|
52
|
-
import { tilde } from "./claudedir.js";
|
|
52
|
+
import { claudeJsonPath, tilde } from "./claudedir.js";
|
|
53
53
|
import { applyPrune, undoPrune } from "./prune.js";
|
|
54
|
+
import { applyMcpDefer, MCP_DEFER_SINCE, undoMcpDefer } from "./mcpdefer.js";
|
|
54
55
|
import { fallbackStateDir, readLedger } from "./ledger.js";
|
|
55
56
|
import { claudeDir } from "./claudedir.js";
|
|
56
57
|
import { comparisonLine } from "./abstore.js";
|
|
@@ -66,7 +67,7 @@ import { CODEX_COMPACT_KEY, CODEX_COMPACT_LIMIT, codexCompactOverrides, codexCom
|
|
|
66
67
|
* the subagent variable ahead of agent definitions there). autoCompactWindow
|
|
67
68
|
* is not in 2.1.62 and the changelog does not say when it came: not named.
|
|
68
69
|
*/
|
|
69
|
-
const SINCE = { "cache-ttl": CACHE_TTL_SINCE, "cache-ttl-subagents": CACHE_TTL_SINCE, "tool-output": BASH_OUTPUT_SINCE, "progress-summaries": PROGRESS_SUMMARIES_SINCE };
|
|
70
|
+
const SINCE = { "mcp-defer": MCP_DEFER_SINCE, "cache-ttl": CACHE_TTL_SINCE, "cache-ttl-subagents": CACHE_TTL_SINCE, "tool-output": BASH_OUTPUT_SINCE, "progress-summaries": PROGRESS_SUMMARIES_SINCE };
|
|
70
71
|
/** Below this a priced fix is not worth a setting. */
|
|
71
72
|
const MIN_USD = 1;
|
|
72
73
|
export const money = (n) => (n >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
|
|
@@ -270,6 +271,20 @@ export function planFixes(i) {
|
|
|
270
271
|
const n = ps.none.host;
|
|
271
272
|
fixes.push({ id: "progress-summaries", title: "Subagent progress summaries", basis: "", quality: "", change: "", state: "not-here", note: `your ${n} background subagent${n === 1 ? "" : "s"} ran in ${ps.hosts.map(hostName).join(" and ")}, where Claude Code writes no progress summaries: nothing to turn off` });
|
|
272
273
|
}
|
|
274
|
+
const md = i.mcpDefer?.servers.filter((s) => s.scope === "user" || s.scope === "project") ?? [];
|
|
275
|
+
if (md.length) {
|
|
276
|
+
const usd = md.reduce((t, s) => t + s.usd, 0);
|
|
277
|
+
fixes.push({
|
|
278
|
+
id: "mcp-defer",
|
|
279
|
+
title: `Keep ${md.length === 1 ? `the MCP server ${md[0].name}` : `${md.length} MCP servers`} behind tool search`,
|
|
280
|
+
...(usd > 0 ? { savedUsd: usd } : {}),
|
|
281
|
+
basis: `${md.map((s) => `${s.name} (~${k(s.tokens)} tokens)`).join(", ")} went whole into every session and subagent start that loaded ${md.length === 1 ? "it" : "them"}, re-read at each step: what that cost in ${i.mcpDefer.days} days, at most (the tool names stay)`,
|
|
282
|
+
quality: "Claude loads one of their tools through tool search when it needs it: one more step the first time in a conversation. Not measured here: applied only when named",
|
|
283
|
+
change: `${tilde(claudeJsonPath())}: "alwaysLoad": false on ${md.map((s) => s.name).join(", ")}`,
|
|
284
|
+
state: "available",
|
|
285
|
+
value: "false",
|
|
286
|
+
});
|
|
287
|
+
}
|
|
273
288
|
for (const f of fixes) {
|
|
274
289
|
const o = i.overrides?.[f.id];
|
|
275
290
|
if (o?.length && f.state === "available")
|
|
@@ -352,7 +367,7 @@ const YOURS = new Set(["subagent-model", "tool-output", "progress-summaries"]);
|
|
|
352
367
|
/** The environment variable a settings fix writes, when the shell's own value is the user's too. */
|
|
353
368
|
const SHELL_ENV = { "subagent-model": SUBAGENT_MODEL_ENV, "progress-summaries": PROGRESS_SUMMARIES_ENV };
|
|
354
369
|
/** Fixes with a quality cost not measured here: applied only when named, never by `--apply all`. */
|
|
355
|
-
const NAMED_ONLY = new Set(["subagent-model"]);
|
|
370
|
+
const NAMED_ONLY = new Set(["subagent-model", "mcp-defer"]);
|
|
356
371
|
/** What would keep this fix's value from taking effect, as Claude Code merges settings. */
|
|
357
372
|
export function fixOverrides(id, deps = {}) {
|
|
358
373
|
// Codex reads its own config.toml: a profile's value, or a project's file.
|
|
@@ -548,6 +563,23 @@ export async function applyFix(fix, deps = {}, context = {}) {
|
|
|
548
563
|
withLock(lockPath(home), () => writeFixRecords([...loadFixRecords(home).filter((x) => x.id !== "autopilot"), { id: "autopilot", at }], home));
|
|
549
564
|
return r;
|
|
550
565
|
}
|
|
566
|
+
if (fix.id === "mcp-defer") {
|
|
567
|
+
const servers = context.mcpDefer?.servers ?? [];
|
|
568
|
+
if (!servers.length)
|
|
569
|
+
return { ok: false, lines: ["mcp-defer: no MCP server of yours went whole into a start"] };
|
|
570
|
+
return withLock(lockPath(home), () => {
|
|
571
|
+
const records = loadFixRecords(home);
|
|
572
|
+
const r = applyMcpDefer(servers, { home, cwd: deps.cwd });
|
|
573
|
+
if (r.entries.length) {
|
|
574
|
+
const old = records.find((x) => x.id === "mcp-defer");
|
|
575
|
+
// A second apply keeps the first one's entries (their earlier values) and adds the new keys.
|
|
576
|
+
const same = (a, b) => a.key.join("/") === b.key.join("/");
|
|
577
|
+
const entries = [...(old?.entries ?? []).filter((e) => !r.entries.some((n) => same(n, e))), ...r.entries.map((n) => old?.entries?.find((e) => same(e, n)) ?? n)];
|
|
578
|
+
writeFixRecords([...records.filter((x) => x.id !== "mcp-defer"), { id: "mcp-defer", at: old?.at ?? at, file: r.file, entries }], home);
|
|
579
|
+
}
|
|
580
|
+
return { ok: true, lines: r.lines };
|
|
581
|
+
});
|
|
582
|
+
}
|
|
551
583
|
if (fix.id === "prune") {
|
|
552
584
|
if (!context.prune)
|
|
553
585
|
return { ok: false, lines: ["prune: no plan for this folder"] };
|
|
@@ -653,6 +685,9 @@ export async function undoFixes(ids, deps = {}) {
|
|
|
653
685
|
done = false;
|
|
654
686
|
}
|
|
655
687
|
}
|
|
688
|
+
else if (r.id === "mcp-defer") {
|
|
689
|
+
lines.push(...withLock(lockPath(home), () => undoMcpDefer(r.file ?? claudeJsonPath(home), r.entries ?? [])));
|
|
690
|
+
}
|
|
656
691
|
else if (r.id === "prune") {
|
|
657
692
|
const u = r.cwd ? undoPrune(r.cwd) : undefined;
|
|
658
693
|
lines.push(u ? `✓ switched back on in ${u.file}: ${u.removed.join(", ") || "nothing left to remove"}` : "✓ prune: nothing left to undo");
|
|
@@ -848,6 +883,7 @@ const LABEL = {
|
|
|
848
883
|
"tool-output": "Long Bash output",
|
|
849
884
|
"codex-compact": "Codex auto-compact limit",
|
|
850
885
|
"progress-summaries": "Subagent progress summaries",
|
|
886
|
+
"mcp-defer": "MCP servers sent whole",
|
|
851
887
|
};
|
|
852
888
|
/**
|
|
853
889
|
* Priced levers that save part of the same dollars, and why: each is
|
|
@@ -870,7 +906,7 @@ export function overlaps(fixes) {
|
|
|
870
906
|
const priced = new Set(fixes.filter((f) => f.savedUsd !== undefined).map((f) => f.id));
|
|
871
907
|
return OVERLAPS.filter(([a, b]) => priced.has(a) && priced.has(b)).map(([a, b, why]) => `${a} and ${b}: ${why}.`);
|
|
872
908
|
}
|
|
873
|
-
export function renderFixPlan(days, billedUsd, fixes, since, command = (s) => `context-doctor ${s}`, coldResume, recordProblem, codexBilledUsd = 0) {
|
|
909
|
+
export function renderFixPlan(days, billedUsd, fixes, since, command = (s) => `context-doctor ${s}`, coldResume, recordProblem, codexBilledUsd = 0, keepWarm) {
|
|
874
910
|
const out = [];
|
|
875
911
|
if (recordProblem)
|
|
876
912
|
out.push(`⚠ ${recordProblem}`);
|
|
@@ -925,14 +961,22 @@ export function renderFixPlan(days, billedUsd, fixes, since, command = (s) => `c
|
|
|
925
961
|
const elsewhere = fixes.filter((f) => f.state === "not-here");
|
|
926
962
|
for (const f of elsewhere)
|
|
927
963
|
out.push(` - ${LABEL[f.id]}: ${f.note}`);
|
|
928
|
-
|
|
964
|
+
const compactAdvice = coldResume !== undefined && coldResume.netUsd >= MIN_USD;
|
|
965
|
+
const warmAdvice = keepWarm !== undefined && keepWarm.netUsd >= MIN_USD;
|
|
966
|
+
if (compactAdvice || warmAdvice) {
|
|
929
967
|
out.push("");
|
|
930
968
|
out.push("Advice you act on");
|
|
969
|
+
}
|
|
970
|
+
if (compactAdvice) {
|
|
931
971
|
out.push(` /compact when you come back to a big session after the cache expired: ${money(coldResume.netUsd)} over ${coldResume.returns} returns.`);
|
|
932
972
|
out.push(coldResume.hooked
|
|
933
973
|
? " The every-prompt hook offers it at those moments; say yes when it does."
|
|
934
974
|
: ` Nothing points those moments out yet: ${command("install")} (or the Claude Code plugin) adds the hook that does.`);
|
|
935
975
|
}
|
|
976
|
+
if (warmAdvice) {
|
|
977
|
+
out.push(` Keep the cache warm while you step away, up to ${keepWarm.hours} h: ${money(keepWarm.netUsd)} net of ${money(keepWarm.pingUsd)} in pings (${keepWarm.keptWarm} of ${keepWarm.returns} cold returns kept warm).`);
|
|
978
|
+
out.push(` /context-doctor-keep-warm ${keepWarm.hours}h in Claude Code with the plugin, each time you leave; on a subscription the pings use your limit too. By gap: ${command("cache-misses")}`);
|
|
979
|
+
}
|
|
936
980
|
out.push("");
|
|
937
981
|
if (avail.length) {
|
|
938
982
|
out.push(`Apply: ${command("fix")} in a terminal asks about each one; or ${command(`fix --apply ${avail.map((f) => f.id).join(",")}`)}`);
|