@cloudflare/think 0.8.2 → 0.8.4
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/LICENSE +21 -0
- package/README.md +80 -29
- package/dist/chat-sdk-Bb93yaZh.js.map +1 -1
- package/dist/extensions/index.js +1 -2
- package/dist/extensions/index.js.map +1 -1
- package/dist/{index-CKAMYQXB.d.ts → index-By2rkaOh.d.ts} +381 -56
- package/dist/{manager-DnCkoyVo.js → manager-EBL4uMVp.js} +28 -19
- package/dist/{manager-DnCkoyVo.js.map → manager-EBL4uMVp.js.map} +1 -1
- package/dist/messengers/index.d.ts +1 -1
- package/dist/messengers/telegram.d.ts +1 -1
- package/dist/messengers/telegram.js.map +1 -1
- package/dist/think.d.ts +64 -56
- package/dist/think.js +544 -99
- package/dist/think.js.map +1 -1
- package/dist/tools/browser.js.map +1 -1
- package/dist/tools/extensions.js +1 -1
- package/dist/tools/extensions.js.map +1 -1
- package/dist/tools/workspace.js.map +1 -1
- package/dist/workflows.d.ts +2 -1
- package/dist/workflows.js +30 -12
- package/dist/workflows.js.map +1 -1
- package/package.json +3 -3
- package/dist/classPrivateFieldGet2-D_obpP6O.js +0 -27
package/dist/think.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { i as
|
|
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";
|
|
5
5
|
import * as skills from "agents/skills";
|
|
6
6
|
import { SkillRegistry } from "agents/skills";
|
|
7
7
|
import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext } from "agents";
|
|
8
|
-
import { AbortRegistry, CHAT_MESSAGE_TYPES, ContinuationState, ResumableStream, StreamAccumulator, SubmitConcurrencyController, TurnQueue, applyChunkToParts, applyToolUpdate, createChatFiberSnapshot, createToolsFromClientSchemas, crossMessageToolResultUpdate, enforceRowSizeLimit, normalizeToolInput, parseProtocolMessage, reconcileMessages, resolveToolMergeId, sanitizeMessage, toolApprovalUpdate, toolResultUpdate, unwrapChatFiberSnapshot, wrapChatFiberSnapshot } from "agents/chat";
|
|
8
|
+
import { AbortRegistry, CHAT_MESSAGE_TYPES, ContinuationState, MAX_BOUND_PARAMS, ResumableStream, StreamAccumulator, SubmitConcurrencyController, TurnQueue, applyChunkToParts, applyToolUpdate, buildInClauseStrings, createChatFiberSnapshot, createToolsFromClientSchemas, crossMessageToolResultUpdate, enforceRowSizeLimit, normalizeToolInput, parseProtocolMessage, reconcileMessages, resolveToolMergeId, sanitizeMessage, toolApprovalUpdate, toolResultUpdate, unwrapChatFiberSnapshot, wrapChatFiberSnapshot } from "agents/chat";
|
|
9
9
|
import { Session, Session as Session$1 } from "agents/experimental/memory/session";
|
|
10
10
|
import { truncateOlderMessages } from "agents/experimental/memory/utils";
|
|
11
11
|
import { Workspace, Workspace as Workspace$1 } from "@cloudflare/shell";
|
|
@@ -291,13 +291,15 @@ 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
|
|
299
|
+
const KV_DELETE_MAX_KEYS = 128;
|
|
300
|
+
const DEFAULT_CHAT_RECOVERY_NO_PROGRESS_TIMEOUT_MS = 300 * 1e3;
|
|
299
301
|
const CHAT_RECOVERY_ALARM_DEBOUNCE_MS = 30 * 1e3;
|
|
300
|
-
const
|
|
302
|
+
const CHAT_RECOVERING_FLAG_TTL_MS = 900 * 1e3;
|
|
301
303
|
const AGENT_TOOL_STREAM_PROGRESS_BUMP_THROTTLE_MS = 5e3;
|
|
302
304
|
const CONTINUE_CHECKPOINT_PROMPT = "Continue your previous response from exactly where it left off. Do not repeat any of it.";
|
|
303
305
|
/**
|
|
@@ -325,6 +327,61 @@ function defineScheduledTasks(tasks) {
|
|
|
325
327
|
return tasks;
|
|
326
328
|
}
|
|
327
329
|
const THINK_WORKFLOW_PROMPT_METADATA_KEY = "__thinkWorkflowPrompt";
|
|
330
|
+
/**
|
|
331
|
+
* Matches the context-window-overflow error messages of the common providers.
|
|
332
|
+
* Anthropic (`prompt is too long`), OpenAI (`context_length_exceeded`,
|
|
333
|
+
* `maximum context length`, `reduce the length of …`), Google Gemini (`exceeds
|
|
334
|
+
* the maximum number of tokens`, `input token count`), Bedrock / Mistral /
|
|
335
|
+
* others (`input is too long`, `too many tokens`, `context window`).
|
|
336
|
+
*
|
|
337
|
+
* This default deliberately favors recall over precision: a missed overflow
|
|
338
|
+
* means no recovery (the feature's whole point), whereas a false positive
|
|
339
|
+
* self-heals — the retry hits the same non-overflow error, the budget is spent,
|
|
340
|
+
* and it surfaces terminally anyway. The vaguest fragment (`reduce the length`)
|
|
341
|
+
* is anchored to `of` to match the real OpenAI phrasing without matching
|
|
342
|
+
* unrelated prose. Apps that need stricter matching can wrap this classifier.
|
|
343
|
+
*/
|
|
344
|
+
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;
|
|
345
|
+
/**
|
|
346
|
+
* Opt-in default classifier for {@link Think.classifyChatError}. Matches the
|
|
347
|
+
* context-window-overflow error messages of the common providers (Anthropic,
|
|
348
|
+
* OpenAI, Google, Bedrock, Mistral, …) and returns `"context_overflow"`.
|
|
349
|
+
*
|
|
350
|
+
* Think ships this as an explicitly-imported helper rather than wiring it into
|
|
351
|
+
* core, so the framework default stays free of provider strings. Assign it (or
|
|
352
|
+
* delegate to it) when you do not need custom classification:
|
|
353
|
+
*
|
|
354
|
+
* @example
|
|
355
|
+
* ```typescript
|
|
356
|
+
* import { Think, defaultContextOverflowClassifier } from "@cloudflare/think";
|
|
357
|
+
*
|
|
358
|
+
* export class MyAgent extends Think<Env> {
|
|
359
|
+
* override contextOverflow = { reactive: true };
|
|
360
|
+
* override classifyChatError = defaultContextOverflowClassifier;
|
|
361
|
+
* }
|
|
362
|
+
* ```
|
|
363
|
+
*
|
|
364
|
+
* Or combine with your own checks:
|
|
365
|
+
*
|
|
366
|
+
* @example
|
|
367
|
+
* ```typescript
|
|
368
|
+
* override classifyChatError(error: unknown): ChatErrorClassification | void {
|
|
369
|
+
* if (isMyRateLimit(error)) return "rate_limit";
|
|
370
|
+
* return defaultContextOverflowClassifier(error);
|
|
371
|
+
* }
|
|
372
|
+
* ```
|
|
373
|
+
*/
|
|
374
|
+
function defaultContextOverflowClassifier(error) {
|
|
375
|
+
let text;
|
|
376
|
+
if (error instanceof Error) text = error.message;
|
|
377
|
+
else if (typeof error === "string") text = error;
|
|
378
|
+
else try {
|
|
379
|
+
text = JSON.stringify(error);
|
|
380
|
+
} catch {
|
|
381
|
+
text = String(error);
|
|
382
|
+
}
|
|
383
|
+
return CONTEXT_OVERFLOW_PATTERN.test(text) ? "context_overflow" : void 0;
|
|
384
|
+
}
|
|
328
385
|
const TIMED_OUT = Symbol("timed-out");
|
|
329
386
|
var _configCache = /* @__PURE__ */ new WeakMap();
|
|
330
387
|
var _configTableReady = /* @__PURE__ */ new WeakMap();
|
|
@@ -373,6 +430,10 @@ var Think = class Think extends Agent {
|
|
|
373
430
|
this.maxSteps = 10;
|
|
374
431
|
this.sendReasoning = true;
|
|
375
432
|
this.chatStreamStallTimeoutMs = 0;
|
|
433
|
+
this._turnModelMessageBaseline = 0;
|
|
434
|
+
this._activeTurnTools = {};
|
|
435
|
+
this._proactiveCompactionsThisRun = 0;
|
|
436
|
+
this._warnedMissingClassifier = false;
|
|
376
437
|
this.hookTimeout = 5e3;
|
|
377
438
|
this._lastAgentToolStreamProgressAt = 0;
|
|
378
439
|
const _onStart = this.onStart.bind(this);
|
|
@@ -860,6 +921,22 @@ var Think = class Think extends Agent {
|
|
|
860
921
|
lines.push("- Do not claim access to capabilities that are not exposed as tools in this turn.");
|
|
861
922
|
return lines.join("\n");
|
|
862
923
|
}
|
|
924
|
+
/** Whether the reactive compact-and-retry backstop is enabled. */
|
|
925
|
+
get _overflowReactiveEnabled() {
|
|
926
|
+
return this.contextOverflow?.reactive === true;
|
|
927
|
+
}
|
|
928
|
+
/** Reactive compact-and-retry budget. */
|
|
929
|
+
get _overflowMaxRetries() {
|
|
930
|
+
return this.contextOverflow?.maxRetries ?? 1;
|
|
931
|
+
}
|
|
932
|
+
/** Proactive guard config, when enabled. */
|
|
933
|
+
get _overflowGuard() {
|
|
934
|
+
return this.contextOverflow?.proactive;
|
|
935
|
+
}
|
|
936
|
+
/** Per-run cap on proactive compactions (independent of the reactive budget). */
|
|
937
|
+
get _overflowProactiveMaxCompactions() {
|
|
938
|
+
return Math.max(1, this.contextOverflow?.proactive?.maxCompactions ?? 1);
|
|
939
|
+
}
|
|
863
940
|
/**
|
|
864
941
|
* Configure the session. Called once during `onStart`.
|
|
865
942
|
* Override to add context blocks, compaction, search, skills.
|
|
@@ -1110,9 +1187,123 @@ var Think = class Think extends Agent {
|
|
|
1110
1187
|
onChatError(error, _ctx) {
|
|
1111
1188
|
return error;
|
|
1112
1189
|
}
|
|
1190
|
+
/**
|
|
1191
|
+
* Classify a raw chat-turn error into a provider-agnostic category.
|
|
1192
|
+
*
|
|
1193
|
+
* Think deliberately ships **no** provider-specific matching: it cannot know
|
|
1194
|
+
* that Anthropic's `"prompt is too long"` or OpenAI's
|
|
1195
|
+
* `context_length_exceeded` means "context overflow" without baking provider
|
|
1196
|
+
* knowledge into core. The app does know its provider/model, so it owns the
|
|
1197
|
+
* mapping — the same split Think already uses for `tokenCounter`.
|
|
1198
|
+
*
|
|
1199
|
+
* Currently this hook drives **only** context-overflow recovery: it is
|
|
1200
|
+
* consulted when a turn errors **and** `contextOverflow.reactive` is enabled
|
|
1201
|
+
* (if reactive is off, it is not called). Return `"context_overflow"` to run
|
|
1202
|
+
* the compact-and-retry backstop; if recovery cannot save the turn, that
|
|
1203
|
+
* classification is surfaced on the terminal `onChatError` call via
|
|
1204
|
+
* {@link ChatErrorContext.classification}. The other categories are reserved
|
|
1205
|
+
* for future use — returning one today is a no-op (the turn terminalizes as
|
|
1206
|
+
* usual) and it is **not** forwarded to `onChatError`. Returning
|
|
1207
|
+
* `void`/`"unknown"` keeps the existing terminal behavior.
|
|
1208
|
+
*
|
|
1209
|
+
* The argument may be an `Error`, an AI SDK `APICallError` (with
|
|
1210
|
+
* `statusCode`/`responseBody`), or — for in-stream provider errors that
|
|
1211
|
+
* surface as a stream error part rather than a throw — the error message
|
|
1212
|
+
* string. Narrow accordingly.
|
|
1213
|
+
*
|
|
1214
|
+
* The second argument carries a {@link ChatErrorContext}: when consulted for
|
|
1215
|
+
* overflow recovery it is `{ stage: "stream", requestId }`, so a classifier
|
|
1216
|
+
* can correlate the error with the in-flight turn (e.g. to call
|
|
1217
|
+
* {@link cancelChat}).
|
|
1218
|
+
*
|
|
1219
|
+
* @example Anthropic + OpenAI context-overflow
|
|
1220
|
+
* ```typescript
|
|
1221
|
+
* classifyChatError(error: unknown): ChatErrorClassification | void {
|
|
1222
|
+
* const text = error instanceof Error ? error.message : String(error);
|
|
1223
|
+
* if (/prompt is too long|context length|context_length_exceeded|maximum context/i.test(text)) {
|
|
1224
|
+
* return "context_overflow";
|
|
1225
|
+
* }
|
|
1226
|
+
* }
|
|
1227
|
+
* ```
|
|
1228
|
+
*/
|
|
1229
|
+
classifyChatError(_error, _ctx) {}
|
|
1230
|
+
/**
|
|
1231
|
+
* Whether an error (thrown or surfaced as an in-stream error string) should
|
|
1232
|
+
* trigger the opt-in compact-and-retry backstop. Consults the app's
|
|
1233
|
+
* `classifyChatError` and the `contextOverflow.reactive` flag. Centralized
|
|
1234
|
+
* so both stream consumers (WebSocket + RPC) classify identically.
|
|
1235
|
+
*/
|
|
1236
|
+
_isRecoverableContextOverflow(error, requestId) {
|
|
1237
|
+
if (!this._overflowReactiveEnabled) return false;
|
|
1238
|
+
if (this.classifyChatError === Think.prototype.classifyChatError) {
|
|
1239
|
+
if (!this._warnedMissingClassifier) {
|
|
1240
|
+
this._warnedMissingClassifier = true;
|
|
1241
|
+
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).");
|
|
1242
|
+
}
|
|
1243
|
+
return false;
|
|
1244
|
+
}
|
|
1245
|
+
let classification;
|
|
1246
|
+
try {
|
|
1247
|
+
classification = this.classifyChatError(error, {
|
|
1248
|
+
stage: "stream",
|
|
1249
|
+
requestId
|
|
1250
|
+
});
|
|
1251
|
+
} catch (err) {
|
|
1252
|
+
console.warn(`[Think] classifyChatError threw; treating as non-overflow: ${err instanceof Error ? err.message : String(err)}`);
|
|
1253
|
+
return false;
|
|
1254
|
+
}
|
|
1255
|
+
return classification === "context_overflow";
|
|
1256
|
+
}
|
|
1257
|
+
/**
|
|
1258
|
+
* Compact the session in response to a context overflow (reactive backstop or
|
|
1259
|
+
* proactive guard). Returns whether history was actually shortened — a no-op
|
|
1260
|
+
* compaction (returns `null`) means a retry would just overflow again, so the
|
|
1261
|
+
* caller should fall through to the terminal error rather than loop.
|
|
1262
|
+
*
|
|
1263
|
+
* This is the single emit point for `chat:context:compacted`, so callers must
|
|
1264
|
+
* NOT emit it again.
|
|
1265
|
+
*/
|
|
1266
|
+
async _compactForContextOverflow(reason, extra) {
|
|
1267
|
+
try {
|
|
1268
|
+
const result = await this.session.compact();
|
|
1269
|
+
const shortened = Boolean(result);
|
|
1270
|
+
this._emit("chat:context:compacted", {
|
|
1271
|
+
reason,
|
|
1272
|
+
shortened,
|
|
1273
|
+
...extra
|
|
1274
|
+
});
|
|
1275
|
+
return shortened;
|
|
1276
|
+
} catch (err) {
|
|
1277
|
+
console.warn(`[Think] context-overflow compaction failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
1278
|
+
return false;
|
|
1279
|
+
}
|
|
1280
|
+
}
|
|
1281
|
+
/**
|
|
1282
|
+
* Finalize a context overflow that recovery could not fix (compaction was a
|
|
1283
|
+
* no-op, or the retry budget is spent). Routes the error through
|
|
1284
|
+
* `onChatError` with `classification: "context_overflow"` and emits
|
|
1285
|
+
* `chat:request:failed`, so every overflow terminal — whichever path it took
|
|
1286
|
+
* — is reported identically. Returns the (possibly app-reshaped) message for
|
|
1287
|
+
* the caller to deliver via its own transport (RPC callback / WS broadcast).
|
|
1288
|
+
*/
|
|
1289
|
+
_finalizeContextOverflowError(requestId, rawError) {
|
|
1290
|
+
const raw = rawError ?? "Context window exceeded.";
|
|
1291
|
+
const wrapped = this.onChatError(raw, {
|
|
1292
|
+
requestId,
|
|
1293
|
+
stage: "stream",
|
|
1294
|
+
messagesPersisted: true,
|
|
1295
|
+
classification: "context_overflow"
|
|
1296
|
+
});
|
|
1297
|
+
const message = wrapped instanceof Error ? wrapped.message : String(wrapped);
|
|
1298
|
+
this._emit("chat:request:failed", {
|
|
1299
|
+
requestId,
|
|
1300
|
+
stage: "stream",
|
|
1301
|
+
messagesPersisted: true,
|
|
1302
|
+
error: message
|
|
1303
|
+
});
|
|
1304
|
+
return message;
|
|
1305
|
+
}
|
|
1113
1306
|
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
1307
|
const agentClassName = this.constructor.name;
|
|
1117
1308
|
const agentId = this.ctx.id.toString();
|
|
1118
1309
|
const ctxExports = this.ctx.exports;
|
|
@@ -1148,12 +1339,76 @@ var Think = class Think extends Agent {
|
|
|
1148
1339
|
});
|
|
1149
1340
|
}
|
|
1150
1341
|
/**
|
|
1342
|
+
* Assemble provider-ready model messages from the current session history:
|
|
1343
|
+
* repair the transcript, truncate older messages, drop any still-incomplete
|
|
1344
|
+
* tool calls, and convert to `ModelMessage[]`. Shared by the turn entry point
|
|
1345
|
+
* and the proactive context guard so a mid-turn recompaction rebuilds the
|
|
1346
|
+
* head through the exact same pipeline.
|
|
1347
|
+
*/
|
|
1348
|
+
async _assembleModelMessages(tools) {
|
|
1349
|
+
const truncated = truncateOlderMessages(await this._repairTranscriptForProvider(this.messages));
|
|
1350
|
+
const incompleteAfterRepair = this._incompleteToolCallIds(truncated);
|
|
1351
|
+
if (incompleteAfterRepair.length > 0) {
|
|
1352
|
+
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.`);
|
|
1353
|
+
this._emit("chat:transcript:repaired", {
|
|
1354
|
+
removedToolCalls: incompleteAfterRepair.length,
|
|
1355
|
+
normalizedInputs: 0,
|
|
1356
|
+
toolCallIds: incompleteAfterRepair
|
|
1357
|
+
});
|
|
1358
|
+
}
|
|
1359
|
+
return convertToModelMessages(truncated, {
|
|
1360
|
+
tools,
|
|
1361
|
+
ignoreIncompleteToolCalls: true
|
|
1362
|
+
});
|
|
1363
|
+
}
|
|
1364
|
+
/**
|
|
1365
|
+
* Proactive context guard (Layer 1). Runs before each step from the
|
|
1366
|
+
* `prepareStep` wrapper. If `contextOverflow.proactive` is set and the *previous*
|
|
1367
|
+
* step's model-reported input tokens cross the budget, compact the session in
|
|
1368
|
+
* place and return recompacted messages for the upcoming step — heading off a
|
|
1369
|
+
* provider context-overflow 400 before it happens.
|
|
1370
|
+
*
|
|
1371
|
+
* Keys off `usage.inputTokens` (provider-agnostic; every provider reports it)
|
|
1372
|
+
* rather than any provider error string, and reuses `_assembleModelMessages`
|
|
1373
|
+
* so the recompacted head goes through the same repair/convert pipeline. The
|
|
1374
|
+
* current turn's in-flight steps (everything after `_turnModelMessageBaseline`)
|
|
1375
|
+
* are spliced back on so no completed work is lost.
|
|
1376
|
+
*
|
|
1377
|
+
* Best-effort: any failure (no-op compaction, reconciliation that would leave
|
|
1378
|
+
* an incomplete tool pair) returns `undefined` so the step proceeds unchanged
|
|
1379
|
+
* and the reactive backstop (`contextOverflow.reactive`) can still
|
|
1380
|
+
* catch a genuine overflow.
|
|
1381
|
+
*/
|
|
1382
|
+
async _maybeProactiveContextCompact(event) {
|
|
1383
|
+
const guard = this._overflowGuard;
|
|
1384
|
+
if (!guard || guard.maxInputTokens <= 0) return void 0;
|
|
1385
|
+
if (this._proactiveCompactionsThisRun >= this._overflowProactiveMaxCompactions) return void 0;
|
|
1386
|
+
const prev = event.steps?.at(-1);
|
|
1387
|
+
const used = prev?.usage?.inputTokens ?? prev?.usage?.totalTokens;
|
|
1388
|
+
if (used == null || !Number.isFinite(used)) return void 0;
|
|
1389
|
+
const headroom = guard.headroom ?? .9;
|
|
1390
|
+
if (used < guard.maxInputTokens * headroom) return void 0;
|
|
1391
|
+
try {
|
|
1392
|
+
this._proactiveCompactionsThisRun++;
|
|
1393
|
+
if (!await this._compactForContextOverflow("proactive")) return void 0;
|
|
1394
|
+
const head = await this._assembleModelMessages(this._activeTurnTools);
|
|
1395
|
+
const tail = event.messages.slice(this._turnModelMessageBaseline);
|
|
1396
|
+
const merged = [...head, ...tail];
|
|
1397
|
+
this._turnModelMessageBaseline = head.length;
|
|
1398
|
+
return merged;
|
|
1399
|
+
} catch (err) {
|
|
1400
|
+
console.warn(`[Think] proactive context compaction failed; proceeding without it: ${err instanceof Error ? err.message : String(err)}`);
|
|
1401
|
+
return;
|
|
1402
|
+
}
|
|
1403
|
+
}
|
|
1404
|
+
/**
|
|
1151
1405
|
* The single convergence point for all chat turn entry paths.
|
|
1152
1406
|
* Merges tools, assembles context, fires lifecycle hooks, wraps tools
|
|
1153
1407
|
* for interception, and calls streamText.
|
|
1154
1408
|
*/
|
|
1155
1409
|
async _runInferenceLoop(input) {
|
|
1156
1410
|
this._activeStallTimeoutMs = void 0;
|
|
1411
|
+
this._proactiveCompactionsThisRun = 0;
|
|
1157
1412
|
if (this.waitForMcpConnections) {
|
|
1158
1413
|
const timeout = typeof this.waitForMcpConnections === "object" ? this.waitForMcpConnections.timeout : 1e4;
|
|
1159
1414
|
await this.mcp.waitForConnections({ timeout });
|
|
@@ -1176,20 +1431,7 @@ var Think = class Think extends Agent {
|
|
|
1176
1431
|
};
|
|
1177
1432
|
const baseSystem = await this.session.freezeSystemPrompt() || this.getSystemPrompt();
|
|
1178
1433
|
const system = this._systemPromptForTurn(baseSystem, tools);
|
|
1179
|
-
const
|
|
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
|
-
});
|
|
1434
|
+
const messages = await this._assembleModelMessages(tools);
|
|
1193
1435
|
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
1436
|
const model = this.getModel();
|
|
1195
1437
|
const ctx = {
|
|
@@ -1215,6 +1457,8 @@ var Think = class Think extends Agent {
|
|
|
1215
1457
|
...config.tools
|
|
1216
1458
|
} : tools;
|
|
1217
1459
|
const finalTools = this._wrapToolsWithDecision(mergedTools);
|
|
1460
|
+
this._turnModelMessageBaseline = finalMessages.length;
|
|
1461
|
+
this._activeTurnTools = mergedTools;
|
|
1218
1462
|
const finalMaxSteps = config.maxSteps ?? this.maxSteps;
|
|
1219
1463
|
const finalSendReasoning = config.sendReasoning ?? this.sendReasoning;
|
|
1220
1464
|
this._activeStallTimeoutMs = config.chatStreamStallTimeoutMs ?? this.chatStreamStallTimeoutMs;
|
|
@@ -1244,8 +1488,15 @@ var Think = class Think extends Agent {
|
|
|
1244
1488
|
output: finalOutput,
|
|
1245
1489
|
abortSignal: input.signal,
|
|
1246
1490
|
prepareStep: (async (event) => {
|
|
1491
|
+
const guarded = await this._maybeProactiveContextCompact(event);
|
|
1247
1492
|
const result = await this.beforeStep(event);
|
|
1248
|
-
|
|
1493
|
+
const base = result == null ? {} : result;
|
|
1494
|
+
const baseMessages = base.messages;
|
|
1495
|
+
if (guarded && baseMessages === void 0) return {
|
|
1496
|
+
...base,
|
|
1497
|
+
messages: guarded
|
|
1498
|
+
};
|
|
1499
|
+
return base;
|
|
1249
1500
|
}),
|
|
1250
1501
|
onChunk: async (event) => {
|
|
1251
1502
|
await this.onChunk(event);
|
|
@@ -1570,32 +1821,45 @@ var Think = class Think extends Agent {
|
|
|
1570
1821
|
await this._appendMessageToHistory(userMsg);
|
|
1571
1822
|
this._broadcastMessages();
|
|
1572
1823
|
const chatBody = async () => {
|
|
1573
|
-
let
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1824
|
+
for (let attempt = 0;; attempt++) {
|
|
1825
|
+
let result;
|
|
1826
|
+
try {
|
|
1827
|
+
result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
|
|
1828
|
+
agent: this,
|
|
1829
|
+
connection: void 0,
|
|
1830
|
+
request: void 0,
|
|
1831
|
+
email: void 0
|
|
1832
|
+
}, () => this._runInferenceLoop({
|
|
1833
|
+
signal: abortSignal,
|
|
1834
|
+
continuation: false
|
|
1835
|
+
}));
|
|
1836
|
+
} catch (error) {
|
|
1837
|
+
const wrapped = this.onChatError(error, {
|
|
1838
|
+
stage: "turn",
|
|
1839
|
+
messagesPersisted: true
|
|
1840
|
+
});
|
|
1841
|
+
const errorMessage = wrapped instanceof Error ? wrapped.message : String(wrapped);
|
|
1842
|
+
this._emit("chat:request:failed", {
|
|
1843
|
+
stage: "turn",
|
|
1844
|
+
messagesPersisted: true,
|
|
1845
|
+
error: errorMessage
|
|
1846
|
+
});
|
|
1847
|
+
await callback.onError(errorMessage);
|
|
1848
|
+
return;
|
|
1849
|
+
}
|
|
1850
|
+
const { status, error } = await this._streamResultToRpcCallback(requestId, result, callback, abortSignal, { overflowRecovery: this._overflowReactiveEnabled });
|
|
1851
|
+
if (status === "overflow_retry") {
|
|
1852
|
+
if (attempt < this._overflowMaxRetries && !abortSignal?.aborted) {
|
|
1853
|
+
if (await this._compactForContextOverflow("reactive", {
|
|
1854
|
+
requestId,
|
|
1855
|
+
attempt: attempt + 1
|
|
1856
|
+
})) continue;
|
|
1857
|
+
}
|
|
1858
|
+
const message = this._finalizeContextOverflowError(requestId, error);
|
|
1859
|
+
await callback.onError(message);
|
|
1860
|
+
}
|
|
1596
1861
|
return;
|
|
1597
1862
|
}
|
|
1598
|
-
await this._streamResultToRpcCallback(requestId, result, callback, abortSignal);
|
|
1599
1863
|
};
|
|
1600
1864
|
if (this.chatRecovery) await this._runChatRecoveryFiber(requestId, false, chatBody);
|
|
1601
1865
|
else await chatBody();
|
|
@@ -1755,6 +2019,7 @@ var Think = class Think extends Agent {
|
|
|
1755
2019
|
const row = this._readAgentToolChildRun(runId);
|
|
1756
2020
|
if (!row || row.completed_at !== null) return;
|
|
1757
2021
|
this._agentToolAbortControllers.get(runId)?.abort(reason);
|
|
2022
|
+
for (const controller of this._submissionAbortControllers.values()) controller.abort(reason);
|
|
1758
2023
|
this.sql`
|
|
1759
2024
|
UPDATE cf_agent_tool_child_runs
|
|
1760
2025
|
SET status = 'aborted',
|
|
@@ -1763,6 +2028,7 @@ var Think = class Think extends Agent {
|
|
|
1763
2028
|
WHERE run_id = ${runId}
|
|
1764
2029
|
AND status NOT IN ('completed', 'error', 'aborted')
|
|
1765
2030
|
`;
|
|
2031
|
+
this._finalizeAgentToolChildRunTailers(runId);
|
|
1766
2032
|
}
|
|
1767
2033
|
/**
|
|
1768
2034
|
* Classify any in-flight chat-recovery on this child facet (#1630). A child
|
|
@@ -1837,6 +2103,38 @@ var Think = class Think extends Agent {
|
|
|
1837
2103
|
this._agentToolLastErrors.delete(runId);
|
|
1838
2104
|
this._agentToolPreTurnAssistantIds.delete(runId);
|
|
1839
2105
|
}
|
|
2106
|
+
/**
|
|
2107
|
+
* Eagerly terminalize this child facet's OWN agent-tool run row(s) once a
|
|
2108
|
+
* recovered turn has settled. A recovered turn re-runs via either
|
|
2109
|
+
* `_chatRecoveryContinue` → `continueLastTurn` or, for a pre-stream eviction,
|
|
2110
|
+
* `_chatRecoveryRetry` (a fresh user turn) — neither flows through
|
|
2111
|
+
* `startAgentToolRun`'s finalizer, so without this the run row strands
|
|
2112
|
+
* `running` and its tailers stay open until a parent inspect lazily
|
|
2113
|
+
* reconciles it — forcing a re-attached parent to wait out a full no-progress
|
|
2114
|
+
* window before collecting an already-finished result (#1630 follow-up).
|
|
2115
|
+
* Reconciling here closes the tail promptly so the parent collects the
|
|
2116
|
+
* terminal immediately. No-op on non-child facets (their
|
|
2117
|
+
* `cf_agent_tool_child_runs` table is empty) and on rows whose in-memory run
|
|
2118
|
+
* is still live (those are finalized by `startAgentToolRun`); the underlying
|
|
2119
|
+
* reconcile leaves a row `running` while its recovery is still in progress.
|
|
2120
|
+
*/
|
|
2121
|
+
async _reconcileOwnStaleAgentToolChildRuns() {
|
|
2122
|
+
let rows;
|
|
2123
|
+
try {
|
|
2124
|
+
rows = this.sql`
|
|
2125
|
+
SELECT run_id FROM cf_agent_tool_child_runs
|
|
2126
|
+
WHERE completed_at IS NULL
|
|
2127
|
+
`;
|
|
2128
|
+
} catch {
|
|
2129
|
+
return;
|
|
2130
|
+
}
|
|
2131
|
+
for (const { run_id } of rows) {
|
|
2132
|
+
if (this._agentToolAbortControllers.has(run_id)) continue;
|
|
2133
|
+
try {
|
|
2134
|
+
await this._reconcileStaleAgentToolChildRun(run_id);
|
|
2135
|
+
} catch {}
|
|
2136
|
+
}
|
|
2137
|
+
}
|
|
1840
2138
|
async getAgentToolChunks(runId, options) {
|
|
1841
2139
|
const row = this._readAgentToolChildRun(runId);
|
|
1842
2140
|
if (!row?.stream_id) return [];
|
|
@@ -2543,16 +2841,13 @@ var Think = class Think extends Agent {
|
|
|
2543
2841
|
]);
|
|
2544
2842
|
const limit = Math.min(Math.max(options?.limit ?? 100, 1), 500);
|
|
2545
2843
|
const completedBefore = options?.completedBefore?.getTime();
|
|
2546
|
-
const
|
|
2844
|
+
const idsToDelete = [...statuses].flatMap((status) => this._listTerminalSubmissionRowsForDelete(status, limit, completedBefore)).sort((a, b) => (a.completed_at ?? a.created_at) === (b.completed_at ?? b.created_at) ? a.created_at - b.created_at : (a.completed_at ?? a.created_at) - (b.completed_at ?? b.created_at)).slice(0, limit).filter((row) => this._isTerminalSubmissionStatus(row.status)).map((row) => row.submission_id);
|
|
2547
2845
|
let deleted = 0;
|
|
2548
|
-
for (
|
|
2549
|
-
|
|
2550
|
-
|
|
2551
|
-
|
|
2552
|
-
|
|
2553
|
-
AND status IN ('completed', 'aborted', 'skipped', 'error')
|
|
2554
|
-
`;
|
|
2555
|
-
deleted++;
|
|
2846
|
+
for (let i = 0; i < idsToDelete.length; i += MAX_BOUND_PARAMS) {
|
|
2847
|
+
const batch = idsToDelete.slice(i, i + MAX_BOUND_PARAMS);
|
|
2848
|
+
const strings = buildInClauseStrings("DELETE FROM cf_think_submissions WHERE status IN ('completed', 'aborted', 'skipped', 'error') AND submission_id IN ", batch.length);
|
|
2849
|
+
this.sql(strings, ...batch);
|
|
2850
|
+
deleted += batch.length;
|
|
2556
2851
|
}
|
|
2557
2852
|
return deleted;
|
|
2558
2853
|
}
|
|
@@ -2996,26 +3291,46 @@ var Think = class Think extends Agent {
|
|
|
2996
3291
|
const detachExternal = this._aborts.linkExternal(requestId, options?.signal);
|
|
2997
3292
|
try {
|
|
2998
3293
|
const programmaticBody = async () => {
|
|
2999
|
-
|
|
3000
|
-
|
|
3001
|
-
|
|
3002
|
-
|
|
3003
|
-
|
|
3004
|
-
|
|
3005
|
-
|
|
3006
|
-
|
|
3007
|
-
|
|
3008
|
-
|
|
3009
|
-
|
|
3010
|
-
|
|
3011
|
-
|
|
3294
|
+
for (let attempt = 0;; attempt++) {
|
|
3295
|
+
const result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
|
|
3296
|
+
agent: this,
|
|
3297
|
+
connection: void 0,
|
|
3298
|
+
request: void 0,
|
|
3299
|
+
email: void 0
|
|
3300
|
+
}, () => this._runInferenceLoop({
|
|
3301
|
+
signal: abortSignal,
|
|
3302
|
+
clientTools,
|
|
3303
|
+
body,
|
|
3304
|
+
workflowPrompt: options?.workflowPrompt,
|
|
3305
|
+
continuation: false
|
|
3306
|
+
}));
|
|
3307
|
+
if (!result) return;
|
|
3308
|
+
let overflowError;
|
|
3309
|
+
let overflowRequested = false;
|
|
3310
|
+
const overflowRecovery = this._overflowReactiveEnabled ? { onRetry: (err) => {
|
|
3311
|
+
overflowRequested = true;
|
|
3312
|
+
overflowError = err;
|
|
3313
|
+
} } : void 0;
|
|
3012
3314
|
const streamResult = await this._streamResult(requestId, result, abortSignal, {
|
|
3013
3315
|
captureProgrammaticStreamError: options?.captureProgrammaticStreamError,
|
|
3014
|
-
captureOutput: options?.captureOutput
|
|
3316
|
+
captureOutput: options?.captureOutput,
|
|
3317
|
+
overflowRecovery
|
|
3015
3318
|
});
|
|
3319
|
+
if (overflowRequested) {
|
|
3320
|
+
if (attempt < this._overflowMaxRetries && !abortSignal?.aborted) {
|
|
3321
|
+
if (await this._compactForContextOverflow("reactive", {
|
|
3322
|
+
requestId,
|
|
3323
|
+
attempt: attempt + 1
|
|
3324
|
+
})) continue;
|
|
3325
|
+
}
|
|
3326
|
+
error = this._finalizeContextOverflowError(requestId, overflowError);
|
|
3327
|
+
status = "error";
|
|
3328
|
+
return;
|
|
3329
|
+
}
|
|
3016
3330
|
status = streamResult.status;
|
|
3017
3331
|
error = streamResult.error;
|
|
3018
3332
|
output = streamResult.output;
|
|
3333
|
+
return;
|
|
3019
3334
|
}
|
|
3020
3335
|
};
|
|
3021
3336
|
if (this.chatRecovery) await this._runChatRecoveryFiber(requestId, false, programmaticBody);
|
|
@@ -3349,24 +3664,55 @@ var Think = class Think extends Agent {
|
|
|
3349
3664
|
}
|
|
3350
3665
|
}
|
|
3351
3666
|
const chatTurnBody = async () => {
|
|
3352
|
-
|
|
3353
|
-
|
|
3354
|
-
|
|
3355
|
-
|
|
3356
|
-
|
|
3357
|
-
|
|
3358
|
-
|
|
3359
|
-
|
|
3360
|
-
|
|
3361
|
-
|
|
3362
|
-
|
|
3363
|
-
|
|
3364
|
-
|
|
3365
|
-
|
|
3366
|
-
|
|
3367
|
-
|
|
3368
|
-
|
|
3369
|
-
|
|
3667
|
+
for (let attempt = 0;; attempt++) {
|
|
3668
|
+
const result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
|
|
3669
|
+
agent: this,
|
|
3670
|
+
connection,
|
|
3671
|
+
request: void 0,
|
|
3672
|
+
email: void 0
|
|
3673
|
+
}, () => this._runInferenceLoop({
|
|
3674
|
+
signal: abortSignal,
|
|
3675
|
+
clientTools: clientToolsForTurn,
|
|
3676
|
+
body: bodyForTurn,
|
|
3677
|
+
continuation: false
|
|
3678
|
+
}));
|
|
3679
|
+
if (!result) {
|
|
3680
|
+
this._broadcastChat({
|
|
3681
|
+
type: MSG_CHAT_RESPONSE,
|
|
3682
|
+
id: requestId,
|
|
3683
|
+
body: "No response was generated.",
|
|
3684
|
+
done: true
|
|
3685
|
+
});
|
|
3686
|
+
return;
|
|
3687
|
+
}
|
|
3688
|
+
let overflowError;
|
|
3689
|
+
let overflowRequested = false;
|
|
3690
|
+
const overflowRecovery = this._overflowReactiveEnabled ? { onRetry: (error) => {
|
|
3691
|
+
overflowRequested = true;
|
|
3692
|
+
overflowError = error;
|
|
3693
|
+
} } : void 0;
|
|
3694
|
+
await this._streamResult(requestId, result, abortSignal, {
|
|
3695
|
+
parentId: branchParentId,
|
|
3696
|
+
overflowRecovery
|
|
3697
|
+
});
|
|
3698
|
+
if (overflowRequested) {
|
|
3699
|
+
if (attempt < this._overflowMaxRetries && !abortSignal?.aborted) {
|
|
3700
|
+
if (await this._compactForContextOverflow("reactive", {
|
|
3701
|
+
requestId,
|
|
3702
|
+
attempt: attempt + 1
|
|
3703
|
+
})) continue;
|
|
3704
|
+
}
|
|
3705
|
+
const message = this._finalizeContextOverflowError(requestId, overflowError);
|
|
3706
|
+
this._broadcastChat({
|
|
3707
|
+
type: MSG_CHAT_RESPONSE,
|
|
3708
|
+
id: requestId,
|
|
3709
|
+
body: message,
|
|
3710
|
+
done: true,
|
|
3711
|
+
error: true
|
|
3712
|
+
});
|
|
3713
|
+
}
|
|
3714
|
+
return;
|
|
3715
|
+
}
|
|
3370
3716
|
};
|
|
3371
3717
|
if (this.chatRecovery) await this._runChatRecoveryFiber(requestId, false, chatTurnBody);
|
|
3372
3718
|
else await chatTurnBody();
|
|
@@ -3490,7 +3836,7 @@ var Think = class Think extends Agent {
|
|
|
3490
3836
|
await this._clearHistory();
|
|
3491
3837
|
this._broadcast({ type: MSG_CHAT_CLEAR }, connection ? [connection.id] : void 0);
|
|
3492
3838
|
}
|
|
3493
|
-
async _streamResultToRpcCallback(requestId, result, callback, abortSignal) {
|
|
3839
|
+
async _streamResultToRpcCallback(requestId, result, callback, abortSignal, options) {
|
|
3494
3840
|
const streamId = this._resumableStream.start(requestId);
|
|
3495
3841
|
const accumulator = new StreamAccumulator({ messageId: crypto.randomUUID() });
|
|
3496
3842
|
this._streamingAssistant = accumulator;
|
|
@@ -3501,6 +3847,7 @@ var Think = class Think extends Agent {
|
|
|
3501
3847
|
let streamError;
|
|
3502
3848
|
let pendingRpcError;
|
|
3503
3849
|
let skipFinalizeRearm = false;
|
|
3850
|
+
let overflowRetry = false;
|
|
3504
3851
|
const stallTimeoutMs = this._activeStallTimeoutMs ?? this.chatStreamStallTimeoutMs;
|
|
3505
3852
|
try {
|
|
3506
3853
|
this._insideInferenceLoop = true;
|
|
@@ -3525,6 +3872,10 @@ var Think = class Think extends Agent {
|
|
|
3525
3872
|
const { action } = accumulator.applyChunk(streamChunk);
|
|
3526
3873
|
if (action?.type === "error") {
|
|
3527
3874
|
streamError = action.error;
|
|
3875
|
+
if (options?.overflowRecovery && this._isRecoverableContextOverflow(streamError, requestId)) {
|
|
3876
|
+
overflowRetry = true;
|
|
3877
|
+
break;
|
|
3878
|
+
}
|
|
3528
3879
|
this._emit("message:error", { error: streamError });
|
|
3529
3880
|
this._emit("chat:request:failed", {
|
|
3530
3881
|
requestId,
|
|
@@ -3554,6 +3905,14 @@ var Think = class Think extends Agent {
|
|
|
3554
3905
|
} finally {
|
|
3555
3906
|
this._insideInferenceLoop = false;
|
|
3556
3907
|
}
|
|
3908
|
+
if (overflowRetry) {
|
|
3909
|
+
this._resumableStream.complete(streamId);
|
|
3910
|
+
streamFinalized = true;
|
|
3911
|
+
return {
|
|
3912
|
+
status: "overflow_retry",
|
|
3913
|
+
error: streamError
|
|
3914
|
+
};
|
|
3915
|
+
}
|
|
3557
3916
|
if (streamError) this._resumableStream.markError(streamId);
|
|
3558
3917
|
else this._resumableStream.complete(streamId);
|
|
3559
3918
|
streamFinalized = true;
|
|
@@ -3621,7 +3980,7 @@ var Think = class Think extends Agent {
|
|
|
3621
3980
|
}
|
|
3622
3981
|
skipFinalizeRearm = true;
|
|
3623
3982
|
await callback.onInterrupted?.();
|
|
3624
|
-
return;
|
|
3983
|
+
return { status: "aborted" };
|
|
3625
3984
|
}
|
|
3626
3985
|
if (outcome === "exhausted") {
|
|
3627
3986
|
if (!streamFinalized) {
|
|
@@ -3631,7 +3990,7 @@ var Think = class Think extends Agent {
|
|
|
3631
3990
|
doneSent = true;
|
|
3632
3991
|
skipFinalizeRearm = true;
|
|
3633
3992
|
await callback.onInterrupted?.();
|
|
3634
|
-
return;
|
|
3993
|
+
return { status: "aborted" };
|
|
3635
3994
|
}
|
|
3636
3995
|
}
|
|
3637
3996
|
if (!streamFinalized) {
|
|
@@ -3679,6 +4038,7 @@ var Think = class Think extends Agent {
|
|
|
3679
4038
|
else this._onStreamingTurnFinalized();
|
|
3680
4039
|
}
|
|
3681
4040
|
if (pendingRpcError) await callback.onError(pendingRpcError);
|
|
4041
|
+
return { status: streamError || pendingRpcError ? "error" : aborted ? "aborted" : "completed" };
|
|
3682
4042
|
}
|
|
3683
4043
|
/**
|
|
3684
4044
|
* Whether storing this chunk should immediately flush the resumable-stream
|
|
@@ -3773,6 +4133,7 @@ var Think = class Think extends Agent {
|
|
|
3773
4133
|
let streamAborted = false;
|
|
3774
4134
|
let streamError;
|
|
3775
4135
|
let output;
|
|
4136
|
+
let overflowRetry = false;
|
|
3776
4137
|
const flushState = {
|
|
3777
4138
|
chunksSinceFlush: 0,
|
|
3778
4139
|
hasFlushedContent: false
|
|
@@ -3798,6 +4159,10 @@ var Think = class Think extends Agent {
|
|
|
3798
4159
|
if (action?.type === "cross-message-tool-update") await this._applyToolUpdateToMessages(crossMessageToolResultUpdate(action.toolCallId, action.updateType, action.output, action.errorText, action.preliminary));
|
|
3799
4160
|
if (action?.type === "error") {
|
|
3800
4161
|
streamError = action.error;
|
|
4162
|
+
if (options?.overflowRecovery && this._isRecoverableContextOverflow(streamError, requestId)) {
|
|
4163
|
+
overflowRetry = true;
|
|
4164
|
+
break;
|
|
4165
|
+
}
|
|
3801
4166
|
if (options?.captureProgrammaticStreamError) this._programmaticStreamErrors.set(requestId, streamError);
|
|
3802
4167
|
this._emit("message:error", { error: streamError });
|
|
3803
4168
|
this._emit("chat:request:failed", {
|
|
@@ -3829,6 +4194,14 @@ var Think = class Think extends Agent {
|
|
|
3829
4194
|
} finally {
|
|
3830
4195
|
this._insideInferenceLoop = false;
|
|
3831
4196
|
}
|
|
4197
|
+
if (overflowRetry && options?.overflowRecovery) {
|
|
4198
|
+
this._resumableStream.complete(streamId);
|
|
4199
|
+
this._pendingResumeConnections.clear();
|
|
4200
|
+
doneSent = true;
|
|
4201
|
+
options.overflowRecovery.onRetry(streamError);
|
|
4202
|
+
this._streamingAssistant = null;
|
|
4203
|
+
return { status: "aborted" };
|
|
4204
|
+
}
|
|
3832
4205
|
if (streamError) this._resumableStream.markError(streamId);
|
|
3833
4206
|
else this._resumableStream.complete(streamId);
|
|
3834
4207
|
this._pendingResumeConnections.clear();
|
|
@@ -4137,6 +4510,9 @@ var Think = class Think extends Agent {
|
|
|
4137
4510
|
maxAttempts: Math.max(1, Math.floor(custom?.maxAttempts ?? DEFAULT_CHAT_RECOVERY_MAX_ATTEMPTS)),
|
|
4138
4511
|
stableTimeoutMs: Math.max(0, Math.floor(custom?.stableTimeoutMs ?? DEFAULT_CHAT_RECOVERY_STABLE_TIMEOUT_MS)),
|
|
4139
4512
|
terminalMessage: custom?.terminalMessage ?? DEFAULT_CHAT_RECOVERY_TERMINAL_MESSAGE,
|
|
4513
|
+
noProgressTimeoutMs: Math.max(0, Math.floor(custom?.noProgressTimeoutMs ?? DEFAULT_CHAT_RECOVERY_NO_PROGRESS_TIMEOUT_MS)),
|
|
4514
|
+
maxRecoveryWork: typeof custom?.maxRecoveryWork === "number" && custom.maxRecoveryWork >= 0 ? custom.maxRecoveryWork : DEFAULT_CHAT_RECOVERY_MAX_WORK,
|
|
4515
|
+
...custom?.shouldKeepRecovering ? { shouldKeepRecovering: custom.shouldKeepRecovering } : {},
|
|
4140
4516
|
...custom?.onExhausted ? { onExhausted: custom.onExhausted } : {}
|
|
4141
4517
|
};
|
|
4142
4518
|
}
|
|
@@ -4189,7 +4565,7 @@ var Think = class Think extends Agent {
|
|
|
4189
4565
|
const entries = await this.ctx.storage.list({ prefix: CHAT_RECOVERY_INCIDENT_KEY_PREFIX });
|
|
4190
4566
|
const staleKeys = [];
|
|
4191
4567
|
for (const [key, incident] of entries) if (now - (incident?.lastAttemptAt ?? incident?.firstSeenAt ?? 0) > CHAT_RECOVERY_INCIDENT_TTL_MS) staleKeys.push(key);
|
|
4192
|
-
for (
|
|
4568
|
+
for (let i = 0; i < staleKeys.length; i += KV_DELETE_MAX_KEYS) await this.ctx.storage.delete(staleKeys.slice(i, i + KV_DELETE_MAX_KEYS));
|
|
4193
4569
|
}
|
|
4194
4570
|
async _beginChatRecoveryIncident(input) {
|
|
4195
4571
|
const config = this._resolveChatRecoveryConfig();
|
|
@@ -4198,15 +4574,35 @@ var Think = class Think extends Agent {
|
|
|
4198
4574
|
const now = input.nowMs ?? Date.now();
|
|
4199
4575
|
await this._sweepStaleChatRecoveryIncidents(now);
|
|
4200
4576
|
const existing = await this.ctx.storage.get(key);
|
|
4577
|
+
if (this._lastClientTools === void 0) this._restoreClientTools();
|
|
4201
4578
|
const prevProgress = existing?.progress ?? 0;
|
|
4202
4579
|
const currentProgress = await this._chatRecoveryProgressMarker();
|
|
4203
4580
|
const madeProgress = existing != null && currentProgress > prevProgress;
|
|
4204
|
-
const
|
|
4205
|
-
const
|
|
4206
|
-
const
|
|
4581
|
+
const awaitingClientInteraction = this.hasPendingInteraction();
|
|
4582
|
+
const lastProgressAt = madeProgress || awaitingClientInteraction ? now : existing?.lastProgressAt ?? existing?.firstSeenAt ?? now;
|
|
4583
|
+
const noProgressExceeded = existing != null && !awaitingClientInteraction && now - lastProgressAt > config.noProgressTimeoutMs;
|
|
4584
|
+
const workBaseline = existing?.workBaseline ?? currentProgress;
|
|
4585
|
+
const progress = Math.max(prevProgress, currentProgress);
|
|
4586
|
+
const work = progress - workBaseline;
|
|
4587
|
+
const workBudgetExceeded = existing != null && Number.isFinite(config.maxRecoveryWork) && work > config.maxRecoveryWork;
|
|
4207
4588
|
const debounced = existing != null && !madeProgress && now - existing.lastAttemptAt < CHAT_RECOVERY_ALARM_DEBOUNCE_MS;
|
|
4208
4589
|
const attempt = madeProgress ? 1 : debounced ? existing?.attempt ?? 1 : (existing?.attempt ?? 0) + 1;
|
|
4209
|
-
|
|
4590
|
+
let abortedByCaller = false;
|
|
4591
|
+
if (existing != null && !awaitingClientInteraction && config.shouldKeepRecovering && !noProgressExceeded && !workBudgetExceeded && attempt <= config.maxAttempts) try {
|
|
4592
|
+
abortedByCaller = await config.shouldKeepRecovering({
|
|
4593
|
+
incidentId,
|
|
4594
|
+
requestId: input.requestId,
|
|
4595
|
+
recoveryRootRequestId: input.recoveryRootRequestId ?? input.requestId,
|
|
4596
|
+
attempt,
|
|
4597
|
+
maxAttempts: config.maxAttempts,
|
|
4598
|
+
recoveryKind: input.recoveryKind,
|
|
4599
|
+
work,
|
|
4600
|
+
ageMs: now - (existing.firstSeenAt ?? now)
|
|
4601
|
+
}) === false;
|
|
4602
|
+
} catch (error) {
|
|
4603
|
+
console.error("[Think] chatRecovery shouldKeepRecovering hook threw", error);
|
|
4604
|
+
}
|
|
4605
|
+
const exhausted = !awaitingClientInteraction && (noProgressExceeded || workBudgetExceeded || abortedByCaller || attempt > config.maxAttempts);
|
|
4210
4606
|
const incident = {
|
|
4211
4607
|
incidentId,
|
|
4212
4608
|
requestId: input.requestId,
|
|
@@ -4218,8 +4614,9 @@ var Think = class Think extends Agent {
|
|
|
4218
4614
|
firstSeenAt: existing?.firstSeenAt ?? now,
|
|
4219
4615
|
lastAttemptAt: now,
|
|
4220
4616
|
lastProgressAt,
|
|
4221
|
-
progress
|
|
4222
|
-
|
|
4617
|
+
progress,
|
|
4618
|
+
workBaseline,
|
|
4619
|
+
...exhausted ? { reason: workBudgetExceeded ? "work_budget_exceeded" : noProgressExceeded ? "no_progress_timeout" : abortedByCaller ? "recovery_aborted" : "max_attempts_exceeded" } : {}
|
|
4223
4620
|
};
|
|
4224
4621
|
await this.ctx.storage.put(key, incident);
|
|
4225
4622
|
if (!existing) this._emit("chat:recovery:detected", {
|
|
@@ -4546,6 +4943,50 @@ var Think = class Think extends Agent {
|
|
|
4546
4943
|
return true;
|
|
4547
4944
|
}
|
|
4548
4945
|
/**
|
|
4946
|
+
* Park a recovery continuation that timed out waiting for stable state
|
|
4947
|
+
* because the turn is holding a pending CLIENT interaction (an
|
|
4948
|
+
* `input-available` client-tool part or an `approval-requested` part — see
|
|
4949
|
+
* `hasPendingInteraction`). Such a turn is WAITING ON THE HUMAN, not stuck:
|
|
4950
|
+
* the SPA replays the interrupted tool-result / approval after reconnect,
|
|
4951
|
+
* which drives a fresh continuation via the auto-continuation barrier
|
|
4952
|
+
* independently of the recovery retry loop. Burning the attempt budget on
|
|
4953
|
+
* that wait (each `waitUntilStable` times out because the human hasn't
|
|
4954
|
+
* answered) would seal a perfectly healthy turn on `stable_timeout` — the
|
|
4955
|
+
* exact symptom behind HITL "session recovery errors" under deploy churn.
|
|
4956
|
+
*
|
|
4957
|
+
* So instead of rescheduling or exhausting, we stop the loop and mark the
|
|
4958
|
+
* incident `skipped` (reason `awaiting_client_interaction`). That retains the
|
|
4959
|
+
* incident record (a later genuine interruption re-evaluates it) while
|
|
4960
|
+
* resolving the live "recovering…" indicator via `_updateChatRecoveryIncident`
|
|
4961
|
+
* so the client sees the parked tool-call UI rather than an eternal spinner.
|
|
4962
|
+
* A client that never returns is reclaimed by the incident TTL sweep and DO
|
|
4963
|
+
* idle-eviction. SERVER-tool orphans are excluded by `hasPendingInteraction`
|
|
4964
|
+
* (their `execute` died with the isolate), so they still recover normally.
|
|
4965
|
+
*
|
|
4966
|
+
* For a SUBMISSION-backed turn (`recoveredRequestId` present) the recovery
|
|
4967
|
+
* loop is the submission row's SOLE completion driver after a restart, and the
|
|
4968
|
+
* client's replay resumes the conversation as an independent auto-continuation
|
|
4969
|
+
* that never touches the submission. Parking would therefore leave the row
|
|
4970
|
+
* `running` until `_recoverSubmissionsOnStart` swept it to `error` on the next
|
|
4971
|
+
* restart. We instead complete it `completed` here: the park condition is a
|
|
4972
|
+
* fully-materialized client tool call in the leaf, which is exactly the
|
|
4973
|
+
* terminal state a non-interrupted submission reaches when its step emits a
|
|
4974
|
+
* client tool call (the model does not block on client tools — see
|
|
4975
|
+
* `_runProgrammaticMessagesTurn`, which marks such a step `completed`). The
|
|
4976
|
+
* human round-trip then proceeds via the normal auto-continuation, identical
|
|
4977
|
+
* to the non-crash flow.
|
|
4978
|
+
*
|
|
4979
|
+
* Returns `true` when the recovery was parked (caller must return), `false`
|
|
4980
|
+
* when there is no pending client interaction (caller proceeds to the normal
|
|
4981
|
+
* reschedule / exhaustion path).
|
|
4982
|
+
*/
|
|
4983
|
+
async _parkRecoveryForPendingInteraction(data) {
|
|
4984
|
+
if (!this.hasPendingInteraction()) return false;
|
|
4985
|
+
await this._updateChatRecoveryIncident(data?.incidentId, "skipped", "awaiting_client_interaction");
|
|
4986
|
+
if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "completed", null, null);
|
|
4987
|
+
return true;
|
|
4988
|
+
}
|
|
4989
|
+
/**
|
|
4549
4990
|
* Resolve the stream id for a recovery turn so the give-up terminalization
|
|
4550
4991
|
* can surface whatever partial the turn produced. Prefers the durable stream
|
|
4551
4992
|
* row keyed by the recovery-root request id; falls back to the live active
|
|
@@ -4707,6 +5148,7 @@ var Think = class Think extends Agent {
|
|
|
4707
5148
|
try {
|
|
4708
5149
|
const recoveryConfig = this._resolveChatRecoveryConfig();
|
|
4709
5150
|
if (!await this.waitUntilStable({ timeout: recoveryConfig.stableTimeoutMs })) {
|
|
5151
|
+
if (await this._parkRecoveryForPendingInteraction(data)) return;
|
|
4710
5152
|
if (await this._rescheduleRecoveryAfterStableTimeout("_chatRecoveryRetry", data, recoveryConfig.maxAttempts)) return;
|
|
4711
5153
|
await this._exhaustRecoveryAfterStableTimeout("_chatRecoveryRetry", data);
|
|
4712
5154
|
return;
|
|
@@ -4731,6 +5173,7 @@ var Think = class Think extends Agent {
|
|
|
4731
5173
|
} finally {
|
|
4732
5174
|
this._activeChatRecoveryRootRequestId = previousRootRequestId;
|
|
4733
5175
|
if (recoveredSubmission) this._submissionAbortControllers.delete(recoveredSubmission.submission_id);
|
|
5176
|
+
await this._reconcileOwnStaleAgentToolChildRuns();
|
|
4734
5177
|
}
|
|
4735
5178
|
}
|
|
4736
5179
|
_hasRunningSubmission(requestId) {
|
|
@@ -4812,6 +5255,7 @@ var Think = class Think extends Agent {
|
|
|
4812
5255
|
try {
|
|
4813
5256
|
const recoveryConfig = this._resolveChatRecoveryConfig();
|
|
4814
5257
|
if (!await this.waitUntilStable({ timeout: recoveryConfig.stableTimeoutMs })) {
|
|
5258
|
+
if (await this._parkRecoveryForPendingInteraction(data)) return;
|
|
4815
5259
|
console.warn("[Think] _chatRecoveryContinue timed out waiting for stable state");
|
|
4816
5260
|
if (await this._rescheduleRecoveryAfterStableTimeout("_chatRecoveryContinue", data, recoveryConfig.maxAttempts)) return;
|
|
4817
5261
|
await this._exhaustRecoveryAfterStableTimeout("_chatRecoveryContinue", data);
|
|
@@ -4834,6 +5278,7 @@ var Think = class Think extends Agent {
|
|
|
4834
5278
|
} finally {
|
|
4835
5279
|
this._activeChatRecoveryRootRequestId = previousRootRequestId;
|
|
4836
5280
|
if (recoveredSubmission) this._submissionAbortControllers.delete(recoveredSubmission.submission_id);
|
|
5281
|
+
await this._reconcileOwnStaleAgentToolChildRuns();
|
|
4837
5282
|
}
|
|
4838
5283
|
}
|
|
4839
5284
|
_applyRecoveredRequestContext(data) {
|
|
@@ -5138,7 +5583,7 @@ var Think = class Think extends Agent {
|
|
|
5138
5583
|
*/
|
|
5139
5584
|
async _setChatRecovering(active, requestId) {
|
|
5140
5585
|
const existing = await this.ctx.storage.get(CHAT_RECOVERING_KEY);
|
|
5141
|
-
const activeExisting = existing && Date.now() - (existing.at ?? 0) <
|
|
5586
|
+
const activeExisting = existing && Date.now() - (existing.at ?? 0) < CHAT_RECOVERING_FLAG_TTL_MS;
|
|
5142
5587
|
if (active) {
|
|
5143
5588
|
if (activeExisting) return;
|
|
5144
5589
|
await this.ctx.storage.put(CHAT_RECOVERING_KEY, {
|
|
@@ -5176,7 +5621,7 @@ var Think = class Think extends Agent {
|
|
|
5176
5621
|
error: true
|
|
5177
5622
|
});
|
|
5178
5623
|
const recovering = await this.ctx.storage.get(CHAT_RECOVERING_KEY);
|
|
5179
|
-
if (recovering && Date.now() - (recovering.at ?? 0) <
|
|
5624
|
+
if (recovering && Date.now() - (recovering.at ?? 0) < CHAT_RECOVERING_FLAG_TTL_MS) messages.push({
|
|
5180
5625
|
type: MSG_CHAT_RECOVERING,
|
|
5181
5626
|
recovering: true,
|
|
5182
5627
|
...recovering.requestId ? { id: recovering.requestId } : {}
|
|
@@ -5227,6 +5672,6 @@ Think.CHAT_FIBER_NAME = "__cf_internal_chat_turn";
|
|
|
5227
5672
|
Think.MESSAGE_DEBOUNCE_MS = 750;
|
|
5228
5673
|
Think.submissionRecoveryStaleMs = 900 * 1e3;
|
|
5229
5674
|
//#endregion
|
|
5230
|
-
export { Session, Think, Workspace, defineScheduledTasks, skills };
|
|
5675
|
+
export { Session, Think, Workspace, defaultContextOverflowClassifier, defineScheduledTasks, skills };
|
|
5231
5676
|
|
|
5232
5677
|
//# sourceMappingURL=think.js.map
|