context-doctor 0.46.0 → 0.48.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 (68) hide show
  1. package/README.md +9 -4
  2. package/dist/ab.d.ts +51 -3
  3. package/dist/ab.js +71 -28
  4. package/dist/abclaude.d.ts +167 -0
  5. package/dist/abclaude.js +511 -0
  6. package/dist/abstore.d.ts +46 -0
  7. package/dist/abstore.js +58 -0
  8. package/dist/autopilot.js +9 -5
  9. package/dist/blob.js +66 -12
  10. package/dist/budget.d.ts +8 -2
  11. package/dist/budget.js +30 -7
  12. package/dist/ci.js +2 -1
  13. package/dist/claudeplugin.d.ts +97 -0
  14. package/dist/claudeplugin.js +142 -0
  15. package/dist/cli.js +128 -36
  16. package/dist/compactcost.d.ts +74 -0
  17. package/dist/compactcost.js +115 -0
  18. package/dist/cursor.js +2 -0
  19. package/dist/doctor.js +90 -18
  20. package/dist/extract.js +4 -3
  21. package/dist/fanout.d.ts +15 -0
  22. package/dist/fanout.js +30 -9
  23. package/dist/firstfix.d.ts +43 -0
  24. package/dist/firstfix.js +80 -0
  25. package/dist/fix.d.ts +53 -4
  26. package/dist/fix.js +101 -13
  27. package/dist/httpguard.d.ts +13 -0
  28. package/dist/httpguard.js +22 -0
  29. package/dist/install.d.ts +21 -9
  30. package/dist/install.js +213 -40
  31. package/dist/limits.d.ts +5 -0
  32. package/dist/limits.js +26 -2
  33. package/dist/mcp.d.ts +4 -0
  34. package/dist/mcp.js +142 -97
  35. package/dist/mcpclient.js +73 -42
  36. package/dist/missledger.js +5 -3
  37. package/dist/mod/api.d.ts +8 -2
  38. package/dist/mod/api.js +2 -2
  39. package/dist/mod/logic.d.ts +13 -1
  40. package/dist/mod/logic.js +24 -2
  41. package/dist/mod/register.d.ts +2 -0
  42. package/dist/mod/register.js +19 -5
  43. package/dist/modelids.d.ts +62 -3
  44. package/dist/modelids.js +156 -8
  45. package/dist/modelswitch.js +8 -4
  46. package/dist/modmeasure.js +13 -1
  47. package/dist/orgrates.d.ts +18 -0
  48. package/dist/orgrates.js +51 -2
  49. package/dist/pack.d.ts +13 -0
  50. package/dist/pack.js +38 -2
  51. package/dist/preferences.js +2 -1
  52. package/dist/pricing.d.ts +8 -0
  53. package/dist/pricing.js +30 -2
  54. package/dist/progresssummaries.d.ts +148 -0
  55. package/dist/progresssummaries.js +248 -0
  56. package/dist/proxy.d.ts +1 -1
  57. package/dist/proxy.js +1 -1
  58. package/dist/prune.d.ts +8 -0
  59. package/dist/prune.js +11 -1
  60. package/dist/spend.d.ts +34 -0
  61. package/dist/spend.js +48 -4
  62. package/dist/subagentmodel.d.ts +12 -0
  63. package/dist/subagentmodel.js +17 -4
  64. package/dist/subagentpay.d.ts +8 -0
  65. package/dist/subagentpay.js +8 -1
  66. package/dist/toolcwd.d.ts +14 -0
  67. package/dist/toolcwd.js +17 -0
  68. package/package.json +6 -3
package/dist/install.js CHANGED
@@ -19,6 +19,7 @@ import { claudeCodePresent, claudeDir, claudeJsonPath } from "./claudedir.js";
19
19
  import { fallbackStateDir } from "./ledger.js";
20
20
  import { codexDir as codexHomeDir } from "./codexdir.js";
21
21
  import { scanCacheDir } from "./scan.js";
22
+ import { isOurDeclaration, isOurPluginKey, MARKETPLACE, marketplaceDeclaration, marketplaceRegistered, MOD_SINCE, modReadiness, PLUGIN_KEY, pluginMarkerPath, pluginStage, readPluginMarker } from "./claudeplugin.js";
22
23
  import { editJsonText, parseSettingsText, sameJson, withSettingsLock, writeAtomic } from "./settingsedit.js";
23
24
  function claudeDesktopConfigPath() {
24
25
  switch (platform()) {
@@ -118,17 +119,8 @@ export function launcherNamesMissingPackage(entry) {
118
119
  return false;
119
120
  return rest.find((w) => !w.startsWith("-")) === "context-doctor-mcp";
120
121
  }
121
- /**
122
- * The Claude Code plugin's key in enabledPlugins: "<plugin>@<marketplace>".
123
- * Our marketplace (.claude-plugin/marketplace.json) is named context-doctor
124
- * and lists one plugin, context-doctor, so the official key is
125
- * "context-doctor@context-doctor"; a copy listed in another marketplace keeps
126
- * the plugin name, so any "context-doctor@…" key is ours.
127
- */
128
- export const PLUGIN_KEY = "context-doctor@context-doctor";
129
- export function isOurPluginKey(key) {
130
- return key === PLUGIN_KEY || key.startsWith("context-doctor@");
131
- }
122
+ // The plugin's key lives in claudeplugin.ts with the rest of the plugin path.
123
+ export { PLUGIN_KEY, isOurPluginKey } from "./claudeplugin.js";
132
124
  /**
133
125
  * Is the context-doctor plugin switched on in the user's Claude Code
134
126
  * settings? The plugin brings its own MCP server, skills and hooks, so
@@ -162,6 +154,116 @@ export function claudeInstalledCopies(home = homedir()) {
162
154
  found.push("skill in ~/.claude/skills/context-doctor");
163
155
  return found;
164
156
  }
157
+ export function claudeCodeRoute(readiness = modReadiness(claudeCodeInstallsFromEnv())) {
158
+ let enabled = {};
159
+ try {
160
+ const e = readJson(join(claudeDir(), "settings.json")).enabledPlugins;
161
+ if (isPlainObject(e))
162
+ enabled = e;
163
+ }
164
+ catch { /* unreadable: the step that writes it reports that */ }
165
+ const on = Object.entries(enabled).some(([key, v]) => isOurPluginKey(key) && v === true);
166
+ if (on && !readPluginMarker())
167
+ return { via: "plugin", ours: false, readiness };
168
+ // Turned off by hand (install never writes false): the user's call stands.
169
+ if (enabled[PLUGIN_KEY] === false)
170
+ return { via: "hooks", why: "off", readiness };
171
+ if (readiness.ok)
172
+ return { via: "plugin", ours: true, readiness };
173
+ return { via: "hooks", why: readiness.old.length > 0 ? "old" : "unknown", readiness };
174
+ }
175
+ /**
176
+ * Switch the plugin on in ~/.claude/settings.json: this repository as a
177
+ * marketplace and the plugin enabled, each key only if it is not there
178
+ * already, written key by key under the settings lock (so uninstall gives
179
+ * the file back byte for byte), and what was added recorded in the marker.
180
+ * Returns whether the file changed.
181
+ */
182
+ function enablePlugin() {
183
+ const path = join(claudeDir(), "settings.json");
184
+ return settingsUpdate(path, () => {
185
+ const settings = readJson(path);
186
+ for (const key of ["extraKnownMarketplaces", "enabledPlugins"]) {
187
+ if (settings[key] !== undefined && !isPlainObject(settings[key]))
188
+ throw new Error(`"${key}" in ${path} is not an object; fix it, then re-run. Nothing was changed.`);
189
+ }
190
+ const marker = readPluginMarker() ?? { marketplace: false, enabled: false };
191
+ let changed = false;
192
+ // Declared already (either spelling), or a marketplace of that name Claude
193
+ // Code already knows (added with /plugin, perhaps from a local checkout):
194
+ // declaring this repository over it would move it to GitHub.
195
+ const declared = [settings.extraKnownMarketplaces, settings.additionalMarketplaces].some((m) => isPlainObject(m) && m[MARKETPLACE] !== undefined);
196
+ if (!declared && !marketplaceRegistered()) {
197
+ settings.extraKnownMarketplaces = { ...(settings.extraKnownMarketplaces ?? {}), [MARKETPLACE]: marketplaceDeclaration() };
198
+ marker.marketplace = true;
199
+ changed = true;
200
+ }
201
+ if (settings.enabledPlugins?.[PLUGIN_KEY] !== true) {
202
+ settings.enabledPlugins = { ...(settings.enabledPlugins ?? {}), [PLUGIN_KEY]: true };
203
+ marker.enabled = true;
204
+ changed = true;
205
+ }
206
+ if (!changed)
207
+ return false;
208
+ // The record first: from here on a later install's backup step and
209
+ // uninstall see these keys as install's, not the user's.
210
+ writeAtomic(pluginMarkerPath(), JSON.stringify(marker) + "\n");
211
+ writeJsonWithBackup(path, settings);
212
+ return true;
213
+ });
214
+ }
215
+ /**
216
+ * Take out the plugin keys install wrote (each only if it still says what
217
+ * install wrote), then the marker. Returns whether settings.json changed.
218
+ */
219
+ function disablePlugin() {
220
+ const marker = readPluginMarker();
221
+ let changed = false;
222
+ const path = join(claudeDir(), "settings.json");
223
+ if (marker && existsSync(path)) {
224
+ settingsUpdate(path, () => {
225
+ const settings = readJson(path);
226
+ if (dropOurPluginKeys(settings, marker)) {
227
+ writeUninstalled(path, settings);
228
+ changed = true;
229
+ }
230
+ });
231
+ }
232
+ rmSync(pluginMarkerPath(), { force: true });
233
+ return changed;
234
+ }
235
+ /** Install's own Claude Code hooks, by event, with the name each step prints. */
236
+ const CLAUDE_HOOKS = [
237
+ ["UserPromptSubmit", "Claude Code every-prompt hook"],
238
+ ["PreCompact", "Claude Code compaction hook"],
239
+ ["SessionStart", "Claude Code session-start hook"],
240
+ ["PreModelSwitch", "Claude Code model-switch warning"],
241
+ ["PreToolUse", "Claude Code subagent price"],
242
+ ];
243
+ /** Remove our MCP server from one app's config, as uninstall does. */
244
+ function removeMcpEntry(name, configPath) {
245
+ if (!existsSync(configPath))
246
+ return;
247
+ const config = readJson(configPath);
248
+ if (config.mcpServers?.["context-doctor"]) {
249
+ delete config.mcpServers["context-doctor"];
250
+ writeUninstalled(configPath, config);
251
+ done(`✓ ${name}: MCP server removed`);
252
+ }
253
+ }
254
+ /**
255
+ * Install's own Claude Code wiring out (the MCP server in ~/.claude.json,
256
+ * the skill, the hooks), each step on its own, as uninstall takes them out:
257
+ * beside the plugin each would run twice.
258
+ */
259
+ function removeClaudeCodeCopies(attempt) {
260
+ const settings = join(claudeDir(), "settings.json");
261
+ for (const [event, label] of CLAUDE_HOOKS)
262
+ attempt(label, () => uninstallHookFrom(settings, label, event));
263
+ attempt("Claude Code", () => removeMcpEntry("Claude Code", claudeJsonPath()));
264
+ attempt("Agent Skill", () => removeSkill(join(claudeDir(), "skills", "context-doctor"), "Agent Skill"));
265
+ attempt("Claude Code skill folders", () => removeSkillFolders(claudeDir()));
266
+ }
165
267
  /**
166
268
  * A config that configures nothing: `{}`, or only empty `mcpServers` /
167
269
  * `hooks` containers (plus `extraKeys`, e.g. the `version` install writes
@@ -466,11 +568,8 @@ function addHookEntry(settingsPath, event, opts) {
466
568
  /** Each hook removal on its own: a malformed file for one app must not leave the others installed. */
467
569
  function uninstallHook(attempt) {
468
570
  const claude = join(claudeDir(), "settings.json");
469
- attempt("Claude Code every-prompt hook", () => uninstallHookFrom(claude, "Claude Code every-prompt hook"));
470
- attempt("Claude Code compaction hook", () => uninstallHookFrom(claude, "Claude Code compaction hook", "PreCompact"));
471
- attempt("Claude Code session-start hook", () => uninstallHookFrom(claude, "Claude Code session-start hook", "SessionStart"));
472
- attempt("Claude Code model-switch warning", () => uninstallHookFrom(claude, "Claude Code model-switch warning", "PreModelSwitch"));
473
- attempt("Claude Code subagent price", () => uninstallHookFrom(claude, "Claude Code subagent price", "PreToolUse"));
571
+ for (const [event, label] of CLAUDE_HOOKS)
572
+ attempt(label, () => uninstallHookFrom(claude, label, event));
474
573
  attempt("Codex every-prompt hook", () => uninstallHookFrom(join(codexDir(), "hooks.json"), "Codex every-prompt hook"));
475
574
  attempt("Gemini CLI every-prompt hook", () => uninstallHookFrom(geminiSettingsPath(), "Gemini CLI every-prompt hook", "BeforeAgent"));
476
575
  attempt("Cursor hooks", () => uninstallCursorHook());
@@ -1077,6 +1176,49 @@ function uninstallAntigravityFolders() {
1077
1176
  rmSync(dir, { recursive: true });
1078
1177
  rmSync(marker, { force: true });
1079
1178
  }
1179
+ /**
1180
+ * Claude Code's half of install for the route chosen: the plugin switched
1181
+ * on (or found on) and install's own copies taken out, or the plugin keys
1182
+ * install wrote taken out again before its own wiring goes in. Says which,
1183
+ * and what each Claude Code here gets.
1184
+ */
1185
+ function routeClaudeCode(route, attempt) {
1186
+ const settingsPath = join(claudeDir(), "settings.json");
1187
+ if (route.via === "plugin" && !route.ours) {
1188
+ console.log("– Claude Code: skipped the MCP server, skill and hooks. The context-doctor plugin is enabled and");
1189
+ console.log(" provides them already (and, on Claude Code 2.1.286+, its mod); installing them as well would load its instructions and tools twice.");
1190
+ }
1191
+ else if (route.via === "plugin") {
1192
+ const changed = enablePlugin();
1193
+ console.log(changed
1194
+ ? `✓ Claude Code: the context-doctor plugin enabled (${tilde(settingsPath)}: extraKnownMarketplaces, enabledPlugins), in place of install's own MCP server, skill and hooks`
1195
+ : "✓ Claude Code: the context-doctor plugin already enabled, unchanged");
1196
+ console.log(` ${describeInstalls(route.readiness.installs)} ${route.readiness.installs.length === 1 ? "runs" : "run"} its mod: limit readings and Claude Code's own session cost after each turn,`);
1197
+ console.log(" the Compact first button on a cold return, /context-doctor-fix; and the MCP server, skills and hooks install used to add itself.");
1198
+ if (pluginStage().stage !== "installed") {
1199
+ console.log(" Claude Code downloads it in the background at its next start and loads it from the session after (or at once: /reload-plugins).");
1200
+ }
1201
+ }
1202
+ else {
1203
+ if (readPluginMarker()) {
1204
+ if (disablePlugin())
1205
+ console.log("– Claude Code: the context-doctor plugin install had enabled is turned off again (its keys removed from settings.json).");
1206
+ }
1207
+ const why = route.why === "off"
1208
+ ? "the context-doctor plugin is turned off in your settings (enabledPlugins); turn it on in /plugin for its mod, and install leaves Claude Code to it"
1209
+ : route.why === "old"
1210
+ ? `${describeInstalls(route.readiness.old)} predates mods (${MOD_SINCE}), and every Claude Code here reads the same settings; update or remove it, then run install again for the plugin and its mod`
1211
+ : `no Claude Code version found to check (the plugin's mod needs ${MOD_SINCE} or later)`;
1212
+ console.log(`– Claude Code: install's own MCP server, skill and hooks, not the plugin: ${why}.`);
1213
+ return;
1214
+ }
1215
+ // Beside the plugin, install's own copies would run twice: out they go, as uninstall takes them out.
1216
+ const copies = claudeInstalledCopies();
1217
+ if (copies.length > 0) {
1218
+ console.log(` Taking out install's own copies (${copies.join(", ")}), which would load twice beside the plugin:`);
1219
+ removeClaudeCodeCopies(attempt);
1220
+ }
1221
+ }
1080
1222
  /**
1081
1223
  * Install into every detected app.
1082
1224
  *
@@ -1097,19 +1239,23 @@ export function runInstall(options = {}) {
1097
1239
  return { failures: [] };
1098
1240
  }
1099
1241
  const failures = [];
1100
- // The plugin already gives Claude Code the server, skill and hooks; a
1101
- // second copy of each makes every session load the instructions and the
1102
- // tools twice. Claude Code is skipped; the other apps are not.
1103
- const viaPlugin = claudePluginEnabled();
1104
- if (viaPlugin) {
1105
- console.log("– Claude Code: skipped the MCP server, skill and hooks. The context-doctor plugin is enabled and");
1106
- console.log(" provides them already; installing them as well would load its instructions and tools twice.");
1107
- const copies = claudeInstalledCopies();
1108
- if (copies.length > 0) {
1109
- console.log(` An earlier install is still in place (${copies.join(", ")}): \`${selfCommand("uninstall")}\``);
1110
- console.log(` removes it, then \`${selfCommand("install")}\` wires the other apps again.`);
1242
+ const attempt = (label, fn) => {
1243
+ try {
1244
+ fn();
1111
1245
  }
1112
- }
1246
+ catch (e) {
1247
+ console.error(`✗ ${label}: ${e.message}`);
1248
+ failures.push(label);
1249
+ }
1250
+ };
1251
+ // Claude Code through the plugin (claudeplugin.ts) when it runs mods, or
1252
+ // with install's own MCP server, skill and hooks. Never both: a second
1253
+ // copy of each makes every session load the instructions and the tools
1254
+ // twice. The other apps are wired either way.
1255
+ const route = claudeCodePresent() ? claudeCodeRoute() : undefined;
1256
+ const viaPlugin = route?.via === "plugin";
1257
+ if (route)
1258
+ attempt("Claude Code plugin", () => routeClaudeCode(route, attempt));
1113
1259
  for (const target of found) {
1114
1260
  if (viaPlugin && target.name === "Claude Code")
1115
1261
  continue;
@@ -1348,8 +1494,29 @@ function withoutOurs(config) {
1348
1494
  }
1349
1495
  if (typeof c.statusLine?.command === "string" && isOurStatusLine(c.statusLine.command))
1350
1496
  delete c.statusLine;
1497
+ // The plugin keys count as ours only where install wrote them (its marker
1498
+ // says so): an enabledPlugins entry the user made is theirs.
1499
+ const marker = readPluginMarker();
1500
+ if (marker)
1501
+ dropOurPluginKeys(c, marker);
1351
1502
  return c;
1352
1503
  }
1504
+ /**
1505
+ * Take the plugin keys install wrote out of a settings object, each only if
1506
+ * it still says what install wrote. Returns whether anything went.
1507
+ */
1508
+ function dropOurPluginKeys(c, marker) {
1509
+ let dropped = false;
1510
+ if (marker.enabled && isPlainObject(c.enabledPlugins) && c.enabledPlugins[PLUGIN_KEY] === true) {
1511
+ delete c.enabledPlugins[PLUGIN_KEY];
1512
+ dropped = true;
1513
+ }
1514
+ if (marker.marketplace && isPlainObject(c.extraKnownMarketplaces) && isOurDeclaration(c.extraKnownMarketplaces[MARKETPLACE])) {
1515
+ delete c.extraKnownMarketplaces[MARKETPLACE];
1516
+ dropped = true;
1517
+ }
1518
+ return dropped;
1519
+ }
1353
1520
  /**
1354
1521
  * The file as it was before install, as far as its backup can tell:
1355
1522
  * `created` when install made the file (no backup was needed), or when the
@@ -1384,7 +1551,8 @@ function installOrigin(path, extraKeys) {
1384
1551
  */
1385
1552
  function writeUninstalled(path, config, extraKeys = []) {
1386
1553
  const { created, before, empty } = installOrigin(path, extraKeys);
1387
- for (const key of ["mcpServers", "hooks"]) {
1554
+ // The plugin's containers too (settings.json): install made them when the file had none.
1555
+ for (const key of ["mcpServers", "hooks", "enabledPlugins", "extraKnownMarketplaces"]) {
1388
1556
  const v = config[key];
1389
1557
  if (v && typeof v === "object" && Object.keys(v).length === 0 && !(key in before))
1390
1558
  delete config[key];
@@ -1457,11 +1625,14 @@ const OUR_CLAUDE_FILES = [
1457
1625
  ".context-doctor-proxy.log",
1458
1626
  ".context-doctor-proxy-restart",
1459
1627
  ".context-doctor-limits.jsonl",
1628
+ ".context-doctor-session-cost.jsonl",
1460
1629
  ".context-doctor-misses.jsonl",
1461
1630
  ".context-doctor-subagent-costs.json",
1462
1631
  ".context-doctor-budget.json",
1463
1632
  ".context-doctor-budget-state.json",
1464
1633
  ".context-doctor-budget-said.d",
1634
+ // ab --via claude-code's kept comparisons (abstore.ts), which fix quotes.
1635
+ ".context-doctor-ab.json",
1465
1636
  ];
1466
1637
  export async function runUninstall() {
1467
1638
  changes = 0;
@@ -1500,17 +1671,19 @@ export async function runUninstall() {
1500
1671
  console.error(`✗ autopilot: ${e.message}`);
1501
1672
  }
1502
1673
  for (const target of targets().filter((t) => t.detect())) {
1503
- attempt(target.name, () => {
1504
- if (!existsSync(target.configPath))
1505
- return;
1506
- const config = readJson(target.configPath);
1507
- if (config.mcpServers?.["context-doctor"]) {
1508
- delete config.mcpServers["context-doctor"];
1509
- writeUninstalled(target.configPath, config);
1510
- done(`✓ ${target.name}: MCP server removed`);
1511
- }
1512
- });
1513
- }
1674
+ attempt(target.name, () => removeMcpEntry(target.name, target.configPath));
1675
+ }
1676
+ // The plugin keys install wrote; a plugin the user enabled stays theirs.
1677
+ attempt("Claude Code plugin", () => {
1678
+ if (disablePlugin()) {
1679
+ done("✓ Claude Code: the context-doctor plugin turned off (the keys install added to ~/.claude/settings.json removed)");
1680
+ if (pluginStage().stage !== "none")
1681
+ console.log(" Claude Code keeps its downloaded copy, disabled, under ~/.claude/plugins; `claude plugin uninstall context-doctor@context-doctor` deletes it.");
1682
+ }
1683
+ else if (claudePluginEnabled()) {
1684
+ console.log("– Claude Code: the context-doctor plugin stays enabled: you turned it on, not install (turn it off in /plugin).");
1685
+ }
1686
+ });
1514
1687
  attempt("Agent Skill", () => removeSkill(join(claudeDir(), "skills", "context-doctor"), "Agent Skill"));
1515
1688
  for (const dir of antigravityAllSkillDirs())
1516
1689
  attempt(`Antigravity skill (${tilde(dir)})`, () => removeSkill(dir, "Antigravity skill"));
package/dist/limits.d.ts CHANGED
@@ -27,6 +27,7 @@
27
27
  */
28
28
  import { type Extractor } from "./scan.js";
29
29
  import { type ModelPricing, type Modifiers } from "./pricing.js";
30
+ import { type CompactionRequest } from "./compactcost.js";
30
31
  /** Claude Code's two windows, as its status line input names them. */
31
32
  export declare const CLAUDE_WINDOWS: readonly ["five_hour", "seven_day"];
32
33
  /** One reading of one window: how much of it was used at `ts`. */
@@ -107,6 +108,8 @@ export declare function codexLimitData(since: number, root?: string): {
107
108
  export declare const USAGE_ROWS: Extractor<{
108
109
  ids: Record<string, 1>;
109
110
  }>;
111
+ /** A compaction's estimated request as a request point (no message id: its key is the boundary's uuid). */
112
+ export declare function compactionPoint(c: CompactionRequest): ClaudeRequest;
110
113
  /** One Claude Code request as `claudeFileUsage` reads it: the usage point, and what `spend` and `budget` add up. */
111
114
  export interface ClaudeRequest extends UsagePoint {
112
115
  /** The row's uuid: what tells a fork's copy of a reply from the reply itself. */
@@ -125,6 +128,8 @@ export interface ClaudeRequest extends UsagePoint {
125
128
  estimated?: boolean;
126
129
  /** Its row's price changed on this day, before the request. */
127
130
  changedOn?: string;
131
+ /** A compaction's own request, which no row records usage for: estimated (compactcost.ts). */
132
+ compaction?: boolean;
128
133
  }
129
134
  /**
130
135
  * The requests of one Claude Code transcript between `since` and `until`,
package/dist/limits.js CHANGED
@@ -35,6 +35,7 @@ import { subagentFiles } from "./subagents.js";
35
35
  import { pick, rowsOf, slimUsage } from "./scan.js";
36
36
  import { isUnbilledModel, NO_MODIFIERS, openAIUsage, requestCost } from "./pricing.js";
37
37
  import { realModel } from "./tokens.js";
38
+ import { isCompactionRow, newTrack, slimSummary, trackCompaction } from "./compactcost.js";
38
39
  const MIN = 60_000;
39
40
  const HOUR = 60 * MIN;
40
41
  const DAY = 24 * HOUR;
@@ -338,10 +339,11 @@ export function codexLimitData(since, root = codexSessionsRoot()) {
338
339
  * main thread.
339
340
  */
340
341
  export const USAGE_ROWS = {
341
- id: "usage.3",
342
+ id: "usage.4",
342
343
  init: () => ({ ids: {} }),
343
344
  line(line, row, out, st) {
344
- if (!line.includes('"usage"'))
345
+ const compaction = isCompactionRow(line);
346
+ if (!compaction && !line.includes('"usage"'))
345
347
  return;
346
348
  let e;
347
349
  try {
@@ -350,6 +352,15 @@ export const USAGE_ROWS = {
350
352
  catch {
351
353
  return;
352
354
  }
355
+ // A compaction's boundary (the context it read) and its summary (the output): what its own request is estimated from (compactcost.ts).
356
+ if (compaction && e?.type === "system" && e.subtype === "compact_boundary") {
357
+ out.push(pick({ ...e, isSidechain: e.isSidechain === true || undefined, compactMetadata: pick(e.compactMetadata ?? {}, ["preTokens"]) }, ["type", "subtype", "uuid", "sessionId", "timestamp", "isSidechain", "compactMetadata"]));
358
+ return;
359
+ }
360
+ if (compaction && e?.type === "user" && e.isCompactSummary === true) {
361
+ out.push(slimSummary(e));
362
+ return;
363
+ }
353
364
  const m = e?.message;
354
365
  if (e?.type !== "assistant" || !m?.usage)
355
366
  return;
@@ -363,6 +374,15 @@ export const USAGE_ROWS = {
363
374
  out.push(pick({ ...e, isSidechain: e.isSidechain === true || undefined, message: pick({ ...m, usage: slimUsage(m.usage) }, ["id", "model", "usage"]) }, ["type", "uuid", "timestamp", "isSidechain", "message"]));
364
375
  },
365
376
  };
377
+ /** A compaction's estimated request as a request point (no message id: its key is the boundary's uuid). */
378
+ export function compactionPoint(c) {
379
+ const u = c.usage;
380
+ return {
381
+ ts: c.ts, app: "claude", model: c.model, input: num(u.input_tokens), read: num(u.cache_read_input_tokens), write: num(u.cache_creation_input_tokens), output: num(u.output_tokens),
382
+ usd: c.cost.totalUsd, promptUsd: c.cost.promptUsd, rates: c.cost.rates, modifiers: c.cost.modifiers, compaction: true,
383
+ ...(c.uuid ? { uuid: c.uuid } : {}), ...(c.sidechain ? { sidechain: true } : {}), ...(c.cost.estimated ? { estimated: true } : {}), ...(c.cost.changedOn ? { changedOn: c.cost.changedOn } : {}),
384
+ };
385
+ }
366
386
  /**
367
387
  * The requests of one Claude Code transcript between `since` and `until`,
368
388
  * each reply once, its output settled on its last row (billed at the
@@ -376,7 +396,11 @@ export function claudeFileUsage(file, since, until = Infinity, runRows) {
376
396
  const sighting = replyCounter(runRows);
377
397
  const settle = outputSettler();
378
398
  const byId = new Map();
399
+ const track = newTrack();
379
400
  rowsOf(file, USAGE_ROWS).forEach((e) => {
401
+ const done = trackCompaction(track, e);
402
+ if (done && done.ts >= since && done.ts <= until)
403
+ out.push(compactionPoint(done));
380
404
  const m = e?.message;
381
405
  if (e?.type !== "assistant" || !m?.usage)
382
406
  return;
package/dist/mcp.d.ts CHANGED
@@ -18,5 +18,9 @@
18
18
  * save_handoff — store a handoff brief the next chat starts from (a chat's history cannot be cut)
19
19
  * recall — search this session's own transcript (compacted turns, cleared output); stdio only
20
20
  * Prompts: context_checkup, handoff, ask_file. Resources (stdio): handoff://latest, handoff://<id>.
21
+ *
22
+ * Built on the MCP SDK's v2 packages: one server definition answers both
23
+ * protocol eras, a 2025-era client's `initialize` (2024-10-07 to 2025-11-25)
24
+ * and a 2026-07-28 client's `server/discover`, over stdio and --http.
21
25
  */
22
26
  export {};