context-doctor 0.37.0 → 0.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/doctor.js CHANGED
@@ -6,7 +6,7 @@
6
6
  * when any check fails (✗), so a script can tell; an app that is absent, or
7
7
  * that nothing was installed into, is a note (–), not a failure.
8
8
  */
9
- import { autopilotPaths, health, installedVersion, proxyUrl, recentSurfaces } from "./autopilot.js";
9
+ import { autopilotPaths, DEFAULT_AUTOPILOT_PORT, health, installedVersion, portOccupant, proxyUrl, recentSurfaces } from "./autopilot.js";
10
10
  import { spawn } from "node:child_process";
11
11
  import { accessSync, constants as fsConstants, existsSync, readFileSync } from "node:fs";
12
12
  import { homedir, platform } from "node:os";
@@ -21,6 +21,7 @@ import { COPILOT_HOOK_EVENT, copilotHookFilePath, copilotLegacyConfigPath, copil
21
21
  import { describeDesktopUsage, desktopUsage } from "./desktopusage.js";
22
22
  import { withInvocation } from "./invocation.js";
23
23
  import { describeInstalls, modelSwitchReadiness, PRE_MODEL_SWITCH_SINCE } from "./modelswitch.js";
24
+ import { describeCosts, subagentCostsPath } from "./fanout.js";
24
25
  function claudeDesktopConfigPath() {
25
26
  switch (platform()) {
26
27
  case "darwin": return join(homedir(), "Library", "Application Support", "Claude", "claude_desktop_config.json");
@@ -143,6 +144,33 @@ function pluginEnabled(layers) {
143
144
  }
144
145
  return [...state.values()].some(Boolean);
145
146
  }
147
+ /** "headroom (pid 4242)", or "another program". */
148
+ function occupantName(o) {
149
+ return `${o.name ?? "another program"}${o.pid ? ` (pid ${o.pid})` : ""}`;
150
+ }
151
+ /**
152
+ * The subagent price (PreToolUse on the Agent tool, fanout.ts): registered
153
+ * with a matcher that names the tool by both its names, and what the medians
154
+ * it quotes come from.
155
+ */
156
+ function fanoutCheck(settings, plugin) {
157
+ const label = "Subagent price";
158
+ const entries = Array.isArray(settings.hooks?.PreToolUse) ? settings.hooks.PreToolUse : [];
159
+ const ours = entries.find((e) => /context-doctor|cli\.js"?\s+hook/.test(e.hooks?.[0]?.command ?? ""));
160
+ let costs;
161
+ try {
162
+ costs = JSON.parse(readFileSync(subagentCostsPath(), "utf8"));
163
+ }
164
+ catch { /* not measured yet */ }
165
+ const basis = costs?.all ? `; quotes your medians (${describeCosts(costs)})` : "; quotes your medians once you have run a few subagents";
166
+ if (ours && !/\bAgent\b/.test(ours.matcher ?? ""))
167
+ return { label, status: "warn", detail: `PreToolUse entry without the Agent matcher (${JSON.stringify(ours.matcher ?? "")}): it runs before every tool; re-run context-doctor install` };
168
+ if (ours)
169
+ return { label, status: "ok", detail: `PreToolUse on the Agent tool: before a subagent starts, its price at your median and the Sonnet option; never blocks${basis}` };
170
+ if (plugin)
171
+ return { label, status: "ok", detail: `PreToolUse: provided by the context-doctor plugin${basis}` };
172
+ return { label, status: "warn", detail: "not registered: subagents start with no price shown; run context-doctor install" };
173
+ }
146
174
  /**
147
175
  * The model-switch warning (PreModelSwitch). Its entry in settings.json is a
148
176
  * failure next to a Claude Code older than the event: that version skips the
@@ -375,6 +403,7 @@ export async function runDoctor() {
375
403
  else if (!ours && plugin) {
376
404
  checks.push({ label: "Every-prompt hook", status: "ok", detail: "provided by the context-doctor plugin" });
377
405
  checks.push({ label: "Compaction hook", status: "ok", detail: "PreCompact: provided by the context-doctor plugin" });
406
+ checks.push(fanoutCheck(settings, plugin));
378
407
  }
379
408
  else if (!ours) {
380
409
  checks.push(missingHook("Every-prompt hook", claudeMcp));
@@ -392,6 +421,7 @@ export async function runDoctor() {
392
421
  checks.push(preOurs
393
422
  ? { label: "Compaction hook", status: "ok", detail: "PreCompact: each compaction's summary keeps the session's files, open tasks, your instructions and failing commands" }
394
423
  : { label: "Compaction hook", status: "warn", detail: "not registered: compactions use generic instructions; run context-doctor install" });
424
+ checks.push(fanoutCheck(settings, plugin));
395
425
  }
396
426
  checks.push(modelSwitchCheck(settings, plugin));
397
427
  }
@@ -635,6 +665,20 @@ export async function runDoctor() {
635
665
  }
636
666
  if (!existsSync(paths.config)) {
637
667
  checks.push({ label: "Autopilot", status: "skip", detail: "off (context-doctor autopilot on: clears stale tool output in every new Claude Code session)" });
668
+ // Another local proxy on autopilot's port: `autopilot on` would not start there.
669
+ const other = await portOccupant(DEFAULT_AUTOPILOT_PORT);
670
+ if (other.listening && !other.ours) {
671
+ checks.push({
672
+ label: "Autopilot port",
673
+ status: "warn",
674
+ detail: other.bindable
675
+ ? `${occupantName(other)} listens on port ${DEFAULT_AUTOPILOT_PORT} on another address: \`autopilot on\` would start beside it on 127.0.0.1 and take the traffic sent to 127.0.0.1 (Claude Code's), while apps that use localhost:${DEFAULT_AUTOPILOT_PORT} may reach ${occupantName(other)}; to keep them apart: context-doctor autopilot on --port 8788`
676
+ : `${occupantName(other)} already listens on ${proxyUrl(DEFAULT_AUTOPILOT_PORT)}: \`autopilot on\` could not start there; use another port (context-doctor autopilot on --port 8788)`,
677
+ });
678
+ }
679
+ else if (other.onIpv6Loopback) {
680
+ checks.push({ label: "Autopilot port", status: "warn", detail: `${other.onIpv6Loopback} listens on [::1]:${DEFAULT_AUTOPILOT_PORT}: apps that use localhost:${DEFAULT_AUTOPILOT_PORT} may reach it instead of autopilot, which uses 127.0.0.1` });
681
+ }
638
682
  }
639
683
  else if (!cfg) {
640
684
  let routedTo;
@@ -676,6 +720,19 @@ export async function runDoctor() {
676
720
  : h.ok && h.autopilot && routed
677
721
  ? { label: "Autopilot", status: "ok", detail: `proxy up on ${proxyUrl(cfg.port)}, Claude Code routed through it${seen >= 0 ? ` (${seen} requests since start)` : ""}${paused ? " (PAUSED: passthrough)" : ""}` }
678
722
  : { label: "Autopilot", status: "fail", detail: !h.ok ? `proxy not answering on ${proxyUrl(cfg.port)}: the next Claude Code prompt restarts it; or run: context-doctor autopilot on` : "settings.json no longer routes Claude Code to the proxy: run context-doctor autopilot on" });
723
+ // Not ours, yet listening on our port: with Claude Code routed there,
724
+ // its requests go through that program, and the proxy cannot restart.
725
+ const other = await portOccupant(cfg.port);
726
+ if (!h.ok && other.listening && !other.ours) {
727
+ checks.push({
728
+ label: "Autopilot port",
729
+ status: "fail",
730
+ detail: `${occupantName(other)} answers on ${proxyUrl(cfg.port)} instead of the proxy${routed ? ", and Claude Code's requests go to it" : ""}${other.bindable ? " (the proxy can start beside it on 127.0.0.1: the next Claude Code prompt restarts it)" : ""}: stop it, or move autopilot (context-doctor autopilot off, then autopilot on --port 8788)`,
731
+ });
732
+ }
733
+ else if (other.onIpv6Loopback) {
734
+ checks.push({ label: "Autopilot port", status: "warn", detail: `${other.onIpv6Loopback} listens on [::1]:${cfg.port}: Claude Code reaches autopilot at 127.0.0.1, but apps that use localhost:${cfg.port} may reach ${other.onIpv6Loopback} instead` });
735
+ }
679
736
  }
680
737
  }
681
738
  const mark = { ok: "✓", warn: "!", fail: "✗", skip: "–" };
@@ -0,0 +1,131 @@
1
+ /**
2
+ * The fan-out guard: a price on a subagent before it starts.
3
+ *
4
+ * Claude Code launches subagents with its Agent tool (named Task before
5
+ * 2.1.63; 2.1.308 still maps a "Task" matcher to it, 2.1.62 knows only
6
+ * "Task", so the matcher is "Agent|Task"). Each one has its own context and
7
+ * its own bill, and a fan-out of five is five bills, with nothing shown
8
+ * before they start. A PreToolUse hook on that tool runs first: it answers
9
+ * with a `systemMessage` the user sees, and once per session an
10
+ * `additionalContext` note the model reads, and never a permission decision,
11
+ * so the subagent always starts (verified in the hooks docs and both
12
+ * binaries: no decision means the normal permission flow; a hook that fails
13
+ * or times out does not block a PreToolUse call; only exit 2 would, and this
14
+ * never exits 2). PreToolUse is in 2.1.62's event list, so it needs none of
15
+ * PreModelSwitch's version guard.
16
+ *
17
+ * The price is the user's own: the median cost of the subagents of that
18
+ * type (and model) in their transcripts, the same reading `context-doctor
19
+ * subagents` does, cached for a day. Where the subagent would run on Opus or
20
+ * Fable, the note gives the Sonnet price too: the Agent tool takes
21
+ * `model: "sonnet"`.
22
+ */
23
+ /** The subagent tool, by its current name and its pre-2.1.63 alias. */
24
+ export declare const FANOUT_MATCHER = "Agent|Task";
25
+ export interface CostStat {
26
+ n: number;
27
+ median: number;
28
+ p90: number;
29
+ /** The model most of these ran on. */
30
+ model?: string;
31
+ }
32
+ export interface SubagentCosts {
33
+ computedAt: number;
34
+ days: number;
35
+ /** Subagents measured (each priced at list price, as `subagents` does). */
36
+ n: number;
37
+ all?: CostStat;
38
+ byType: Record<string, CostStat>;
39
+ /** "<type>|<model>" */
40
+ byTypeModel: Record<string, CostStat>;
41
+ byModel: Record<string, CostStat>;
42
+ }
43
+ export declare function subagentCostsPath(): string;
44
+ /**
45
+ * Each subagent's bill in the last `days`, newest transcripts first, by
46
+ * type and model. `limit` and `budgetMs` bound the work when the hook has
47
+ * to measure (the cache is a day old): the newest subagents are the best
48
+ * guide anyway.
49
+ */
50
+ export declare function measureSubagentCosts(days?: number, opts?: {
51
+ limit?: number;
52
+ budgetMs?: number;
53
+ sessions?: string[];
54
+ now?: number;
55
+ }): SubagentCosts;
56
+ export declare function saveSubagentCosts(c: SubagentCosts, path?: string): void;
57
+ /** The cached medians when under a day old, else measured now (bounded) and cached. */
58
+ export declare function subagentCosts(now?: number, path?: string): SubagentCosts | undefined;
59
+ export interface FanoutEstimate {
60
+ type: string;
61
+ model?: string;
62
+ median: number;
63
+ p90: number;
64
+ runs: number;
65
+ /** The Sonnet option, when the subagent would run on Opus or Fable. */
66
+ cheaper?: {
67
+ model: string;
68
+ median: number;
69
+ measured: boolean;
70
+ };
71
+ }
72
+ /** The model a type is pinned to: 90%+ of its runs (3 or more) in one family, priced at that family's most-run model. */
73
+ export declare function pinnedModel(costs: SubagentCosts, type: string): string | undefined;
74
+ /** What a subagent of this type on this model costs, from the user's own runs. Undefined with too few. */
75
+ export declare function estimateSubagent(costs: SubagentCosts, type: string, modelAlias?: string, parentModel?: string): FanoutEstimate | undefined;
76
+ /** PreToolUse input for the Agent tool, as far as this reads it. */
77
+ export interface FanoutInput {
78
+ session_id?: string;
79
+ transcript_path?: string;
80
+ tool_name?: string;
81
+ tool_input?: {
82
+ subagent_type?: unknown;
83
+ model?: unknown;
84
+ description?: unknown;
85
+ run_in_background?: unknown;
86
+ };
87
+ }
88
+ /**
89
+ * One launch, as the session's launch log records it. The log is appended
90
+ * to before it is read, so hooks that run at once for a fan-out (one per
91
+ * subagent) each see the launches before their own and decide alone:
92
+ * exactly one is the first of its type, the third is the burst. A shared
93
+ * state file read and written back by each would lose all but one write.
94
+ */
95
+ export interface SpawnLine {
96
+ t: number;
97
+ type: string;
98
+ /** Unique per launch. */
99
+ id: string;
100
+ /** This launch was quoted a cheaper model (the model gets one note, on the first such launch). */
101
+ c: boolean;
102
+ }
103
+ /** The session's launch log, beside the hook's per-session state. */
104
+ export declare function spawnLogPath(sessionId: string): string;
105
+ /** Append this launch, then read the log back (its last 64 KB: hundreds of launches). */
106
+ export declare function recordSpawn(path: string, line: SpawnLine): SpawnLine[];
107
+ /** What a launch's input says: its type and the model alias it asks for. */
108
+ export declare function launchOf(input: FanoutInput): {
109
+ type: string;
110
+ alias?: string;
111
+ } | undefined;
112
+ /**
113
+ * What to say before this launch, from the session's launch log (this one
114
+ * included, as `own`). The user sees the price on the first launch of a type
115
+ * in the session and when launches bunch up (3 within two minutes, then
116
+ * every 5th); the model gets one short note a session, on the first launch
117
+ * that was quoted a cheaper model.
118
+ */
119
+ export declare function fanoutMessage(est: FanoutEstimate | undefined, alias: string | undefined, log: SpawnLine[], own: SpawnLine): {
120
+ systemMessage?: string;
121
+ additionalContext?: string;
122
+ };
123
+ /** The whole PreToolUse answer: estimate, log, decide. Silent (an empty object) for anything else. */
124
+ export declare function fanoutHook(input: FanoutInput, costs: SubagentCosts | undefined, sessionId: string, now?: number): {
125
+ systemMessage?: string;
126
+ additionalContext?: string;
127
+ };
128
+ /** For `doctor` and the docs: where the medians come from. */
129
+ export declare function describeCosts(c: SubagentCosts | undefined): string;
130
+ /** The medians the subagent price quotes, for `context-doctor subagents`. */
131
+ export declare function renderCostMedians(c: SubagentCosts): string[];
package/dist/fanout.js ADDED
@@ -0,0 +1,317 @@
1
+ /**
2
+ * The fan-out guard: a price on a subagent before it starts.
3
+ *
4
+ * Claude Code launches subagents with its Agent tool (named Task before
5
+ * 2.1.63; 2.1.308 still maps a "Task" matcher to it, 2.1.62 knows only
6
+ * "Task", so the matcher is "Agent|Task"). Each one has its own context and
7
+ * its own bill, and a fan-out of five is five bills, with nothing shown
8
+ * before they start. A PreToolUse hook on that tool runs first: it answers
9
+ * with a `systemMessage` the user sees, and once per session an
10
+ * `additionalContext` note the model reads, and never a permission decision,
11
+ * so the subagent always starts (verified in the hooks docs and both
12
+ * binaries: no decision means the normal permission flow; a hook that fails
13
+ * or times out does not block a PreToolUse call; only exit 2 would, and this
14
+ * never exits 2). PreToolUse is in 2.1.62's event list, so it needs none of
15
+ * PreModelSwitch's version guard.
16
+ *
17
+ * The price is the user's own: the median cost of the subagents of that
18
+ * type (and model) in their transcripts, the same reading `context-doctor
19
+ * subagents` does, cached for a day. Where the subagent would run on Opus or
20
+ * Fable, the note gives the Sonnet price too: the Agent tool takes
21
+ * `model: "sonnet"`.
22
+ */
23
+ import { appendFileSync, existsSync, readdirSync, readFileSync, statSync, writeFileSync, mkdirSync } from "node:fs";
24
+ import { createHash, randomUUID } from "node:crypto";
25
+ import { basename, dirname, join } from "node:path";
26
+ import { statePath } from "./ledger.js";
27
+ import { listSessions } from "./session.js";
28
+ import { scanSubagent } from "./subagentpay.js";
29
+ import { formatUsd, pricingFor } from "./pricing.js";
30
+ import { tailUsage } from "./statusline.js";
31
+ /** The subagent tool, by its current name and its pre-2.1.63 alias. */
32
+ export const FANOUT_MATCHER = "Agent|Task";
33
+ const DAY = 86_400_000;
34
+ /** Enough runs for a median to mean something. */
35
+ const MIN_RUNS = 3;
36
+ export function subagentCostsPath() {
37
+ return join(dirname(statePath()), ".context-doctor-subagent-costs.json");
38
+ }
39
+ function stat(costs) {
40
+ const s = costs.map((c) => c.usd).sort((a, b) => a - b);
41
+ const models = new Map();
42
+ for (const c of costs)
43
+ if (c.model)
44
+ models.set(c.model, (models.get(c.model) ?? 0) + 1);
45
+ return {
46
+ n: s.length,
47
+ median: s[Math.floor(s.length / 2)],
48
+ p90: s[Math.min(s.length - 1, Math.floor(s.length * 0.9))],
49
+ model: [...models.entries()].sort((a, b) => b[1] - a[1])[0]?.[0],
50
+ };
51
+ }
52
+ /**
53
+ * Each subagent's bill in the last `days`, newest transcripts first, by
54
+ * type and model. `limit` and `budgetMs` bound the work when the hook has
55
+ * to measure (the cache is a day old): the newest subagents are the best
56
+ * guide anyway.
57
+ */
58
+ export function measureSubagentCosts(days = 30, opts = {}) {
59
+ const now = opts.now ?? Date.now();
60
+ const since = now - days * DAY;
61
+ const started = Date.now();
62
+ const parents = opts.sessions ?? listSessions(10_000).filter((s) => s.path.includes(".claude") && s.modifiedAt.getTime() >= since).map((s) => s.path);
63
+ const files = [];
64
+ for (const parent of parents) {
65
+ const dir = join(parent.replace(/\.jsonl$/, ""), "subagents");
66
+ let names;
67
+ try {
68
+ names = readdirSync(dir);
69
+ }
70
+ catch {
71
+ continue;
72
+ }
73
+ for (const f of names) {
74
+ if (!/^agent-.+\.jsonl$/.test(f))
75
+ continue;
76
+ const file = join(dir, f);
77
+ try {
78
+ const at = statSync(file).mtimeMs;
79
+ if (at >= since)
80
+ files.push({ file, meta: join(dir, f.replace(/\.jsonl$/, ".meta.json")), at });
81
+ }
82
+ catch { /* gone */ }
83
+ }
84
+ }
85
+ files.sort((a, b) => b.at - a.at);
86
+ const runs = [];
87
+ for (const f of files.slice(0, opts.limit ?? Infinity)) {
88
+ if (opts.budgetMs !== undefined && Date.now() - started > opts.budgetMs)
89
+ break;
90
+ try {
91
+ const s = scanSubagent(f.file);
92
+ if (!(s.costUsd > 0))
93
+ continue;
94
+ let type = "unknown";
95
+ try {
96
+ type = String(JSON.parse(readFileSync(f.meta, "utf8"))?.agentType ?? "unknown").slice(0, 60);
97
+ }
98
+ catch { /* older Claude Code: no meta */ }
99
+ runs.push({ type, model: s.model, usd: s.costUsd });
100
+ }
101
+ catch { /* unreadable */ }
102
+ }
103
+ const group = (key) => {
104
+ const m = new Map();
105
+ for (const r of runs) {
106
+ const k = key(r);
107
+ if (k)
108
+ m.set(k, [...(m.get(k) ?? []), r]);
109
+ }
110
+ return Object.fromEntries([...m.entries()].map(([k, v]) => [k, stat(v)]));
111
+ };
112
+ return {
113
+ computedAt: now,
114
+ days,
115
+ n: runs.length,
116
+ all: runs.length ? stat(runs) : undefined,
117
+ byType: group((r) => r.type),
118
+ byTypeModel: group((r) => (r.model ? `${r.type}|${r.model}` : undefined)),
119
+ byModel: group((r) => r.model),
120
+ };
121
+ }
122
+ export function saveSubagentCosts(c, path = subagentCostsPath()) {
123
+ try {
124
+ mkdirSync(dirname(path), { recursive: true });
125
+ writeFileSync(path, JSON.stringify(c));
126
+ }
127
+ catch { /* a cache */ }
128
+ }
129
+ /** The cached medians when under a day old, else measured now (bounded) and cached. */
130
+ export function subagentCosts(now = Date.now(), path = subagentCostsPath()) {
131
+ try {
132
+ if (existsSync(path)) {
133
+ const c = JSON.parse(readFileSync(path, "utf8"));
134
+ if (typeof c?.computedAt === "number" && now - c.computedAt < DAY && now >= c.computedAt && c.byType && typeof c.byType === "object")
135
+ return c;
136
+ }
137
+ }
138
+ catch { /* remeasure */ }
139
+ try {
140
+ const c = measureSubagentCosts(30, { limit: 80, budgetMs: 1500, now });
141
+ saveSubagentCosts(c, path);
142
+ return c;
143
+ }
144
+ catch {
145
+ return undefined;
146
+ }
147
+ }
148
+ /** The Agent tool's model aliases, as a model id to price them at: the one these runs used most, else the current version. */
149
+ const ALIAS = {
150
+ sonnet: { family: /sonnet/i, fallback: "claude-sonnet-5-5" },
151
+ opus: { family: /opus/i, fallback: "claude-opus-5-5" },
152
+ haiku: { family: /haiku/i, fallback: "claude-haiku-5-5" },
153
+ fable: { family: /fable|mythos/i, fallback: "claude-fable-5-1" },
154
+ };
155
+ function aliasModel(alias, costs) {
156
+ const a = ALIAS[alias.toLowerCase()];
157
+ if (!a)
158
+ return undefined;
159
+ const seen = Object.entries(costs.byModel).filter(([m]) => a.family.test(m)).sort((x, y) => y[1].n - x[1].n)[0]?.[0];
160
+ return seen ?? a.fallback;
161
+ }
162
+ const short = (model) => {
163
+ const m = /claude-(opus|sonnet|haiku|fable|mythos)-(\d+)(?:-(\d{1,2}))?(?!\d)/i.exec(model ?? "");
164
+ return m ? `${m[1][0].toUpperCase()}${m[1].slice(1)} ${m[2]}${m[3] ? `.${m[3]}` : ""}` : model ?? "its model";
165
+ };
166
+ const familyOf = (model) => /(opus|sonnet|haiku|fable|mythos)/i.exec(model)?.[1]?.toLowerCase().replace("mythos", "fable");
167
+ /** The model a type is pinned to: 90%+ of its runs (3 or more) in one family, priced at that family's most-run model. */
168
+ export function pinnedModel(costs, type) {
169
+ const runs = Object.entries(costs.byTypeModel).filter(([k]) => k.startsWith(`${type}|`)).map(([k, v]) => ({ model: k.slice(type.length + 1), n: v.n }));
170
+ const total = runs.reduce((a, r) => a + r.n, 0);
171
+ if (total < MIN_RUNS)
172
+ return undefined;
173
+ const families = new Map();
174
+ for (const r of runs) {
175
+ const f = familyOf(r.model);
176
+ if (f)
177
+ families.set(f, (families.get(f) ?? 0) + r.n);
178
+ }
179
+ const [family, n] = [...families.entries()].sort((a, b) => b[1] - a[1])[0] ?? [];
180
+ if (!family || n / total < 0.9)
181
+ return undefined;
182
+ return runs.filter((r) => familyOf(r.model) === family).sort((a, b) => b.n - a.n)[0].model;
183
+ }
184
+ /** What a subagent of this type on this model costs, from the user's own runs. Undefined with too few. */
185
+ export function estimateSubagent(costs, type, modelAlias, parentModel) {
186
+ const byType = costs.byType[type];
187
+ // A subagent runs on the model it is given; else a type whose runs all
188
+ // used one family is pinned to it by its definition (claude-code-guide runs
189
+ // on Haiku whatever the parent is), priced at its usual model; else it
190
+ // inherits the parent's model (general-purpose and Explore ran on several
191
+ // families on the author's history: they follow the parent).
192
+ const model = (modelAlias ? aliasModel(modelAlias, costs) : undefined) ?? pinnedModel(costs, type) ?? parentModel ?? (byType && byType.n >= MIN_RUNS ? byType.model : undefined);
193
+ const scale = (from, to) => {
194
+ const a = pricingFor(from), b = pricingFor(to);
195
+ return a && b && a.inputPerM > 0 ? b.inputPerM / a.inputPerM : 1;
196
+ };
197
+ let base, factor = 1;
198
+ const exact = model ? costs.byTypeModel[`${type}|${model}`] : undefined;
199
+ if (exact && exact.n >= MIN_RUNS)
200
+ base = exact;
201
+ else if (byType && byType.n >= MIN_RUNS) {
202
+ base = byType;
203
+ factor = scale(byType.model, model ?? byType.model);
204
+ }
205
+ else if (model && costs.byModel[model]?.n >= MIN_RUNS)
206
+ base = costs.byModel[model];
207
+ else if (costs.all && costs.all.n >= MIN_RUNS) {
208
+ base = costs.all;
209
+ factor = scale(costs.all.model, model ?? costs.all.model);
210
+ }
211
+ if (!base)
212
+ return undefined;
213
+ const est = { type, model: model ?? base.model, median: base.median * factor, p90: base.p90 * factor, runs: base.n };
214
+ const sonnet = aliasModel("sonnet", costs);
215
+ // Sonnet is offered only where it is cheaper than what the subagent runs on.
216
+ if (est.model && /opus|fable|mythos/i.test(est.model) && (pricingFor(sonnet)?.inputPerM ?? Infinity) < (pricingFor(est.model)?.inputPerM ?? 0)) {
217
+ const measured = costs.byTypeModel[`${type}|${sonnet}`];
218
+ est.cheaper = measured && measured.n >= MIN_RUNS
219
+ ? { model: sonnet, median: measured.median, measured: true }
220
+ : { model: sonnet, median: est.median * scale(est.model, sonnet), measured: false };
221
+ if (!(est.cheaper.median < est.median))
222
+ delete est.cheaper;
223
+ }
224
+ return est;
225
+ }
226
+ const BURST_MS = 120_000;
227
+ /** The session's launch log, beside the hook's per-session state. */
228
+ export function spawnLogPath(sessionId) {
229
+ return join(statePath().replace(/\.json$/, "") + ".d", createHash("sha1").update(sessionId).digest("hex").slice(0, 16) + ".spawns.jsonl");
230
+ }
231
+ /** Append this launch, then read the log back (its last 64 KB: hundreds of launches). */
232
+ export function recordSpawn(path, line) {
233
+ try {
234
+ mkdirSync(dirname(path), { recursive: true });
235
+ appendFileSync(path, JSON.stringify(line) + "\n");
236
+ const size = statSync(path).size;
237
+ const text = readFileSync(path, "utf8");
238
+ return text.slice(Math.max(0, size - 64 * 1024)).split("\n").flatMap((l) => {
239
+ try {
240
+ const v = JSON.parse(l);
241
+ return v && typeof v.t === "number" && typeof v.type === "string" && typeof v.id === "string" ? [{ t: v.t, type: v.type, id: v.id, c: v.c === true }] : [];
242
+ }
243
+ catch {
244
+ return [];
245
+ }
246
+ });
247
+ }
248
+ catch {
249
+ return [line];
250
+ }
251
+ }
252
+ /** What a launch's input says: its type and the model alias it asks for. */
253
+ export function launchOf(input) {
254
+ if (!/^(Agent|Task)$/.test(String(input.tool_name ?? "")))
255
+ return undefined;
256
+ const ti = input.tool_input && typeof input.tool_input === "object" ? input.tool_input : {};
257
+ const type = typeof ti.subagent_type === "string" && ti.subagent_type.trim() ? ti.subagent_type.trim().slice(0, 60) : "general-purpose";
258
+ return { type, alias: typeof ti.model === "string" ? ti.model : undefined };
259
+ }
260
+ /**
261
+ * What to say before this launch, from the session's launch log (this one
262
+ * included, as `own`). The user sees the price on the first launch of a type
263
+ * in the session and when launches bunch up (3 within two minutes, then
264
+ * every 5th); the model gets one short note a session, on the first launch
265
+ * that was quoted a cheaper model.
266
+ */
267
+ export function fanoutMessage(est, alias, log, own) {
268
+ if (!est)
269
+ return {};
270
+ const at = log.findIndex((l) => l.id === own.id);
271
+ const upTo = at >= 0 ? log.slice(0, at + 1) : [...log, own];
272
+ const firstOfType = upTo.find((l) => l.type === own.type)?.id === own.id;
273
+ const burst = upTo.filter((l) => Math.abs(own.t - l.t) < BURST_MS).length;
274
+ const showBurst = burst >= 3 && (burst === 3 || burst % 5 === 0);
275
+ const out = {};
276
+ const cheaper = est.cheaper && !alias ? est.cheaper : undefined;
277
+ if (firstOfType || showBurst) {
278
+ const runs = `${est.runs} run${est.runs === 1 ? "" : "s"}`;
279
+ const sonnet = cheaper ? ` On Sonnet: ~${formatUsd(cheaper.median)}${cheaper.measured ? "" : " at its price"}.` : "";
280
+ out.systemMessage = showBurst
281
+ ? `context-doctor: ${burst} subagents in 2 minutes, ~${formatUsd(est.median * burst)} together at your median of ~${formatUsd(est.median)} for ${own.type} on ${short(est.model)} (${runs}).${sonnet}`
282
+ : `context-doctor: a ${own.type} subagent on ${short(est.model)} costs ~${formatUsd(est.median)} at your median (p90 ${formatUsd(est.p90)}, ${runs}, list price).${sonnet}`;
283
+ }
284
+ if (cheaper && upTo.find((l) => l.c)?.id === own.id) {
285
+ out.additionalContext = `context-doctor: on this machine a ${own.type} subagent costs ~${formatUsd(est.median)} at the median on ${short(est.model)}, ~${formatUsd(cheaper.median)} on Sonnet. For search, reading or summarising, pass model: "sonnet" to the Agent tool.`;
286
+ }
287
+ return out;
288
+ }
289
+ /** The whole PreToolUse answer: estimate, log, decide. Silent (an empty object) for anything else. */
290
+ export function fanoutHook(input, costs, sessionId, now = Date.now()) {
291
+ const launch = launchOf(input);
292
+ if (!launch || !costs)
293
+ return {};
294
+ const parentModel = input.transcript_path && existsSync(input.transcript_path) ? tailUsage(input.transcript_path)?.model : undefined;
295
+ const est = estimateSubagent(costs, launch.type, launch.alias, parentModel);
296
+ if (!est)
297
+ return {};
298
+ const own = { t: now, type: launch.type, id: randomUUID(), c: Boolean(est.cheaper && !launch.alias) };
299
+ return fanoutMessage(est, launch.alias, recordSpawn(spawnLogPath(sessionId), own), own);
300
+ }
301
+ /** For `doctor` and the docs: where the medians come from. */
302
+ export function describeCosts(c) {
303
+ if (!c || !c.all)
304
+ return "no subagent runs measured yet";
305
+ return `${c.n} subagents in ${c.days} days, median ${formatUsd(c.all.median)} (${basename(subagentCostsPath())})`;
306
+ }
307
+ /** The medians the subagent price quotes, for `context-doctor subagents`. */
308
+ export function renderCostMedians(c) {
309
+ const types = Object.entries(c.byType).filter(([, s]) => s.n >= MIN_RUNS).sort((a, b) => b[1].n - a[1].n).slice(0, 8);
310
+ if (!types.length)
311
+ return [];
312
+ return [
313
+ "",
314
+ `What a subagent costs here (median, p90; the price shown before one starts):`,
315
+ ...types.map(([t, s]) => ` ${t.slice(0, 26).padEnd(26)} ${formatUsd(s.median).padStart(8)} ${formatUsd(s.p90).padStart(8)} ${s.n} runs, mostly ${short(s.model)}`),
316
+ ];
317
+ }
package/dist/handoff.js CHANGED
@@ -150,6 +150,9 @@ const SECRET_KEY_NAME = "(?:password|passwd|passphrase|pwd|secret|secret[_-]?key
150
150
  // The key: an identifier whose LAST segment names a secret (DB_PASSWORD,
151
151
  // OPENAI_API_KEY, _authToken), so token_count or max_tokens are not keys.
152
152
  const ASSIGNMENT = new RegExp(`(?<![A-Za-z0-9])((?:[A-Za-z0-9]+[_.-])*${SECRET_KEY_NAME}["']?\\s*[:=]\\s*["']?)([^\\s"'\`,;()<>{}\\[\\]]{3,})(?=$|[\\s"'\`,;)\\]}])`, "gim");
153
+ // The same keys with a quoted value, spaces and all: a passphrase
154
+ // (`"password": "correct horse battery staple"`) is several words.
155
+ const QUOTED_ASSIGNMENT = new RegExp(`(?<![A-Za-z0-9])((?:[A-Za-z0-9]+[_.-])*${SECRET_KEY_NAME}["']?\\s*[:=]\\s*)(["'])([^"'\\n]{3,500})\\2`, "gim");
153
156
  const NOT_A_VALUE = /^(?:string|str|number|int|integer|bool|boolean|any|null|nil|none|undefined|true|false|required|optional|empty|redacted|hidden|secret|password|\*+|x{3,}|\.{3,})$/i;
154
157
  const PLACEHOLDER = /^(?:your[_-]|<|\$\{?|%|\{\{|changeme|placeholder|example|dummy)|(?:[_-]here)(?:[_-]?\d+)?$/i;
155
158
  function isRealValue(v) {
@@ -181,6 +184,13 @@ export function maskSecrets(text) {
181
184
  return r;
182
185
  });
183
186
  }
187
+ out = out.replace(QUOTED_ASSIGNMENT, (whole, key, quote, value) => {
188
+ if (!isRealValue(value.trim()))
189
+ return whole;
190
+ count++;
191
+ kinds.add("a password or secret assignment");
192
+ return `${key}${quote}[${MASK}]${quote}`;
193
+ });
184
194
  out = out.replace(ASSIGNMENT, (whole, key, value) => {
185
195
  if (!isRealValue(value))
186
196
  return whole;
package/dist/hook.js CHANGED
@@ -27,6 +27,7 @@ import { formatUsd, pricingFor } from "./pricing.js";
27
27
  import { checkBudget, loadConfig } from "./config.js";
28
28
  import { modelSwitchMessage } from "./modelswitch.js";
29
29
  import { compactFacts, compactInstructions } from "./precompact.js";
30
+ import { fanoutHook, subagentCosts } from "./fanout.js";
30
31
  /** Default nudge threshold; a project budget or env var can lower/raise it. */
31
32
  const DEFAULT_WARN_TOKENS = 80_000;
32
33
  /**
@@ -211,6 +212,20 @@ export async function runHook(app) {
211
212
  process.stdout.write(JSON.stringify({ systemMessage: message }) + "\n");
212
213
  return;
213
214
  }
215
+ // Before a subagent starts (PreToolUse on the Agent tool): its price at
216
+ // the user's own median, to the user, and once to the model. Never a
217
+ // permission decision, never exit 2: the subagent always starts.
218
+ if (input.hook_event_name === "PreToolUse") {
219
+ const r = fanoutHook(input, subagentCosts(), input.session_id ?? input.transcript_path ?? "unknown");
220
+ const out = {};
221
+ if (r.systemMessage)
222
+ out.systemMessage = r.systemMessage;
223
+ if (r.additionalContext)
224
+ out.hookSpecificOutput = { hookEventName: "PreToolUse", additionalContext: r.additionalContext };
225
+ if (Object.keys(out).length)
226
+ process.stdout.write(JSON.stringify(out) + "\n");
227
+ return;
228
+ }
214
229
  // A resumed session: Claude Code says whether its cache expired and what
215
230
  // re-caching costs. Kept for the first prompt, which decides the offer
216
231
  // (an offer before any message would come before the rebuild it prices).