context-doctor 0.49.1 → 0.50.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 (46) hide show
  1. package/README.md +15 -14
  2. package/dist/appwindow.d.ts +69 -0
  3. package/dist/appwindow.js +147 -0
  4. package/dist/ccost.js +8 -4
  5. package/dist/claudedir.d.ts +15 -0
  6. package/dist/claudedir.js +19 -1
  7. package/dist/cli.js +59 -23
  8. package/dist/clihelp.d.ts +5 -1
  9. package/dist/clihelp.js +9 -1
  10. package/dist/codexstatusline.d.ts +176 -0
  11. package/dist/codexstatusline.js +353 -0
  12. package/dist/compactwindow.d.ts +14 -2
  13. package/dist/compactwindow.js +30 -5
  14. package/dist/credits.d.ts +130 -0
  15. package/dist/credits.js +265 -0
  16. package/dist/doctor.d.ts +6 -0
  17. package/dist/doctor.js +15 -1
  18. package/dist/fanout.d.ts +2 -0
  19. package/dist/fanout.js +12 -2
  20. package/dist/fix.d.ts +37 -1
  21. package/dist/fix.js +67 -9
  22. package/dist/limits.d.ts +45 -1
  23. package/dist/limits.js +121 -9
  24. package/dist/mcp.d.ts +1 -0
  25. package/dist/mcp.js +106 -100
  26. package/dist/mod/api.d.ts +27 -1
  27. package/dist/mod/api.js +2 -1
  28. package/dist/mod/logic.d.ts +39 -0
  29. package/dist/mod/logic.js +42 -1
  30. package/dist/mod/register.d.ts +4 -0
  31. package/dist/mod/register.js +25 -1
  32. package/dist/modelids.js +2 -2
  33. package/dist/orgrates.d.ts +4 -2
  34. package/dist/orgrates.js +21 -3
  35. package/dist/overhead.js +2 -1
  36. package/dist/pricing.js +7 -0
  37. package/dist/progresssummaries.d.ts +20 -1
  38. package/dist/progresssummaries.js +33 -3
  39. package/dist/proxy.d.ts +1 -1
  40. package/dist/proxy.js +9 -4
  41. package/dist/savings.js +3 -1
  42. package/dist/spend.d.ts +28 -1
  43. package/dist/spend.js +38 -5
  44. package/dist/starts.d.ts +27 -1
  45. package/dist/starts.js +81 -18
  46. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -35,6 +35,8 @@ import { replaySubagentModels, shares, SUBAGENT_MODEL_ENV, SUBAGENT_MODEL_FORCE_
35
35
  import { BASH_OUTPUT_ENV, BASH_OUTPUT_KEY, replayToolOutput, TOOL_OUTPUT_ROWS } from "./tooloutput.js";
36
36
  import { CODEX_COMPACT_ROWS, codexRollouts, currentCodexCompact, replayCodexCompact } from "./codexcompact.js";
37
37
  import { currentCompactWindow, estimateCompactWindows, MAX_WINDOW, MIN_WINDOW, parseWindow, renderCompactWindows, setCompactWindow, settingsPath } from "./compactwindow.js";
38
+ import { appWindowLines, readAppWindows } from "./appwindow.js";
39
+ import { modelName } from "./subagentmodel.js";
38
40
  import { tilde } from "./claudedir.js";
39
41
  import { renderPreferences, copyToClipboard, CHAT_PREFERENCES } from "./preferences.js";
40
42
  import { recordLedger } from "./ledger.js";
@@ -56,7 +58,8 @@ import { analyzeCacheUsage, renderCacheReport } from "./cache.js";
56
58
  import { renderToolTimings } from "./timing.js";
57
59
  import { packContextSemantic, readSources, renderPack } from "./pack.js";
58
60
  import { measureBaselines, measureMcpSizes, overheadReport, renderOverhead } from "./overhead.js";
59
- import { deferrableConfigured, measureStarts, START_ROWS } from "./starts.js";
61
+ import { CALL_ROWS, deferrableApp, deferrableConfigured, measureStarts, START_ROWS } from "./starts.js";
62
+ import { DEFER_APP_TOOLS_ENV } from "./mod/logic.js";
60
63
  import { applySplit, planSplit, renderSplit } from "./split.js";
61
64
  import { ciReport, renderCiMarkdown, renderCiText } from "./ci.js";
62
65
  import { renderReads, repeatedReads } from "./reads.js";
@@ -67,6 +70,7 @@ import { renderPayback, subagentPayback, SUBAGENT_CANDIDATE } from "./subagentpa
67
70
  import { compactionQuality, renderCompactionQuality, QUALITY_ROWS } from "./compactquality.js";
68
71
  import { isHandoffId, listHandoffs, readHandoff, renderHandoffList, stripControls } from "./handoff.js";
69
72
  import { claudeLimitFit, limitSavingsLines, limitsReport, renderLimits, renderLimitsReport } from "./limits.js";
73
+ import { creditsLines, creditsReport } from "./credits.js";
70
74
  import { currentTranscript, findSession, recall, renderRecall } from "./recall.js";
71
75
  import { measureSubagentCosts, renderCostMedians, saveSubagentCosts } from "./fanout.js";
72
76
  import { applyPrune, canonical, installedSkills, planPrune, renderPrune, undoPrune } from "./prune.js";
@@ -127,13 +131,17 @@ Start here:
127
131
  as billed. --share: totals only, to paste
128
132
  context-doctor fix [--apply ids|all] [--share] What to change, ranked by dollars on your own
129
133
  sessions (compact earlier, the cache lifetime,
130
- autopilot, MCP tool search, unused servers, the
131
- subagents' model): each applied only on a yes
132
- (the subagents' model only by name, never by
133
- "all"), \`fix undo\` reverts them, later runs show
134
- what each saved since. A bare \`context-doctor\`
135
- in a terminal shows the same plan on one screen
136
- and asks once about the fixes with no quality cost
134
+ autopilot, MCP tool search, MCP servers loaded up
135
+ front, the Desktop app's own tools, unused servers,
136
+ long Bash output to a file, the subagents' model,
137
+ Codex's auto-compact limit, subagent progress
138
+ summaries): each applied only on a yes (the
139
+ subagents' model and the two MCP deferrals only by
140
+ name, never by "all"), \`fix undo\` reverts them,
141
+ later runs show what each saved since. A bare
142
+ \`context-doctor\` in a terminal shows the same plan
143
+ on one screen and asks once about the fixes with
144
+ no quality cost
137
145
  context-doctor doctor Self-check the installation (configs, hook, skill,
138
146
  MCP handshake) with one pasteable diagnosis
139
147
  context-doctor uninstall Undo install
@@ -414,12 +422,12 @@ async function measureFixInputs(days) {
414
422
  // With autopilot already on, its replay (most of the time) answers nothing `fix` asks.
415
423
  const replaying = progressLine(autopilotOnNow ? "Reading your Claude Code sessions" : "Replaying your Claude Code sessions");
416
424
  const setWindow = currentCompactWindow();
417
- // The starts are measured only when a server of the user's own could have gone whole into them (mcp-defer).
425
+ // A server of the user's own that could have gone whole into a start (mcp-defer); the Desktop app's own servers (desktop-tools-defer) are measured from every start.
418
426
  const configured = claudeMcpConfigs(cwd).some((c) => c.scope !== ".mcp.json");
419
427
  // Each transcript read once for every replay below; what an earlier run kept is not read again (scan.ts).
420
428
  prescan([
421
- { paths: claudeTranscripts(days), extractors: [savingsRows(!autopilotOnNow), REQUEST_ROWS, TOOL_OUTPUT_ROWS, ...(configured ? [START_ROWS] : [])] },
422
- { paths: subagentTranscripts(Date.now() - days * 86_400_000), extractors: [REQUEST_ROWS, SUBAGENT_ROWS, TOOL_OUTPUT_ROWS, PROGRESS_ROWS, ...(configured ? [START_ROWS] : [])] },
429
+ { paths: claudeTranscripts(days), extractors: [savingsRows(!autopilotOnNow), REQUEST_ROWS, TOOL_OUTPUT_ROWS, START_ROWS, CALL_ROWS] },
430
+ { paths: subagentTranscripts(Date.now() - days * 86_400_000), extractors: [REQUEST_ROWS, SUBAGENT_ROWS, TOOL_OUTPUT_ROWS, PROGRESS_ROWS, START_ROWS, CALL_ROWS] },
423
431
  ...(setWindow === undefined ? [{ paths: claudeTranscripts(60), extractors: [QUALITY_ROWS] }] : []),
424
432
  { paths: codexRollouts(Date.now() - days * 86_400_000), extractors: [CODEX_COMPACT_ROWS] },
425
433
  ], replaying.tick);
@@ -434,11 +442,14 @@ async function measureFixInputs(days) {
434
442
  const reread = compactionQuality(60, undefined, measuring.tick).extraRereadTokensPerCompaction;
435
443
  measuring.clear();
436
444
  const windowing = progressLine("Replaying an earlier auto-compact window");
437
- const cw = estimateCompactWindows([400_000], days, undefined, reread, windowing.tick);
445
+ // The Desktop app's own window offer, answered: that model's sessions are left as they ran.
446
+ const app = readAppWindows({ cwd });
447
+ const cw = estimateCompactWindows([400_000], days, undefined, reread, windowing.tick, { leaveModels: app.answers.map((a) => a.model) });
438
448
  windowing.clear();
439
449
  const est = cw.estimates[0];
450
+ const appLines = appWindowLines(app, cw.leftAlone?.sessions ?? 0);
440
451
  if (cw.sessions > 0 && est)
441
- compactWindow = { window: est.window, savedUsd: est.savedUsd, savedShare: est.savedPct, compactionsPerWeek: (est.compactions / cw.days) * 7, nowPerWeek: (cw.actualCompactions / cw.days) * 7 };
452
+ compactWindow = { window: est.window, savedUsd: est.savedUsd, savedShare: est.savedPct, compactionsPerWeek: (est.compactions / cw.days) * 7, nowPerWeek: (cw.actualCompactions / cw.days) * 7, ...(appLines.length ? { app: { lines: appLines, answered: app.answers.map((a) => modelName(a.model)), leftSessions: cw.leftAlone?.sessions ?? 0 } } : {}) };
442
453
  }
443
454
  const ttling = progressLine("Replaying both cache lifetimes");
444
455
  const ttl = estimateCacheTtl(days, { onProgress: ttling.tick });
@@ -495,7 +506,16 @@ async function measureFixInputs(days) {
495
506
  userSettings = JSON.parse(readFileSync(join(claudeDir(), "settings.json"), "utf8")) ?? {};
496
507
  }
497
508
  catch { /* none */ }
498
- const deferrable = configured ? deferrableConfigured(measureStarts({ days, cwd })) : [];
509
+ const starts = measureStarts({ days, cwd });
510
+ const deferrable = configured ? deferrableConfigured(starts) : [];
511
+ const appTools = deferrableApp(starts);
512
+ // CONTEXT_DOCTOR_DEFER_MCP: the user's settings.json env (fix writes it there), else a shell's own value (not the session's copy of a settings value).
513
+ const userDt = sources.find((s) => s.name === "user")?.settings.env?.[DEFER_APP_TOOLS_ENV];
514
+ const desktopToolsSet = userDt !== undefined && userDt !== null && String(userDt).trim() !== ""
515
+ ? { value: String(userDt), where: `${tilde(join(claudeDir(), "settings.json"))} env` }
516
+ : !underClaudeCode() && shellSet(DEFER_APP_TOOLS_ENV, sources, process.env)
517
+ ? { value: process.env[DEFER_APP_TOOLS_ENV], where: "the environment" }
518
+ : undefined;
499
519
  let recordProblem;
500
520
  try {
501
521
  loadFixRecords();
@@ -504,7 +524,11 @@ async function measureFixInputs(days) {
504
524
  recordProblem = e.message;
505
525
  }
506
526
  const sessions = report.sessions.length;
507
- const ids = ["compact-window", "cache-ttl", "cache-ttl-subagents", "tool-search", "subagent-model", "tool-output", "codex-compact", "progress-summaries"];
527
+ const ids = ["compact-window", "cache-ttl", "cache-ttl-subagents", "tool-search", "subagent-model", "tool-output", "codex-compact", "progress-summaries", "desktop-tools-defer"];
528
+ const overrides = Object.fromEntries(ids.map((id) => [id, fixOverrides(id, { cwd })]));
529
+ // The mod is what reads the variable: without the plugin, nothing moves.
530
+ if (appTools.length && !claudePluginEnabled())
531
+ overrides["desktop-tools-defer"].push("context-doctor's Claude Code plugin is not enabled, and its mod is what reads this (/plugin install context-doctor@context-doctor inside Claude Code)");
508
532
  return {
509
533
  prunePlan,
510
534
  inputs: {
@@ -518,6 +542,8 @@ async function measureFixInputs(days) {
518
542
  mcpServers: toolSearchOff ? servers.length : 0,
519
543
  prune: prunePlan,
520
544
  ...(deferrable.length ? { mcpDefer: { servers: deferrable, days } } : {}),
545
+ ...(appTools.length ? { desktopTools: { servers: appTools.map((s) => ({ name: s.name, tools: s.tools, tokens: s.tokens, starts: s.starts, calledStarts: s.calledStarts, usd: s.usd, unusedUsd: s.unusedUsd, calledUsd: s.calledUsd })), days } } : {}),
546
+ ...(desktopToolsSet ? { desktopToolsSet } : {}),
521
547
  subagentModel,
522
548
  subagentModelSet,
523
549
  // The newest ab --via claude-code comparison of Sonnet 5.5 with another model: the subagent-model line quotes it.
@@ -528,7 +554,7 @@ async function measureFixInputs(days) {
528
554
  ...(psState.set ? { progressSummariesSet: psState.set } : {}),
529
555
  ...(codexCompact.requests > 0 ? { codexCompact } : {}),
530
556
  ...(cxSet ? { codexCompactSet: { raw: cxSet.raw, where: cxSet.where } } : {}),
531
- overrides: Object.fromEntries(ids.map((id) => [id, fixOverrides(id, { cwd })])),
557
+ overrides,
532
558
  recordProblem,
533
559
  // The installs a setting is too new for are named on its fix.
534
560
  claudeCodeInstalls: claudeCodeInstallsFromEnv(),
@@ -1169,7 +1195,7 @@ async function main() {
1169
1195
  const reread = compactionQuality(60, undefined, measuring.tick).extraRereadTokensPerCompaction;
1170
1196
  measuring.clear();
1171
1197
  const windowing = progressLine("Replaying an earlier auto-compact window");
1172
- const cwReport = estimateCompactWindows([setWindow ?? 400_000], args.days ?? 30, undefined, reread, windowing.tick);
1198
+ const cwReport = estimateCompactWindows([setWindow ?? 400_000], args.days ?? 30, undefined, reread, windowing.tick, { leaveModels: readAppWindows().answers.map((a) => a.model) });
1173
1199
  windowing.clear();
1174
1200
  const est = cwReport.estimates[0];
1175
1201
  const cwLine = cwReport.sessions > 0 && est
@@ -1261,6 +1287,11 @@ async function main() {
1261
1287
  console.log(`✓ autoCompactWindow = ${w} in ${tilde(settingsPath())}${note ? ` (${note})` : ""}.`);
1262
1288
  console.log(" Claude Code sessions started from now on compact as if the window were that size,");
1263
1289
  console.log(" in the terminal, IDEs and the desktop app. Check in a session with /context.");
1290
+ const answered = readAppWindows().answers;
1291
+ if (answered.length) {
1292
+ console.log(` You answered the Desktop app's own window offer for ${answered.map((a) => modelName(a.model)).join(", ")}: whether this setting`);
1293
+ console.log(" or the app's choice wins there is not recorded on this computer.");
1294
+ }
1264
1295
  const over = fixOverrides("compact-window");
1265
1296
  if (over.length) {
1266
1297
  console.log(` ⚠ It will not take effect while ${over.join("; ")} ${over.length === 1 ? "overrides" : "override"} it.`);
@@ -1281,14 +1312,17 @@ async function main() {
1281
1312
  const reread = compactionQuality(60, undefined, measuring.tick).extraRereadTokensPerCompaction;
1282
1313
  measuring.clear();
1283
1314
  const replaying = progressLine("Replaying your sessions at each window");
1284
- const cw = estimateCompactWindows(windows.sort((a, b) => a - b), args.days ?? 30, undefined, reread, replaying.tick);
1315
+ const app = readAppWindows();
1316
+ const cw = estimateCompactWindows(windows.sort((a, b) => a - b), args.days ?? 30, undefined, reread, replaying.tick, { leaveModels: app.answers.map((a) => a.model) });
1285
1317
  replaying.clear();
1318
+ const appLines = appWindowLines(app, cw.leftAlone?.sessions ?? 0);
1286
1319
  if (args.json) {
1287
- console.log(JSON.stringify({ ...cw, current: current ?? null }, null, 2));
1320
+ // The Desktop app's answers and the server's windows, only when there are some (the output is otherwise as before).
1321
+ console.log(JSON.stringify({ ...cw, current: current ?? null, ...(appLines.length ? { desktopApp: app } : {}) }, null, 2));
1288
1322
  return;
1289
1323
  }
1290
1324
  const limitFit = claudeLimitFit(limitsReport(cw.days, { claudeOnly: true }));
1291
- console.log(renderCompactWindows(cw, current, (estimates) => limitSavingsLines(limitFit, estimates.map((e) => [`${Math.round(e.window / 1000)}k window`, Math.max(0, e.savedUsd)]), cw.days)));
1325
+ console.log(renderCompactWindows(cw, current, (estimates) => limitSavingsLines(limitFit, estimates.map((e) => [`${Math.round(e.window / 1000)}k window`, Math.max(0, e.savedUsd)]), cw.days), appLines, app.served.length > 0));
1292
1326
  return;
1293
1327
  }
1294
1328
  if (args.command === "autopilot") {
@@ -1550,7 +1584,9 @@ async function main() {
1550
1584
  console.log(copyToClipboard(text) ? "\n(copied to the clipboard)" : "\n(no clipboard tool found; copy the lines above)");
1551
1585
  return;
1552
1586
  }
1553
- console.log(args.json ? JSON.stringify(report, null, 2) : renderLimits(report));
1587
+ // Requests paid from usage credits past a limit: read only when the ledger says a limit ran out.
1588
+ const credits = creditsReport(report.days, { now: report.now });
1589
+ console.log(args.json ? JSON.stringify(credits ? { ...report, credits } : report, null, 2) : renderLimits(report, credits ? creditsLines(credits, report.now) : []));
1554
1590
  return;
1555
1591
  }
1556
1592
  if (args.command === "spend") {
@@ -1795,8 +1831,8 @@ async function main() {
1795
1831
  // One read of each Claude Code transcript for both counts (scan.ts); subagents hold MCP calls too.
1796
1832
  const mains = claudeTranscripts(args.days ?? 30);
1797
1833
  prescan([
1798
- { paths: mains, extractors: [REQUEST_ROWS, MCP_ROWS, START_ROWS] },
1799
- { paths: mains.flatMap((p) => subagentFiles(p).map((f) => f.file)), extractors: [MCP_ROWS, REQUEST_ROWS, START_ROWS] },
1834
+ { paths: mains, extractors: [REQUEST_ROWS, MCP_ROWS, START_ROWS, CALL_ROWS] },
1835
+ { paths: mains.flatMap((p) => subagentFiles(p).map((f) => f.file)), extractors: [MCP_ROWS, REQUEST_ROWS, START_ROWS, CALL_ROWS] },
1800
1836
  ], sessions.tick);
1801
1837
  const report = overheadReport({
1802
1838
  days: args.days,
package/dist/clihelp.d.ts CHANGED
@@ -4,7 +4,11 @@
4
4
  * cut out of the full help text. Kept apart from cli.ts, which runs on
5
5
  * import, so they can be tested directly.
6
6
  */
7
- /** Edit distance (insert, delete, substitute; each 1). */
7
+ /**
8
+ * Edit distance (insert, delete, substitute, swap two neighbours; each 1).
9
+ * The swap is the commonest typo: without it `--reprot` was as far from
10
+ * `--repeat` as from `--report`, and the first listed won.
11
+ */
8
12
  export declare function levenshtein(a: string, b: string): number;
9
13
  /**
10
14
  * The closest candidate, when it is close enough to be a typo: within a
package/dist/clihelp.js CHANGED
@@ -4,16 +4,24 @@
4
4
  * cut out of the full help text. Kept apart from cli.ts, which runs on
5
5
  * import, so they can be tested directly.
6
6
  */
7
- /** Edit distance (insert, delete, substitute; each 1). */
7
+ /**
8
+ * Edit distance (insert, delete, substitute, swap two neighbours; each 1).
9
+ * The swap is the commonest typo: without it `--reprot` was as far from
10
+ * `--repeat` as from `--report`, and the first listed won.
11
+ */
8
12
  export function levenshtein(a, b) {
9
13
  if (a === b)
10
14
  return 0;
15
+ let before = [];
11
16
  let prev = Array.from({ length: b.length + 1 }, (_, j) => j);
12
17
  for (let i = 1; i <= a.length; i++) {
13
18
  const cur = [i];
14
19
  for (let j = 1; j <= b.length; j++) {
15
20
  cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
21
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1])
22
+ cur[j] = Math.min(cur[j], before[j - 2] + 1);
16
23
  }
24
+ before = prev;
17
25
  prev = cur;
18
26
  }
19
27
  return prev[b.length];
@@ -0,0 +1,176 @@
1
+ /**
2
+ * Codex's footer, drawn by our MCP server (ROADMAP G5).
3
+ *
4
+ * Codex 0.171.0 lets an MCP tool be a status line, behind its
5
+ * `tui_extensions_statusline` experiment (`/experimental`, Custom status
6
+ * line). The shapes here are Codex's own (openai/codex, codex-rs, read
7
+ * 2026-11-20): `tui/src/statusline_provider/descriptor.rs` takes a tool
8
+ * whose `_meta["openai/ui"].entrypoints` holds exactly one
9
+ * `{ type: "statusline", resourceUri: "ui://..." }`, the tool's title being
10
+ * its name in the `/statusline` picker; `tui/src/chatwidget/statusline_reader.rs`
11
+ * then reads that resource with the displayed thread's snapshot in
12
+ * `params._meta["com.openai/codex-statusline-state"]`, gives each read one
13
+ * second, waits a second and reads again; `statusline_reader/resource.rs`
14
+ * wants exactly one text content at the advertised URI, `application/json`,
15
+ * holding a UI tree (`tui/src/ui_tree.rs`: unknown fields refused, 64 KiB,
16
+ * 256 non-null nodes, depth 16, 16 KiB of text; `null` clears the footer).
17
+ * An error or a timeout stops the polling until the person picks the
18
+ * provider again, so a read here never fails: at worst it answers the last
19
+ * line it drew, or `null`.
20
+ *
21
+ * What it shows, short and plain, only what is known:
22
+ * context 412k of 1.0M (41%) $3.21 this session limits: 5h 23%, weekly 41%
23
+ * The context and the plan's windows are the snapshot's own figures. The
24
+ * dollars are the session's price as `spend` and the every-prompt hook count
25
+ * it, at list prices, the agents the thread spawned included (sessionTotal,
26
+ * sharing the hook's per-session entries). That reads the thread's rollout,
27
+ * whole on a change, which on a 70 MB rollout takes longer than a footer
28
+ * may wait, so it runs in a worker thread, at most one at a time, cached
29
+ * per thread and refreshed when the thread's token totals move; a read
30
+ * waits for it at most READ_BUDGET_MS and otherwise draws the last price
31
+ * it had, or, before the first, the snapshot's own totals priced at the
32
+ * model's rates (the thread alone).
33
+ *
34
+ * Nothing is drawn unasked: Codex shows it only to someone who turned the
35
+ * experiment on and picked it in `/statusline`, and the tool is listed only
36
+ * to Codex (mcp.ts).
37
+ */
38
+ import type { Worker } from "node:worker_threads";
39
+ /** The resource Codex reads; the tool advertises it. */
40
+ export declare const CODEX_STATUSLINE_URI = "ui://context-doctor/statusline";
41
+ /** Where Codex puts the displayed thread's snapshot in a read's `params._meta`. */
42
+ export declare const CODEX_STATUSLINE_STATE = "com.openai/codex-statusline-state";
43
+ /** The tool's `_meta`: exactly one statusline entrypoint (Codex ignores a tool with two). */
44
+ export declare const CODEX_STATUSLINE_META: {
45
+ "openai/ui": {
46
+ entrypoints: {
47
+ type: string;
48
+ resourceUri: string;
49
+ }[];
50
+ };
51
+ };
52
+ /** The worker thread's role, passed as its `workerData`. */
53
+ export declare const PRICE_WORKER_ROLE = "context-doctor/codex-statusline-price";
54
+ /** Codex gives a read one second; this answers well inside it. */
55
+ export declare const READ_BUDGET_MS = 200;
56
+ type Color = string;
57
+ export type UiNode = string | {
58
+ type: "text";
59
+ props?: {
60
+ color?: Color | null;
61
+ weight?: "normal" | "bold" | null;
62
+ };
63
+ children: Array<UiNode | null>;
64
+ } | {
65
+ type: "row";
66
+ props: {
67
+ gap: number;
68
+ wrap?: "nowrap" | "wrap";
69
+ justify?: "start" | "center" | "end" | "between";
70
+ };
71
+ children: Array<UiNode | null>;
72
+ };
73
+ /** Codex's limits on a tree's JSON (ui_tree/decode.rs). */
74
+ export declare const TREE_LIMITS: {
75
+ bytes: number;
76
+ nodes: number;
77
+ depth: number;
78
+ textBytes: number;
79
+ };
80
+ /** A tree's JSON measured as Codex measures it; `ok` when it is within every limit. */
81
+ export declare function measureTree(json: string): {
82
+ ok: boolean;
83
+ bytes: number;
84
+ nodes: number;
85
+ depth: number;
86
+ textBytes: number;
87
+ };
88
+ interface RateLimitWindow {
89
+ used_percent?: number;
90
+ window_minutes?: number | null;
91
+ resets_at?: number | null;
92
+ }
93
+ /** The parts of Codex's `StatuslineState` this reads. Everything optional: a field Codex leaves out is simply not shown. */
94
+ export interface CodexStatuslineState {
95
+ account?: {
96
+ rate_limits?: Array<{
97
+ limit_id?: string;
98
+ primary_limit?: RateLimitWindow | null;
99
+ secondary_limit?: RateLimitWindow | null;
100
+ }>;
101
+ };
102
+ thread?: {
103
+ id?: string;
104
+ model?: {
105
+ id?: string;
106
+ display_name?: string;
107
+ };
108
+ usage?: {
109
+ context?: {
110
+ context_window_size?: number;
111
+ used_tokens?: number;
112
+ used_percentage?: number;
113
+ };
114
+ total?: {
115
+ total_input_tokens?: number;
116
+ cache_read_input_tokens?: number;
117
+ cache_write_input_tokens?: number;
118
+ other_input_tokens?: number;
119
+ output_tokens?: number;
120
+ };
121
+ cost?: {
122
+ total_cost_usd?: number;
123
+ total_credits?: number;
124
+ };
125
+ };
126
+ };
127
+ }
128
+ /**
129
+ * The thread's own token totals priced at its model's list rates, the tier
130
+ * of its current context: the price before the rollout's is known. The
131
+ * thread alone (no spawned agents); undefined for a model with no price.
132
+ */
133
+ export declare function snapshotUsd(state: CodexStatuslineState, at?: number): number | undefined;
134
+ /**
135
+ * The footer for one snapshot, or null when nothing is known (Codex then
136
+ * clears it). `sessionUsd`: the session's price, when known; otherwise the
137
+ * snapshot's totals priced, then Codex's own figure.
138
+ */
139
+ export declare function renderCodexStatusline(state: CodexStatuslineState | undefined, sessionUsd?: number, nowMs?: number): UiNode | null;
140
+ /**
141
+ * The rollout of a Codex thread: `sessions/YYYY/MM/DD/rollout-<time>-<id>.jsonl`
142
+ * in the day folders around the time its id was made (local and UTC), then
143
+ * the archive, then every session folder.
144
+ */
145
+ export declare function rolloutFor(threadId: string, home?: string): string | undefined;
146
+ /** The worker side: prices a thread's session on request (sessionprice.ts), one at a time. */
147
+ export declare function servePriceWorker(): Promise<void>;
148
+ /**
149
+ * One per server process: what each thread's session has cost, kept, and
150
+ * the worker that reads it. `spawn` starts the worker (mcp.ts knows the
151
+ * file it runs from); undefined, or a worker that fails, leaves the
152
+ * snapshot's own figures.
153
+ */
154
+ export declare class CodexStatusline {
155
+ private spawn?;
156
+ private worker;
157
+ private broken;
158
+ private next;
159
+ private waiting;
160
+ private inFlight;
161
+ private prices;
162
+ private lastGood;
163
+ constructor(spawn?: (() => Worker) | undefined);
164
+ private ask;
165
+ /** The thread's session price: cached, refreshed in the background, waited for at most `budgetMs`. */
166
+ private price;
167
+ /**
168
+ * The resource's text for one read: a UI tree's JSON, or "null". Never
169
+ * throws and answers within about `budgetMs`: a failure answers the last
170
+ * line drawn for the thread.
171
+ */
172
+ read(rawState: unknown, budgetMs?: number): Promise<string>;
173
+ /** Stops the worker (tests). */
174
+ close(): Promise<void>;
175
+ }
176
+ export {};