@cloudflare/think 0.8.2 → 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,13 +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
296
  const CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS = 3;
296
297
  const DEFAULT_CHAT_RECOVERY_TERMINAL_MESSAGE = "The assistant was interrupted and could not recover. Please try again.";
297
298
  const CHAT_RECOVERY_INCIDENT_TTL_MS = 3600 * 1e3;
298
- const CHAT_RECOVERY_NO_PROGRESS_WINDOW_MS = 300 * 1e3;
299
+ const DEFAULT_CHAT_RECOVERY_NO_PROGRESS_TIMEOUT_MS = 300 * 1e3;
299
300
  const CHAT_RECOVERY_ALARM_DEBOUNCE_MS = 30 * 1e3;
300
- const CHAT_RECOVERY_MAX_WINDOW_MS = 900 * 1e3;
301
+ const CHAT_RECOVERING_FLAG_TTL_MS = 900 * 1e3;
301
302
  const AGENT_TOOL_STREAM_PROGRESS_BUMP_THROTTLE_MS = 5e3;
302
303
  const CONTINUE_CHECKPOINT_PROMPT = "Continue your previous response from exactly where it left off. Do not repeat any of it.";
303
304
  /**
@@ -325,6 +326,61 @@ function defineScheduledTasks(tasks) {
325
326
  return tasks;
326
327
  }
327
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
+ }
328
384
  const TIMED_OUT = Symbol("timed-out");
329
385
  var _configCache = /* @__PURE__ */ new WeakMap();
330
386
  var _configTableReady = /* @__PURE__ */ new WeakMap();
@@ -373,6 +429,10 @@ var Think = class Think extends Agent {
373
429
  this.maxSteps = 10;
374
430
  this.sendReasoning = true;
375
431
  this.chatStreamStallTimeoutMs = 0;
432
+ this._turnModelMessageBaseline = 0;
433
+ this._activeTurnTools = {};
434
+ this._proactiveCompactionsThisRun = 0;
435
+ this._warnedMissingClassifier = false;
376
436
  this.hookTimeout = 5e3;
377
437
  this._lastAgentToolStreamProgressAt = 0;
378
438
  const _onStart = this.onStart.bind(this);
@@ -860,6 +920,22 @@ var Think = class Think extends Agent {
860
920
  lines.push("- Do not claim access to capabilities that are not exposed as tools in this turn.");
861
921
  return lines.join("\n");
862
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
+ }
863
939
  /**
864
940
  * Configure the session. Called once during `onStart`.
865
941
  * Override to add context blocks, compaction, search, skills.
@@ -1110,9 +1186,123 @@ var Think = class Think extends Agent {
1110
1186
  onChatError(error, _ctx) {
1111
1187
  return error;
1112
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
+ }
1113
1305
  async _initializeExtensions() {
1114
- const { ExtensionManager } = await import("./manager-DnCkoyVo.js").then((n) => n.n);
1115
- const { sanitizeName } = await import("./manager-DnCkoyVo.js").then((n) => n.n);
1116
1306
  const agentClassName = this.constructor.name;
1117
1307
  const agentId = this.ctx.id.toString();
1118
1308
  const ctxExports = this.ctx.exports;
@@ -1148,12 +1338,76 @@ var Think = class Think extends Agent {
1148
1338
  });
1149
1339
  }
1150
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
+ /**
1151
1404
  * The single convergence point for all chat turn entry paths.
1152
1405
  * Merges tools, assembles context, fires lifecycle hooks, wraps tools
1153
1406
  * for interception, and calls streamText.
1154
1407
  */
1155
1408
  async _runInferenceLoop(input) {
1156
1409
  this._activeStallTimeoutMs = void 0;
1410
+ this._proactiveCompactionsThisRun = 0;
1157
1411
  if (this.waitForMcpConnections) {
1158
1412
  const timeout = typeof this.waitForMcpConnections === "object" ? this.waitForMcpConnections.timeout : 1e4;
1159
1413
  await this.mcp.waitForConnections({ timeout });
@@ -1176,20 +1430,7 @@ var Think = class Think extends Agent {
1176
1430
  };
1177
1431
  const baseSystem = await this.session.freezeSystemPrompt() || this.getSystemPrompt();
1178
1432
  const system = this._systemPromptForTurn(baseSystem, tools);
1179
- const truncated = truncateOlderMessages(await this._repairTranscriptForProvider(this.messages));
1180
- const incompleteAfterRepair = this._incompleteToolCallIds(truncated);
1181
- if (incompleteAfterRepair.length > 0) {
1182
- 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.`);
1183
- this._emit("chat:transcript:repaired", {
1184
- removedToolCalls: incompleteAfterRepair.length,
1185
- normalizedInputs: 0,
1186
- toolCallIds: incompleteAfterRepair
1187
- });
1188
- }
1189
- const messages = await convertToModelMessages(truncated, {
1190
- tools,
1191
- ignoreIncompleteToolCalls: true
1192
- });
1433
+ const messages = await this._assembleModelMessages(tools);
1193
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.");
1194
1435
  const model = this.getModel();
1195
1436
  const ctx = {
@@ -1215,6 +1456,8 @@ var Think = class Think extends Agent {
1215
1456
  ...config.tools
1216
1457
  } : tools;
1217
1458
  const finalTools = this._wrapToolsWithDecision(mergedTools);
1459
+ this._turnModelMessageBaseline = finalMessages.length;
1460
+ this._activeTurnTools = mergedTools;
1218
1461
  const finalMaxSteps = config.maxSteps ?? this.maxSteps;
1219
1462
  const finalSendReasoning = config.sendReasoning ?? this.sendReasoning;
1220
1463
  this._activeStallTimeoutMs = config.chatStreamStallTimeoutMs ?? this.chatStreamStallTimeoutMs;
@@ -1244,8 +1487,15 @@ var Think = class Think extends Agent {
1244
1487
  output: finalOutput,
1245
1488
  abortSignal: input.signal,
1246
1489
  prepareStep: (async (event) => {
1490
+ const guarded = await this._maybeProactiveContextCompact(event);
1247
1491
  const result = await this.beforeStep(event);
1248
- 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;
1249
1499
  }),
1250
1500
  onChunk: async (event) => {
1251
1501
  await this.onChunk(event);
@@ -1570,32 +1820,45 @@ var Think = class Think extends Agent {
1570
1820
  await this._appendMessageToHistory(userMsg);
1571
1821
  this._broadcastMessages();
1572
1822
  const chatBody = async () => {
1573
- let result;
1574
- try {
1575
- result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
1576
- agent: this,
1577
- connection: void 0,
1578
- request: void 0,
1579
- email: void 0
1580
- }, () => this._runInferenceLoop({
1581
- signal: abortSignal,
1582
- continuation: false
1583
- }));
1584
- } catch (error) {
1585
- const wrapped = this.onChatError(error, {
1586
- stage: "turn",
1587
- messagesPersisted: true
1588
- });
1589
- const errorMessage = wrapped instanceof Error ? wrapped.message : String(wrapped);
1590
- this._emit("chat:request:failed", {
1591
- stage: "turn",
1592
- messagesPersisted: true,
1593
- error: errorMessage
1594
- });
1595
- 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
+ }
1596
1860
  return;
1597
1861
  }
1598
- await this._streamResultToRpcCallback(requestId, result, callback, abortSignal);
1599
1862
  };
1600
1863
  if (this.chatRecovery) await this._runChatRecoveryFiber(requestId, false, chatBody);
1601
1864
  else await chatBody();
@@ -1755,6 +2018,7 @@ var Think = class Think extends Agent {
1755
2018
  const row = this._readAgentToolChildRun(runId);
1756
2019
  if (!row || row.completed_at !== null) return;
1757
2020
  this._agentToolAbortControllers.get(runId)?.abort(reason);
2021
+ for (const controller of this._submissionAbortControllers.values()) controller.abort(reason);
1758
2022
  this.sql`
1759
2023
  UPDATE cf_agent_tool_child_runs
1760
2024
  SET status = 'aborted',
@@ -1763,6 +2027,7 @@ var Think = class Think extends Agent {
1763
2027
  WHERE run_id = ${runId}
1764
2028
  AND status NOT IN ('completed', 'error', 'aborted')
1765
2029
  `;
2030
+ this._finalizeAgentToolChildRunTailers(runId);
1766
2031
  }
1767
2032
  /**
1768
2033
  * Classify any in-flight chat-recovery on this child facet (#1630). A child
@@ -1837,6 +2102,38 @@ var Think = class Think extends Agent {
1837
2102
  this._agentToolLastErrors.delete(runId);
1838
2103
  this._agentToolPreTurnAssistantIds.delete(runId);
1839
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
+ }
1840
2137
  async getAgentToolChunks(runId, options) {
1841
2138
  const row = this._readAgentToolChildRun(runId);
1842
2139
  if (!row?.stream_id) return [];
@@ -2996,26 +3293,46 @@ var Think = class Think extends Agent {
2996
3293
  const detachExternal = this._aborts.linkExternal(requestId, options?.signal);
2997
3294
  try {
2998
3295
  const programmaticBody = async () => {
2999
- const result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
3000
- agent: this,
3001
- connection: void 0,
3002
- request: void 0,
3003
- email: void 0
3004
- }, () => this._runInferenceLoop({
3005
- signal: abortSignal,
3006
- clientTools,
3007
- body,
3008
- workflowPrompt: options?.workflowPrompt,
3009
- continuation: false
3010
- }));
3011
- 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;
3012
3316
  const streamResult = await this._streamResult(requestId, result, abortSignal, {
3013
3317
  captureProgrammaticStreamError: options?.captureProgrammaticStreamError,
3014
- captureOutput: options?.captureOutput
3318
+ captureOutput: options?.captureOutput,
3319
+ overflowRecovery
3015
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
+ }
3016
3332
  status = streamResult.status;
3017
3333
  error = streamResult.error;
3018
3334
  output = streamResult.output;
3335
+ return;
3019
3336
  }
3020
3337
  };
3021
3338
  if (this.chatRecovery) await this._runChatRecoveryFiber(requestId, false, programmaticBody);
@@ -3349,24 +3666,55 @@ var Think = class Think extends Agent {
3349
3666
  }
3350
3667
  }
3351
3668
  const chatTurnBody = async () => {
3352
- const result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
3353
- agent: this,
3354
- connection,
3355
- request: void 0,
3356
- email: void 0
3357
- }, () => this._runInferenceLoop({
3358
- signal: abortSignal,
3359
- clientTools: clientToolsForTurn,
3360
- body: bodyForTurn,
3361
- continuation: false
3362
- }));
3363
- if (result) await this._streamResult(requestId, result, abortSignal, { parentId: branchParentId });
3364
- else this._broadcastChat({
3365
- type: MSG_CHAT_RESPONSE,
3366
- id: requestId,
3367
- body: "No response was generated.",
3368
- done: true
3369
- });
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
+ }
3370
3718
  };
3371
3719
  if (this.chatRecovery) await this._runChatRecoveryFiber(requestId, false, chatTurnBody);
3372
3720
  else await chatTurnBody();
@@ -3490,7 +3838,7 @@ var Think = class Think extends Agent {
3490
3838
  await this._clearHistory();
3491
3839
  this._broadcast({ type: MSG_CHAT_CLEAR }, connection ? [connection.id] : void 0);
3492
3840
  }
3493
- async _streamResultToRpcCallback(requestId, result, callback, abortSignal) {
3841
+ async _streamResultToRpcCallback(requestId, result, callback, abortSignal, options) {
3494
3842
  const streamId = this._resumableStream.start(requestId);
3495
3843
  const accumulator = new StreamAccumulator({ messageId: crypto.randomUUID() });
3496
3844
  this._streamingAssistant = accumulator;
@@ -3501,6 +3849,7 @@ var Think = class Think extends Agent {
3501
3849
  let streamError;
3502
3850
  let pendingRpcError;
3503
3851
  let skipFinalizeRearm = false;
3852
+ let overflowRetry = false;
3504
3853
  const stallTimeoutMs = this._activeStallTimeoutMs ?? this.chatStreamStallTimeoutMs;
3505
3854
  try {
3506
3855
  this._insideInferenceLoop = true;
@@ -3525,6 +3874,10 @@ var Think = class Think extends Agent {
3525
3874
  const { action } = accumulator.applyChunk(streamChunk);
3526
3875
  if (action?.type === "error") {
3527
3876
  streamError = action.error;
3877
+ if (options?.overflowRecovery && this._isRecoverableContextOverflow(streamError, requestId)) {
3878
+ overflowRetry = true;
3879
+ break;
3880
+ }
3528
3881
  this._emit("message:error", { error: streamError });
3529
3882
  this._emit("chat:request:failed", {
3530
3883
  requestId,
@@ -3554,6 +3907,14 @@ var Think = class Think extends Agent {
3554
3907
  } finally {
3555
3908
  this._insideInferenceLoop = false;
3556
3909
  }
3910
+ if (overflowRetry) {
3911
+ this._resumableStream.complete(streamId);
3912
+ streamFinalized = true;
3913
+ return {
3914
+ status: "overflow_retry",
3915
+ error: streamError
3916
+ };
3917
+ }
3557
3918
  if (streamError) this._resumableStream.markError(streamId);
3558
3919
  else this._resumableStream.complete(streamId);
3559
3920
  streamFinalized = true;
@@ -3621,7 +3982,7 @@ var Think = class Think extends Agent {
3621
3982
  }
3622
3983
  skipFinalizeRearm = true;
3623
3984
  await callback.onInterrupted?.();
3624
- return;
3985
+ return { status: "aborted" };
3625
3986
  }
3626
3987
  if (outcome === "exhausted") {
3627
3988
  if (!streamFinalized) {
@@ -3631,7 +3992,7 @@ var Think = class Think extends Agent {
3631
3992
  doneSent = true;
3632
3993
  skipFinalizeRearm = true;
3633
3994
  await callback.onInterrupted?.();
3634
- return;
3995
+ return { status: "aborted" };
3635
3996
  }
3636
3997
  }
3637
3998
  if (!streamFinalized) {
@@ -3679,6 +4040,7 @@ var Think = class Think extends Agent {
3679
4040
  else this._onStreamingTurnFinalized();
3680
4041
  }
3681
4042
  if (pendingRpcError) await callback.onError(pendingRpcError);
4043
+ return { status: streamError || pendingRpcError ? "error" : aborted ? "aborted" : "completed" };
3682
4044
  }
3683
4045
  /**
3684
4046
  * Whether storing this chunk should immediately flush the resumable-stream
@@ -3773,6 +4135,7 @@ var Think = class Think extends Agent {
3773
4135
  let streamAborted = false;
3774
4136
  let streamError;
3775
4137
  let output;
4138
+ let overflowRetry = false;
3776
4139
  const flushState = {
3777
4140
  chunksSinceFlush: 0,
3778
4141
  hasFlushedContent: false
@@ -3798,6 +4161,10 @@ var Think = class Think extends Agent {
3798
4161
  if (action?.type === "cross-message-tool-update") await this._applyToolUpdateToMessages(crossMessageToolResultUpdate(action.toolCallId, action.updateType, action.output, action.errorText, action.preliminary));
3799
4162
  if (action?.type === "error") {
3800
4163
  streamError = action.error;
4164
+ if (options?.overflowRecovery && this._isRecoverableContextOverflow(streamError, requestId)) {
4165
+ overflowRetry = true;
4166
+ break;
4167
+ }
3801
4168
  if (options?.captureProgrammaticStreamError) this._programmaticStreamErrors.set(requestId, streamError);
3802
4169
  this._emit("message:error", { error: streamError });
3803
4170
  this._emit("chat:request:failed", {
@@ -3829,6 +4196,14 @@ var Think = class Think extends Agent {
3829
4196
  } finally {
3830
4197
  this._insideInferenceLoop = false;
3831
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
+ }
3832
4207
  if (streamError) this._resumableStream.markError(streamId);
3833
4208
  else this._resumableStream.complete(streamId);
3834
4209
  this._pendingResumeConnections.clear();
@@ -4137,6 +4512,9 @@ var Think = class Think extends Agent {
4137
4512
  maxAttempts: Math.max(1, Math.floor(custom?.maxAttempts ?? DEFAULT_CHAT_RECOVERY_MAX_ATTEMPTS)),
4138
4513
  stableTimeoutMs: Math.max(0, Math.floor(custom?.stableTimeoutMs ?? DEFAULT_CHAT_RECOVERY_STABLE_TIMEOUT_MS)),
4139
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 } : {},
4140
4518
  ...custom?.onExhausted ? { onExhausted: custom.onExhausted } : {}
4141
4519
  };
4142
4520
  }
@@ -4198,15 +4576,35 @@ var Think = class Think extends Agent {
4198
4576
  const now = input.nowMs ?? Date.now();
4199
4577
  await this._sweepStaleChatRecoveryIncidents(now);
4200
4578
  const existing = await this.ctx.storage.get(key);
4579
+ if (this._lastClientTools === void 0) this._restoreClientTools();
4201
4580
  const prevProgress = existing?.progress ?? 0;
4202
4581
  const currentProgress = await this._chatRecoveryProgressMarker();
4203
4582
  const madeProgress = existing != null && currentProgress > prevProgress;
4204
- const lastProgressAt = madeProgress ? now : existing?.lastProgressAt ?? existing?.firstSeenAt ?? now;
4205
- const noProgressExceeded = existing != null && now - lastProgressAt > CHAT_RECOVERY_NO_PROGRESS_WINDOW_MS;
4206
- 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;
4207
4590
  const debounced = existing != null && !madeProgress && now - existing.lastAttemptAt < CHAT_RECOVERY_ALARM_DEBOUNCE_MS;
4208
4591
  const attempt = madeProgress ? 1 : debounced ? existing?.attempt ?? 1 : (existing?.attempt ?? 0) + 1;
4209
- 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);
4210
4608
  const incident = {
4211
4609
  incidentId,
4212
4610
  requestId: input.requestId,
@@ -4218,8 +4616,9 @@ var Think = class Think extends Agent {
4218
4616
  firstSeenAt: existing?.firstSeenAt ?? now,
4219
4617
  lastAttemptAt: now,
4220
4618
  lastProgressAt,
4221
- progress: Math.max(prevProgress, currentProgress),
4222
- ...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" } : {}
4223
4622
  };
4224
4623
  await this.ctx.storage.put(key, incident);
4225
4624
  if (!existing) this._emit("chat:recovery:detected", {
@@ -4546,6 +4945,50 @@ var Think = class Think extends Agent {
4546
4945
  return true;
4547
4946
  }
4548
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
+ /**
4549
4992
  * Resolve the stream id for a recovery turn so the give-up terminalization
4550
4993
  * can surface whatever partial the turn produced. Prefers the durable stream
4551
4994
  * row keyed by the recovery-root request id; falls back to the live active
@@ -4707,6 +5150,7 @@ var Think = class Think extends Agent {
4707
5150
  try {
4708
5151
  const recoveryConfig = this._resolveChatRecoveryConfig();
4709
5152
  if (!await this.waitUntilStable({ timeout: recoveryConfig.stableTimeoutMs })) {
5153
+ if (await this._parkRecoveryForPendingInteraction(data)) return;
4710
5154
  if (await this._rescheduleRecoveryAfterStableTimeout("_chatRecoveryRetry", data, recoveryConfig.maxAttempts)) return;
4711
5155
  await this._exhaustRecoveryAfterStableTimeout("_chatRecoveryRetry", data);
4712
5156
  return;
@@ -4731,6 +5175,7 @@ var Think = class Think extends Agent {
4731
5175
  } finally {
4732
5176
  this._activeChatRecoveryRootRequestId = previousRootRequestId;
4733
5177
  if (recoveredSubmission) this._submissionAbortControllers.delete(recoveredSubmission.submission_id);
5178
+ await this._reconcileOwnStaleAgentToolChildRuns();
4734
5179
  }
4735
5180
  }
4736
5181
  _hasRunningSubmission(requestId) {
@@ -4812,6 +5257,7 @@ var Think = class Think extends Agent {
4812
5257
  try {
4813
5258
  const recoveryConfig = this._resolveChatRecoveryConfig();
4814
5259
  if (!await this.waitUntilStable({ timeout: recoveryConfig.stableTimeoutMs })) {
5260
+ if (await this._parkRecoveryForPendingInteraction(data)) return;
4815
5261
  console.warn("[Think] _chatRecoveryContinue timed out waiting for stable state");
4816
5262
  if (await this._rescheduleRecoveryAfterStableTimeout("_chatRecoveryContinue", data, recoveryConfig.maxAttempts)) return;
4817
5263
  await this._exhaustRecoveryAfterStableTimeout("_chatRecoveryContinue", data);
@@ -4834,6 +5280,7 @@ var Think = class Think extends Agent {
4834
5280
  } finally {
4835
5281
  this._activeChatRecoveryRootRequestId = previousRootRequestId;
4836
5282
  if (recoveredSubmission) this._submissionAbortControllers.delete(recoveredSubmission.submission_id);
5283
+ await this._reconcileOwnStaleAgentToolChildRuns();
4837
5284
  }
4838
5285
  }
4839
5286
  _applyRecoveredRequestContext(data) {
@@ -5138,7 +5585,7 @@ var Think = class Think extends Agent {
5138
5585
  */
5139
5586
  async _setChatRecovering(active, requestId) {
5140
5587
  const existing = await this.ctx.storage.get(CHAT_RECOVERING_KEY);
5141
- 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;
5142
5589
  if (active) {
5143
5590
  if (activeExisting) return;
5144
5591
  await this.ctx.storage.put(CHAT_RECOVERING_KEY, {
@@ -5176,7 +5623,7 @@ var Think = class Think extends Agent {
5176
5623
  error: true
5177
5624
  });
5178
5625
  const recovering = await this.ctx.storage.get(CHAT_RECOVERING_KEY);
5179
- 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({
5180
5627
  type: MSG_CHAT_RECOVERING,
5181
5628
  recovering: true,
5182
5629
  ...recovering.requestId ? { id: recovering.requestId } : {}
@@ -5227,6 +5674,6 @@ Think.CHAT_FIBER_NAME = "__cf_internal_chat_turn";
5227
5674
  Think.MESSAGE_DEBOUNCE_MS = 750;
5228
5675
  Think.submissionRecoveryStaleMs = 900 * 1e3;
5229
5676
  //#endregion
5230
- export { Session, Think, Workspace, defineScheduledTasks, skills };
5677
+ export { Session, Think, Workspace, defaultContextOverflowClassifier, defineScheduledTasks, skills };
5231
5678
 
5232
5679
  //# sourceMappingURL=think.js.map