@cloudflare/think 0.16.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 +137 -35
- 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-BZKPlFcA.d.ts → index-CJ--4uax.d.ts} +626 -192
- 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 +1220 -440
- 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 +126 -56
- package/docs/lifecycle-hooks.md +51 -15
- package/docs/sub-agents.md +7 -19
- 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,60 @@ 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
|
+
}
|
|
1125
|
+
/** Stable id prefix for fallback notes that preserve orphaned execution outcomes. */
|
|
1126
|
+
const EXECUTION_OUTCOME_MESSAGE_PREFIX = "exec-outcome-";
|
|
1127
|
+
/**
|
|
1128
|
+
* Present framework-authored execution outcome notes to providers as user
|
|
1129
|
+
* context. Think persists these notes as system messages so clients and
|
|
1130
|
+
* recovery do not mistake them for human input, but AI SDK v7 and strict
|
|
1131
|
+
* providers reject system messages in arbitrary transcript
|
|
1132
|
+
* positions. The provider-only projection leaves current and legacy session
|
|
1133
|
+
* history unchanged.
|
|
1134
|
+
*/
|
|
1135
|
+
function toProviderSafeExecutionOutcomeMessage(message) {
|
|
1136
|
+
return message.role === "system" && message.id.startsWith(EXECUTION_OUTCOME_MESSAGE_PREFIX) ? {
|
|
1137
|
+
...message,
|
|
1138
|
+
role: "user"
|
|
1139
|
+
} : message;
|
|
1140
|
+
}
|
|
808
1141
|
/**
|
|
809
1142
|
* Reserved name for the synthetic tool a workflow `step.prompt` turn uses to
|
|
810
1143
|
* deliver its structured final answer. The agent runs a full multi-step,
|
|
@@ -893,9 +1226,27 @@ function defaultContextOverflowClassifier(error) {
|
|
|
893
1226
|
}
|
|
894
1227
|
return CONTEXT_OVERFLOW_PATTERN.test(text) ? "context_overflow" : void 0;
|
|
895
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();
|
|
896
1238
|
var _configCache = /* @__PURE__ */ new WeakMap();
|
|
897
1239
|
var _configTableReady = /* @__PURE__ */ new WeakMap();
|
|
1240
|
+
var _configMemo = /* @__PURE__ */ new WeakMap();
|
|
1241
|
+
var _agentToolChildRunTableReady = /* @__PURE__ */ new WeakMap();
|
|
898
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
|
+
}
|
|
899
1250
|
/**
|
|
900
1251
|
* Internal onStart steps that failed on this wake and were skipped so the
|
|
901
1252
|
* agent could still come up (see {@link OnStartDegradation}). Empty when
|
|
@@ -907,30 +1258,39 @@ var Think = class Think extends Agent {
|
|
|
907
1258
|
}
|
|
908
1259
|
constructor(ctx, env) {
|
|
909
1260
|
super(ctx, env);
|
|
1261
|
+
_classPrivateMethodInitSpec(this, _Think_brand);
|
|
910
1262
|
this.includeMcpTools = true;
|
|
911
1263
|
this.waitForMcpConnections = false;
|
|
912
1264
|
this.storeMessages = false;
|
|
913
1265
|
this.storeTools = false;
|
|
1266
|
+
this.skillWorkspace = false;
|
|
914
1267
|
this._skillRegistry = null;
|
|
915
1268
|
this._loggedSkillWarnings = /* @__PURE__ */ new Set();
|
|
916
1269
|
this._loggedProtocolWarnings = /* @__PURE__ */ new Set();
|
|
917
1270
|
this.messageConcurrency = "queue";
|
|
918
|
-
this.hydrationByteBudget =
|
|
1271
|
+
this.hydrationByteBudget = 32 * 1024 * 1024;
|
|
919
1272
|
this.mediaEviction = true;
|
|
920
1273
|
this.chatRecovery = true;
|
|
1274
|
+
this.sessions = new Sessions({ reservedMetadataKeys: RESERVED_MESSAGE_METADATA_KEYS });
|
|
1275
|
+
_classPrivateFieldInitSpec(this, _contextBlocks, void 0);
|
|
921
1276
|
this._cachedMessages = [];
|
|
922
1277
|
this._onStartDegradations = [];
|
|
923
1278
|
this.workspaceBash = true;
|
|
924
1279
|
this.fetchTools = false;
|
|
925
1280
|
this._mediaEvictionRunning = false;
|
|
926
1281
|
this._mediaEvictionScheduled = false;
|
|
927
|
-
this.
|
|
1282
|
+
this._mediaEvictionPending = false;
|
|
1283
|
+
this._mediaEvictionAppendsDuringPass = 0;
|
|
928
1284
|
this._warnedEvictionUnsupported = false;
|
|
1285
|
+
this._mediaEvictionFruitless = null;
|
|
929
1286
|
this._lastHydration = null;
|
|
930
1287
|
this._warnedHydrationWindowed = false;
|
|
1288
|
+
this._cacheCoversActivePath = false;
|
|
1289
|
+
this._cachedBytesSinceSync = 0;
|
|
931
1290
|
this._lastWindowedEmit = null;
|
|
932
1291
|
this._aborts = new AbortRegistry();
|
|
933
1292
|
this._turnQueue = new TurnQueue();
|
|
1293
|
+
this.streams = createChatStreams();
|
|
934
1294
|
this._pendingResumeConnections = /* @__PURE__ */ new Set();
|
|
935
1295
|
this._resumeHandshakeInstance = null;
|
|
936
1296
|
this._continuation = new ContinuationState();
|
|
@@ -969,6 +1329,8 @@ var Think = class Think extends Agent {
|
|
|
969
1329
|
this._programmaticStreamErrors = /* @__PURE__ */ new Map();
|
|
970
1330
|
_classPrivateFieldInitSpec(this, _configCache, null);
|
|
971
1331
|
_classPrivateFieldInitSpec(this, _configTableReady, false);
|
|
1332
|
+
_classPrivateFieldInitSpec(this, _configMemo, /* @__PURE__ */ new Map());
|
|
1333
|
+
this._liveChatTurnClosures = /* @__PURE__ */ new Map();
|
|
972
1334
|
this.maxSteps = 10;
|
|
973
1335
|
this.actionLedgerRetention = {
|
|
974
1336
|
settledMs: 720 * 60 * 60 * 1e3,
|
|
@@ -990,9 +1352,16 @@ var Think = class Think extends Agent {
|
|
|
990
1352
|
this._proactiveCompactionsThisRun = 0;
|
|
991
1353
|
this._warnedMissingClassifier = false;
|
|
992
1354
|
this.hookTimeout = 5e3;
|
|
1355
|
+
_classPrivateFieldInitSpec(this, _agentToolChildRunTableReady, false);
|
|
993
1356
|
this._agentToolProgressEmitterInstance = null;
|
|
994
|
-
this.
|
|
1357
|
+
this._persistedRequestContext = {};
|
|
1358
|
+
this._progressSeed = null;
|
|
995
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();
|
|
996
1365
|
const _onStart = this.onStart.bind(this);
|
|
997
1366
|
const startThink = async (props, update) => {
|
|
998
1367
|
await withAgentSpan(this, "initialize_think_session", "startup", { "cloudflare.agents.component": "think" }, async () => {
|
|
@@ -1000,24 +1369,42 @@ var Think = class Think extends Agent {
|
|
|
1000
1369
|
sql: this.ctx.storage.sql,
|
|
1001
1370
|
name: () => this.name
|
|
1002
1371
|
});
|
|
1003
|
-
|
|
1004
|
-
this.session
|
|
1005
|
-
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;
|
|
1006
1378
|
switch (event.type) {
|
|
1007
1379
|
case "append":
|
|
1008
1380
|
if (!event.inserted || event.parentId !== void 0) await this._syncMessages();
|
|
1009
|
-
else
|
|
1010
|
-
|
|
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();
|
|
1011
1394
|
break;
|
|
1012
1395
|
case "update":
|
|
1013
|
-
this._patchCachedMessage(event.message);
|
|
1396
|
+
if (this._cachedMessages.some((message) => message.id === event.message.id)) this._patchCachedMessage(event.message);
|
|
1014
1397
|
break;
|
|
1015
1398
|
case "clear":
|
|
1016
1399
|
this._replaceCachedMessages([]);
|
|
1400
|
+
this._cacheCoversActivePath = true;
|
|
1017
1401
|
break;
|
|
1018
1402
|
case "delete":
|
|
1403
|
+
await this._syncMessages();
|
|
1404
|
+
break;
|
|
1019
1405
|
case "compact":
|
|
1020
1406
|
await this._syncMessages();
|
|
1407
|
+
await _classPrivateFieldGet2(_contextBlocks, this)?.refreshSystemPrompt();
|
|
1021
1408
|
break;
|
|
1022
1409
|
}
|
|
1023
1410
|
});
|
|
@@ -1026,11 +1413,12 @@ var Think = class Think extends Agent {
|
|
|
1026
1413
|
this._onStartDegradations = [];
|
|
1027
1414
|
await withAgentSpan(this, "hydrate_think_session", "startup", { "cloudflare.agents.component": "think" }, async () => {
|
|
1028
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([]);
|
|
1029
|
-
this._refreshMediaEvictionSignalFromCache();
|
|
1030
1416
|
});
|
|
1031
1417
|
if (this.extensionLoader) await withAgentSpan(this, "initialize_think_extensions", "startup", { "cloudflare.agents.component": "think" }, () => this._initializeExtensions());
|
|
1032
1418
|
await withAgentSpan(this, "initialize_think_chat", "startup", { "cloudflare.agents.component": "think" }, async () => {
|
|
1033
|
-
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
|
+
} });
|
|
1034
1422
|
this._restoreClientTools();
|
|
1035
1423
|
this._restoreBody();
|
|
1036
1424
|
this._setupProtocolHandlers();
|
|
@@ -1046,7 +1434,6 @@ var Think = class Think extends Agent {
|
|
|
1046
1434
|
if (this._hasPendingSubmissions()) await this._scheduleSubmissionDrain();
|
|
1047
1435
|
if (this._hasPendingWorkflowNotifications()) this._startWorkflowNotificationDrain();
|
|
1048
1436
|
}, "Pending submissions / workflow notifications were not recovered on this wake; the next successful wake will recover them."));
|
|
1049
|
-
if (this._lastHydration?.truncated) this._scheduleMediaEvictionPass({ force: true });
|
|
1050
1437
|
update({
|
|
1051
1438
|
"cloudflare.agents.hydration.messages": this._lastHydration?.hydratedMessages,
|
|
1052
1439
|
"cloudflare.agents.hydration.content_bytes": this._lastHydration?.totalContentBytes,
|
|
@@ -1076,11 +1463,12 @@ var Think = class Think extends Agent {
|
|
|
1076
1463
|
*
|
|
1077
1464
|
* Intentionally UNBUDGETED — unlike the cache refresh in `_syncMessages`,
|
|
1078
1465
|
* which routes through `session.getRecentHistory(hydrationByteBudget)`, this
|
|
1079
|
-
* returns the full active path.
|
|
1080
|
-
*
|
|
1081
|
-
*
|
|
1082
|
-
*
|
|
1083
|
-
*
|
|
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`).
|
|
1084
1472
|
*
|
|
1085
1473
|
* These full reads are not the unbounded boot-time hydration that bricked the
|
|
1086
1474
|
* DO in #1710: they run during a live turn (never in `onStart`), so an
|
|
@@ -1167,7 +1555,7 @@ var Think = class Think extends Agent {
|
|
|
1167
1555
|
if (repair.removedToolCalls === 0 && repair.normalizedInputs === 0) return messages;
|
|
1168
1556
|
for (const message of repair.messages) {
|
|
1169
1557
|
const original = messages.find((candidate) => candidate.id === message.id);
|
|
1170
|
-
if (original && original.parts !== message.parts) await this.session.updateMessage(
|
|
1558
|
+
if (original && original.parts !== message.parts) await this.session.updateMessage(message);
|
|
1171
1559
|
}
|
|
1172
1560
|
this._replaceCachedMessages(repair.messages);
|
|
1173
1561
|
this._broadcastMessages();
|
|
@@ -1210,121 +1598,133 @@ var Think = class Think extends Agent {
|
|
|
1210
1598
|
}
|
|
1211
1599
|
}
|
|
1212
1600
|
/**
|
|
1213
|
-
*
|
|
1214
|
-
*
|
|
1215
|
-
*
|
|
1216
|
-
*
|
|
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.
|
|
1217
1605
|
*/
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
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;
|
|
1222
1631
|
this._mediaEvictionScheduled = true;
|
|
1223
1632
|
setTimeout(() => {
|
|
1224
1633
|
this._mediaEvictionScheduled = false;
|
|
1225
1634
|
this._evictAgedMediaBestEffort();
|
|
1226
1635
|
}, 0);
|
|
1227
1636
|
}
|
|
1228
|
-
_scheduleMediaEvictionAfterAppend(message) {
|
|
1229
|
-
const config = resolveMediaEvictionConfig(this.mediaEviction);
|
|
1230
|
-
if (!config) return;
|
|
1231
|
-
if (!this._mediaEvictionObservedOversized) this._mediaEvictionObservedOversized = this._messageMayNeedMediaEviction(message, config);
|
|
1232
|
-
if (!this._mediaEvictionObservedOversized) return;
|
|
1233
|
-
const keepRecent = Math.max(config.keepRecentMessages, MODEL_RECENT_WINDOW);
|
|
1234
|
-
if (this._cachedMessages.length > keepRecent) this._scheduleMediaEvictionPass({ force: true });
|
|
1235
|
-
}
|
|
1236
|
-
_refreshMediaEvictionSignalFromCache() {
|
|
1237
|
-
const config = resolveMediaEvictionConfig(this.mediaEviction);
|
|
1238
|
-
if (!config) {
|
|
1239
|
-
this._mediaEvictionObservedOversized = false;
|
|
1240
|
-
return;
|
|
1241
|
-
}
|
|
1242
|
-
this._mediaEvictionObservedOversized = this._cachedMessages.some((message) => this._messageMayNeedMediaEviction(message, config));
|
|
1243
|
-
}
|
|
1244
|
-
_messageMayNeedMediaEviction(message, config) {
|
|
1245
|
-
return JSON.stringify(message).length >= config.minPartBytes;
|
|
1246
|
-
}
|
|
1247
1637
|
/**
|
|
1248
|
-
*
|
|
1638
|
+
* Remove aged media from the conversation, leaving a Workspace pointer the
|
|
1639
|
+
* agent can read back.
|
|
1249
1640
|
*
|
|
1250
|
-
* Memory-bounded by design:
|
|
1251
|
-
* (no content loaded), only rows
|
|
1252
|
-
*
|
|
1253
|
-
*
|
|
1254
|
-
*
|
|
1255
|
-
*
|
|
1256
|
-
* workspace BEFORE the row is rewritten, so a failed pass never loses
|
|
1257
|
-
* 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.
|
|
1258
1647
|
*
|
|
1259
1648
|
* The aged cutoff is `keepRecentMessages` clamped to at least
|
|
1260
|
-
* `MODEL_RECENT_WINDOW`: messages the model still replays at full
|
|
1261
|
-
*
|
|
1262
|
-
*
|
|
1263
|
-
* When a pass stops at `maxRowsPerPass` with eligible rows remaining,
|
|
1264
|
-
* another pass is scheduled automatically so a large backlog drains
|
|
1265
|
-
* without waiting for new appends. Termination is guaranteed: every
|
|
1266
|
-
* rewritten row drops below `minPartBytes` and is skipped by later
|
|
1267
|
-
* 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.
|
|
1268
1651
|
*
|
|
1269
|
-
*
|
|
1270
|
-
*
|
|
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.
|
|
1271
1656
|
*/
|
|
1272
1657
|
async _evictAgedMediaBestEffort() {
|
|
1273
1658
|
if (this._mediaEvictionRunning) return null;
|
|
1274
1659
|
const config = resolveMediaEvictionConfig(this.mediaEviction);
|
|
1275
1660
|
if (!config) return null;
|
|
1276
1661
|
this._mediaEvictionRunning = true;
|
|
1277
|
-
|
|
1662
|
+
this._mediaEvictionAppendsDuringPass = 0;
|
|
1663
|
+
const totals = {
|
|
1664
|
+
messages: 0,
|
|
1665
|
+
parts: 0,
|
|
1666
|
+
bytes: 0,
|
|
1667
|
+
backlogRemains: false
|
|
1668
|
+
};
|
|
1278
1669
|
try {
|
|
1279
|
-
const
|
|
1280
|
-
if (!
|
|
1670
|
+
const writeFileBytes = this.workspace.writeFileBytes?.bind(this.workspace);
|
|
1671
|
+
if (!writeFileBytes) {
|
|
1281
1672
|
if (!this._warnedEvictionUnsupported) {
|
|
1282
1673
|
this._warnedEvictionUnsupported = true;
|
|
1283
|
-
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.");
|
|
1284
1675
|
}
|
|
1285
1676
|
return null;
|
|
1286
1677
|
}
|
|
1678
|
+
const stats = await this.session.getHistoryRowStats();
|
|
1287
1679
|
const keepRecent = Math.max(config.keepRecentMessages, MODEL_RECENT_WINDOW);
|
|
1288
1680
|
const aged = stats.slice(0, Math.max(0, stats.length - keepRecent));
|
|
1289
1681
|
let processed = 0;
|
|
1290
|
-
const totals = {
|
|
1291
|
-
messages: 0,
|
|
1292
|
-
parts: 0,
|
|
1293
|
-
bytes: 0,
|
|
1294
|
-
externalizedBytes: 0
|
|
1295
|
-
};
|
|
1296
1682
|
for (const row of aged) {
|
|
1297
1683
|
if (row.bytes < config.minPartBytes) continue;
|
|
1298
1684
|
if (processed >= config.maxRowsPerPass) {
|
|
1299
|
-
backlogRemains = true;
|
|
1685
|
+
totals.backlogRemains = true;
|
|
1300
1686
|
break;
|
|
1301
1687
|
}
|
|
1302
1688
|
processed++;
|
|
1303
1689
|
const message = await this.session.getMessage(row.id);
|
|
1304
1690
|
if (!message) continue;
|
|
1305
|
-
const result =
|
|
1691
|
+
const result = await evictMediaFromMessage(message, {
|
|
1306
1692
|
minPartBytes: config.minPartBytes,
|
|
1307
|
-
|
|
1308
|
-
|
|
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
|
+
}
|
|
1309
1698
|
});
|
|
1310
1699
|
if (!result.changed) continue;
|
|
1311
|
-
|
|
1312
|
-
await this.workspace.writeFile(blob.path, blob.data);
|
|
1313
|
-
totals.externalizedBytes += blob.data.length;
|
|
1314
|
-
}
|
|
1315
|
-
await this.session.internal_rewriteMessage(sanitizeMessage(result.message));
|
|
1700
|
+
await this._updateMessageInHistory(result.message);
|
|
1316
1701
|
totals.messages++;
|
|
1317
1702
|
totals.parts += result.parts;
|
|
1318
1703
|
totals.bytes += result.bytes;
|
|
1319
1704
|
}
|
|
1320
|
-
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
|
+
};
|
|
1321
1717
|
return totals;
|
|
1322
1718
|
} catch (error) {
|
|
1323
1719
|
console.error("[Think] media eviction pass failed; a later pass will retry.", error);
|
|
1324
1720
|
return null;
|
|
1325
1721
|
} finally {
|
|
1326
1722
|
this._mediaEvictionRunning = false;
|
|
1327
|
-
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
|
+
}
|
|
1328
1728
|
}
|
|
1329
1729
|
}
|
|
1330
1730
|
/** Replace the live cache with a durable storage snapshot. */
|
|
@@ -1332,23 +1732,35 @@ var Think = class Think extends Agent {
|
|
|
1332
1732
|
this._cachedMessages = messages;
|
|
1333
1733
|
return this._cachedMessages;
|
|
1334
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
|
+
}
|
|
1335
1741
|
/**
|
|
1336
1742
|
* Refresh the live cache from durable storage at a safe boundary.
|
|
1337
1743
|
*
|
|
1338
1744
|
* Bounded by `hydrationByteBudget`: oversized transcripts hydrate as a
|
|
1339
1745
|
* recent window instead of exhausting the isolate's memory (#1710). The
|
|
1340
|
-
*
|
|
1341
|
-
*
|
|
1342
|
-
*
|
|
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.
|
|
1343
1750
|
*/
|
|
1344
1751
|
async _syncMessages() {
|
|
1752
|
+
this._cacheCoversActivePath = false;
|
|
1753
|
+
this._cachedBytesSinceSync = 0;
|
|
1345
1754
|
const budget = this.hydrationByteBudget;
|
|
1346
1755
|
if (!Number.isFinite(budget) || budget <= 0) {
|
|
1347
1756
|
this._lastHydration = null;
|
|
1348
1757
|
this._lastWindowedEmit = null;
|
|
1349
|
-
|
|
1758
|
+
const full = this._replaceCachedMessages(await this._readMessagesFromStorage());
|
|
1759
|
+
this._cacheCoversActivePath = true;
|
|
1760
|
+
this._scheduleMediaEvictionPass();
|
|
1761
|
+
return full;
|
|
1350
1762
|
}
|
|
1351
|
-
const recent = await this.session.getRecentHistory(budget
|
|
1763
|
+
const recent = await this.session.getRecentHistory(budget);
|
|
1352
1764
|
this._lastHydration = {
|
|
1353
1765
|
truncated: recent.truncated,
|
|
1354
1766
|
totalContentBytes: recent.totalContentBytes,
|
|
@@ -1371,7 +1783,10 @@ var Think = class Think extends Agent {
|
|
|
1371
1783
|
});
|
|
1372
1784
|
}
|
|
1373
1785
|
} else this._lastWindowedEmit = null;
|
|
1374
|
-
|
|
1786
|
+
const hydrated = this._replaceCachedMessages(recent.messages);
|
|
1787
|
+
this._cacheCoversActivePath = !recent.truncated;
|
|
1788
|
+
this._scheduleMediaEvictionPass();
|
|
1789
|
+
return hydrated;
|
|
1375
1790
|
}
|
|
1376
1791
|
/** Patch or append one message in the live cache after a durable write. */
|
|
1377
1792
|
_upsertCachedMessage(message) {
|
|
@@ -1379,49 +1794,50 @@ var Think = class Think extends Agent {
|
|
|
1379
1794
|
if (index === -1) this._cachedMessages.push(message);
|
|
1380
1795
|
else this._cachedMessages[index] = message;
|
|
1381
1796
|
}
|
|
1382
|
-
/**
|
|
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
|
+
*/
|
|
1383
1804
|
_patchCachedMessage(message) {
|
|
1384
1805
|
const index = this._cachedMessages.findIndex((m) => m.id === message.id);
|
|
1385
|
-
if (index
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
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
|
+
}
|
|
1390
1813
|
}
|
|
1391
1814
|
async _appendMessageToHistory(message, parentId) {
|
|
1392
|
-
|
|
1393
|
-
await this.session.appendMessage(safe, parentId);
|
|
1394
|
-
return safe;
|
|
1815
|
+
return (await this.session.appendMessage(message, { parentId })).message;
|
|
1395
1816
|
}
|
|
1396
1817
|
async _updateMessageInHistory(message) {
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
}
|
|
1407
|
-
/**
|
|
1408
|
-
* The orphan-persist store adapter — orphan-persist steps **(c)/(d)** route
|
|
1409
|
-
* their write through this shared `OrphanPersistStore` seam (the
|
|
1410
|
-
* `SessionProvider` write-subset). Delegates to `this.session` with `_rowSafe`
|
|
1411
|
-
* applied at the write boundary (sanitize + row-size cap), exactly as Think's
|
|
1412
|
-
* other Session call sites do. The `SessionMessage → UIMessage` read cast is
|
|
1413
|
-
* confined here, matching those call sites.
|
|
1414
|
-
* @internal
|
|
1415
|
-
*/
|
|
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. */
|
|
1416
1827
|
_orphanStore() {
|
|
1417
1828
|
return {
|
|
1418
1829
|
getMessage: async (id) => await this.session.getMessage(id),
|
|
1419
|
-
appendMessage: (message, parentId) =>
|
|
1420
|
-
|
|
1830
|
+
appendMessage: async (message, parentId) => {
|
|
1831
|
+
await this.session.appendMessage(message, { parentId });
|
|
1832
|
+
},
|
|
1833
|
+
updateMessage: async (message) => {
|
|
1834
|
+
await this.session.updateMessage(message);
|
|
1835
|
+
}
|
|
1421
1836
|
};
|
|
1422
1837
|
}
|
|
1423
1838
|
async _clearHistory() {
|
|
1424
1839
|
await this.session.clearMessages();
|
|
1840
|
+
await _classPrivateFieldGet2(_contextBlocks, this)?.refreshSystemPrompt();
|
|
1425
1841
|
await this._clearChatTerminal();
|
|
1426
1842
|
}
|
|
1427
1843
|
/** Append a message while keeping Think's live message cache coherent. */
|
|
@@ -1556,19 +1972,25 @@ var Think = class Think extends Agent {
|
|
|
1556
1972
|
return null;
|
|
1557
1973
|
}
|
|
1558
1974
|
_migrateLegacyConfigToThinkTable() {
|
|
1559
|
-
const
|
|
1560
|
-
|
|
1561
|
-
|
|
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;
|
|
1562
1980
|
for (const key of Think.CONFIG_KEYS) {
|
|
1563
|
-
const value = this.sql`
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
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;
|
|
1567
1988
|
if (value !== void 0) this.sql`
|
|
1568
1989
|
INSERT OR IGNORE INTO think_config (key, value)
|
|
1569
1990
|
VALUES (${key}, ${value})
|
|
1570
1991
|
`;
|
|
1571
1992
|
}
|
|
1993
|
+
this.ctx.storage.sql.exec(`DROP TABLE ${source}`);
|
|
1572
1994
|
}
|
|
1573
1995
|
_ensureConfigTable() {
|
|
1574
1996
|
if (_classPrivateFieldGet2(_configTableReady, this)) return;
|
|
@@ -1584,24 +2006,30 @@ var Think = class Think extends Agent {
|
|
|
1584
2006
|
}
|
|
1585
2007
|
_configSet(key, value) {
|
|
1586
2008
|
this._ensureConfigTable();
|
|
2009
|
+
if (_classPrivateFieldGet2(_configMemo, this).get(key) === value) return;
|
|
1587
2010
|
this.sql`
|
|
1588
2011
|
INSERT OR REPLACE INTO think_config (key, value)
|
|
1589
2012
|
VALUES (${key}, ${value})
|
|
1590
2013
|
`;
|
|
2014
|
+
_classPrivateFieldGet2(_configMemo, this).set(key, value);
|
|
1591
2015
|
}
|
|
1592
2016
|
_configGet(key) {
|
|
1593
2017
|
this._ensureConfigTable();
|
|
1594
|
-
|
|
2018
|
+
const value = this.sql`
|
|
1595
2019
|
SELECT value FROM think_config
|
|
1596
2020
|
WHERE key = ${key}
|
|
1597
2021
|
`[0]?.value;
|
|
2022
|
+
_classPrivateFieldGet2(_configMemo, this).set(key, value);
|
|
2023
|
+
return value;
|
|
1598
2024
|
}
|
|
1599
2025
|
_configDelete(key) {
|
|
1600
2026
|
this._ensureConfigTable();
|
|
2027
|
+
if (_classPrivateFieldGet2(_configMemo, this).has(key) && _classPrivateFieldGet2(_configMemo, this).get(key) === void 0) return;
|
|
1601
2028
|
this.sql`
|
|
1602
2029
|
DELETE FROM think_config
|
|
1603
2030
|
WHERE key = ${key}
|
|
1604
2031
|
`;
|
|
2032
|
+
_classPrivateFieldGet2(_configMemo, this).set(key, void 0);
|
|
1605
2033
|
}
|
|
1606
2034
|
/**
|
|
1607
2035
|
* Return the model to use for inference. Must be overridden by subclasses.
|
|
@@ -1672,9 +2100,8 @@ var Think = class Think extends Agent {
|
|
|
1672
2100
|
}
|
|
1673
2101
|
/**
|
|
1674
2102
|
* Return the fallback system prompt for the assistant.
|
|
1675
|
-
* Ignored when
|
|
1676
|
-
*
|
|
1677
|
-
* 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.
|
|
1678
2105
|
*/
|
|
1679
2106
|
getSystemPrompt() {
|
|
1680
2107
|
return [
|
|
@@ -1928,6 +2355,117 @@ var Think = class Think extends Agent {
|
|
|
1928
2355
|
* Task-local timezone declarations take precedence.
|
|
1929
2356
|
*/
|
|
1930
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
|
+
}
|
|
1931
2469
|
async _runChatRecoveryFiber(requestId, continuation, fn) {
|
|
1932
2470
|
const snapshot = createChatFiberSnapshot({
|
|
1933
2471
|
kind: "think-chat-turn",
|
|
@@ -1938,10 +2476,43 @@ var Think = class Think extends Agent {
|
|
|
1938
2476
|
lastBody: this._lastBody,
|
|
1939
2477
|
lastClientTools: this._lastClientTools
|
|
1940
2478
|
});
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
|
|
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;
|
|
1944
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
|
+
}
|
|
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
|
+
}
|
|
1945
2516
|
}
|
|
1946
2517
|
_systemPromptForTurn(baseSystem, tools) {
|
|
1947
2518
|
if (baseSystem.includes("You are running inside a Think agent.")) return baseSystem;
|
|
@@ -1959,7 +2530,6 @@ var Think = class Think extends Agent {
|
|
|
1959
2530
|
"grep",
|
|
1960
2531
|
"delete"
|
|
1961
2532
|
].some((toolName) => toolNames.has(toolName));
|
|
1962
|
-
const hasContextTools = toolNames.has("load_context") || toolNames.has("unload_context");
|
|
1963
2533
|
const hasExtensionTools = toolNames.has("load_extension") || toolNames.has("list_extensions");
|
|
1964
2534
|
const hasExecuteTool = toolNames.has("execute");
|
|
1965
2535
|
const hasFetchTools = [...toolNames].some((name) => name.startsWith("fetch_"));
|
|
@@ -1973,7 +2543,6 @@ var Think = class Think extends Agent {
|
|
|
1973
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.");
|
|
1974
2544
|
lines.push("- Some tools may call server code, browser/client code, MCP servers, extensions, or delegated agents. Use them according to their descriptions.");
|
|
1975
2545
|
}
|
|
1976
|
-
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.");
|
|
1977
2546
|
if (hasExtensionTools) lines.push("- If extension tools are available, use them only when loading or inspecting extensions directly helps with the task.");
|
|
1978
2547
|
if (hasExecuteTool) lines.push("- If sandboxed execution is available, prefer it for safe, bounded checks or coordinated multi-step operations.");
|
|
1979
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.");
|
|
@@ -1997,15 +2566,20 @@ var Think = class Think extends Agent {
|
|
|
1997
2566
|
return Math.max(1, this.contextOverflow?.proactive?.maxCompactions ?? 1);
|
|
1998
2567
|
}
|
|
1999
2568
|
/**
|
|
2000
|
-
* Configure
|
|
2001
|
-
*
|
|
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.
|
|
2002
2576
|
*
|
|
2003
2577
|
* @example
|
|
2004
2578
|
* ```typescript
|
|
2005
2579
|
* configureSession(session: Session) {
|
|
2006
2580
|
* return session
|
|
2007
|
-
* .
|
|
2008
|
-
* .
|
|
2581
|
+
* .onCompaction(createCompactFunction({ summarize }))
|
|
2582
|
+
* .compactAfter(80_000);
|
|
2009
2583
|
* }
|
|
2010
2584
|
* ```
|
|
2011
2585
|
*/
|
|
@@ -2013,6 +2587,26 @@ var Think = class Think extends Agent {
|
|
|
2013
2587
|
return session;
|
|
2014
2588
|
}
|
|
2015
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
|
+
/**
|
|
2016
2610
|
* Return Agent Skills sources for this Think agent.
|
|
2017
2611
|
*
|
|
2018
2612
|
* Bundled skills are typically imported with the Agents Vite plugin:
|
|
@@ -2032,7 +2626,7 @@ var Think = class Think extends Agent {
|
|
|
2032
2626
|
const sources = await this.getSkills();
|
|
2033
2627
|
if (sources.length === 0) return;
|
|
2034
2628
|
if (this.getSystemPrompt !== Think.prototype.getSystemPrompt) {
|
|
2035
|
-
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.";
|
|
2036
2630
|
if (!this._loggedSkillWarnings.has(warning)) {
|
|
2037
2631
|
this._loggedSkillWarnings.add(warning);
|
|
2038
2632
|
console.warn(`[think] ${warning}`);
|
|
@@ -2042,18 +2636,49 @@ var Think = class Think extends Agent {
|
|
|
2042
2636
|
await registry.load();
|
|
2043
2637
|
this._logSkillWarnings(registry);
|
|
2044
2638
|
this._skillRegistry = registry;
|
|
2045
|
-
await this.
|
|
2639
|
+
await this._configureSkillWorkspace(registry);
|
|
2640
|
+
await this.context.addBlock({
|
|
2641
|
+
label: registry.contextLabel,
|
|
2046
2642
|
description: "Think skills: available skill catalog",
|
|
2047
2643
|
provider: { get: () => registry.systemPrompt() }
|
|
2048
2644
|
});
|
|
2049
|
-
if (this._configGet("skillsFingerprint") !== registry.fingerprint) {
|
|
2050
|
-
await this.
|
|
2645
|
+
if ((this._skillsFingerprint ??= this._configGet("skillsFingerprint") ?? null) !== registry.fingerprint) {
|
|
2646
|
+
await this.context.refreshSystemPrompt();
|
|
2051
2647
|
this._configSet("skillsFingerprint", registry.fingerprint);
|
|
2648
|
+
this._skillsFingerprint = registry.fingerprint;
|
|
2052
2649
|
}
|
|
2053
2650
|
} catch (error) {
|
|
2054
2651
|
console.warn(`[think] Failed to initialize skills; continuing without them: ${error instanceof Error ? error.message : String(error)}`);
|
|
2055
2652
|
}
|
|
2056
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
|
+
}
|
|
2057
2682
|
/**
|
|
2058
2683
|
* Log registry diagnostics (duplicate names, sources that failed to list),
|
|
2059
2684
|
* deduped by message so a new collision after a deploy still surfaces while
|
|
@@ -2080,9 +2705,11 @@ var Think = class Think extends Agent {
|
|
|
2080
2705
|
try {
|
|
2081
2706
|
await this._skillRegistry.refresh();
|
|
2082
2707
|
this._logSkillWarnings(this._skillRegistry);
|
|
2083
|
-
|
|
2084
|
-
|
|
2708
|
+
await this._configureSkillWorkspace(this._skillRegistry);
|
|
2709
|
+
if ((this._skillsFingerprint ??= this._configGet("skillsFingerprint") ?? null) !== this._skillRegistry.fingerprint) {
|
|
2710
|
+
await this.context.refreshSystemPrompt();
|
|
2085
2711
|
this._configSet("skillsFingerprint", this._skillRegistry.fingerprint);
|
|
2712
|
+
this._skillsFingerprint = this._skillRegistry.fingerprint;
|
|
2086
2713
|
}
|
|
2087
2714
|
} catch (error) {
|
|
2088
2715
|
console.warn(`[think] Failed to refresh skills; using last known catalog: ${error instanceof Error ? error.message : String(error)}`);
|
|
@@ -2441,15 +3068,16 @@ var Think = class Think extends Agent {
|
|
|
2441
3068
|
const prefix = sanitizeName(ext.name);
|
|
2442
3069
|
for (const ctxDef of manifest.context) {
|
|
2443
3070
|
const namespacedLabel = `${prefix}_${ctxDef.label}`;
|
|
2444
|
-
await this.
|
|
3071
|
+
await this.context.addBlock({
|
|
3072
|
+
label: namespacedLabel,
|
|
2445
3073
|
description: ctxDef.description,
|
|
2446
3074
|
maxTokens: ctxDef.maxTokens
|
|
2447
3075
|
});
|
|
2448
3076
|
}
|
|
2449
3077
|
}
|
|
2450
3078
|
this.extensionManager.onUnload(async (_name, contextLabels) => {
|
|
2451
|
-
for (const label of contextLabels) this.
|
|
2452
|
-
await this.
|
|
3079
|
+
for (const label of contextLabels) this.context.removeBlock(label);
|
|
3080
|
+
await this.context.refreshSystemPrompt();
|
|
2453
3081
|
});
|
|
2454
3082
|
}
|
|
2455
3083
|
/**
|
|
@@ -2460,7 +3088,7 @@ var Think = class Think extends Agent {
|
|
|
2460
3088
|
* head through the exact same pipeline.
|
|
2461
3089
|
*/
|
|
2462
3090
|
async _assembleModelMessages(tools) {
|
|
2463
|
-
const truncated = truncateOlderMessages(await this._repairTranscriptForProvider(this.messages));
|
|
3091
|
+
const truncated = truncateOlderMessages((await this._repairTranscriptForProvider(this.messages)).map(toProviderSafeExecutionOutcomeMessage));
|
|
2464
3092
|
const incompleteAfterRepair = this._incompleteToolCallIds(truncated);
|
|
2465
3093
|
if (incompleteAfterRepair.length > 0) {
|
|
2466
3094
|
console.warn(`[Think] ${incompleteAfterRepair.length} incomplete tool call(s) survived transcript repair and will be dropped by ignoreIncompleteToolCalls: ${incompleteAfterRepair.join(", ")}. This indicates a gap in _repairToolTranscriptParts.`);
|
|
@@ -2637,7 +3265,7 @@ var Think = class Think extends Agent {
|
|
|
2637
3265
|
const actionTools = await this._compileActionTools();
|
|
2638
3266
|
const extensionTools = this.extensionManager?.getTools() ?? {};
|
|
2639
3267
|
await this._refreshSkillsIfChanged();
|
|
2640
|
-
const contextTools = await this.
|
|
3268
|
+
const contextTools = await this.context.tools();
|
|
2641
3269
|
const skillTools = this._skillRegistry?.tools() ?? {};
|
|
2642
3270
|
const clientToolSet = createToolsFromClientSchemas(input.clientTools, input.clientToolExecutor ? { execute: input.clientToolExecutor } : void 0);
|
|
2643
3271
|
let tools = {
|
|
@@ -2655,7 +3283,7 @@ var Think = class Think extends Agent {
|
|
|
2655
3283
|
const channelDefinition = channelContext ? this._channels?.get(channelContext.channelId) : void 0;
|
|
2656
3284
|
if (channelDefinition?.tools) tools = channelDefinition.tools(tools);
|
|
2657
3285
|
const channelInstructions = channelDefinition?.instructions && channelContext ? typeof channelDefinition.instructions === "function" ? await channelDefinition.instructions(channelContext) : channelDefinition.instructions : void 0;
|
|
2658
|
-
const rawBaseSystem = await this.
|
|
3286
|
+
const rawBaseSystem = await this.context.freezeSystemPrompt() || this.getSystemPrompt();
|
|
2659
3287
|
const baseSystem = channelInstructions ? `${channelInstructions}\n\n${rawBaseSystem}` : rawBaseSystem;
|
|
2660
3288
|
const system = this._systemPromptForTurn(baseSystem, tools);
|
|
2661
3289
|
const messages = await this._assembleModelMessages(tools);
|
|
@@ -2748,7 +3376,10 @@ var Think = class Think extends Agent {
|
|
|
2748
3376
|
abortSignal: input.signal,
|
|
2749
3377
|
prepareStep: (async (event) => {
|
|
2750
3378
|
const guarded = await this._maybeProactiveContextCompact(event);
|
|
2751
|
-
const result = await this.beforeStep(
|
|
3379
|
+
const result = await this.beforeStep(guarded ? {
|
|
3380
|
+
...event,
|
|
3381
|
+
messages: guarded
|
|
3382
|
+
} : event);
|
|
2752
3383
|
const base = result == null ? {} : result;
|
|
2753
3384
|
const baseMessages = base.messages;
|
|
2754
3385
|
const withMessages = guarded && baseMessages === void 0 ? {
|
|
@@ -3498,10 +4129,10 @@ var Think = class Think extends Agent {
|
|
|
3498
4129
|
}));
|
|
3499
4130
|
}
|
|
3500
4131
|
async _hostGetContext(label) {
|
|
3501
|
-
return this.
|
|
4132
|
+
return this.context.getBlock(label)?.content ?? null;
|
|
3502
4133
|
}
|
|
3503
4134
|
async _hostSetContext(label, content) {
|
|
3504
|
-
await this.
|
|
4135
|
+
await this.context.setBlock(label, content);
|
|
3505
4136
|
}
|
|
3506
4137
|
async _hostGetMessages(limit) {
|
|
3507
4138
|
const history = this.messages;
|
|
@@ -3680,8 +4311,7 @@ var Think = class Think extends Agent {
|
|
|
3680
4311
|
return;
|
|
3681
4312
|
}
|
|
3682
4313
|
};
|
|
3683
|
-
|
|
3684
|
-
else await chatBody();
|
|
4314
|
+
await this._runChatRecoveryFiber(requestId, false, chatBody);
|
|
3685
4315
|
}
|
|
3686
4316
|
});
|
|
3687
4317
|
} finally {
|
|
@@ -3824,6 +4454,7 @@ var Think = class Think extends Agent {
|
|
|
3824
4454
|
this._broadcast({ type: MSG_CHAT_CLEAR });
|
|
3825
4455
|
}
|
|
3826
4456
|
_ensureAgentToolChildRunTable() {
|
|
4457
|
+
if (_classPrivateFieldGet2(_agentToolChildRunTableReady, this)) return;
|
|
3827
4458
|
this.sql`
|
|
3828
4459
|
CREATE TABLE IF NOT EXISTS cf_agent_tool_child_runs (
|
|
3829
4460
|
run_id TEXT PRIMARY KEY,
|
|
@@ -3850,6 +4481,7 @@ var Think = class Think extends Agent {
|
|
|
3850
4481
|
PRIMARY KEY (run_id, sequence)
|
|
3851
4482
|
)
|
|
3852
4483
|
`;
|
|
4484
|
+
_classPrivateFieldSet2(_agentToolChildRunTableReady, this, true);
|
|
3853
4485
|
}
|
|
3854
4486
|
_persistAgentToolMilestone(runId, name, data, at) {
|
|
3855
4487
|
this._ensureAgentToolChildRunTable();
|
|
@@ -5150,7 +5782,7 @@ var Think = class Think extends Agent {
|
|
|
5150
5782
|
return parsed;
|
|
5151
5783
|
}
|
|
5152
5784
|
_serializeSubmissionMessages(messages) {
|
|
5153
|
-
return JSON.stringify(messages.map((message) =>
|
|
5785
|
+
return JSON.stringify(messages.map((message) => enforceRowSizeLimit(sanitizeMessage(message), { warn: (warning) => console.warn(`[Think] ${warning}`) })));
|
|
5154
5786
|
}
|
|
5155
5787
|
_serializeMetadata(metadata) {
|
|
5156
5788
|
return metadata === void 0 ? null : JSON.stringify(metadata);
|
|
@@ -5277,7 +5909,7 @@ var Think = class Think extends Agent {
|
|
|
5277
5909
|
if (!this._hasPendingWorkflowNotifications()) return;
|
|
5278
5910
|
this.keepAliveWhile(() => this._drainWorkflowNotifications()).catch((error) => {
|
|
5279
5911
|
console.error("[Think] Failed to drain workflow notifications", error);
|
|
5280
|
-
this.
|
|
5912
|
+
this._rearmWorkflowNotificationAlarm();
|
|
5281
5913
|
});
|
|
5282
5914
|
}
|
|
5283
5915
|
_hasPendingWorkflowNotifications() {
|
|
@@ -5330,22 +5962,48 @@ var Think = class Think extends Agent {
|
|
|
5330
5962
|
} finally {
|
|
5331
5963
|
this._drainingWorkflowNotifications = false;
|
|
5332
5964
|
}
|
|
5333
|
-
await this.
|
|
5965
|
+
await this._rearmWorkflowNotificationAlarm();
|
|
5334
5966
|
}
|
|
5335
|
-
|
|
5967
|
+
_nextWorkflowNotificationAlarm() {
|
|
5336
5968
|
this._ensureWorkflowNotificationTable();
|
|
5337
5969
|
const pending = this.sql`
|
|
5338
|
-
SELECT attempts
|
|
5970
|
+
SELECT attempts, updated_at
|
|
5339
5971
|
FROM cf_think_workflow_notifications
|
|
5340
5972
|
WHERE delivered_at IS NULL
|
|
5341
5973
|
ORDER BY created_at ASC, notification_id ASC
|
|
5342
5974
|
LIMIT 1
|
|
5343
5975
|
`;
|
|
5344
|
-
if (!pending[0]) return;
|
|
5976
|
+
if (!pending[0]) return null;
|
|
5345
5977
|
const delayMs = Math.min(300 * 1e3, 1e3 * 2 ** Math.min(pending[0].attempts, 8));
|
|
5346
|
-
|
|
5347
|
-
|
|
5348
|
-
|
|
5978
|
+
return Math.max(pending[0].updated_at + delayMs, Date.now() + 1);
|
|
5979
|
+
}
|
|
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);
|
|
5991
|
+
}
|
|
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
|
+
});
|
|
5349
6007
|
}
|
|
5350
6008
|
async inspectSubmission(submissionId) {
|
|
5351
6009
|
const row = this._readSubmission(submissionId);
|
|
@@ -5684,7 +6342,7 @@ var Think = class Think extends Agent {
|
|
|
5684
6342
|
if (updated?.status === "pending") await this._emitSubmissionStatus(updated);
|
|
5685
6343
|
continue;
|
|
5686
6344
|
}
|
|
5687
|
-
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;
|
|
5688
6346
|
this.sql`
|
|
5689
6347
|
UPDATE cf_think_submissions
|
|
5690
6348
|
SET status = 'error',
|
|
@@ -5705,18 +6363,28 @@ var Think = class Think extends Agent {
|
|
|
5705
6363
|
if (applied === 0) return "none";
|
|
5706
6364
|
return applied === messages.length ? "all" : "partial";
|
|
5707
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
|
+
}
|
|
5708
6380
|
_hasRecoverableChatTurn(requestId) {
|
|
5709
6381
|
if (this.sql`
|
|
5710
6382
|
SELECT id FROM cf_agents_runs
|
|
5711
6383
|
WHERE name = ${this.constructor.CHAT_FIBER_NAME + ":" + requestId}
|
|
5712
6384
|
LIMIT 1
|
|
5713
6385
|
`.length > 0) return true;
|
|
5714
|
-
|
|
5715
|
-
|
|
5716
|
-
WHERE request_id = ${requestId}
|
|
5717
|
-
AND status = 'streaming'
|
|
5718
|
-
LIMIT 1
|
|
5719
|
-
`.length > 0;
|
|
6386
|
+
if (this._recoverableChatTurnTaskCreatedAt(requestId) !== null) return true;
|
|
6387
|
+
return this._resumableStream.latestActiveStreamInfoForRequest(requestId) !== null;
|
|
5720
6388
|
}
|
|
5721
6389
|
_hasFreshRecoverableSubmissionEvidence(row) {
|
|
5722
6390
|
if (!row.request_id) return false;
|
|
@@ -5727,27 +6395,25 @@ var Think = class Think extends Agent {
|
|
|
5727
6395
|
LIMIT 1
|
|
5728
6396
|
`;
|
|
5729
6397
|
if (fiberRows[0] && fiberRows[0].created_at >= cutoff) return true;
|
|
5730
|
-
const
|
|
5731
|
-
|
|
5732
|
-
|
|
5733
|
-
|
|
5734
|
-
|
|
5735
|
-
|
|
5736
|
-
|
|
5737
|
-
|
|
5738
|
-
|
|
5739
|
-
|
|
5740
|
-
|
|
5741
|
-
|
|
5742
|
-
|
|
5743
|
-
|
|
5744
|
-
|
|
5745
|
-
|
|
5746
|
-
|
|
5747
|
-
|
|
5748
|
-
|
|
5749
|
-
return false;
|
|
5750
|
-
}
|
|
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;
|
|
5751
6417
|
});
|
|
5752
6418
|
}
|
|
5753
6419
|
/**
|
|
@@ -5930,8 +6596,7 @@ var Think = class Think extends Agent {
|
|
|
5930
6596
|
return;
|
|
5931
6597
|
}
|
|
5932
6598
|
};
|
|
5933
|
-
|
|
5934
|
-
else await programmaticBody();
|
|
6599
|
+
await this._runChatRecoveryFiber(requestId, false, programmaticBody);
|
|
5935
6600
|
} finally {
|
|
5936
6601
|
if (abortSignal?.aborted) wasAborted = true;
|
|
5937
6602
|
detachExternal();
|
|
@@ -6015,8 +6680,7 @@ var Think = class Think extends Agent {
|
|
|
6015
6680
|
error = streamResult.error;
|
|
6016
6681
|
}
|
|
6017
6682
|
};
|
|
6018
|
-
|
|
6019
|
-
else await continueTurnBody();
|
|
6683
|
+
await this._runChatRecoveryFiber(requestId, true, continueTurnBody);
|
|
6020
6684
|
} finally {
|
|
6021
6685
|
if (abortSignal?.aborted) wasAborted = true;
|
|
6022
6686
|
detachExternal();
|
|
@@ -6080,8 +6744,7 @@ var Think = class Think extends Agent {
|
|
|
6080
6744
|
error = streamResult.error;
|
|
6081
6745
|
}
|
|
6082
6746
|
};
|
|
6083
|
-
|
|
6084
|
-
else await retryTurnBody();
|
|
6747
|
+
await this._runChatRecoveryFiber(requestId, false, retryTurnBody);
|
|
6085
6748
|
} finally {
|
|
6086
6749
|
if (abortSignal?.aborted) wasAborted = true;
|
|
6087
6750
|
detachExternal();
|
|
@@ -6251,31 +6914,16 @@ var Think = class Think extends Agent {
|
|
|
6251
6914
|
});
|
|
6252
6915
|
const clientToolsForTurn = this._lastClientTools;
|
|
6253
6916
|
const bodyForTurn = this._lastBody;
|
|
6254
|
-
const
|
|
6255
|
-
|
|
6256
|
-
|
|
6257
|
-
|
|
6258
|
-
}
|
|
6259
|
-
|
|
6260
|
-
let branchParentId;
|
|
6261
|
-
if (isRegeneration && reconciled.length > 0) branchParentId = reconciled[reconciled.length - 1].id;
|
|
6262
|
-
if (!await withAgentSpan(this, "persist_incoming_messages", "interaction", {
|
|
6263
|
-
"cloudflare.agents.component": "think",
|
|
6264
|
-
"cloudflare.agents.turn.request_id": requestId,
|
|
6265
|
-
"cloudflare.agents.turn.trigger": "ws-chat"
|
|
6266
|
-
}, async () => {
|
|
6267
|
-
if (this._turnQueue.generation !== epoch) return false;
|
|
6268
|
-
for (const msg of reconciled) {
|
|
6269
|
-
if (this._turnQueue.generation !== epoch) return false;
|
|
6270
|
-
await this._persistIncomingMessage(msg, serverMessages);
|
|
6271
|
-
}
|
|
6272
|
-
if (this._turnQueue.generation !== epoch) return false;
|
|
6273
|
-
await this._syncMessages();
|
|
6274
|
-
return true;
|
|
6275
|
-
})) {
|
|
6917
|
+
const reconciledTurn = await this._reconcileAndPersistIncoming(incomingMessages, {
|
|
6918
|
+
requestId,
|
|
6919
|
+
isRegeneration,
|
|
6920
|
+
isCurrent: () => this._turnQueue.generation === epoch
|
|
6921
|
+
});
|
|
6922
|
+
if (!reconciledTurn) {
|
|
6276
6923
|
this._completeSkippedRequest(connection, requestId);
|
|
6277
6924
|
return;
|
|
6278
6925
|
}
|
|
6926
|
+
const { branchParentId } = reconciledTurn;
|
|
6279
6927
|
this._broadcastMessages([connection.id]);
|
|
6280
6928
|
messagesPersisted = true;
|
|
6281
6929
|
failureStage = "turn";
|
|
@@ -6369,8 +7017,7 @@ var Think = class Think extends Agent {
|
|
|
6369
7017
|
return;
|
|
6370
7018
|
}
|
|
6371
7019
|
};
|
|
6372
|
-
|
|
6373
|
-
else await chatTurnBody();
|
|
7020
|
+
await this._runChatRecoveryFiber(requestId, false, chatTurnBody);
|
|
6374
7021
|
}
|
|
6375
7022
|
})).status === "stale") this._broadcastChat({
|
|
6376
7023
|
type: MSG_CHAT_RESPONSE,
|
|
@@ -6704,7 +7351,7 @@ var Think = class Think extends Agent {
|
|
|
6704
7351
|
};
|
|
6705
7352
|
}
|
|
6706
7353
|
if (streamError) this._errorResumableStream(streamId);
|
|
6707
|
-
else this.
|
|
7354
|
+
else this._finishResumableStream(streamId);
|
|
6708
7355
|
streamFinalized = true;
|
|
6709
7356
|
this._broadcastChat({
|
|
6710
7357
|
type: MSG_CHAT_RESPONSE,
|
|
@@ -6715,9 +7362,10 @@ var Think = class Think extends Agent {
|
|
|
6715
7362
|
doneSent = true;
|
|
6716
7363
|
assistantMsg = accumulator.toMessage();
|
|
6717
7364
|
if (accumulator.parts.length > 0) {
|
|
6718
|
-
await this.
|
|
7365
|
+
await this._persistAssistantMessageWithCutover(streamId, assistantMsg, void 0, { discard: this._discardStreamAtCutover(requestId) });
|
|
6719
7366
|
this._broadcastMessages();
|
|
6720
7367
|
}
|
|
7368
|
+
this._resumableStream.finalizePending();
|
|
6721
7369
|
if (streamError) {
|
|
6722
7370
|
await this._fireResponseHook({
|
|
6723
7371
|
message: assistantMsg,
|
|
@@ -6861,12 +7509,6 @@ var Think = class Think extends Agent {
|
|
|
6861
7509
|
state.chunksSinceFlush = 0;
|
|
6862
7510
|
state.hasFlushedContent = true;
|
|
6863
7511
|
}
|
|
6864
|
-
if (shouldCreditStreamProgress({
|
|
6865
|
-
codec: aiSdkRecoveryCodec,
|
|
6866
|
-
type: chunk.type,
|
|
6867
|
-
throttle: this._streamProgressCredit,
|
|
6868
|
-
now: Date.now()
|
|
6869
|
-
})) await this._bumpChatRecoveryProgress();
|
|
6870
7512
|
}
|
|
6871
7513
|
async _streamResult(requestId, result, abortSignal, options) {
|
|
6872
7514
|
const clearGen = this._turnQueue.generation;
|
|
@@ -6959,7 +7601,7 @@ var Think = class Think extends Agent {
|
|
|
6959
7601
|
return { status: "aborted" };
|
|
6960
7602
|
}
|
|
6961
7603
|
if (streamError) this._errorResumableStream(streamId);
|
|
6962
|
-
else this.
|
|
7604
|
+
else this._finishResumableStream(streamId);
|
|
6963
7605
|
this._pendingResumeConnections.clear();
|
|
6964
7606
|
this._broadcastChat({
|
|
6965
7607
|
type: MSG_CHAT_RESPONSE,
|
|
@@ -7045,9 +7687,10 @@ var Think = class Think extends Agent {
|
|
|
7045
7687
|
if (this._turnQueue.generation === clearGen) try {
|
|
7046
7688
|
const assistantMsg = accumulator.toMessage();
|
|
7047
7689
|
if (accumulator.parts.length > 0) {
|
|
7048
|
-
await this.
|
|
7690
|
+
await this._persistAssistantMessageWithCutover(streamId, assistantMsg, parentId, { discard: this._discardStreamAtCutover(requestId) });
|
|
7049
7691
|
this._broadcastMessages();
|
|
7050
7692
|
}
|
|
7693
|
+
this._resumableStream.finalizePending();
|
|
7051
7694
|
await this._fireResponseHook({
|
|
7052
7695
|
message: assistantMsg,
|
|
7053
7696
|
requestId,
|
|
@@ -7058,6 +7701,7 @@ var Think = class Think extends Agent {
|
|
|
7058
7701
|
} catch (e) {
|
|
7059
7702
|
console.error("Failed to persist assistant message:", e);
|
|
7060
7703
|
}
|
|
7704
|
+
this._resumableStream.finalizePending();
|
|
7061
7705
|
this._onStreamingTurnFinalized();
|
|
7062
7706
|
return streamError ? {
|
|
7063
7707
|
status: "error",
|
|
@@ -7088,6 +7732,44 @@ var Think = class Think extends Agent {
|
|
|
7088
7732
|
await this._upsertMessageInHistory(toPersist, parentId);
|
|
7089
7733
|
}
|
|
7090
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
|
+
/**
|
|
7091
7773
|
* Remove parts belonging to Think's internal structured-output final-answer
|
|
7092
7774
|
* tool (`think_final_answer`, or a collision-suffixed variant) from a UI
|
|
7093
7775
|
* message so the internal call/result never enters the persisted conversation
|
|
@@ -7109,38 +7791,83 @@ var Think = class Think extends Agent {
|
|
|
7109
7791
|
};
|
|
7110
7792
|
}
|
|
7111
7793
|
/**
|
|
7112
|
-
*
|
|
7113
|
-
* messages
|
|
7114
|
-
*
|
|
7115
|
-
*
|
|
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.
|
|
7116
7803
|
*/
|
|
7117
|
-
async
|
|
7118
|
-
const
|
|
7119
|
-
|
|
7120
|
-
|
|
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;
|
|
7121
7825
|
}
|
|
7122
7826
|
/**
|
|
7123
|
-
*
|
|
7124
|
-
*
|
|
7125
|
-
*
|
|
7126
|
-
*
|
|
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.
|
|
7127
7835
|
*/
|
|
7128
|
-
|
|
7129
|
-
|
|
7130
|
-
|
|
7131
|
-
|
|
7132
|
-
|
|
7133
|
-
|
|
7134
|
-
|
|
7135
|
-
|
|
7136
|
-
|
|
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;
|
|
7137
7864
|
}
|
|
7138
7865
|
_persistClientTools() {
|
|
7139
|
-
|
|
7140
|
-
else this._configDelete("lastClientTools");
|
|
7866
|
+
this._persistRequestContextKey("lastClientTools", this._lastClientTools);
|
|
7141
7867
|
}
|
|
7142
7868
|
_restoreClientTools() {
|
|
7143
7869
|
const raw = this._configGet("lastClientTools");
|
|
7870
|
+
this._persistedRequestContext.lastClientTools = raw;
|
|
7144
7871
|
if (raw) try {
|
|
7145
7872
|
this._lastClientTools = JSON.parse(raw);
|
|
7146
7873
|
} catch {
|
|
@@ -7148,11 +7875,11 @@ var Think = class Think extends Agent {
|
|
|
7148
7875
|
}
|
|
7149
7876
|
}
|
|
7150
7877
|
_persistBody() {
|
|
7151
|
-
|
|
7152
|
-
else this._configDelete("lastBody");
|
|
7878
|
+
this._persistRequestContextKey("lastBody", this._lastBody);
|
|
7153
7879
|
}
|
|
7154
7880
|
_restoreBody() {
|
|
7155
7881
|
const raw = this._configGet("lastBody");
|
|
7882
|
+
this._persistedRequestContext.lastBody = raw;
|
|
7156
7883
|
if (raw) try {
|
|
7157
7884
|
this._lastBody = JSON.parse(raw);
|
|
7158
7885
|
} catch {
|
|
@@ -7466,15 +8193,17 @@ var Think = class Think extends Agent {
|
|
|
7466
8193
|
return output;
|
|
7467
8194
|
}
|
|
7468
8195
|
/**
|
|
7469
|
-
* Replace a paused execute-tool output in the transcript
|
|
7470
|
-
* execution's new outcome and kick the auto-continuation so the
|
|
7471
|
-
* it.
|
|
8196
|
+
* Replace a paused execute-tool or durable-action output in the transcript
|
|
8197
|
+
* with the execution's new outcome and kick the auto-continuation so the
|
|
8198
|
+
* model sees it.
|
|
7472
8199
|
*
|
|
7473
8200
|
* When no paused part carries `executionId` — the output was already
|
|
7474
8201
|
* replaced from another tab, or compaction summarized the part away — the
|
|
7475
8202
|
* runtime has still durably applied the approval/rejection, so the outcome
|
|
7476
|
-
* must not be dropped: it is appended as a system note
|
|
7477
|
-
* continuation still fires so the model can act on it.
|
|
8203
|
+
* must not be dropped: it is appended as a framework-authored system note,
|
|
8204
|
+
* and the continuation still fires so the model can act on it. Provider
|
|
8205
|
+
* assembly projects this narrowly identified note to ordinary user context
|
|
8206
|
+
* without changing its durable authorship.
|
|
7478
8207
|
*/
|
|
7479
8208
|
async _applyExecutionOutcome(executionId, output) {
|
|
7480
8209
|
const toolCallId = this._findPausedExecutionToolCall(executionId);
|
|
@@ -7486,12 +8215,13 @@ var Think = class Think extends Agent {
|
|
|
7486
8215
|
} catch {
|
|
7487
8216
|
summary = String(output);
|
|
7488
8217
|
}
|
|
8218
|
+
const outcomeSource = executionId.startsWith(ACTION_PAUSE_ID_PREFIX) ? "durable action" : "execute tool";
|
|
7489
8219
|
await this._appendMessageToHistory({
|
|
7490
|
-
id:
|
|
8220
|
+
id: `${EXECUTION_OUTCOME_MESSAGE_PREFIX}${executionId}-${crypto.randomUUID()}`,
|
|
7491
8221
|
role: "system",
|
|
7492
8222
|
parts: [{
|
|
7493
8223
|
type: "text",
|
|
7494
|
-
text: `[
|
|
8224
|
+
text: `[${outcomeSource}] The paused execution "${executionId}" was resolved, but its tool call is no longer in the transcript (it may have been compacted). Outcome: ${summary}`
|
|
7495
8225
|
}]
|
|
7496
8226
|
});
|
|
7497
8227
|
} else await this._enqueueInteractionApply(() => this._applyToolUpdateToMessages(pausedExecutionUpdate(toolCallId, executionId, output)));
|
|
@@ -7541,29 +8271,30 @@ var Think = class Think extends Agent {
|
|
|
7541
8271
|
async _applyToolUpdateToMessages(update) {
|
|
7542
8272
|
let broadcastMessage;
|
|
7543
8273
|
const streaming = this._streamingAssistant;
|
|
8274
|
+
let accumulatorOwnsCall = false;
|
|
7544
8275
|
if (streaming) {
|
|
7545
8276
|
const accParts = streaming.parts;
|
|
7546
8277
|
const result = applyToolUpdate(accParts, update);
|
|
7547
|
-
if (result
|
|
7548
|
-
|
|
7549
|
-
|
|
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
|
+
}
|
|
7550
8284
|
}
|
|
7551
8285
|
}
|
|
7552
|
-
const
|
|
7553
|
-
|
|
7554
|
-
const
|
|
7555
|
-
const
|
|
7556
|
-
|
|
7557
|
-
if (result) {
|
|
7558
|
-
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]) {
|
|
7559
8291
|
const updatedMsg = {
|
|
7560
|
-
...
|
|
8292
|
+
...owner,
|
|
7561
8293
|
parts: result.parts
|
|
7562
8294
|
};
|
|
7563
8295
|
const safe = await this._updateMessageInHistory(updatedMsg);
|
|
7564
8296
|
this._patchCachedMessage(safe);
|
|
7565
8297
|
broadcastMessage = safe;
|
|
7566
|
-
break;
|
|
7567
8298
|
}
|
|
7568
8299
|
}
|
|
7569
8300
|
if (broadcastMessage) this._broadcast({
|
|
@@ -7571,6 +8302,55 @@ var Think = class Think extends Agent {
|
|
|
7571
8302
|
message: broadcastMessage
|
|
7572
8303
|
});
|
|
7573
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
|
+
}
|
|
7574
8354
|
hasPendingInteraction() {
|
|
7575
8355
|
const clientResolvable = this._clientResolvableToolNames();
|
|
7576
8356
|
const streaming = this._streamingAssistant;
|
|
@@ -7659,33 +8439,38 @@ var Think = class Think extends Agent {
|
|
|
7659
8439
|
* recomputed from the live, mutable transcript. Compaction collapses older
|
|
7660
8440
|
* assistant messages into a summary, lowering the count — so a turn that had
|
|
7661
8441
|
* genuinely advanced could read as "no progress" between attempts and exhaust
|
|
7662
|
-
* its budget prematurely (#1628).
|
|
7663
|
-
*
|
|
7664
|
-
*
|
|
7665
|
-
*
|
|
7666
|
-
*
|
|
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.
|
|
7667
8452
|
*/
|
|
7668
8453
|
async _chatRecoveryProgressMarker() {
|
|
7669
|
-
|
|
7670
|
-
|
|
7671
|
-
|
|
7672
|
-
|
|
7673
|
-
|
|
7674
|
-
|
|
7675
|
-
async _bumpChatRecoveryProgress() {
|
|
7676
|
-
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();
|
|
7677
8460
|
}
|
|
7678
8461
|
/**
|
|
7679
8462
|
* N9: forwarding a sub-agent's chunks IS forward progress for this parent
|
|
7680
8463
|
* turn, so credit the parent's recovery progress marker — otherwise a parent
|
|
7681
8464
|
* whose turn merely `await`s a child banks no progress of its own and its
|
|
7682
|
-
* 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
|
|
7683
8468
|
* invoked after a child actually produced output (see
|
|
7684
8469
|
* `_forwardAgentToolStream`), so a silent child still lets the parent exhaust.
|
|
7685
8470
|
* Throttled (and reset per isolate) so we never write storage per token.
|
|
7686
8471
|
*/
|
|
7687
8472
|
async _onAgentToolStreamProgress() {
|
|
7688
|
-
if (this._agentToolStreamProgress.shouldCredit(Date.now()))
|
|
8473
|
+
if (this._agentToolStreamProgress.shouldCredit(Date.now())) this._resumableStream.creditProgress();
|
|
7689
8474
|
}
|
|
7690
8475
|
async _beginChatRecoveryIncident(input) {
|
|
7691
8476
|
return this._chatRecoveryEngine().beginIncident(input);
|
|
@@ -7714,9 +8499,7 @@ var Think = class Think extends Agent {
|
|
|
7714
8499
|
recoveryKind: event.recoveryKind,
|
|
7715
8500
|
...event.reason ? { reason: event.reason } : {}
|
|
7716
8501
|
}),
|
|
7717
|
-
scheduleRecovery:
|
|
7718
|
-
await this.schedule(delaySeconds, callback, data, chatRecoverySchedulePolicy(reason));
|
|
7719
|
-
},
|
|
8502
|
+
scheduleRecovery: (callback, data, reason, delaySeconds) => this._enqueueChatRecovery(callback, data, reason, delaySeconds),
|
|
7720
8503
|
setRecovering: (active, requestId) => this._setChatRecovering(active, requestId),
|
|
7721
8504
|
onShouldKeepRecoveringError: (error) => console.error("[Think] chatRecovery shouldKeepRecovering hook threw", error),
|
|
7722
8505
|
exhaustChatRecovery: (incident, config, partial, streamId, createdAt) => this._exhaustChatRecovery(incident, config, partial, streamId, createdAt),
|
|
@@ -7773,12 +8556,8 @@ var Think = class Think extends Agent {
|
|
|
7773
8556
|
* emits `chat:recovery:exhausted`, marks the submission interrupted, and
|
|
7774
8557
|
* delivers the configured `terminalMessage`). The caller must NOT run the
|
|
7775
8558
|
* generic terminal path — the terminal UX is already delivered.
|
|
7776
|
-
* - `"disabled"` — chat recovery is off; the caller falls through to the
|
|
7777
|
-
* generic terminal error (the watchdog's original "kill the spinner"
|
|
7778
|
-
* behavior, unchanged).
|
|
7779
8559
|
*/
|
|
7780
8560
|
async _routeStallToBoundedRecovery(input) {
|
|
7781
|
-
if (!this._resolveChatRecoveryConfig().enabled) return "disabled";
|
|
7782
8561
|
const recoveryRootRequestId = this._activeChatRecoveryRootRequestId ?? input.requestId;
|
|
7783
8562
|
const latestUserMessageId = [...this.messages].reverse().find((m) => m.role === "user")?.id ?? null;
|
|
7784
8563
|
const { incident, config, exhausted } = await this._beginChatRecoveryIncident({
|
|
@@ -7860,14 +8639,10 @@ var Think = class Think extends Agent {
|
|
|
7860
8639
|
let streamId = "";
|
|
7861
8640
|
let streamStatus;
|
|
7862
8641
|
if (requestId) {
|
|
7863
|
-
const
|
|
7864
|
-
|
|
7865
|
-
|
|
7866
|
-
|
|
7867
|
-
`;
|
|
7868
|
-
if (rows.length > 0) {
|
|
7869
|
-
streamId = rows[0].id;
|
|
7870
|
-
streamStatus = rows[0].status;
|
|
8642
|
+
const info = this._resumableStream.latestStreamInfoForRequest(requestId);
|
|
8643
|
+
if (info) {
|
|
8644
|
+
streamId = info.id;
|
|
8645
|
+
streamStatus = info.status;
|
|
7871
8646
|
}
|
|
7872
8647
|
}
|
|
7873
8648
|
if (!streamId && this._resumableStream.hasActiveStream()) {
|
|
@@ -7944,13 +8719,13 @@ var Think = class Think extends Agent {
|
|
|
7944
8719
|
});
|
|
7945
8720
|
else if (options.continue === false && !streamIsTerminal) {
|
|
7946
8721
|
await this._updateChatRecoveryIncident(incident.incidentId, "skipped", "continue_disabled");
|
|
7947
|
-
const
|
|
7948
|
-
await this._markRecoveredSubmissionInterrupted(recoveryRootRequestId,
|
|
7949
|
-
await this._recordTerminalChatStatus("interrupted", requestId,
|
|
8722
|
+
const declinedMessage = "Submission was interrupted and automatic continuation was declined.";
|
|
8723
|
+
await this._markRecoveredSubmissionInterrupted(recoveryRootRequestId, declinedMessage);
|
|
8724
|
+
await this._recordTerminalChatStatus("interrupted", requestId, declinedMessage);
|
|
7950
8725
|
this._broadcastChat({
|
|
7951
8726
|
type: MSG_CHAT_RESPONSE,
|
|
7952
8727
|
id: requestId,
|
|
7953
|
-
body:
|
|
8728
|
+
body: declinedMessage,
|
|
7954
8729
|
done: true,
|
|
7955
8730
|
error: true
|
|
7956
8731
|
});
|
|
@@ -8055,10 +8830,10 @@ var Think = class Think extends Agent {
|
|
|
8055
8830
|
* `_exhaustChatRecovery` entirely — so an app relying on `onExhausted` for the
|
|
8056
8831
|
* terminal banner regressed to an eternal spinner when recovery gave up under
|
|
8057
8832
|
* extreme churn. The error path matters just as much: a non-transient throw
|
|
8058
|
-
* in a recovery callback is SWALLOWED by
|
|
8059
|
-
*
|
|
8060
|
-
* without routing it here the
|
|
8061
|
-
* 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
|
|
8062
8837
|
* `_chatRecoveryRetry` and `_chatRecoveryContinue`.
|
|
8063
8838
|
*
|
|
8064
8839
|
* Exactly-once terminalization is defended by two independent guards:
|
|
@@ -8076,8 +8851,9 @@ var Think = class Think extends Agent {
|
|
|
8076
8851
|
* Residual at-least-once edges, all deliberately accepted as "deliver a
|
|
8077
8852
|
* second banner" ≫ "silently drop the turn":
|
|
8078
8853
|
* • No `incidentId` at all in the payload (only reachable via a direct/test
|
|
8079
|
-
* invocation — every production
|
|
8080
|
-
* 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.
|
|
8081
8857
|
* • The record is swept AGAIN between two alarms (guard #1 re-persists on the
|
|
8082
8858
|
* first, so this needs a second independent sweep) — vanishingly unlikely.
|
|
8083
8859
|
* • A platform transient interrupts `_exhaustChatRecovery` after the banner
|
|
@@ -8085,18 +8861,25 @@ var Think = class Think extends Agent {
|
|
|
8085
8861
|
* (the terminal writes themselves are idempotent).
|
|
8086
8862
|
*/
|
|
8087
8863
|
/**
|
|
8088
|
-
*
|
|
8089
|
-
*
|
|
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}.
|
|
8090
8871
|
*/
|
|
8091
|
-
|
|
8092
|
-
|
|
8872
|
+
async onAlarmMemoryLimit(context) {
|
|
8873
|
+
if (!context.sealed) return;
|
|
8874
|
+
await this._cf_sealMemoryLimitedRecovery();
|
|
8093
8875
|
}
|
|
8094
8876
|
/**
|
|
8095
|
-
* Seal any still-live recovery incident as an out-of-memory exhaustion
|
|
8096
|
-
* the alarm circuit breaker trips at its strike budget (#1825). Runs
|
|
8097
|
-
* outermost alarm frame (post-unwind), so the terminal banner /
|
|
8098
|
-
* and the sealed-incident write can land where the mid-turn
|
|
8099
|
-
* 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`.
|
|
8100
8883
|
*/
|
|
8101
8884
|
async _cf_sealMemoryLimitedRecovery() {
|
|
8102
8885
|
const active = await listActiveChatRecoveryIncidents(this.ctx.storage);
|
|
@@ -8168,9 +8951,9 @@ var Think = class Think extends Agent {
|
|
|
8168
8951
|
* deploy code-update reset / script supersede, a `retryable`-flagged
|
|
8169
8952
|
* platform error, or "Network connection lost.", looking through wrappers
|
|
8170
8953
|
* like `SqlError` via the `cause` chain) is re-thrown (after best-effort
|
|
8171
|
-
* marking the incident `failed` for observability) so
|
|
8172
|
-
*
|
|
8173
|
-
* 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
|
|
8174
8957
|
* still recover, so it must NOT terminalize. Terminalizing here was the
|
|
8175
8958
|
* #1730 freeze: the give-up's own seal needs the very storage that is
|
|
8176
8959
|
* down, so it throws too, burns the in-process retry budget inside the
|
|
@@ -8181,11 +8964,11 @@ var Think = class Think extends Agent {
|
|
|
8181
8964
|
* `submission_not_running` no-op skip (a self-defeating defer).
|
|
8182
8965
|
* - Any OTHER (application) error is terminalized through the give-up path
|
|
8183
8966
|
* (`onExhausted` + the `terminalMessage` banner) and NOT re-thrown. This is
|
|
8184
|
-
* the fix for the silent-seal failure mode:
|
|
8185
|
-
*
|
|
8186
|
-
*
|
|
8187
|
-
*
|
|
8188
|
-
*
|
|
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).
|
|
8189
8972
|
*/
|
|
8190
8973
|
async _handleRecoveryCallbackError(callback, data, error) {
|
|
8191
8974
|
if (await this._handleRecoveryOom(callback, data, error)) return;
|
|
@@ -8202,6 +8985,9 @@ var Think = class Think extends Agent {
|
|
|
8202
8985
|
await this._exhaustRecoveryGiveUp(callback, data, "recovery_error");
|
|
8203
8986
|
}
|
|
8204
8987
|
async _chatRecoveryRetry(data) {
|
|
8988
|
+
await this._dispatchChatRecovery("_chatRecoveryRetry", data, (onTurnStarted) => this._chatRecoveryRetryDetached(data, onTurnStarted));
|
|
8989
|
+
}
|
|
8990
|
+
async _chatRecoveryRetryDetached(data, onTurnStarted) {
|
|
8205
8991
|
const recoveredSubmission = data?.recoveredRequestId ? this._readRunningSubmissionByRequestId(data.recoveredRequestId) : null;
|
|
8206
8992
|
if (data?.recoveredRequestId && !recoveredSubmission) {
|
|
8207
8993
|
await this._updateChatRecoveryIncident(data.incidentId, "skipped", "submission_not_running");
|
|
@@ -8231,6 +9017,7 @@ var Think = class Think extends Agent {
|
|
|
8231
9017
|
return;
|
|
8232
9018
|
}
|
|
8233
9019
|
this._applyRecoveredRequestContext(data);
|
|
9020
|
+
onTurnStarted?.();
|
|
8234
9021
|
const result = await this._retryLastUserTurn(this._lastClientTools, this._lastBody, controller ? {
|
|
8235
9022
|
signal: controller.signal,
|
|
8236
9023
|
trigger: "recovery-retry"
|
|
@@ -8312,6 +9099,9 @@ var Think = class Think extends Agent {
|
|
|
8312
9099
|
return {};
|
|
8313
9100
|
}
|
|
8314
9101
|
async _chatRecoveryContinue(data) {
|
|
9102
|
+
await this._dispatchChatRecovery("_chatRecoveryContinue", data, (onTurnStarted) => this._chatRecoveryContinueDetached(data, onTurnStarted));
|
|
9103
|
+
}
|
|
9104
|
+
async _chatRecoveryContinueDetached(data, onTurnStarted) {
|
|
8315
9105
|
const recoveredSubmission = data?.recoveredRequestId ? this._readRunningSubmissionByRequestId(data.recoveredRequestId) : null;
|
|
8316
9106
|
if (data?.recoveredRequestId && !recoveredSubmission) {
|
|
8317
9107
|
await this._updateChatRecoveryIncident(data.incidentId, "skipped", "submission_not_running");
|
|
@@ -8339,6 +9129,7 @@ var Think = class Think extends Agent {
|
|
|
8339
9129
|
return;
|
|
8340
9130
|
}
|
|
8341
9131
|
this._applyRecoveredRequestContext(data);
|
|
9132
|
+
onTurnStarted?.();
|
|
8342
9133
|
const result = await this.continueLastTurn(void 0, controller ? {
|
|
8343
9134
|
signal: controller.signal,
|
|
8344
9135
|
trigger: "recovery-continue"
|
|
@@ -8496,8 +9287,7 @@ var Think = class Think extends Agent {
|
|
|
8496
9287
|
streamed = true;
|
|
8497
9288
|
}
|
|
8498
9289
|
};
|
|
8499
|
-
|
|
8500
|
-
else await continuationBody();
|
|
9290
|
+
await this._runChatRecoveryFiber(requestId, true, continuationBody);
|
|
8501
9291
|
} finally {
|
|
8502
9292
|
this._aborts.remove(requestId);
|
|
8503
9293
|
if (!streamed) this._continuation.sendResumeNone();
|
|
@@ -8553,8 +9343,7 @@ var Think = class Think extends Agent {
|
|
|
8553
9343
|
}));
|
|
8554
9344
|
if (result) await this._streamResult(requestId, result, abortSignal, { continuation: true });
|
|
8555
9345
|
};
|
|
8556
|
-
|
|
8557
|
-
else await continuationBody();
|
|
9346
|
+
await this._runChatRecoveryFiber(requestId, true, continuationBody);
|
|
8558
9347
|
}
|
|
8559
9348
|
});
|
|
8560
9349
|
} catch (error) {
|
|
@@ -8743,45 +9532,31 @@ var Think = class Think extends Agent {
|
|
|
8743
9532
|
_startResumableStream(requestId, options) {
|
|
8744
9533
|
const streamId = this._resumableStream.start(requestId, options);
|
|
8745
9534
|
this._preStream.flushOnStreamStart((c) => this._notifyStreamResuming(c));
|
|
8746
|
-
this._ensureStreamCleanupScheduled();
|
|
8747
9535
|
return streamId;
|
|
8748
9536
|
}
|
|
8749
|
-
/**
|
|
8750
|
-
* Mark a resumable stream completed and arm buffer cleanup. Wrapper around
|
|
8751
|
-
* `ResumableStream.complete` so every stream-finish path also schedules the
|
|
8752
|
-
* cleanup alarm (#1706).
|
|
8753
|
-
*/
|
|
9537
|
+
/** Mark a resumable stream completed (settled now, rows kept until reclaim). */
|
|
8754
9538
|
_completeResumableStream(streamId) {
|
|
8755
9539
|
this._resumableStream.complete(streamId);
|
|
8756
|
-
this._ensureStreamCleanupScheduled();
|
|
8757
9540
|
}
|
|
8758
9541
|
/**
|
|
8759
|
-
*
|
|
8760
|
-
* `
|
|
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()`.
|
|
8761
9545
|
*/
|
|
9546
|
+
_finishResumableStream(streamId) {
|
|
9547
|
+
this._resumableStream.finish(streamId);
|
|
9548
|
+
}
|
|
9549
|
+
/** Mark a resumable stream errored. */
|
|
8762
9550
|
_errorResumableStream(streamId) {
|
|
8763
9551
|
this._resumableStream.markError(streamId);
|
|
8764
|
-
this._ensureStreamCleanupScheduled();
|
|
8765
9552
|
}
|
|
8766
9553
|
/**
|
|
8767
|
-
*
|
|
8768
|
-
*
|
|
8769
|
-
*
|
|
8770
|
-
* only fires when a *subsequent* stream completes, which never happens for a
|
|
8771
|
-
* chat that receives a single turn (#1706).
|
|
8772
|
-
*
|
|
8773
|
-
* `idempotent` dedupes on (callback, payload, owner) so repeated finishes
|
|
8774
|
-
* collapse onto one pending alarm rather than stacking.
|
|
8775
|
-
*/
|
|
8776
|
-
async _ensureStreamCleanupScheduled({ idempotent = true } = {}) {
|
|
8777
|
-
await this.schedule(STREAM_CLEANUP_DELAY_SECONDS, "_cleanupStreamBuffers", void 0, { idempotent });
|
|
8778
|
-
}
|
|
8779
|
-
/**
|
|
8780
|
-
* Alarm callback: sweep aged stream buffers, re-arming while rows remain (see
|
|
8781
|
-
* 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.
|
|
8782
9557
|
*/
|
|
8783
9558
|
async _cleanupStreamBuffers() {
|
|
8784
|
-
|
|
9559
|
+
this._resumableStream.reclaim();
|
|
8785
9560
|
}
|
|
8786
9561
|
async _persistOrphanedStream(streamId) {
|
|
8787
9562
|
this._resumableStream.flushBuffer();
|
|
@@ -8808,6 +9583,11 @@ var Think = class Think extends Agent {
|
|
|
8808
9583
|
}, exclude);
|
|
8809
9584
|
}
|
|
8810
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
|
+
}
|
|
8811
9591
|
Think.CONFIG_KEYS = [
|
|
8812
9592
|
"_think_config",
|
|
8813
9593
|
"lastClientTools",
|
|
@@ -8824,6 +9604,6 @@ for (const method of [
|
|
|
8824
9604
|
Think.prototype.rejectExecution
|
|
8825
9605
|
]) callable()(method, void 0);
|
|
8826
9606
|
//#endregion
|
|
8827
|
-
export { Session, Think, Workspace, action, defaultContextOverflowClassifier, isAction, messengerChannel, skills };
|
|
9607
|
+
export { ThinkSession as Session, ThinkSession, Think, Workspace, action, defaultContextOverflowClassifier, isAction, messengerChannel, skills };
|
|
8828
9608
|
|
|
8829
9609
|
//# sourceMappingURL=think.js.map
|