context-doctor 0.31.1 → 0.33.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 (81) hide show
  1. package/README.md +96 -706
  2. package/dist/autoclear.d.ts +58 -7
  3. package/dist/autoclear.js +159 -31
  4. package/dist/autopilot.d.ts +43 -3
  5. package/dist/autopilot.js +169 -35
  6. package/dist/cache.d.ts +6 -2
  7. package/dist/cache.js +48 -23
  8. package/dist/cacheplan.d.ts +5 -3
  9. package/dist/cacheplan.js +46 -8
  10. package/dist/calibration.d.ts +7 -2
  11. package/dist/calibration.js +14 -3
  12. package/dist/ci.js +34 -6
  13. package/dist/cli.js +416 -271
  14. package/dist/clihelp.d.ts +24 -0
  15. package/dist/clihelp.js +116 -0
  16. package/dist/coldresume.d.ts +32 -7
  17. package/dist/coldresume.js +148 -34
  18. package/dist/compactquality.d.ts +1 -1
  19. package/dist/compactquality.js +37 -14
  20. package/dist/compactwindow.d.ts +29 -5
  21. package/dist/compactwindow.js +104 -47
  22. package/dist/config.d.ts +6 -0
  23. package/dist/config.js +4 -1
  24. package/dist/cursor.d.ts +9 -0
  25. package/dist/cursor.js +53 -22
  26. package/dist/dashboard.d.ts +10 -0
  27. package/dist/dashboard.js +27 -2
  28. package/dist/diff.js +33 -4
  29. package/dist/doctor.d.ts +3 -2
  30. package/dist/doctor.js +199 -34
  31. package/dist/embed.d.ts +9 -0
  32. package/dist/embed.js +40 -5
  33. package/dist/experiment.d.ts +1 -0
  34. package/dist/experiment.js +6 -3
  35. package/dist/hook.js +23 -4
  36. package/dist/impact.d.ts +32 -0
  37. package/dist/impact.js +45 -6
  38. package/dist/install.d.ts +59 -2
  39. package/dist/install.js +458 -57
  40. package/dist/invocation.d.ts +18 -0
  41. package/dist/invocation.js +49 -0
  42. package/dist/ledger.js +9 -2
  43. package/dist/mcp.d.ts +6 -3
  44. package/dist/mcp.js +93 -299
  45. package/dist/mcpclient.js +45 -0
  46. package/dist/mcpschema.d.ts +17 -2
  47. package/dist/mcpschema.js +100 -26
  48. package/dist/optimize.d.ts +2 -0
  49. package/dist/optimize.js +151 -64
  50. package/dist/overhead.d.ts +12 -1
  51. package/dist/overhead.js +88 -34
  52. package/dist/pack.d.ts +11 -0
  53. package/dist/pack.js +75 -12
  54. package/dist/parse.js +42 -18
  55. package/dist/preferences.d.ts +1 -1
  56. package/dist/preferences.js +5 -5
  57. package/dist/pricing.d.ts +57 -5
  58. package/dist/pricing.js +94 -8
  59. package/dist/proxy.d.ts +13 -2
  60. package/dist/proxy.js +258 -43
  61. package/dist/reads.d.ts +1 -1
  62. package/dist/reads.js +61 -24
  63. package/dist/report.d.ts +10 -0
  64. package/dist/report.js +12 -4
  65. package/dist/savings.d.ts +23 -8
  66. package/dist/savings.js +88 -37
  67. package/dist/session.d.ts +52 -0
  68. package/dist/session.js +186 -6
  69. package/dist/split.js +6 -1
  70. package/dist/statusline.d.ts +3 -1
  71. package/dist/statusline.js +29 -17
  72. package/dist/subagentpay.d.ts +6 -3
  73. package/dist/subagentpay.js +53 -18
  74. package/dist/subagents.d.ts +7 -3
  75. package/dist/subagents.js +28 -8
  76. package/dist/tasks.d.ts +22 -7
  77. package/dist/tasks.js +47 -20
  78. package/dist/wrap.d.ts +6 -0
  79. package/dist/wrap.js +142 -6
  80. package/package.json +5 -8
  81. package/skills/context-doctor/SKILL.md +3 -3
@@ -51,13 +51,21 @@ export interface AutoClearOptions {
51
51
  * warm clearing off, cold cache only (the never-worse setting).
52
52
  */
53
53
  paybackSafety?: number;
54
- /** Where cleared ids persist so a restart does not un-clear (and re-bill) them. */
54
+ /**
55
+ * Where cleared ids persist so a restart does not un-clear (and re-bill)
56
+ * them, with each conversation's last request time so a restart does not
57
+ * mistake a warm cache for a cold one.
58
+ */
55
59
  statePath?: string;
56
60
  /**
57
- * Treat a conversation this instance has never seen as warm-cached (so
58
- * nothing is cleared on it). The proxy sees every request and leaves this
59
- * off; an in-process wrapper in a fresh process cannot know whether another
60
- * process just sent the conversation, so it turns this on.
61
+ * Treat a conversation this instance has no record of as warm-cached (so
62
+ * nothing is cleared on it). Both the proxy and the in-process wrapper turn
63
+ * this on: a wrapper in a fresh process cannot know whether another process
64
+ * just sent the conversation, and a restarted proxy cannot know either
65
+ * unless the conversation's last request time was persisted (statePath).
66
+ * Calling a warm cache cold pays a full rewrite; calling a cold one warm
67
+ * only delays a free clearing to the next idle gap. Off here so a bare
68
+ * AutoClearer (the savings replay) keeps its first-request-is-cold model.
61
69
  */
62
70
  unseenIsWarm?: boolean;
63
71
  }
@@ -71,7 +79,26 @@ export interface AutoClearResult {
71
79
  reason: string;
72
80
  /** Index of the first message rewritten on this request (the cache breaks from here), or -1. */
73
81
  firstChanged: number;
82
+ /** Ids this request cleared for the first time. */
83
+ newIds: string[];
84
+ /** Every id whose clearing this request carries, earlier batches included. */
85
+ appliedIds: string[];
74
86
  }
87
+ /**
88
+ * Whether a thinking block comes at or after message `index`. On current
89
+ * Claude models (Fable 5.1, Opus 5.5, Sonnet 5.5, Haiku 5.5) a thinking
90
+ * block's signature binds the conversation before it: an edit to an earlier
91
+ * message invalidates every later thinking block, and accounts created on or
92
+ * after 2026-08-31 get a 400 for it ("... bound to a different
93
+ * conversation"), on every retry of the same body.
94
+ */
95
+ export declare function thinkingAfter(messages: unknown[], index: number): boolean;
96
+ /**
97
+ * A request that sets thinking.block_binding has opted into that check (any
98
+ * value, "drop_block" included, which silently drops the reasoning an edit
99
+ * invalidates), so it is treated like an account known to enforce it.
100
+ */
101
+ export declare function optsIntoThinkingCheck(body: Record<string, unknown>): boolean;
75
102
  interface Found {
76
103
  /** Index of the message / input item that holds the result (cache breaks from here). */
77
104
  unit: number;
@@ -93,7 +120,12 @@ interface View {
93
120
  toolName: Map<string, string>;
94
121
  results: Array<Omit<Found, "tokens">>;
95
122
  firstUser: unknown;
96
- firstToolId: string;
123
+ /**
124
+ * Index of the last unit the model wrote (-1 for none). Results after it
125
+ * arrive with this request: the model has not read them yet, so they are
126
+ * never eligible, however many there are (six parallel reads).
127
+ */
128
+ seenUpTo: number;
97
129
  ttlMs: number;
98
130
  }
99
131
  export declare function clearedNote(tokens: number): string;
@@ -114,12 +146,19 @@ export declare class AutoClearer {
114
146
  private convs;
115
147
  private opts;
116
148
  private dirty;
149
+ /** Conversation times changed since the last save (written at most every CONV_SAVE_MS, or on flush). */
150
+ private convsDirty;
151
+ private lastSave;
152
+ /** Accounts (salted credential hashes from the caller) whose API rejected a history autopilot edited. */
153
+ private rejecting;
117
154
  constructor(options?: AutoClearOptions);
118
155
  /**
119
156
  * Rewrite `body` in place: an Anthropic Messages, OpenAI Chat Completions or
120
157
  * OpenAI Responses request. Never throws; anything unrecognised is left alone.
158
+ * `account` names the credential the request carries (the proxy passes a
159
+ * salted hash), for accounts whose API rejects edited history.
121
160
  */
122
- apply(body: Record<string, unknown>, now?: number, modelHint?: string): AutoClearResult;
161
+ apply(body: Record<string, unknown>, now?: number, modelHint?: string, account?: string): AutoClearResult;
123
162
  /**
124
163
  * Warm cache: clearing rewrites everything after the first cleared result
125
164
  * at the write rate (1.25x instead of 0.1x: 1.15x extra, once), and saves
@@ -129,6 +168,18 @@ export declare class AutoClearer {
129
168
  * cover the rewrite `paybackSafety` times over.
130
169
  */
131
170
  private shouldClearWarm;
171
+ /** Write pending state now (the proxy calls this on a timer and before it exits). */
172
+ flush(): void;
173
+ /** Whether this account's API has rejected a history autopilot edited (see thinkingAfter). */
174
+ rejectsEdits(account?: string): boolean;
175
+ /** Remember, across restarts, that this account's API rejects edited history. */
176
+ noteEditsRejected(account: string): void;
177
+ /**
178
+ * Stop applying these clearings: the API refused the request that carried
179
+ * them, and any thinking it produces from now on is bound to the history
180
+ * without them.
181
+ */
182
+ forget(ids: string[]): void;
132
183
  private load;
133
184
  private save;
134
185
  }
package/dist/autoclear.js CHANGED
@@ -55,7 +55,44 @@ export const CLEARABLE_TOOLS = new Set([
55
55
  ]);
56
56
  /** Tokens billed for one image inside a tool result (a full-size screenshot is ~1.6k on Claude). */
57
57
  const IMAGE_TOKENS = 1600;
58
+ /**
59
+ * Whether a thinking block comes at or after message `index`. On current
60
+ * Claude models (Fable 5.1, Opus 5.5, Sonnet 5.5, Haiku 5.5) a thinking
61
+ * block's signature binds the conversation before it: an edit to an earlier
62
+ * message invalidates every later thinking block, and accounts created on or
63
+ * after 2026-08-31 get a 400 for it ("... bound to a different
64
+ * conversation"), on every retry of the same body.
65
+ */
66
+ export function thinkingAfter(messages, index) {
67
+ for (let i = Math.max(0, index); i < messages.length; i++) {
68
+ const content = messages[i]?.content;
69
+ if (Array.isArray(content) && content.some((b) => b?.type === "thinking" || b?.type === "redacted_thinking"))
70
+ return true;
71
+ }
72
+ return false;
73
+ }
74
+ /**
75
+ * A request that sets thinking.block_binding has opted into that check (any
76
+ * value, "drop_block" included, which silently drops the reasoning an edit
77
+ * invalidates), so it is treated like an account known to enforce it.
78
+ */
79
+ export function optsIntoThinkingCheck(body) {
80
+ const thinking = body.thinking;
81
+ return Boolean(thinking && typeof thinking === "object" && thinking.block_binding !== undefined);
82
+ }
58
83
  const HOUR = 3_600_000;
84
+ /**
85
+ * Conversations' last request times are written at most this often (and on
86
+ * flush). A record read back after a crash can be this much older than the
87
+ * truth, so it is read as this much newer: when unsure, warm.
88
+ */
89
+ const CONV_SAVE_MS = 60_000;
90
+ function lastIndex(items, pred) {
91
+ for (let i = items.length - 1; i >= 0; i--)
92
+ if (pred(items[i]))
93
+ return i;
94
+ return -1;
95
+ }
59
96
  export function clearedNote(tokens) {
60
97
  // Not "run it again": a cleared Bash result may come from a command with
61
98
  // side effects (a push, a delete), and repeating that would be wrong.
@@ -92,7 +129,10 @@ export function requestTtlMs(body) {
92
129
  const openai = Array.isArray(body.input) || (Array.isArray(body.messages) && isOpenAIChat(body.messages));
93
130
  if (openai)
94
131
  return body.prompt_cache_retention === "24h" ? 24 * HOUR : HOUR;
95
- const json = JSON.stringify(body.system ?? "") + JSON.stringify(body.tools ?? "") + JSON.stringify(body.messages?.slice(-3) ?? "");
132
+ // Automatic caching puts cache_control at the top level of the request; a
133
+ // 1-hour cache marked there was read as the 5-minute default, so autopilot
134
+ // could clear into a cache that was still warm.
135
+ const json = JSON.stringify(body.cache_control ?? "") + JSON.stringify(body.system ?? "") + JSON.stringify(body.tools ?? "") + JSON.stringify(body.messages?.slice(-3) ?? "");
96
136
  return /"ttl"\s*:\s*"1h"/.test(json) ? HOUR : 300_000;
97
137
  }
98
138
  function isOpenAIChat(messages) {
@@ -101,11 +141,13 @@ function isOpenAIChat(messages) {
101
141
  export function viewOf(body) {
102
142
  const toolName = new Map();
103
143
  const results = [];
104
- let firstToolId = "";
105
144
  // Gemini generateContent: contents[].parts[] with functionCall / functionResponse.
106
- // Ids are optional there, so a missing one is derived from its position
107
- // (stable: history only grows) and scoped to the conversation, because the
108
- // cleared set is keyed by id and positions repeat across conversations.
145
+ // Ids are optional there, so a missing one is derived. Position and the
146
+ // first user message alone repeat whenever the same prompt runs twice, and
147
+ // the cleared set is keyed by id: run 2 then had run 1's clearings applied
148
+ // to its own results, newest included. The response's own content is part
149
+ // of the derived id, so another run's result is another id unless it is
150
+ // byte-identical at the same place (and apply() still requires it eligible).
109
151
  if (Array.isArray(body.contents)) {
110
152
  const units = body.contents;
111
153
  const firstUser = units.find((u) => u?.role === "user")?.parts;
@@ -118,12 +160,12 @@ export function viewOf(body) {
118
160
  const call = p?.functionCall;
119
161
  const resp = p?.functionResponse;
120
162
  if (call && typeof call === "object") {
121
- const id = typeof call.id === "string" && call.id ? call.id : `gemini:${scope}:${i}:${j}`;
122
- toolName.set(id, String(call.name ?? ""));
123
- firstToolId ||= id;
163
+ if (typeof call.id === "string" && call.id)
164
+ toolName.set(call.id, String(call.name ?? ""));
124
165
  }
125
166
  else if (resp && typeof resp === "object") {
126
- const id = typeof resp.id === "string" && resp.id ? resp.id : `gemini:${scope}:${i}:${j}`;
167
+ const content = createHash("sha1").update(JSON.stringify(resp.response ?? "")).digest("hex").slice(0, 12);
168
+ const id = typeof resp.id === "string" && resp.id ? resp.id : `gemini:${scope}:${i}:${j}:${content}`;
127
169
  // The response names its tool, so it classifies on its own.
128
170
  if (!toolName.has(id))
129
171
  toolName.set(id, String(resp.name ?? ""));
@@ -131,7 +173,8 @@ export function viewOf(body) {
131
173
  }
132
174
  });
133
175
  });
134
- return { format: "gemini", units, toolName, results, firstUser, firstToolId, ttlMs: requestTtlMs(body) };
176
+ const seenUpTo = lastIndex(units, (u) => u?.role === "model");
177
+ return { format: "gemini", units, toolName, results, firstUser, seenUpTo, ttlMs: requestTtlMs(body) };
135
178
  }
136
179
  if (Array.isArray(body.input)) {
137
180
  const units = body.input;
@@ -139,19 +182,23 @@ export function viewOf(body) {
139
182
  const t = it?.type;
140
183
  if ((t === "function_call" || t === "custom_tool_call" || t === "local_shell_call") && typeof it.call_id === "string") {
141
184
  toolName.set(it.call_id, t === "local_shell_call" ? "shell" : String(it.name ?? ""));
142
- firstToolId ||= it.call_id;
143
185
  }
144
186
  else if ((t === "function_call_output" || t === "custom_tool_call_output" || t === "local_shell_call_output") && typeof it.call_id === "string") {
145
187
  results.push({ unit: i, id: it.call_id, content: it.output, set: (note) => { units[i] = { ...it, output: note }; } });
146
188
  }
147
189
  });
148
190
  const firstUser = units.find((u) => u?.role === "user")?.content;
149
- return { format: "openai-responses", units, toolName, results, firstUser, firstToolId, ttlMs: requestTtlMs(body) };
191
+ // Model-written items: its tool calls, reasoning and assistant messages.
192
+ // With previous_response_id the input holds none of them, so every result
193
+ // in it is new to the model.
194
+ const seenUpTo = lastIndex(units, (u) => u?.role === "assistant" || ["function_call", "custom_tool_call", "local_shell_call", "reasoning"].includes(String(u?.type)));
195
+ return { format: "openai-responses", units, toolName, results, firstUser, seenUpTo, ttlMs: requestTtlMs(body) };
150
196
  }
151
197
  const messages = body.messages;
152
198
  if (!Array.isArray(messages) || messages.length === 0)
153
199
  return undefined;
154
200
  const firstUser = messages.find((m) => m?.role === "user")?.content;
201
+ const seenUpTo = lastIndex(messages, (m) => m?.role === "assistant");
155
202
  if (isOpenAIChat(messages)) {
156
203
  messages.forEach((m, i) => {
157
204
  if (m?.role === "assistant" && Array.isArray(m.tool_calls)) {
@@ -159,14 +206,13 @@ export function viewOf(body) {
159
206
  if (typeof c?.id !== "string")
160
207
  continue;
161
208
  toolName.set(c.id, String(c.function?.name ?? c.name ?? ""));
162
- firstToolId ||= c.id;
163
209
  }
164
210
  }
165
211
  else if (m?.role === "tool" && typeof m.tool_call_id === "string") {
166
212
  results.push({ unit: i, id: m.tool_call_id, content: m.content, set: (note) => { messages[i] = { ...m, content: note }; } });
167
213
  }
168
214
  });
169
- return { format: "openai-chat", units: messages, toolName, results, firstUser, firstToolId, ttlMs: requestTtlMs(body) };
215
+ return { format: "openai-chat", units: messages, toolName, results, firstUser, seenUpTo, ttlMs: requestTtlMs(body) };
170
216
  }
171
217
  messages.forEach((m, i) => {
172
218
  if (!Array.isArray(m?.content))
@@ -175,25 +221,36 @@ export function viewOf(body) {
175
221
  blocks.forEach((b, j) => {
176
222
  if (m.role === "assistant" && b?.type === "tool_use" && typeof b.id === "string") {
177
223
  toolName.set(b.id, String(b.name ?? ""));
178
- firstToolId ||= b.id;
179
224
  }
180
225
  else if (m.role === "user" && b?.type === "tool_result" && typeof b.tool_use_id === "string") {
181
226
  results.push({ unit: i, id: b.tool_use_id, content: b.content, set: (note) => { blocks[j] = { ...b, content: note }; } });
182
227
  }
183
228
  });
184
229
  });
185
- return { format: "anthropic", units: messages, toolName, results, firstUser, firstToolId, ttlMs: requestTtlMs(body) };
230
+ return { format: "anthropic", units: messages, toolName, results, firstUser, seenUpTo, ttlMs: requestTtlMs(body) };
186
231
  }
187
232
  /**
188
- * A conversation's identity: its first user message plus its first tool call
189
- * id. The message alone can repeat across sessions (the same project context
190
- * opens every session in a folder); tool call ids are unique per session.
233
+ * A conversation's identity, the same from its first request on: the first
234
+ * user message, plus the client's own session tag when it sends one
235
+ * (Anthropic metadata.user_id, which Claude Code fills per session; OpenAI
236
+ * prompt_cache_key). The first user message is read without cache_control:
237
+ * Claude Code marks the last message, which on request 1 is the first one,
238
+ * and moves the marker on request 2. Through 0.31.1 the key also held the
239
+ * first tool call id, so request 2 (the first tool round) was a new,
240
+ * never-seen conversation, called cold eight seconds after request 1.
241
+ * Two sessions that open with the same message and send no tag share a key;
242
+ * that only ever makes one look warm when the other is, the safe direction.
191
243
  * The model is left out on purpose: switching models mid-session keeps the
192
244
  * conversation (and the cleared set) but not the cache, which the TTL check
193
245
  * cannot see, so a model switch is treated as warm, the safe direction.
194
246
  */
195
- function conversationKey(view) {
196
- return createHash("sha1").update(JSON.stringify(view.firstUser ?? "").slice(0, 4000)).update(view.firstToolId).digest("hex");
247
+ function conversationKey(view, body) {
248
+ const first = JSON.stringify(view.firstUser ?? "", (k, v) => (k === "cache_control" ? undefined : v)) ?? "";
249
+ const h = createHash("sha1").update(first.slice(0, 4000));
250
+ const tag = body.metadata?.user_id ?? body.prompt_cache_key;
251
+ if (typeof tag === "string")
252
+ h.update("\0").update(tag);
253
+ return h.digest("hex");
197
254
  }
198
255
  export class AutoClearer {
199
256
  cleared = new Map();
@@ -202,6 +259,11 @@ export class AutoClearer {
202
259
  convs = new Map();
203
260
  opts;
204
261
  dirty = false;
262
+ /** Conversation times changed since the last save (written at most every CONV_SAVE_MS, or on flush). */
263
+ convsDirty = false;
264
+ lastSave = 0;
265
+ /** Accounts (salted credential hashes from the caller) whose API rejected a history autopilot edited. */
266
+ rejecting = new Set();
205
267
  constructor(options = {}) {
206
268
  this.opts = {
207
269
  keepRecent: options.keepRecent ?? 3,
@@ -215,21 +277,26 @@ export class AutoClearer {
215
277
  /**
216
278
  * Rewrite `body` in place: an Anthropic Messages, OpenAI Chat Completions or
217
279
  * OpenAI Responses request. Never throws; anything unrecognised is left alone.
280
+ * `account` names the credential the request carries (the proxy passes a
281
+ * salted hash), for accounts whose API rejects edited history.
218
282
  */
219
- apply(body, now = Date.now(), modelHint) {
220
- const none = (reason, cold = false) => ({ changed: false, newlyCleared: 0, tokensRemoved: 0, cold, reason, firstChanged: -1 });
283
+ apply(body, now = Date.now(), modelHint, account) {
284
+ const none = (reason, cold = false) => ({ changed: false, newlyCleared: 0, tokensRemoved: 0, cold, reason, firstChanged: -1, newIds: [], appliedIds: [] });
221
285
  try {
222
286
  const view = viewOf(body);
223
287
  if (!view)
224
288
  return none("no messages");
225
289
  // Gemini puts the model in the URL, not the body; the proxy passes it.
226
290
  const model = typeof body.model === "string" ? body.model : modelHint;
227
- const key = conversationKey(view);
291
+ const key = conversationKey(view, body);
228
292
  const conv = this.convs.get(key);
229
293
  const cold = conv ? now - conv.last > view.ttlMs : !this.opts.unseenIsWarm;
294
+ // Delete first so the map stays in last-used order and the cap evicts idle conversations.
295
+ this.convs.delete(key);
230
296
  this.convs.set(key, { last: now, requests: (conv?.requests ?? 0) + 1 });
231
297
  if (this.convs.size > 2000)
232
298
  this.convs.delete(this.convs.keys().next().value);
299
+ this.convsDirty = true;
233
300
  const results = view.results.map((r) => {
234
301
  let tokens = this.sizes.get(r.id);
235
302
  if (tokens === undefined) {
@@ -240,8 +307,11 @@ export class AutoClearer {
240
307
  }
241
308
  return { ...r, tokens };
242
309
  });
310
+ // Results that arrive with this request (after the model's last turn)
311
+ // are not eligible however many there are: the model has not read them.
243
312
  const eligible = results.slice(0, Math.max(0, results.length - this.opts.keepRecent))
244
- .filter((r) => CLEARABLE_TOOLS.has(view.toolName.get(r.id) ?? ""));
313
+ .filter((r) => r.unit <= view.seenUpTo && CLEARABLE_TOOLS.has(view.toolName.get(r.id) ?? ""));
314
+ const eligibleIds = new Set(eligible.map((r) => r.id));
245
315
  const pending = eligible.filter((r) => !this.cleared.has(r.id) && r.tokens > 200);
246
316
  const pendingTokens = pending.reduce((n, r) => n + r.tokens, 0);
247
317
  let reason = "nothing to clear";
@@ -262,17 +332,29 @@ export class AutoClearer {
262
332
  else if (pendingTokens > 0) {
263
333
  reason = `waiting for a ${Math.round(this.opts.minClearTokens / 1000)}k batch`;
264
334
  }
335
+ // An account that rejects edited history gets no NEW clearing a
336
+ // thinking block comes after: that block is bound to the history as it
337
+ // was. Clearings already sent keep being applied, because thinking
338
+ // generated since then is bound to the cleared history; dropping them
339
+ // would break the conversation the other way.
340
+ if (taken.length && (this.rejectsEdits(account) || optsIntoThinkingCheck(body)) && thinkingAfter(view.units, Math.min(...taken.map((r) => r.unit)))) {
341
+ taken = [];
342
+ reason = "thinking blocks follow the stale output and this account rejects edited history: left as is";
343
+ }
265
344
  for (const r of taken)
266
345
  this.cleared.set(r.id, r.tokens);
267
346
  if (taken.length)
268
347
  this.dirty = true;
269
348
  // Apply every clearing ever decided for this conversation, so the
270
- // prefix is identical to what was sent last time.
349
+ // prefix is identical to what was sent last time. A remembered id must
350
+ // still be eligible here: a derived id (Gemini without ids) can recur in
351
+ // another conversation, where it must not cost that one its newest result.
271
352
  let removed = 0;
272
353
  let changed = false;
273
354
  let firstChanged = -1;
355
+ const appliedIds = [];
274
356
  for (const r of results) {
275
- if (!this.cleared.has(r.id))
357
+ if (!this.cleared.has(r.id) || !eligibleIds.has(r.id))
276
358
  continue;
277
359
  const note = clearedNote(this.cleared.get(r.id));
278
360
  if (r.content === note)
@@ -280,11 +362,12 @@ export class AutoClearer {
280
362
  removed += Math.max(0, r.tokens - estimateTokens(note, model));
281
363
  r.set(note);
282
364
  changed = true;
365
+ appliedIds.push(r.id);
283
366
  if (firstChanged === -1 || r.unit < firstChanged)
284
367
  firstChanged = r.unit;
285
368
  }
286
369
  this.save();
287
- return { changed, newlyCleared: taken.length, tokensRemoved: removed, cold, reason, firstChanged };
370
+ return { changed, newlyCleared: taken.length, tokensRemoved: removed, cold, reason, firstChanged, newIds: taken.map((r) => r.id), appliedIds };
288
371
  }
289
372
  catch {
290
373
  return none("error: request forwarded unchanged");
@@ -307,6 +390,36 @@ export class AutoClearer {
307
390
  const saving = 0.1 * pendingTokens * requestsSoFar;
308
391
  return saving >= this.opts.paybackSafety * rewriteCost;
309
392
  }
393
+ /** Write pending state now (the proxy calls this on a timer and before it exits). */
394
+ flush() {
395
+ this.save(true);
396
+ }
397
+ /** Whether this account's API has rejected a history autopilot edited (see thinkingAfter). */
398
+ rejectsEdits(account) {
399
+ return account !== undefined && this.rejecting.has(account);
400
+ }
401
+ /** Remember, across restarts, that this account's API rejects edited history. */
402
+ noteEditsRejected(account) {
403
+ if (this.rejecting.has(account))
404
+ return;
405
+ this.rejecting.add(account);
406
+ this.dirty = true;
407
+ this.save();
408
+ }
409
+ /**
410
+ * Stop applying these clearings: the API refused the request that carried
411
+ * them, and any thinking it produces from now on is bound to the history
412
+ * without them.
413
+ */
414
+ forget(ids) {
415
+ let any = false;
416
+ for (const id of ids)
417
+ any = this.cleared.delete(id) || any;
418
+ if (any) {
419
+ this.dirty = true;
420
+ this.save();
421
+ }
422
+ }
310
423
  load() {
311
424
  if (!this.opts.statePath || !existsSync(this.opts.statePath))
312
425
  return;
@@ -314,20 +427,35 @@ export class AutoClearer {
314
427
  const data = JSON.parse(readFileSync(this.opts.statePath, "utf8"));
315
428
  for (const [id, tokens] of data.cleared ?? [])
316
429
  this.cleared.set(id, tokens);
430
+ for (const account of data.rejectsEdits ?? [])
431
+ if (typeof account === "string")
432
+ this.rejecting.add(account);
433
+ // Each conversation's last request time, so a restart does not make
434
+ // every open conversation "unseen" (cold) and rewrite a warm cache.
435
+ for (const [key, last, requests] of data.convs ?? []) {
436
+ if (typeof key === "string" && typeof last === "number")
437
+ this.convs.set(key, { last: last + CONV_SAVE_MS, requests: Number(requests) || 1 });
438
+ }
317
439
  }
318
440
  catch {
319
441
  /* a corrupt state file only means results may be re-cleared once */
320
442
  }
321
443
  }
322
- save() {
323
- if (!this.dirty || !this.opts.statePath)
444
+ save(force = false) {
445
+ if (!this.opts.statePath)
446
+ return;
447
+ const due = this.convsDirty && (force || Date.now() - this.lastSave >= CONV_SAVE_MS);
448
+ if (!this.dirty && !due)
324
449
  return;
325
450
  this.dirty = false;
451
+ this.convsDirty = false;
452
+ this.lastSave = Date.now();
326
453
  try {
327
454
  // Newest 50k ids: far more than any live session holds.
328
455
  const entries = [...this.cleared.entries()].slice(-50_000);
456
+ const convs = [...this.convs.entries()].map(([k, c]) => [k, c.last, c.requests]);
329
457
  mkdirSync(dirname(this.opts.statePath), { recursive: true });
330
- writeFileSync(this.opts.statePath, JSON.stringify({ cleared: entries }));
458
+ writeFileSync(this.opts.statePath, JSON.stringify({ cleared: entries, convs, rejectsEdits: [...this.rejecting] }));
331
459
  }
332
460
  catch {
333
461
  /* persistence is best effort */
@@ -30,13 +30,36 @@ export declare function autopilotPaths(home?: string): AutopilotPaths;
30
30
  export declare function proxyUrl(port: number): string;
31
31
  /** The command the service runs. Absolute paths: services start with an empty PATH. */
32
32
  export declare function serviceCommand(node: string, cli: string, port: number, paths: AutopilotPaths): string[];
33
+ /**
34
+ * The service restarts the proxy when it fails, not when it exits 0. The
35
+ * proxy exits 0 when another context-doctor proxy already serves its port;
36
+ * with KeepAlive true (Restart=always) launchd restarted it into the same
37
+ * EADDRINUSE every 5 s, 45 times in one real log.
38
+ */
33
39
  export declare function launchdPlist(args: string[], log: string): string;
34
40
  export declare function systemdUnit(args: string[], log: string): string;
35
41
  export declare function windowsTaskCommand(args: string[]): string;
42
+ /**
43
+ * Runs a service-manager command, true on success. Injectable so tests can
44
+ * use a throwaway HOME without ever reaching the real launchd, systemd or
45
+ * Task Scheduler: those name the service globally (a label, a unit name, a
46
+ * task name), not per HOME.
47
+ */
48
+ export type ServiceExec = (cmd: string, args: string[]) => boolean;
49
+ /**
50
+ * Claude Code turns MCP tool search off when ANTHROPIC_BASE_URL is not an
51
+ * Anthropic host ("Set ENABLE_TOOL_SEARCH=true (or auto / auto:N) if your
52
+ * proxy forwards tool_reference blocks", 2.1.295), so routing it through
53
+ * autopilot loaded every MCP tool definition into every request. The proxy
54
+ * forwards those blocks and the anthropic-beta header untouched, so tool
55
+ * search stays on ("auto", Claude Code's own default) unless the user set it.
56
+ * Returns true when we set it.
57
+ */
58
+ export declare function keepToolSearch(env: Record<string, string>): boolean;
36
59
  /** Version of the package a CLI path belongs to (dist/cli.js -> ../package.json). */
37
60
  export declare function installedVersion(cli: string): string | undefined;
38
61
  /** Restart the installed background service onto the current build (launchd, systemd). */
39
- export declare function restartService(): boolean;
62
+ export declare function restartService(home?: string, exec?: ServiceExec): boolean;
40
63
  export declare function startDetached(args: string[], log: string): void;
41
64
  export interface Health {
42
65
  ok: boolean;
@@ -44,6 +67,13 @@ export interface Health {
44
67
  version?: string;
45
68
  }
46
69
  export declare function health(port: number, timeoutMs?: number): Promise<Health>;
70
+ /**
71
+ * The ANTHROPIC_BASE_URL `off` should restore, decided at `on`: the one an
72
+ * earlier `on` recorded, else what settings.json holds now, but never our own
73
+ * proxy's. With the config damaged, settings.json already holds the proxy URL
74
+ * from the last `on`, and recording that made `off` put the proxy URL back.
75
+ */
76
+ export declare function baseUrlToRestore(paths: AutopilotPaths, port: number, current: string | null): string | null;
47
77
  /** Which Claude Code surfaces ran recent sessions: entrypoint -> count. */
48
78
  export declare function recentSurfaces(days?: number, home?: string): Map<string, number>;
49
79
  /** Lines explaining which recent sessions autopilot can reach, or nothing when all can. */
@@ -53,11 +83,21 @@ export declare function autopilotOn(port?: number, paths?: AutopilotPaths): Prom
53
83
  ok: boolean;
54
84
  lines: string[];
55
85
  }>;
56
- export declare function autopilotOff(paths?: AutopilotPaths): Promise<string[]>;
86
+ export declare function autopilotOff(paths?: AutopilotPaths, exec?: ServiceExec): Promise<string[]>;
57
87
  export declare function autopilotPause(paused: boolean, paths?: AutopilotPaths): string;
88
+ /**
89
+ * Pause or resume, saying what actually happened. Without autopilot on there
90
+ * is no proxy to pause: this used to claim "✓ Paused" over nothing, and on a
91
+ * machine with no ~/.claude it threw ENOENT writing the pause file. `ok` is
92
+ * false when nothing was done, for the exit code.
93
+ */
94
+ export declare function autopilotPauseResult(paused: boolean, paths?: AutopilotPaths): {
95
+ ok: boolean;
96
+ message: string;
97
+ };
58
98
  export declare function autopilotStatus(paths?: AutopilotPaths): Promise<string[]>;
59
99
  /**
60
100
  * Called by the every-prompt hook: if autopilot is on and the proxy is down,
61
101
  * start it before the prompt's request goes out. Returns quickly either way.
62
102
  */
63
- export declare function ensureProxyUp(paths?: AutopilotPaths): Promise<void>;
103
+ export declare function ensureProxyUp(paths?: AutopilotPaths, exec?: ServiceExec): Promise<void>;