maxpool 1.24.68 → 1.24.70

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "maxpool",
3
- "version": "1.24.68",
3
+ "version": "1.24.70",
4
4
  "description": "Multi-account Claude Code proxy with adaptive, rate-aware load balancing across Claude accounts",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
package/src/config.js CHANGED
@@ -70,6 +70,13 @@ export function createDefaultConfig() {
70
70
  // is blind to idle / out-of-band-used accounts and the scorer will pile traffic
71
71
  // onto exactly the account it cannot see. 0 = off.
72
72
  quotaProbeSeconds: 60,
73
+ // Provider-thinking scrub (owner 2026-11-05): drop `thinking`/`redacted_thinking`
74
+ // blocks (and any unknown block type) from PROVIDER responses before they reach the
75
+ // client, so a mixed GLM+Claude session never stores foreign thinking — the stored
76
+ // blocks are what Anthropic signature-400s on and the repair strips, breaking the
77
+ // cache prefix. Claude-account responses are NEVER scrubbed. Default OFF until the
78
+ // E2E package is owner-approved.
79
+ providerThinkingScrub: false,
73
80
  routing: {
74
81
  mode: 'automatic',
75
82
  preferredAccount: null,
package/src/index.js CHANGED
@@ -18,6 +18,7 @@ import { loadOrCreateConfig, loadConfig, saveConfig, atomicConfigUpdate, getConf
18
18
  import { setEventLogPath, installConsoleMirror, setConsoleStdoutSuppressed, appendEventLog } from './event-log.js';
19
19
  import { sendLoginToPool, planCliLogin, resolveUsablePools } from './cloud-login.js';
20
20
  import { SleepGuard } from './sleep-guard.js';
21
+ import { controllingTerminalAlive } from './terminal-alive.js';
21
22
  import { AccountManager } from './account-manager.js';
22
23
  import { createProxyServer, REQUEST_IDLE_MAX_MS } from './server.js';
23
24
 
@@ -1638,7 +1639,18 @@ async function serverWorkerCommand() {
1638
1639
  // drain + exit cleanly so we never reload into a headless orphan that outlives
1639
1640
  // the terminal and squats the port. Headless/service mode keeps SIGHUP as the
1640
1641
  // conventional reload signal (baton under the supervisor, else exit-75).
1641
- process.on('SIGHUP', () => { if (isInteractiveTerminal()) shutdownGracefully('SIGHUP', { terminalClose: true }); else requestReload(); });
1642
+ // A SIGHUP while the terminal is still open came from another program (`kill
1643
+ // -HUP`), not a closed window — ignore it rather than kill every session using
1644
+ // the pool. Re-check shortly after, in case the signal raced the terminal revoke.
1645
+ const hangupShutdown = () => shutdownGracefully('SIGHUP', { terminalClose: true });
1646
+ process.on('SIGHUP', () => {
1647
+ if (!isInteractiveTerminal()) return requestReload();
1648
+ if (!controllingTerminalAlive()) return hangupShutdown();
1649
+ console.log('[Maxpool] Ignored SIGHUP: this terminal is still open, so another program sent it (not a closed window). Maxpool keeps running — press r to restart it.');
1650
+ for (const ms of [500, 2000]) {
1651
+ setTimeout(() => { if (!draining && !controllingTerminalAlive()) hangupShutdown(); }, ms).unref?.();
1652
+ }
1653
+ });
1642
1654
  }
1643
1655
 
1644
1656
  function logPlainServerStart({ host, port, accounts, threshold, config }) {
package/src/pool-link.js CHANGED
@@ -178,6 +178,17 @@ function sanitizeRemoteStatus(json) {
178
178
  * so a link that hasn't polled yet still benches what it benched last run.
179
179
  */
180
180
  const BOOT_IDS_TTL_MS = 14 * 24 * 3600 * 1000; // stale beyond this → trust a fresh boot instead
181
+ export const FAILS_BEFORE_DOWN = 2;
182
+
183
+ /** Plain-English cause of a link failure, for the one-line cloud banner. */
184
+ export function describeLinkError(err) {
185
+ const e = String(err || '');
186
+ if (e === 'key rejected') return "the cloud pool rejected this laptop's key";
187
+ if (/^HTTP 5\d\d$/.test(e)) return `the cloud pool answered with an error (${e})`;
188
+ if (/^HTTP /.test(e)) return `the cloud pool answered ${e}`;
189
+ // timeout, ECONNREFUSED/RESET, "fetch failed", DNS… — from here they look alike.
190
+ return `no connection — check your internet or the tunnel (${e || 'network error'})`;
191
+ }
181
192
 
182
193
  export class PoolLink {
183
194
  constructor(def, deps = {}) {
@@ -194,6 +205,8 @@ export class PoolLink {
194
205
  this.status = null; // raw remote status JSON when ok
195
206
  this.lastError = null;
196
207
  this.lastOkAt = null;
208
+ this.failStreak = 0; // consecutive failed checks
209
+ this.downSince = null; // when lastError was first set (the outage start)
197
210
  this.identities = new Map();
198
211
  this.summary = null;
199
212
  }
@@ -226,13 +239,23 @@ export class PoolLink {
226
239
  this.status = sanitizeRemoteStatus(r.json);
227
240
  this.lastOkAt = r.at;
228
241
  this.lastError = null;
242
+ this.failStreak = 0;
243
+ this.downSince = null;
229
244
  this.identities = remoteIdentities(r.json);
230
245
  this.summary = summarizeRemote(r.json);
231
246
  } else {
232
- // Keep the LAST good status for display, but mark the link degraded so
233
- // routing benches it and the UI names the error.
234
- this.lastError = r.error;
235
- this.summary = null;
247
+ // One missed check on a flaky network is not an outage: a single timeout
248
+ // used to flip every cloud row to ✕ while requests were still getting
249
+ // through. Mark the link down only after FAILS_BEFORE_DOWN checks in a row
250
+ // (a rejected key is never transient — down at once). Keep the LAST good
251
+ // status for display; down → routing benches it and the UI names the cause.
252
+ this.failStreak = (this.failStreak || 0) + 1;
253
+ this.lastPollError = r.error;
254
+ if (this.failStreak >= FAILS_BEFORE_DOWN || r.error === 'key rejected' || this.lastOkAt == null) {
255
+ if (!this.lastError) this.downSince = r.at;
256
+ this.lastError = r.error;
257
+ this.summary = null;
258
+ }
236
259
  }
237
260
  return r;
238
261
  } finally {
@@ -0,0 +1,330 @@
1
+ /**
2
+ * Provider-thinking scrub — keep foreign reasoning OUT of the shared transcript.
3
+ *
4
+ * WHY (owner 2026-11-05, task research/maxpool-round2): a mixed GLM+Claude session
5
+ * stores GLM-authored `thinking` blocks; Claude rejects their signatures (400), and the
6
+ * repair that recovers the session strips ALL thinking — rewriting the cached prefix from
7
+ * the first thinking block onward. Scrubbing provider thinking at the RESPONSE boundary
8
+ * means the transcript never contains it: no 400s, no repair, and the Claude-side cache
9
+ * prefix is never mutated by contamination. Claude accounts are NEVER scrubbed (their
10
+ * thinking is validly signed, cache-relevant, and must round-trip).
11
+ *
12
+ * Two lanes (red team 2026-11-05, finding 2): the streaming lane (streamResponse) and
13
+ * the buffered/non-streaming lane (next to normalizeModelEcho). Both must scrub or the
14
+ * fallback lane re-poisons histories CC itself hits exactly when providers misbehave.
15
+ *
16
+ * Red-team finding 1: NEVER skip SSE block indexes. A second CC reducer family (SDK
17
+ * paths, query-tool subagents, RC hosts) pushes on content_block_start and indexes by
18
+ * ARRAY POSITION — a suppressed block shifts every later one and silently corrupts text.
19
+ * So the streaming scrub RENUMBERS: an oldIndex→newIndex map rewrites every subsequent
20
+ * start/delta/stop for the same message. Internal consumers (usage ledger, capacity,
21
+ * streamLog) still see the PRE-scrub stream (finding 6: scrub applies at res.write only).
22
+ *
23
+ * Red-team finding 3: a thinking-only provider turn must not scrub to `content: []` —
24
+ * Anthropic rejects empty assistant content on the next request and no repair covers it.
25
+ * Synthesize a "(reasoning omitted)" text block instead.
26
+ *
27
+ * Red-team finding 4: unknown/renamed provider block types would pass through, get
28
+ * stored, and 400 later in a class no repair matches. The provider pass allows only
29
+ * known Anthropic types; anything else is dropped.
30
+ * `redacted_thinking` is also scrubbed — a provider can never produce a valid one.
31
+ *
32
+ * Red-team findings 1+6 (2026-11-06, round 3): the KNOWN provider tool blocks —
33
+ * mcp_tool_use / mcp_tool_result / server_tool_use / web_search_tool_result — must not be
34
+ * dropped either (that deleted GLM's web-tool calls and fetched results from the client
35
+ * transcript). They are CONVERTED to text in both lanes via foreignToolBlockText(), the
36
+ * same convention the REQUEST-side repair (convertForeignServerTools in server.js) uses —
37
+ * one exported helper, no drifting copies. Truly unknown types stay dropped.
38
+ *
39
+ * Provenance-ready for the deferred replay-memory upgrade (B): nothing here parses block
40
+ * content. If B is ever built, its memory keys off (session, provider, turn) and stores
41
+ * these blocks as opaque bytes — a z.ai format change cannot corrupt it.
42
+ */
43
+
44
+ /** Anthropic content-block types a PROVIDER response may carry through to the client. */
45
+ const PROVIDER_ALLOWED_BLOCK_TYPES = new Set([
46
+ 'text', 'tool_use', 'thinking', 'redacted_thinking', // thinking* are listed so the
47
+ // scrub can MATCH them explicitly; both are removed below — never forwarded.
48
+ ]);
49
+
50
+ /**
51
+ * Provider-authored TOOL blocks the scrub CONVERTS to text (red-team 2026-11-06 round-3
52
+ * finding 1) instead of dropping. GLM emits these on response turns (web search, MCP
53
+ * tools like webReader); the client transcript must keep what was called and found, in
54
+ * the same text form the request-side repair produces. Everything else unknown = dropped.
55
+ */
56
+ const PROVIDER_CONVERTIBLE_TOOL_TYPES = new Set([
57
+ 'server_tool_use', 'web_search_tool_result', 'mcp_tool_use', 'mcp_tool_result',
58
+ ]);
59
+
60
+ const SCRUB_PLACEHOLDER = '(reasoning omitted)';
61
+
62
+ // ── ONE converter shared by the request-side repair (server.js convertForeignServerTools)
63
+ // ── and both scrub lanes. Pure: block in → string out, no globals, no state.
64
+
65
+ /**
66
+ * Text rendering of one provider tool block, request-side convention:
67
+ * server_tool_use → "[searched the web for: <query>]" / "[used <name>]"
68
+ * mcp_tool_use → "[called <name> (<server>) on <input, 300 code points>]"
69
+ * web_search_tool_result → "[search results: …]"
70
+ * mcp_tool_result → "[<name> result: …]" / "[mcp tool returned no usable results]"
71
+ * Truncation is by CODE POINTS: a raw .slice can split a surrogate pair (an emoji at
72
+ * char 299), and a lone surrogate makes the body invalid JSON-UTF8 Anthropic 400s with
73
+ * no repair path — killing the session the conversion is saving (red-team M1).
74
+ */
75
+ export function foreignToolBlockText(b) {
76
+ if (b?.type === 'server_tool_use') {
77
+ const q = b.input?.query;
78
+ return q ? `[searched the web for: ${q}]` : `[used ${b.name || 'a tool'}]`;
79
+ }
80
+ if (b?.type === 'mcp_tool_use') {
81
+ const inp = JSON.stringify(b.input ?? {});
82
+ return `[called ${b.name || 'a tool'}${b.server_name ? ` (${b.server_name})` : ''} on ${codePointClamp(inp, 300)}]`;
83
+ }
84
+ // Any result block (web_search_tool_result / mcp_tool_result) referring to a foreign call.
85
+ const rows = Array.isArray(b?.content) ? b.content.slice() : [];
86
+ // Fall back through the shapes a PROVIDER may use — the point of converting rather
87
+ // than dropping is to keep what the search found; assuming Anthropic's {title,url}
88
+ // would silently discard a GLM row that carries text instead.
89
+ if (typeof b?.content === 'string' && b.content) rows.push(b.content); // a plain-string result (e.g. an error row) — keep it (red-team M6)
90
+ const found = rows
91
+ .map(r => [r?.title, r?.url].filter(Boolean).join(' — ')
92
+ || (typeof r === 'string' ? r : (r?.text ?? r?.content ?? r?.snippet ?? '')))
93
+ .map(t => (typeof t === 'string' ? codePointClamp(t, 300) : ''))
94
+ .filter(Boolean).slice(0, 10);
95
+ if (b?.type === 'mcp_tool_result') {
96
+ // An MCP result carries {type:'text'} rows, not {title,url} — label it as the tool's
97
+ // answer rather than "[search results]" so the transcript stays honest.
98
+ return found.length ? `[${b.name || 'mcp tool'} result: ${found.join(' | ')}]` : '[mcp tool returned no usable results]';
99
+ }
100
+ return found.length ? `[search results: ${found.join(' | ')}]` : '[search returned no usable results]';
101
+ }
102
+
103
+ function codePointClamp(s, n) { return Array.from(s).slice(0, n).join(''); }
104
+
105
+ /** One summary line for the logs — per RESPONSE, not per block (red-team 2026-11-06 finding 6). */
106
+ export function describeScrub(stats) {
107
+ const parts = [];
108
+ if (stats.thinking) parts.push(`removed ${stats.thinking} provider thinking block(s)`);
109
+ if (stats.converted) parts.push(`converted ${stats.converted} provider tool block(s)`);
110
+ if (stats.unknown.length) parts.push(`dropped ${stats.unknown.length} unknown block(s): ${[...new Set(stats.unknown)].map(t => `"${t}"`).join(', ')}`);
111
+ return parts.join(', ');
112
+ }
113
+
114
+ /** Streaming-lane block classifier: null = forward verbatim, 'drop' | block = convert. */
115
+ function scrubCell(bt) {
116
+ if (bt === 'thinking' || bt === 'redacted_thinking') return 'drop';
117
+ if (PROVIDER_CONVERTIBLE_TOOL_TYPES.has(String(bt))) return 'convert';
118
+ if (PROVIDER_ALLOWED_BLOCK_TYPES.has(String(bt))) return 'forward';
119
+ return 'drop';
120
+ }
121
+
122
+ /**
123
+ * Scrub a COMPLETE parsed response body (buffered lane). Mutates nothing; returns a new
124
+ * object when something was scrubbed, else null (caller forwards the original).
125
+ * statsOut (optional object) receives { thinking, converted, unknown:[] }.
126
+ */
127
+ export function scrubProviderResponseBody(json, statsOut) {
128
+ if (!json || typeof json !== 'object' || !Array.isArray(json.content)) return null;
129
+ const stats = { thinking: 0, converted: 0, unknown: [] };
130
+ let changed = false;
131
+ const out = [];
132
+ for (const block of json.content) {
133
+ const cell = scrubCell(block?.type);
134
+ if (cell === 'drop') {
135
+ if (block?.type === 'thinking' || block?.type === 'redacted_thinking') stats.thinking++;
136
+ else stats.unknown.push(String(block?.type));
137
+ changed = true;
138
+ continue;
139
+ }
140
+ if (cell === 'convert') {
141
+ stats.converted++;
142
+ out.push({ type: 'text', text: foreignToolBlockText(block) }); // round-3 finding 1
143
+ changed = true;
144
+ continue;
145
+ }
146
+ out.push(block);
147
+ }
148
+ if (!changed) return null;
149
+ if (statsOut) Object.assign(statsOut, stats);
150
+ if (out.length === 0) out.push({ type: 'text', text: SCRUB_PLACEHOLDER }); // finding 3
151
+ return { ...json, content: out };
152
+ }
153
+
154
+ /**
155
+ * Streaming-lane scrub state. Feed it each raw SSE chunk BEFORE res.write; it returns
156
+ * the bytes to write (possibly rewritten, possibly split — renumbering can change an
157
+ * event's length). Parse-level, not regex-level: SSE events are small and framed, and a
158
+ * regex cannot renumber `index` fields safely.
159
+ */
160
+ export class ProviderThinkingScrubber {
161
+ constructor({ onScrub } = {}) {
162
+ this.onScrub = onScrub || null; // fires once per scrubbed block (instrumentation)
163
+ this.rewrite = null; // Map oldIndex -> newIndex (-1 = suppressed)
164
+ this.keptCount = 0;
165
+ this.sawAnyThinking = false;
166
+ this.buffer = ''; // incomplete SSE tail
167
+ this.scrubbedCount = 0;
168
+ this.convertedCount = 0; // tool blocks converted to text (NOT counted in scrubbedCount)
169
+ this._unknown = [];
170
+ this._pending = null; // { oldIndex, cell:'convert', block, json } while a convertible block streams
171
+ this._stopped = false; // placeholder already injected (message_delta or message_stop)
172
+ }
173
+
174
+ /** Per-response stats for describeScrub() — one summary line per response. */
175
+ stats() { return { thinking: this.scrubbedCount, converted: this.convertedCount, unknown: this._unknown }; }
176
+
177
+ /** Process one decoded chunk; returns the string to write (may be ''). */
178
+ push(text) {
179
+ this.buffer += text;
180
+ const events = this.buffer.split('\n\n');
181
+ this.buffer = events.pop() ?? '';
182
+ let out = '';
183
+ for (const ev of events) out += this.event(ev);
184
+ return out;
185
+ }
186
+
187
+ /** Flush at stream end: process any trailing event without a blank line. */
188
+ flush() {
189
+ const rest = this.buffer;
190
+ this.buffer = '';
191
+ return rest ? this.event(rest) : '';
192
+ }
193
+
194
+ event(ev) {
195
+ const lines = ev.split('\n');
196
+ let data = null;
197
+ let dataLine = -1;
198
+ for (let i = 0; i < lines.length; i++) {
199
+ if (lines[i].startsWith('data:')) { data = lines[i].slice(5).trimStart(); dataLine = i; break; }
200
+ }
201
+ if (data == null) return ev + '\n\n'; // non-data frame (event:, ping) — verbatim
202
+ let j;
203
+ try { j = JSON.parse(data); } catch { return ev + '\n\n'; } // malformed JSON — verbatim
204
+ const t = j?.type;
205
+ if (t === 'content_block_start') {
206
+ const bt = j?.content_block?.type;
207
+ const cell = scrubCell(bt);
208
+ if (cell === 'drop') {
209
+ this.scrubbedCount++;
210
+ this.sawAnyThinking = this.sawAnyThinking || bt === 'thinking' || bt === 'redacted_thinking';
211
+ if (bt !== 'thinking' && bt !== 'redacted_thinking') this._unknown.push(String(bt));
212
+ this.onScrub?.(bt);
213
+ if (!this.rewrite) this.rewrite = new Map();
214
+ this.rewrite.set(j.index, -1); // suppressed: start/delta/stop all dropped
215
+ return '';
216
+ }
217
+ if (cell === 'convert') {
218
+ // Round-3 finding 1: buffer the whole block, then emit it as ONE text block at
219
+ // the renumbered index — the client transcript keeps the call and its result.
220
+ const newIdx = this.nextIndex(j.index);
221
+ this.convertedCount++;
222
+ this._pending = { oldIndex: j.index, block: { ...j.content_block }, json: '' };
223
+ const startEv = { type: 'content_block_start', index: newIdx, content_block: { type: 'text', text: '' } };
224
+ return `event: content_block_start\ndata: ${JSON.stringify(startEv)}\n\n`;
225
+ }
226
+ // Keep: renumber past every suppressed block before it.
227
+ if (!this.rewrite) this.rewrite = new Map();
228
+ this.keptCount = (this.keptCount || 0) + 1;
229
+ const newIdx = this.nextIndex(j.index);
230
+ if (newIdx !== j.index) { j = { ...j, index: newIdx }; return this.render(lines, dataLine, j) + '\n\n'; }
231
+ return ev + '\n\n';
232
+ }
233
+ if (t === 'content_block_delta') {
234
+ if (this._pending && j.index === this._pending.oldIndex) {
235
+ const d = j.delta?.type;
236
+ if (d === 'input_json_delta') this._pending.json += String(j.delta.partial_json ?? '');
237
+ else if (d === 'text_delta') this._pending.block.text = (this._pending.block.text || '') + (j.delta.text ?? '');
238
+ else if (d === 'thinking_delta' || d === 'signature_delta') { /* content only — ignored */ }
239
+ else {
240
+ // A delta type we do not model inside a convertible block: rather than guess
241
+ // (a wrong guess DELETES provider content), fail open and convert from what we
242
+ // have — an accurate bracket summary without the unknown payload.
243
+ this._pending.unknownDelta = true;
244
+ }
245
+ return '';
246
+ }
247
+ if (this.rewrite) {
248
+ const mapped = this.rewrite.get(j.index);
249
+ if (mapped === -1) return ''; // belongs to a suppressed block
250
+ if (mapped !== undefined && mapped !== j.index) {
251
+ j = { ...j, index: mapped };
252
+ return this.render(lines, dataLine, j) + '\n\n';
253
+ }
254
+ }
255
+ return ev + '\n\n';
256
+ }
257
+ if (t === 'content_block_stop') {
258
+ if (this._pending && j.index === this._pending.oldIndex) {
259
+ const p = this._pending;
260
+ this._pending = null;
261
+ const blockIdx = this.rewrite.get(p.oldIndex);
262
+ const block = { ...p.block };
263
+ if (p.json !== '') {
264
+ try { block.input = JSON.parse(p.json); }
265
+ catch { /* provider sent malformed partial JSON — convert from the metadata we hold */ }
266
+ }
267
+ const text = foreignToolBlockText(block);
268
+ const deltaEv = { type: 'content_block_delta', index: blockIdx, delta: { type: 'text_delta', text } };
269
+ return `event: content_block_delta\ndata: ${JSON.stringify(deltaEv)}\n\nevent: content_block_stop\ndata: ${JSON.stringify({ type: 'content_block_stop', index: blockIdx })}\n\n`;
270
+ }
271
+ if (this.rewrite) {
272
+ const mapped = this.rewrite.get(j.index);
273
+ if (mapped === -1) return '';
274
+ if (mapped !== undefined && mapped !== j.index) {
275
+ j = { ...j, index: mapped };
276
+ return this.render(lines, dataLine, j) + '\n\n';
277
+ }
278
+ }
279
+ return ev + '\n\n';
280
+ }
281
+ if (t === 'message_delta' && this.scrubbedCount > 0 && !this.keptCount && !this.convertedCount) {
282
+ // Finding 3 (streaming): every block was suppressed — emit ONE complete placeholder
283
+ // text block before the message closes, so the stored turn is never content:[].
284
+ // A converted tool block counts as content (round-3 finding 1) — no placeholder then.
285
+ this.keptCount = 1;
286
+ this._stopped = true;
287
+ const startEv = { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } };
288
+ const deltaEv = { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: SCRUB_PLACEHOLDER } };
289
+ const stopEv = { type: 'content_block_stop', index: 0 };
290
+ return `event: content_block_start\ndata: ${JSON.stringify(startEv)}\n\n`
291
+ + `event: content_block_delta\ndata: ${JSON.stringify(deltaEv)}\n\n`
292
+ + `event: content_block_stop\ndata: ${JSON.stringify(stopEv)}\n\n`
293
+ + ev + '\n\n';
294
+ }
295
+ if (t === 'message_stop' && !this._stopped && this.scrubbedCount > 0 && !this.keptCount && !this.convertedCount) {
296
+ // Finding 4: a thinking-only stream can close with message_stop and NO message_delta
297
+ // (z.ai compat shape) — inject the placeholder block events BEFORE message_stop so
298
+ // the stored turn is never content:[] on that path either.
299
+ this.keptCount = 1;
300
+ this._stopped = true;
301
+ const startEv = { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } };
302
+ const deltaEv = { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: SCRUB_PLACEHOLDER } };
303
+ const stopEv = { type: 'content_block_stop', index: 0 };
304
+ return `event: content_block_start\ndata: ${JSON.stringify(startEv)}\n\nevent: content_block_delta\ndata: ${JSON.stringify(deltaEv)}\n\nevent: content_block_stop\ndata: ${JSON.stringify(stopEv)}\n\n` + ev + '\n\n';
305
+ }
306
+ // message_start / message_stop / ping / usage: verbatim
307
+ return ev + '\n\n';
308
+ }
309
+
310
+ nextIndex(oldIdx) {
311
+ // Compute the renumbered index for a KEPT or CONVERTED block: count how many
312
+ // suppressed blocks (map value -1) sit before it, subtract. Deterministic; no array reliance.
313
+ if (!this.rewrite) this.rewrite = new Map();
314
+ let shift = 0;
315
+ for (const [o, n] of this.rewrite) if (o < oldIdx && n === -1) shift++;
316
+ const mapped = oldIdx - shift;
317
+ this.rewrite.set(oldIdx, mapped);
318
+ return mapped;
319
+ }
320
+
321
+ render(lines, dataLine, j) {
322
+ lines[dataLine] = 'data: ' + JSON.stringify(j);
323
+ return lines.join('\n');
324
+ }
325
+ }
326
+
327
+ /** Is the scrub active for this request? (config flag + provider account) */
328
+ export function scrubEnabledFor(account, config) {
329
+ return Boolean(config?.providerThinkingScrub) && account?.type === 'provider';
330
+ }
package/src/server.js CHANGED
@@ -3,6 +3,7 @@ import { appendEventLog } from './event-log.js';
3
3
  import { atomicConfigUpdate } from './config.js';
4
4
  import { HOP_HEADER, nextHopCount, safeText } from './pool-link.js';
5
5
  import { ThreadOwners, readThreadIntent, threadRefusalBody, isThreadlessAccount } from './thread-gate.js';
6
+ import { ProviderThinkingScrubber, scrubProviderResponseBody, scrubEnabledFor, foreignToolBlockText, describeScrub } from './provider-thinking-scrub.js';
6
7
  import { writeFile, mkdir } from 'node:fs/promises';
7
8
  import { readFileSync } from 'node:fs';
8
9
  import { join } from 'node:path';
@@ -495,6 +496,9 @@ export function createProxyServer(accountManager, config, hooks = {}) {
495
496
  }
496
497
  requestInfo.sessionKey = headerValue(req.headers, 'x-maxpool-session');
497
498
  requestInfo.caller = req._caller || null;
499
+ // Read per request (not captured at boot) so a config flip + seamless reload
500
+ // takes effect on the next request with no restart.
501
+ requestInfo.providerThinkingScrub = Boolean(config.providerThinkingScrub);
498
502
  // The CLIENT tells us how long it will wait — the only source that is actually
499
503
  // true. A `cc` session exports CLAUDE_STREAM_IDLE_TIMEOUT_MS=3h and forwards it
500
504
  // here; a bare `claude` sends nothing and keeps the conservative 240s default,
@@ -675,9 +679,14 @@ async function forwardRequest(
675
679
  || accountManager.isSessionThinkingContaminated?.(requestInfo.sessionKey))) {
676
680
  const pre = stripForeignThinkingBlocks(body);
677
681
  if (pre.body) {
678
- if (pre.converted) console.log(`[Maxpool] Up-front repair: stripped ${pre.removed} provider thinking block(s), converted ${pre.converted} provider tool block(s) before routing [sess ${requestInfo.sessionKey || '?'}]`);
679
682
  body = pre.body;
680
683
  requestInfo = { ...requestInfo, thinkingStripped: true };
684
+ // Never hide a repair (Anthropic gateway guidance): this pre-strip rewrites the
685
+ // request body on EVERY turn of a latched session and was silent — the only
686
+ // visible trace was the one-time latch line, so per-turn rewrites (each a cache
687
+ // prefix change) were uncountable. One line per rewrite, same prefix as the
688
+ // reactive repair so a single grep counts both.
689
+ console.log(`[Maxpool] Recovering session on Claude: pre-strip removed ${pre.removed} provider thinking block(s), converted ${pre.converted} provider search block(s) [sess ${String(requestInfo.sessionKey || '?').slice(0, 8)}]`);
681
690
  if (pre.converted) {
682
691
  // The body now replays cleanly on Claude, so drop the predictive verdict —
683
692
  // otherwise routing still exiles it and _noteRequestPolicy latches it sticky.
@@ -1868,13 +1877,19 @@ async function forwardRequest(
1868
1877
 
1869
1878
  if (isStreaming) {
1870
1879
  const streamLog = logDir ? [] : null;
1880
+ // PROVIDER-THINKING SCRUB (owner 2026-11-05): applied inside streamResponse at the
1881
+ // res.write boundary only — usage accounting, capacity and streamLog below still
1882
+ // see the ORIGINAL upstream stream (red-team finding 6).
1883
+ const scrubber = scrubEnabledFor(account, { providerThinkingScrub: requestInfo.providerThinkingScrub })
1884
+ ? new ProviderThinkingScrubber({ onScrub: () => requestInfo._scrubbed = (requestInfo._scrubbed || 0) + 1 })
1885
+ : null;
1871
1886
  // CAPACITY LEDGER: accrue in a FINALLY — a stream that dies mid-flight throws
1872
1887
  // from streamResponse, and the tokens genuinely delivered before the failure
1873
1888
  // are real capacity; skipping them under-counts exactly the longest
1874
1889
  // generations (red-team F5). One accrual per request, per-stream running max
1875
1890
  // (M3 — cumulative interim deltas must not be summed).
1876
1891
  try {
1877
- await streamResponse(upstreamRes.body, res, upstreamRes.status, responseHeaders, account.index, accountManager, streamLog, requestInfo);
1892
+ await streamResponse(upstreamRes.body, res, upstreamRes.status, responseHeaders, account.index, accountManager, streamLog, requestInfo, undefined, scrubber);
1878
1893
  } finally {
1879
1894
  accountManager.accrueCapacity?.(account.index, {
1880
1895
  input: requestInfo._capacityInput || 0,
@@ -1889,6 +1904,12 @@ async function forwardRequest(
1889
1904
  logSections.push(`=== RESPONSE BODY (streamed) ===\n${streamLog.join('')}`);
1890
1905
  writeRequestLog(logDir, reqId, logSections);
1891
1906
  }
1907
+ // SCRUB VISIBILITY (E2E verification V1): the counter existed but was never
1908
+ // surfaced — client-side "no thinking" is indistinguishable from "z.ai emitted
1909
+ // none". One line whenever the scrub actually removed blocks.
1910
+ if (scrubber && (requestInfo._scrubbed || scrubber.convertedCount)) {
1911
+ console.log(`[Maxpool] scrub: ${describeScrub(scrubber.stats())} from "${account.name}" response [sess ${String(requestInfo.sessionKey || '?').slice(0, 8)}]`);
1912
+ }
1892
1913
  } else { // Bound the non-streaming body read so a mid-body upstream stall can't hang
1893
1914
  // the request forever and leak the lease (same class as the streaming idle
1894
1915
  // guard). On timeout → UPSTREAM_BODY → the caller frees the lease.
@@ -1944,7 +1965,21 @@ async function forwardRequest(
1944
1965
  // body reaches Claude Code. Computed BEFORE writeHead so a length change lands
1945
1966
  // in the SAME header block — setting content-length after writeHead is a no-op
1946
1967
  // and would ship a body/length mismatch (the client then hangs or truncates).
1947
- const outBuf = normalizeModelEcho(buf, requestInfo.model);
1968
+ // PROVIDER-THINKING SCRUB runs in the SAME lane (red team finding 2: CC falls
1969
+ // back to non-streaming exactly when providers misbehave; an SSE-only scrub
1970
+ // would re-poison histories on the degraded path). Same header rule applies.
1971
+ let outBuf = normalizeModelEcho(buf, requestInfo.model);
1972
+ if (scrubEnabledFor(account, { providerThinkingScrub: requestInfo.providerThinkingScrub })) {
1973
+ const scrubStats = {};
1974
+ const scrubbed = scrubProviderResponseBody(safeJsonParse(outBuf), scrubStats);
1975
+ if (scrubbed) {
1976
+ outBuf = Buffer.from(JSON.stringify(scrubbed));
1977
+ requestInfo._scrubbed = (requestInfo._scrubbed || 0) + scrubStats.thinking + scrubStats.unknown.length;
1978
+ // SCRUB VISIBILITY (E2E V1): ONE summary line per response, matching the
1979
+ // streaming lane's line.
1980
+ console.log(`[Maxpool] scrub: ${describeScrub(scrubStats)} from "${account.name}" response (buffered)`);
1981
+ }
1982
+ }
1948
1983
  const outHeaders = outBuf === buf
1949
1984
  ? responseHeaders
1950
1985
  : { ...responseHeaders, 'content-length': String(outBuf.length) };
@@ -2824,41 +2859,13 @@ function convertForeignServerTools(content, foreignIds) {
2824
2859
  let converted = 0;
2825
2860
  const out = [];
2826
2861
  for (const b of content) {
2827
- if (b?.type === 'server_tool_use' && foreignIds.has(b.id)) {
2828
- const q = b.input?.query;
2829
- out.push({ type: 'text', text: q ? `[searched the web for: ${q}]` : `[used ${b.name || 'a tool'}]` });
2830
- converted++;
2831
- continue;
2832
- }
2833
- if (b?.type === 'mcp_tool_use' && foreignIds.has(b.id)) {
2834
- const inp = JSON.stringify(b.input ?? {});
2835
- // Truncate by CODE POINTS: a raw .slice can split a surrogate pair (an emoji at
2836
- // char 299), and a lone surrogate makes the body invalid JSON-UTF8 Anthropic 400s
2837
- // with no repair path — killing the session the conversion is saving (red-team M1).
2838
- out.push({ type: 'text', text: `[called ${b.name || 'a tool'}${b.server_name ? ` (${b.server_name})` : ''} on ${Array.from(inp).slice(0, 300).join('')}]` });
2839
- converted++;
2840
- continue;
2841
- }
2862
+ // Text conventions live in provider-thinking-scrub.js (foreignToolBlockText) so the
2863
+ // request-side repair and the response-side scrub can never drift apart.
2864
+ const isCall = (b?.type === 'server_tool_use' || b?.type === 'mcp_tool_use') && foreignIds.has(b.id);
2842
2865
  // Any result block referring to a foreign call — web_search_tool_result, mcp_tool_result and friends.
2843
- if (b?.tool_use_id && foreignIds.has(b.tool_use_id)) {
2844
- const rows = Array.isArray(b.content) ? b.content : [];
2845
- // Fall back through the shapes a PROVIDER may use — the point of converting rather
2846
- // than dropping is to keep what the search found; assuming Anthropic's {title,url}
2847
- // would silently discard a GLM row that carries text instead.
2848
- if (typeof b.content === 'string' && b.content) rows.push(b.content); // a plain-string result (e.g. an error row) — keep it (red-team M6)
2849
- const found = rows
2850
- .map(r => [r?.title, r?.url].filter(Boolean).join(' — ')
2851
- || (typeof r === 'string' ? r : (r?.text ?? r?.content ?? r?.snippet ?? '')))
2852
- .map(t => (typeof t === 'string' ? Array.from(t).slice(0, 300).join('') : ''))
2853
- .filter(Boolean).slice(0, 10);
2854
- if (b?.type === 'mcp_tool_result') {
2855
- // An MCP result carries {type:'text'} rows, not {title,url} — label it as the
2856
- // tool's answer rather than "[search results]" so the transcript stays honest.
2857
- out.push({ type: 'text', text: found.length ? `[${b.name || 'mcp tool'} result: ${found.join(' | ')}]` : '[mcp tool returned no usable results]' });
2858
- converted++;
2859
- continue;
2860
- }
2861
- out.push({ type: 'text', text: found.length ? `[search results: ${found.join(' | ')}]` : '[search returned no usable results]' });
2866
+ const isResult = !isCall && b?.tool_use_id && foreignIds.has(b.tool_use_id);
2867
+ if (isCall || isResult) {
2868
+ out.push({ type: 'text', text: foreignToolBlockText(b) });
2862
2869
  converted++;
2863
2870
  continue;
2864
2871
  }
@@ -3785,7 +3792,7 @@ function totalLen(chunks) {
3785
3792
  return n;
3786
3793
  }
3787
3794
 
3788
- async function streamResponse(webStream, res, status, responseHeaders, accountIndex, accountManager, streamLog, requestInfo = {}, idleMs = STREAM_IDLE_MS) {
3795
+ async function streamResponse(webStream, res, status, responseHeaders, accountIndex, accountManager, streamLog, requestInfo = {}, idleMs = STREAM_IDLE_MS, scrubber = null) {
3789
3796
  const reader = webStream.getReader();
3790
3797
  const decoder = new TextDecoder();
3791
3798
  let sseBuffer = '';
@@ -3931,10 +3938,15 @@ async function streamResponse(webStream, res, status, responseHeaders, accountIn
3931
3938
  }
3932
3939
  }
3933
3940
 
3934
- // Forward chunk immediately
3935
- const ok = res.write(out);
3941
+ // Forward chunk immediately. Decode ONCE (B1, build review 2026-11-06): a second
3942
+ // decode({stream:true}) on this shared TextDecoder flushes a pending partial UTF-8
3943
+ // sequence as U+FFFD — the usage/streamLog lane garbled in BOTH flag states. The
3944
+ // single decoded text feeds the scrubber (client lane) and the accounting lane.
3945
+ const chunkText = decoder.decode(out, { stream: true });
3946
+ const writeText = scrubber ? scrubber.push(chunkText) : null;
3947
+ const ok = scrubber ? (writeText ? res.write(writeText) : true) : res.write(out);
3936
3948
 
3937
- const text = decoder.decode(out, { stream: true });
3949
+ const text = chunkText;
3938
3950
 
3939
3951
  // Capture for logging
3940
3952
  if (streamLog) streamLog.push(text);
@@ -4052,7 +4064,17 @@ async function streamResponse(webStream, res, status, responseHeaders, accountIn
4052
4064
  // means the upstream died mid-event (an event without its '\n\n' terminator).
4053
4065
  // Complete-event streams without a terminal message_stop (z.ai compat shape,
4054
4066
  // test fixtures) end with an EMPTY residual and pass through unchanged.
4055
- if ((committed || res.headersSent) && sseBuffer.trim() && !res.destroyed && !res.writableEnded) {
4067
+ const truncatedMidEvent = Boolean(sseBuffer.trim());
4068
+ // Scrubber tail flush (an SSE event without its trailing '\n\n' is still buffered
4069
+ // inside the scrubber). Runs BEFORE the sentinel so the error frame is always the
4070
+ // last thing the client sees; skipped when the sentinel fires — the scrubber tail is
4071
+ // then the same half-event the sentinel reports, and emitting it would hand the
4072
+ // client a corrupt frame ahead of the error.
4073
+ if (scrubber && !truncatedMidEvent && !res.destroyed && !res.writableEnded) {
4074
+ const tail = scrubber.flush();
4075
+ if (tail) { try { res.write(tail); } catch { /* client gone */ } }
4076
+ }
4077
+ if ((committed || res.headersSent) && truncatedMidEvent && !res.destroyed && !res.writableEnded) {
4056
4078
  try {
4057
4079
  res.write(`event: error\ndata: ${JSON.stringify({
4058
4080
  type: 'error',
@@ -4203,3 +4225,8 @@ function computeRetryAfter(accountManager, requestInfo = {}) {
4203
4225
 
4204
4226
  // Test seam: prepareRuntimeProviders with a plain headers object.
4205
4227
  export const __test = { prepareRuntimeProviders };
4228
+
4229
+ /** Parse-or-null helper for the buffered scrub lane (never throws on a non-JSON body). */
4230
+ function safeJsonParse(buf) {
4231
+ try { return JSON.parse(buf.toString('utf8')); } catch { return null; }
4232
+ }
@@ -0,0 +1,24 @@
1
+ // Is the terminal running maxpool still open? A SIGHUP has two very different
2
+ // senders: the kernel, when the window closes (→ shut down, or we orphan onto a
3
+ // dead terminal), and another program running `kill -HUP` to "reload" (→ shutting
4
+ // down kills every session using the pool; happened 2026-11-07). When the window
5
+ // really closed, the controlling terminal is revoked: opening /dev/tty fails and
6
+ // writes to it fail. When it is still open, both succeed.
7
+ import { openSync, closeSync, writeSync } from 'node:fs';
8
+
9
+ export function controllingTerminalAlive({
10
+ isTTY = Boolean(process.stdout.isTTY),
11
+ fd = process.stdout.fd,
12
+ open = openSync, close = closeSync, write = writeSync,
13
+ } = {}) {
14
+ // Not a real terminal (a pipe, or the test suite's forced-terminal mode): no way
15
+ // to tell, so keep the long-standing answer — treat the SIGHUP as a hangup.
16
+ if (!isTTY) return false;
17
+ try {
18
+ close(open('/dev/tty', 'r+'));
19
+ write(fd, '');
20
+ return true;
21
+ } catch {
22
+ return false;
23
+ }
24
+ }
package/src/tui.js CHANGED
@@ -4,6 +4,7 @@ import { homedir } from 'node:os';
4
4
  import { fetchProfile, loginOAuth, tokenFingerprint, isLoginCancelled } from './oauth.js';
5
5
  import { appendEventLog, setConsoleStdoutSuppressed } from './event-log.js';
6
6
  import { sendLoginToPool } from './cloud-login.js';
7
+ import { describeLinkError } from './pool-link.js';
7
8
 
8
9
  // ── ANSI helpers ─────────────────────────────────────────────
9
10
 
@@ -815,6 +816,22 @@ export class TUI {
815
816
  return ` Routing ${cyan(routing)}${xpText}`;
816
817
  }
817
818
 
819
+ /** One line per unreachable team pool, so a lost connection reads as ONE cause
820
+ * instead of every cloud row turning red. '' lines are skipped by the caller. */
821
+ _cloudLinkLines(W = 80, now = Date.now()) {
822
+ const out = [];
823
+ for (const l of this.am.poolLinks || []) {
824
+ if (!l.lastError && l.lastOkAt != null) continue;
825
+ const since = l.downSince ?? l.lastOkAt;
826
+ const forTxt = since ? ` for ${formatAge(now - since)}` : '';
827
+ const synced = l.lastOkAt ? ` · last synced ${new Date(l.lastOkAt).toLocaleTimeString()}` : '';
828
+ const why = l.lastOkAt == null && !l.lastError ? 'connecting…' : describeLinkError(l.lastError);
829
+ const line = ` Cloud ${yellow(`⟐ ${l.name} unreachable${forTxt}`)} ${dim('—')} ${why}${dim(`. Cloud accounts paused; local accounts still serving${synced}.`)}`;
830
+ out.push(fitLine(line, W));
831
+ }
832
+ return out;
833
+ }
834
+
818
835
  _renderUpdatesDetail() {
819
836
  const v = this.am.versionInfo;
820
837
  const running = v?.current ? `v${v.current}` : 'unknown';
@@ -2076,6 +2093,7 @@ export class TUI {
2076
2093
  if (provReq > 0) xpText += ` ${dim('·')} ${yellow(`providers: ${provReq} req/15m`)}`;
2077
2094
  }
2078
2095
  lines.push(this._routingLine(routing, xpText));
2096
+ lines.push(...this._cloudLinkLines(W));
2079
2097
  const queuedCount = this.am.queueState?.waiting?.length || 0;
2080
2098
  // Throttle and WAITING are different things and used to share one line labelled
2081
2099
  // "Anthropic upstream throttled" — so a request parked purely because every account
@@ -2367,7 +2385,8 @@ export class TUI {
2367
2385
  case 'paused': status = yellow('paused'); break;
2368
2386
  case 'disabled': status = red('✕ disabled'); break;
2369
2387
  case 'pool-benched': status = gray('in cloud'); break;
2370
- case 'cloud-down': status = red('⟐ cloud ✕'); break;
2388
+ // The banner above names the cause once; each row just says it is out of reach.
2389
+ case 'cloud-down': status = yellow('⟐ offline'); break;
2371
2390
  // Disabled AND needs re-login — both facts matter, and DISABLED LEADS.
2372
2391
  // The owner's question that drove this (2026-09-30): "when I disable the account
2373
2392
  // and then the token expires, does it show disabled or reauth? It needs to