@cloudflare/think 0.17.0 → 0.18.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 +133 -31
- package/dist/{chat-sdk-C8BvREXn.js → chat-sdk-B77QwYuj.js} +49 -31
- package/dist/chat-sdk-B77QwYuj.js.map +1 -0
- package/dist/extensions/index.d.ts +1 -1
- package/dist/extensions/index.js +1 -1
- package/dist/extensions/index.js.map +1 -1
- package/dist/{index-B7zEkBBM.d.ts → index-CJ--4uax.d.ts} +614 -182
- package/dist/{manager-CSk5htym.js → manager-Cb3DNZgp.js} +10 -10
- package/dist/{manager-CSk5htym.js.map → manager-Cb3DNZgp.js.map} +1 -1
- package/dist/messengers/index.d.ts +1 -1
- package/dist/messengers/index.js +1 -1
- package/dist/messengers/telegram.d.ts +1 -1
- package/dist/messengers/telegram.js +1 -1
- package/dist/think.d.ts +3 -3
- package/dist/think.js +1174 -406
- package/dist/think.js.map +1 -1
- package/dist/tools/execute.d.ts +1 -1
- package/dist/tools/extensions.js +1 -1
- package/dist/tools/workspace.d.ts +1 -1
- package/dist/tools/workspace.js.map +1 -1
- package/dist/workflows.d.ts +1 -1
- package/dist/{workspace-DxZQSbko.d.ts → workspace-CNeXc2vl.d.ts} +8 -2
- package/docs/client-tools.md +1 -1
- package/docs/getting-started.md +19 -14
- package/docs/index.md +98 -28
- package/docs/lifecycle-hooks.md +51 -15
- package/docs/tools.md +2 -2
- package/package.json +6 -6
- package/dist/chat-sdk-C8BvREXn.js.map +0 -1
package/dist/think.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { a as
|
|
1
|
+
import { a as _assertClassBrand, i as _classPrivateFieldGet2, n as sanitizeName, o as _classPrivateFieldInitSpec, r as _classPrivateFieldSet2, s as _classPrivateMethodInitSpec, t as ExtensionManager } from "./manager-Cb3DNZgp.js";
|
|
2
2
|
import { createWorkspaceTools } from "./tools/workspace.js";
|
|
3
3
|
import { createFetchTools } from "./tools/fetch.js";
|
|
4
4
|
import { truncatePausedExecutionOutput } from "./tools/execute.js";
|
|
5
|
-
import { t as ThinkMessengerRuntime } from "./chat-sdk-
|
|
5
|
+
import { g as MESSENGER_REPLY_FIBER_NAME, t as ThinkMessengerRuntime } from "./chat-sdk-B77QwYuj.js";
|
|
6
|
+
import "./messengers/index.js";
|
|
6
7
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
7
8
|
import * as aiSdk from "ai";
|
|
8
9
|
import { convertToModelMessages, hasToolCall, jsonSchema, stepCountIs, tool } from "ai";
|
|
@@ -13,64 +14,284 @@ import { openai } from "workers-ai-provider/openai";
|
|
|
13
14
|
import * as skills from "agents/skills";
|
|
14
15
|
import { SkillRegistry } from "agents/skills";
|
|
15
16
|
import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext, __DO_NOT_USE_WILL_BREAK__withInvocationScope, callable, getCurrentAgent, isDurableObjectMemoryLimitReset, isPlatformTransientError } from "agents";
|
|
16
|
-
import { AbortRegistry, AgentToolProgressEmitter, AgentToolStreamProgressThrottle, AutoContinuationController, CHAT_MESSAGE_TYPES, ChatRecoveryEngine, ChatStreamStalledError, ContinuationState, MAX_BOUND_PARAMS, PreStreamTurns, ResumableStream, ResumeHandshake,
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
17
|
+
import { AbortRegistry, AgentToolProgressEmitter, AgentToolStreamProgressThrottle, AutoContinuationController, CHAT_MESSAGE_TYPES, CHAT_RECOVERY_PROGRESS_KEY, CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS, CHAT_RECOVERY_TASK_NAME, ChatRecoveryEngine, ChatStreamStalledError, ContinuationState, MAX_BOUND_PARAMS, PreStreamTurns, ResumableStream, ResumeHandshake, StreamAccumulator, SubmitConcurrencyController, TIMED_OUT, TurnQueue, aiSdkRecoveryCodec, applyToolUpdate, awaitWithDeadline, buildChatRecoveringFrame, buildInClauseStrings, chatRecoveryTaskRunOptions, classifyAgentToolChildRecovery, clearChatTerminal, clientResolvableToolNames, createChatFiberSnapshot, createChatRecoveryTaskDefinition, createChatStreams, createChatTurnTaskDefinition, createToolsFromClientSchemas, crossMessageToolResultUpdate, dispatchChatRecoveryToHandoff, drainInteractionApplies, enforceRowSizeLimit, hasIncompleteToolBatch, interceptAgentToolBroadcast, iterateWithStallWatchdog, listActiveChatRecoveryIncidents, normalizeToolInput, parseProtocolMessage, partAwaitsClientInteraction, pausedExecutionUpdate, pendingChatTerminal, persistReconstructedOrphan, readChatRecoveryProgress, reconcileMessages, recordChatTerminal, repairInterruptedToolParts, resolveChatRecoveryConfig, resolveToolMergeId, runChatRecoveryExhaustion, sanitizeMessage, setChatRecovering, sweepStaleChatRecoveryIncidents, toolApprovalUpdate, toolPartHasSettledResult, toolResultUpdate, truncateOlderMessages, unwrapChatFiberSnapshot, wrapChatFiberSnapshot } from "agents/chat";
|
|
18
|
+
import { Sessions, isCompactionMessage } from "agents/sessions";
|
|
19
|
+
import { AgentContextProvider, ContextBlocks } from "agents/context";
|
|
19
20
|
import { Workspace, Workspace as Workspace$1 } from "@cloudflare/shell";
|
|
21
|
+
//#region src/session.ts
|
|
22
|
+
var _handle = /* @__PURE__ */ new WeakMap();
|
|
23
|
+
var _context = /* @__PURE__ */ new WeakMap();
|
|
24
|
+
var _pendingContext = /* @__PURE__ */ new WeakMap();
|
|
25
|
+
var _promptStore = /* @__PURE__ */ new WeakMap();
|
|
26
|
+
var _compactionErrorHandler = /* @__PURE__ */ new WeakMap();
|
|
27
|
+
var ThinkSession = class {
|
|
28
|
+
/** @internal Constructed by Think during `onStart`. */
|
|
29
|
+
constructor(handle, context) {
|
|
30
|
+
_classPrivateFieldInitSpec(this, _handle, void 0);
|
|
31
|
+
_classPrivateFieldInitSpec(this, _context, void 0);
|
|
32
|
+
_classPrivateFieldInitSpec(this, _pendingContext, []);
|
|
33
|
+
_classPrivateFieldInitSpec(this, _promptStore, void 0);
|
|
34
|
+
_classPrivateFieldInitSpec(this, _compactionErrorHandler, null);
|
|
35
|
+
_classPrivateFieldSet2(_handle, this, handle);
|
|
36
|
+
_classPrivateFieldSet2(_context, this, context);
|
|
37
|
+
}
|
|
38
|
+
get sessionId() {
|
|
39
|
+
return _classPrivateFieldGet2(_handle, this).sessionId;
|
|
40
|
+
}
|
|
41
|
+
/** @internal Blocks declared through `withContext()` during configuration. */
|
|
42
|
+
internal_takePendingContext() {
|
|
43
|
+
const pending = _classPrivateFieldGet2(_pendingContext, this) ?? [];
|
|
44
|
+
_classPrivateFieldSet2(_pendingContext, this, null);
|
|
45
|
+
return pending;
|
|
46
|
+
}
|
|
47
|
+
/** @internal A custom frozen-prompt store passed to `withCachedPrompt()`. */
|
|
48
|
+
internal_promptStore() {
|
|
49
|
+
return _classPrivateFieldGet2(_promptStore, this);
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Declare a prompt context block.
|
|
53
|
+
*
|
|
54
|
+
* @deprecated Return the block from `configureContext()` instead. Only
|
|
55
|
+
* callable inside `configureSession()`; after startup use
|
|
56
|
+
* `this.context.addBlock()`.
|
|
57
|
+
*/
|
|
58
|
+
withContext(label, options = {}) {
|
|
59
|
+
if (!_classPrivateFieldGet2(_pendingContext, this)) throw new Error("withContext() is only available inside configureSession(). After startup, add a block with this.context.addBlock().");
|
|
60
|
+
_classPrivateFieldGet2(_pendingContext, this).push({
|
|
61
|
+
label,
|
|
62
|
+
...options
|
|
63
|
+
});
|
|
64
|
+
return this;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Persist the frozen system prompt.
|
|
68
|
+
*
|
|
69
|
+
* @deprecated The frozen prompt is always persisted now, so this is a
|
|
70
|
+
* no-op. A custom `provider` is still honoured as the prompt store.
|
|
71
|
+
*/
|
|
72
|
+
withCachedPrompt(provider) {
|
|
73
|
+
if (provider) _classPrivateFieldSet2(_promptStore, this, provider);
|
|
74
|
+
return this;
|
|
75
|
+
}
|
|
76
|
+
/** Register the function `compact()` calls to summarize a branch. */
|
|
77
|
+
onCompaction(fn) {
|
|
78
|
+
_classPrivateFieldGet2(_handle, this).onCompaction(async (messages) => {
|
|
79
|
+
try {
|
|
80
|
+
return await fn(messages);
|
|
81
|
+
} catch (error) {
|
|
82
|
+
const handler = _classPrivateFieldGet2(_compactionErrorHandler, this);
|
|
83
|
+
if (!handler) throw error;
|
|
84
|
+
await handler(error);
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
return this;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Auto-compact after an append once the stamped token estimate crosses the
|
|
92
|
+
* threshold. Requires `onCompaction()`.
|
|
93
|
+
*/
|
|
94
|
+
compactAfter(tokenThreshold, _options) {
|
|
95
|
+
_classPrivateFieldGet2(_handle, this).compactAfter(tokenThreshold);
|
|
96
|
+
return this;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Observe compaction failures. When set, a failing compaction function
|
|
100
|
+
* calls the handler and the compaction is skipped; without one the failure
|
|
101
|
+
* is reported through the `session:error` capability event.
|
|
102
|
+
*/
|
|
103
|
+
onCompactionError(handler) {
|
|
104
|
+
_classPrivateFieldSet2(_compactionErrorHandler, this, handler);
|
|
105
|
+
return this;
|
|
106
|
+
}
|
|
107
|
+
history(options) {
|
|
108
|
+
return _classPrivateFieldGet2(_handle, this).history(options);
|
|
109
|
+
}
|
|
110
|
+
historyBatches(options) {
|
|
111
|
+
return _classPrivateFieldGet2(_handle, this).historyBatches(options);
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Materialize the whole selected path. Accepts a leaf id positionally, as
|
|
115
|
+
* the pre-Sessions API did, or a read-options object.
|
|
116
|
+
*/
|
|
117
|
+
getHistory(leafIdOrOptions) {
|
|
118
|
+
return _classPrivateFieldGet2(_handle, this).getHistory(readOptions(leafIdOrOptions));
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Byte-budgeted read of the most recent messages on the active path. The
|
|
122
|
+
* pre-Sessions `minRecentMessages` argument is accepted and ignored: the
|
|
123
|
+
* budget is a hard ceiling, and the newest message is always returned.
|
|
124
|
+
*/
|
|
125
|
+
getRecentHistory(maxContentBytes, optionsOrMinRecentMessages) {
|
|
126
|
+
const options = typeof optionsOrMinRecentMessages === "object" ? optionsOrMinRecentMessages : void 0;
|
|
127
|
+
return _classPrivateFieldGet2(_handle, this).getRecentHistory(maxContentBytes, options);
|
|
128
|
+
}
|
|
129
|
+
getHistoryRowStats(leafId) {
|
|
130
|
+
return _classPrivateFieldGet2(_handle, this).getHistoryRowStats(leafId);
|
|
131
|
+
}
|
|
132
|
+
/** @deprecated Read `getHistoryRowStats()` and take its length. */
|
|
133
|
+
async getPathLength(leafId) {
|
|
134
|
+
return (await _classPrivateFieldGet2(_handle, this).getHistoryRowStats(leafId)).length;
|
|
135
|
+
}
|
|
136
|
+
getMessage(id) {
|
|
137
|
+
return _classPrivateFieldGet2(_handle, this).getMessage(id);
|
|
138
|
+
}
|
|
139
|
+
getLatestLeaf() {
|
|
140
|
+
return _classPrivateFieldGet2(_handle, this).getLatestLeaf();
|
|
141
|
+
}
|
|
142
|
+
getBranches(messageId) {
|
|
143
|
+
return _classPrivateFieldGet2(_handle, this).getBranches(messageId);
|
|
144
|
+
}
|
|
145
|
+
search(query, options) {
|
|
146
|
+
return _classPrivateFieldGet2(_handle, this).search(query, options);
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Append one message. Accepts the parent id positionally, as the
|
|
150
|
+
* pre-Sessions API did, or an options object.
|
|
151
|
+
*/
|
|
152
|
+
appendMessage(message, parentIdOrOptions) {
|
|
153
|
+
return _classPrivateFieldGet2(_handle, this).appendMessage(message, appendOptions(parentIdOrOptions));
|
|
154
|
+
}
|
|
155
|
+
updateMessage(message, options) {
|
|
156
|
+
return _classPrivateFieldGet2(_handle, this).updateMessage(message, options);
|
|
157
|
+
}
|
|
158
|
+
upsertMessage(message, parentIdOrOptions) {
|
|
159
|
+
return _classPrivateFieldGet2(_handle, this).upsertMessage(message, appendOptions(parentIdOrOptions));
|
|
160
|
+
}
|
|
161
|
+
importMessage(message, options) {
|
|
162
|
+
return _classPrivateFieldGet2(_handle, this).importMessage(message, options);
|
|
163
|
+
}
|
|
164
|
+
deleteMessages(messageIds) {
|
|
165
|
+
return _classPrivateFieldGet2(_handle, this).deleteMessages(messageIds);
|
|
166
|
+
}
|
|
167
|
+
clearMessages() {
|
|
168
|
+
return _classPrivateFieldGet2(_handle, this).clearMessages();
|
|
169
|
+
}
|
|
170
|
+
addCompaction(summary, fromMessageId, toMessageId) {
|
|
171
|
+
return _classPrivateFieldGet2(_handle, this).addCompaction(summary, fromMessageId, toMessageId);
|
|
172
|
+
}
|
|
173
|
+
getCompactions() {
|
|
174
|
+
return _classPrivateFieldGet2(_handle, this).getCompactions();
|
|
175
|
+
}
|
|
176
|
+
compact(leafId) {
|
|
177
|
+
return _classPrivateFieldGet2(_handle, this).compact(leafId);
|
|
178
|
+
}
|
|
179
|
+
/** @deprecated Use `this.context.addBlock({ label, ...options })`. */
|
|
180
|
+
addContext(label, options = {}) {
|
|
181
|
+
return _classPrivateFieldGet2(_context, this).call(this).addBlock({
|
|
182
|
+
label,
|
|
183
|
+
...options
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
/** @deprecated Use `this.context.removeBlock(label)`. */
|
|
187
|
+
removeContext(label) {
|
|
188
|
+
return _classPrivateFieldGet2(_context, this).call(this).removeBlock(label);
|
|
189
|
+
}
|
|
190
|
+
/** @deprecated Use `this.context.getBlock(label)`. */
|
|
191
|
+
getContextBlock(label) {
|
|
192
|
+
return _classPrivateFieldGet2(_context, this).call(this).getBlock(label);
|
|
193
|
+
}
|
|
194
|
+
/** @deprecated Use `this.context.getBlocks()`. */
|
|
195
|
+
getContextBlocks() {
|
|
196
|
+
return _classPrivateFieldGet2(_context, this).call(this).getBlocks();
|
|
197
|
+
}
|
|
198
|
+
/** @deprecated Use `this.context.setBlock(label, content)`. */
|
|
199
|
+
replaceContextBlock(label, content) {
|
|
200
|
+
return _classPrivateFieldGet2(_context, this).call(this).setBlock(label, content);
|
|
201
|
+
}
|
|
202
|
+
/** @deprecated Use `this.context.appendToBlock(label, content)`. */
|
|
203
|
+
appendContextBlock(label, content) {
|
|
204
|
+
return _classPrivateFieldGet2(_context, this).call(this).appendToBlock(label, content);
|
|
205
|
+
}
|
|
206
|
+
/** @deprecated Use `this.context.freezeSystemPrompt()`. */
|
|
207
|
+
freezeSystemPrompt() {
|
|
208
|
+
return _classPrivateFieldGet2(_context, this).call(this).freezeSystemPrompt();
|
|
209
|
+
}
|
|
210
|
+
/** @deprecated Use `this.context.refreshSystemPrompt()`. */
|
|
211
|
+
refreshSystemPrompt() {
|
|
212
|
+
return _classPrivateFieldGet2(_context, this).call(this).refreshSystemPrompt();
|
|
213
|
+
}
|
|
214
|
+
/** @deprecated Use `this.context.tools()`. */
|
|
215
|
+
tools() {
|
|
216
|
+
return _classPrivateFieldGet2(_context, this).call(this).tools();
|
|
217
|
+
}
|
|
218
|
+
};
|
|
219
|
+
function readOptions(leafIdOrOptions) {
|
|
220
|
+
if (leafIdOrOptions === void 0) return void 0;
|
|
221
|
+
if (leafIdOrOptions === null || typeof leafIdOrOptions === "string") return { leafId: leafIdOrOptions };
|
|
222
|
+
return leafIdOrOptions;
|
|
223
|
+
}
|
|
224
|
+
function appendOptions(parentIdOrOptions) {
|
|
225
|
+
if (parentIdOrOptions === void 0) return void 0;
|
|
226
|
+
if (parentIdOrOptions === null || typeof parentIdOrOptions === "string") return { parentId: parentIdOrOptions };
|
|
227
|
+
return parentIdOrOptions;
|
|
228
|
+
}
|
|
229
|
+
//#endregion
|
|
20
230
|
//#region src/media-eviction.ts
|
|
231
|
+
/** Nested tool-output walks stop here so hostile output cannot recurse forever. */
|
|
232
|
+
const MAX_WALK_DEPTH = 8;
|
|
21
233
|
function resolveMediaEvictionConfig(config) {
|
|
22
234
|
if (config === false) return null;
|
|
23
235
|
const base = config === true ? {} : config;
|
|
24
236
|
return {
|
|
25
237
|
keepRecentMessages: base.keepRecentMessages ?? 8,
|
|
26
238
|
minPartBytes: base.minPartBytes ?? 32 * 1024,
|
|
27
|
-
externalizeToWorkspace: base.externalizeToWorkspace ?? true,
|
|
28
239
|
maxRowsPerPass: base.maxRowsPerPass ?? 64
|
|
29
240
|
};
|
|
30
241
|
}
|
|
31
|
-
const MAX_WALK_DEPTH = 8;
|
|
32
242
|
/**
|
|
33
|
-
*
|
|
34
|
-
*
|
|
243
|
+
* The exact marker Think has always written. Old and new markers are
|
|
244
|
+
* byte-identical, so a transcript evicted before and after the Sessions
|
|
245
|
+
* replatform reads the same and old markers keep resolving.
|
|
246
|
+
*/
|
|
247
|
+
function evictionMarker(bytes, path, mediaType) {
|
|
248
|
+
return `[evicted ${mediaType ? `${mediaType}, ` : ""}${bytes} bytes; preserved at ${path}]`;
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Replace aged oversized media in one message with markers, writing the
|
|
252
|
+
* bytes to the Workspace first. Returns a new message — the input is never
|
|
253
|
+
* mutated, and nothing is written when nothing qualifies.
|
|
35
254
|
*/
|
|
36
|
-
function
|
|
255
|
+
async function evictMediaFromMessage(message, options) {
|
|
37
256
|
const state = {
|
|
38
257
|
options,
|
|
258
|
+
index: 0,
|
|
39
259
|
parts: 0,
|
|
40
|
-
bytes: 0
|
|
41
|
-
blobs: []
|
|
260
|
+
bytes: 0
|
|
42
261
|
};
|
|
43
262
|
let changed = false;
|
|
44
|
-
const parts =
|
|
263
|
+
const parts = [];
|
|
264
|
+
for (const part of message.parts) {
|
|
45
265
|
if (part.type === "file" && "url" in part) {
|
|
46
|
-
const
|
|
47
|
-
if (
|
|
266
|
+
const marker = await evictUrl(state, part.url, part.mediaType);
|
|
267
|
+
if (marker !== null) {
|
|
48
268
|
changed = true;
|
|
49
|
-
|
|
50
|
-
const path = extractBlob(state, url, mediaType);
|
|
51
|
-
return {
|
|
269
|
+
parts.push({
|
|
52
270
|
type: "text",
|
|
53
|
-
text:
|
|
54
|
-
};
|
|
271
|
+
text: marker
|
|
272
|
+
});
|
|
273
|
+
continue;
|
|
55
274
|
}
|
|
56
|
-
|
|
275
|
+
parts.push(part);
|
|
276
|
+
continue;
|
|
57
277
|
}
|
|
58
278
|
if ((part.type.startsWith("tool-") || part.type === "dynamic-tool") && "output" in part) {
|
|
59
279
|
const output = part.output;
|
|
60
280
|
if (output !== void 0) {
|
|
61
281
|
const before = state.parts;
|
|
62
|
-
const
|
|
282
|
+
const rewritten = await walkAndEvict(state, output, 0);
|
|
63
283
|
if (state.parts > before) {
|
|
64
284
|
changed = true;
|
|
65
|
-
|
|
285
|
+
parts.push({
|
|
66
286
|
...part,
|
|
67
|
-
output:
|
|
68
|
-
};
|
|
287
|
+
output: rewritten
|
|
288
|
+
});
|
|
289
|
+
continue;
|
|
69
290
|
}
|
|
70
291
|
}
|
|
71
292
|
}
|
|
72
|
-
|
|
73
|
-
}
|
|
293
|
+
parts.push(part);
|
|
294
|
+
}
|
|
74
295
|
return {
|
|
75
296
|
message: changed ? {
|
|
76
297
|
...message,
|
|
@@ -78,60 +299,117 @@ function evictLargeMediaFromMessage(message, options) {
|
|
|
78
299
|
} : message,
|
|
79
300
|
changed,
|
|
80
301
|
parts: state.parts,
|
|
81
|
-
bytes: state.bytes
|
|
82
|
-
blobs: state.blobs
|
|
302
|
+
bytes: state.bytes
|
|
83
303
|
};
|
|
84
304
|
}
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
305
|
+
/**
|
|
306
|
+
* Evict one stored payload locator. Returns its marker, or `null` when the
|
|
307
|
+
* value is not an evictable payload or is below the size threshold.
|
|
308
|
+
*/
|
|
309
|
+
async function evictUrl(state, url, fallbackMediaType) {
|
|
310
|
+
if (typeof url !== "string") return null;
|
|
311
|
+
const payload = resolvePayload(state, url);
|
|
312
|
+
if (!payload) return null;
|
|
313
|
+
const mediaType = payload.mediaType ?? fallbackMediaType;
|
|
314
|
+
const path = await state.options.write(state.index, payload.bytes, mediaType);
|
|
315
|
+
state.index++;
|
|
316
|
+
state.parts++;
|
|
317
|
+
state.bytes += payload.bytes.byteLength;
|
|
318
|
+
return evictionMarker(payload.bytes.byteLength, path, mediaType);
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* A stored payload is always an inline `data:` URL now, so eviction decodes
|
|
322
|
+
* it directly.
|
|
323
|
+
*/
|
|
324
|
+
function resolvePayload(state, url) {
|
|
325
|
+
const { minPartBytes } = state.options;
|
|
326
|
+
if (!url.startsWith("data:")) return null;
|
|
327
|
+
if (url.length < minPartBytes) return null;
|
|
328
|
+
const decoded = decodeDataUrl(url);
|
|
329
|
+
if (!decoded || decoded.bytes.byteLength < minPartBytes) return null;
|
|
330
|
+
return decoded;
|
|
331
|
+
}
|
|
332
|
+
async function walkAndEvict(state, value, depth) {
|
|
333
|
+
if (typeof value === "string") return await evictUrl(state, value) ?? value;
|
|
92
334
|
if (value === null || typeof value !== "object" || depth >= MAX_WALK_DEPTH) return value;
|
|
93
335
|
if (Array.isArray(value)) {
|
|
94
336
|
let changed = false;
|
|
95
|
-
const result =
|
|
96
|
-
|
|
337
|
+
const result = [];
|
|
338
|
+
for (const item of value) {
|
|
339
|
+
const next = await walkAndEvict(state, item, depth + 1);
|
|
97
340
|
if (next !== item) changed = true;
|
|
98
|
-
|
|
99
|
-
}
|
|
341
|
+
result.push(next);
|
|
342
|
+
}
|
|
100
343
|
return changed ? result : value;
|
|
101
344
|
}
|
|
102
345
|
let changed = false;
|
|
103
346
|
const result = {};
|
|
104
347
|
for (const [key, entry] of Object.entries(value)) {
|
|
105
|
-
const next = walkAndEvict(state, entry, depth + 1);
|
|
348
|
+
const next = await walkAndEvict(state, entry, depth + 1);
|
|
106
349
|
if (next !== entry) changed = true;
|
|
107
350
|
result[key] = next;
|
|
108
351
|
}
|
|
109
352
|
return changed ? result : value;
|
|
110
353
|
}
|
|
111
|
-
/**
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
const
|
|
126
|
-
|
|
354
|
+
/**
|
|
355
|
+
* Whether a pass over `message` could evict anything: a file part or a tool
|
|
356
|
+
* output holding a `data:` URL at least `minPartBytes` long. Decodes nothing —
|
|
357
|
+
* this is the in-memory gate that decides whether a pass is worth scheduling,
|
|
358
|
+
* so a decoded payload that turns out smaller than the threshold is merely a
|
|
359
|
+
* pass that changes nothing.
|
|
360
|
+
*/
|
|
361
|
+
function hasEvictableMedia(message, minPartBytes) {
|
|
362
|
+
const isCandidate = (value) => typeof value === "string" && value.length >= minPartBytes && value.startsWith("data:");
|
|
363
|
+
const walk = (value, depth) => {
|
|
364
|
+
if (isCandidate(value)) return true;
|
|
365
|
+
if (value === null || typeof value !== "object" || depth >= MAX_WALK_DEPTH) return false;
|
|
366
|
+
return (Array.isArray(value) ? value : Object.values(value)).some((entry) => walk(entry, depth + 1));
|
|
367
|
+
};
|
|
368
|
+
for (const part of message.parts) {
|
|
369
|
+
if (part.type === "file" && "url" in part) {
|
|
370
|
+
if (isCandidate(part.url)) return true;
|
|
371
|
+
continue;
|
|
372
|
+
}
|
|
373
|
+
if ((part.type.startsWith("tool-") || part.type === "dynamic-tool") && "output" in part && walk(part.output, 0)) return true;
|
|
374
|
+
}
|
|
375
|
+
return false;
|
|
127
376
|
}
|
|
128
|
-
|
|
129
|
-
|
|
377
|
+
/** Decode a `data:` URL into raw bytes. Returns null when it is malformed. */
|
|
378
|
+
function decodeDataUrl(url) {
|
|
379
|
+
const comma = url.indexOf(",");
|
|
380
|
+
if (comma === -1) return null;
|
|
381
|
+
const header = url.slice(5, comma);
|
|
382
|
+
const base64 = /;base64$/i.test(header);
|
|
383
|
+
const mediaType = header.replace(/;base64$/i, "").split(";")[0]?.trim() || void 0;
|
|
384
|
+
const payload = url.slice(comma + 1);
|
|
385
|
+
try {
|
|
386
|
+
if (base64) {
|
|
387
|
+
const binary = atob(payload);
|
|
388
|
+
const bytes = new Uint8Array(binary.length);
|
|
389
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
390
|
+
return mediaType === void 0 ? { bytes } : {
|
|
391
|
+
bytes,
|
|
392
|
+
mediaType
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
const bytes = new TextEncoder().encode(decodeURIComponent(payload));
|
|
396
|
+
return mediaType === void 0 ? { bytes } : {
|
|
397
|
+
bytes,
|
|
398
|
+
mediaType
|
|
399
|
+
};
|
|
400
|
+
} catch {
|
|
401
|
+
return null;
|
|
402
|
+
}
|
|
130
403
|
}
|
|
404
|
+
/** File extension for an evicted payload, derived from its media type. */
|
|
131
405
|
function extensionFor(mediaType) {
|
|
132
406
|
if (!mediaType) return "txt";
|
|
133
407
|
return mediaType.split("/")[1]?.replace(/[^a-zA-Z0-9]/g, "") || "bin";
|
|
134
408
|
}
|
|
409
|
+
/** Workspace path for the n-th value evicted from a message. */
|
|
410
|
+
function evictedFilePath(messageId, index, mediaType) {
|
|
411
|
+
return `/attachments/evicted/${messageId}-${index}.${extensionFor(mediaType)}`;
|
|
412
|
+
}
|
|
135
413
|
//#endregion
|
|
136
414
|
//#region src/channels/index.ts
|
|
137
415
|
/** Wrap a {@link MessengerDefinition} as a `kind: "messenger"` channel. */
|
|
@@ -229,7 +507,8 @@ function resolveChannels(configured, messengers) {
|
|
|
229
507
|
* - getSystemPrompt() — return the legacy fallback system prompt
|
|
230
508
|
* - getTools() — return the ToolSet for the agentic loop
|
|
231
509
|
* - maxSteps — max tool-call rounds per turn (default: 10)
|
|
232
|
-
* - configureSession() —
|
|
510
|
+
* - configureSession() — compaction and search policy
|
|
511
|
+
* - configureContext() — declare prompt context blocks
|
|
233
512
|
*
|
|
234
513
|
* Lifecycle hooks:
|
|
235
514
|
* - beforeTurn() — inspect/override context, tools, model before inference
|
|
@@ -277,21 +556,23 @@ function resolveChannels(configured, messengers) {
|
|
|
277
556
|
* @example With context blocks and self-updating memory
|
|
278
557
|
* ```typescript
|
|
279
558
|
* import { Think } from "@cloudflare/think";
|
|
280
|
-
* import type {
|
|
559
|
+
* import type { ContextConfig } from "agents/context";
|
|
281
560
|
*
|
|
282
561
|
* export class MemoryAgent extends Think<Env> {
|
|
283
562
|
* getModel() { ... }
|
|
284
563
|
*
|
|
285
|
-
*
|
|
286
|
-
* return
|
|
287
|
-
*
|
|
564
|
+
* configureContext(): ContextConfig[] {
|
|
565
|
+
* return [
|
|
566
|
+
* {
|
|
567
|
+
* label: "soul",
|
|
288
568
|
* provider: { get: async () => "You are a helpful coding assistant." }
|
|
289
|
-
* }
|
|
290
|
-
*
|
|
569
|
+
* },
|
|
570
|
+
* {
|
|
571
|
+
* label: "memory",
|
|
291
572
|
* description: "Important facts learned during conversation.",
|
|
292
573
|
* maxTokens: 2000
|
|
293
|
-
* }
|
|
294
|
-
*
|
|
574
|
+
* }
|
|
575
|
+
* ];
|
|
295
576
|
* }
|
|
296
577
|
* }
|
|
297
578
|
* ```
|
|
@@ -304,15 +585,19 @@ const usesAISDKV7Telemetry = "registerTelemetry" in aiSdk;
|
|
|
304
585
|
* `truncateOlderMessages`' default `keepRecent` (see `_assembleModelMessages`).
|
|
305
586
|
*
|
|
306
587
|
* Both memory bounds are anchored to this window (#1710):
|
|
307
|
-
* - budgeted hydration
|
|
308
|
-
*
|
|
309
|
-
*
|
|
588
|
+
* - budgeted hydration (`hydrationByteBudget`) is a hard byte ceiling, so a
|
|
589
|
+
* window of unusually large messages can be shorter than this; the model
|
|
590
|
+
* then sees what fits rather than exhausting isolate memory;
|
|
310
591
|
* - media eviction never rewrites messages inside it (the
|
|
311
|
-
* `keepRecentMessages` clamp), so
|
|
312
|
-
* fidelity
|
|
592
|
+
* `keepRecentMessages` clamp), so the rows the model replays at full
|
|
593
|
+
* fidelity are never stripped.
|
|
313
594
|
*/
|
|
314
595
|
const MODEL_RECENT_WINDOW = 4;
|
|
315
596
|
const DEFAULT_ACTION_TIMEOUT_MS = 3e4;
|
|
597
|
+
/** Whether a workspace can receive raw bytes, which skills projection needs. */
|
|
598
|
+
function hasWriteFileBytes(workspace) {
|
|
599
|
+
return typeof workspace.writeFileBytes === "function";
|
|
600
|
+
}
|
|
316
601
|
const ACTION_OUTPUT_MAX_CHARS = 2e4;
|
|
317
602
|
const MAX_REPLY_ATTACHMENTS_PER_TURN = 32;
|
|
318
603
|
const ACTION_LEDGER_SWEEP_INTERVAL_MS = 3600 * 1e3;
|
|
@@ -799,12 +1084,44 @@ function isAction(value) {
|
|
|
799
1084
|
const admittedTurnContext = new AsyncLocalStorage();
|
|
800
1085
|
const inferenceStreamFinalizers = /* @__PURE__ */ new WeakMap();
|
|
801
1086
|
const THINK_WORKFLOW_PROMPT_METADATA_KEY = "__thinkWorkflowPrompt";
|
|
1087
|
+
const THINK_WORKFLOW_NOTIFICATIONS_JOB_ID = "think:workflow-notifications";
|
|
802
1088
|
/**
|
|
803
1089
|
* Message-metadata keys that are server-written turn context (stamped by
|
|
804
1090
|
* `_stampChannel`) and trusted by hooks and recovery. They are stripped from
|
|
805
1091
|
* client-supplied messages at intake so a client can never forge them.
|
|
806
1092
|
*/
|
|
807
1093
|
const RESERVED_MESSAGE_METADATA_KEYS = ["channel", "turnMetadata"];
|
|
1094
|
+
const cachedMessageEncoder = new TextEncoder();
|
|
1095
|
+
/**
|
|
1096
|
+
* A cached message's size in the unit the hydration budget is measured in:
|
|
1097
|
+
* UTF-8 bytes of its serialized form, not UTF-16 code units.
|
|
1098
|
+
*/
|
|
1099
|
+
function cachedMessageBytes(message) {
|
|
1100
|
+
return cachedMessageEncoder.encode(JSON.stringify(message)).byteLength;
|
|
1101
|
+
}
|
|
1102
|
+
/**
|
|
1103
|
+
* The stored form of a client-sourced message's metadata: Sessions drops the
|
|
1104
|
+
* reserved keys on every client write, so a compare against a stored row has
|
|
1105
|
+
* to drop them too. Mirrors `SessionCore.stripReservedMetadata` for the keys
|
|
1106
|
+
* Think registers.
|
|
1107
|
+
*/
|
|
1108
|
+
function stripReservedMetadata(message) {
|
|
1109
|
+
const metadata = message.metadata;
|
|
1110
|
+
if (typeof metadata !== "object" || metadata === null || Array.isArray(metadata)) return message;
|
|
1111
|
+
const remaining = { ...metadata };
|
|
1112
|
+
let changed = false;
|
|
1113
|
+
for (const key of RESERVED_MESSAGE_METADATA_KEYS) if (key in remaining) {
|
|
1114
|
+
delete remaining[key];
|
|
1115
|
+
changed = true;
|
|
1116
|
+
}
|
|
1117
|
+
if (!changed) return message;
|
|
1118
|
+
if (Object.keys(remaining).length > 0) return {
|
|
1119
|
+
...message,
|
|
1120
|
+
metadata: remaining
|
|
1121
|
+
};
|
|
1122
|
+
const { metadata: _dropped, ...withoutMetadata } = message;
|
|
1123
|
+
return withoutMetadata;
|
|
1124
|
+
}
|
|
808
1125
|
/** Stable id prefix for fallback notes that preserve orphaned execution outcomes. */
|
|
809
1126
|
const EXECUTION_OUTCOME_MESSAGE_PREFIX = "exec-outcome-";
|
|
810
1127
|
/**
|
|
@@ -909,9 +1226,27 @@ function defaultContextOverflowClassifier(error) {
|
|
|
909
1226
|
}
|
|
910
1227
|
return CONTEXT_OVERFLOW_PATTERN.test(text) ? "context_overflow" : void 0;
|
|
911
1228
|
}
|
|
1229
|
+
/**
|
|
1230
|
+
* Definition name for messenger reply runs on the Tasks capability. The
|
|
1231
|
+
* reserved prefix keeps it outside the public `fibers.run()` surface; the
|
|
1232
|
+
* recovery context still carries the historical `MESSENGER_REPLY_FIBER_NAME`
|
|
1233
|
+
* so the messenger runtime's recovery gate is unchanged.
|
|
1234
|
+
*/
|
|
1235
|
+
const MESSENGER_REPLY_TASK_DEFINITION = "__cf_internal_messenger_reply";
|
|
1236
|
+
var _contextBlocks = /* @__PURE__ */ new WeakMap();
|
|
1237
|
+
var _Think_brand = /* @__PURE__ */ new WeakSet();
|
|
912
1238
|
var _configCache = /* @__PURE__ */ new WeakMap();
|
|
913
1239
|
var _configTableReady = /* @__PURE__ */ new WeakMap();
|
|
1240
|
+
var _configMemo = /* @__PURE__ */ new WeakMap();
|
|
1241
|
+
var _agentToolChildRunTableReady = /* @__PURE__ */ new WeakMap();
|
|
914
1242
|
var Think = class Think extends Agent {
|
|
1243
|
+
/**
|
|
1244
|
+
* The agent's context blocks. Available once the Lifecycle has started.
|
|
1245
|
+
*/
|
|
1246
|
+
get context() {
|
|
1247
|
+
if (!_classPrivateFieldGet2(_contextBlocks, this)) throw new Error("Context is not initialized yet; it is available after onStart().");
|
|
1248
|
+
return _classPrivateFieldGet2(_contextBlocks, this);
|
|
1249
|
+
}
|
|
915
1250
|
/**
|
|
916
1251
|
* Internal onStart steps that failed on this wake and were skipped so the
|
|
917
1252
|
* agent could still come up (see {@link OnStartDegradation}). Empty when
|
|
@@ -923,30 +1258,39 @@ var Think = class Think extends Agent {
|
|
|
923
1258
|
}
|
|
924
1259
|
constructor(ctx, env) {
|
|
925
1260
|
super(ctx, env);
|
|
1261
|
+
_classPrivateMethodInitSpec(this, _Think_brand);
|
|
926
1262
|
this.includeMcpTools = true;
|
|
927
1263
|
this.waitForMcpConnections = false;
|
|
928
1264
|
this.storeMessages = false;
|
|
929
1265
|
this.storeTools = false;
|
|
1266
|
+
this.skillWorkspace = false;
|
|
930
1267
|
this._skillRegistry = null;
|
|
931
1268
|
this._loggedSkillWarnings = /* @__PURE__ */ new Set();
|
|
932
1269
|
this._loggedProtocolWarnings = /* @__PURE__ */ new Set();
|
|
933
1270
|
this.messageConcurrency = "queue";
|
|
934
|
-
this.hydrationByteBudget =
|
|
1271
|
+
this.hydrationByteBudget = 32 * 1024 * 1024;
|
|
935
1272
|
this.mediaEviction = true;
|
|
936
1273
|
this.chatRecovery = true;
|
|
1274
|
+
this.sessions = new Sessions({ reservedMetadataKeys: RESERVED_MESSAGE_METADATA_KEYS });
|
|
1275
|
+
_classPrivateFieldInitSpec(this, _contextBlocks, void 0);
|
|
937
1276
|
this._cachedMessages = [];
|
|
938
1277
|
this._onStartDegradations = [];
|
|
939
1278
|
this.workspaceBash = true;
|
|
940
1279
|
this.fetchTools = false;
|
|
941
1280
|
this._mediaEvictionRunning = false;
|
|
942
1281
|
this._mediaEvictionScheduled = false;
|
|
943
|
-
this.
|
|
1282
|
+
this._mediaEvictionPending = false;
|
|
1283
|
+
this._mediaEvictionAppendsDuringPass = 0;
|
|
944
1284
|
this._warnedEvictionUnsupported = false;
|
|
1285
|
+
this._mediaEvictionFruitless = null;
|
|
945
1286
|
this._lastHydration = null;
|
|
946
1287
|
this._warnedHydrationWindowed = false;
|
|
1288
|
+
this._cacheCoversActivePath = false;
|
|
1289
|
+
this._cachedBytesSinceSync = 0;
|
|
947
1290
|
this._lastWindowedEmit = null;
|
|
948
1291
|
this._aborts = new AbortRegistry();
|
|
949
1292
|
this._turnQueue = new TurnQueue();
|
|
1293
|
+
this.streams = createChatStreams();
|
|
950
1294
|
this._pendingResumeConnections = /* @__PURE__ */ new Set();
|
|
951
1295
|
this._resumeHandshakeInstance = null;
|
|
952
1296
|
this._continuation = new ContinuationState();
|
|
@@ -985,6 +1329,8 @@ var Think = class Think extends Agent {
|
|
|
985
1329
|
this._programmaticStreamErrors = /* @__PURE__ */ new Map();
|
|
986
1330
|
_classPrivateFieldInitSpec(this, _configCache, null);
|
|
987
1331
|
_classPrivateFieldInitSpec(this, _configTableReady, false);
|
|
1332
|
+
_classPrivateFieldInitSpec(this, _configMemo, /* @__PURE__ */ new Map());
|
|
1333
|
+
this._liveChatTurnClosures = /* @__PURE__ */ new Map();
|
|
988
1334
|
this.maxSteps = 10;
|
|
989
1335
|
this.actionLedgerRetention = {
|
|
990
1336
|
settledMs: 720 * 60 * 60 * 1e3,
|
|
@@ -1006,9 +1352,16 @@ var Think = class Think extends Agent {
|
|
|
1006
1352
|
this._proactiveCompactionsThisRun = 0;
|
|
1007
1353
|
this._warnedMissingClassifier = false;
|
|
1008
1354
|
this.hookTimeout = 5e3;
|
|
1355
|
+
_classPrivateFieldInitSpec(this, _agentToolChildRunTableReady, false);
|
|
1009
1356
|
this._agentToolProgressEmitterInstance = null;
|
|
1010
|
-
this.
|
|
1357
|
+
this._persistedRequestContext = {};
|
|
1358
|
+
this._progressSeed = null;
|
|
1011
1359
|
this._agentToolStreamProgress = new AgentToolStreamProgressThrottle();
|
|
1360
|
+
this.lifecycle.use(this.sessions);
|
|
1361
|
+
this.lifecycle.use(this.streams);
|
|
1362
|
+
this._registerChatTurnTaskDefinition();
|
|
1363
|
+
this._registerChatRecoveryTaskDefinition();
|
|
1364
|
+
this._registerMessengerReplyTaskDefinition();
|
|
1012
1365
|
const _onStart = this.onStart.bind(this);
|
|
1013
1366
|
const startThink = async (props, update) => {
|
|
1014
1367
|
await withAgentSpan(this, "initialize_think_session", "startup", { "cloudflare.agents.component": "think" }, async () => {
|
|
@@ -1016,24 +1369,42 @@ var Think = class Think extends Agent {
|
|
|
1016
1369
|
sql: this.ctx.storage.sql,
|
|
1017
1370
|
name: () => this.name
|
|
1018
1371
|
});
|
|
1019
|
-
|
|
1020
|
-
this.session
|
|
1021
|
-
this.
|
|
1372
|
+
this.session = await this.configureSession(new ThinkSession(this.sessions.session(), () => this.context));
|
|
1373
|
+
_classPrivateFieldSet2(_contextBlocks, this, new ContextBlocks([...await this.configureContext(), ...this.session.internal_takePendingContext()], this.session.internal_promptStore() ?? _assertClassBrand(_Think_brand, this, _contextProvider).call(this, "_system_prompt"), (label) => _assertClassBrand(_Think_brand, this, _contextProvider).call(this, label)));
|
|
1374
|
+
await _classPrivateFieldGet2(_contextBlocks, this).load();
|
|
1375
|
+
this._unsubscribeSessionChanges?.();
|
|
1376
|
+
this._unsubscribeSessionChanges = this.sessions.subscribe(async (event) => {
|
|
1377
|
+
if (event.sessionId !== this.session.sessionId) return;
|
|
1022
1378
|
switch (event.type) {
|
|
1023
1379
|
case "append":
|
|
1024
1380
|
if (!event.inserted || event.parentId !== void 0) await this._syncMessages();
|
|
1025
|
-
else
|
|
1026
|
-
|
|
1381
|
+
else {
|
|
1382
|
+
this._upsertCachedMessage(event.message);
|
|
1383
|
+
this._noteCachedGrowth(cachedMessageBytes(event.message));
|
|
1384
|
+
if (this._mediaEvictionFruitless) this._mediaEvictionFruitless.appendsSince++;
|
|
1385
|
+
if (this._mediaEvictionRunning) this._mediaEvictionAppendsDuringPass++;
|
|
1386
|
+
this._scheduleMediaEvictionPass();
|
|
1387
|
+
}
|
|
1388
|
+
break;
|
|
1389
|
+
case "import":
|
|
1390
|
+
this._cacheCoversActivePath = false;
|
|
1391
|
+
break;
|
|
1392
|
+
case "compaction":
|
|
1393
|
+
await this._syncMessages();
|
|
1027
1394
|
break;
|
|
1028
1395
|
case "update":
|
|
1029
|
-
this._patchCachedMessage(event.message);
|
|
1396
|
+
if (this._cachedMessages.some((message) => message.id === event.message.id)) this._patchCachedMessage(event.message);
|
|
1030
1397
|
break;
|
|
1031
1398
|
case "clear":
|
|
1032
1399
|
this._replaceCachedMessages([]);
|
|
1400
|
+
this._cacheCoversActivePath = true;
|
|
1033
1401
|
break;
|
|
1034
1402
|
case "delete":
|
|
1403
|
+
await this._syncMessages();
|
|
1404
|
+
break;
|
|
1035
1405
|
case "compact":
|
|
1036
1406
|
await this._syncMessages();
|
|
1407
|
+
await _classPrivateFieldGet2(_contextBlocks, this)?.refreshSystemPrompt();
|
|
1037
1408
|
break;
|
|
1038
1409
|
}
|
|
1039
1410
|
});
|
|
@@ -1042,11 +1413,12 @@ var Think = class Think extends Agent {
|
|
|
1042
1413
|
this._onStartDegradations = [];
|
|
1043
1414
|
await withAgentSpan(this, "hydrate_think_session", "startup", { "cloudflare.agents.component": "think" }, async () => {
|
|
1044
1415
|
if (!await this._runBestEffortOnStartStep("transcript-hydration", () => this._syncMessages(), "The agent is starting with an empty in-memory message view; persisted history is untouched. If the error is SQLITE_NOMEM, the stored transcript is too large to hydrate (often inline base64 media in tool results) — compact or clear the session to recover.")) this._replaceCachedMessages([]);
|
|
1045
|
-
this._refreshMediaEvictionSignalFromCache();
|
|
1046
1416
|
});
|
|
1047
1417
|
if (this.extensionLoader) await withAgentSpan(this, "initialize_think_extensions", "startup", { "cloudflare.agents.component": "think" }, () => this._initializeExtensions());
|
|
1048
1418
|
await withAgentSpan(this, "initialize_think_chat", "startup", { "cloudflare.agents.component": "think" }, async () => {
|
|
1049
|
-
this._resumableStream = new ResumableStream(this.sql.bind(this))
|
|
1419
|
+
this._resumableStream = new ResumableStream(this.streams, this.sql.bind(this), { onProgress: (durable) => {
|
|
1420
|
+
this.ctx.storage.put(CHAT_RECOVERY_PROGRESS_KEY, durable).catch(() => {});
|
|
1421
|
+
} });
|
|
1050
1422
|
this._restoreClientTools();
|
|
1051
1423
|
this._restoreBody();
|
|
1052
1424
|
this._setupProtocolHandlers();
|
|
@@ -1062,7 +1434,6 @@ var Think = class Think extends Agent {
|
|
|
1062
1434
|
if (this._hasPendingSubmissions()) await this._scheduleSubmissionDrain();
|
|
1063
1435
|
if (this._hasPendingWorkflowNotifications()) this._startWorkflowNotificationDrain();
|
|
1064
1436
|
}, "Pending submissions / workflow notifications were not recovered on this wake; the next successful wake will recover them."));
|
|
1065
|
-
if (this._lastHydration?.truncated) this._scheduleMediaEvictionPass({ force: true });
|
|
1066
1437
|
update({
|
|
1067
1438
|
"cloudflare.agents.hydration.messages": this._lastHydration?.hydratedMessages,
|
|
1068
1439
|
"cloudflare.agents.hydration.content_bytes": this._lastHydration?.totalContentBytes,
|
|
@@ -1092,11 +1463,12 @@ var Think = class Think extends Agent {
|
|
|
1092
1463
|
*
|
|
1093
1464
|
* Intentionally UNBUDGETED — unlike the cache refresh in `_syncMessages`,
|
|
1094
1465
|
* which routes through `session.getRecentHistory(hydrationByteBudget)`, this
|
|
1095
|
-
* returns the full active path.
|
|
1096
|
-
*
|
|
1097
|
-
*
|
|
1098
|
-
*
|
|
1099
|
-
*
|
|
1466
|
+
* returns the full active path. Its caller, message reconciliation, must see
|
|
1467
|
+
* every message: it diffs incoming client messages against the complete
|
|
1468
|
+
* server transcript, so a windowed read would drop rows and corrupt the
|
|
1469
|
+
* result. It is reached only when the live cache does not already cover the
|
|
1470
|
+
* path (`_serverTranscriptForReconcile`); tool-update application resolves
|
|
1471
|
+
* its one target row without it (`_resolveToolCallOwner`).
|
|
1100
1472
|
*
|
|
1101
1473
|
* These full reads are not the unbounded boot-time hydration that bricked the
|
|
1102
1474
|
* DO in #1710: they run during a live turn (never in `onStart`), so an
|
|
@@ -1183,7 +1555,7 @@ var Think = class Think extends Agent {
|
|
|
1183
1555
|
if (repair.removedToolCalls === 0 && repair.normalizedInputs === 0) return messages;
|
|
1184
1556
|
for (const message of repair.messages) {
|
|
1185
1557
|
const original = messages.find((candidate) => candidate.id === message.id);
|
|
1186
|
-
if (original && original.parts !== message.parts) await this.session.updateMessage(
|
|
1558
|
+
if (original && original.parts !== message.parts) await this.session.updateMessage(message);
|
|
1187
1559
|
}
|
|
1188
1560
|
this._replaceCachedMessages(repair.messages);
|
|
1189
1561
|
this._broadcastMessages();
|
|
@@ -1226,121 +1598,133 @@ var Think = class Think extends Agent {
|
|
|
1226
1598
|
}
|
|
1227
1599
|
}
|
|
1228
1600
|
/**
|
|
1229
|
-
*
|
|
1230
|
-
*
|
|
1231
|
-
*
|
|
1232
|
-
*
|
|
1601
|
+
* Whether the cache can stand in for the stored path when deciding if an
|
|
1602
|
+
* eviction pass is worth running. It cannot when the hydration is a window
|
|
1603
|
+
* of the path, or when a compaction overlay collapses rows the pass would
|
|
1604
|
+
* still read and rewrite.
|
|
1233
1605
|
*/
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1606
|
+
_agedRowsHiddenFromCache() {
|
|
1607
|
+
return this._lastHydration?.truncated === true || this._cachedMessages.some((message) => isCompactionMessage(message));
|
|
1608
|
+
}
|
|
1609
|
+
/**
|
|
1610
|
+
* Schedule a bounded media-eviction pass (see `mediaEviction`).
|
|
1611
|
+
*
|
|
1612
|
+
* Coalesces repeated requests and defers past the current event-loop work,
|
|
1613
|
+
* so it is safe to call from the cache-refresh path that `onStart` runs
|
|
1614
|
+
* inside `blockConcurrencyWhile`: the pass itself never runs in `onStart`,
|
|
1615
|
+
* and `_evictAgedMediaBestEffort` swallows its own failures, so a bad pass
|
|
1616
|
+
* can never brick the object.
|
|
1617
|
+
*/
|
|
1618
|
+
_scheduleMediaEvictionPass() {
|
|
1619
|
+
if (this._mediaEvictionScheduled) return;
|
|
1620
|
+
if (this._mediaEvictionRunning) {
|
|
1621
|
+
this._mediaEvictionPending = true;
|
|
1622
|
+
return;
|
|
1623
|
+
}
|
|
1624
|
+
const config = resolveMediaEvictionConfig(this.mediaEviction);
|
|
1625
|
+
if (!config) return;
|
|
1626
|
+
const keepRecent = Math.max(config.keepRecentMessages, MODEL_RECENT_WINDOW);
|
|
1627
|
+
if (this._agedRowsHiddenFromCache()) {
|
|
1628
|
+
const fruitless = this._mediaEvictionFruitless;
|
|
1629
|
+
if (fruitless !== null && this._lastHydration !== null && fruitless.storedBytes === this._lastHydration.totalContentBytes && fruitless.appendsSince < keepRecent) return;
|
|
1630
|
+
} else if (!this._cachedMessages.slice(0, Math.max(0, this._cachedMessages.length - keepRecent)).some((message) => hasEvictableMedia(message, config.minPartBytes))) return;
|
|
1238
1631
|
this._mediaEvictionScheduled = true;
|
|
1239
1632
|
setTimeout(() => {
|
|
1240
1633
|
this._mediaEvictionScheduled = false;
|
|
1241
1634
|
this._evictAgedMediaBestEffort();
|
|
1242
1635
|
}, 0);
|
|
1243
1636
|
}
|
|
1244
|
-
_scheduleMediaEvictionAfterAppend(message) {
|
|
1245
|
-
const config = resolveMediaEvictionConfig(this.mediaEviction);
|
|
1246
|
-
if (!config) return;
|
|
1247
|
-
if (!this._mediaEvictionObservedOversized) this._mediaEvictionObservedOversized = this._messageMayNeedMediaEviction(message, config);
|
|
1248
|
-
if (!this._mediaEvictionObservedOversized) return;
|
|
1249
|
-
const keepRecent = Math.max(config.keepRecentMessages, MODEL_RECENT_WINDOW);
|
|
1250
|
-
if (this._cachedMessages.length > keepRecent) this._scheduleMediaEvictionPass({ force: true });
|
|
1251
|
-
}
|
|
1252
|
-
_refreshMediaEvictionSignalFromCache() {
|
|
1253
|
-
const config = resolveMediaEvictionConfig(this.mediaEviction);
|
|
1254
|
-
if (!config) {
|
|
1255
|
-
this._mediaEvictionObservedOversized = false;
|
|
1256
|
-
return;
|
|
1257
|
-
}
|
|
1258
|
-
this._mediaEvictionObservedOversized = this._cachedMessages.some((message) => this._messageMayNeedMediaEviction(message, config));
|
|
1259
|
-
}
|
|
1260
|
-
_messageMayNeedMediaEviction(message, config) {
|
|
1261
|
-
return JSON.stringify(message).length >= config.minPartBytes;
|
|
1262
|
-
}
|
|
1263
1637
|
/**
|
|
1264
|
-
*
|
|
1638
|
+
* Remove aged media from the conversation, leaving a Workspace pointer the
|
|
1639
|
+
* agent can read back.
|
|
1265
1640
|
*
|
|
1266
|
-
* Memory-bounded by design:
|
|
1267
|
-
* (no content loaded), only rows
|
|
1268
|
-
*
|
|
1269
|
-
*
|
|
1270
|
-
*
|
|
1271
|
-
*
|
|
1272
|
-
* workspace BEFORE the row is rewritten, so a failed pass never loses
|
|
1273
|
-
* data. Best-effort: failures are logged and the next pass retries.
|
|
1641
|
+
* Memory-bounded by design: candidate sizes come from `getHistoryRowStats()`
|
|
1642
|
+
* (no content loaded), only rows big enough to hold an evictable payload are
|
|
1643
|
+
* read, and they are processed one at a time. Bytes are written to the
|
|
1644
|
+
* Workspace BEFORE the row is rewritten, so a failed pass never loses data;
|
|
1645
|
+
* once the rewritten row is stored, its Sessions attachment reference is
|
|
1646
|
+
* gone and the blob is reaped, so the bytes live in exactly one place.
|
|
1274
1647
|
*
|
|
1275
1648
|
* The aged cutoff is `keepRecentMessages` clamped to at least
|
|
1276
|
-
* `MODEL_RECENT_WINDOW`: messages the model still replays at full
|
|
1277
|
-
*
|
|
1278
|
-
*
|
|
1279
|
-
* When a pass stops at `maxRowsPerPass` with eligible rows remaining,
|
|
1280
|
-
* another pass is scheduled automatically so a large backlog drains
|
|
1281
|
-
* without waiting for new appends. Termination is guaranteed: every
|
|
1282
|
-
* rewritten row drops below `minPartBytes` and is skipped by later
|
|
1283
|
-
* passes, so the eligible set strictly shrinks.
|
|
1649
|
+
* `MODEL_RECENT_WINDOW`: messages the model still replays at full fidelity
|
|
1650
|
+
* are never rewritten, whatever the configuration says.
|
|
1284
1651
|
*
|
|
1285
|
-
*
|
|
1286
|
-
*
|
|
1652
|
+
* Best-effort: failures are logged and the next pass retries. When a pass
|
|
1653
|
+
* stops at `maxRowsPerPass` having made progress, the next one is scheduled
|
|
1654
|
+
* so a backlog drains on its own; a pass that changed nothing does not
|
|
1655
|
+
* reschedule, which is what guarantees termination.
|
|
1287
1656
|
*/
|
|
1288
1657
|
async _evictAgedMediaBestEffort() {
|
|
1289
1658
|
if (this._mediaEvictionRunning) return null;
|
|
1290
1659
|
const config = resolveMediaEvictionConfig(this.mediaEviction);
|
|
1291
1660
|
if (!config) return null;
|
|
1292
1661
|
this._mediaEvictionRunning = true;
|
|
1293
|
-
|
|
1662
|
+
this._mediaEvictionAppendsDuringPass = 0;
|
|
1663
|
+
const totals = {
|
|
1664
|
+
messages: 0,
|
|
1665
|
+
parts: 0,
|
|
1666
|
+
bytes: 0,
|
|
1667
|
+
backlogRemains: false
|
|
1668
|
+
};
|
|
1294
1669
|
try {
|
|
1295
|
-
const
|
|
1296
|
-
if (!
|
|
1670
|
+
const writeFileBytes = this.workspace.writeFileBytes?.bind(this.workspace);
|
|
1671
|
+
if (!writeFileBytes) {
|
|
1297
1672
|
if (!this._warnedEvictionUnsupported) {
|
|
1298
1673
|
this._warnedEvictionUnsupported = true;
|
|
1299
|
-
console.warn("[Think] mediaEviction is enabled but the configured
|
|
1674
|
+
console.warn("[Think] mediaEviction is enabled but the configured workspace does not implement writeFileBytes; media eviction is a no-op for this agent.");
|
|
1300
1675
|
}
|
|
1301
1676
|
return null;
|
|
1302
1677
|
}
|
|
1678
|
+
const stats = await this.session.getHistoryRowStats();
|
|
1303
1679
|
const keepRecent = Math.max(config.keepRecentMessages, MODEL_RECENT_WINDOW);
|
|
1304
1680
|
const aged = stats.slice(0, Math.max(0, stats.length - keepRecent));
|
|
1305
1681
|
let processed = 0;
|
|
1306
|
-
const totals = {
|
|
1307
|
-
messages: 0,
|
|
1308
|
-
parts: 0,
|
|
1309
|
-
bytes: 0,
|
|
1310
|
-
externalizedBytes: 0
|
|
1311
|
-
};
|
|
1312
1682
|
for (const row of aged) {
|
|
1313
1683
|
if (row.bytes < config.minPartBytes) continue;
|
|
1314
1684
|
if (processed >= config.maxRowsPerPass) {
|
|
1315
|
-
backlogRemains = true;
|
|
1685
|
+
totals.backlogRemains = true;
|
|
1316
1686
|
break;
|
|
1317
1687
|
}
|
|
1318
1688
|
processed++;
|
|
1319
1689
|
const message = await this.session.getMessage(row.id);
|
|
1320
1690
|
if (!message) continue;
|
|
1321
|
-
const result =
|
|
1691
|
+
const result = await evictMediaFromMessage(message, {
|
|
1322
1692
|
minPartBytes: config.minPartBytes,
|
|
1323
|
-
|
|
1324
|
-
|
|
1693
|
+
write: async (index, bytes, mediaType) => {
|
|
1694
|
+
const path = evictedFilePath(message.id, index, mediaType);
|
|
1695
|
+
await writeFileBytes(path, bytes, mediaType ?? "application/octet-stream");
|
|
1696
|
+
return path;
|
|
1697
|
+
}
|
|
1325
1698
|
});
|
|
1326
1699
|
if (!result.changed) continue;
|
|
1327
|
-
|
|
1328
|
-
await this.workspace.writeFile(blob.path, blob.data);
|
|
1329
|
-
totals.externalizedBytes += blob.data.length;
|
|
1330
|
-
}
|
|
1331
|
-
await this.session.internal_rewriteMessage(sanitizeMessage(result.message));
|
|
1700
|
+
await this._updateMessageInHistory(result.message);
|
|
1332
1701
|
totals.messages++;
|
|
1333
1702
|
totals.parts += result.parts;
|
|
1334
1703
|
totals.bytes += result.bytes;
|
|
1335
1704
|
}
|
|
1336
|
-
if (totals.messages > 0)
|
|
1705
|
+
if (totals.messages > 0) {
|
|
1706
|
+
this._mediaEvictionFruitless = null;
|
|
1707
|
+
this._emit("chat:media:evicted", {
|
|
1708
|
+
messages: totals.messages,
|
|
1709
|
+
parts: totals.parts,
|
|
1710
|
+
bytes: totals.bytes,
|
|
1711
|
+
externalizedBytes: totals.bytes
|
|
1712
|
+
});
|
|
1713
|
+
} else if (this._agedRowsHiddenFromCache() && this._lastHydration) this._mediaEvictionFruitless = {
|
|
1714
|
+
storedBytes: this._lastHydration.totalContentBytes,
|
|
1715
|
+
appendsSince: this._mediaEvictionAppendsDuringPass
|
|
1716
|
+
};
|
|
1337
1717
|
return totals;
|
|
1338
1718
|
} catch (error) {
|
|
1339
1719
|
console.error("[Think] media eviction pass failed; a later pass will retry.", error);
|
|
1340
1720
|
return null;
|
|
1341
1721
|
} finally {
|
|
1342
1722
|
this._mediaEvictionRunning = false;
|
|
1343
|
-
if (backlogRemains) this._scheduleMediaEvictionPass(
|
|
1723
|
+
if (totals.backlogRemains && totals.messages > 0) this._scheduleMediaEvictionPass();
|
|
1724
|
+
if (this._mediaEvictionPending) {
|
|
1725
|
+
this._mediaEvictionPending = false;
|
|
1726
|
+
this._scheduleMediaEvictionPass();
|
|
1727
|
+
}
|
|
1344
1728
|
}
|
|
1345
1729
|
}
|
|
1346
1730
|
/** Replace the live cache with a durable storage snapshot. */
|
|
@@ -1348,23 +1732,35 @@ var Think = class Think extends Agent {
|
|
|
1348
1732
|
this._cachedMessages = messages;
|
|
1349
1733
|
return this._cachedMessages;
|
|
1350
1734
|
}
|
|
1735
|
+
_noteCachedGrowth(bytes) {
|
|
1736
|
+
const budget = this.hydrationByteBudget;
|
|
1737
|
+
if (bytes <= 0 || !Number.isFinite(budget) || budget <= 0 || !this._lastHydration) return;
|
|
1738
|
+
this._cachedBytesSinceSync += bytes;
|
|
1739
|
+
if (this._lastHydration.totalContentBytes + this._cachedBytesSinceSync > budget) this._cacheCoversActivePath = false;
|
|
1740
|
+
}
|
|
1351
1741
|
/**
|
|
1352
1742
|
* Refresh the live cache from durable storage at a safe boundary.
|
|
1353
1743
|
*
|
|
1354
1744
|
* Bounded by `hydrationByteBudget`: oversized transcripts hydrate as a
|
|
1355
1745
|
* recent window instead of exhausting the isolate's memory (#1710). The
|
|
1356
|
-
*
|
|
1357
|
-
*
|
|
1358
|
-
*
|
|
1746
|
+
* budget is a hard ceiling with no message-count floor beneath it — a floor
|
|
1747
|
+
* that admitted rows regardless of size would defeat the bound it sits
|
|
1748
|
+
* under. A window of unusually large messages can therefore be shorter than
|
|
1749
|
+
* `MODEL_RECENT_WINDOW`; `getHistory()` still reads the full path.
|
|
1359
1750
|
*/
|
|
1360
1751
|
async _syncMessages() {
|
|
1752
|
+
this._cacheCoversActivePath = false;
|
|
1753
|
+
this._cachedBytesSinceSync = 0;
|
|
1361
1754
|
const budget = this.hydrationByteBudget;
|
|
1362
1755
|
if (!Number.isFinite(budget) || budget <= 0) {
|
|
1363
1756
|
this._lastHydration = null;
|
|
1364
1757
|
this._lastWindowedEmit = null;
|
|
1365
|
-
|
|
1758
|
+
const full = this._replaceCachedMessages(await this._readMessagesFromStorage());
|
|
1759
|
+
this._cacheCoversActivePath = true;
|
|
1760
|
+
this._scheduleMediaEvictionPass();
|
|
1761
|
+
return full;
|
|
1366
1762
|
}
|
|
1367
|
-
const recent = await this.session.getRecentHistory(budget
|
|
1763
|
+
const recent = await this.session.getRecentHistory(budget);
|
|
1368
1764
|
this._lastHydration = {
|
|
1369
1765
|
truncated: recent.truncated,
|
|
1370
1766
|
totalContentBytes: recent.totalContentBytes,
|
|
@@ -1387,7 +1783,10 @@ var Think = class Think extends Agent {
|
|
|
1387
1783
|
});
|
|
1388
1784
|
}
|
|
1389
1785
|
} else this._lastWindowedEmit = null;
|
|
1390
|
-
|
|
1786
|
+
const hydrated = this._replaceCachedMessages(recent.messages);
|
|
1787
|
+
this._cacheCoversActivePath = !recent.truncated;
|
|
1788
|
+
this._scheduleMediaEvictionPass();
|
|
1789
|
+
return hydrated;
|
|
1391
1790
|
}
|
|
1392
1791
|
/** Patch or append one message in the live cache after a durable write. */
|
|
1393
1792
|
_upsertCachedMessage(message) {
|
|
@@ -1395,49 +1794,50 @@ var Think = class Think extends Agent {
|
|
|
1395
1794
|
if (index === -1) this._cachedMessages.push(message);
|
|
1396
1795
|
else this._cachedMessages[index] = message;
|
|
1397
1796
|
}
|
|
1398
|
-
/**
|
|
1797
|
+
/**
|
|
1798
|
+
* Patch a message that is already present in the live cache. An update
|
|
1799
|
+
* that enlarges the message (a tool result landing on it) grows the cache
|
|
1800
|
+
* exactly as an append does, so it is charged against the hydration
|
|
1801
|
+
* budget the same way; and it may have put an inline payload on an aged
|
|
1802
|
+
* row, so a fruitless eviction pass no longer stands.
|
|
1803
|
+
*/
|
|
1399
1804
|
_patchCachedMessage(message) {
|
|
1400
1805
|
const index = this._cachedMessages.findIndex((m) => m.id === message.id);
|
|
1401
|
-
if (index
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1806
|
+
if (index === -1) return;
|
|
1807
|
+
const grew = cachedMessageBytes(message) - cachedMessageBytes(this._cachedMessages[index]);
|
|
1808
|
+
this._cachedMessages[index] = message;
|
|
1809
|
+
if (grew > 0) {
|
|
1810
|
+
this._noteCachedGrowth(grew);
|
|
1811
|
+
this._mediaEvictionFruitless = null;
|
|
1812
|
+
}
|
|
1406
1813
|
}
|
|
1407
1814
|
async _appendMessageToHistory(message, parentId) {
|
|
1408
|
-
|
|
1409
|
-
await this.session.appendMessage(safe, parentId);
|
|
1410
|
-
return safe;
|
|
1815
|
+
return (await this.session.appendMessage(message, { parentId })).message;
|
|
1411
1816
|
}
|
|
1412
1817
|
async _updateMessageInHistory(message) {
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
}
|
|
1423
|
-
/**
|
|
1424
|
-
* The orphan-persist store adapter — orphan-persist steps **(c)/(d)** route
|
|
1425
|
-
* their write through this shared `OrphanPersistStore` seam (the
|
|
1426
|
-
* `SessionProvider` write-subset). Delegates to `this.session` with `_rowSafe`
|
|
1427
|
-
* applied at the write boundary (sanitize + row-size cap), exactly as Think's
|
|
1428
|
-
* other Session call sites do. The `SessionMessage → UIMessage` read cast is
|
|
1429
|
-
* confined here, matching those call sites.
|
|
1430
|
-
* @internal
|
|
1431
|
-
*/
|
|
1818
|
+
return await this.session.updateMessage(message) ?? message;
|
|
1819
|
+
}
|
|
1820
|
+
async _upsertMessageInHistory(message, parentId, source = "server") {
|
|
1821
|
+
return (await this.session.upsertMessage(message, {
|
|
1822
|
+
parentId,
|
|
1823
|
+
source
|
|
1824
|
+
})).message;
|
|
1825
|
+
}
|
|
1826
|
+
/** Session-backed orphan persistence with Think's default branch. */
|
|
1432
1827
|
_orphanStore() {
|
|
1433
1828
|
return {
|
|
1434
1829
|
getMessage: async (id) => await this.session.getMessage(id),
|
|
1435
|
-
appendMessage: (message, parentId) =>
|
|
1436
|
-
|
|
1830
|
+
appendMessage: async (message, parentId) => {
|
|
1831
|
+
await this.session.appendMessage(message, { parentId });
|
|
1832
|
+
},
|
|
1833
|
+
updateMessage: async (message) => {
|
|
1834
|
+
await this.session.updateMessage(message);
|
|
1835
|
+
}
|
|
1437
1836
|
};
|
|
1438
1837
|
}
|
|
1439
1838
|
async _clearHistory() {
|
|
1440
1839
|
await this.session.clearMessages();
|
|
1840
|
+
await _classPrivateFieldGet2(_contextBlocks, this)?.refreshSystemPrompt();
|
|
1441
1841
|
await this._clearChatTerminal();
|
|
1442
1842
|
}
|
|
1443
1843
|
/** Append a message while keeping Think's live message cache coherent. */
|
|
@@ -1572,19 +1972,25 @@ var Think = class Think extends Agent {
|
|
|
1572
1972
|
return null;
|
|
1573
1973
|
}
|
|
1574
1974
|
_migrateLegacyConfigToThinkTable() {
|
|
1575
|
-
const
|
|
1576
|
-
|
|
1577
|
-
|
|
1975
|
+
const legacy = this.ctx.storage.sql.exec(`SELECT name FROM sqlite_master
|
|
1976
|
+
WHERE type = 'table'
|
|
1977
|
+
AND name IN ('assistant_config', 'assistant_config__lifted_v1')`).toArray().map((row) => String(row.name));
|
|
1978
|
+
const source = legacy.includes("assistant_config") ? "assistant_config" : legacy.includes("assistant_config__lifted_v1") ? "assistant_config__lifted_v1" : null;
|
|
1979
|
+
if (!source) return;
|
|
1578
1980
|
for (const key of Think.CONFIG_KEYS) {
|
|
1579
|
-
const value = this.sql`
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1981
|
+
const value = (source === "assistant_config" ? this.sql`
|
|
1982
|
+
SELECT value FROM assistant_config
|
|
1983
|
+
WHERE session_id = '' AND key = ${key}
|
|
1984
|
+
` : this.sql`
|
|
1985
|
+
SELECT value FROM assistant_config__lifted_v1
|
|
1986
|
+
WHERE session_id = '' AND key = ${key}
|
|
1987
|
+
`)[0]?.value;
|
|
1583
1988
|
if (value !== void 0) this.sql`
|
|
1584
1989
|
INSERT OR IGNORE INTO think_config (key, value)
|
|
1585
1990
|
VALUES (${key}, ${value})
|
|
1586
1991
|
`;
|
|
1587
1992
|
}
|
|
1993
|
+
this.ctx.storage.sql.exec(`DROP TABLE ${source}`);
|
|
1588
1994
|
}
|
|
1589
1995
|
_ensureConfigTable() {
|
|
1590
1996
|
if (_classPrivateFieldGet2(_configTableReady, this)) return;
|
|
@@ -1600,24 +2006,30 @@ var Think = class Think extends Agent {
|
|
|
1600
2006
|
}
|
|
1601
2007
|
_configSet(key, value) {
|
|
1602
2008
|
this._ensureConfigTable();
|
|
2009
|
+
if (_classPrivateFieldGet2(_configMemo, this).get(key) === value) return;
|
|
1603
2010
|
this.sql`
|
|
1604
2011
|
INSERT OR REPLACE INTO think_config (key, value)
|
|
1605
2012
|
VALUES (${key}, ${value})
|
|
1606
2013
|
`;
|
|
2014
|
+
_classPrivateFieldGet2(_configMemo, this).set(key, value);
|
|
1607
2015
|
}
|
|
1608
2016
|
_configGet(key) {
|
|
1609
2017
|
this._ensureConfigTable();
|
|
1610
|
-
|
|
2018
|
+
const value = this.sql`
|
|
1611
2019
|
SELECT value FROM think_config
|
|
1612
2020
|
WHERE key = ${key}
|
|
1613
2021
|
`[0]?.value;
|
|
2022
|
+
_classPrivateFieldGet2(_configMemo, this).set(key, value);
|
|
2023
|
+
return value;
|
|
1614
2024
|
}
|
|
1615
2025
|
_configDelete(key) {
|
|
1616
2026
|
this._ensureConfigTable();
|
|
2027
|
+
if (_classPrivateFieldGet2(_configMemo, this).has(key) && _classPrivateFieldGet2(_configMemo, this).get(key) === void 0) return;
|
|
1617
2028
|
this.sql`
|
|
1618
2029
|
DELETE FROM think_config
|
|
1619
2030
|
WHERE key = ${key}
|
|
1620
2031
|
`;
|
|
2032
|
+
_classPrivateFieldGet2(_configMemo, this).set(key, void 0);
|
|
1621
2033
|
}
|
|
1622
2034
|
/**
|
|
1623
2035
|
* Return the model to use for inference. Must be overridden by subclasses.
|
|
@@ -1688,9 +2100,8 @@ var Think = class Think extends Agent {
|
|
|
1688
2100
|
}
|
|
1689
2101
|
/**
|
|
1690
2102
|
* Return the fallback system prompt for the assistant.
|
|
1691
|
-
* Ignored when
|
|
1692
|
-
*
|
|
1693
|
-
* coexist with context blocks or skills.
|
|
2103
|
+
* Ignored when context blocks are configured. Use `configureContext()` for
|
|
2104
|
+
* always-on instructions that should coexist with context blocks or skills.
|
|
1694
2105
|
*/
|
|
1695
2106
|
getSystemPrompt() {
|
|
1696
2107
|
return [
|
|
@@ -1944,6 +2355,117 @@ var Think = class Think extends Agent {
|
|
|
1944
2355
|
* Task-local timezone declarations take precedence.
|
|
1945
2356
|
*/
|
|
1946
2357
|
getDefaultTimezone() {}
|
|
2358
|
+
/**
|
|
2359
|
+
* Register the shared chat-turn Task definition (see
|
|
2360
|
+
* `agents/chat` `createChatTurnTaskDefinition` for the turn logic): the
|
|
2361
|
+
* host wires its protected internals through the hooks.
|
|
2362
|
+
*/
|
|
2363
|
+
_registerChatTurnTaskDefinition() {
|
|
2364
|
+
const chatFiberName = this.constructor.CHAT_FIBER_NAME;
|
|
2365
|
+
this.tasks.register(chatFiberName, createChatTurnTaskDefinition({
|
|
2366
|
+
definitionName: chatFiberName,
|
|
2367
|
+
storage: this.ctx.storage,
|
|
2368
|
+
getRunCreatedAt: async (runId) => (await this.tasks.get(runId))?.createdAt ?? null,
|
|
2369
|
+
getLiveClosure: (nonce) => this._liveChatTurnClosures.get(nonce),
|
|
2370
|
+
keepAliveWhile: (fn) => this.keepAliveWhile(fn),
|
|
2371
|
+
withStash: (context, fn) => this._withFiberStash(context, fn),
|
|
2372
|
+
handleRecovery: (ctx) => this._handleInternalFiberRecovery(ctx)
|
|
2373
|
+
}));
|
|
2374
|
+
}
|
|
2375
|
+
/** Register the shared Tasks transport for recovery continuations. */
|
|
2376
|
+
_registerChatRecoveryTaskDefinition() {
|
|
2377
|
+
this.tasks.register(CHAT_RECOVERY_TASK_NAME, createChatRecoveryTaskDefinition({
|
|
2378
|
+
_chatRecoveryContinue: (data) => this._chatRecoveryContinue(data),
|
|
2379
|
+
_chatRecoveryRetry: (data) => this._chatRecoveryRetry(data)
|
|
2380
|
+
}));
|
|
2381
|
+
}
|
|
2382
|
+
/**
|
|
2383
|
+
* Run a queue-driven recovery callback to its model handoff and return;
|
|
2384
|
+
* the turn continues as tracked alarm work, and a detached platform
|
|
2385
|
+
* failure enqueues one replacement attempt through the same transport.
|
|
2386
|
+
*/
|
|
2387
|
+
_dispatchChatRecovery(callback, data, detached) {
|
|
2388
|
+
return dispatchChatRecoveryToHandoff({
|
|
2389
|
+
detached,
|
|
2390
|
+
track: (turn) => this.lifecycle.trackAlarmWork(turn),
|
|
2391
|
+
redefer: (dedupeKey) => this._enqueueChatRecovery(callback, data ?? {}, "redefer", CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS, dedupeKey),
|
|
2392
|
+
onDetachedError: (error) => console.error(`[Think] ${callback} dispatch failed`, error)
|
|
2393
|
+
});
|
|
2394
|
+
}
|
|
2395
|
+
/**
|
|
2396
|
+
* Enqueue one recovery attempt on the shared Tasks transport. Tasks
|
|
2397
|
+
* mirrors a routed dynamic agent's wake to the root's alarm; the run
|
|
2398
|
+
* itself, and this continuation's replay, still execute here. `dedupeKey`
|
|
2399
|
+
* keys a retried enqueue so it joins its own prior attempt instead of
|
|
2400
|
+
* duplicating it — see {@link chatRecoveryTaskRunOptions}.
|
|
2401
|
+
*/
|
|
2402
|
+
async _enqueueChatRecovery(callback, data, reason, delaySeconds, dedupeKey) {
|
|
2403
|
+
const input = {
|
|
2404
|
+
callback,
|
|
2405
|
+
data,
|
|
2406
|
+
delaySeconds
|
|
2407
|
+
};
|
|
2408
|
+
await this.tasks.__DO_NOT_USE_WILL_BREAK__enqueue(CHAT_RECOVERY_TASK_NAME, input, chatRecoveryTaskRunOptions(input, reason, dedupeKey));
|
|
2409
|
+
}
|
|
2410
|
+
/**
|
|
2411
|
+
* The messenger-reply Task definition. A live webhook reply executes as
|
|
2412
|
+
* one journaled step through the runtime's closure registry, persisting
|
|
2413
|
+
* its re-entry snapshot in host storage; a replay whose closure is gone
|
|
2414
|
+
* is recovered on wake by the same
|
|
2415
|
+
* `ThinkMessengerRuntime.handleFiberRecovery` the legacy scan used.
|
|
2416
|
+
*/
|
|
2417
|
+
_registerMessengerReplyTaskDefinition() {
|
|
2418
|
+
this.tasks.register(MESSENGER_REPLY_TASK_DEFINITION, async (input, step) => {
|
|
2419
|
+
const { nonce } = input;
|
|
2420
|
+
await step.do("deliver", {
|
|
2421
|
+
retries: { limit: 1 },
|
|
2422
|
+
timeout: "1 day"
|
|
2423
|
+
}, async ({ signal }) => {
|
|
2424
|
+
const runtime = this._messengerRuntime;
|
|
2425
|
+
if (!runtime) throw new Error("Messenger runtime is unavailable");
|
|
2426
|
+
const runId = `msgr_${nonce}`;
|
|
2427
|
+
const persistKey = `__cf_messenger_recovery:${runId}`;
|
|
2428
|
+
if (!runtime.hasLiveReply(nonce)) {
|
|
2429
|
+
const persisted = await this.ctx.storage.get(persistKey);
|
|
2430
|
+
const createdAt = (await this.tasks.get(runId))?.createdAt ?? Date.now();
|
|
2431
|
+
const ctx = {
|
|
2432
|
+
id: runId,
|
|
2433
|
+
name: MESSENGER_REPLY_FIBER_NAME,
|
|
2434
|
+
snapshot: persisted ?? null,
|
|
2435
|
+
createdAt,
|
|
2436
|
+
recoveryReason: "interrupted"
|
|
2437
|
+
};
|
|
2438
|
+
await runtime.handleFiberRecovery(ctx, { persistRecoverySnapshot: async (snapshot) => {
|
|
2439
|
+
await this.ctx.storage.put(persistKey, snapshot);
|
|
2440
|
+
} });
|
|
2441
|
+
await this.ctx.storage.delete(persistKey);
|
|
2442
|
+
return;
|
|
2443
|
+
}
|
|
2444
|
+
const initial = runtime.initialReplySnapshot(nonce);
|
|
2445
|
+
if (initial !== void 0) await this.ctx.storage.put(persistKey, initial);
|
|
2446
|
+
await runtime.executeLiveReply(nonce, {
|
|
2447
|
+
id: runId,
|
|
2448
|
+
signal,
|
|
2449
|
+
stash: (data) => void this.ctx.storage.put(persistKey, data).catch(() => {}),
|
|
2450
|
+
snapshot: null
|
|
2451
|
+
});
|
|
2452
|
+
await this.ctx.storage.delete(persistKey);
|
|
2453
|
+
});
|
|
2454
|
+
});
|
|
2455
|
+
}
|
|
2456
|
+
/**
|
|
2457
|
+
* Host seam for {@link ThinkMessengerRuntime}: durably accept one reply
|
|
2458
|
+
* run on the Tasks capability and execute it inline while this isolate
|
|
2459
|
+
* lives.
|
|
2460
|
+
* @internal
|
|
2461
|
+
*/
|
|
2462
|
+
async _runMessengerReplyTask(input) {
|
|
2463
|
+
return { accepted: (await this.tasks.__DO_NOT_USE_WILL_BREAK__runAttached(MESSENGER_REPLY_TASK_DEFINITION, { nonce: input.nonce }, {
|
|
2464
|
+
runId: `msgr_${input.nonce}`,
|
|
2465
|
+
idempotencyKey: input.idempotencyKey,
|
|
2466
|
+
metadata: input.metadata
|
|
2467
|
+
})).accepted };
|
|
2468
|
+
}
|
|
1947
2469
|
async _runChatRecoveryFiber(requestId, continuation, fn) {
|
|
1948
2470
|
const snapshot = createChatFiberSnapshot({
|
|
1949
2471
|
kind: "think-chat-turn",
|
|
@@ -1954,10 +2476,43 @@ var Think = class Think extends Agent {
|
|
|
1954
2476
|
lastBody: this._lastBody,
|
|
1955
2477
|
lastClientTools: this._lastClientTools
|
|
1956
2478
|
});
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
2479
|
+
const wrap = (data) => wrapChatFiberSnapshot("__cfThinkChatFiberSnapshot", snapshot, data);
|
|
2480
|
+
if (this.parentPath.length > 0) return this._runFiberWithStashWrapper(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => fn(), {
|
|
2481
|
+
initialSnapshot: wrap(null),
|
|
2482
|
+
wrapStash: wrap
|
|
2483
|
+
});
|
|
2484
|
+
const nonce = crypto.randomUUID();
|
|
2485
|
+
let resolveOutcome;
|
|
2486
|
+
let rejectOutcome;
|
|
2487
|
+
const outcome = new Promise((resolve, reject) => {
|
|
2488
|
+
resolveOutcome = resolve;
|
|
2489
|
+
rejectOutcome = reject;
|
|
2490
|
+
});
|
|
2491
|
+
outcome.catch(() => {});
|
|
2492
|
+
const ambient = __DO_NOT_USE_WILL_BREAK__agentContext.getStore();
|
|
2493
|
+
this._liveChatTurnClosures.set(nonce, {
|
|
2494
|
+
initial: wrap(null),
|
|
2495
|
+
wrap,
|
|
2496
|
+
run: ambient ? () => __DO_NOT_USE_WILL_BREAK__agentContext.run(ambient, fn) : fn,
|
|
2497
|
+
settle: {
|
|
2498
|
+
resolve: resolveOutcome,
|
|
2499
|
+
reject: rejectOutcome
|
|
2500
|
+
}
|
|
1960
2501
|
});
|
|
2502
|
+
try {
|
|
2503
|
+
await this.tasks.__DO_NOT_USE_WILL_BREAK__runAttached(this.constructor.CHAT_FIBER_NAME, {
|
|
2504
|
+
requestId,
|
|
2505
|
+
continuation,
|
|
2506
|
+
nonce
|
|
2507
|
+
}, {
|
|
2508
|
+
runId: `chat_${nonce}`,
|
|
2509
|
+
retain: false,
|
|
2510
|
+
metadata: { requestId }
|
|
2511
|
+
});
|
|
2512
|
+
return await outcome;
|
|
2513
|
+
} finally {
|
|
2514
|
+
this._liveChatTurnClosures.delete(nonce);
|
|
2515
|
+
}
|
|
1961
2516
|
}
|
|
1962
2517
|
_systemPromptForTurn(baseSystem, tools) {
|
|
1963
2518
|
if (baseSystem.includes("You are running inside a Think agent.")) return baseSystem;
|
|
@@ -1975,7 +2530,6 @@ var Think = class Think extends Agent {
|
|
|
1975
2530
|
"grep",
|
|
1976
2531
|
"delete"
|
|
1977
2532
|
].some((toolName) => toolNames.has(toolName));
|
|
1978
|
-
const hasContextTools = toolNames.has("load_context") || toolNames.has("unload_context");
|
|
1979
2533
|
const hasExtensionTools = toolNames.has("load_extension") || toolNames.has("list_extensions");
|
|
1980
2534
|
const hasExecuteTool = toolNames.has("execute");
|
|
1981
2535
|
const hasFetchTools = [...toolNames].some((name) => name.startsWith("fetch_"));
|
|
@@ -1989,7 +2543,6 @@ var Think = class Think extends Agent {
|
|
|
1989
2543
|
lines.push("- Use the tools exposed in this turn when they materially improve accuracy or let you act on the user's request. Treat tool descriptions and schemas as the source of truth.");
|
|
1990
2544
|
lines.push("- Some tools may call server code, browser/client code, MCP servers, extensions, or delegated agents. Use them according to their descriptions.");
|
|
1991
2545
|
}
|
|
1992
|
-
if (hasContextTools) lines.push("- If context-loading tools are available, use them to load relevant memory, skills, or project context before acting on incomplete information.");
|
|
1993
2546
|
if (hasExtensionTools) lines.push("- If extension tools are available, use them only when loading or inspecting extensions directly helps with the task.");
|
|
1994
2547
|
if (hasExecuteTool) lines.push("- If sandboxed execution is available, prefer it for safe, bounded checks or coordinated multi-step operations.");
|
|
1995
2548
|
if (hasFetchTools) lines.push("- If fetch tools are available, use them to read allowlisted HTTP resources (documentation, APIs). They are read-only and bounded; respect their allowlist and do not assume access to other URLs.");
|
|
@@ -2013,15 +2566,20 @@ var Think = class Think extends Agent {
|
|
|
2013
2566
|
return Math.max(1, this.contextOverflow?.proactive?.maxCompactions ?? 1);
|
|
2014
2567
|
}
|
|
2015
2568
|
/**
|
|
2016
|
-
* Configure
|
|
2017
|
-
*
|
|
2569
|
+
* Configure conversation storage. Called once during `onStart`. Override to
|
|
2570
|
+
* set the compaction policy; prompt context is declared by
|
|
2571
|
+
* {@link Think.configureContext} instead.
|
|
2572
|
+
*
|
|
2573
|
+
* The handle still accepts the pre-Sessions `withContext()` and
|
|
2574
|
+
* `withCachedPrompt()` chain, so an existing override keeps working; those
|
|
2575
|
+
* blocks are appended after the ones `configureContext()` returns.
|
|
2018
2576
|
*
|
|
2019
2577
|
* @example
|
|
2020
2578
|
* ```typescript
|
|
2021
2579
|
* configureSession(session: Session) {
|
|
2022
2580
|
* return session
|
|
2023
|
-
* .
|
|
2024
|
-
* .
|
|
2581
|
+
* .onCompaction(createCompactFunction({ summarize }))
|
|
2582
|
+
* .compactAfter(80_000);
|
|
2025
2583
|
* }
|
|
2026
2584
|
* ```
|
|
2027
2585
|
*/
|
|
@@ -2029,6 +2587,26 @@ var Think = class Think extends Agent {
|
|
|
2029
2587
|
return session;
|
|
2030
2588
|
}
|
|
2031
2589
|
/**
|
|
2590
|
+
* Declare the prompt context blocks for this agent.
|
|
2591
|
+
*
|
|
2592
|
+
* Blocks render into the system prompt and, when their provider is
|
|
2593
|
+
* writable, give the model `set_context` to update them. A block declared
|
|
2594
|
+
* without a provider is auto-wired to durable per-agent SQLite storage.
|
|
2595
|
+
*
|
|
2596
|
+
* @example
|
|
2597
|
+
* ```typescript
|
|
2598
|
+
* configureContext(): ContextConfig[] {
|
|
2599
|
+
* return [
|
|
2600
|
+
* { label: "soul", provider: { get: async () => "You are helpful." } },
|
|
2601
|
+
* { label: "memory", description: "Learned facts", maxTokens: 2000 }
|
|
2602
|
+
* ];
|
|
2603
|
+
* }
|
|
2604
|
+
* ```
|
|
2605
|
+
*/
|
|
2606
|
+
configureContext() {
|
|
2607
|
+
return [];
|
|
2608
|
+
}
|
|
2609
|
+
/**
|
|
2032
2610
|
* Return Agent Skills sources for this Think agent.
|
|
2033
2611
|
*
|
|
2034
2612
|
* Bundled skills are typically imported with the Agents Vite plugin:
|
|
@@ -2048,7 +2626,7 @@ var Think = class Think extends Agent {
|
|
|
2048
2626
|
const sources = await this.getSkills();
|
|
2049
2627
|
if (sources.length === 0) return;
|
|
2050
2628
|
if (this.getSystemPrompt !== Think.prototype.getSystemPrompt) {
|
|
2051
|
-
const warning = "getSystemPrompt() is only used as a fallback when no
|
|
2629
|
+
const warning = "getSystemPrompt() is only used as a fallback when no context blocks are configured. getSkills() registers a skills context block, so move always-on instructions into configureContext() instead.";
|
|
2052
2630
|
if (!this._loggedSkillWarnings.has(warning)) {
|
|
2053
2631
|
this._loggedSkillWarnings.add(warning);
|
|
2054
2632
|
console.warn(`[think] ${warning}`);
|
|
@@ -2058,18 +2636,49 @@ var Think = class Think extends Agent {
|
|
|
2058
2636
|
await registry.load();
|
|
2059
2637
|
this._logSkillWarnings(registry);
|
|
2060
2638
|
this._skillRegistry = registry;
|
|
2061
|
-
await this.
|
|
2639
|
+
await this._configureSkillWorkspace(registry);
|
|
2640
|
+
await this.context.addBlock({
|
|
2641
|
+
label: registry.contextLabel,
|
|
2062
2642
|
description: "Think skills: available skill catalog",
|
|
2063
2643
|
provider: { get: () => registry.systemPrompt() }
|
|
2064
2644
|
});
|
|
2065
|
-
if (this._configGet("skillsFingerprint") !== registry.fingerprint) {
|
|
2066
|
-
await this.
|
|
2645
|
+
if ((this._skillsFingerprint ??= this._configGet("skillsFingerprint") ?? null) !== registry.fingerprint) {
|
|
2646
|
+
await this.context.refreshSystemPrompt();
|
|
2067
2647
|
this._configSet("skillsFingerprint", registry.fingerprint);
|
|
2648
|
+
this._skillsFingerprint = registry.fingerprint;
|
|
2068
2649
|
}
|
|
2069
2650
|
} catch (error) {
|
|
2070
2651
|
console.warn(`[think] Failed to initialize skills; continuing without them: ${error instanceof Error ? error.message : String(error)}`);
|
|
2071
2652
|
}
|
|
2072
2653
|
}
|
|
2654
|
+
async _configureSkillWorkspace(registry) {
|
|
2655
|
+
if (this.skillWorkspace === false) return;
|
|
2656
|
+
const workspace = this.workspace;
|
|
2657
|
+
if (!hasWriteFileBytes(workspace)) {
|
|
2658
|
+
const warning = "skillWorkspace is enabled but the configured workspace does not implement writeFileBytes; skills stay source-backed.";
|
|
2659
|
+
if (!this._loggedSkillWarnings.has(warning)) {
|
|
2660
|
+
this._loggedSkillWarnings.add(warning);
|
|
2661
|
+
console.warn(`[think] ${warning}`);
|
|
2662
|
+
}
|
|
2663
|
+
return;
|
|
2664
|
+
}
|
|
2665
|
+
try {
|
|
2666
|
+
const key = "skillsWorkspaceFingerprint";
|
|
2667
|
+
if (this._configGet(key) === registry.fingerprint) {
|
|
2668
|
+
await registry.useWorkspace(workspace, this.skillWorkspace);
|
|
2669
|
+
return;
|
|
2670
|
+
}
|
|
2671
|
+
const seeded = await registry.seedWorkspace(workspace, this.skillWorkspace);
|
|
2672
|
+
for (const warning of seeded.warnings) {
|
|
2673
|
+
if (this._loggedSkillWarnings.has(warning)) continue;
|
|
2674
|
+
this._loggedSkillWarnings.add(warning);
|
|
2675
|
+
console.warn(`[think] ${warning}`);
|
|
2676
|
+
}
|
|
2677
|
+
if (seeded.skipped === 0) this._configSet(key, registry.fingerprint);
|
|
2678
|
+
} catch (error) {
|
|
2679
|
+
console.warn(`[think] Failed to seed skills into the workspace; source-backed skill tools remain available: ${error instanceof Error ? error.message : String(error)}`);
|
|
2680
|
+
}
|
|
2681
|
+
}
|
|
2073
2682
|
/**
|
|
2074
2683
|
* Log registry diagnostics (duplicate names, sources that failed to list),
|
|
2075
2684
|
* deduped by message so a new collision after a deploy still surfaces while
|
|
@@ -2096,9 +2705,11 @@ var Think = class Think extends Agent {
|
|
|
2096
2705
|
try {
|
|
2097
2706
|
await this._skillRegistry.refresh();
|
|
2098
2707
|
this._logSkillWarnings(this._skillRegistry);
|
|
2099
|
-
|
|
2100
|
-
|
|
2708
|
+
await this._configureSkillWorkspace(this._skillRegistry);
|
|
2709
|
+
if ((this._skillsFingerprint ??= this._configGet("skillsFingerprint") ?? null) !== this._skillRegistry.fingerprint) {
|
|
2710
|
+
await this.context.refreshSystemPrompt();
|
|
2101
2711
|
this._configSet("skillsFingerprint", this._skillRegistry.fingerprint);
|
|
2712
|
+
this._skillsFingerprint = this._skillRegistry.fingerprint;
|
|
2102
2713
|
}
|
|
2103
2714
|
} catch (error) {
|
|
2104
2715
|
console.warn(`[think] Failed to refresh skills; using last known catalog: ${error instanceof Error ? error.message : String(error)}`);
|
|
@@ -2457,15 +3068,16 @@ var Think = class Think extends Agent {
|
|
|
2457
3068
|
const prefix = sanitizeName(ext.name);
|
|
2458
3069
|
for (const ctxDef of manifest.context) {
|
|
2459
3070
|
const namespacedLabel = `${prefix}_${ctxDef.label}`;
|
|
2460
|
-
await this.
|
|
3071
|
+
await this.context.addBlock({
|
|
3072
|
+
label: namespacedLabel,
|
|
2461
3073
|
description: ctxDef.description,
|
|
2462
3074
|
maxTokens: ctxDef.maxTokens
|
|
2463
3075
|
});
|
|
2464
3076
|
}
|
|
2465
3077
|
}
|
|
2466
3078
|
this.extensionManager.onUnload(async (_name, contextLabels) => {
|
|
2467
|
-
for (const label of contextLabels) this.
|
|
2468
|
-
await this.
|
|
3079
|
+
for (const label of contextLabels) this.context.removeBlock(label);
|
|
3080
|
+
await this.context.refreshSystemPrompt();
|
|
2469
3081
|
});
|
|
2470
3082
|
}
|
|
2471
3083
|
/**
|
|
@@ -2653,7 +3265,7 @@ var Think = class Think extends Agent {
|
|
|
2653
3265
|
const actionTools = await this._compileActionTools();
|
|
2654
3266
|
const extensionTools = this.extensionManager?.getTools() ?? {};
|
|
2655
3267
|
await this._refreshSkillsIfChanged();
|
|
2656
|
-
const contextTools = await this.
|
|
3268
|
+
const contextTools = await this.context.tools();
|
|
2657
3269
|
const skillTools = this._skillRegistry?.tools() ?? {};
|
|
2658
3270
|
const clientToolSet = createToolsFromClientSchemas(input.clientTools, input.clientToolExecutor ? { execute: input.clientToolExecutor } : void 0);
|
|
2659
3271
|
let tools = {
|
|
@@ -2671,7 +3283,7 @@ var Think = class Think extends Agent {
|
|
|
2671
3283
|
const channelDefinition = channelContext ? this._channels?.get(channelContext.channelId) : void 0;
|
|
2672
3284
|
if (channelDefinition?.tools) tools = channelDefinition.tools(tools);
|
|
2673
3285
|
const channelInstructions = channelDefinition?.instructions && channelContext ? typeof channelDefinition.instructions === "function" ? await channelDefinition.instructions(channelContext) : channelDefinition.instructions : void 0;
|
|
2674
|
-
const rawBaseSystem = await this.
|
|
3286
|
+
const rawBaseSystem = await this.context.freezeSystemPrompt() || this.getSystemPrompt();
|
|
2675
3287
|
const baseSystem = channelInstructions ? `${channelInstructions}\n\n${rawBaseSystem}` : rawBaseSystem;
|
|
2676
3288
|
const system = this._systemPromptForTurn(baseSystem, tools);
|
|
2677
3289
|
const messages = await this._assembleModelMessages(tools);
|
|
@@ -2764,7 +3376,10 @@ var Think = class Think extends Agent {
|
|
|
2764
3376
|
abortSignal: input.signal,
|
|
2765
3377
|
prepareStep: (async (event) => {
|
|
2766
3378
|
const guarded = await this._maybeProactiveContextCompact(event);
|
|
2767
|
-
const result = await this.beforeStep(
|
|
3379
|
+
const result = await this.beforeStep(guarded ? {
|
|
3380
|
+
...event,
|
|
3381
|
+
messages: guarded
|
|
3382
|
+
} : event);
|
|
2768
3383
|
const base = result == null ? {} : result;
|
|
2769
3384
|
const baseMessages = base.messages;
|
|
2770
3385
|
const withMessages = guarded && baseMessages === void 0 ? {
|
|
@@ -3514,10 +4129,10 @@ var Think = class Think extends Agent {
|
|
|
3514
4129
|
}));
|
|
3515
4130
|
}
|
|
3516
4131
|
async _hostGetContext(label) {
|
|
3517
|
-
return this.
|
|
4132
|
+
return this.context.getBlock(label)?.content ?? null;
|
|
3518
4133
|
}
|
|
3519
4134
|
async _hostSetContext(label, content) {
|
|
3520
|
-
await this.
|
|
4135
|
+
await this.context.setBlock(label, content);
|
|
3521
4136
|
}
|
|
3522
4137
|
async _hostGetMessages(limit) {
|
|
3523
4138
|
const history = this.messages;
|
|
@@ -3839,6 +4454,7 @@ var Think = class Think extends Agent {
|
|
|
3839
4454
|
this._broadcast({ type: MSG_CHAT_CLEAR });
|
|
3840
4455
|
}
|
|
3841
4456
|
_ensureAgentToolChildRunTable() {
|
|
4457
|
+
if (_classPrivateFieldGet2(_agentToolChildRunTableReady, this)) return;
|
|
3842
4458
|
this.sql`
|
|
3843
4459
|
CREATE TABLE IF NOT EXISTS cf_agent_tool_child_runs (
|
|
3844
4460
|
run_id TEXT PRIMARY KEY,
|
|
@@ -3865,6 +4481,7 @@ var Think = class Think extends Agent {
|
|
|
3865
4481
|
PRIMARY KEY (run_id, sequence)
|
|
3866
4482
|
)
|
|
3867
4483
|
`;
|
|
4484
|
+
_classPrivateFieldSet2(_agentToolChildRunTableReady, this, true);
|
|
3868
4485
|
}
|
|
3869
4486
|
_persistAgentToolMilestone(runId, name, data, at) {
|
|
3870
4487
|
this._ensureAgentToolChildRunTable();
|
|
@@ -5165,7 +5782,7 @@ var Think = class Think extends Agent {
|
|
|
5165
5782
|
return parsed;
|
|
5166
5783
|
}
|
|
5167
5784
|
_serializeSubmissionMessages(messages) {
|
|
5168
|
-
return JSON.stringify(messages.map((message) =>
|
|
5785
|
+
return JSON.stringify(messages.map((message) => enforceRowSizeLimit(sanitizeMessage(message), { warn: (warning) => console.warn(`[Think] ${warning}`) })));
|
|
5169
5786
|
}
|
|
5170
5787
|
_serializeMetadata(metadata) {
|
|
5171
5788
|
return metadata === void 0 ? null : JSON.stringify(metadata);
|
|
@@ -5360,11 +5977,33 @@ var Think = class Think extends Agent {
|
|
|
5360
5977
|
const delayMs = Math.min(300 * 1e3, 1e3 * 2 ** Math.min(pending[0].attempts, 8));
|
|
5361
5978
|
return Math.max(pending[0].updated_at + delayMs, Date.now() + 1);
|
|
5362
5979
|
}
|
|
5363
|
-
|
|
5364
|
-
|
|
5980
|
+
/**
|
|
5981
|
+
* Drive the Think-owned workflow-notification host job. Unknown fns
|
|
5982
|
+
* delegate to Agent's dispatch.
|
|
5983
|
+
*/
|
|
5984
|
+
_onHostJob(fn, context) {
|
|
5985
|
+
if (fn === "thinkWorkflowNotifications") {
|
|
5986
|
+
this._startWorkflowNotificationDrain();
|
|
5987
|
+
const next = this._nextWorkflowNotificationAlarm();
|
|
5988
|
+
return next === null ? void 0 : { rescheduleAt: next };
|
|
5989
|
+
}
|
|
5990
|
+
return super._onHostJob(fn, context);
|
|
5365
5991
|
}
|
|
5366
|
-
|
|
5367
|
-
|
|
5992
|
+
/**
|
|
5993
|
+
* Sync the workflow-notification wake job with pending-notification state.
|
|
5994
|
+
* Replaces the pull-based `_getExtensionAlarm()` contribution.
|
|
5995
|
+
*/
|
|
5996
|
+
async _rearmWorkflowNotificationAlarm() {
|
|
5997
|
+
const next = this._nextWorkflowNotificationAlarm();
|
|
5998
|
+
if (next === null) {
|
|
5999
|
+
if (this.lifecycle.jobs.get(THINK_WORKFLOW_NOTIFICATIONS_JOB_ID)) await this.lifecycle.jobs.cancel(THINK_WORKFLOW_NOTIFICATIONS_JOB_ID);
|
|
6000
|
+
return;
|
|
6001
|
+
}
|
|
6002
|
+
await this.lifecycle.jobs.push({
|
|
6003
|
+
id: THINK_WORKFLOW_NOTIFICATIONS_JOB_ID,
|
|
6004
|
+
fn: "thinkWorkflowNotifications",
|
|
6005
|
+
time: next
|
|
6006
|
+
});
|
|
5368
6007
|
}
|
|
5369
6008
|
async inspectSubmission(submissionId) {
|
|
5370
6009
|
const row = this._readSubmission(submissionId);
|
|
@@ -5703,7 +6342,7 @@ var Think = class Think extends Agent {
|
|
|
5703
6342
|
if (updated?.status === "pending") await this._emitSubmissionStatus(updated);
|
|
5704
6343
|
continue;
|
|
5705
6344
|
}
|
|
5706
|
-
if (row.request_id && (this._hasRecoverableChatTurn(row.request_id) && this._hasFreshRecoverableSubmissionEvidence(row) || this._hasScheduledRecoveredContinuation(row.request_id))) continue;
|
|
6345
|
+
if (row.request_id && (this._hasRecoverableChatTurn(row.request_id) && this._hasFreshRecoverableSubmissionEvidence(row) || await this._hasScheduledRecoveredContinuation(row.request_id))) continue;
|
|
5707
6346
|
this.sql`
|
|
5708
6347
|
UPDATE cf_think_submissions
|
|
5709
6348
|
SET status = 'error',
|
|
@@ -5724,18 +6363,28 @@ var Think = class Think extends Agent {
|
|
|
5724
6363
|
if (applied === 0) return "none";
|
|
5725
6364
|
return applied === messages.length ? "all" : "partial";
|
|
5726
6365
|
}
|
|
6366
|
+
/**
|
|
6367
|
+
* Wall-clock creation time of a non-terminal chat-turn run on the Tasks
|
|
6368
|
+
* capability, or null. The metadata column holds the exact JSON the chat
|
|
6369
|
+
* wrapper wrote, so string equality matches the requestId.
|
|
6370
|
+
*/
|
|
6371
|
+
_recoverableChatTurnTaskCreatedAt(requestId) {
|
|
6372
|
+
return this.sql`
|
|
6373
|
+
SELECT created_at FROM cf_agents_task_runs
|
|
6374
|
+
WHERE definition = ${this.constructor.CHAT_FIBER_NAME}
|
|
6375
|
+
AND state IN ('pending', 'running', 'waiting', 'recovering')
|
|
6376
|
+
AND metadata = ${JSON.stringify({ requestId })}
|
|
6377
|
+
LIMIT 1
|
|
6378
|
+
`[0]?.created_at ?? null;
|
|
6379
|
+
}
|
|
5727
6380
|
_hasRecoverableChatTurn(requestId) {
|
|
5728
6381
|
if (this.sql`
|
|
5729
6382
|
SELECT id FROM cf_agents_runs
|
|
5730
6383
|
WHERE name = ${this.constructor.CHAT_FIBER_NAME + ":" + requestId}
|
|
5731
6384
|
LIMIT 1
|
|
5732
6385
|
`.length > 0) return true;
|
|
5733
|
-
|
|
5734
|
-
|
|
5735
|
-
WHERE request_id = ${requestId}
|
|
5736
|
-
AND status = 'streaming'
|
|
5737
|
-
LIMIT 1
|
|
5738
|
-
`.length > 0;
|
|
6386
|
+
if (this._recoverableChatTurnTaskCreatedAt(requestId) !== null) return true;
|
|
6387
|
+
return this._resumableStream.latestActiveStreamInfoForRequest(requestId) !== null;
|
|
5739
6388
|
}
|
|
5740
6389
|
_hasFreshRecoverableSubmissionEvidence(row) {
|
|
5741
6390
|
if (!row.request_id) return false;
|
|
@@ -5746,27 +6395,25 @@ var Think = class Think extends Agent {
|
|
|
5746
6395
|
LIMIT 1
|
|
5747
6396
|
`;
|
|
5748
6397
|
if (fiberRows[0] && fiberRows[0].created_at >= cutoff) return true;
|
|
5749
|
-
const
|
|
5750
|
-
|
|
5751
|
-
|
|
5752
|
-
|
|
5753
|
-
|
|
5754
|
-
|
|
5755
|
-
|
|
5756
|
-
|
|
5757
|
-
|
|
5758
|
-
|
|
5759
|
-
|
|
5760
|
-
|
|
5761
|
-
|
|
5762
|
-
|
|
5763
|
-
|
|
5764
|
-
|
|
5765
|
-
|
|
5766
|
-
|
|
5767
|
-
|
|
5768
|
-
return false;
|
|
5769
|
-
}
|
|
6398
|
+
const capabilityCreatedAt = this._recoverableChatTurnTaskCreatedAt(row.request_id);
|
|
6399
|
+
if (capabilityCreatedAt !== null && capabilityCreatedAt >= cutoff) return true;
|
|
6400
|
+
const streamInfo = this._resumableStream.latestActiveStreamInfoForRequest(row.request_id);
|
|
6401
|
+
return streamInfo ? streamInfo.createdAt >= cutoff : false;
|
|
6402
|
+
}
|
|
6403
|
+
async _hasScheduledRecoveredContinuation(requestId) {
|
|
6404
|
+
if ((await this.tasks.list({
|
|
6405
|
+
definition: CHAT_RECOVERY_TASK_NAME,
|
|
6406
|
+
status: [
|
|
6407
|
+
"pending",
|
|
6408
|
+
"running",
|
|
6409
|
+
"waiting"
|
|
6410
|
+
],
|
|
6411
|
+
limit: Number.MAX_SAFE_INTEGER
|
|
6412
|
+
})).some((run) => run.metadata?.callback === "_chatRecoveryContinue" && run.metadata.recoveredRequestId === requestId)) return true;
|
|
6413
|
+
return (await this.listSchedules()).some((schedule) => {
|
|
6414
|
+
if (schedule.callback !== "_chatRecoveryContinue") return false;
|
|
6415
|
+
const payload = schedule.payload;
|
|
6416
|
+
return payload !== null && typeof payload === "object" && "recoveredRequestId" in payload && payload.recoveredRequestId === requestId;
|
|
5770
6417
|
});
|
|
5771
6418
|
}
|
|
5772
6419
|
/**
|
|
@@ -6267,31 +6914,16 @@ var Think = class Think extends Agent {
|
|
|
6267
6914
|
});
|
|
6268
6915
|
const clientToolsForTurn = this._lastClientTools;
|
|
6269
6916
|
const bodyForTurn = this._lastBody;
|
|
6270
|
-
const
|
|
6271
|
-
|
|
6272
|
-
|
|
6273
|
-
|
|
6274
|
-
}
|
|
6275
|
-
|
|
6276
|
-
let branchParentId;
|
|
6277
|
-
if (isRegeneration && reconciled.length > 0) branchParentId = reconciled[reconciled.length - 1].id;
|
|
6278
|
-
if (!await withAgentSpan(this, "persist_incoming_messages", "interaction", {
|
|
6279
|
-
"cloudflare.agents.component": "think",
|
|
6280
|
-
"cloudflare.agents.turn.request_id": requestId,
|
|
6281
|
-
"cloudflare.agents.turn.trigger": "ws-chat"
|
|
6282
|
-
}, async () => {
|
|
6283
|
-
if (this._turnQueue.generation !== epoch) return false;
|
|
6284
|
-
for (const msg of reconciled) {
|
|
6285
|
-
if (this._turnQueue.generation !== epoch) return false;
|
|
6286
|
-
await this._persistIncomingMessage(msg, serverMessages);
|
|
6287
|
-
}
|
|
6288
|
-
if (this._turnQueue.generation !== epoch) return false;
|
|
6289
|
-
await this._syncMessages();
|
|
6290
|
-
return true;
|
|
6291
|
-
})) {
|
|
6917
|
+
const reconciledTurn = await this._reconcileAndPersistIncoming(incomingMessages, {
|
|
6918
|
+
requestId,
|
|
6919
|
+
isRegeneration,
|
|
6920
|
+
isCurrent: () => this._turnQueue.generation === epoch
|
|
6921
|
+
});
|
|
6922
|
+
if (!reconciledTurn) {
|
|
6292
6923
|
this._completeSkippedRequest(connection, requestId);
|
|
6293
6924
|
return;
|
|
6294
6925
|
}
|
|
6926
|
+
const { branchParentId } = reconciledTurn;
|
|
6295
6927
|
this._broadcastMessages([connection.id]);
|
|
6296
6928
|
messagesPersisted = true;
|
|
6297
6929
|
failureStage = "turn";
|
|
@@ -6719,7 +7351,7 @@ var Think = class Think extends Agent {
|
|
|
6719
7351
|
};
|
|
6720
7352
|
}
|
|
6721
7353
|
if (streamError) this._errorResumableStream(streamId);
|
|
6722
|
-
else this.
|
|
7354
|
+
else this._finishResumableStream(streamId);
|
|
6723
7355
|
streamFinalized = true;
|
|
6724
7356
|
this._broadcastChat({
|
|
6725
7357
|
type: MSG_CHAT_RESPONSE,
|
|
@@ -6730,9 +7362,10 @@ var Think = class Think extends Agent {
|
|
|
6730
7362
|
doneSent = true;
|
|
6731
7363
|
assistantMsg = accumulator.toMessage();
|
|
6732
7364
|
if (accumulator.parts.length > 0) {
|
|
6733
|
-
await this.
|
|
7365
|
+
await this._persistAssistantMessageWithCutover(streamId, assistantMsg, void 0, { discard: this._discardStreamAtCutover(requestId) });
|
|
6734
7366
|
this._broadcastMessages();
|
|
6735
7367
|
}
|
|
7368
|
+
this._resumableStream.finalizePending();
|
|
6736
7369
|
if (streamError) {
|
|
6737
7370
|
await this._fireResponseHook({
|
|
6738
7371
|
message: assistantMsg,
|
|
@@ -6876,12 +7509,6 @@ var Think = class Think extends Agent {
|
|
|
6876
7509
|
state.chunksSinceFlush = 0;
|
|
6877
7510
|
state.hasFlushedContent = true;
|
|
6878
7511
|
}
|
|
6879
|
-
if (shouldCreditStreamProgress({
|
|
6880
|
-
codec: aiSdkRecoveryCodec,
|
|
6881
|
-
type: chunk.type,
|
|
6882
|
-
throttle: this._streamProgressCredit,
|
|
6883
|
-
now: Date.now()
|
|
6884
|
-
})) await this._bumpChatRecoveryProgress();
|
|
6885
7512
|
}
|
|
6886
7513
|
async _streamResult(requestId, result, abortSignal, options) {
|
|
6887
7514
|
const clearGen = this._turnQueue.generation;
|
|
@@ -6974,7 +7601,7 @@ var Think = class Think extends Agent {
|
|
|
6974
7601
|
return { status: "aborted" };
|
|
6975
7602
|
}
|
|
6976
7603
|
if (streamError) this._errorResumableStream(streamId);
|
|
6977
|
-
else this.
|
|
7604
|
+
else this._finishResumableStream(streamId);
|
|
6978
7605
|
this._pendingResumeConnections.clear();
|
|
6979
7606
|
this._broadcastChat({
|
|
6980
7607
|
type: MSG_CHAT_RESPONSE,
|
|
@@ -7060,9 +7687,10 @@ var Think = class Think extends Agent {
|
|
|
7060
7687
|
if (this._turnQueue.generation === clearGen) try {
|
|
7061
7688
|
const assistantMsg = accumulator.toMessage();
|
|
7062
7689
|
if (accumulator.parts.length > 0) {
|
|
7063
|
-
await this.
|
|
7690
|
+
await this._persistAssistantMessageWithCutover(streamId, assistantMsg, parentId, { discard: this._discardStreamAtCutover(requestId) });
|
|
7064
7691
|
this._broadcastMessages();
|
|
7065
7692
|
}
|
|
7693
|
+
this._resumableStream.finalizePending();
|
|
7066
7694
|
await this._fireResponseHook({
|
|
7067
7695
|
message: assistantMsg,
|
|
7068
7696
|
requestId,
|
|
@@ -7073,6 +7701,7 @@ var Think = class Think extends Agent {
|
|
|
7073
7701
|
} catch (e) {
|
|
7074
7702
|
console.error("Failed to persist assistant message:", e);
|
|
7075
7703
|
}
|
|
7704
|
+
this._resumableStream.finalizePending();
|
|
7076
7705
|
this._onStreamingTurnFinalized();
|
|
7077
7706
|
return streamError ? {
|
|
7078
7707
|
status: "error",
|
|
@@ -7103,6 +7732,44 @@ var Think = class Think extends Agent {
|
|
|
7103
7732
|
await this._upsertMessageInHistory(toPersist, parentId);
|
|
7104
7733
|
}
|
|
7105
7734
|
/**
|
|
7735
|
+
* The cutover: persist the finished turn's assistant message, settle its
|
|
7736
|
+
* resumable stream and delete the stream's rows in ONE SQLite transaction,
|
|
7737
|
+
* so a crash leaves either the live stream (recovery rebuilds the message
|
|
7738
|
+
* from it) or the message — never neither, never both. The session
|
|
7739
|
+
* change feed and auto-compaction run once the transaction has committed.
|
|
7740
|
+
*/
|
|
7741
|
+
async _persistAssistantMessageWithCutover(streamId, msg, parentId, options = {}) {
|
|
7742
|
+
const toPersist = this._strippedForPersist(msg);
|
|
7743
|
+
if (toPersist === null) return;
|
|
7744
|
+
if (this._resumableStream.pendingCutoverId !== streamId) {
|
|
7745
|
+
await this._upsertMessageInHistory(toPersist, parentId);
|
|
7746
|
+
return;
|
|
7747
|
+
}
|
|
7748
|
+
const sync = this.sessions.session().__DO_NOT_USE_WILL_BREAK__sync();
|
|
7749
|
+
let after;
|
|
7750
|
+
try {
|
|
7751
|
+
this._resumableStream.cutover(streamId, () => {
|
|
7752
|
+
after = sync.upsert(toPersist, {
|
|
7753
|
+
parentId,
|
|
7754
|
+
source: "server"
|
|
7755
|
+
}).after;
|
|
7756
|
+
}, { discard: options.discard ?? true });
|
|
7757
|
+
} catch (error) {
|
|
7758
|
+
sync.abandon();
|
|
7759
|
+
throw error;
|
|
7760
|
+
}
|
|
7761
|
+
await after?.();
|
|
7762
|
+
}
|
|
7763
|
+
/**
|
|
7764
|
+
* Whether this turn's stream rows can go with its cutover. An agent-tool
|
|
7765
|
+
* child turn keeps them: the parent tails the stored chunks after the
|
|
7766
|
+
* child completes (`getAgentToolChunks`), so the rows are reclaimed by
|
|
7767
|
+
* the child's next `start()` instead, as `AIChatAgent` does.
|
|
7768
|
+
*/
|
|
7769
|
+
_discardStreamAtCutover(requestId) {
|
|
7770
|
+
return !this._agentToolRunsByRequestId.get(requestId);
|
|
7771
|
+
}
|
|
7772
|
+
/**
|
|
7106
7773
|
* Remove parts belonging to Think's internal structured-output final-answer
|
|
7107
7774
|
* tool (`think_final_answer`, or a collision-suffixed variant) from a UI
|
|
7108
7775
|
* message so the internal call/result never enters the persisted conversation
|
|
@@ -7124,38 +7791,83 @@ var Think = class Think extends Agent {
|
|
|
7124
7791
|
};
|
|
7125
7792
|
}
|
|
7126
7793
|
/**
|
|
7127
|
-
*
|
|
7128
|
-
* messages
|
|
7129
|
-
*
|
|
7130
|
-
*
|
|
7794
|
+
* Turn-start persistence of the client's transcript: reconcile the posted
|
|
7795
|
+
* messages against the server's active path, write only what changed, and
|
|
7796
|
+
* leave the live cache current. Returns `null` when a newer request
|
|
7797
|
+
* superseded this one part-way through (`isCurrent` turned false).
|
|
7798
|
+
*
|
|
7799
|
+
* Storage traffic here is independent of transcript length: the server
|
|
7800
|
+
* transcript comes from the live cache when it covers the path, unchanged
|
|
7801
|
+
* echoed messages are skipped before Sessions is asked, and the cache is
|
|
7802
|
+
* re-read only when it is windowed.
|
|
7131
7803
|
*/
|
|
7132
|
-
async
|
|
7133
|
-
const
|
|
7134
|
-
|
|
7135
|
-
|
|
7804
|
+
async _reconcileAndPersistIncoming(incomingMessages, options) {
|
|
7805
|
+
const spanAttributes = {
|
|
7806
|
+
"cloudflare.agents.component": "think",
|
|
7807
|
+
"cloudflare.agents.turn.request_id": options.requestId,
|
|
7808
|
+
"cloudflare.agents.turn.trigger": "ws-chat"
|
|
7809
|
+
};
|
|
7810
|
+
const serverMessages = await withAgentSpan(this, "load_chat_history", "interaction", spanAttributes, () => this._serverTranscriptForReconcile());
|
|
7811
|
+
const serverMessagesById = new Map(serverMessages.map((message) => [message.id, message]));
|
|
7812
|
+
const reconciled = reconcileMessages(incomingMessages, serverMessages, sanitizeMessage);
|
|
7813
|
+
let branchParentId;
|
|
7814
|
+
if (options.isRegeneration && reconciled.length > 0) branchParentId = reconciled[reconciled.length - 1].id;
|
|
7815
|
+
return await withAgentSpan(this, "persist_incoming_messages", "interaction", spanAttributes, async () => {
|
|
7816
|
+
if (!options.isCurrent()) return false;
|
|
7817
|
+
for (const msg of reconciled) {
|
|
7818
|
+
if (!options.isCurrent()) return false;
|
|
7819
|
+
await this._persistIncomingMessage(msg, serverMessages, serverMessagesById);
|
|
7820
|
+
}
|
|
7821
|
+
if (!options.isCurrent()) return false;
|
|
7822
|
+
if (!this._cacheCoversActivePath) await this._syncMessages();
|
|
7823
|
+
return true;
|
|
7824
|
+
}) ? { branchParentId } : null;
|
|
7136
7825
|
}
|
|
7137
7826
|
/**
|
|
7138
|
-
*
|
|
7139
|
-
*
|
|
7140
|
-
*
|
|
7141
|
-
*
|
|
7827
|
+
* The server transcript that reconciliation diffs client messages against.
|
|
7828
|
+
* The live cache answers when it holds the whole active path — the common
|
|
7829
|
+
* case, kept current by the change feed after every durable write. A
|
|
7830
|
+
* windowed or unhydrated cache falls back to the full storage read, since
|
|
7831
|
+
* reconciliation must see every message (`_readMessagesFromStorage`).
|
|
7832
|
+
*
|
|
7833
|
+
* Returns a snapshot: the writes that follow patch the cache through the
|
|
7834
|
+
* change feed while the caller is still iterating.
|
|
7142
7835
|
*/
|
|
7143
|
-
|
|
7144
|
-
|
|
7145
|
-
|
|
7146
|
-
|
|
7147
|
-
|
|
7148
|
-
|
|
7149
|
-
|
|
7150
|
-
|
|
7151
|
-
|
|
7836
|
+
async _serverTranscriptForReconcile() {
|
|
7837
|
+
if (this._cacheCoversActivePath) return [...this._cachedMessages];
|
|
7838
|
+
return this._readMessagesFromStorage();
|
|
7839
|
+
}
|
|
7840
|
+
/**
|
|
7841
|
+
* Persist an incoming message after reconciliation. For assistant
|
|
7842
|
+
* messages, also resolve their ID against any server-side row that
|
|
7843
|
+
* already owns the same `toolCallId` so we update the existing row
|
|
7844
|
+
* instead of inserting an orphan duplicate.
|
|
7845
|
+
*
|
|
7846
|
+
* A message whose stored form is what the server already holds is skipped
|
|
7847
|
+
* outright. The client posts its whole transcript on every request, so
|
|
7848
|
+
* without this every prior message would cost Sessions an existence read
|
|
7849
|
+
* plus a full-row compare (and, for media, a decode and hash of every
|
|
7850
|
+
* payload) per turn — reads spent discovering nothing changed.
|
|
7851
|
+
*/
|
|
7852
|
+
async _persistIncomingMessage(msg, serverMessages, serverMessagesById) {
|
|
7853
|
+
const resolved = msg.role === "assistant" ? resolveToolMergeId(msg, serverMessages) : msg;
|
|
7854
|
+
const prior = serverMessagesById?.get(resolved.id);
|
|
7855
|
+
if (prior && JSON.stringify(prior) === JSON.stringify(stripReservedMetadata(sanitizeMessage(resolved)))) return;
|
|
7856
|
+
await this._upsertMessageInHistory(resolved, void 0, "client");
|
|
7857
|
+
}
|
|
7858
|
+
_persistRequestContextKey(key, value) {
|
|
7859
|
+
const json = value ? JSON.stringify(value) : void 0;
|
|
7860
|
+
if (this._persistedRequestContext[key] === json) return;
|
|
7861
|
+
if (json === void 0) this._configDelete(key);
|
|
7862
|
+
else this._configSet(key, json);
|
|
7863
|
+
this._persistedRequestContext[key] = json;
|
|
7152
7864
|
}
|
|
7153
7865
|
_persistClientTools() {
|
|
7154
|
-
|
|
7155
|
-
else this._configDelete("lastClientTools");
|
|
7866
|
+
this._persistRequestContextKey("lastClientTools", this._lastClientTools);
|
|
7156
7867
|
}
|
|
7157
7868
|
_restoreClientTools() {
|
|
7158
7869
|
const raw = this._configGet("lastClientTools");
|
|
7870
|
+
this._persistedRequestContext.lastClientTools = raw;
|
|
7159
7871
|
if (raw) try {
|
|
7160
7872
|
this._lastClientTools = JSON.parse(raw);
|
|
7161
7873
|
} catch {
|
|
@@ -7163,11 +7875,11 @@ var Think = class Think extends Agent {
|
|
|
7163
7875
|
}
|
|
7164
7876
|
}
|
|
7165
7877
|
_persistBody() {
|
|
7166
|
-
|
|
7167
|
-
else this._configDelete("lastBody");
|
|
7878
|
+
this._persistRequestContextKey("lastBody", this._lastBody);
|
|
7168
7879
|
}
|
|
7169
7880
|
_restoreBody() {
|
|
7170
7881
|
const raw = this._configGet("lastBody");
|
|
7882
|
+
this._persistedRequestContext.lastBody = raw;
|
|
7171
7883
|
if (raw) try {
|
|
7172
7884
|
this._lastBody = JSON.parse(raw);
|
|
7173
7885
|
} catch {
|
|
@@ -7559,29 +8271,30 @@ var Think = class Think extends Agent {
|
|
|
7559
8271
|
async _applyToolUpdateToMessages(update) {
|
|
7560
8272
|
let broadcastMessage;
|
|
7561
8273
|
const streaming = this._streamingAssistant;
|
|
8274
|
+
let accumulatorOwnsCall = false;
|
|
7562
8275
|
if (streaming) {
|
|
7563
8276
|
const accParts = streaming.parts;
|
|
7564
8277
|
const result = applyToolUpdate(accParts, update);
|
|
7565
|
-
if (result
|
|
7566
|
-
|
|
7567
|
-
|
|
8278
|
+
if (result) {
|
|
8279
|
+
accumulatorOwnsCall = true;
|
|
8280
|
+
if (result.parts[result.index] !== accParts[result.index]) {
|
|
8281
|
+
accParts[result.index] = result.parts[result.index];
|
|
8282
|
+
broadcastMessage = streaming.toMessage();
|
|
8283
|
+
}
|
|
7568
8284
|
}
|
|
7569
8285
|
}
|
|
7570
|
-
const
|
|
7571
|
-
|
|
7572
|
-
const
|
|
7573
|
-
const
|
|
7574
|
-
|
|
7575
|
-
if (result) {
|
|
7576
|
-
if (result.parts[result.index] === msgParts[result.index]) break;
|
|
8286
|
+
const owner = await this._resolveToolCallOwner(update.toolCallId, accumulatorOwnsCall && streaming ? streaming.messageId : void 0);
|
|
8287
|
+
if (owner) {
|
|
8288
|
+
const ownerParts = owner.parts;
|
|
8289
|
+
const result = applyToolUpdate(ownerParts, update);
|
|
8290
|
+
if (result && result.parts[result.index] !== ownerParts[result.index]) {
|
|
7577
8291
|
const updatedMsg = {
|
|
7578
|
-
...
|
|
8292
|
+
...owner,
|
|
7579
8293
|
parts: result.parts
|
|
7580
8294
|
};
|
|
7581
8295
|
const safe = await this._updateMessageInHistory(updatedMsg);
|
|
7582
8296
|
this._patchCachedMessage(safe);
|
|
7583
8297
|
broadcastMessage = safe;
|
|
7584
|
-
break;
|
|
7585
8298
|
}
|
|
7586
8299
|
}
|
|
7587
8300
|
if (broadcastMessage) this._broadcast({
|
|
@@ -7589,6 +8302,55 @@ var Think = class Think extends Agent {
|
|
|
7589
8302
|
message: broadcastMessage
|
|
7590
8303
|
});
|
|
7591
8304
|
}
|
|
8305
|
+
/**
|
|
8306
|
+
* The persisted message that owns `toolCallId`, read as one row — or
|
|
8307
|
+
* `null` when no persisted row owns it.
|
|
8308
|
+
*
|
|
8309
|
+
* Lookup order, cheapest first:
|
|
8310
|
+
*
|
|
8311
|
+
* 1. `liveMessageId`, when the in-flight accumulator owns the call. A row
|
|
8312
|
+
* under that id exists only when stall recovery persisted a partial
|
|
8313
|
+
* mid-stream. When it does not, the call is not on its own row — but a
|
|
8314
|
+
* provider can replay a prior tool round-trip into a fresh continuation
|
|
8315
|
+
* accumulator (#1404), so the persisted owner may still be an earlier
|
|
8316
|
+
* message; the cache is checked for that before concluding there is
|
|
8317
|
+
* nothing durable to update. Storage is never walked for a call the
|
|
8318
|
+
* live turn owns: every row it could target is on the cached path.
|
|
8319
|
+
* 2. The live cache, for the id only. Whatever names the row, the returned
|
|
8320
|
+
* message is always the STORED form: the apply must compare against
|
|
8321
|
+
* what storage holds, and the cache may be patched ahead of it.
|
|
8322
|
+
* 3. Storage, newest first, stopping at the first owner. Reached only when
|
|
8323
|
+
* the cache does not cover the active path (a windowed hydration, a
|
|
8324
|
+
* boot whose hydration failed, or rows imported behind the cache): a
|
|
8325
|
+
* cross-message result can target a row older than the window, and the
|
|
8326
|
+
* path is read from the leaf so a recent hit costs the rows it passed,
|
|
8327
|
+
* not the transcript.
|
|
8328
|
+
*
|
|
8329
|
+
* This is what keeps a long turn's tool updates independent of transcript
|
|
8330
|
+
* length: the previous shape re-read the whole path per update.
|
|
8331
|
+
*/
|
|
8332
|
+
async _resolveToolCallOwner(toolCallId, liveMessageId) {
|
|
8333
|
+
const owns = (message) => message.parts.some((part) => part.toolCallId === toolCallId);
|
|
8334
|
+
const stored = async (id) => {
|
|
8335
|
+
const row = await this.session.getMessage(id);
|
|
8336
|
+
return row && owns(row) ? row : null;
|
|
8337
|
+
};
|
|
8338
|
+
const cachedOwnerId = () => {
|
|
8339
|
+
for (let i = this._cachedMessages.length - 1; i >= 0; i--) if (owns(this._cachedMessages[i])) return this._cachedMessages[i].id;
|
|
8340
|
+
return null;
|
|
8341
|
+
};
|
|
8342
|
+
if (liveMessageId !== void 0) {
|
|
8343
|
+
const live = await stored(liveMessageId);
|
|
8344
|
+
if (live) return live;
|
|
8345
|
+
const cachedId = cachedOwnerId();
|
|
8346
|
+
return cachedId === null ? null : stored(cachedId);
|
|
8347
|
+
}
|
|
8348
|
+
const cachedId = cachedOwnerId();
|
|
8349
|
+
if (cachedId !== null) return stored(cachedId);
|
|
8350
|
+
if (this._cacheCoversActivePath) return null;
|
|
8351
|
+
for await (const message of this.session.history({ newestFirst: true })) if (owns(message)) return message;
|
|
8352
|
+
return null;
|
|
8353
|
+
}
|
|
7592
8354
|
hasPendingInteraction() {
|
|
7593
8355
|
const clientResolvable = this._clientResolvableToolNames();
|
|
7594
8356
|
const streaming = this._streamingAssistant;
|
|
@@ -7677,33 +8439,38 @@ var Think = class Think extends Agent {
|
|
|
7677
8439
|
* recomputed from the live, mutable transcript. Compaction collapses older
|
|
7678
8440
|
* assistant messages into a summary, lowering the count — so a turn that had
|
|
7679
8441
|
* genuinely advanced could read as "no progress" between attempts and exhaust
|
|
7680
|
-
* its budget prematurely (#1628).
|
|
7681
|
-
*
|
|
7682
|
-
*
|
|
7683
|
-
*
|
|
7684
|
-
*
|
|
8442
|
+
* its budget prematurely (#1628). It then became a KV counter bumped per
|
|
8443
|
+
* credited chunk. It is now derived from the stream log the chunks were
|
|
8444
|
+
* already flushed to (`ResumableStream.progressMarker`): the log only grows
|
|
8445
|
+
* when new content lands durably, a reconnect replay or a recovery
|
|
8446
|
+
* re-persist reads it without appending (#1637), and compaction rewrites
|
|
8447
|
+
* the transcript, not the log. Nothing is written per chunk.
|
|
8448
|
+
*
|
|
8449
|
+
* The pre-derivation KV counter is folded in once per isolate, so a marker
|
|
8450
|
+
* an in-flight incident already recorded is never read lower after the
|
|
8451
|
+
* upgrade.
|
|
7685
8452
|
*/
|
|
7686
8453
|
async _chatRecoveryProgressMarker() {
|
|
7687
|
-
|
|
7688
|
-
|
|
7689
|
-
|
|
7690
|
-
|
|
7691
|
-
|
|
7692
|
-
|
|
7693
|
-
async _bumpChatRecoveryProgress() {
|
|
7694
|
-
return bumpChatRecoveryProgress(this.ctx.storage);
|
|
8454
|
+
this._progressSeed ??= readChatRecoveryProgress(this.ctx.storage).then((legacy) => this._resumableStream.seedProgress(legacy), (error) => {
|
|
8455
|
+
this._progressSeed = null;
|
|
8456
|
+
throw error;
|
|
8457
|
+
});
|
|
8458
|
+
await this._progressSeed;
|
|
8459
|
+
return this._resumableStream.progressMarker();
|
|
7695
8460
|
}
|
|
7696
8461
|
/**
|
|
7697
8462
|
* N9: forwarding a sub-agent's chunks IS forward progress for this parent
|
|
7698
8463
|
* turn, so credit the parent's recovery progress marker — otherwise a parent
|
|
7699
8464
|
* whose turn merely `await`s a child banks no progress of its own and its
|
|
7700
|
-
* no-progress window exhausts while the child is healthily streaming.
|
|
8465
|
+
* no-progress window exhausts while the child is healthily streaming. The
|
|
8466
|
+
* child's output goes to clients, not to this object's stream log, so the
|
|
8467
|
+
* derived marker cannot see it; this is the one explicit credit left. Only
|
|
7701
8468
|
* invoked after a child actually produced output (see
|
|
7702
8469
|
* `_forwardAgentToolStream`), so a silent child still lets the parent exhaust.
|
|
7703
8470
|
* Throttled (and reset per isolate) so we never write storage per token.
|
|
7704
8471
|
*/
|
|
7705
8472
|
async _onAgentToolStreamProgress() {
|
|
7706
|
-
if (this._agentToolStreamProgress.shouldCredit(Date.now()))
|
|
8473
|
+
if (this._agentToolStreamProgress.shouldCredit(Date.now())) this._resumableStream.creditProgress();
|
|
7707
8474
|
}
|
|
7708
8475
|
async _beginChatRecoveryIncident(input) {
|
|
7709
8476
|
return this._chatRecoveryEngine().beginIncident(input);
|
|
@@ -7732,9 +8499,7 @@ var Think = class Think extends Agent {
|
|
|
7732
8499
|
recoveryKind: event.recoveryKind,
|
|
7733
8500
|
...event.reason ? { reason: event.reason } : {}
|
|
7734
8501
|
}),
|
|
7735
|
-
scheduleRecovery:
|
|
7736
|
-
await this.schedule(delaySeconds, callback, data, chatRecoverySchedulePolicy(reason));
|
|
7737
|
-
},
|
|
8502
|
+
scheduleRecovery: (callback, data, reason, delaySeconds) => this._enqueueChatRecovery(callback, data, reason, delaySeconds),
|
|
7738
8503
|
setRecovering: (active, requestId) => this._setChatRecovering(active, requestId),
|
|
7739
8504
|
onShouldKeepRecoveringError: (error) => console.error("[Think] chatRecovery shouldKeepRecovering hook threw", error),
|
|
7740
8505
|
exhaustChatRecovery: (incident, config, partial, streamId, createdAt) => this._exhaustChatRecovery(incident, config, partial, streamId, createdAt),
|
|
@@ -7874,14 +8639,10 @@ var Think = class Think extends Agent {
|
|
|
7874
8639
|
let streamId = "";
|
|
7875
8640
|
let streamStatus;
|
|
7876
8641
|
if (requestId) {
|
|
7877
|
-
const
|
|
7878
|
-
|
|
7879
|
-
|
|
7880
|
-
|
|
7881
|
-
`;
|
|
7882
|
-
if (rows.length > 0) {
|
|
7883
|
-
streamId = rows[0].id;
|
|
7884
|
-
streamStatus = rows[0].status;
|
|
8642
|
+
const info = this._resumableStream.latestStreamInfoForRequest(requestId);
|
|
8643
|
+
if (info) {
|
|
8644
|
+
streamId = info.id;
|
|
8645
|
+
streamStatus = info.status;
|
|
7885
8646
|
}
|
|
7886
8647
|
}
|
|
7887
8648
|
if (!streamId && this._resumableStream.hasActiveStream()) {
|
|
@@ -8069,10 +8830,10 @@ var Think = class Think extends Agent {
|
|
|
8069
8830
|
* `_exhaustChatRecovery` entirely — so an app relying on `onExhausted` for the
|
|
8070
8831
|
* terminal banner regressed to an eternal spinner when recovery gave up under
|
|
8071
8832
|
* extreme churn. The error path matters just as much: a non-transient throw
|
|
8072
|
-
* in a recovery callback is SWALLOWED by
|
|
8073
|
-
*
|
|
8074
|
-
* without routing it here the
|
|
8075
|
-
* all — the half-finished message wedges silently. Shared by
|
|
8833
|
+
* in a recovery callback is SWALLOWED by the driving Task attempt (or the
|
|
8834
|
+
* routed one-shot schedule row) — only a platform transient is re-thrown to
|
|
8835
|
+
* preserve it — so without routing it here the run/row settles with no
|
|
8836
|
+
* terminal UX at all — the half-finished message wedges silently. Shared by
|
|
8076
8837
|
* `_chatRecoveryRetry` and `_chatRecoveryContinue`.
|
|
8077
8838
|
*
|
|
8078
8839
|
* Exactly-once terminalization is defended by two independent guards:
|
|
@@ -8090,8 +8851,9 @@ var Think = class Think extends Agent {
|
|
|
8090
8851
|
* Residual at-least-once edges, all deliberately accepted as "deliver a
|
|
8091
8852
|
* second banner" ≫ "silently drop the turn":
|
|
8092
8853
|
* • No `incidentId` at all in the payload (only reachable via a direct/test
|
|
8093
|
-
* invocation — every production
|
|
8094
|
-
* incident can't be persisted (no key), so guard #1 can't
|
|
8854
|
+
* invocation — every production recovery enqueue carries one): the
|
|
8855
|
+
* synthesized incident can't be persisted (no key), so guard #1 can't
|
|
8856
|
+
* arm.
|
|
8095
8857
|
* • The record is swept AGAIN between two alarms (guard #1 re-persists on the
|
|
8096
8858
|
* first, so this needs a second independent sweep) — vanishingly unlikely.
|
|
8097
8859
|
* • A platform transient interrupts `_exhaustChatRecovery` after the banner
|
|
@@ -8099,18 +8861,25 @@ var Think = class Think extends Agent {
|
|
|
8099
8861
|
* (the terminal writes themselves are idempotent).
|
|
8100
8862
|
*/
|
|
8101
8863
|
/**
|
|
8102
|
-
*
|
|
8103
|
-
*
|
|
8864
|
+
* Host memory-limit policy hook (#1825), dispatched structurally by
|
|
8865
|
+
* Lifecycle's circuit breaker — protected because it is framework
|
|
8866
|
+
* machinery, not part of the public Think API. Tasks applies the breaker to
|
|
8867
|
+
* root recovery runs; the routed dynamic-agent fallback applies it to
|
|
8868
|
+
* `recoveryLoop` schedule rows (see `RecoveryLoopScheduleOptions`). At the
|
|
8869
|
+
* strike budget this hook seals active incidents via
|
|
8870
|
+
* {@link _cf_sealMemoryLimitedRecovery}.
|
|
8104
8871
|
*/
|
|
8105
|
-
|
|
8106
|
-
|
|
8872
|
+
async onAlarmMemoryLimit(context) {
|
|
8873
|
+
if (!context.sealed) return;
|
|
8874
|
+
await this._cf_sealMemoryLimitedRecovery();
|
|
8107
8875
|
}
|
|
8108
8876
|
/**
|
|
8109
|
-
* Seal any still-live recovery incident as an out-of-memory exhaustion
|
|
8110
|
-
* the alarm circuit breaker trips at its strike budget (#1825). Runs
|
|
8111
|
-
* outermost alarm frame (post-unwind), so the terminal banner /
|
|
8112
|
-
* and the sealed-incident write can land where the mid-turn
|
|
8113
|
-
* OOMed. Reuses the shared give-up spine via
|
|
8877
|
+
* Seal any still-live recovery incident as an out-of-memory exhaustion
|
|
8878
|
+
* when the alarm circuit breaker trips at its strike budget (#1825). Runs
|
|
8879
|
+
* at the outermost alarm frame (post-unwind), so the terminal banner /
|
|
8880
|
+
* `onExhausted` and the sealed-incident write can land where the mid-turn
|
|
8881
|
+
* give-up's writes OOMed. Reuses the shared give-up spine via
|
|
8882
|
+
* `_exhaustRecoveryGiveUp`.
|
|
8114
8883
|
*/
|
|
8115
8884
|
async _cf_sealMemoryLimitedRecovery() {
|
|
8116
8885
|
const active = await listActiveChatRecoveryIncidents(this.ctx.storage);
|
|
@@ -8182,9 +8951,9 @@ var Think = class Think extends Agent {
|
|
|
8182
8951
|
* deploy code-update reset / script supersede, a `retryable`-flagged
|
|
8183
8952
|
* platform error, or "Network connection lost.", looking through wrappers
|
|
8184
8953
|
* like `SqlError` via the `cause` chain) is re-thrown (after best-effort
|
|
8185
|
-
* marking the incident `failed` for observability) so
|
|
8186
|
-
*
|
|
8187
|
-
* the platform re-runs recovery once it is healthy again — the turn can
|
|
8954
|
+
* marking the incident `failed` for observability) so the current
|
|
8955
|
+
* attempt (the driving Task run, or the routed one-shot schedule row) is
|
|
8956
|
+
* preserved and the platform re-runs recovery once it is healthy again — the turn can
|
|
8188
8957
|
* still recover, so it must NOT terminalize. Terminalizing here was the
|
|
8189
8958
|
* #1730 freeze: the give-up's own seal needs the very storage that is
|
|
8190
8959
|
* down, so it throws too, burns the in-process retry budget inside the
|
|
@@ -8195,11 +8964,11 @@ var Think = class Think extends Agent {
|
|
|
8195
8964
|
* `submission_not_running` no-op skip (a self-defeating defer).
|
|
8196
8965
|
* - Any OTHER (application) error is terminalized through the give-up path
|
|
8197
8966
|
* (`onExhausted` + the `terminalMessage` banner) and NOT re-thrown. This is
|
|
8198
|
-
* the fix for the silent-seal failure mode:
|
|
8199
|
-
*
|
|
8200
|
-
*
|
|
8201
|
-
*
|
|
8202
|
-
*
|
|
8967
|
+
* the fix for the silent-seal failure mode: the driving attempt swallows
|
|
8968
|
+
* a non-transient throw and settles without terminalizing, so without
|
|
8969
|
+
* terminalizing here the half-finished turn is dropped with no terminal
|
|
8970
|
+
* event and no banner (the user stares at a frozen message until they
|
|
8971
|
+
* send something new).
|
|
8203
8972
|
*/
|
|
8204
8973
|
async _handleRecoveryCallbackError(callback, data, error) {
|
|
8205
8974
|
if (await this._handleRecoveryOom(callback, data, error)) return;
|
|
@@ -8216,6 +8985,9 @@ var Think = class Think extends Agent {
|
|
|
8216
8985
|
await this._exhaustRecoveryGiveUp(callback, data, "recovery_error");
|
|
8217
8986
|
}
|
|
8218
8987
|
async _chatRecoveryRetry(data) {
|
|
8988
|
+
await this._dispatchChatRecovery("_chatRecoveryRetry", data, (onTurnStarted) => this._chatRecoveryRetryDetached(data, onTurnStarted));
|
|
8989
|
+
}
|
|
8990
|
+
async _chatRecoveryRetryDetached(data, onTurnStarted) {
|
|
8219
8991
|
const recoveredSubmission = data?.recoveredRequestId ? this._readRunningSubmissionByRequestId(data.recoveredRequestId) : null;
|
|
8220
8992
|
if (data?.recoveredRequestId && !recoveredSubmission) {
|
|
8221
8993
|
await this._updateChatRecoveryIncident(data.incidentId, "skipped", "submission_not_running");
|
|
@@ -8245,6 +9017,7 @@ var Think = class Think extends Agent {
|
|
|
8245
9017
|
return;
|
|
8246
9018
|
}
|
|
8247
9019
|
this._applyRecoveredRequestContext(data);
|
|
9020
|
+
onTurnStarted?.();
|
|
8248
9021
|
const result = await this._retryLastUserTurn(this._lastClientTools, this._lastBody, controller ? {
|
|
8249
9022
|
signal: controller.signal,
|
|
8250
9023
|
trigger: "recovery-retry"
|
|
@@ -8326,6 +9099,9 @@ var Think = class Think extends Agent {
|
|
|
8326
9099
|
return {};
|
|
8327
9100
|
}
|
|
8328
9101
|
async _chatRecoveryContinue(data) {
|
|
9102
|
+
await this._dispatchChatRecovery("_chatRecoveryContinue", data, (onTurnStarted) => this._chatRecoveryContinueDetached(data, onTurnStarted));
|
|
9103
|
+
}
|
|
9104
|
+
async _chatRecoveryContinueDetached(data, onTurnStarted) {
|
|
8329
9105
|
const recoveredSubmission = data?.recoveredRequestId ? this._readRunningSubmissionByRequestId(data.recoveredRequestId) : null;
|
|
8330
9106
|
if (data?.recoveredRequestId && !recoveredSubmission) {
|
|
8331
9107
|
await this._updateChatRecoveryIncident(data.incidentId, "skipped", "submission_not_running");
|
|
@@ -8353,6 +9129,7 @@ var Think = class Think extends Agent {
|
|
|
8353
9129
|
return;
|
|
8354
9130
|
}
|
|
8355
9131
|
this._applyRecoveredRequestContext(data);
|
|
9132
|
+
onTurnStarted?.();
|
|
8356
9133
|
const result = await this.continueLastTurn(void 0, controller ? {
|
|
8357
9134
|
signal: controller.signal,
|
|
8358
9135
|
trigger: "recovery-continue"
|
|
@@ -8755,45 +9532,31 @@ var Think = class Think extends Agent {
|
|
|
8755
9532
|
_startResumableStream(requestId, options) {
|
|
8756
9533
|
const streamId = this._resumableStream.start(requestId, options);
|
|
8757
9534
|
this._preStream.flushOnStreamStart((c) => this._notifyStreamResuming(c));
|
|
8758
|
-
this._ensureStreamCleanupScheduled();
|
|
8759
9535
|
return streamId;
|
|
8760
9536
|
}
|
|
8761
|
-
/**
|
|
8762
|
-
* Mark a resumable stream completed and arm buffer cleanup. Wrapper around
|
|
8763
|
-
* `ResumableStream.complete` so every stream-finish path also schedules the
|
|
8764
|
-
* cleanup alarm (#1706).
|
|
8765
|
-
*/
|
|
9537
|
+
/** Mark a resumable stream completed (settled now, rows kept until reclaim). */
|
|
8766
9538
|
_completeResumableStream(streamId) {
|
|
8767
9539
|
this._resumableStream.complete(streamId);
|
|
8768
|
-
this._ensureStreamCleanupScheduled();
|
|
8769
9540
|
}
|
|
8770
9541
|
/**
|
|
8771
|
-
*
|
|
8772
|
-
* `
|
|
9542
|
+
* The producer finished; leave the row for the cutover that persists the
|
|
9543
|
+
* assistant message (`_persistAssistantMessageWithCutover`). Every path
|
|
9544
|
+
* that calls this must end in that cutover or `finalizePending()`.
|
|
8773
9545
|
*/
|
|
9546
|
+
_finishResumableStream(streamId) {
|
|
9547
|
+
this._resumableStream.finish(streamId);
|
|
9548
|
+
}
|
|
9549
|
+
/** Mark a resumable stream errored. */
|
|
8774
9550
|
_errorResumableStream(streamId) {
|
|
8775
9551
|
this._resumableStream.markError(streamId);
|
|
8776
|
-
this._ensureStreamCleanupScheduled();
|
|
8777
9552
|
}
|
|
8778
9553
|
/**
|
|
8779
|
-
*
|
|
8780
|
-
*
|
|
8781
|
-
*
|
|
8782
|
-
* only fires when a *subsequent* stream completes, which never happens for a
|
|
8783
|
-
* chat that receives a single turn (#1706).
|
|
8784
|
-
*
|
|
8785
|
-
* `idempotent` dedupes on (callback, payload, owner) so repeated finishes
|
|
8786
|
-
* collapse onto one pending alarm rather than stacking.
|
|
8787
|
-
*/
|
|
8788
|
-
async _ensureStreamCleanupScheduled({ idempotent = true } = {}) {
|
|
8789
|
-
await this.schedule(STREAM_CLEANUP_DELAY_SECONDS, "_cleanupStreamBuffers", void 0, { idempotent });
|
|
8790
|
-
}
|
|
8791
|
-
/**
|
|
8792
|
-
* Alarm callback: sweep aged stream buffers, re-arming while rows remain (see
|
|
8793
|
-
* the shared {@link cleanupStreamBuffers}).
|
|
9554
|
+
* @deprecated Streams are reclaimed at cutover and on the next stream
|
|
9555
|
+
* start; no alarm is armed any more. Kept so a cleanup alarm persisted by
|
|
9556
|
+
* an earlier version still resolves to a callback when it fires.
|
|
8794
9557
|
*/
|
|
8795
9558
|
async _cleanupStreamBuffers() {
|
|
8796
|
-
|
|
9559
|
+
this._resumableStream.reclaim();
|
|
8797
9560
|
}
|
|
8798
9561
|
async _persistOrphanedStream(streamId) {
|
|
8799
9562
|
this._resumableStream.flushBuffer();
|
|
@@ -8820,6 +9583,11 @@ var Think = class Think extends Agent {
|
|
|
8820
9583
|
}, exclude);
|
|
8821
9584
|
}
|
|
8822
9585
|
};
|
|
9586
|
+
/** Durable SQLite storage for one context block of this agent. */
|
|
9587
|
+
function _contextProvider(label) {
|
|
9588
|
+
const sessionId = this.session?.sessionId ?? "";
|
|
9589
|
+
return new AgentContextProvider(this, sessionId ? `${label}_${sessionId}` : label);
|
|
9590
|
+
}
|
|
8823
9591
|
Think.CONFIG_KEYS = [
|
|
8824
9592
|
"_think_config",
|
|
8825
9593
|
"lastClientTools",
|
|
@@ -8836,6 +9604,6 @@ for (const method of [
|
|
|
8836
9604
|
Think.prototype.rejectExecution
|
|
8837
9605
|
]) callable()(method, void 0);
|
|
8838
9606
|
//#endregion
|
|
8839
|
-
export { Session, Think, Workspace, action, defaultContextOverflowClassifier, isAction, messengerChannel, skills };
|
|
9607
|
+
export { ThinkSession as Session, ThinkSession, Think, Workspace, action, defaultContextOverflowClassifier, isAction, messengerChannel, skills };
|
|
8840
9608
|
|
|
8841
9609
|
//# sourceMappingURL=think.js.map
|