@cloudflare/think 0.1.1 → 0.2.0
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/README.md +51 -107
- package/dist/{classPrivateFieldSet2-q3BTMj1l.js → classPrivateFieldGet2-B0jG-d4Z.js} +6 -6
- package/dist/extensions/index.d.ts +1 -1
- package/dist/extensions/index.js +2 -3
- package/dist/extensions/index.js.map +1 -1
- package/dist/{index-BlcvIdWK.d.ts → index-CAMRySsy.d.ts} +1 -1
- package/dist/{manager-JX4H9C6S.js → manager-BY5AZLVa.js} +8 -4
- package/dist/{manager-JX4H9C6S.js.map → manager-BY5AZLVa.js.map} +1 -1
- package/dist/think.d.ts +292 -183
- package/dist/think.js +948 -505
- package/dist/think.js.map +1 -1
- package/dist/tools/extensions.d.ts +1 -1
- package/dist/tools/extensions.js +1 -1
- package/package.json +10 -19
- package/dist/classPrivateMethodInitSpec-CvUe57wu.js +0 -7
- package/dist/index-C4OTSwUW.d.ts +0 -193
- package/dist/message-builder.d.ts +0 -51
- package/dist/message-builder.js +0 -217
- package/dist/message-builder.js.map +0 -1
- package/dist/session/index.d.ts +0 -22
- package/dist/session/index.js +0 -2
- package/dist/session-C6ZU_1zM.js +0 -507
- package/dist/session-C6ZU_1zM.js.map +0 -1
- package/dist/transport.d.ts +0 -69
- package/dist/transport.js +0 -166
- package/dist/transport.js.map +0 -1
package/dist/think.js
CHANGED
|
@@ -1,177 +1,67 @@
|
|
|
1
|
-
import { t as
|
|
2
|
-
import { applyChunkToParts } from "./message-builder.js";
|
|
3
|
-
import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldGet2, t as _classPrivateFieldSet2 } from "./classPrivateFieldSet2-q3BTMj1l.js";
|
|
1
|
+
import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-B0jG-d4Z.js";
|
|
4
2
|
import { convertToModelMessages, pruneMessages, stepCountIs, streamText } from "ai";
|
|
5
3
|
import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext } from "agents";
|
|
6
|
-
import {
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
const textEncoder = new TextEncoder();
|
|
10
|
-
/** Maximum serialized message size before compaction (bytes). 1.8MB with headroom below SQLite's 2MB limit. */
|
|
11
|
-
const ROW_MAX_BYTES = 18e5;
|
|
12
|
-
/** Measure UTF-8 byte length of a string. */
|
|
13
|
-
function byteLength(s) {
|
|
14
|
-
return textEncoder.encode(s).byteLength;
|
|
15
|
-
}
|
|
16
|
-
/**
|
|
17
|
-
* Sanitize a message for persistence by removing ephemeral provider-specific
|
|
18
|
-
* data that should not be stored or sent back in subsequent requests.
|
|
19
|
-
*
|
|
20
|
-
* 1. Strips OpenAI ephemeral fields (itemId, reasoningEncryptedContent)
|
|
21
|
-
* 2. Filters truly empty reasoning parts (no text, no remaining providerMetadata)
|
|
22
|
-
*/
|
|
23
|
-
function sanitizeMessage(message) {
|
|
24
|
-
const sanitizedParts = message.parts.map((part) => {
|
|
25
|
-
let sanitizedPart = part;
|
|
26
|
-
if ("providerMetadata" in sanitizedPart && sanitizedPart.providerMetadata && typeof sanitizedPart.providerMetadata === "object" && "openai" in sanitizedPart.providerMetadata) sanitizedPart = stripOpenAIMetadata(sanitizedPart, "providerMetadata");
|
|
27
|
-
if ("callProviderMetadata" in sanitizedPart && sanitizedPart.callProviderMetadata && typeof sanitizedPart.callProviderMetadata === "object" && "openai" in sanitizedPart.callProviderMetadata) sanitizedPart = stripOpenAIMetadata(sanitizedPart, "callProviderMetadata");
|
|
28
|
-
return sanitizedPart;
|
|
29
|
-
}).filter((part) => {
|
|
30
|
-
if (part.type === "reasoning") {
|
|
31
|
-
const reasoningPart = part;
|
|
32
|
-
if (!reasoningPart.text || reasoningPart.text.trim() === "") {
|
|
33
|
-
if ("providerMetadata" in reasoningPart && reasoningPart.providerMetadata && typeof reasoningPart.providerMetadata === "object" && Object.keys(reasoningPart.providerMetadata).length > 0) return true;
|
|
34
|
-
return false;
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
return true;
|
|
38
|
-
});
|
|
39
|
-
return {
|
|
40
|
-
...message,
|
|
41
|
-
parts: sanitizedParts
|
|
42
|
-
};
|
|
43
|
-
}
|
|
44
|
-
/**
|
|
45
|
-
* Strip OpenAI-specific ephemeral fields from a metadata object.
|
|
46
|
-
*/
|
|
47
|
-
function stripOpenAIMetadata(part, metadataKey) {
|
|
48
|
-
const metadata = part[metadataKey];
|
|
49
|
-
if (!metadata?.openai) return part;
|
|
50
|
-
const { itemId: _itemId, reasoningEncryptedContent: _rec, ...restOpenai } = metadata.openai;
|
|
51
|
-
const hasOtherOpenaiFields = Object.keys(restOpenai).length > 0;
|
|
52
|
-
const { openai: _openai, ...restMetadata } = metadata;
|
|
53
|
-
let newMetadata;
|
|
54
|
-
if (hasOtherOpenaiFields) newMetadata = {
|
|
55
|
-
...restMetadata,
|
|
56
|
-
openai: restOpenai
|
|
57
|
-
};
|
|
58
|
-
else if (Object.keys(restMetadata).length > 0) newMetadata = restMetadata;
|
|
59
|
-
const { [metadataKey]: _oldMeta, ...restPart } = part;
|
|
60
|
-
if (newMetadata) return {
|
|
61
|
-
...restPart,
|
|
62
|
-
[metadataKey]: newMetadata
|
|
63
|
-
};
|
|
64
|
-
return restPart;
|
|
65
|
-
}
|
|
66
|
-
/**
|
|
67
|
-
* Enforce SQLite row size limits by compacting tool outputs and text parts
|
|
68
|
-
* when a serialized message exceeds the safety threshold (1.8MB).
|
|
69
|
-
*
|
|
70
|
-
* Compaction strategy:
|
|
71
|
-
* 1. Compact tool outputs over 1KB (replace with summary)
|
|
72
|
-
* 2. If still too big, truncate text parts from oldest to newest
|
|
73
|
-
*/
|
|
74
|
-
function enforceRowSizeLimit(message) {
|
|
75
|
-
let json = JSON.stringify(message);
|
|
76
|
-
let size = byteLength(json);
|
|
77
|
-
if (size <= ROW_MAX_BYTES) return message;
|
|
78
|
-
if (message.role !== "assistant") return truncateTextParts(message);
|
|
79
|
-
const compactedParts = message.parts.map((part) => {
|
|
80
|
-
if ("output" in part && "toolCallId" in part && "state" in part && part.state === "output-available") {
|
|
81
|
-
const outputJson = JSON.stringify(part.output);
|
|
82
|
-
if (outputJson.length > 1e3) return {
|
|
83
|
-
...part,
|
|
84
|
-
output: `This tool output was too large to persist in storage (${outputJson.length} bytes). If the user asks about this data, suggest re-running the tool. Preview: ${outputJson.slice(0, 500)}...`
|
|
85
|
-
};
|
|
86
|
-
}
|
|
87
|
-
return part;
|
|
88
|
-
});
|
|
89
|
-
let result = {
|
|
90
|
-
...message,
|
|
91
|
-
parts: compactedParts
|
|
92
|
-
};
|
|
93
|
-
json = JSON.stringify(result);
|
|
94
|
-
size = byteLength(json);
|
|
95
|
-
if (size <= ROW_MAX_BYTES) return result;
|
|
96
|
-
return truncateTextParts(result);
|
|
97
|
-
}
|
|
98
|
-
/**
|
|
99
|
-
* Truncate text parts to fit within the row size limit.
|
|
100
|
-
*/
|
|
101
|
-
function truncateTextParts(message) {
|
|
102
|
-
const parts = [...message.parts];
|
|
103
|
-
for (let i = 0; i < parts.length; i++) {
|
|
104
|
-
const part = parts[i];
|
|
105
|
-
if (part.type === "text" && "text" in part) {
|
|
106
|
-
const text = part.text;
|
|
107
|
-
if (text.length > 1e3) {
|
|
108
|
-
parts[i] = {
|
|
109
|
-
...part,
|
|
110
|
-
text: `[Text truncated for storage (${text.length} chars). First 500 chars: ${text.slice(0, 500)}...]`
|
|
111
|
-
};
|
|
112
|
-
const candidate = {
|
|
113
|
-
...message,
|
|
114
|
-
parts
|
|
115
|
-
};
|
|
116
|
-
if (byteLength(JSON.stringify(candidate)) <= ROW_MAX_BYTES) break;
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
return {
|
|
121
|
-
...message,
|
|
122
|
-
parts
|
|
123
|
-
};
|
|
124
|
-
}
|
|
125
|
-
//#endregion
|
|
4
|
+
import { AbortRegistry, CHAT_MESSAGE_TYPES, ContinuationState, ResumableStream, StreamAccumulator, TurnQueue, applyChunkToParts, applyToolUpdate, createToolsFromClientSchemas, enforceRowSizeLimit, parseProtocolMessage, sanitizeMessage, toolApprovalUpdate, toolResultUpdate } from "agents/chat";
|
|
5
|
+
import { Session, Session as Session$1 } from "agents/experimental/memory/session";
|
|
6
|
+
import { truncateOlderMessages } from "agents/experimental/memory/utils";
|
|
126
7
|
//#region src/think.ts
|
|
127
|
-
const
|
|
128
|
-
const
|
|
129
|
-
const
|
|
130
|
-
const
|
|
131
|
-
const
|
|
132
|
-
const
|
|
133
|
-
|
|
8
|
+
const MSG_CHAT_MESSAGES = CHAT_MESSAGE_TYPES.CHAT_MESSAGES;
|
|
9
|
+
const MSG_CHAT_RESPONSE = CHAT_MESSAGE_TYPES.USE_CHAT_RESPONSE;
|
|
10
|
+
const MSG_CHAT_CLEAR = CHAT_MESSAGE_TYPES.CHAT_CLEAR;
|
|
11
|
+
const MSG_STREAM_RESUMING = CHAT_MESSAGE_TYPES.STREAM_RESUMING;
|
|
12
|
+
const MSG_STREAM_RESUME_NONE = CHAT_MESSAGE_TYPES.STREAM_RESUME_NONE;
|
|
13
|
+
const MSG_MESSAGE_UPDATED = CHAT_MESSAGE_TYPES.MESSAGE_UPDATED;
|
|
14
|
+
const TIMED_OUT = Symbol("timed-out");
|
|
134
15
|
var _configCache = /* @__PURE__ */ new WeakMap();
|
|
135
16
|
/**
|
|
136
|
-
*
|
|
137
|
-
*
|
|
138
|
-
* Works as both a top-level agent (WebSocket chat protocol) and a
|
|
139
|
-
* sub-agent (RPC streaming via `chat()`).
|
|
17
|
+
* An opinionated chat agent base class.
|
|
140
18
|
*
|
|
141
19
|
* @experimental Requires the `"experimental"` compatibility flag.
|
|
142
20
|
*/
|
|
143
|
-
var Think = class extends
|
|
144
|
-
constructor(
|
|
145
|
-
super(
|
|
146
|
-
this.
|
|
147
|
-
this.
|
|
148
|
-
this.
|
|
149
|
-
this.
|
|
150
|
-
this.
|
|
151
|
-
this.
|
|
152
|
-
this.
|
|
153
|
-
|
|
21
|
+
var Think = class Think extends Agent {
|
|
22
|
+
constructor(ctx, env) {
|
|
23
|
+
super(ctx, env);
|
|
24
|
+
this.waitForMcpConnections = false;
|
|
25
|
+
this.messageConcurrency = "queue";
|
|
26
|
+
this.unstable_chatRecovery = false;
|
|
27
|
+
this._aborts = new AbortRegistry();
|
|
28
|
+
this._turnQueue = new TurnQueue();
|
|
29
|
+
this._pendingResumeConnections = /* @__PURE__ */ new Set();
|
|
30
|
+
this._continuation = new ContinuationState();
|
|
31
|
+
this._continuationTimer = null;
|
|
32
|
+
this._insideResponseHook = false;
|
|
33
|
+
this._pendingInteractionPromise = null;
|
|
34
|
+
this._submitSequence = 0;
|
|
35
|
+
this._latestOverlappingSubmitSequence = 0;
|
|
36
|
+
this._activeDebounceTimer = null;
|
|
37
|
+
this._activeDebounceResolve = null;
|
|
154
38
|
_classPrivateFieldInitSpec(this, _configCache, null);
|
|
39
|
+
const _onStart = this.onStart.bind(this);
|
|
40
|
+
this.onStart = async () => {
|
|
41
|
+
const baseSession = Session$1.create(this);
|
|
42
|
+
this.session = await this.configureSession(baseSession);
|
|
43
|
+
this.session.getHistory();
|
|
44
|
+
this._resumableStream = new ResumableStream(this.sql.bind(this));
|
|
45
|
+
this._restoreClientTools();
|
|
46
|
+
this._restoreBody();
|
|
47
|
+
this._setupProtocolHandlers();
|
|
48
|
+
await _onStart();
|
|
49
|
+
};
|
|
155
50
|
}
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
`;
|
|
163
|
-
_classPrivateFieldSet2(_configTableReady, this, true);
|
|
51
|
+
/**
|
|
52
|
+
* Conversation history. Computed from the active session.
|
|
53
|
+
* Always fresh — reads from Session's tree-structured storage.
|
|
54
|
+
*/
|
|
55
|
+
get messages() {
|
|
56
|
+
return this.session.getHistory();
|
|
164
57
|
}
|
|
165
58
|
/**
|
|
166
59
|
* Persist a typed configuration object.
|
|
167
|
-
* Stored in
|
|
60
|
+
* Stored in Session's assistant_config table — survives restarts and hibernation.
|
|
168
61
|
*/
|
|
169
62
|
configure(config) {
|
|
170
|
-
this._ensureConfigTable();
|
|
171
63
|
const json = JSON.stringify(config);
|
|
172
|
-
this.
|
|
173
|
-
INSERT OR REPLACE INTO _think_config (key, value) VALUES ('config', ${json})
|
|
174
|
-
`;
|
|
64
|
+
this._configSet("_think_config", json);
|
|
175
65
|
_classPrivateFieldSet2(_configCache, this, config);
|
|
176
66
|
}
|
|
177
67
|
/**
|
|
@@ -179,28 +69,36 @@ var Think = class extends ThinkBase {
|
|
|
179
69
|
*/
|
|
180
70
|
getConfig() {
|
|
181
71
|
if (_classPrivateFieldGet2(_configCache, this)) return _classPrivateFieldGet2(_configCache, this);
|
|
182
|
-
this.
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
`;
|
|
186
|
-
if (rows.length > 0) {
|
|
187
|
-
_classPrivateFieldSet2(_configCache, this, JSON.parse(rows[0].value));
|
|
72
|
+
const raw = this._configGet("_think_config");
|
|
73
|
+
if (raw !== void 0) {
|
|
74
|
+
_classPrivateFieldSet2(_configCache, this, JSON.parse(raw));
|
|
188
75
|
return _classPrivateFieldGet2(_configCache, this);
|
|
189
76
|
}
|
|
190
77
|
return null;
|
|
191
78
|
}
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
79
|
+
_configSet(key, value) {
|
|
80
|
+
const sessionId = this._sessionId();
|
|
81
|
+
this.sql`
|
|
82
|
+
INSERT OR REPLACE INTO assistant_config (session_id, key, value)
|
|
83
|
+
VALUES (${sessionId}, ${key}, ${value})
|
|
84
|
+
`;
|
|
85
|
+
}
|
|
86
|
+
_configGet(key) {
|
|
87
|
+
const sessionId = this._sessionId();
|
|
88
|
+
return this.sql`
|
|
89
|
+
SELECT value FROM assistant_config
|
|
90
|
+
WHERE session_id = ${sessionId} AND key = ${key}
|
|
91
|
+
`[0]?.value;
|
|
92
|
+
}
|
|
93
|
+
_configDelete(key) {
|
|
94
|
+
const sessionId = this._sessionId();
|
|
95
|
+
this.sql`
|
|
96
|
+
DELETE FROM assistant_config
|
|
97
|
+
WHERE session_id = ${sessionId} AND key = ${key}
|
|
98
|
+
`;
|
|
99
|
+
}
|
|
100
|
+
_sessionId() {
|
|
101
|
+
return "";
|
|
204
102
|
}
|
|
205
103
|
/**
|
|
206
104
|
* Return the language model to use for inference.
|
|
@@ -212,101 +110,119 @@ var Think = class extends ThinkBase {
|
|
|
212
110
|
}
|
|
213
111
|
/**
|
|
214
112
|
* Return the system prompt for the assistant.
|
|
215
|
-
*
|
|
113
|
+
* Used as fallback when no context blocks are configured via `configureSession`.
|
|
216
114
|
*/
|
|
217
115
|
getSystemPrompt() {
|
|
218
116
|
return "You are a helpful assistant.";
|
|
219
117
|
}
|
|
220
|
-
/**
|
|
221
|
-
* Return the tools available to the assistant.
|
|
222
|
-
* Override to provide workspace tools, custom tools, etc.
|
|
223
|
-
*/
|
|
118
|
+
/** Return the tools available to the assistant. */
|
|
224
119
|
getTools() {
|
|
225
120
|
return {};
|
|
226
121
|
}
|
|
227
|
-
/**
|
|
228
|
-
* Return the maximum number of tool-call steps per turn.
|
|
229
|
-
*/
|
|
122
|
+
/** Return the maximum number of tool-call steps per turn. */
|
|
230
123
|
getMaxSteps() {
|
|
231
124
|
return 10;
|
|
232
125
|
}
|
|
233
126
|
/**
|
|
234
|
-
*
|
|
127
|
+
* Configure the session. Called once during `onStart`.
|
|
128
|
+
* Override to add context blocks, compaction, search, skills.
|
|
129
|
+
*
|
|
130
|
+
* The base session is pre-created with `Session.create(this)`.
|
|
131
|
+
* Return it with builder methods chained.
|
|
132
|
+
*
|
|
133
|
+
* Async is supported — use it to read configuration from KV, D1,
|
|
134
|
+
* or R2 before setting up context blocks.
|
|
135
|
+
*
|
|
136
|
+
* @example
|
|
137
|
+
* ```typescript
|
|
138
|
+
* configureSession(session: Session) {
|
|
139
|
+
* return session
|
|
140
|
+
* .withContext("memory", { description: "Learned facts", maxTokens: 2000 })
|
|
141
|
+
* .withCachedPrompt();
|
|
142
|
+
* }
|
|
143
|
+
* ```
|
|
235
144
|
*
|
|
236
|
-
*
|
|
237
|
-
*
|
|
145
|
+
* @example Async configuration from KV
|
|
146
|
+
* ```typescript
|
|
147
|
+
* async configureSession(session: Session) {
|
|
148
|
+
* const config = await this.env.KV.get("agent-config", "json");
|
|
149
|
+
* return session
|
|
150
|
+
* .withContext("memory", { maxTokens: config.memoryTokens })
|
|
151
|
+
* .withCachedPrompt();
|
|
152
|
+
* }
|
|
153
|
+
* ```
|
|
238
154
|
*/
|
|
239
|
-
|
|
240
|
-
return
|
|
241
|
-
}
|
|
242
|
-
async _hostReadFile(path) {
|
|
243
|
-
const ws = this.getWorkspace();
|
|
244
|
-
if (!ws) throw new Error("No workspace available on this agent");
|
|
245
|
-
return ws.readFile(path);
|
|
246
|
-
}
|
|
247
|
-
async _hostWriteFile(path, content) {
|
|
248
|
-
const ws = this.getWorkspace();
|
|
249
|
-
if (!ws) throw new Error("No workspace available on this agent");
|
|
250
|
-
await ws.writeFile(path, content);
|
|
251
|
-
}
|
|
252
|
-
async _hostDeleteFile(path) {
|
|
253
|
-
const ws = this.getWorkspace();
|
|
254
|
-
if (!ws) throw new Error("No workspace available on this agent");
|
|
255
|
-
return ws.deleteFile(path);
|
|
256
|
-
}
|
|
257
|
-
async _hostListFiles(dir) {
|
|
258
|
-
const ws = this.getWorkspace();
|
|
259
|
-
if (!ws) throw new Error("No workspace available on this agent");
|
|
260
|
-
return ws.readDir(dir);
|
|
155
|
+
configureSession(session) {
|
|
156
|
+
return session;
|
|
261
157
|
}
|
|
262
158
|
/**
|
|
263
|
-
* Assemble the
|
|
264
|
-
*
|
|
265
|
-
*
|
|
159
|
+
* Assemble context for the LLM from the current session state.
|
|
160
|
+
*
|
|
161
|
+
* Default implementation:
|
|
162
|
+
* 1. Freezes the system prompt from context blocks (falls back to getSystemPrompt())
|
|
163
|
+
* 2. Gets history from session
|
|
164
|
+
* 3. Applies read-time truncation (old tool outputs, long text)
|
|
165
|
+
* 4. Converts to model messages with tool call pruning
|
|
166
|
+
*
|
|
167
|
+
* Returns { system, messages } so the caller has both.
|
|
266
168
|
*/
|
|
267
169
|
async assembleContext() {
|
|
268
|
-
return
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
170
|
+
return {
|
|
171
|
+
system: await this.session.freezeSystemPrompt() || this.getSystemPrompt(),
|
|
172
|
+
messages: pruneMessages({
|
|
173
|
+
messages: await convertToModelMessages(truncateOlderMessages(this.session.getHistory())),
|
|
174
|
+
toolCalls: "before-last-2-messages"
|
|
175
|
+
})
|
|
176
|
+
};
|
|
272
177
|
}
|
|
273
178
|
/**
|
|
274
179
|
* Handle a chat turn and return the streaming result.
|
|
275
180
|
*
|
|
276
181
|
* The default implementation runs the agentic loop:
|
|
277
|
-
* 1.
|
|
278
|
-
* 2.
|
|
279
|
-
*
|
|
280
|
-
* Override for full control over inference (e.g. different models per turn,
|
|
281
|
-
* RAG pipelines, routing to specialized sub-agents, etc.).
|
|
182
|
+
* 1. Merge tools: getTools() + clientTools + session context tools + options.tools
|
|
183
|
+
* 2. Assemble context (system prompt + messages) from session state
|
|
184
|
+
* 3. Call `streamText` with the model, system prompt, tools, and step limit
|
|
282
185
|
*
|
|
283
|
-
*
|
|
284
|
-
* latest message persisted to the current session.
|
|
186
|
+
* Override for full control over inference.
|
|
285
187
|
*
|
|
286
188
|
* @returns A result with `toUIMessageStream()` — AI SDK's `streamText()`
|
|
287
189
|
* return value satisfies this interface.
|
|
288
190
|
*/
|
|
289
191
|
async onChatMessage(options) {
|
|
290
192
|
const baseTools = this.getTools();
|
|
291
|
-
const
|
|
193
|
+
const clientToolSet = createToolsFromClientSchemas(options?.clientTools);
|
|
194
|
+
const contextTools = await this.session.tools();
|
|
195
|
+
const tools = {
|
|
292
196
|
...baseTools,
|
|
293
|
-
...
|
|
294
|
-
|
|
197
|
+
...clientToolSet,
|
|
198
|
+
...contextTools,
|
|
199
|
+
...options?.tools
|
|
200
|
+
};
|
|
201
|
+
const { system, messages } = await this.assembleContext();
|
|
202
|
+
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.");
|
|
295
203
|
return streamText({
|
|
296
204
|
model: this.getModel(),
|
|
297
|
-
system
|
|
298
|
-
messages
|
|
205
|
+
system,
|
|
206
|
+
messages,
|
|
299
207
|
tools,
|
|
300
208
|
stopWhen: stepCountIs(this.getMaxSteps()),
|
|
301
209
|
abortSignal: options?.signal
|
|
302
210
|
});
|
|
303
211
|
}
|
|
304
212
|
/**
|
|
213
|
+
* Called after a chat turn completes and the assistant message has been
|
|
214
|
+
* persisted. The turn lock is released before this hook runs, so it is
|
|
215
|
+
* safe to call other methods from inside.
|
|
216
|
+
*
|
|
217
|
+
* Fires for all turn completion paths: WebSocket chat requests,
|
|
218
|
+
* sub-agent RPC, and auto-continuation.
|
|
219
|
+
*
|
|
220
|
+
* Override for logging, chaining, analytics, usage tracking.
|
|
221
|
+
*/
|
|
222
|
+
onChatResponse(_result) {}
|
|
223
|
+
/**
|
|
305
224
|
* Handle an error that occurred during a chat turn.
|
|
306
225
|
* Override to customize error handling (e.g. logging, metrics).
|
|
307
|
-
*
|
|
308
|
-
* @param error The error that occurred
|
|
309
|
-
* @returns The error (or a wrapped version) to propagate
|
|
310
226
|
*/
|
|
311
227
|
onChatError(error) {
|
|
312
228
|
return error;
|
|
@@ -316,214 +232,420 @@ var Think = class extends ThinkBase {
|
|
|
316
232
|
* stream UIMessageChunk events via callback, and persist the
|
|
317
233
|
* assistant's response.
|
|
318
234
|
*
|
|
319
|
-
*
|
|
320
|
-
* so the user doesn't lose context.
|
|
321
|
-
*
|
|
322
|
-
* @param userMessage The user's message (string or UIMessage for multi-modal)
|
|
235
|
+
* @param userMessage The user's message (string or UIMessage)
|
|
323
236
|
* @param callback Streaming callback (typically an RpcTarget from the parent)
|
|
324
237
|
* @param options Optional chat options (e.g. AbortSignal)
|
|
325
238
|
*/
|
|
326
239
|
async chat(userMessage, callback, options) {
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
240
|
+
const requestId = crypto.randomUUID();
|
|
241
|
+
await this._turnQueue.enqueue(requestId, async () => {
|
|
242
|
+
const userMsg = typeof userMessage === "string" ? {
|
|
243
|
+
id: crypto.randomUUID(),
|
|
244
|
+
role: "user",
|
|
245
|
+
parts: [{
|
|
246
|
+
type: "text",
|
|
247
|
+
text: userMessage
|
|
248
|
+
}]
|
|
249
|
+
} : userMessage;
|
|
250
|
+
await this.session.appendMessage(userMsg);
|
|
251
|
+
const accumulator = new StreamAccumulator({ messageId: crypto.randomUUID() });
|
|
252
|
+
try {
|
|
253
|
+
const result = await this.onChatMessage({
|
|
254
|
+
signal: options?.signal,
|
|
255
|
+
tools: options?.tools,
|
|
256
|
+
continuation: false
|
|
257
|
+
});
|
|
258
|
+
let aborted = false;
|
|
259
|
+
for await (const chunk of result.toUIMessageStream()) {
|
|
260
|
+
if (options?.signal?.aborted) {
|
|
261
|
+
aborted = true;
|
|
262
|
+
break;
|
|
263
|
+
}
|
|
264
|
+
accumulator.applyChunk(chunk);
|
|
265
|
+
await callback.onEvent(JSON.stringify(chunk));
|
|
353
266
|
}
|
|
354
|
-
|
|
355
|
-
|
|
267
|
+
const assistantMsg = accumulator.toMessage();
|
|
268
|
+
this._persistAssistantMessage(assistantMsg);
|
|
269
|
+
if (!aborted) {
|
|
270
|
+
await callback.onDone();
|
|
271
|
+
await this._fireResponseHook({
|
|
272
|
+
message: assistantMsg,
|
|
273
|
+
requestId,
|
|
274
|
+
continuation: false,
|
|
275
|
+
status: "completed"
|
|
276
|
+
});
|
|
277
|
+
} else await this._fireResponseHook({
|
|
278
|
+
message: assistantMsg,
|
|
279
|
+
requestId,
|
|
280
|
+
continuation: false,
|
|
281
|
+
status: "aborted"
|
|
282
|
+
});
|
|
283
|
+
} catch (error) {
|
|
284
|
+
const assistantMsg = accumulator.parts.length > 0 ? accumulator.toMessage() : null;
|
|
285
|
+
if (assistantMsg) this._persistAssistantMessage(assistantMsg);
|
|
286
|
+
const wrapped = this.onChatError(error);
|
|
287
|
+
const errorMessage = wrapped instanceof Error ? wrapped.message : String(wrapped);
|
|
288
|
+
if (assistantMsg) await this._fireResponseHook({
|
|
289
|
+
message: assistantMsg,
|
|
290
|
+
requestId,
|
|
291
|
+
continuation: false,
|
|
292
|
+
status: "error",
|
|
293
|
+
error: errorMessage
|
|
294
|
+
});
|
|
295
|
+
if (callback.onError) await callback.onError(errorMessage);
|
|
296
|
+
else throw wrapped;
|
|
356
297
|
}
|
|
357
|
-
|
|
358
|
-
if (!aborted) await callback.onDone();
|
|
359
|
-
} catch (error) {
|
|
360
|
-
if (assistantMsg.parts.length > 0) this._persistAssistantMessage(assistantMsg);
|
|
361
|
-
const wrapped = this.onChatError(error);
|
|
362
|
-
const errorMessage = wrapped instanceof Error ? wrapped.message : String(wrapped);
|
|
363
|
-
if (callback.onError) await callback.onError(errorMessage);
|
|
364
|
-
else throw wrapped;
|
|
365
|
-
}
|
|
366
|
-
}
|
|
367
|
-
getSessions() {
|
|
368
|
-
return this.sessions.list();
|
|
369
|
-
}
|
|
370
|
-
createSession(name) {
|
|
371
|
-
const session = this.sessions.create(name);
|
|
372
|
-
this._sessionId = session.id;
|
|
373
|
-
this.messages = [];
|
|
374
|
-
this._broadcastMessages();
|
|
375
|
-
return session;
|
|
298
|
+
});
|
|
376
299
|
}
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
this._sessionId = sessionId;
|
|
380
|
-
this.messages = this.sessions.getHistory(sessionId);
|
|
381
|
-
this._broadcastMessages();
|
|
300
|
+
/** Get the conversation history as UIMessage[]. */
|
|
301
|
+
getMessages() {
|
|
382
302
|
return this.messages;
|
|
383
303
|
}
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
this.
|
|
387
|
-
if (this._sessionId === sessionId) {
|
|
388
|
-
this._sessionId = null;
|
|
389
|
-
this.messages = [];
|
|
390
|
-
this._broadcastMessages();
|
|
391
|
-
}
|
|
392
|
-
}
|
|
393
|
-
renameSession(sessionId, name) {
|
|
394
|
-
if (!this.sessions.get(sessionId)) throw new Error(`Session not found: ${sessionId}`);
|
|
395
|
-
this.sessions.rename(sessionId, name);
|
|
396
|
-
}
|
|
397
|
-
getCurrentSessionId() {
|
|
398
|
-
return this._sessionId;
|
|
399
|
-
}
|
|
400
|
-
/**
|
|
401
|
-
* Get the current session info, or null if no session exists yet.
|
|
402
|
-
*/
|
|
403
|
-
getSession() {
|
|
404
|
-
if (!this._sessionId) return null;
|
|
405
|
-
return this.sessions.get(this._sessionId);
|
|
304
|
+
/** Clear all messages from storage. */
|
|
305
|
+
clearMessages() {
|
|
306
|
+
this.session.clearMessages();
|
|
406
307
|
}
|
|
407
308
|
/**
|
|
408
|
-
*
|
|
309
|
+
* Inject messages and trigger a model turn — without a WebSocket request.
|
|
310
|
+
*
|
|
311
|
+
* Use for scheduled responses, webhook-triggered turns, proactive agents,
|
|
312
|
+
* or chaining from `onChatResponse`.
|
|
313
|
+
*
|
|
314
|
+
* Accepts static messages or a callback that derives messages from the
|
|
315
|
+
* current state (useful when multiple calls queue up — the callback runs
|
|
316
|
+
* with the latest messages when the turn actually starts).
|
|
317
|
+
*
|
|
318
|
+
* @example Scheduled follow-up
|
|
319
|
+
* ```typescript
|
|
320
|
+
* async onScheduled() {
|
|
321
|
+
* await this.saveMessages([{
|
|
322
|
+
* id: crypto.randomUUID(),
|
|
323
|
+
* role: "user",
|
|
324
|
+
* parts: [{ type: "text", text: "Time for your daily summary." }]
|
|
325
|
+
* }]);
|
|
326
|
+
* }
|
|
327
|
+
* ```
|
|
328
|
+
*
|
|
329
|
+
* @example Function form
|
|
330
|
+
* ```typescript
|
|
331
|
+
* await this.saveMessages((current) => [
|
|
332
|
+
* ...current,
|
|
333
|
+
* { id: crypto.randomUUID(), role: "user", parts: [{ type: "text", text: "Continue." }] }
|
|
334
|
+
* ]);
|
|
335
|
+
* ```
|
|
409
336
|
*/
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
337
|
+
async saveMessages(messages) {
|
|
338
|
+
const requestId = crypto.randomUUID();
|
|
339
|
+
const clientTools = this._lastClientTools;
|
|
340
|
+
const body = this._lastBody;
|
|
341
|
+
const epoch = this._turnQueue.generation;
|
|
342
|
+
let status = "completed";
|
|
343
|
+
await this.keepAliveWhile(async () => {
|
|
344
|
+
await this._turnQueue.enqueue(requestId, async () => {
|
|
345
|
+
const resolved = typeof messages === "function" ? await messages(this.messages) : messages;
|
|
346
|
+
if (this._turnQueue.generation !== epoch) {
|
|
347
|
+
status = "skipped";
|
|
348
|
+
return;
|
|
349
|
+
}
|
|
350
|
+
for (const msg of resolved) await this.session.appendMessage(msg);
|
|
351
|
+
this._broadcastMessages();
|
|
352
|
+
if (this._turnQueue.generation !== epoch) {
|
|
353
|
+
status = "skipped";
|
|
354
|
+
return;
|
|
355
|
+
}
|
|
356
|
+
const abortSignal = this._aborts.getSignal(requestId);
|
|
357
|
+
try {
|
|
358
|
+
const programmaticBody = async () => {
|
|
359
|
+
const result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
|
|
360
|
+
agent: this,
|
|
361
|
+
connection: void 0,
|
|
362
|
+
request: void 0,
|
|
363
|
+
email: void 0
|
|
364
|
+
}, () => this.onChatMessage({
|
|
365
|
+
signal: abortSignal,
|
|
366
|
+
clientTools,
|
|
367
|
+
body,
|
|
368
|
+
continuation: false
|
|
369
|
+
}));
|
|
370
|
+
if (result) await this._streamResult(requestId, result, abortSignal);
|
|
371
|
+
};
|
|
372
|
+
if (this.unstable_chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
|
|
373
|
+
await programmaticBody();
|
|
374
|
+
});
|
|
375
|
+
else await programmaticBody();
|
|
376
|
+
} finally {
|
|
377
|
+
this._aborts.remove(requestId);
|
|
378
|
+
}
|
|
379
|
+
});
|
|
380
|
+
});
|
|
381
|
+
if (this._turnQueue.generation !== epoch && status === "completed") status = "skipped";
|
|
382
|
+
return {
|
|
383
|
+
requestId,
|
|
384
|
+
status
|
|
385
|
+
};
|
|
413
386
|
}
|
|
414
387
|
/**
|
|
415
|
-
*
|
|
388
|
+
* Run a new LLM call following the last assistant message.
|
|
389
|
+
*
|
|
390
|
+
* The model sees the full conversation (including the last assistant
|
|
391
|
+
* response) and generates a new response. The new response is persisted
|
|
392
|
+
* as a separate assistant message. Building block for chat recovery
|
|
393
|
+
* (Phase 4), "generate more" buttons, and self-correction.
|
|
394
|
+
*
|
|
395
|
+
* Note: this creates a new message, not an append to the existing one.
|
|
396
|
+
* True continuation-as-append (chunk rewriting) is planned for Phase 4.
|
|
397
|
+
*
|
|
398
|
+
* Returns early with `status: "skipped"` if there is no assistant message
|
|
399
|
+
* to continue from.
|
|
416
400
|
*/
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
401
|
+
async continueLastTurn(body) {
|
|
402
|
+
const lastLeaf = this.session.getLatestLeaf();
|
|
403
|
+
if (!lastLeaf || lastLeaf.role !== "assistant") return {
|
|
404
|
+
requestId: "",
|
|
405
|
+
status: "skipped"
|
|
406
|
+
};
|
|
407
|
+
const requestId = crypto.randomUUID();
|
|
408
|
+
const clientTools = this._lastClientTools;
|
|
409
|
+
const resolvedBody = body ?? this._lastBody;
|
|
410
|
+
const epoch = this._turnQueue.generation;
|
|
411
|
+
let status = "completed";
|
|
412
|
+
await this.keepAliveWhile(async () => {
|
|
413
|
+
await this._turnQueue.enqueue(requestId, async () => {
|
|
414
|
+
if (this._turnQueue.generation !== epoch) {
|
|
415
|
+
status = "skipped";
|
|
416
|
+
return;
|
|
417
|
+
}
|
|
418
|
+
const abortSignal = this._aborts.getSignal(requestId);
|
|
419
|
+
try {
|
|
420
|
+
const continueTurnBody = async () => {
|
|
421
|
+
const result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
|
|
422
|
+
agent: this,
|
|
423
|
+
connection: void 0,
|
|
424
|
+
request: void 0,
|
|
425
|
+
email: void 0
|
|
426
|
+
}, () => this.onChatMessage({
|
|
427
|
+
signal: abortSignal,
|
|
428
|
+
clientTools,
|
|
429
|
+
body: resolvedBody,
|
|
430
|
+
continuation: true
|
|
431
|
+
}));
|
|
432
|
+
if (result) await this._streamResult(requestId, result, abortSignal, { continuation: true });
|
|
433
|
+
};
|
|
434
|
+
if (this.unstable_chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
|
|
435
|
+
await continueTurnBody();
|
|
436
|
+
});
|
|
437
|
+
else await continueTurnBody();
|
|
438
|
+
} finally {
|
|
439
|
+
this._aborts.remove(requestId);
|
|
440
|
+
}
|
|
441
|
+
});
|
|
442
|
+
});
|
|
443
|
+
if (this._turnQueue.generation !== epoch && status === "completed") status = "skipped";
|
|
444
|
+
return {
|
|
445
|
+
requestId,
|
|
446
|
+
status
|
|
447
|
+
};
|
|
420
448
|
}
|
|
421
449
|
/**
|
|
422
|
-
*
|
|
450
|
+
* Override to apply custom transformations to messages before they are
|
|
451
|
+
* persisted to Session storage. Runs after the built-in sanitization
|
|
452
|
+
* (OpenAI metadata stripping, row size enforcement) but before
|
|
453
|
+
* `session.appendMessage` / `session.updateMessage`.
|
|
454
|
+
*
|
|
455
|
+
* Use for redacting PII, stripping internal metadata, or custom compaction.
|
|
423
456
|
*/
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
this.sessions.clearMessages(this._sessionId);
|
|
427
|
-
this.messages = [];
|
|
428
|
-
this._persistedMessageCache.clear();
|
|
457
|
+
sanitizeMessageForPersistence(message) {
|
|
458
|
+
return message;
|
|
429
459
|
}
|
|
430
|
-
/**
|
|
431
|
-
* Wrap onMessage and onRequest to intercept the chat protocol.
|
|
432
|
-
* Unrecognized messages are forwarded to the user's handlers.
|
|
433
|
-
* @internal
|
|
434
|
-
*/
|
|
435
460
|
_setupProtocolHandlers() {
|
|
461
|
+
const _onConnect = this.onConnect.bind(this);
|
|
462
|
+
this.onConnect = async (connection, ctx) => {
|
|
463
|
+
if (this._resumableStream.hasActiveStream()) this._notifyStreamResuming(connection);
|
|
464
|
+
connection.send(JSON.stringify({
|
|
465
|
+
type: MSG_CHAT_MESSAGES,
|
|
466
|
+
messages: this.messages
|
|
467
|
+
}));
|
|
468
|
+
return _onConnect(connection, ctx);
|
|
469
|
+
};
|
|
470
|
+
const _onClose = this.onClose.bind(this);
|
|
471
|
+
this.onClose = async (connection, code, reason, wasClean) => {
|
|
472
|
+
this._pendingResumeConnections.delete(connection.id);
|
|
473
|
+
this._continuation.awaitingConnections.delete(connection.id);
|
|
474
|
+
if (this._continuation.pending?.connectionId === connection.id) this._continuation.pending = null;
|
|
475
|
+
if (this._continuation.activeConnectionId === connection.id) this._continuation.activeConnectionId = null;
|
|
476
|
+
return _onClose(connection, code, reason, wasClean);
|
|
477
|
+
};
|
|
436
478
|
const _onMessage = this.onMessage.bind(this);
|
|
437
479
|
this.onMessage = async (connection, message) => {
|
|
438
|
-
if (typeof message === "string")
|
|
439
|
-
const
|
|
440
|
-
if (
|
|
441
|
-
|
|
480
|
+
if (typeof message === "string") {
|
|
481
|
+
const event = parseProtocolMessage(message);
|
|
482
|
+
if (event) {
|
|
483
|
+
await this._handleProtocolEvent(connection, event);
|
|
484
|
+
return;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
442
487
|
return _onMessage(connection, message);
|
|
443
488
|
};
|
|
444
489
|
const _onRequest = this.onRequest.bind(this);
|
|
445
490
|
this.onRequest = async (request) => {
|
|
446
491
|
const url = new URL(request.url);
|
|
447
|
-
if (url.pathname === "/get-messages" || url.pathname.endsWith("/get-messages"))
|
|
448
|
-
const sessionId = url.searchParams.get("sessionId");
|
|
449
|
-
if (sessionId) {
|
|
450
|
-
if (!this.sessions.get(sessionId)) return Response.json({ error: "Session not found" }, { status: 404 });
|
|
451
|
-
return Response.json(this.sessions.getHistory(sessionId));
|
|
452
|
-
}
|
|
453
|
-
return Response.json(this.messages);
|
|
454
|
-
}
|
|
492
|
+
if (url.pathname === "/get-messages" || url.pathname.endsWith("/get-messages")) return Response.json(this.messages);
|
|
455
493
|
return _onRequest(request);
|
|
456
494
|
};
|
|
457
495
|
}
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
await this._handleChatRequest(connection,
|
|
468
|
-
|
|
496
|
+
async _handleProtocolEvent(connection, event) {
|
|
497
|
+
switch (event.type) {
|
|
498
|
+
case "stream-resume-request":
|
|
499
|
+
this._handleStreamResumeRequest(connection);
|
|
500
|
+
break;
|
|
501
|
+
case "stream-resume-ack":
|
|
502
|
+
this._handleStreamResumeAck(connection, event.id);
|
|
503
|
+
break;
|
|
504
|
+
case "chat-request":
|
|
505
|
+
if (event.init?.method === "POST") await this._handleChatRequest(connection, event);
|
|
506
|
+
break;
|
|
507
|
+
case "tool-result": {
|
|
508
|
+
if (event.clientTools && Array.isArray(event.clientTools) && event.clientTools.length > 0) {
|
|
509
|
+
this._lastClientTools = event.clientTools;
|
|
510
|
+
this._persistClientTools();
|
|
511
|
+
}
|
|
512
|
+
const resultPromise = Promise.resolve().then(() => {
|
|
513
|
+
this._applyToolResult(event.toolCallId, event.output, event.state, event.errorText);
|
|
514
|
+
return true;
|
|
515
|
+
});
|
|
516
|
+
this._pendingInteractionPromise = resultPromise;
|
|
517
|
+
resultPromise.finally(() => {
|
|
518
|
+
if (this._pendingInteractionPromise === resultPromise) this._pendingInteractionPromise = null;
|
|
519
|
+
}).catch(() => {});
|
|
520
|
+
if (event.autoContinue) this._scheduleAutoContinuation(connection);
|
|
521
|
+
break;
|
|
469
522
|
}
|
|
523
|
+
case "tool-approval": {
|
|
524
|
+
const approvalPromise = Promise.resolve().then(() => {
|
|
525
|
+
this._applyToolApproval(event.toolCallId, event.approved);
|
|
526
|
+
return true;
|
|
527
|
+
});
|
|
528
|
+
this._pendingInteractionPromise = approvalPromise;
|
|
529
|
+
approvalPromise.finally(() => {
|
|
530
|
+
if (this._pendingInteractionPromise === approvalPromise) this._pendingInteractionPromise = null;
|
|
531
|
+
}).catch(() => {});
|
|
532
|
+
if (event.autoContinue) this._scheduleAutoContinuation(connection);
|
|
533
|
+
break;
|
|
534
|
+
}
|
|
535
|
+
case "clear":
|
|
536
|
+
this._handleClear(connection);
|
|
537
|
+
break;
|
|
538
|
+
case "cancel":
|
|
539
|
+
this._aborts.cancel(event.id);
|
|
540
|
+
break;
|
|
541
|
+
case "messages": break;
|
|
470
542
|
}
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
if (
|
|
476
|
-
|
|
477
|
-
|
|
543
|
+
}
|
|
544
|
+
_handleStreamResumeRequest(connection) {
|
|
545
|
+
if (this._resumableStream.hasActiveStream()) if (this._continuation.activeRequestId === this._resumableStream.activeRequestId && this._continuation.activeConnectionId !== null && this._continuation.activeConnectionId !== connection.id) connection.send(JSON.stringify({ type: MSG_STREAM_RESUME_NONE }));
|
|
546
|
+
else this._notifyStreamResuming(connection);
|
|
547
|
+
else if (this._continuation.pending !== null && this._continuation.pending.connectionId === connection.id) this._continuation.awaitingConnections.set(connection.id, connection);
|
|
548
|
+
else connection.send(JSON.stringify({ type: MSG_STREAM_RESUME_NONE }));
|
|
549
|
+
}
|
|
550
|
+
_handleStreamResumeAck(connection, requestId) {
|
|
551
|
+
this._pendingResumeConnections.delete(connection.id);
|
|
552
|
+
if (this._resumableStream.hasActiveStream() && this._resumableStream.activeRequestId === requestId) {
|
|
553
|
+
const orphanedStreamId = this._resumableStream.replayChunks(connection, this._resumableStream.activeRequestId);
|
|
554
|
+
if (orphanedStreamId) this._persistOrphanedStream(orphanedStreamId);
|
|
478
555
|
}
|
|
479
|
-
return false;
|
|
480
556
|
}
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
* 2. Ensure a session exists
|
|
485
|
-
* 3. Persist user messages to session
|
|
486
|
-
* 4. Call onChatMessage
|
|
487
|
-
* 5. Stream response back to clients
|
|
488
|
-
* 6. Persist assistant message to session
|
|
489
|
-
* @internal
|
|
490
|
-
*/
|
|
491
|
-
async _handleChatRequest(connection, data) {
|
|
492
|
-
const init = data.init;
|
|
493
|
-
if (!init?.body) return;
|
|
494
|
-
let parsed;
|
|
557
|
+
async _handleChatRequest(connection, event) {
|
|
558
|
+
if (!event.init?.body) return;
|
|
559
|
+
let rawParsed;
|
|
495
560
|
try {
|
|
496
|
-
|
|
561
|
+
rawParsed = JSON.parse(event.init.body);
|
|
497
562
|
} catch {
|
|
498
563
|
return;
|
|
499
564
|
}
|
|
500
|
-
const incomingMessages =
|
|
565
|
+
const { messages: incomingMessages, clientTools: rawClientTools, trigger: rawTrigger, ...customBody } = rawParsed;
|
|
501
566
|
if (!Array.isArray(incomingMessages)) return;
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
567
|
+
const isRegeneration = rawTrigger === "regenerate-message";
|
|
568
|
+
const isSubmitMessage = !isRegeneration;
|
|
569
|
+
const requestId = event.id;
|
|
570
|
+
const concurrencyDecision = this._getSubmitConcurrencyDecision(isSubmitMessage);
|
|
571
|
+
if (concurrencyDecision.action === "drop") {
|
|
572
|
+
this._rollbackDroppedSubmit(connection);
|
|
573
|
+
this._completeSkippedRequest(connection, requestId);
|
|
574
|
+
return;
|
|
575
|
+
}
|
|
576
|
+
const requestClientTools = rawClientTools && rawClientTools.length > 0 ? rawClientTools : void 0;
|
|
577
|
+
if (requestClientTools) {
|
|
578
|
+
this._lastClientTools = requestClientTools;
|
|
579
|
+
this._persistClientTools();
|
|
580
|
+
} else if (rawClientTools !== void 0) {
|
|
581
|
+
this._lastClientTools = void 0;
|
|
582
|
+
this._persistClientTools();
|
|
583
|
+
}
|
|
584
|
+
this._lastBody = Object.keys(customBody).length > 0 ? customBody : void 0;
|
|
585
|
+
this._persistBody();
|
|
586
|
+
const clientToolsForTurn = this._lastClientTools;
|
|
587
|
+
const bodyForTurn = this._lastBody;
|
|
588
|
+
let branchParentId;
|
|
589
|
+
if (isRegeneration && incomingMessages.length > 0) branchParentId = incomingMessages[incomingMessages.length - 1].id;
|
|
590
|
+
for (const msg of incomingMessages) await this.session.appendMessage(msg);
|
|
505
591
|
this._broadcastMessages([connection.id]);
|
|
506
|
-
const
|
|
507
|
-
const
|
|
508
|
-
this._abortControllers.set(requestId, abortController);
|
|
592
|
+
const abortSignal = this._aborts.getSignal(requestId);
|
|
593
|
+
const epoch = this._turnQueue.generation;
|
|
509
594
|
try {
|
|
510
595
|
await this.keepAliveWhile(async () => {
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
596
|
+
if ((await this._turnQueue.enqueue(requestId, async () => {
|
|
597
|
+
if (this._isSupersededSubmit(concurrencyDecision.submitSequence)) {
|
|
598
|
+
this._completeSkippedRequest(connection, requestId);
|
|
599
|
+
return;
|
|
600
|
+
}
|
|
601
|
+
if (concurrencyDecision.debounceUntilMs !== null) {
|
|
602
|
+
await this._waitForTimestamp(concurrencyDecision.debounceUntilMs);
|
|
603
|
+
if (this._turnQueue.generation !== epoch) {
|
|
604
|
+
this._completeSkippedRequest(connection, requestId);
|
|
605
|
+
return;
|
|
606
|
+
}
|
|
607
|
+
if (this._isSupersededSubmit(concurrencyDecision.submitSequence)) {
|
|
608
|
+
this._completeSkippedRequest(connection, requestId);
|
|
609
|
+
return;
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
const chatTurnBody = async () => {
|
|
613
|
+
if (this.waitForMcpConnections) {
|
|
614
|
+
const timeout = typeof this.waitForMcpConnections === "object" ? this.waitForMcpConnections.timeout : 1e4;
|
|
615
|
+
await this.mcp.waitForConnections({ timeout });
|
|
616
|
+
}
|
|
617
|
+
const result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
|
|
618
|
+
agent: this,
|
|
619
|
+
connection,
|
|
620
|
+
request: void 0,
|
|
621
|
+
email: void 0
|
|
622
|
+
}, () => this.onChatMessage({
|
|
623
|
+
signal: abortSignal,
|
|
624
|
+
clientTools: clientToolsForTurn,
|
|
625
|
+
body: bodyForTurn,
|
|
626
|
+
continuation: false
|
|
627
|
+
}));
|
|
628
|
+
if (result) await this._streamResult(requestId, result, abortSignal, { parentId: branchParentId });
|
|
629
|
+
else this._broadcastChat({
|
|
630
|
+
type: MSG_CHAT_RESPONSE,
|
|
631
|
+
id: requestId,
|
|
632
|
+
body: "No response was generated.",
|
|
633
|
+
done: true
|
|
634
|
+
});
|
|
635
|
+
};
|
|
636
|
+
if (this.unstable_chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
|
|
637
|
+
await chatTurnBody();
|
|
638
|
+
});
|
|
639
|
+
else await chatTurnBody();
|
|
640
|
+
})).status === "stale") this._broadcastChat({
|
|
519
641
|
type: MSG_CHAT_RESPONSE,
|
|
520
642
|
id: requestId,
|
|
521
|
-
body: "
|
|
643
|
+
body: "",
|
|
522
644
|
done: true
|
|
523
645
|
});
|
|
524
646
|
});
|
|
525
647
|
} catch (error) {
|
|
526
|
-
this.
|
|
648
|
+
this._broadcastChat({
|
|
527
649
|
type: MSG_CHAT_RESPONSE,
|
|
528
650
|
id: requestId,
|
|
529
651
|
body: error instanceof Error ? error.message : "Error",
|
|
@@ -531,80 +653,82 @@ var Think = class extends ThinkBase {
|
|
|
531
653
|
error: true
|
|
532
654
|
});
|
|
533
655
|
} finally {
|
|
534
|
-
this.
|
|
656
|
+
this._aborts.remove(requestId);
|
|
535
657
|
}
|
|
536
658
|
}
|
|
537
659
|
/**
|
|
538
|
-
*
|
|
539
|
-
*
|
|
660
|
+
* Abort the active turn, invalidate queued turns, and reset
|
|
661
|
+
* concurrency/continuation state. Call this when intercepting
|
|
662
|
+
* clear events or implementing custom reset logic.
|
|
663
|
+
*
|
|
664
|
+
* Does NOT clear messages, streams, or persisted state —
|
|
665
|
+
* only turn execution state.
|
|
540
666
|
*/
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
this.
|
|
544
|
-
if (this.
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
this.
|
|
667
|
+
resetTurnState() {
|
|
668
|
+
this._turnQueue.reset();
|
|
669
|
+
this._aborts.destroyAll();
|
|
670
|
+
if (this._continuationTimer) {
|
|
671
|
+
clearTimeout(this._continuationTimer);
|
|
672
|
+
this._continuationTimer = null;
|
|
673
|
+
}
|
|
674
|
+
this._cancelActiveDebounce();
|
|
675
|
+
this._pendingInteractionPromise = null;
|
|
676
|
+
this._continuation.sendResumeNone();
|
|
677
|
+
this._continuation.clearAll();
|
|
549
678
|
}
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
679
|
+
_handleClear(connection) {
|
|
680
|
+
this.resetTurnState();
|
|
681
|
+
this._resumableStream.clearAll();
|
|
682
|
+
this._pendingResumeConnections.clear();
|
|
683
|
+
this._lastClientTools = void 0;
|
|
684
|
+
this._persistClientTools();
|
|
685
|
+
this._lastBody = void 0;
|
|
686
|
+
this._persistBody();
|
|
687
|
+
this.session.clearMessages();
|
|
688
|
+
this._broadcast({ type: MSG_CHAT_CLEAR }, connection ? [connection.id] : void 0);
|
|
557
689
|
}
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
parts: []
|
|
569
|
-
};
|
|
690
|
+
async _streamResult(requestId, result, abortSignal, options) {
|
|
691
|
+
const clearGen = this._turnQueue.generation;
|
|
692
|
+
const streamId = this._resumableStream.start(requestId);
|
|
693
|
+
const continuation = options?.continuation ?? false;
|
|
694
|
+
const parentId = options?.parentId;
|
|
695
|
+
if (this._continuation.pending?.requestId === requestId) {
|
|
696
|
+
this._continuation.activatePending();
|
|
697
|
+
this._continuation.flushAwaitingConnections((c) => this._notifyStreamResuming(c));
|
|
698
|
+
}
|
|
699
|
+
const accumulator = new StreamAccumulator({ messageId: crypto.randomUUID() });
|
|
570
700
|
let doneSent = false;
|
|
701
|
+
let streamAborted = false;
|
|
702
|
+
let streamError;
|
|
571
703
|
try {
|
|
572
704
|
for await (const chunk of result.toUIMessageStream()) {
|
|
573
|
-
if (abortSignal?.aborted)
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
case "start":
|
|
577
|
-
if (data.messageId != null) message.id = data.messageId;
|
|
578
|
-
if (data.messageMetadata != null) message.metadata = message.metadata ? {
|
|
579
|
-
...message.metadata,
|
|
580
|
-
...data.messageMetadata
|
|
581
|
-
} : data.messageMetadata;
|
|
582
|
-
break;
|
|
583
|
-
case "finish":
|
|
584
|
-
case "message-metadata":
|
|
585
|
-
if (data.messageMetadata != null) message.metadata = message.metadata ? {
|
|
586
|
-
...message.metadata,
|
|
587
|
-
...data.messageMetadata
|
|
588
|
-
} : data.messageMetadata;
|
|
589
|
-
break;
|
|
590
|
-
case "error":
|
|
591
|
-
this._broadcast({
|
|
592
|
-
type: MSG_CHAT_RESPONSE,
|
|
593
|
-
id: requestId,
|
|
594
|
-
body: data.errorText ?? JSON.stringify(data),
|
|
595
|
-
done: false,
|
|
596
|
-
error: true
|
|
597
|
-
});
|
|
598
|
-
continue;
|
|
705
|
+
if (abortSignal?.aborted) {
|
|
706
|
+
streamAborted = true;
|
|
707
|
+
break;
|
|
599
708
|
}
|
|
600
|
-
|
|
709
|
+
const { action } = accumulator.applyChunk(chunk);
|
|
710
|
+
if (action?.type === "error") {
|
|
711
|
+
this._broadcastChat({
|
|
712
|
+
type: MSG_CHAT_RESPONSE,
|
|
713
|
+
id: requestId,
|
|
714
|
+
body: action.error,
|
|
715
|
+
done: false,
|
|
716
|
+
error: true
|
|
717
|
+
});
|
|
718
|
+
continue;
|
|
719
|
+
}
|
|
720
|
+
const chunkBody = JSON.stringify(chunk);
|
|
721
|
+
this._resumableStream.storeChunk(streamId, chunkBody);
|
|
722
|
+
this._broadcastChat({
|
|
601
723
|
type: MSG_CHAT_RESPONSE,
|
|
602
724
|
id: requestId,
|
|
603
|
-
body:
|
|
725
|
+
body: chunkBody,
|
|
604
726
|
done: false
|
|
605
727
|
});
|
|
606
728
|
}
|
|
607
|
-
this.
|
|
729
|
+
this._resumableStream.complete(streamId);
|
|
730
|
+
this._pendingResumeConnections.clear();
|
|
731
|
+
this._broadcastChat({
|
|
608
732
|
type: MSG_CHAT_RESPONSE,
|
|
609
733
|
id: requestId,
|
|
610
734
|
body: "",
|
|
@@ -612,82 +736,399 @@ var Think = class extends ThinkBase {
|
|
|
612
736
|
});
|
|
613
737
|
doneSent = true;
|
|
614
738
|
} catch (error) {
|
|
739
|
+
streamError = error instanceof Error ? error.message : "Stream error";
|
|
740
|
+
this._resumableStream.markError(streamId);
|
|
741
|
+
this._pendingResumeConnections.clear();
|
|
615
742
|
if (!doneSent) {
|
|
616
|
-
this.
|
|
743
|
+
this._broadcastChat({
|
|
617
744
|
type: MSG_CHAT_RESPONSE,
|
|
618
745
|
id: requestId,
|
|
619
|
-
body:
|
|
746
|
+
body: streamError,
|
|
620
747
|
done: true,
|
|
621
748
|
error: true
|
|
622
749
|
});
|
|
623
750
|
doneSent = true;
|
|
624
751
|
}
|
|
625
752
|
} finally {
|
|
626
|
-
if (!doneSent)
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
753
|
+
if (!doneSent) {
|
|
754
|
+
this._resumableStream.markError(streamId);
|
|
755
|
+
this._pendingResumeConnections.clear();
|
|
756
|
+
this._broadcastChat({
|
|
757
|
+
type: MSG_CHAT_RESPONSE,
|
|
758
|
+
id: requestId,
|
|
759
|
+
body: "",
|
|
760
|
+
done: true
|
|
761
|
+
});
|
|
762
|
+
}
|
|
632
763
|
}
|
|
633
|
-
if (
|
|
634
|
-
|
|
764
|
+
if (accumulator.parts.length > 0 && this._turnQueue.generation === clearGen) try {
|
|
765
|
+
const assistantMsg = accumulator.toMessage();
|
|
766
|
+
this._persistAssistantMessage(assistantMsg, parentId);
|
|
635
767
|
this._broadcastMessages();
|
|
768
|
+
await this._fireResponseHook({
|
|
769
|
+
message: assistantMsg,
|
|
770
|
+
requestId,
|
|
771
|
+
continuation,
|
|
772
|
+
status: streamAborted ? "aborted" : streamError ? "error" : "completed",
|
|
773
|
+
error: streamError
|
|
774
|
+
});
|
|
636
775
|
} catch (e) {
|
|
637
776
|
console.error("Failed to persist assistant message:", e);
|
|
638
777
|
}
|
|
639
778
|
}
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
779
|
+
_persistAssistantMessage(msg, parentId) {
|
|
780
|
+
const sized = enforceRowSizeLimit(sanitizeMessage(msg));
|
|
781
|
+
const safe = this.sanitizeMessageForPersistence(sized);
|
|
782
|
+
if (this.session.getMessage(safe.id)) this.session.updateMessage(safe);
|
|
783
|
+
else this.session.appendMessage(safe, parentId);
|
|
784
|
+
}
|
|
785
|
+
_persistClientTools() {
|
|
786
|
+
if (this._lastClientTools) this._configSet("lastClientTools", JSON.stringify(this._lastClientTools));
|
|
787
|
+
else this._configDelete("lastClientTools");
|
|
788
|
+
}
|
|
789
|
+
_restoreClientTools() {
|
|
790
|
+
const raw = this._configGet("lastClientTools");
|
|
791
|
+
if (raw) try {
|
|
792
|
+
this._lastClientTools = JSON.parse(raw);
|
|
793
|
+
} catch {
|
|
794
|
+
this._lastClientTools = void 0;
|
|
652
795
|
}
|
|
653
|
-
if (this.maxPersistedMessages != null) this._enforceMaxPersistedMessages();
|
|
654
|
-
this.messages = this.sessions.getHistory(this._sessionId);
|
|
655
796
|
}
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
* @internal
|
|
660
|
-
*/
|
|
661
|
-
_rebuildPersistenceCache() {
|
|
662
|
-
this._persistedMessageCache.clear();
|
|
663
|
-
for (const msg of this.messages) this._persistedMessageCache.set(msg.id, JSON.stringify(msg));
|
|
797
|
+
_persistBody() {
|
|
798
|
+
if (this._lastBody) this._configSet("lastBody", JSON.stringify(this._lastBody));
|
|
799
|
+
else this._configDelete("lastBody");
|
|
664
800
|
}
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
801
|
+
_restoreBody() {
|
|
802
|
+
const raw = this._configGet("lastBody");
|
|
803
|
+
if (raw) try {
|
|
804
|
+
this._lastBody = JSON.parse(raw);
|
|
805
|
+
} catch {
|
|
806
|
+
this._lastBody = void 0;
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
_applyToolResult(toolCallId, output, overrideState, errorText) {
|
|
810
|
+
const update = toolResultUpdate(toolCallId, output, overrideState, errorText);
|
|
811
|
+
this._applyToolUpdateToMessages(update);
|
|
812
|
+
}
|
|
813
|
+
_applyToolApproval(toolCallId, approved) {
|
|
814
|
+
const update = toolApprovalUpdate(toolCallId, approved);
|
|
815
|
+
this._applyToolUpdateToMessages(update);
|
|
816
|
+
}
|
|
817
|
+
_applyToolUpdateToMessages(update) {
|
|
818
|
+
const history = this.messages;
|
|
819
|
+
for (const msg of history) {
|
|
820
|
+
const result = applyToolUpdate(msg.parts, update);
|
|
821
|
+
if (result) {
|
|
822
|
+
const safe = enforceRowSizeLimit(sanitizeMessage({
|
|
823
|
+
...msg,
|
|
824
|
+
parts: result.parts
|
|
825
|
+
}));
|
|
826
|
+
this.session.updateMessage(safe);
|
|
827
|
+
this._broadcast({
|
|
828
|
+
type: MSG_MESSAGE_UPDATED,
|
|
829
|
+
message: safe
|
|
830
|
+
});
|
|
831
|
+
return;
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
hasPendingInteraction() {
|
|
836
|
+
return this.messages.some((message) => message.role === "assistant" && this._messageHasPendingInteraction(message));
|
|
837
|
+
}
|
|
838
|
+
async waitUntilStable(options) {
|
|
839
|
+
const deadline = options?.timeout != null ? Date.now() + options.timeout : null;
|
|
840
|
+
while (true) {
|
|
841
|
+
if (await this._awaitWithDeadline(this._turnQueue.waitForIdle(), deadline) === TIMED_OUT) return false;
|
|
842
|
+
if (!this.hasPendingInteraction()) return true;
|
|
843
|
+
const pending = this._pendingInteractionPromise;
|
|
844
|
+
if (pending) {
|
|
845
|
+
let result;
|
|
846
|
+
try {
|
|
847
|
+
result = await this._awaitWithDeadline(pending, deadline);
|
|
848
|
+
} catch {
|
|
849
|
+
continue;
|
|
850
|
+
}
|
|
851
|
+
if (result === TIMED_OUT) return false;
|
|
852
|
+
} else if (await this._awaitWithDeadline(new Promise((resolve) => setTimeout(resolve, 100)), deadline) === TIMED_OUT) return false;
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
async _awaitWithDeadline(promise, deadline) {
|
|
856
|
+
if (deadline == null) return promise;
|
|
857
|
+
const remainingMs = Math.max(0, deadline - Date.now());
|
|
858
|
+
let timer;
|
|
859
|
+
const result = await Promise.race([promise, new Promise((resolve) => {
|
|
860
|
+
timer = setTimeout(() => resolve(TIMED_OUT), remainingMs);
|
|
861
|
+
})]);
|
|
862
|
+
clearTimeout(timer);
|
|
863
|
+
return result;
|
|
864
|
+
}
|
|
865
|
+
_messageHasPendingInteraction(message) {
|
|
866
|
+
return message.parts.some((part) => "state" in part && (part.state === "input-available" || part.state === "approval-requested"));
|
|
867
|
+
}
|
|
868
|
+
async _handleInternalFiberRecovery(ctx) {
|
|
869
|
+
const chatPrefix = this.constructor.CHAT_FIBER_NAME + ":";
|
|
870
|
+
if (!ctx.name.startsWith(chatPrefix)) return false;
|
|
871
|
+
const requestId = ctx.name.slice(chatPrefix.length);
|
|
872
|
+
let streamId = "";
|
|
873
|
+
if (requestId) {
|
|
874
|
+
const rows = this.sql`
|
|
875
|
+
SELECT id FROM cf_ai_chat_stream_metadata
|
|
876
|
+
WHERE request_id = ${requestId}
|
|
877
|
+
ORDER BY created_at DESC LIMIT 1
|
|
878
|
+
`;
|
|
879
|
+
if (rows.length > 0) streamId = rows[0].id;
|
|
880
|
+
}
|
|
881
|
+
if (!streamId && this._resumableStream.hasActiveStream()) streamId = this._resumableStream.activeStreamId ?? "";
|
|
882
|
+
const partial = streamId ? this._getPartialStreamText(streamId) : {
|
|
883
|
+
text: "",
|
|
884
|
+
parts: []
|
|
885
|
+
};
|
|
886
|
+
const options = await this.onChatRecovery({
|
|
887
|
+
streamId: streamId ?? "",
|
|
888
|
+
requestId,
|
|
889
|
+
partialText: partial.text,
|
|
890
|
+
partialParts: partial.parts,
|
|
891
|
+
recoveryData: ctx.snapshot,
|
|
892
|
+
messages: [...this.messages],
|
|
893
|
+
lastBody: this._lastBody,
|
|
894
|
+
lastClientTools: this._lastClientTools
|
|
895
|
+
});
|
|
896
|
+
const streamStillActive = streamId && this._resumableStream.hasActiveStream() && this._resumableStream.activeStreamId === streamId;
|
|
897
|
+
if (options.persist !== false && streamStillActive) this._persistOrphanedStream(streamId);
|
|
898
|
+
if (streamStillActive) this._resumableStream.complete(streamId);
|
|
899
|
+
if (options.continue !== false) {
|
|
900
|
+
const lastLeaf = this.session.getLatestLeaf();
|
|
901
|
+
const targetId = lastLeaf?.role === "assistant" ? lastLeaf.id : void 0;
|
|
902
|
+
await this.schedule(0, "_chatRecoveryContinue", targetId ? { targetAssistantId: targetId } : void 0, { idempotent: true });
|
|
903
|
+
}
|
|
904
|
+
return true;
|
|
905
|
+
}
|
|
906
|
+
async onChatRecovery(_ctx) {
|
|
907
|
+
return {};
|
|
908
|
+
}
|
|
909
|
+
async _chatRecoveryContinue(data) {
|
|
910
|
+
if (!await this.waitUntilStable({ timeout: 1e4 })) {
|
|
911
|
+
console.warn("[Think] _chatRecoveryContinue timed out waiting for stable state, skipping continuation");
|
|
912
|
+
return;
|
|
913
|
+
}
|
|
914
|
+
const targetId = data?.targetAssistantId;
|
|
915
|
+
const lastLeaf = this.session.getLatestLeaf();
|
|
916
|
+
if (targetId && lastLeaf?.id !== targetId) return;
|
|
917
|
+
await this.continueLastTurn();
|
|
918
|
+
}
|
|
919
|
+
_getPartialStreamText(streamId) {
|
|
920
|
+
const chunks = this._resumableStream.getStreamChunks(streamId);
|
|
921
|
+
const parts = [];
|
|
922
|
+
for (const chunk of chunks) try {
|
|
923
|
+
applyChunkToParts(parts, JSON.parse(chunk.body));
|
|
924
|
+
} catch {}
|
|
925
|
+
return {
|
|
926
|
+
text: parts.filter((p) => p.type === "text" && "text" in p).map((p) => p.text).join(""),
|
|
927
|
+
parts
|
|
928
|
+
};
|
|
929
|
+
}
|
|
930
|
+
_normalizeMessageConcurrency() {
|
|
931
|
+
if (typeof this.messageConcurrency === "string") return this.messageConcurrency;
|
|
932
|
+
const debounceMs = this.messageConcurrency.debounceMs;
|
|
933
|
+
return {
|
|
934
|
+
strategy: "debounce",
|
|
935
|
+
debounceMs: typeof debounceMs === "number" && Number.isFinite(debounceMs) && debounceMs >= 0 ? debounceMs : Think.MESSAGE_DEBOUNCE_MS
|
|
936
|
+
};
|
|
937
|
+
}
|
|
938
|
+
_getSubmitConcurrencyDecision(isSubmitMessage) {
|
|
939
|
+
const queuedTurns = this._turnQueue.queuedCount();
|
|
940
|
+
if (!isSubmitMessage || queuedTurns === 0) return {
|
|
941
|
+
action: "execute",
|
|
942
|
+
submitSequence: null,
|
|
943
|
+
debounceUntilMs: null
|
|
944
|
+
};
|
|
945
|
+
const concurrency = this._normalizeMessageConcurrency();
|
|
946
|
+
if (concurrency === "queue") return {
|
|
947
|
+
action: "execute",
|
|
948
|
+
submitSequence: null,
|
|
949
|
+
debounceUntilMs: null
|
|
950
|
+
};
|
|
951
|
+
if (concurrency === "drop") return {
|
|
952
|
+
action: "drop",
|
|
953
|
+
submitSequence: null,
|
|
954
|
+
debounceUntilMs: null
|
|
955
|
+
};
|
|
956
|
+
const submitSequence = ++this._submitSequence;
|
|
957
|
+
this._latestOverlappingSubmitSequence = submitSequence;
|
|
958
|
+
if (concurrency === "latest" || concurrency === "merge") return {
|
|
959
|
+
action: "execute",
|
|
960
|
+
submitSequence,
|
|
961
|
+
debounceUntilMs: null
|
|
962
|
+
};
|
|
963
|
+
return {
|
|
964
|
+
action: "execute",
|
|
965
|
+
submitSequence,
|
|
966
|
+
debounceUntilMs: Date.now() + concurrency.debounceMs
|
|
967
|
+
};
|
|
968
|
+
}
|
|
969
|
+
_isSupersededSubmit(submitSequence) {
|
|
970
|
+
return submitSequence !== null && submitSequence < this._latestOverlappingSubmitSequence;
|
|
971
|
+
}
|
|
972
|
+
async _waitForTimestamp(timestampMs) {
|
|
973
|
+
const remainingMs = timestampMs - Date.now();
|
|
974
|
+
if (remainingMs <= 0) return;
|
|
975
|
+
await new Promise((resolve) => {
|
|
976
|
+
this._activeDebounceResolve = resolve;
|
|
977
|
+
this._activeDebounceTimer = setTimeout(() => {
|
|
978
|
+
this._activeDebounceTimer = null;
|
|
979
|
+
this._activeDebounceResolve = null;
|
|
980
|
+
resolve();
|
|
981
|
+
}, remainingMs);
|
|
982
|
+
});
|
|
983
|
+
}
|
|
984
|
+
_cancelActiveDebounce() {
|
|
985
|
+
if (this._activeDebounceTimer !== null) {
|
|
986
|
+
clearTimeout(this._activeDebounceTimer);
|
|
987
|
+
this._activeDebounceTimer = null;
|
|
988
|
+
}
|
|
989
|
+
if (this._activeDebounceResolve !== null) {
|
|
990
|
+
this._activeDebounceResolve();
|
|
991
|
+
this._activeDebounceResolve = null;
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
_completeSkippedRequest(connection, requestId) {
|
|
995
|
+
connection.send(JSON.stringify({
|
|
996
|
+
type: MSG_CHAT_RESPONSE,
|
|
997
|
+
id: requestId,
|
|
998
|
+
body: "",
|
|
999
|
+
done: true
|
|
1000
|
+
}));
|
|
1001
|
+
}
|
|
1002
|
+
_rollbackDroppedSubmit(connection) {
|
|
1003
|
+
connection.send(JSON.stringify({
|
|
1004
|
+
type: MSG_CHAT_MESSAGES,
|
|
1005
|
+
messages: this.messages
|
|
1006
|
+
}));
|
|
1007
|
+
}
|
|
1008
|
+
_scheduleAutoContinuation(connection) {
|
|
1009
|
+
if (this._continuation.pending?.pastCoalesce) {
|
|
1010
|
+
this._continuation.deferred = {
|
|
1011
|
+
connection,
|
|
1012
|
+
connectionId: connection.id,
|
|
1013
|
+
clientTools: this._lastClientTools,
|
|
1014
|
+
body: void 0,
|
|
1015
|
+
errorPrefix: "[Think] Auto-continuation failed:",
|
|
1016
|
+
prerequisite: null
|
|
1017
|
+
};
|
|
1018
|
+
return;
|
|
1019
|
+
}
|
|
1020
|
+
if (this._continuation.pending) {
|
|
1021
|
+
this._continuation.pending.connection = connection;
|
|
1022
|
+
this._continuation.pending.connectionId = connection.id;
|
|
1023
|
+
this._continuation.pending.clientTools = this._lastClientTools;
|
|
1024
|
+
this._continuation.awaitingConnections.set(connection.id, connection);
|
|
1025
|
+
return;
|
|
1026
|
+
}
|
|
1027
|
+
if (this._continuationTimer) clearTimeout(this._continuationTimer);
|
|
1028
|
+
this._continuationTimer = setTimeout(() => {
|
|
1029
|
+
this._continuationTimer = null;
|
|
1030
|
+
this._fireAutoContinuation(connection);
|
|
1031
|
+
}, 50);
|
|
1032
|
+
}
|
|
1033
|
+
_fireAutoContinuation(connection) {
|
|
1034
|
+
if (!this._continuation.pending) {
|
|
1035
|
+
const requestId = crypto.randomUUID();
|
|
1036
|
+
this._continuation.pending = {
|
|
1037
|
+
connection,
|
|
1038
|
+
connectionId: connection.id,
|
|
1039
|
+
requestId,
|
|
1040
|
+
clientTools: this._lastClientTools,
|
|
1041
|
+
body: void 0,
|
|
1042
|
+
errorPrefix: "[Think] Auto-continuation failed:",
|
|
1043
|
+
prerequisite: null,
|
|
1044
|
+
pastCoalesce: false
|
|
1045
|
+
};
|
|
1046
|
+
this._continuation.awaitingConnections.set(connection.id, connection);
|
|
1047
|
+
}
|
|
1048
|
+
const { requestId, clientTools } = this._continuation.pending;
|
|
1049
|
+
const abortSignal = this._aborts.getSignal(requestId);
|
|
1050
|
+
this.keepAliveWhile(async () => {
|
|
1051
|
+
await this._turnQueue.enqueue(requestId, async () => {
|
|
1052
|
+
if (this._continuation.pending) this._continuation.pending.pastCoalesce = true;
|
|
1053
|
+
let streamed = false;
|
|
1054
|
+
try {
|
|
1055
|
+
const continuationBody = async () => {
|
|
1056
|
+
const result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
|
|
1057
|
+
agent: this,
|
|
1058
|
+
connection,
|
|
1059
|
+
request: void 0,
|
|
1060
|
+
email: void 0
|
|
1061
|
+
}, () => this.onChatMessage({
|
|
1062
|
+
signal: abortSignal,
|
|
1063
|
+
clientTools,
|
|
1064
|
+
body: this._lastBody,
|
|
1065
|
+
continuation: true
|
|
1066
|
+
}));
|
|
1067
|
+
if (result) {
|
|
1068
|
+
await this._streamResult(requestId, result, abortSignal, { continuation: true });
|
|
1069
|
+
streamed = true;
|
|
1070
|
+
}
|
|
1071
|
+
};
|
|
1072
|
+
if (this.unstable_chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
|
|
1073
|
+
await continuationBody();
|
|
1074
|
+
});
|
|
1075
|
+
else await continuationBody();
|
|
1076
|
+
} finally {
|
|
1077
|
+
this._aborts.remove(requestId);
|
|
1078
|
+
if (!streamed) this._continuation.sendResumeNone();
|
|
1079
|
+
this._continuation.clearPending();
|
|
1080
|
+
this._activateDeferredContinuation();
|
|
1081
|
+
}
|
|
1082
|
+
});
|
|
1083
|
+
}).catch((error) => {
|
|
1084
|
+
console.error("[Think] Auto-continuation failed:", error);
|
|
1085
|
+
this._aborts.remove(requestId);
|
|
1086
|
+
});
|
|
1087
|
+
}
|
|
1088
|
+
_activateDeferredContinuation() {
|
|
1089
|
+
const pending = this._continuation.activateDeferred(() => crypto.randomUUID());
|
|
1090
|
+
if (!pending) return;
|
|
1091
|
+
this._fireAutoContinuation(pending.connection);
|
|
1092
|
+
}
|
|
1093
|
+
async _fireResponseHook(result) {
|
|
1094
|
+
if (this._insideResponseHook) return;
|
|
1095
|
+
this._insideResponseHook = true;
|
|
1096
|
+
try {
|
|
1097
|
+
await this.onChatResponse(result);
|
|
1098
|
+
} catch (err) {
|
|
1099
|
+
console.error("[Think] onChatResponse error:", err);
|
|
1100
|
+
} finally {
|
|
1101
|
+
this._insideResponseHook = false;
|
|
1102
|
+
}
|
|
1103
|
+
}
|
|
1104
|
+
_notifyStreamResuming(connection) {
|
|
1105
|
+
if (!this._resumableStream.hasActiveStream()) return;
|
|
1106
|
+
this._pendingResumeConnections.add(connection.id);
|
|
1107
|
+
connection.send(JSON.stringify({
|
|
1108
|
+
type: MSG_STREAM_RESUMING,
|
|
1109
|
+
id: this._resumableStream.activeRequestId
|
|
1110
|
+
}));
|
|
1111
|
+
}
|
|
1112
|
+
_persistOrphanedStream(streamId) {
|
|
1113
|
+
this._resumableStream.flushBuffer();
|
|
1114
|
+
const chunks = this._resumableStream.getStreamChunks(streamId);
|
|
1115
|
+
if (chunks.length === 0) return;
|
|
1116
|
+
const accumulator = new StreamAccumulator({ messageId: crypto.randomUUID() });
|
|
1117
|
+
for (const chunk of chunks) try {
|
|
1118
|
+
accumulator.applyChunk(JSON.parse(chunk.body));
|
|
1119
|
+
} catch {}
|
|
1120
|
+
if (accumulator.parts.length > 0) {
|
|
1121
|
+
this._persistAssistantMessage(accumulator.toMessage());
|
|
1122
|
+
this._broadcastMessages();
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
_broadcastChat(message, exclude) {
|
|
1126
|
+
const allExclusions = [...exclude || [], ...this._pendingResumeConnections];
|
|
1127
|
+
this.broadcast(JSON.stringify(message), allExclusions);
|
|
679
1128
|
}
|
|
680
|
-
/**
|
|
681
|
-
* Broadcast a JSON message to all connected clients.
|
|
682
|
-
* @internal
|
|
683
|
-
*/
|
|
684
1129
|
_broadcast(message, exclude) {
|
|
685
1130
|
this.broadcast(JSON.stringify(message), exclude);
|
|
686
1131
|
}
|
|
687
|
-
/**
|
|
688
|
-
* Broadcast the current message list to all connected clients.
|
|
689
|
-
* @internal
|
|
690
|
-
*/
|
|
691
1132
|
_broadcastMessages(exclude) {
|
|
692
1133
|
this._broadcast({
|
|
693
1134
|
type: MSG_CHAT_MESSAGES,
|
|
@@ -695,7 +1136,9 @@ var Think = class extends ThinkBase {
|
|
|
695
1136
|
}, exclude);
|
|
696
1137
|
}
|
|
697
1138
|
};
|
|
1139
|
+
Think.CHAT_FIBER_NAME = "__cf_internal_chat_turn";
|
|
1140
|
+
Think.MESSAGE_DEBOUNCE_MS = 750;
|
|
698
1141
|
//#endregion
|
|
699
|
-
export { Think };
|
|
1142
|
+
export { Session, Think };
|
|
700
1143
|
|
|
701
1144
|
//# sourceMappingURL=think.js.map
|