@cloudflare/think 0.8.1 → 0.8.3

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/think.js CHANGED
@@ -1,4 +1,4 @@
1
- import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-D_obpP6O.js";
1
+ import { a as _classPrivateFieldSet2, i as _classPrivateFieldGet2, n as sanitizeName, s as _classPrivateFieldInitSpec, t as ExtensionManager } from "./manager-EBL4uMVp.js";
2
2
  import { createWorkspaceTools } from "./tools/workspace.js";
3
3
  import { t as ThinkMessengerRuntime } from "./chat-sdk-Bb93yaZh.js";
4
4
  import { Output, convertToModelMessages, jsonSchema, stepCountIs, streamText } from "ai";
@@ -291,14 +291,14 @@ var ChatStreamStalledError = class extends Error {
291
291
  const CHAT_RECOVERY_INCIDENT_KEY_PREFIX = "cf:chat-recovery:incident:";
292
292
  const CHAT_RECOVERY_PROGRESS_KEY = "cf:chat-recovery:progress";
293
293
  const DEFAULT_CHAT_RECOVERY_MAX_ATTEMPTS = 10;
294
+ const DEFAULT_CHAT_RECOVERY_MAX_WORK = Number.POSITIVE_INFINITY;
294
295
  const DEFAULT_CHAT_RECOVERY_STABLE_TIMEOUT_MS = 1e4;
295
- const AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS = 6e4;
296
296
  const CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS = 3;
297
297
  const DEFAULT_CHAT_RECOVERY_TERMINAL_MESSAGE = "The assistant was interrupted and could not recover. Please try again.";
298
298
  const CHAT_RECOVERY_INCIDENT_TTL_MS = 3600 * 1e3;
299
- const CHAT_RECOVERY_NO_PROGRESS_WINDOW_MS = 300 * 1e3;
299
+ const DEFAULT_CHAT_RECOVERY_NO_PROGRESS_TIMEOUT_MS = 300 * 1e3;
300
300
  const CHAT_RECOVERY_ALARM_DEBOUNCE_MS = 30 * 1e3;
301
- const CHAT_RECOVERY_MAX_WINDOW_MS = 900 * 1e3;
301
+ const CHAT_RECOVERING_FLAG_TTL_MS = 900 * 1e3;
302
302
  const AGENT_TOOL_STREAM_PROGRESS_BUMP_THROTTLE_MS = 5e3;
303
303
  const CONTINUE_CHECKPOINT_PROMPT = "Continue your previous response from exactly where it left off. Do not repeat any of it.";
304
304
  /**
@@ -326,6 +326,61 @@ function defineScheduledTasks(tasks) {
326
326
  return tasks;
327
327
  }
328
328
  const THINK_WORKFLOW_PROMPT_METADATA_KEY = "__thinkWorkflowPrompt";
329
+ /**
330
+ * Matches the context-window-overflow error messages of the common providers.
331
+ * Anthropic (`prompt is too long`), OpenAI (`context_length_exceeded`,
332
+ * `maximum context length`, `reduce the length of …`), Google Gemini (`exceeds
333
+ * the maximum number of tokens`, `input token count`), Bedrock / Mistral /
334
+ * others (`input is too long`, `too many tokens`, `context window`).
335
+ *
336
+ * This default deliberately favors recall over precision: a missed overflow
337
+ * means no recovery (the feature's whole point), whereas a false positive
338
+ * self-heals — the retry hits the same non-overflow error, the budget is spent,
339
+ * and it surfaces terminally anyway. The vaguest fragment (`reduce the length`)
340
+ * is anchored to `of` to match the real OpenAI phrasing without matching
341
+ * unrelated prose. Apps that need stricter matching can wrap this classifier.
342
+ */
343
+ const CONTEXT_OVERFLOW_PATTERN = /prompt is too long|context[_ ]length[_ ]exceeded|maximum context length|exceeds the maximum number of tokens|input token count|reduce the length of|input is too long|too many (?:input )?tokens|context window/i;
344
+ /**
345
+ * Opt-in default classifier for {@link Think.classifyChatError}. Matches the
346
+ * context-window-overflow error messages of the common providers (Anthropic,
347
+ * OpenAI, Google, Bedrock, Mistral, …) and returns `"context_overflow"`.
348
+ *
349
+ * Think ships this as an explicitly-imported helper rather than wiring it into
350
+ * core, so the framework default stays free of provider strings. Assign it (or
351
+ * delegate to it) when you do not need custom classification:
352
+ *
353
+ * @example
354
+ * ```typescript
355
+ * import { Think, defaultContextOverflowClassifier } from "@cloudflare/think";
356
+ *
357
+ * export class MyAgent extends Think<Env> {
358
+ * override contextOverflow = { reactive: true };
359
+ * override classifyChatError = defaultContextOverflowClassifier;
360
+ * }
361
+ * ```
362
+ *
363
+ * Or combine with your own checks:
364
+ *
365
+ * @example
366
+ * ```typescript
367
+ * override classifyChatError(error: unknown): ChatErrorClassification | void {
368
+ * if (isMyRateLimit(error)) return "rate_limit";
369
+ * return defaultContextOverflowClassifier(error);
370
+ * }
371
+ * ```
372
+ */
373
+ function defaultContextOverflowClassifier(error) {
374
+ let text;
375
+ if (error instanceof Error) text = error.message;
376
+ else if (typeof error === "string") text = error;
377
+ else try {
378
+ text = JSON.stringify(error);
379
+ } catch {
380
+ text = String(error);
381
+ }
382
+ return CONTEXT_OVERFLOW_PATTERN.test(text) ? "context_overflow" : void 0;
383
+ }
329
384
  const TIMED_OUT = Symbol("timed-out");
330
385
  var _configCache = /* @__PURE__ */ new WeakMap();
331
386
  var _configTableReady = /* @__PURE__ */ new WeakMap();
@@ -374,6 +429,10 @@ var Think = class Think extends Agent {
374
429
  this.maxSteps = 10;
375
430
  this.sendReasoning = true;
376
431
  this.chatStreamStallTimeoutMs = 0;
432
+ this._turnModelMessageBaseline = 0;
433
+ this._activeTurnTools = {};
434
+ this._proactiveCompactionsThisRun = 0;
435
+ this._warnedMissingClassifier = false;
377
436
  this.hookTimeout = 5e3;
378
437
  this._lastAgentToolStreamProgressAt = 0;
379
438
  const _onStart = this.onStart.bind(this);
@@ -861,6 +920,22 @@ var Think = class Think extends Agent {
861
920
  lines.push("- Do not claim access to capabilities that are not exposed as tools in this turn.");
862
921
  return lines.join("\n");
863
922
  }
923
+ /** Whether the reactive compact-and-retry backstop is enabled. */
924
+ get _overflowReactiveEnabled() {
925
+ return this.contextOverflow?.reactive === true;
926
+ }
927
+ /** Reactive compact-and-retry budget. */
928
+ get _overflowMaxRetries() {
929
+ return this.contextOverflow?.maxRetries ?? 1;
930
+ }
931
+ /** Proactive guard config, when enabled. */
932
+ get _overflowGuard() {
933
+ return this.contextOverflow?.proactive;
934
+ }
935
+ /** Per-run cap on proactive compactions (independent of the reactive budget). */
936
+ get _overflowProactiveMaxCompactions() {
937
+ return Math.max(1, this.contextOverflow?.proactive?.maxCompactions ?? 1);
938
+ }
864
939
  /**
865
940
  * Configure the session. Called once during `onStart`.
866
941
  * Override to add context blocks, compaction, search, skills.
@@ -1111,9 +1186,123 @@ var Think = class Think extends Agent {
1111
1186
  onChatError(error, _ctx) {
1112
1187
  return error;
1113
1188
  }
1189
+ /**
1190
+ * Classify a raw chat-turn error into a provider-agnostic category.
1191
+ *
1192
+ * Think deliberately ships **no** provider-specific matching: it cannot know
1193
+ * that Anthropic's `"prompt is too long"` or OpenAI's
1194
+ * `context_length_exceeded` means "context overflow" without baking provider
1195
+ * knowledge into core. The app does know its provider/model, so it owns the
1196
+ * mapping — the same split Think already uses for `tokenCounter`.
1197
+ *
1198
+ * Currently this hook drives **only** context-overflow recovery: it is
1199
+ * consulted when a turn errors **and** `contextOverflow.reactive` is enabled
1200
+ * (if reactive is off, it is not called). Return `"context_overflow"` to run
1201
+ * the compact-and-retry backstop; if recovery cannot save the turn, that
1202
+ * classification is surfaced on the terminal `onChatError` call via
1203
+ * {@link ChatErrorContext.classification}. The other categories are reserved
1204
+ * for future use — returning one today is a no-op (the turn terminalizes as
1205
+ * usual) and it is **not** forwarded to `onChatError`. Returning
1206
+ * `void`/`"unknown"` keeps the existing terminal behavior.
1207
+ *
1208
+ * The argument may be an `Error`, an AI SDK `APICallError` (with
1209
+ * `statusCode`/`responseBody`), or — for in-stream provider errors that
1210
+ * surface as a stream error part rather than a throw — the error message
1211
+ * string. Narrow accordingly.
1212
+ *
1213
+ * The second argument carries a {@link ChatErrorContext}: when consulted for
1214
+ * overflow recovery it is `{ stage: "stream", requestId }`, so a classifier
1215
+ * can correlate the error with the in-flight turn (e.g. to call
1216
+ * {@link cancelChat}).
1217
+ *
1218
+ * @example Anthropic + OpenAI context-overflow
1219
+ * ```typescript
1220
+ * classifyChatError(error: unknown): ChatErrorClassification | void {
1221
+ * const text = error instanceof Error ? error.message : String(error);
1222
+ * if (/prompt is too long|context length|context_length_exceeded|maximum context/i.test(text)) {
1223
+ * return "context_overflow";
1224
+ * }
1225
+ * }
1226
+ * ```
1227
+ */
1228
+ classifyChatError(_error, _ctx) {}
1229
+ /**
1230
+ * Whether an error (thrown or surfaced as an in-stream error string) should
1231
+ * trigger the opt-in compact-and-retry backstop. Consults the app's
1232
+ * `classifyChatError` and the `contextOverflow.reactive` flag. Centralized
1233
+ * so both stream consumers (WebSocket + RPC) classify identically.
1234
+ */
1235
+ _isRecoverableContextOverflow(error, requestId) {
1236
+ if (!this._overflowReactiveEnabled) return false;
1237
+ if (this.classifyChatError === Think.prototype.classifyChatError) {
1238
+ if (!this._warnedMissingClassifier) {
1239
+ this._warnedMissingClassifier = true;
1240
+ console.warn("[Think] contextOverflow.reactive is enabled but classifyChatError() is not overridden, so no error will ever be treated as a context overflow and recovery will never run. Override classifyChatError() (or assign the exported defaultContextOverflowClassifier) to return \"context_overflow\" for your provider's context-window error (e.g. Anthropic \"prompt is too long\", OpenAI context_length_exceeded).");
1241
+ }
1242
+ return false;
1243
+ }
1244
+ let classification;
1245
+ try {
1246
+ classification = this.classifyChatError(error, {
1247
+ stage: "stream",
1248
+ requestId
1249
+ });
1250
+ } catch (err) {
1251
+ console.warn(`[Think] classifyChatError threw; treating as non-overflow: ${err instanceof Error ? err.message : String(err)}`);
1252
+ return false;
1253
+ }
1254
+ return classification === "context_overflow";
1255
+ }
1256
+ /**
1257
+ * Compact the session in response to a context overflow (reactive backstop or
1258
+ * proactive guard). Returns whether history was actually shortened — a no-op
1259
+ * compaction (returns `null`) means a retry would just overflow again, so the
1260
+ * caller should fall through to the terminal error rather than loop.
1261
+ *
1262
+ * This is the single emit point for `chat:context:compacted`, so callers must
1263
+ * NOT emit it again.
1264
+ */
1265
+ async _compactForContextOverflow(reason, extra) {
1266
+ try {
1267
+ const result = await this.session.compact();
1268
+ const shortened = Boolean(result);
1269
+ this._emit("chat:context:compacted", {
1270
+ reason,
1271
+ shortened,
1272
+ ...extra
1273
+ });
1274
+ return shortened;
1275
+ } catch (err) {
1276
+ console.warn(`[Think] context-overflow compaction failed: ${err instanceof Error ? err.message : String(err)}`);
1277
+ return false;
1278
+ }
1279
+ }
1280
+ /**
1281
+ * Finalize a context overflow that recovery could not fix (compaction was a
1282
+ * no-op, or the retry budget is spent). Routes the error through
1283
+ * `onChatError` with `classification: "context_overflow"` and emits
1284
+ * `chat:request:failed`, so every overflow terminal — whichever path it took
1285
+ * — is reported identically. Returns the (possibly app-reshaped) message for
1286
+ * the caller to deliver via its own transport (RPC callback / WS broadcast).
1287
+ */
1288
+ _finalizeContextOverflowError(requestId, rawError) {
1289
+ const raw = rawError ?? "Context window exceeded.";
1290
+ const wrapped = this.onChatError(raw, {
1291
+ requestId,
1292
+ stage: "stream",
1293
+ messagesPersisted: true,
1294
+ classification: "context_overflow"
1295
+ });
1296
+ const message = wrapped instanceof Error ? wrapped.message : String(wrapped);
1297
+ this._emit("chat:request:failed", {
1298
+ requestId,
1299
+ stage: "stream",
1300
+ messagesPersisted: true,
1301
+ error: message
1302
+ });
1303
+ return message;
1304
+ }
1114
1305
  async _initializeExtensions() {
1115
- const { ExtensionManager } = await import("./manager-DnCkoyVo.js").then((n) => n.n);
1116
- const { sanitizeName } = await import("./manager-DnCkoyVo.js").then((n) => n.n);
1117
1306
  const agentClassName = this.constructor.name;
1118
1307
  const agentId = this.ctx.id.toString();
1119
1308
  const ctxExports = this.ctx.exports;
@@ -1149,12 +1338,76 @@ var Think = class Think extends Agent {
1149
1338
  });
1150
1339
  }
1151
1340
  /**
1341
+ * Assemble provider-ready model messages from the current session history:
1342
+ * repair the transcript, truncate older messages, drop any still-incomplete
1343
+ * tool calls, and convert to `ModelMessage[]`. Shared by the turn entry point
1344
+ * and the proactive context guard so a mid-turn recompaction rebuilds the
1345
+ * head through the exact same pipeline.
1346
+ */
1347
+ async _assembleModelMessages(tools) {
1348
+ const truncated = truncateOlderMessages(await this._repairTranscriptForProvider(this.messages));
1349
+ const incompleteAfterRepair = this._incompleteToolCallIds(truncated);
1350
+ if (incompleteAfterRepair.length > 0) {
1351
+ console.warn(`[Think] ${incompleteAfterRepair.length} incomplete tool call(s) survived transcript repair and will be dropped by ignoreIncompleteToolCalls: ${incompleteAfterRepair.join(", ")}. This indicates a gap in _repairToolTranscriptParts.`);
1352
+ this._emit("chat:transcript:repaired", {
1353
+ removedToolCalls: incompleteAfterRepair.length,
1354
+ normalizedInputs: 0,
1355
+ toolCallIds: incompleteAfterRepair
1356
+ });
1357
+ }
1358
+ return convertToModelMessages(truncated, {
1359
+ tools,
1360
+ ignoreIncompleteToolCalls: true
1361
+ });
1362
+ }
1363
+ /**
1364
+ * Proactive context guard (Layer 1). Runs before each step from the
1365
+ * `prepareStep` wrapper. If `contextOverflow.proactive` is set and the *previous*
1366
+ * step's model-reported input tokens cross the budget, compact the session in
1367
+ * place and return recompacted messages for the upcoming step — heading off a
1368
+ * provider context-overflow 400 before it happens.
1369
+ *
1370
+ * Keys off `usage.inputTokens` (provider-agnostic; every provider reports it)
1371
+ * rather than any provider error string, and reuses `_assembleModelMessages`
1372
+ * so the recompacted head goes through the same repair/convert pipeline. The
1373
+ * current turn's in-flight steps (everything after `_turnModelMessageBaseline`)
1374
+ * are spliced back on so no completed work is lost.
1375
+ *
1376
+ * Best-effort: any failure (no-op compaction, reconciliation that would leave
1377
+ * an incomplete tool pair) returns `undefined` so the step proceeds unchanged
1378
+ * and the reactive backstop (`contextOverflow.reactive`) can still
1379
+ * catch a genuine overflow.
1380
+ */
1381
+ async _maybeProactiveContextCompact(event) {
1382
+ const guard = this._overflowGuard;
1383
+ if (!guard || guard.maxInputTokens <= 0) return void 0;
1384
+ if (this._proactiveCompactionsThisRun >= this._overflowProactiveMaxCompactions) return void 0;
1385
+ const prev = event.steps?.at(-1);
1386
+ const used = prev?.usage?.inputTokens ?? prev?.usage?.totalTokens;
1387
+ if (used == null || !Number.isFinite(used)) return void 0;
1388
+ const headroom = guard.headroom ?? .9;
1389
+ if (used < guard.maxInputTokens * headroom) return void 0;
1390
+ try {
1391
+ this._proactiveCompactionsThisRun++;
1392
+ if (!await this._compactForContextOverflow("proactive")) return void 0;
1393
+ const head = await this._assembleModelMessages(this._activeTurnTools);
1394
+ const tail = event.messages.slice(this._turnModelMessageBaseline);
1395
+ const merged = [...head, ...tail];
1396
+ this._turnModelMessageBaseline = head.length;
1397
+ return merged;
1398
+ } catch (err) {
1399
+ console.warn(`[Think] proactive context compaction failed; proceeding without it: ${err instanceof Error ? err.message : String(err)}`);
1400
+ return;
1401
+ }
1402
+ }
1403
+ /**
1152
1404
  * The single convergence point for all chat turn entry paths.
1153
1405
  * Merges tools, assembles context, fires lifecycle hooks, wraps tools
1154
1406
  * for interception, and calls streamText.
1155
1407
  */
1156
1408
  async _runInferenceLoop(input) {
1157
1409
  this._activeStallTimeoutMs = void 0;
1410
+ this._proactiveCompactionsThisRun = 0;
1158
1411
  if (this.waitForMcpConnections) {
1159
1412
  const timeout = typeof this.waitForMcpConnections === "object" ? this.waitForMcpConnections.timeout : 1e4;
1160
1413
  await this.mcp.waitForConnections({ timeout });
@@ -1177,20 +1430,7 @@ var Think = class Think extends Agent {
1177
1430
  };
1178
1431
  const baseSystem = await this.session.freezeSystemPrompt() || this.getSystemPrompt();
1179
1432
  const system = this._systemPromptForTurn(baseSystem, tools);
1180
- const truncated = truncateOlderMessages(await this._repairTranscriptForProvider(this.messages));
1181
- const incompleteAfterRepair = this._incompleteToolCallIds(truncated);
1182
- if (incompleteAfterRepair.length > 0) {
1183
- console.warn(`[Think] ${incompleteAfterRepair.length} incomplete tool call(s) survived transcript repair and will be dropped by ignoreIncompleteToolCalls: ${incompleteAfterRepair.join(", ")}. This indicates a gap in _repairToolTranscriptParts.`);
1184
- this._emit("chat:transcript:repaired", {
1185
- removedToolCalls: incompleteAfterRepair.length,
1186
- normalizedInputs: 0,
1187
- toolCallIds: incompleteAfterRepair
1188
- });
1189
- }
1190
- const messages = await convertToModelMessages(truncated, {
1191
- tools,
1192
- ignoreIncompleteToolCalls: true
1193
- });
1433
+ const messages = await this._assembleModelMessages(tools);
1194
1434
  if (messages.length === 0) throw new Error("No messages to send to the model. This usually means the chat request arrived before any messages were persisted.");
1195
1435
  const model = this.getModel();
1196
1436
  const ctx = {
@@ -1216,6 +1456,8 @@ var Think = class Think extends Agent {
1216
1456
  ...config.tools
1217
1457
  } : tools;
1218
1458
  const finalTools = this._wrapToolsWithDecision(mergedTools);
1459
+ this._turnModelMessageBaseline = finalMessages.length;
1460
+ this._activeTurnTools = mergedTools;
1219
1461
  const finalMaxSteps = config.maxSteps ?? this.maxSteps;
1220
1462
  const finalSendReasoning = config.sendReasoning ?? this.sendReasoning;
1221
1463
  this._activeStallTimeoutMs = config.chatStreamStallTimeoutMs ?? this.chatStreamStallTimeoutMs;
@@ -1245,8 +1487,15 @@ var Think = class Think extends Agent {
1245
1487
  output: finalOutput,
1246
1488
  abortSignal: input.signal,
1247
1489
  prepareStep: (async (event) => {
1490
+ const guarded = await this._maybeProactiveContextCompact(event);
1248
1491
  const result = await this.beforeStep(event);
1249
- return result == null ? {} : result;
1492
+ const base = result == null ? {} : result;
1493
+ const baseMessages = base.messages;
1494
+ if (guarded && baseMessages === void 0) return {
1495
+ ...base,
1496
+ messages: guarded
1497
+ };
1498
+ return base;
1250
1499
  }),
1251
1500
  onChunk: async (event) => {
1252
1501
  await this.onChunk(event);
@@ -1571,32 +1820,45 @@ var Think = class Think extends Agent {
1571
1820
  await this._appendMessageToHistory(userMsg);
1572
1821
  this._broadcastMessages();
1573
1822
  const chatBody = async () => {
1574
- let result;
1575
- try {
1576
- result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
1577
- agent: this,
1578
- connection: void 0,
1579
- request: void 0,
1580
- email: void 0
1581
- }, () => this._runInferenceLoop({
1582
- signal: abortSignal,
1583
- continuation: false
1584
- }));
1585
- } catch (error) {
1586
- const wrapped = this.onChatError(error, {
1587
- stage: "turn",
1588
- messagesPersisted: true
1589
- });
1590
- const errorMessage = wrapped instanceof Error ? wrapped.message : String(wrapped);
1591
- this._emit("chat:request:failed", {
1592
- stage: "turn",
1593
- messagesPersisted: true,
1594
- error: errorMessage
1595
- });
1596
- await callback.onError(errorMessage);
1823
+ for (let attempt = 0;; attempt++) {
1824
+ let result;
1825
+ try {
1826
+ result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
1827
+ agent: this,
1828
+ connection: void 0,
1829
+ request: void 0,
1830
+ email: void 0
1831
+ }, () => this._runInferenceLoop({
1832
+ signal: abortSignal,
1833
+ continuation: false
1834
+ }));
1835
+ } catch (error) {
1836
+ const wrapped = this.onChatError(error, {
1837
+ stage: "turn",
1838
+ messagesPersisted: true
1839
+ });
1840
+ const errorMessage = wrapped instanceof Error ? wrapped.message : String(wrapped);
1841
+ this._emit("chat:request:failed", {
1842
+ stage: "turn",
1843
+ messagesPersisted: true,
1844
+ error: errorMessage
1845
+ });
1846
+ await callback.onError(errorMessage);
1847
+ return;
1848
+ }
1849
+ const { status, error } = await this._streamResultToRpcCallback(requestId, result, callback, abortSignal, { overflowRecovery: this._overflowReactiveEnabled });
1850
+ if (status === "overflow_retry") {
1851
+ if (attempt < this._overflowMaxRetries && !abortSignal?.aborted) {
1852
+ if (await this._compactForContextOverflow("reactive", {
1853
+ requestId,
1854
+ attempt: attempt + 1
1855
+ })) continue;
1856
+ }
1857
+ const message = this._finalizeContextOverflowError(requestId, error);
1858
+ await callback.onError(message);
1859
+ }
1597
1860
  return;
1598
1861
  }
1599
- await this._streamResultToRpcCallback(requestId, result, callback, abortSignal);
1600
1862
  };
1601
1863
  if (this.chatRecovery) await this._runChatRecoveryFiber(requestId, false, chatBody);
1602
1864
  else await chatBody();
@@ -1756,6 +2018,7 @@ var Think = class Think extends Agent {
1756
2018
  const row = this._readAgentToolChildRun(runId);
1757
2019
  if (!row || row.completed_at !== null) return;
1758
2020
  this._agentToolAbortControllers.get(runId)?.abort(reason);
2021
+ for (const controller of this._submissionAbortControllers.values()) controller.abort(reason);
1759
2022
  this.sql`
1760
2023
  UPDATE cf_agent_tool_child_runs
1761
2024
  SET status = 'aborted',
@@ -1764,6 +2027,7 @@ var Think = class Think extends Agent {
1764
2027
  WHERE run_id = ${runId}
1765
2028
  AND status NOT IN ('completed', 'error', 'aborted')
1766
2029
  `;
2030
+ this._finalizeAgentToolChildRunTailers(runId);
1767
2031
  }
1768
2032
  /**
1769
2033
  * Classify any in-flight chat-recovery on this child facet (#1630). A child
@@ -1838,6 +2102,38 @@ var Think = class Think extends Agent {
1838
2102
  this._agentToolLastErrors.delete(runId);
1839
2103
  this._agentToolPreTurnAssistantIds.delete(runId);
1840
2104
  }
2105
+ /**
2106
+ * Eagerly terminalize this child facet's OWN agent-tool run row(s) once a
2107
+ * recovered turn has settled. A recovered turn re-runs via either
2108
+ * `_chatRecoveryContinue` → `continueLastTurn` or, for a pre-stream eviction,
2109
+ * `_chatRecoveryRetry` (a fresh user turn) — neither flows through
2110
+ * `startAgentToolRun`'s finalizer, so without this the run row strands
2111
+ * `running` and its tailers stay open until a parent inspect lazily
2112
+ * reconciles it — forcing a re-attached parent to wait out a full no-progress
2113
+ * window before collecting an already-finished result (#1630 follow-up).
2114
+ * Reconciling here closes the tail promptly so the parent collects the
2115
+ * terminal immediately. No-op on non-child facets (their
2116
+ * `cf_agent_tool_child_runs` table is empty) and on rows whose in-memory run
2117
+ * is still live (those are finalized by `startAgentToolRun`); the underlying
2118
+ * reconcile leaves a row `running` while its recovery is still in progress.
2119
+ */
2120
+ async _reconcileOwnStaleAgentToolChildRuns() {
2121
+ let rows;
2122
+ try {
2123
+ rows = this.sql`
2124
+ SELECT run_id FROM cf_agent_tool_child_runs
2125
+ WHERE completed_at IS NULL
2126
+ `;
2127
+ } catch {
2128
+ return;
2129
+ }
2130
+ for (const { run_id } of rows) {
2131
+ if (this._agentToolAbortControllers.has(run_id)) continue;
2132
+ try {
2133
+ await this._reconcileStaleAgentToolChildRun(run_id);
2134
+ } catch {}
2135
+ }
2136
+ }
1841
2137
  async getAgentToolChunks(runId, options) {
1842
2138
  const row = this._readAgentToolChildRun(runId);
1843
2139
  if (!row?.stream_id) return [];
@@ -2997,26 +3293,46 @@ var Think = class Think extends Agent {
2997
3293
  const detachExternal = this._aborts.linkExternal(requestId, options?.signal);
2998
3294
  try {
2999
3295
  const programmaticBody = async () => {
3000
- const result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
3001
- agent: this,
3002
- connection: void 0,
3003
- request: void 0,
3004
- email: void 0
3005
- }, () => this._runInferenceLoop({
3006
- signal: abortSignal,
3007
- clientTools,
3008
- body,
3009
- workflowPrompt: options?.workflowPrompt,
3010
- continuation: false
3011
- }));
3012
- if (result) {
3296
+ for (let attempt = 0;; attempt++) {
3297
+ const result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
3298
+ agent: this,
3299
+ connection: void 0,
3300
+ request: void 0,
3301
+ email: void 0
3302
+ }, () => this._runInferenceLoop({
3303
+ signal: abortSignal,
3304
+ clientTools,
3305
+ body,
3306
+ workflowPrompt: options?.workflowPrompt,
3307
+ continuation: false
3308
+ }));
3309
+ if (!result) return;
3310
+ let overflowError;
3311
+ let overflowRequested = false;
3312
+ const overflowRecovery = this._overflowReactiveEnabled ? { onRetry: (err) => {
3313
+ overflowRequested = true;
3314
+ overflowError = err;
3315
+ } } : void 0;
3013
3316
  const streamResult = await this._streamResult(requestId, result, abortSignal, {
3014
3317
  captureProgrammaticStreamError: options?.captureProgrammaticStreamError,
3015
- captureOutput: options?.captureOutput
3318
+ captureOutput: options?.captureOutput,
3319
+ overflowRecovery
3016
3320
  });
3321
+ if (overflowRequested) {
3322
+ if (attempt < this._overflowMaxRetries && !abortSignal?.aborted) {
3323
+ if (await this._compactForContextOverflow("reactive", {
3324
+ requestId,
3325
+ attempt: attempt + 1
3326
+ })) continue;
3327
+ }
3328
+ error = this._finalizeContextOverflowError(requestId, overflowError);
3329
+ status = "error";
3330
+ return;
3331
+ }
3017
3332
  status = streamResult.status;
3018
3333
  error = streamResult.error;
3019
3334
  output = streamResult.output;
3335
+ return;
3020
3336
  }
3021
3337
  };
3022
3338
  if (this.chatRecovery) await this._runChatRecoveryFiber(requestId, false, programmaticBody);
@@ -3219,10 +3535,12 @@ var Think = class Think extends Agent {
3219
3535
  }
3220
3536
  this._enqueueInteractionApply(() => this._applyToolResult(event.toolCallId, event.output, event.state, event.errorText));
3221
3537
  if (event.autoContinue) this._scheduleAutoContinuation(connection);
3538
+ else this._rearmPendingAutoContinuationForBatch();
3222
3539
  break;
3223
3540
  case "tool-approval":
3224
3541
  this._enqueueInteractionApply(() => this._applyToolApproval(event.toolCallId, event.approved));
3225
3542
  if (event.autoContinue) this._scheduleAutoContinuation(connection);
3543
+ else this._rearmPendingAutoContinuationForBatch();
3226
3544
  break;
3227
3545
  case "clear":
3228
3546
  await this._handleClear(connection);
@@ -3348,24 +3666,55 @@ var Think = class Think extends Agent {
3348
3666
  }
3349
3667
  }
3350
3668
  const chatTurnBody = async () => {
3351
- const result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
3352
- agent: this,
3353
- connection,
3354
- request: void 0,
3355
- email: void 0
3356
- }, () => this._runInferenceLoop({
3357
- signal: abortSignal,
3358
- clientTools: clientToolsForTurn,
3359
- body: bodyForTurn,
3360
- continuation: false
3361
- }));
3362
- if (result) await this._streamResult(requestId, result, abortSignal, { parentId: branchParentId });
3363
- else this._broadcastChat({
3364
- type: MSG_CHAT_RESPONSE,
3365
- id: requestId,
3366
- body: "No response was generated.",
3367
- done: true
3368
- });
3669
+ for (let attempt = 0;; attempt++) {
3670
+ const result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
3671
+ agent: this,
3672
+ connection,
3673
+ request: void 0,
3674
+ email: void 0
3675
+ }, () => this._runInferenceLoop({
3676
+ signal: abortSignal,
3677
+ clientTools: clientToolsForTurn,
3678
+ body: bodyForTurn,
3679
+ continuation: false
3680
+ }));
3681
+ if (!result) {
3682
+ this._broadcastChat({
3683
+ type: MSG_CHAT_RESPONSE,
3684
+ id: requestId,
3685
+ body: "No response was generated.",
3686
+ done: true
3687
+ });
3688
+ return;
3689
+ }
3690
+ let overflowError;
3691
+ let overflowRequested = false;
3692
+ const overflowRecovery = this._overflowReactiveEnabled ? { onRetry: (error) => {
3693
+ overflowRequested = true;
3694
+ overflowError = error;
3695
+ } } : void 0;
3696
+ await this._streamResult(requestId, result, abortSignal, {
3697
+ parentId: branchParentId,
3698
+ overflowRecovery
3699
+ });
3700
+ if (overflowRequested) {
3701
+ if (attempt < this._overflowMaxRetries && !abortSignal?.aborted) {
3702
+ if (await this._compactForContextOverflow("reactive", {
3703
+ requestId,
3704
+ attempt: attempt + 1
3705
+ })) continue;
3706
+ }
3707
+ const message = this._finalizeContextOverflowError(requestId, overflowError);
3708
+ this._broadcastChat({
3709
+ type: MSG_CHAT_RESPONSE,
3710
+ id: requestId,
3711
+ body: message,
3712
+ done: true,
3713
+ error: true
3714
+ });
3715
+ }
3716
+ return;
3717
+ }
3369
3718
  };
3370
3719
  if (this.chatRecovery) await this._runChatRecoveryFiber(requestId, false, chatTurnBody);
3371
3720
  else await chatTurnBody();
@@ -3489,7 +3838,7 @@ var Think = class Think extends Agent {
3489
3838
  await this._clearHistory();
3490
3839
  this._broadcast({ type: MSG_CHAT_CLEAR }, connection ? [connection.id] : void 0);
3491
3840
  }
3492
- async _streamResultToRpcCallback(requestId, result, callback, abortSignal) {
3841
+ async _streamResultToRpcCallback(requestId, result, callback, abortSignal, options) {
3493
3842
  const streamId = this._resumableStream.start(requestId);
3494
3843
  const accumulator = new StreamAccumulator({ messageId: crypto.randomUUID() });
3495
3844
  this._streamingAssistant = accumulator;
@@ -3499,6 +3848,8 @@ var Think = class Think extends Agent {
3499
3848
  let doneSent = false;
3500
3849
  let streamError;
3501
3850
  let pendingRpcError;
3851
+ let skipFinalizeRearm = false;
3852
+ let overflowRetry = false;
3502
3853
  const stallTimeoutMs = this._activeStallTimeoutMs ?? this.chatStreamStallTimeoutMs;
3503
3854
  try {
3504
3855
  this._insideInferenceLoop = true;
@@ -3523,6 +3874,10 @@ var Think = class Think extends Agent {
3523
3874
  const { action } = accumulator.applyChunk(streamChunk);
3524
3875
  if (action?.type === "error") {
3525
3876
  streamError = action.error;
3877
+ if (options?.overflowRecovery && this._isRecoverableContextOverflow(streamError, requestId)) {
3878
+ overflowRetry = true;
3879
+ break;
3880
+ }
3526
3881
  this._emit("message:error", { error: streamError });
3527
3882
  this._emit("chat:request:failed", {
3528
3883
  requestId,
@@ -3552,6 +3907,14 @@ var Think = class Think extends Agent {
3552
3907
  } finally {
3553
3908
  this._insideInferenceLoop = false;
3554
3909
  }
3910
+ if (overflowRetry) {
3911
+ this._resumableStream.complete(streamId);
3912
+ streamFinalized = true;
3913
+ return {
3914
+ status: "overflow_retry",
3915
+ error: streamError
3916
+ };
3917
+ }
3555
3918
  if (streamError) this._resumableStream.markError(streamId);
3556
3919
  else this._resumableStream.complete(streamId);
3557
3920
  streamFinalized = true;
@@ -3617,8 +3980,9 @@ var Think = class Think extends Agent {
3617
3980
  });
3618
3981
  doneSent = true;
3619
3982
  }
3983
+ skipFinalizeRearm = true;
3620
3984
  await callback.onInterrupted?.();
3621
- return;
3985
+ return { status: "aborted" };
3622
3986
  }
3623
3987
  if (outcome === "exhausted") {
3624
3988
  if (!streamFinalized) {
@@ -3626,8 +3990,9 @@ var Think = class Think extends Agent {
3626
3990
  streamFinalized = true;
3627
3991
  }
3628
3992
  doneSent = true;
3993
+ skipFinalizeRearm = true;
3629
3994
  await callback.onInterrupted?.();
3630
- return;
3995
+ return { status: "aborted" };
3631
3996
  }
3632
3997
  }
3633
3998
  if (!streamFinalized) {
@@ -3671,9 +4036,11 @@ var Think = class Think extends Agent {
3671
4036
  });
3672
4037
  await callback.onError(errorMessage);
3673
4038
  } finally {
3674
- this._streamingAssistant = null;
4039
+ if (skipFinalizeRearm) this._streamingAssistant = null;
4040
+ else this._onStreamingTurnFinalized();
3675
4041
  }
3676
4042
  if (pendingRpcError) await callback.onError(pendingRpcError);
4043
+ return { status: streamError || pendingRpcError ? "error" : aborted ? "aborted" : "completed" };
3677
4044
  }
3678
4045
  /**
3679
4046
  * Whether storing this chunk should immediately flush the resumable-stream
@@ -3768,6 +4135,7 @@ var Think = class Think extends Agent {
3768
4135
  let streamAborted = false;
3769
4136
  let streamError;
3770
4137
  let output;
4138
+ let overflowRetry = false;
3771
4139
  const flushState = {
3772
4140
  chunksSinceFlush: 0,
3773
4141
  hasFlushedContent: false
@@ -3793,6 +4161,10 @@ var Think = class Think extends Agent {
3793
4161
  if (action?.type === "cross-message-tool-update") await this._applyToolUpdateToMessages(crossMessageToolResultUpdate(action.toolCallId, action.updateType, action.output, action.errorText, action.preliminary));
3794
4162
  if (action?.type === "error") {
3795
4163
  streamError = action.error;
4164
+ if (options?.overflowRecovery && this._isRecoverableContextOverflow(streamError, requestId)) {
4165
+ overflowRetry = true;
4166
+ break;
4167
+ }
3796
4168
  if (options?.captureProgrammaticStreamError) this._programmaticStreamErrors.set(requestId, streamError);
3797
4169
  this._emit("message:error", { error: streamError });
3798
4170
  this._emit("chat:request:failed", {
@@ -3824,6 +4196,14 @@ var Think = class Think extends Agent {
3824
4196
  } finally {
3825
4197
  this._insideInferenceLoop = false;
3826
4198
  }
4199
+ if (overflowRetry && options?.overflowRecovery) {
4200
+ this._resumableStream.complete(streamId);
4201
+ this._pendingResumeConnections.clear();
4202
+ doneSent = true;
4203
+ options.overflowRecovery.onRetry(streamError);
4204
+ this._streamingAssistant = null;
4205
+ return { status: "aborted" };
4206
+ }
3827
4207
  if (streamError) this._resumableStream.markError(streamId);
3828
4208
  else this._resumableStream.complete(streamId);
3829
4209
  this._pendingResumeConnections.clear();
@@ -3924,7 +4304,7 @@ var Think = class Think extends Agent {
3924
4304
  } catch (e) {
3925
4305
  console.error("Failed to persist assistant message:", e);
3926
4306
  }
3927
- this._streamingAssistant = null;
4307
+ this._onStreamingTurnFinalized();
3928
4308
  return streamError ? {
3929
4309
  status: "error",
3930
4310
  error: streamError
@@ -4132,6 +4512,9 @@ var Think = class Think extends Agent {
4132
4512
  maxAttempts: Math.max(1, Math.floor(custom?.maxAttempts ?? DEFAULT_CHAT_RECOVERY_MAX_ATTEMPTS)),
4133
4513
  stableTimeoutMs: Math.max(0, Math.floor(custom?.stableTimeoutMs ?? DEFAULT_CHAT_RECOVERY_STABLE_TIMEOUT_MS)),
4134
4514
  terminalMessage: custom?.terminalMessage ?? DEFAULT_CHAT_RECOVERY_TERMINAL_MESSAGE,
4515
+ noProgressTimeoutMs: Math.max(0, Math.floor(custom?.noProgressTimeoutMs ?? DEFAULT_CHAT_RECOVERY_NO_PROGRESS_TIMEOUT_MS)),
4516
+ maxRecoveryWork: typeof custom?.maxRecoveryWork === "number" && custom.maxRecoveryWork >= 0 ? custom.maxRecoveryWork : DEFAULT_CHAT_RECOVERY_MAX_WORK,
4517
+ ...custom?.shouldKeepRecovering ? { shouldKeepRecovering: custom.shouldKeepRecovering } : {},
4135
4518
  ...custom?.onExhausted ? { onExhausted: custom.onExhausted } : {}
4136
4519
  };
4137
4520
  }
@@ -4193,15 +4576,35 @@ var Think = class Think extends Agent {
4193
4576
  const now = input.nowMs ?? Date.now();
4194
4577
  await this._sweepStaleChatRecoveryIncidents(now);
4195
4578
  const existing = await this.ctx.storage.get(key);
4579
+ if (this._lastClientTools === void 0) this._restoreClientTools();
4196
4580
  const prevProgress = existing?.progress ?? 0;
4197
4581
  const currentProgress = await this._chatRecoveryProgressMarker();
4198
4582
  const madeProgress = existing != null && currentProgress > prevProgress;
4199
- const lastProgressAt = madeProgress ? now : existing?.lastProgressAt ?? existing?.firstSeenAt ?? now;
4200
- const noProgressExceeded = existing != null && now - lastProgressAt > CHAT_RECOVERY_NO_PROGRESS_WINDOW_MS;
4201
- const incidentAgeExceeded = existing != null && now - existing.firstSeenAt > CHAT_RECOVERY_MAX_WINDOW_MS;
4583
+ const awaitingClientInteraction = this.hasPendingInteraction();
4584
+ const lastProgressAt = madeProgress || awaitingClientInteraction ? now : existing?.lastProgressAt ?? existing?.firstSeenAt ?? now;
4585
+ const noProgressExceeded = existing != null && !awaitingClientInteraction && now - lastProgressAt > config.noProgressTimeoutMs;
4586
+ const workBaseline = existing?.workBaseline ?? currentProgress;
4587
+ const progress = Math.max(prevProgress, currentProgress);
4588
+ const work = progress - workBaseline;
4589
+ const workBudgetExceeded = existing != null && Number.isFinite(config.maxRecoveryWork) && work > config.maxRecoveryWork;
4202
4590
  const debounced = existing != null && !madeProgress && now - existing.lastAttemptAt < CHAT_RECOVERY_ALARM_DEBOUNCE_MS;
4203
4591
  const attempt = madeProgress ? 1 : debounced ? existing?.attempt ?? 1 : (existing?.attempt ?? 0) + 1;
4204
- const exhausted = noProgressExceeded || incidentAgeExceeded || attempt > config.maxAttempts;
4592
+ let abortedByCaller = false;
4593
+ if (existing != null && !awaitingClientInteraction && config.shouldKeepRecovering && !noProgressExceeded && !workBudgetExceeded && attempt <= config.maxAttempts) try {
4594
+ abortedByCaller = await config.shouldKeepRecovering({
4595
+ incidentId,
4596
+ requestId: input.requestId,
4597
+ recoveryRootRequestId: input.recoveryRootRequestId ?? input.requestId,
4598
+ attempt,
4599
+ maxAttempts: config.maxAttempts,
4600
+ recoveryKind: input.recoveryKind,
4601
+ work,
4602
+ ageMs: now - (existing.firstSeenAt ?? now)
4603
+ }) === false;
4604
+ } catch (error) {
4605
+ console.error("[Think] chatRecovery shouldKeepRecovering hook threw", error);
4606
+ }
4607
+ const exhausted = !awaitingClientInteraction && (noProgressExceeded || workBudgetExceeded || abortedByCaller || attempt > config.maxAttempts);
4205
4608
  const incident = {
4206
4609
  incidentId,
4207
4610
  requestId: input.requestId,
@@ -4213,8 +4616,9 @@ var Think = class Think extends Agent {
4213
4616
  firstSeenAt: existing?.firstSeenAt ?? now,
4214
4617
  lastAttemptAt: now,
4215
4618
  lastProgressAt,
4216
- progress: Math.max(prevProgress, currentProgress),
4217
- ...exhausted ? { reason: incidentAgeExceeded ? "max_recovery_window_exceeded" : noProgressExceeded ? "no_progress_timeout" : "max_attempts_exceeded" } : {}
4619
+ progress,
4620
+ workBaseline,
4621
+ ...exhausted ? { reason: workBudgetExceeded ? "work_budget_exceeded" : noProgressExceeded ? "no_progress_timeout" : abortedByCaller ? "recovery_aborted" : "max_attempts_exceeded" } : {}
4218
4622
  };
4219
4623
  await this.ctx.storage.put(key, incident);
4220
4624
  if (!existing) this._emit("chat:recovery:detected", {
@@ -4541,6 +4945,50 @@ var Think = class Think extends Agent {
4541
4945
  return true;
4542
4946
  }
4543
4947
  /**
4948
+ * Park a recovery continuation that timed out waiting for stable state
4949
+ * because the turn is holding a pending CLIENT interaction (an
4950
+ * `input-available` client-tool part or an `approval-requested` part — see
4951
+ * `hasPendingInteraction`). Such a turn is WAITING ON THE HUMAN, not stuck:
4952
+ * the SPA replays the interrupted tool-result / approval after reconnect,
4953
+ * which drives a fresh continuation via the auto-continuation barrier
4954
+ * independently of the recovery retry loop. Burning the attempt budget on
4955
+ * that wait (each `waitUntilStable` times out because the human hasn't
4956
+ * answered) would seal a perfectly healthy turn on `stable_timeout` — the
4957
+ * exact symptom behind HITL "session recovery errors" under deploy churn.
4958
+ *
4959
+ * So instead of rescheduling or exhausting, we stop the loop and mark the
4960
+ * incident `skipped` (reason `awaiting_client_interaction`). That retains the
4961
+ * incident record (a later genuine interruption re-evaluates it) while
4962
+ * resolving the live "recovering…" indicator via `_updateChatRecoveryIncident`
4963
+ * so the client sees the parked tool-call UI rather than an eternal spinner.
4964
+ * A client that never returns is reclaimed by the incident TTL sweep and DO
4965
+ * idle-eviction. SERVER-tool orphans are excluded by `hasPendingInteraction`
4966
+ * (their `execute` died with the isolate), so they still recover normally.
4967
+ *
4968
+ * For a SUBMISSION-backed turn (`recoveredRequestId` present) the recovery
4969
+ * loop is the submission row's SOLE completion driver after a restart, and the
4970
+ * client's replay resumes the conversation as an independent auto-continuation
4971
+ * that never touches the submission. Parking would therefore leave the row
4972
+ * `running` until `_recoverSubmissionsOnStart` swept it to `error` on the next
4973
+ * restart. We instead complete it `completed` here: the park condition is a
4974
+ * fully-materialized client tool call in the leaf, which is exactly the
4975
+ * terminal state a non-interrupted submission reaches when its step emits a
4976
+ * client tool call (the model does not block on client tools — see
4977
+ * `_runProgrammaticMessagesTurn`, which marks such a step `completed`). The
4978
+ * human round-trip then proceeds via the normal auto-continuation, identical
4979
+ * to the non-crash flow.
4980
+ *
4981
+ * Returns `true` when the recovery was parked (caller must return), `false`
4982
+ * when there is no pending client interaction (caller proceeds to the normal
4983
+ * reschedule / exhaustion path).
4984
+ */
4985
+ async _parkRecoveryForPendingInteraction(data) {
4986
+ if (!this.hasPendingInteraction()) return false;
4987
+ await this._updateChatRecoveryIncident(data?.incidentId, "skipped", "awaiting_client_interaction");
4988
+ if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "completed", null, null);
4989
+ return true;
4990
+ }
4991
+ /**
4544
4992
  * Resolve the stream id for a recovery turn so the give-up terminalization
4545
4993
  * can surface whatever partial the turn produced. Prefers the durable stream
4546
4994
  * row keyed by the recovery-root request id; falls back to the live active
@@ -4702,6 +5150,7 @@ var Think = class Think extends Agent {
4702
5150
  try {
4703
5151
  const recoveryConfig = this._resolveChatRecoveryConfig();
4704
5152
  if (!await this.waitUntilStable({ timeout: recoveryConfig.stableTimeoutMs })) {
5153
+ if (await this._parkRecoveryForPendingInteraction(data)) return;
4705
5154
  if (await this._rescheduleRecoveryAfterStableTimeout("_chatRecoveryRetry", data, recoveryConfig.maxAttempts)) return;
4706
5155
  await this._exhaustRecoveryAfterStableTimeout("_chatRecoveryRetry", data);
4707
5156
  return;
@@ -4726,6 +5175,7 @@ var Think = class Think extends Agent {
4726
5175
  } finally {
4727
5176
  this._activeChatRecoveryRootRequestId = previousRootRequestId;
4728
5177
  if (recoveredSubmission) this._submissionAbortControllers.delete(recoveredSubmission.submission_id);
5178
+ await this._reconcileOwnStaleAgentToolChildRuns();
4729
5179
  }
4730
5180
  }
4731
5181
  _hasRunningSubmission(requestId) {
@@ -4807,6 +5257,7 @@ var Think = class Think extends Agent {
4807
5257
  try {
4808
5258
  const recoveryConfig = this._resolveChatRecoveryConfig();
4809
5259
  if (!await this.waitUntilStable({ timeout: recoveryConfig.stableTimeoutMs })) {
5260
+ if (await this._parkRecoveryForPendingInteraction(data)) return;
4810
5261
  console.warn("[Think] _chatRecoveryContinue timed out waiting for stable state");
4811
5262
  if (await this._rescheduleRecoveryAfterStableTimeout("_chatRecoveryContinue", data, recoveryConfig.maxAttempts)) return;
4812
5263
  await this._exhaustRecoveryAfterStableTimeout("_chatRecoveryContinue", data);
@@ -4829,6 +5280,7 @@ var Think = class Think extends Agent {
4829
5280
  } finally {
4830
5281
  this._activeChatRecoveryRootRequestId = previousRootRequestId;
4831
5282
  if (recoveredSubmission) this._submissionAbortControllers.delete(recoveredSubmission.submission_id);
5283
+ await this._reconcileOwnStaleAgentToolChildRuns();
4832
5284
  }
4833
5285
  }
4834
5286
  _applyRecoveredRequestContext(data) {
@@ -4907,6 +5359,40 @@ var Think = class Think extends Agent {
4907
5359
  this._continuation.awaitingConnections.set(connection.id, connection);
4908
5360
  this._resetAutoContinuationTimer();
4909
5361
  }
5362
+ /**
5363
+ * Re-arm the barrier for a tool result/approval that arrived WITHOUT
5364
+ * `autoContinue` (#1650). The client sends `autoContinue: false` for an
5365
+ * errored tool result (it declines to auto-continue a standalone error), but
5366
+ * in a parallel batch a SIBLING may already have requested continuation — and
5367
+ * this result can be the one that completes the batch. In that case we must
5368
+ * re-run the barrier check so the continuation the sibling requested still
5369
+ * fires once the batch is whole.
5370
+ *
5371
+ * Unlike `_scheduleAutoContinuation` this never CREATES a pending
5372
+ * continuation: a standalone errored tool (no opted-in sibling, so no pending)
5373
+ * must not auto-continue. It also no-ops once the continuation is running
5374
+ * (`pastCoalesce`) — a late result then defers/applies through the normal
5375
+ * path rather than re-arming.
5376
+ */
5377
+ _rearmPendingAutoContinuationForBatch() {
5378
+ const pending = this._continuation.pending;
5379
+ if (!pending || pending.pastCoalesce) return;
5380
+ this._resetAutoContinuationTimer();
5381
+ }
5382
+ /**
5383
+ * Called when a streaming assistant turn finalizes (its message, with ALL
5384
+ * tool parts, is now persisted). Clears the in-flight accumulator and re-runs
5385
+ * the auto-continuation barrier for a continuation the stream-active gate held
5386
+ * (#1650). This is essential for an all-fast parallel batch whose every result
5387
+ * landed mid-stream: once the stream ends there is no further tool-result
5388
+ * event to re-arm the barrier, so without this re-check the held continuation
5389
+ * would never fire. A slow batch is also re-checked here and simply continues
5390
+ * to hold (event-driven) until its remaining siblings answer.
5391
+ */
5392
+ _onStreamingTurnFinalized() {
5393
+ this._streamingAssistant = null;
5394
+ this._rearmPendingAutoContinuationForBatch();
5395
+ }
4910
5396
  _resetAutoContinuationTimer() {
4911
5397
  if (this._continuationTimer) clearTimeout(this._continuationTimer);
4912
5398
  this._continuationTimer = setTimeout(() => {
@@ -4923,48 +5409,64 @@ var Think = class Think extends Agent {
4923
5409
  * arrives while slower siblings are still `input-available`. Continuing then
4924
5410
  * would feed the provider an incomplete tool-result set
4925
5411
  * (`MissingToolResultsError`) or, via the transcript-repair backstop, silently
4926
- * error the in-flight sibling and run a spurious extra continuation. We hold
4927
- * the continuation on a barrier until the batch settles. The wait is bounded
4928
- * (`AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS`) so a genuinely orphaned tool
4929
- * call — e.g. the client disconnected mid-batch — still falls through to the
4930
- * repair backstop rather than pinning the continuation open forever.
5412
+ * error the in-flight sibling and run a spurious extra continuation.
5413
+ *
5414
+ * The barrier is event-driven (#1650). Auto-continuation is only ever
5415
+ * triggered by a tool-result/approval event, so rather than wait on a fixed
5416
+ * timer we drain the in-flight applies, re-check, and — if the batch is still
5417
+ * incomplete — return WITHOUT firing and WITHOUT holding the isolate, leaving
5418
+ * `_continuation.pending` in place. The next sibling's result re-arms the
5419
+ * coalesce timer (`_scheduleAutoContinuation`) and re-runs this check; the
5420
+ * continuation fires once the final sibling lands. If the in-memory pending
5421
+ * state is lost to eviction between siblings, the final result re-creates it
5422
+ * from the persisted transcript and fires with a complete batch — self-healing.
5423
+ * A true orphan (a sibling that never arrives) simply never auto-continues,
5424
+ * which is correct: there is nothing valid to continue, and a later user turn
5425
+ * / chat recovery repairs the transcript.
5426
+ *
5427
+ * The barrier also holds while the assistant turn is still streaming (the
5428
+ * stream-active gate below): mid-stream the batch can still grow with tool
5429
+ * calls the model hasn't emitted yet, so no completeness check is meaningful.
5430
+ * `_onStreamingTurnFinalized` re-runs the check once the stream ends.
4931
5431
  */
4932
5432
  _fireAutoContinuationWhenStable(connection) {
4933
5433
  if (!this._continuation.pending) return;
4934
5434
  if (this._continuation.pending.pastCoalesce) return;
4935
5435
  if (this._continuationBarrierActive) return;
5436
+ if (this._streamingAssistant) return;
4936
5437
  if (!this._pendingInteractionPromise && !this._hasIncompleteToolBatch()) {
4937
5438
  this._fireAutoContinuation(connection);
4938
5439
  return;
4939
5440
  }
4940
5441
  this._continuationBarrierActive = true;
4941
- this.keepAliveWhile(() => this._awaitToolBatch()).catch(() => {}).finally(() => {
5442
+ this.keepAliveWhile(() => this._drainInteractionApplies()).catch(() => {}).finally(() => {
4942
5443
  this._continuationBarrierActive = false;
4943
5444
  const pending = this._continuation.pending;
4944
- if (pending) this._fireAutoContinuation(pending.connection);
5445
+ if (!pending || pending.pastCoalesce) return;
5446
+ if (this._streamingAssistant) return;
5447
+ if (this._hasIncompleteToolBatch()) return;
5448
+ this._fireAutoContinuation(pending.connection);
4945
5449
  });
4946
5450
  }
4947
5451
  /**
4948
- * Block until the latest assistant step's parallel tool batch is fully
4949
- * answered, or `AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS` elapses. Awaits the
4950
- * in-flight tool-result apply when one exists (so a sibling that lands
4951
- * mid-wait is observed promptly) and polls otherwise.
5452
+ * Drain every in-flight tool-result/approval apply, including any enqueued
5453
+ * while we wait, so the subsequent `_hasIncompleteToolBatch()` re-check sees
5454
+ * every result that has ALREADY arrived. Bounded by real apply activity (a
5455
+ * storage write each), never by a fixed timer: a batch with no further
5456
+ * results drains in the time its pending applies take and then returns. The
5457
+ * loop re-reads `_interactionApplyTail` after each await because a sibling can
5458
+ * extend the tail mid-drain; we stop once the tail stops advancing.
4952
5459
  */
4953
- async _awaitToolBatch() {
4954
- const deadline = Date.now() + AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS;
4955
- while (Date.now() < deadline) {
5460
+ async _drainInteractionApplies() {
5461
+ let tail = this._interactionApplyTail;
5462
+ for (;;) {
4956
5463
  if (!this._continuation.pending) return;
4957
- const pending = this._pendingInteractionPromise;
4958
- if (pending) {
4959
- try {
4960
- await pending;
4961
- } catch {}
4962
- continue;
4963
- }
4964
- if (!this._hasIncompleteToolBatch()) return;
4965
- await new Promise((resolve) => setTimeout(resolve, 100));
5464
+ try {
5465
+ await tail;
5466
+ } catch {}
5467
+ if (this._interactionApplyTail === tail) return;
5468
+ tail = this._interactionApplyTail;
4966
5469
  }
4967
- console.warn(`[Think] Auto-continuation proceeding after waiting ${AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS}ms for unanswered parallel tool result(s) (#1649).`);
4968
5470
  }
4969
5471
  /**
4970
5472
  * `true` when the latest assistant message is mid-batch: it carries at least
@@ -5083,7 +5585,7 @@ var Think = class Think extends Agent {
5083
5585
  */
5084
5586
  async _setChatRecovering(active, requestId) {
5085
5587
  const existing = await this.ctx.storage.get(CHAT_RECOVERING_KEY);
5086
- const activeExisting = existing && Date.now() - (existing.at ?? 0) < CHAT_RECOVERY_MAX_WINDOW_MS;
5588
+ const activeExisting = existing && Date.now() - (existing.at ?? 0) < CHAT_RECOVERING_FLAG_TTL_MS;
5087
5589
  if (active) {
5088
5590
  if (activeExisting) return;
5089
5591
  await this.ctx.storage.put(CHAT_RECOVERING_KEY, {
@@ -5121,7 +5623,7 @@ var Think = class Think extends Agent {
5121
5623
  error: true
5122
5624
  });
5123
5625
  const recovering = await this.ctx.storage.get(CHAT_RECOVERING_KEY);
5124
- if (recovering && Date.now() - (recovering.at ?? 0) < CHAT_RECOVERY_MAX_WINDOW_MS) messages.push({
5626
+ if (recovering && Date.now() - (recovering.at ?? 0) < CHAT_RECOVERING_FLAG_TTL_MS) messages.push({
5125
5627
  type: MSG_CHAT_RECOVERING,
5126
5628
  recovering: true,
5127
5629
  ...recovering.requestId ? { id: recovering.requestId } : {}
@@ -5172,6 +5674,6 @@ Think.CHAT_FIBER_NAME = "__cf_internal_chat_turn";
5172
5674
  Think.MESSAGE_DEBOUNCE_MS = 750;
5173
5675
  Think.submissionRecoveryStaleMs = 900 * 1e3;
5174
5676
  //#endregion
5175
- export { Session, Think, Workspace, defineScheduledTasks, skills };
5677
+ export { Session, Think, Workspace, defaultContextOverflowClassifier, defineScheduledTasks, skills };
5176
5678
 
5177
5679
  //# sourceMappingURL=think.js.map