@cloudflare/think 0.8.3 → 0.8.5
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/dist/{index-By2rkaOh.d.ts → index-BzPfnYMr.d.ts} +56 -10
- package/dist/messengers/index.d.ts +1 -1
- package/dist/messengers/telegram.d.ts +1 -1
- package/dist/think.d.ts +1 -1
- package/dist/think.js +192 -46
- package/dist/think.js.map +1 -1
- package/dist/workflows.d.ts +1 -1
- package/package.json +4 -2
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License Copyright (c) 2025 Cloudflare, Inc.
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of
|
|
4
|
+
charge, to any person obtaining a copy of this software and associated
|
|
5
|
+
documentation files (the "Software"), to deal in the Software without
|
|
6
|
+
restriction, including without limitation the rights to use, copy, modify, merge,
|
|
7
|
+
publish, distribute, sublicense, and/or sell copies of the Software, and to
|
|
8
|
+
permit persons to whom the Software is furnished to do so, subject to the
|
|
9
|
+
following conditions:
|
|
10
|
+
|
|
11
|
+
The above copyright notice and this permission notice
|
|
12
|
+
(including the next paragraph) shall be included in all copies or substantial
|
|
13
|
+
portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
|
16
|
+
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
17
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
|
|
18
|
+
EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
|
19
|
+
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
20
|
+
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
21
|
+
THE SOFTWARE.
|
|
@@ -1796,6 +1796,16 @@ declare class Think<
|
|
|
1796
1796
|
private _iterateWithStallWatchdog;
|
|
1797
1797
|
private _streamResult;
|
|
1798
1798
|
private _persistAssistantMessage;
|
|
1799
|
+
/**
|
|
1800
|
+
* Remove parts belonging to Think's internal structured-output final-answer
|
|
1801
|
+
* tool (`think_final_answer`, or a collision-suffixed variant) from a UI
|
|
1802
|
+
* message so the internal call/result never enters the persisted conversation
|
|
1803
|
+
* (and is never re-fed to the model on later turns). Stateless and matched by
|
|
1804
|
+
* the reserved name so it also covers recovery re-persist paths. Handles both
|
|
1805
|
+
* the static (`tool-<name>`) and dynamic (`dynamic-tool`) part shapes the AI
|
|
1806
|
+
* SDK can emit.
|
|
1807
|
+
*/
|
|
1808
|
+
private _stripInternalFinalAnswerParts;
|
|
1799
1809
|
/**
|
|
1800
1810
|
* Persist an incoming message after reconciliation. For assistant
|
|
1801
1811
|
* messages, also resolve their ID against any server-side row that
|
|
@@ -2182,14 +2192,44 @@ declare class Think<
|
|
|
2182
2192
|
private _activateDeferredContinuation;
|
|
2183
2193
|
private _fireResponseHook;
|
|
2184
2194
|
/**
|
|
2185
|
-
* Persist (on `error`) or clear (on `completed`/`aborted`)
|
|
2186
|
-
*
|
|
2187
|
-
*
|
|
2188
|
-
*
|
|
2189
|
-
* otherwise, so it is kept
|
|
2195
|
+
* Persist (on `error`/`interrupted`) or clear (on `completed`/`aborted`) the
|
|
2196
|
+
* durable terminal record so it can be replayed to clients on reconnect, and
|
|
2197
|
+
* resolve any in-progress "recovering…" indicator. A `completed`/`aborted`
|
|
2198
|
+
* turn is conveyed by the persisted messages, so the record is cleared; an
|
|
2199
|
+
* `error`/`interrupted` turn has no durable trace otherwise, so it is kept
|
|
2200
|
+
* until a later turn supersedes it.
|
|
2201
|
+
*
|
|
2202
|
+
* The storage primitives are shared with `@cloudflare/ai-chat`
|
|
2203
|
+
* (`_recordChatTerminal` / `_clearChatTerminal` / `_pendingChatTerminal`).
|
|
2190
2204
|
*/
|
|
2191
2205
|
private _recordTerminalChatStatus;
|
|
2192
|
-
|
|
2206
|
+
/**
|
|
2207
|
+
* Persist a durable record of the last terminal turn so a client that
|
|
2208
|
+
* (re)connects after the turn ended still learns its outcome (#1645). Kept
|
|
2209
|
+
* until a later turn supersedes it (`_clearChatTerminal`); a single record is
|
|
2210
|
+
* sufficient because only the most recent terminal is relevant.
|
|
2211
|
+
*/
|
|
2212
|
+
private _recordChatTerminal;
|
|
2213
|
+
/** Clear the durable terminal record once a later turn supersedes it (#1645). */
|
|
2214
|
+
private _clearChatTerminal;
|
|
2215
|
+
private _pendingChatTerminal;
|
|
2216
|
+
/**
|
|
2217
|
+
* Replay a pending terminal outcome (#1645) over the resume handshake so a
|
|
2218
|
+
* reconnecting client surfaces it exactly like a live exhaustion. A bare
|
|
2219
|
+
* terminal frame sent on connect is dropped by the `useAgentChat` client
|
|
2220
|
+
* because it never reaches a transport stream reader; only a frame delivered
|
|
2221
|
+
* on a resumed stream becomes `useChat.error` (this is why the terminal is
|
|
2222
|
+
* NOT included in `_buildIdleConnectMessages`). So we drive `STREAM_RESUMING`
|
|
2223
|
+
* here and send the error frame once the client ACKs (see
|
|
2224
|
+
* `_replayTerminalOnAck`). Returns true if a terminal was pending.
|
|
2225
|
+
*/
|
|
2226
|
+
private _replayTerminalOnResume;
|
|
2227
|
+
/**
|
|
2228
|
+
* Deliver the pending terminal error frame on the resumed stream the client
|
|
2229
|
+
* ACKed (#1645). The record is retained (cleared only when a later turn
|
|
2230
|
+
* supersedes it) so concurrent reconnects each learn the outcome.
|
|
2231
|
+
*/
|
|
2232
|
+
private _replayTerminalOnAck;
|
|
2193
2233
|
/**
|
|
2194
2234
|
* Set or clear the live "recovering…" status for a durable chat turn (#1620).
|
|
2195
2235
|
* Persists a durable record (replayed on connect via `_buildIdleConnectMessages`)
|
|
@@ -2201,9 +2241,15 @@ declare class Think<
|
|
|
2201
2241
|
private _setChatRecovering;
|
|
2202
2242
|
/**
|
|
2203
2243
|
* Messages sent to a client on connect when no stream is active: the current
|
|
2204
|
-
* transcript, plus a replay of
|
|
2205
|
-
*
|
|
2206
|
-
*
|
|
2244
|
+
* transcript, plus a replay of an in-progress "recovering…" status (if any).
|
|
2245
|
+
*
|
|
2246
|
+
* A terminal error is deliberately NOT replayed here. A bare
|
|
2247
|
+
* `MSG_CHAT_RESPONSE` frame on connect is dropped by the `useAgentChat`
|
|
2248
|
+
* client because it never reaches a transport stream reader, so it cannot
|
|
2249
|
+
* become `useChat.error` — a failed turn would still look frozen (#1645).
|
|
2250
|
+
* The terminal outcome is instead surfaced over the resume handshake
|
|
2251
|
+
* (`_replayTerminalOnResume` → ACK → `_replayTerminalOnAck`), the only path
|
|
2252
|
+
* that lands on the stream reader.
|
|
2207
2253
|
*/
|
|
2208
2254
|
private _buildIdleConnectMessages;
|
|
2209
2255
|
private _notifyStreamResuming;
|
|
@@ -2675,4 +2721,4 @@ export {
|
|
|
2675
2721
|
messengerReplySnapshot as z,
|
|
2676
2722
|
ThinkScheduledTask as zt
|
|
2677
2723
|
};
|
|
2678
|
-
//# sourceMappingURL=index-
|
|
2724
|
+
//# sourceMappingURL=index-BzPfnYMr.d.ts.map
|
|
@@ -2,7 +2,7 @@ import {
|
|
|
2
2
|
P as TextStreamCallback,
|
|
3
3
|
n as ChatSdkMessengerOptions,
|
|
4
4
|
o as MessengerDefinition
|
|
5
|
-
} from "../index-
|
|
5
|
+
} from "../index-BzPfnYMr.js";
|
|
6
6
|
import { TelegramAdapterConfig } from "@chat-adapter/telegram";
|
|
7
7
|
|
|
8
8
|
//#region src/messengers/telegram.d.ts
|
package/dist/think.d.ts
CHANGED
package/dist/think.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
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
|
-
import {
|
|
4
|
+
import { convertToModelMessages, hasToolCall, jsonSchema, stepCountIs, streamText, tool } 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";
|
|
@@ -296,6 +296,7 @@ const DEFAULT_CHAT_RECOVERY_STABLE_TIMEOUT_MS = 1e4;
|
|
|
296
296
|
const CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS = 3;
|
|
297
297
|
const DEFAULT_CHAT_RECOVERY_TERMINAL_MESSAGE = "The assistant was interrupted and could not recover. Please try again.";
|
|
298
298
|
const CHAT_RECOVERY_INCIDENT_TTL_MS = 3600 * 1e3;
|
|
299
|
+
const KV_DELETE_MAX_KEYS = 128;
|
|
299
300
|
const DEFAULT_CHAT_RECOVERY_NO_PROGRESS_TIMEOUT_MS = 300 * 1e3;
|
|
300
301
|
const CHAT_RECOVERY_ALARM_DEBOUNCE_MS = 30 * 1e3;
|
|
301
302
|
const CHAT_RECOVERING_FLAG_TTL_MS = 900 * 1e3;
|
|
@@ -327,6 +328,39 @@ function defineScheduledTasks(tasks) {
|
|
|
327
328
|
}
|
|
328
329
|
const THINK_WORKFLOW_PROMPT_METADATA_KEY = "__thinkWorkflowPrompt";
|
|
329
330
|
/**
|
|
331
|
+
* Reserved name for the synthetic tool a workflow `step.prompt` turn uses to
|
|
332
|
+
* deliver its structured final answer. The agent runs a full multi-step,
|
|
333
|
+
* tool-using turn and ends it by calling this tool with arguments matching the
|
|
334
|
+
* requested schema — exactly the way a sub-agent returns a result.
|
|
335
|
+
*
|
|
336
|
+
* Why a tool instead of the AI SDK `output`/`response_format` path: streaming a
|
|
337
|
+
* JSON Schema `response_format` is rejected by some providers (Workers AI
|
|
338
|
+
* returns `AiError 5023: JSON Schema mode is not supported with stream mode`),
|
|
339
|
+
* whereas plain tool-calling streams on every provider. Capturing the tool
|
|
340
|
+
* call's INPUT as the result keeps Think's single streaming engine intact
|
|
341
|
+
* (persistence, recovery, resumable streams) and works uniformly across
|
|
342
|
+
* Workers AI, OpenAI, and Anthropic.
|
|
343
|
+
*
|
|
344
|
+
* The name is namespaced to avoid clashing with user tools; if a user tool
|
|
345
|
+
* already uses it, the turn picks a suffixed variant (see `_handleTurn`).
|
|
346
|
+
*/
|
|
347
|
+
const THINK_FINAL_ANSWER_TOOL_NAME = "think_final_answer";
|
|
348
|
+
/**
|
|
349
|
+
* Whether `name` is (or is a collision-suffixed variant of) the reserved
|
|
350
|
+
* structured-output final-answer tool. Used to strip the internal tool's parts
|
|
351
|
+
* from persisted assistant messages regardless of which per-turn name was used.
|
|
352
|
+
*/
|
|
353
|
+
function isThinkFinalAnswerToolName(name) {
|
|
354
|
+
return name === THINK_FINAL_ANSWER_TOOL_NAME || name.startsWith(`${THINK_FINAL_ANSWER_TOOL_NAME}_`);
|
|
355
|
+
}
|
|
356
|
+
/**
|
|
357
|
+
* Build the system-prompt instruction that tells the model to terminate a
|
|
358
|
+
* structured workflow turn by calling the given final-answer tool.
|
|
359
|
+
*/
|
|
360
|
+
function thinkFinalAnswerInstruction(toolName) {
|
|
361
|
+
return `When you have everything you need to answer, you MUST call the \`${toolName}\` tool exactly once with arguments that match the required schema. Do not write the final answer as plain text — the \`${toolName}\` tool call IS the answer and ends the task.`;
|
|
362
|
+
}
|
|
363
|
+
/**
|
|
330
364
|
* Matches the context-window-overflow error messages of the common providers.
|
|
331
365
|
* Anthropic (`prompt is too long`), OpenAI (`context_length_exceeded`,
|
|
332
366
|
* `maximum context length`, `reduce the length of …`), Google Gemini (`exceeds
|
|
@@ -685,6 +719,7 @@ var Think = class Think extends Agent {
|
|
|
685
719
|
}
|
|
686
720
|
async _clearHistory() {
|
|
687
721
|
await this.session.clearMessages();
|
|
722
|
+
await this._clearChatTerminal();
|
|
688
723
|
}
|
|
689
724
|
/** Append a message while keeping Think's live message cache coherent. */
|
|
690
725
|
appendMessageToHistory(message, parentId) {
|
|
@@ -1444,7 +1479,8 @@ var Think = class Think extends Agent {
|
|
|
1444
1479
|
const subclassConfig = await this.beforeTurn(ctx) ?? {};
|
|
1445
1480
|
const config = await this._pipelineExtensionBeforeTurn(ctx, subclassConfig);
|
|
1446
1481
|
const workflowPrompt = input.workflowPrompt;
|
|
1447
|
-
const
|
|
1482
|
+
const structuredOutputSchema = workflowPrompt?.output ? jsonSchema(workflowPrompt.output.schema) : void 0;
|
|
1483
|
+
const wantsStructuredOutput = structuredOutputSchema !== void 0;
|
|
1448
1484
|
const finalModel = config.model ?? model;
|
|
1449
1485
|
const finalSystem = config.system ?? this._systemPromptForTurn(baseSystem, config.tools ? {
|
|
1450
1486
|
...tools,
|
|
@@ -1456,20 +1492,40 @@ var Think = class Think extends Agent {
|
|
|
1456
1492
|
...config.tools
|
|
1457
1493
|
} : tools;
|
|
1458
1494
|
const finalTools = this._wrapToolsWithDecision(mergedTools);
|
|
1495
|
+
let finalAnswerToolName = THINK_FINAL_ANSWER_TOOL_NAME;
|
|
1496
|
+
if (structuredOutputSchema) {
|
|
1497
|
+
let suffix = 1;
|
|
1498
|
+
while (finalAnswerToolName in finalTools) finalAnswerToolName = `${THINK_FINAL_ANSWER_TOOL_NAME}_${suffix++}`;
|
|
1499
|
+
finalTools[finalAnswerToolName] = tool({
|
|
1500
|
+
description: "Provide your final answer. The arguments MUST match the required schema. Calling this tool ends the task — call it exactly once when you have everything you need.",
|
|
1501
|
+
inputSchema: structuredOutputSchema,
|
|
1502
|
+
execute: async () => "Final answer recorded."
|
|
1503
|
+
});
|
|
1504
|
+
}
|
|
1459
1505
|
this._turnModelMessageBaseline = finalMessages.length;
|
|
1460
1506
|
this._activeTurnTools = mergedTools;
|
|
1461
1507
|
const finalMaxSteps = config.maxSteps ?? this.maxSteps;
|
|
1462
1508
|
const finalSendReasoning = config.sendReasoning ?? this.sendReasoning;
|
|
1463
1509
|
this._activeStallTimeoutMs = config.chatStreamStallTimeoutMs ?? this.chatStreamStallTimeoutMs;
|
|
1464
|
-
const finalOutput =
|
|
1465
|
-
const
|
|
1510
|
+
const finalOutput = config.output;
|
|
1511
|
+
const turnSystem = wantsStructuredOutput ? [finalSystem, thinkFinalAnswerInstruction(finalAnswerToolName)].filter(Boolean).join("\n\n") : finalSystem;
|
|
1512
|
+
const structuredHasRealTools = wantsStructuredOutput && Object.keys(finalTools).some((name) => name !== finalAnswerToolName);
|
|
1513
|
+
const finalToolChoice = wantsStructuredOutput ? config.toolChoice ?? (structuredHasRealTools ? "required" : {
|
|
1514
|
+
type: "tool",
|
|
1515
|
+
toolName: finalAnswerToolName
|
|
1516
|
+
}) : config.toolChoice;
|
|
1517
|
+
const finalStopWhen = [
|
|
1518
|
+
stepCountIs(finalMaxSteps),
|
|
1519
|
+
...wantsStructuredOutput ? [hasToolCall(finalAnswerToolName)] : [],
|
|
1520
|
+
...Array.isArray(config.stopWhen) ? config.stopWhen : config.stopWhen ? [config.stopWhen] : []
|
|
1521
|
+
];
|
|
1466
1522
|
const result = streamText({
|
|
1467
1523
|
model: finalModel,
|
|
1468
|
-
system:
|
|
1524
|
+
system: turnSystem,
|
|
1469
1525
|
messages: finalMessages,
|
|
1470
1526
|
tools: finalTools,
|
|
1471
|
-
activeTools: config.activeTools,
|
|
1472
|
-
toolChoice:
|
|
1527
|
+
activeTools: wantsStructuredOutput && config.activeTools ? [...config.activeTools, finalAnswerToolName] : config.activeTools,
|
|
1528
|
+
toolChoice: finalToolChoice,
|
|
1473
1529
|
maxOutputTokens: config.maxOutputTokens,
|
|
1474
1530
|
temperature: config.temperature,
|
|
1475
1531
|
topP: config.topP,
|
|
@@ -1491,11 +1547,19 @@ var Think = class Think extends Agent {
|
|
|
1491
1547
|
const result = await this.beforeStep(event);
|
|
1492
1548
|
const base = result == null ? {} : result;
|
|
1493
1549
|
const baseMessages = base.messages;
|
|
1494
|
-
|
|
1550
|
+
const withMessages = guarded && baseMessages === void 0 ? {
|
|
1495
1551
|
...base,
|
|
1496
1552
|
messages: guarded
|
|
1553
|
+
} : base;
|
|
1554
|
+
if (wantsStructuredOutput && event.stepNumber >= finalMaxSteps - 1 && withMessages.toolChoice === void 0) return {
|
|
1555
|
+
...withMessages,
|
|
1556
|
+
toolChoice: {
|
|
1557
|
+
type: "tool",
|
|
1558
|
+
toolName: finalAnswerToolName
|
|
1559
|
+
},
|
|
1560
|
+
activeTools: [finalAnswerToolName]
|
|
1497
1561
|
};
|
|
1498
|
-
return
|
|
1562
|
+
return withMessages;
|
|
1499
1563
|
}),
|
|
1500
1564
|
onChunk: async (event) => {
|
|
1501
1565
|
await this.onChunk(event);
|
|
@@ -1506,6 +1570,7 @@ var Think = class Think extends Agent {
|
|
|
1506
1570
|
await this._pipelineExtensionStepFinish(event);
|
|
1507
1571
|
},
|
|
1508
1572
|
experimental_onToolCallFinish: (async (event) => {
|
|
1573
|
+
if (event.toolCall.toolName === finalAnswerToolName) return;
|
|
1509
1574
|
const base = {
|
|
1510
1575
|
...event.toolCall,
|
|
1511
1576
|
stepNumber: event.stepNumber,
|
|
@@ -1525,7 +1590,12 @@ var Think = class Think extends Agent {
|
|
|
1525
1590
|
await this._pipelineExtensionToolCallFinish(event);
|
|
1526
1591
|
})
|
|
1527
1592
|
});
|
|
1528
|
-
const outputPromise =
|
|
1593
|
+
const outputPromise = wantsStructuredOutput ? Promise.resolve(result.toolCalls).then((calls) => {
|
|
1594
|
+
const finalCalls = calls.filter((call) => call.toolName === finalAnswerToolName);
|
|
1595
|
+
const last = finalCalls[finalCalls.length - 1];
|
|
1596
|
+
if (!last) throw new Error(`Model ended the turn without calling the ${finalAnswerToolName} tool`);
|
|
1597
|
+
return last.input;
|
|
1598
|
+
}) : finalOutput && result.output ? Promise.resolve(result.output) : void 0;
|
|
1529
1599
|
if (outputPromise) outputPromise.catch(() => {});
|
|
1530
1600
|
const streamResult = {
|
|
1531
1601
|
toUIMessageStream: () => result.toUIMessageStream({ sendReasoning: finalSendReasoning }),
|
|
@@ -2840,16 +2910,13 @@ var Think = class Think extends Agent {
|
|
|
2840
2910
|
]);
|
|
2841
2911
|
const limit = Math.min(Math.max(options?.limit ?? 100, 1), 500);
|
|
2842
2912
|
const completedBefore = options?.completedBefore?.getTime();
|
|
2843
|
-
const
|
|
2913
|
+
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);
|
|
2844
2914
|
let deleted = 0;
|
|
2845
|
-
for (
|
|
2846
|
-
|
|
2847
|
-
|
|
2848
|
-
|
|
2849
|
-
|
|
2850
|
-
AND status IN ('completed', 'aborted', 'skipped', 'error')
|
|
2851
|
-
`;
|
|
2852
|
-
deleted++;
|
|
2915
|
+
for (let i = 0; i < idsToDelete.length; i += MAX_BOUND_PARAMS) {
|
|
2916
|
+
const batch = idsToDelete.slice(i, i + MAX_BOUND_PARAMS);
|
|
2917
|
+
const strings = buildInClauseStrings("DELETE FROM cf_think_submissions WHERE status IN ('completed', 'aborted', 'skipped', 'error') AND submission_id IN ", batch.length);
|
|
2918
|
+
this.sql(strings, ...batch);
|
|
2919
|
+
deleted += batch.length;
|
|
2853
2920
|
}
|
|
2854
2921
|
return deleted;
|
|
2855
2922
|
}
|
|
@@ -3520,7 +3587,7 @@ var Think = class Think extends Agent {
|
|
|
3520
3587
|
async _handleProtocolEvent(connection, event) {
|
|
3521
3588
|
switch (event.type) {
|
|
3522
3589
|
case "stream-resume-request":
|
|
3523
|
-
this._handleStreamResumeRequest(connection);
|
|
3590
|
+
await this._handleStreamResumeRequest(connection);
|
|
3524
3591
|
break;
|
|
3525
3592
|
case "stream-resume-ack":
|
|
3526
3593
|
await this._handleStreamResumeAck(connection, event.id);
|
|
@@ -3551,18 +3618,18 @@ var Think = class Think extends Agent {
|
|
|
3551
3618
|
case "messages": break;
|
|
3552
3619
|
}
|
|
3553
3620
|
}
|
|
3554
|
-
_handleStreamResumeRequest(connection) {
|
|
3621
|
+
async _handleStreamResumeRequest(connection) {
|
|
3555
3622
|
if (this._resumableStream.hasActiveStream()) if (this._continuation.activeRequestId === this._resumableStream.activeRequestId && this._continuation.activeConnectionId !== null && this._continuation.activeConnectionId !== connection.id) sendIfOpen(connection, JSON.stringify({ type: MSG_STREAM_RESUME_NONE }));
|
|
3556
3623
|
else this._notifyStreamResuming(connection);
|
|
3557
3624
|
else if (this._continuation.pending !== null && (this._continuation.pending.connectionId === null || this._continuation.pending.connectionId === connection.id)) this._continuation.awaitingConnections.set(connection.id, connection);
|
|
3558
|
-
else sendIfOpen(connection, JSON.stringify({ type: MSG_STREAM_RESUME_NONE }));
|
|
3625
|
+
else if (await this._replayTerminalOnResume(connection)) {} else sendIfOpen(connection, JSON.stringify({ type: MSG_STREAM_RESUME_NONE }));
|
|
3559
3626
|
}
|
|
3560
3627
|
async _handleStreamResumeAck(connection, requestId) {
|
|
3561
3628
|
this._pendingResumeConnections.delete(connection.id);
|
|
3562
3629
|
if (this._resumableStream.hasActiveStream() && this._resumableStream.activeRequestId === requestId) {
|
|
3563
3630
|
const orphanedStreamId = this._resumableStream.replayChunks(connection, this._resumableStream.activeRequestId);
|
|
3564
3631
|
if (orphanedStreamId) await this._persistOrphanedStream(orphanedStreamId);
|
|
3565
|
-
} else if (this._resumableStream.hasActiveStream()) {} else if (!this._resumableStream.replayCompletedChunksByRequestId(connection, requestId)) sendIfOpen(connection, JSON.stringify({
|
|
3632
|
+
} else if (this._resumableStream.hasActiveStream()) {} else if (await this._replayTerminalOnAck(connection, requestId)) {} else if (!this._resumableStream.replayCompletedChunksByRequestId(connection, requestId)) sendIfOpen(connection, JSON.stringify({
|
|
3566
3633
|
body: "",
|
|
3567
3634
|
done: true,
|
|
3568
3635
|
id: requestId,
|
|
@@ -3602,6 +3669,7 @@ var Think = class Think extends Agent {
|
|
|
3602
3669
|
this._completeSkippedRequest(connection, requestId);
|
|
3603
3670
|
return;
|
|
3604
3671
|
}
|
|
3672
|
+
await this._clearChatTerminal();
|
|
3605
3673
|
const releasePendingEnqueue = this._submitConcurrency.beginEnqueue();
|
|
3606
3674
|
let pendingEnqueue = true;
|
|
3607
3675
|
const epoch = this._turnQueue.generation;
|
|
@@ -4314,9 +4382,36 @@ var Think = class Think extends Agent {
|
|
|
4314
4382
|
};
|
|
4315
4383
|
}
|
|
4316
4384
|
async _persistAssistantMessage(msg, parentId) {
|
|
4385
|
+
const stripped = this._stripInternalFinalAnswerParts(msg);
|
|
4386
|
+
if (stripped !== msg) {
|
|
4387
|
+
if (!stripped.parts.some((part) => part.type !== "step-start")) return;
|
|
4388
|
+
await this._upsertMessageInHistory(stripped, parentId);
|
|
4389
|
+
return;
|
|
4390
|
+
}
|
|
4317
4391
|
await this._upsertMessageInHistory(msg, parentId);
|
|
4318
4392
|
}
|
|
4319
4393
|
/**
|
|
4394
|
+
* Remove parts belonging to Think's internal structured-output final-answer
|
|
4395
|
+
* tool (`think_final_answer`, or a collision-suffixed variant) from a UI
|
|
4396
|
+
* message so the internal call/result never enters the persisted conversation
|
|
4397
|
+
* (and is never re-fed to the model on later turns). Stateless and matched by
|
|
4398
|
+
* the reserved name so it also covers recovery re-persist paths. Handles both
|
|
4399
|
+
* the static (`tool-<name>`) and dynamic (`dynamic-tool`) part shapes the AI
|
|
4400
|
+
* SDK can emit.
|
|
4401
|
+
*/
|
|
4402
|
+
_stripInternalFinalAnswerParts(msg) {
|
|
4403
|
+
const parts = msg.parts.filter((part) => {
|
|
4404
|
+
const candidate = part;
|
|
4405
|
+
if (typeof candidate.type === "string" && candidate.type.startsWith("tool-") && isThinkFinalAnswerToolName(candidate.type.slice(5))) return false;
|
|
4406
|
+
if (candidate.type === "dynamic-tool" && typeof candidate.toolName === "string" && isThinkFinalAnswerToolName(candidate.toolName)) return false;
|
|
4407
|
+
return true;
|
|
4408
|
+
});
|
|
4409
|
+
return parts.length === msg.parts.length ? msg : {
|
|
4410
|
+
...msg,
|
|
4411
|
+
parts
|
|
4412
|
+
};
|
|
4413
|
+
}
|
|
4414
|
+
/**
|
|
4320
4415
|
* Persist an incoming message after reconciliation. For assistant
|
|
4321
4416
|
* messages, also resolve their ID against any server-side row that
|
|
4322
4417
|
* already owns the same `toolCallId` so we update the existing row
|
|
@@ -4567,7 +4662,7 @@ var Think = class Think extends Agent {
|
|
|
4567
4662
|
const entries = await this.ctx.storage.list({ prefix: CHAT_RECOVERY_INCIDENT_KEY_PREFIX });
|
|
4568
4663
|
const staleKeys = [];
|
|
4569
4664
|
for (const [key, incident] of entries) if (now - (incident?.lastAttemptAt ?? incident?.firstSeenAt ?? 0) > CHAT_RECOVERY_INCIDENT_TTL_MS) staleKeys.push(key);
|
|
4570
|
-
for (
|
|
4665
|
+
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));
|
|
4571
4666
|
}
|
|
4572
4667
|
async _beginChatRecoveryIncident(input) {
|
|
4573
4668
|
const config = this._resolveChatRecoveryConfig();
|
|
@@ -4692,8 +4787,8 @@ var Think = class Think extends Agent {
|
|
|
4692
4787
|
done: true,
|
|
4693
4788
|
error: true
|
|
4694
4789
|
});
|
|
4695
|
-
await this._markRecoveredSubmissionInterrupted(incident.recoveryRootRequestId ?? incident.requestId, config.terminalMessage);
|
|
4696
4790
|
await this._recordTerminalChatStatus("interrupted", incident.requestId, config.terminalMessage);
|
|
4791
|
+
await this._markRecoveredSubmissionInterrupted(incident.recoveryRootRequestId ?? incident.requestId, config.terminalMessage);
|
|
4697
4792
|
}
|
|
4698
4793
|
/**
|
|
4699
4794
|
* Route a stream-stall watchdog abort into bounded recovery instead of a
|
|
@@ -5558,24 +5653,77 @@ var Think = class Think extends Agent {
|
|
|
5558
5653
|
}
|
|
5559
5654
|
}
|
|
5560
5655
|
/**
|
|
5561
|
-
* Persist (on `error`) or clear (on `completed`/`aborted`)
|
|
5562
|
-
*
|
|
5563
|
-
*
|
|
5564
|
-
*
|
|
5565
|
-
* otherwise, so it is kept
|
|
5656
|
+
* Persist (on `error`/`interrupted`) or clear (on `completed`/`aborted`) the
|
|
5657
|
+
* durable terminal record so it can be replayed to clients on reconnect, and
|
|
5658
|
+
* resolve any in-progress "recovering…" indicator. A `completed`/`aborted`
|
|
5659
|
+
* turn is conveyed by the persisted messages, so the record is cleared; an
|
|
5660
|
+
* `error`/`interrupted` turn has no durable trace otherwise, so it is kept
|
|
5661
|
+
* until a later turn supersedes it.
|
|
5662
|
+
*
|
|
5663
|
+
* The storage primitives are shared with `@cloudflare/ai-chat`
|
|
5664
|
+
* (`_recordChatTerminal` / `_clearChatTerminal` / `_pendingChatTerminal`).
|
|
5566
5665
|
*/
|
|
5567
5666
|
async _recordTerminalChatStatus(status, requestId, body) {
|
|
5568
|
-
if (status === "error" || status === "interrupted") await this.
|
|
5667
|
+
if (status === "error" || status === "interrupted") await this._recordChatTerminal(requestId, body);
|
|
5668
|
+
else await this._clearChatTerminal();
|
|
5669
|
+
await this._setChatRecovering(false);
|
|
5670
|
+
}
|
|
5671
|
+
/**
|
|
5672
|
+
* Persist a durable record of the last terminal turn so a client that
|
|
5673
|
+
* (re)connects after the turn ended still learns its outcome (#1645). Kept
|
|
5674
|
+
* until a later turn supersedes it (`_clearChatTerminal`); a single record is
|
|
5675
|
+
* sufficient because only the most recent terminal is relevant.
|
|
5676
|
+
*/
|
|
5677
|
+
async _recordChatTerminal(requestId, body) {
|
|
5678
|
+
await this.ctx.storage.put(CHAT_LAST_TERMINAL_KEY, {
|
|
5569
5679
|
requestId,
|
|
5570
5680
|
body
|
|
5571
5681
|
});
|
|
5572
|
-
else await this.ctx.storage.delete(CHAT_LAST_TERMINAL_KEY);
|
|
5573
|
-
await this._setChatRecovering(false);
|
|
5574
5682
|
}
|
|
5575
|
-
|
|
5683
|
+
/** Clear the durable terminal record once a later turn supersedes it (#1645). */
|
|
5684
|
+
async _clearChatTerminal() {
|
|
5685
|
+
await this.ctx.storage.delete(CHAT_LAST_TERMINAL_KEY);
|
|
5686
|
+
}
|
|
5687
|
+
async _pendingChatTerminal() {
|
|
5576
5688
|
return await this.ctx.storage.get(CHAT_LAST_TERMINAL_KEY) ?? null;
|
|
5577
5689
|
}
|
|
5578
5690
|
/**
|
|
5691
|
+
* Replay a pending terminal outcome (#1645) over the resume handshake so a
|
|
5692
|
+
* reconnecting client surfaces it exactly like a live exhaustion. A bare
|
|
5693
|
+
* terminal frame sent on connect is dropped by the `useAgentChat` client
|
|
5694
|
+
* because it never reaches a transport stream reader; only a frame delivered
|
|
5695
|
+
* on a resumed stream becomes `useChat.error` (this is why the terminal is
|
|
5696
|
+
* NOT included in `_buildIdleConnectMessages`). So we drive `STREAM_RESUMING`
|
|
5697
|
+
* here and send the error frame once the client ACKs (see
|
|
5698
|
+
* `_replayTerminalOnAck`). Returns true if a terminal was pending.
|
|
5699
|
+
*/
|
|
5700
|
+
async _replayTerminalOnResume(connection) {
|
|
5701
|
+
const pending = await this._pendingChatTerminal();
|
|
5702
|
+
if (!pending) return false;
|
|
5703
|
+
sendIfOpen(connection, JSON.stringify({
|
|
5704
|
+
type: MSG_STREAM_RESUMING,
|
|
5705
|
+
id: pending.requestId
|
|
5706
|
+
}));
|
|
5707
|
+
return true;
|
|
5708
|
+
}
|
|
5709
|
+
/**
|
|
5710
|
+
* Deliver the pending terminal error frame on the resumed stream the client
|
|
5711
|
+
* ACKed (#1645). The record is retained (cleared only when a later turn
|
|
5712
|
+
* supersedes it) so concurrent reconnects each learn the outcome.
|
|
5713
|
+
*/
|
|
5714
|
+
async _replayTerminalOnAck(connection, requestId) {
|
|
5715
|
+
const pending = await this._pendingChatTerminal();
|
|
5716
|
+
if (!pending || pending.requestId !== requestId) return false;
|
|
5717
|
+
sendIfOpen(connection, JSON.stringify({
|
|
5718
|
+
body: pending.body,
|
|
5719
|
+
done: true,
|
|
5720
|
+
error: true,
|
|
5721
|
+
id: pending.requestId,
|
|
5722
|
+
type: MSG_CHAT_RESPONSE
|
|
5723
|
+
}));
|
|
5724
|
+
return true;
|
|
5725
|
+
}
|
|
5726
|
+
/**
|
|
5579
5727
|
* Set or clear the live "recovering…" status for a durable chat turn (#1620).
|
|
5580
5728
|
* Persists a durable record (replayed on connect via `_buildIdleConnectMessages`)
|
|
5581
5729
|
* and broadcasts a `MSG_CHAT_RECOVERING` frame — but only on a genuine
|
|
@@ -5605,23 +5753,21 @@ var Think = class Think extends Agent {
|
|
|
5605
5753
|
}
|
|
5606
5754
|
/**
|
|
5607
5755
|
* Messages sent to a client on connect when no stream is active: the current
|
|
5608
|
-
* transcript, plus a replay of
|
|
5609
|
-
*
|
|
5610
|
-
*
|
|
5756
|
+
* transcript, plus a replay of an in-progress "recovering…" status (if any).
|
|
5757
|
+
*
|
|
5758
|
+
* A terminal error is deliberately NOT replayed here. A bare
|
|
5759
|
+
* `MSG_CHAT_RESPONSE` frame on connect is dropped by the `useAgentChat`
|
|
5760
|
+
* client because it never reaches a transport stream reader, so it cannot
|
|
5761
|
+
* become `useChat.error` — a failed turn would still look frozen (#1645).
|
|
5762
|
+
* The terminal outcome is instead surfaced over the resume handshake
|
|
5763
|
+
* (`_replayTerminalOnResume` → ACK → `_replayTerminalOnAck`), the only path
|
|
5764
|
+
* that lands on the stream reader.
|
|
5611
5765
|
*/
|
|
5612
5766
|
async _buildIdleConnectMessages() {
|
|
5613
5767
|
const messages = [{
|
|
5614
5768
|
type: MSG_CHAT_MESSAGES,
|
|
5615
5769
|
messages: this.messages
|
|
5616
5770
|
}];
|
|
5617
|
-
const pending = await this._pendingTerminalChatResponse();
|
|
5618
|
-
if (pending) messages.push({
|
|
5619
|
-
type: MSG_CHAT_RESPONSE,
|
|
5620
|
-
id: pending.requestId,
|
|
5621
|
-
body: pending.body,
|
|
5622
|
-
done: true,
|
|
5623
|
-
error: true
|
|
5624
|
-
});
|
|
5625
5771
|
const recovering = await this.ctx.storage.get(CHAT_RECOVERING_KEY);
|
|
5626
5772
|
if (recovering && Date.now() - (recovering.at ?? 0) < CHAT_RECOVERING_FLAG_TTL_MS) messages.push({
|
|
5627
5773
|
type: MSG_CHAT_RECOVERING,
|