@cloudflare/think 0.2.0 → 0.2.2
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 +134 -31
- package/dist/{classPrivateFieldGet2-B0jG-d4Z.js → classPrivateFieldGet2-fyJ3k1Ht.js} +5 -5
- package/dist/extensions/index.d.ts +20 -10
- package/dist/extensions/index.js +96 -8
- package/dist/extensions/index.js.map +1 -1
- package/dist/hook-proxy-f_DqtJ9u.js +32 -0
- package/dist/hook-proxy-f_DqtJ9u.js.map +1 -0
- package/dist/index-BsB4GUsL.d.ts +109 -0
- package/dist/{manager-BY5AZLVa.js → manager-BTBhPS6g.js} +116 -9
- package/dist/manager-BTBhPS6g.js.map +1 -0
- package/dist/{index-CAMRySsy.d.ts → manager-DCbSiSWT.d.ts} +106 -41
- package/dist/think.d.ts +294 -69
- package/dist/think.js +360 -119
- package/dist/think.js.map +1 -1
- package/dist/tools/browser.d.ts +80 -0
- package/dist/tools/browser.js +74 -0
- package/dist/tools/browser.js.map +1 -0
- package/dist/tools/execute.d.ts +1 -1
- package/dist/tools/extensions.d.ts +3 -3
- package/dist/tools/extensions.js +3 -3
- package/dist/tools/extensions.js.map +1 -1
- package/package.json +7 -6
- package/dist/manager-BY5AZLVa.js.map +0 -1
package/dist/think.js
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { createWorkspaceTools } from "./tools/workspace.js";
|
|
2
|
+
import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-fyJ3k1Ht.js";
|
|
2
3
|
import { convertToModelMessages, pruneMessages, stepCountIs, streamText } from "ai";
|
|
3
4
|
import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext } from "agents";
|
|
4
5
|
import { AbortRegistry, CHAT_MESSAGE_TYPES, ContinuationState, ResumableStream, StreamAccumulator, TurnQueue, applyChunkToParts, applyToolUpdate, createToolsFromClientSchemas, enforceRowSizeLimit, parseProtocolMessage, sanitizeMessage, toolApprovalUpdate, toolResultUpdate } from "agents/chat";
|
|
5
6
|
import { Session, Session as Session$1 } from "agents/experimental/memory/session";
|
|
6
7
|
import { truncateOlderMessages } from "agents/experimental/memory/utils";
|
|
8
|
+
import { Workspace, Workspace as Workspace$1 } from "@cloudflare/shell";
|
|
7
9
|
//#region src/think.ts
|
|
8
10
|
const MSG_CHAT_MESSAGES = CHAT_MESSAGE_TYPES.CHAT_MESSAGES;
|
|
9
11
|
const MSG_CHAT_RESPONSE = CHAT_MESSAGE_TYPES.USE_CHAT_RESPONSE;
|
|
@@ -30,17 +32,25 @@ var Think = class Think extends Agent {
|
|
|
30
32
|
this._continuation = new ContinuationState();
|
|
31
33
|
this._continuationTimer = null;
|
|
32
34
|
this._insideResponseHook = false;
|
|
35
|
+
this._insideInferenceLoop = false;
|
|
33
36
|
this._pendingInteractionPromise = null;
|
|
34
37
|
this._submitSequence = 0;
|
|
35
38
|
this._latestOverlappingSubmitSequence = 0;
|
|
36
39
|
this._activeDebounceTimer = null;
|
|
37
40
|
this._activeDebounceResolve = null;
|
|
38
41
|
_classPrivateFieldInitSpec(this, _configCache, null);
|
|
42
|
+
this.maxSteps = 10;
|
|
43
|
+
this.hookTimeout = 5e3;
|
|
39
44
|
const _onStart = this.onStart.bind(this);
|
|
40
45
|
this.onStart = async () => {
|
|
46
|
+
if (!this.workspace) this.workspace = new Workspace$1({
|
|
47
|
+
sql: this.ctx.storage.sql,
|
|
48
|
+
name: () => this.name
|
|
49
|
+
});
|
|
41
50
|
const baseSession = Session$1.create(this);
|
|
42
51
|
this.session = await this.configureSession(baseSession);
|
|
43
52
|
this.session.getHistory();
|
|
53
|
+
if (this.extensionLoader) await this._initializeExtensions();
|
|
44
54
|
this._resumableStream = new ResumableStream(this.sql.bind(this));
|
|
45
55
|
this._restoreClientTools();
|
|
46
56
|
this._restoreBody();
|
|
@@ -102,11 +112,10 @@ var Think = class Think extends Agent {
|
|
|
102
112
|
}
|
|
103
113
|
/**
|
|
104
114
|
* Return the language model to use for inference.
|
|
105
|
-
* Must be overridden by subclasses
|
|
106
|
-
* `onChatMessage` implementation (the agentic loop).
|
|
115
|
+
* Must be overridden by subclasses.
|
|
107
116
|
*/
|
|
108
117
|
getModel() {
|
|
109
|
-
throw new Error("Override getModel() to return a LanguageModel
|
|
118
|
+
throw new Error("Override getModel() to return a LanguageModel.");
|
|
110
119
|
}
|
|
111
120
|
/**
|
|
112
121
|
* Return the system prompt for the assistant.
|
|
@@ -119,20 +128,10 @@ var Think = class Think extends Agent {
|
|
|
119
128
|
getTools() {
|
|
120
129
|
return {};
|
|
121
130
|
}
|
|
122
|
-
/** Return the maximum number of tool-call steps per turn. */
|
|
123
|
-
getMaxSteps() {
|
|
124
|
-
return 10;
|
|
125
|
-
}
|
|
126
131
|
/**
|
|
127
132
|
* Configure the session. Called once during `onStart`.
|
|
128
133
|
* Override to add context blocks, compaction, search, skills.
|
|
129
134
|
*
|
|
130
|
-
* The base session is pre-created with `Session.create(this)`.
|
|
131
|
-
* Return it with builder methods chained.
|
|
132
|
-
*
|
|
133
|
-
* Async is supported — use it to read configuration from KV, D1,
|
|
134
|
-
* or R2 before setting up context blocks.
|
|
135
|
-
*
|
|
136
135
|
* @example
|
|
137
136
|
* ```typescript
|
|
138
137
|
* configureSession(session: Session) {
|
|
@@ -141,74 +140,81 @@ var Think = class Think extends Agent {
|
|
|
141
140
|
* .withCachedPrompt();
|
|
142
141
|
* }
|
|
143
142
|
* ```
|
|
144
|
-
*
|
|
145
|
-
* @example Async configuration from KV
|
|
146
|
-
* ```typescript
|
|
147
|
-
* async configureSession(session: Session) {
|
|
148
|
-
* const config = await this.env.KV.get("agent-config", "json");
|
|
149
|
-
* return session
|
|
150
|
-
* .withContext("memory", { maxTokens: config.memoryTokens })
|
|
151
|
-
* .withCachedPrompt();
|
|
152
|
-
* }
|
|
153
|
-
* ```
|
|
154
143
|
*/
|
|
155
144
|
configureSession(session) {
|
|
156
145
|
return session;
|
|
157
146
|
}
|
|
158
147
|
/**
|
|
159
|
-
*
|
|
148
|
+
* Return sandboxed extension configurations. Defines load order,
|
|
149
|
+
* which determines hook execution order.
|
|
150
|
+
* Requires `extensionLoader` to be set.
|
|
151
|
+
*/
|
|
152
|
+
getExtensions() {
|
|
153
|
+
return [];
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Called before `streamText` — inspect the assembled context and
|
|
157
|
+
* return overrides. Think assembles tools, system prompt, and messages
|
|
158
|
+
* internally; this hook sees the result and can override any part.
|
|
160
159
|
*
|
|
161
|
-
*
|
|
162
|
-
*
|
|
163
|
-
*
|
|
164
|
-
*
|
|
165
|
-
*
|
|
160
|
+
* Return `void` to accept all defaults.
|
|
161
|
+
*
|
|
162
|
+
* @example Switch model for continuations
|
|
163
|
+
* ```typescript
|
|
164
|
+
* beforeTurn(ctx: TurnContext) {
|
|
165
|
+
* if (ctx.continuation) return { model: this.cheapModel };
|
|
166
|
+
* }
|
|
167
|
+
* ```
|
|
166
168
|
*
|
|
167
|
-
*
|
|
169
|
+
* @example Restrict active tools
|
|
170
|
+
* ```typescript
|
|
171
|
+
* beforeTurn(ctx: TurnContext) {
|
|
172
|
+
* return { activeTools: ["read", "write"] };
|
|
173
|
+
* }
|
|
174
|
+
* ```
|
|
168
175
|
*/
|
|
169
|
-
|
|
170
|
-
return {
|
|
171
|
-
system: await this.session.freezeSystemPrompt() || this.getSystemPrompt(),
|
|
172
|
-
messages: pruneMessages({
|
|
173
|
-
messages: await convertToModelMessages(truncateOlderMessages(this.session.getHistory())),
|
|
174
|
-
toolCalls: "before-last-2-messages"
|
|
175
|
-
})
|
|
176
|
-
};
|
|
177
|
-
}
|
|
176
|
+
beforeTurn(_ctx) {}
|
|
178
177
|
/**
|
|
179
|
-
*
|
|
178
|
+
* Called when the model produces a tool call. Currently fires
|
|
179
|
+
* **after** tool execution (via `onStepFinish` data) — observation only.
|
|
180
180
|
*
|
|
181
|
-
*
|
|
182
|
-
*
|
|
183
|
-
*
|
|
184
|
-
*
|
|
181
|
+
* **Known limitation:** `block` and `substitute` actions in the returned
|
|
182
|
+
* `ToolCallDecision` are not yet functional. The AI SDK's `streamText`
|
|
183
|
+
* does not expose a pre-execution interception point for tool calls
|
|
184
|
+
* in the Workers runtime. The types are in place for when this becomes
|
|
185
|
+
* possible (see plan: "Known limitations — Phase 1").
|
|
185
186
|
*
|
|
186
|
-
*
|
|
187
|
+
* Only fires for server-side tools (tools with `execute`).
|
|
188
|
+
* Client tools are handled on the client — Think can't intercept them.
|
|
187
189
|
*
|
|
188
|
-
*
|
|
189
|
-
*
|
|
190
|
+
* Return `void` to accept default behavior.
|
|
191
|
+
*
|
|
192
|
+
* @example Log tool calls
|
|
193
|
+
* ```typescript
|
|
194
|
+
* beforeToolCall(ctx: ToolCallContext) {
|
|
195
|
+
* console.log(`Tool called: ${ctx.toolName}`, ctx.args);
|
|
196
|
+
* }
|
|
197
|
+
* ```
|
|
190
198
|
*/
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
});
|
|
211
|
-
}
|
|
199
|
+
beforeToolCall(_ctx) {}
|
|
200
|
+
/**
|
|
201
|
+
* Called after a tool executes (or a substitute result is provided).
|
|
202
|
+
* Does NOT fire when `beforeToolCall` blocks with no substitute result.
|
|
203
|
+
*
|
|
204
|
+
* Override for logging, metrics, or result inspection.
|
|
205
|
+
*/
|
|
206
|
+
afterToolCall(_ctx) {}
|
|
207
|
+
/**
|
|
208
|
+
* Called after each step completes (initial, continue, tool-result).
|
|
209
|
+
* Override for step-level logging or analytics.
|
|
210
|
+
*/
|
|
211
|
+
onStepFinish(_ctx) {}
|
|
212
|
+
/**
|
|
213
|
+
* Called for each streaming chunk. High-frequency — fires per token.
|
|
214
|
+
* Override for streaming analytics, progress indicators, or token counting.
|
|
215
|
+
* Observational only (void return).
|
|
216
|
+
*/
|
|
217
|
+
onChunk(_ctx) {}
|
|
212
218
|
/**
|
|
213
219
|
* Called after a chat turn completes and the assistant message has been
|
|
214
220
|
* persisted. The turn lock is released before this hook runs, so it is
|
|
@@ -227,6 +233,242 @@ var Think = class Think extends Agent {
|
|
|
227
233
|
onChatError(error) {
|
|
228
234
|
return error;
|
|
229
235
|
}
|
|
236
|
+
async _initializeExtensions() {
|
|
237
|
+
const { ExtensionManager } = await import("./manager-BTBhPS6g.js").then((n) => n.n);
|
|
238
|
+
const { sanitizeName } = await import("./manager-BTBhPS6g.js").then((n) => n.n);
|
|
239
|
+
const agentClassName = this.constructor.name;
|
|
240
|
+
const agentId = this.ctx.id.toString();
|
|
241
|
+
const ctxExports = this.ctx.exports;
|
|
242
|
+
const hasBridge = ctxExports && typeof ctxExports.HostBridgeLoopback === "function";
|
|
243
|
+
this.extensionManager = new ExtensionManager({
|
|
244
|
+
loader: this.extensionLoader,
|
|
245
|
+
storage: this.ctx.storage,
|
|
246
|
+
...hasBridge ? { createHostBinding: (permissions, ownContextLabels) => ctxExports.HostBridgeLoopback({ props: {
|
|
247
|
+
agentClassName,
|
|
248
|
+
agentId,
|
|
249
|
+
permissions,
|
|
250
|
+
ownContextLabels
|
|
251
|
+
} }) } : {}
|
|
252
|
+
});
|
|
253
|
+
const configs = this.getExtensions();
|
|
254
|
+
for (const config of configs) await this.extensionManager.load(config.manifest, config.source);
|
|
255
|
+
await this.extensionManager.restore();
|
|
256
|
+
for (const ext of this.extensionManager.list()) {
|
|
257
|
+
const manifest = this.extensionManager.getManifest(ext.name);
|
|
258
|
+
if (!manifest?.context) continue;
|
|
259
|
+
const prefix = sanitizeName(ext.name);
|
|
260
|
+
for (const ctxDef of manifest.context) {
|
|
261
|
+
const namespacedLabel = `${prefix}_${ctxDef.label}`;
|
|
262
|
+
await this.session.addContext(namespacedLabel, {
|
|
263
|
+
description: ctxDef.description,
|
|
264
|
+
maxTokens: ctxDef.maxTokens
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
this.extensionManager.onUnload(async (_name, contextLabels) => {
|
|
269
|
+
for (const label of contextLabels) this.session.removeContext(label);
|
|
270
|
+
await this.session.refreshSystemPrompt();
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* The single convergence point for all chat turn entry paths.
|
|
275
|
+
* Merges tools, assembles context, fires lifecycle hooks, wraps tools
|
|
276
|
+
* for interception, and calls streamText.
|
|
277
|
+
*/
|
|
278
|
+
async _runInferenceLoop(input) {
|
|
279
|
+
if (this.waitForMcpConnections) {
|
|
280
|
+
const timeout = typeof this.waitForMcpConnections === "object" ? this.waitForMcpConnections.timeout : 1e4;
|
|
281
|
+
await this.mcp.waitForConnections({ timeout });
|
|
282
|
+
}
|
|
283
|
+
const workspaceTools = createWorkspaceTools(this.workspace);
|
|
284
|
+
const baseTools = this.getTools();
|
|
285
|
+
const extensionTools = this.extensionManager?.getTools() ?? {};
|
|
286
|
+
const contextTools = await this.session.tools();
|
|
287
|
+
const clientToolSet = createToolsFromClientSchemas(input.clientTools);
|
|
288
|
+
const tools = {
|
|
289
|
+
...workspaceTools,
|
|
290
|
+
...baseTools,
|
|
291
|
+
...extensionTools,
|
|
292
|
+
...contextTools,
|
|
293
|
+
...this.mcp?.getAITools?.() ?? {},
|
|
294
|
+
...clientToolSet,
|
|
295
|
+
...input.callerTools
|
|
296
|
+
};
|
|
297
|
+
const system = await this.session.freezeSystemPrompt() || this.getSystemPrompt();
|
|
298
|
+
const messages = pruneMessages({
|
|
299
|
+
messages: await convertToModelMessages(truncateOlderMessages(this.session.getHistory())),
|
|
300
|
+
toolCalls: "before-last-2-messages"
|
|
301
|
+
});
|
|
302
|
+
if (messages.length === 0) throw new Error("No messages to send to the model. This usually means the chat request arrived before any messages were persisted.");
|
|
303
|
+
const model = this.getModel();
|
|
304
|
+
const ctx = {
|
|
305
|
+
system,
|
|
306
|
+
messages,
|
|
307
|
+
tools,
|
|
308
|
+
model,
|
|
309
|
+
continuation: input.continuation,
|
|
310
|
+
body: input.body
|
|
311
|
+
};
|
|
312
|
+
const subclassConfig = await this.beforeTurn(ctx) ?? {};
|
|
313
|
+
const config = await this._pipelineExtensionBeforeTurn(ctx, subclassConfig);
|
|
314
|
+
const finalModel = config.model ?? model;
|
|
315
|
+
const finalSystem = config.system ?? system;
|
|
316
|
+
const finalMessages = config.messages ?? messages;
|
|
317
|
+
const finalTools = config.tools ? {
|
|
318
|
+
...tools,
|
|
319
|
+
...config.tools
|
|
320
|
+
} : tools;
|
|
321
|
+
const finalMaxSteps = config.maxSteps ?? this.maxSteps;
|
|
322
|
+
const result = streamText({
|
|
323
|
+
model: finalModel,
|
|
324
|
+
system: finalSystem,
|
|
325
|
+
messages: finalMessages,
|
|
326
|
+
tools: finalTools,
|
|
327
|
+
activeTools: config.activeTools,
|
|
328
|
+
toolChoice: config.toolChoice,
|
|
329
|
+
stopWhen: stepCountIs(finalMaxSteps),
|
|
330
|
+
providerOptions: config.providerOptions,
|
|
331
|
+
abortSignal: input.signal,
|
|
332
|
+
onChunk: async (event) => {
|
|
333
|
+
await this.onChunk({ chunk: event.chunk });
|
|
334
|
+
},
|
|
335
|
+
onStepFinish: async (event) => {
|
|
336
|
+
const toolCalls = event.toolCalls ?? [];
|
|
337
|
+
const toolResults = event.toolResults ?? [];
|
|
338
|
+
for (let i = 0; i < toolCalls.length; i++) {
|
|
339
|
+
const tc = toolCalls[i];
|
|
340
|
+
if (tc) await this.beforeToolCall({
|
|
341
|
+
toolName: tc.toolName ?? tc.name ?? "",
|
|
342
|
+
args: tc.args ?? {}
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
for (let i = 0; i < toolResults.length; i++) {
|
|
346
|
+
const tr = toolResults[i];
|
|
347
|
+
const tc = toolCalls[i];
|
|
348
|
+
if (tr) await this.afterToolCall({
|
|
349
|
+
toolName: tc?.toolName ?? tc?.name ?? tr?.toolName ?? "",
|
|
350
|
+
args: tc?.args ?? {},
|
|
351
|
+
result: tr.result
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
await this.onStepFinish({
|
|
355
|
+
stepType: event.stepType ?? "initial",
|
|
356
|
+
text: event.text ?? "",
|
|
357
|
+
toolCalls,
|
|
358
|
+
toolResults,
|
|
359
|
+
finishReason: event.finishReason ?? "stop",
|
|
360
|
+
usage: {
|
|
361
|
+
inputTokens: event.usage?.inputTokens ?? 0,
|
|
362
|
+
outputTokens: event.usage?.outputTokens ?? 0
|
|
363
|
+
}
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
});
|
|
367
|
+
return this._transformInferenceResult(result);
|
|
368
|
+
}
|
|
369
|
+
/** @internal Test seam — override in test agents to wrap the stream (e.g. error injection). */
|
|
370
|
+
_transformInferenceResult(result) {
|
|
371
|
+
return result;
|
|
372
|
+
}
|
|
373
|
+
/**
|
|
374
|
+
* Pipeline beforeTurn through sandboxed extensions in load order.
|
|
375
|
+
* Each extension sees the accumulated state from prior extensions
|
|
376
|
+
* (snapshot is rebuilt after each extension's modifications).
|
|
377
|
+
* Results are merged with last-write-wins for scalar fields.
|
|
378
|
+
* Extensions that don't subscribe to beforeTurn are skipped.
|
|
379
|
+
*/
|
|
380
|
+
async _pipelineExtensionBeforeTurn(ctx, subclassConfig) {
|
|
381
|
+
if (!this.extensionManager) return subclassConfig;
|
|
382
|
+
const subscribers = this.extensionManager.getHookSubscribers("beforeTurn");
|
|
383
|
+
if (subscribers.length === 0) return subclassConfig;
|
|
384
|
+
const { createTurnContextSnapshot, parseHookResult } = await import("./hook-proxy-f_DqtJ9u.js");
|
|
385
|
+
let snapshot = createTurnContextSnapshot(ctx);
|
|
386
|
+
let accumulated = { ...subclassConfig };
|
|
387
|
+
if (accumulated.system !== void 0) snapshot.system = accumulated.system;
|
|
388
|
+
if (accumulated.maxSteps !== void 0) snapshot.messageCount = ctx.messages.length;
|
|
389
|
+
for (const sub of subscribers) {
|
|
390
|
+
let timer;
|
|
391
|
+
try {
|
|
392
|
+
const parsed = parseHookResult(await Promise.race([sub.entrypoint.hook("beforeTurn", snapshot), new Promise((_, reject) => {
|
|
393
|
+
timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`Hook timeout: ${sub.name}`)), this.hookTimeout);
|
|
394
|
+
})]));
|
|
395
|
+
if ("config" in parsed) {
|
|
396
|
+
if (parsed.config.system !== void 0) accumulated.system = parsed.config.system;
|
|
397
|
+
if (parsed.config.messages !== void 0) accumulated.messages = parsed.config.messages;
|
|
398
|
+
if (parsed.config.activeTools !== void 0) accumulated.activeTools = parsed.config.activeTools;
|
|
399
|
+
if (parsed.config.toolChoice !== void 0) accumulated.toolChoice = parsed.config.toolChoice;
|
|
400
|
+
if (parsed.config.maxSteps !== void 0) accumulated.maxSteps = parsed.config.maxSteps;
|
|
401
|
+
if (parsed.config.providerOptions !== void 0) accumulated.providerOptions = {
|
|
402
|
+
...accumulated.providerOptions ?? {},
|
|
403
|
+
...parsed.config.providerOptions
|
|
404
|
+
};
|
|
405
|
+
if (accumulated.system !== void 0) snapshot = {
|
|
406
|
+
...snapshot,
|
|
407
|
+
system: accumulated.system
|
|
408
|
+
};
|
|
409
|
+
if (accumulated.activeTools !== void 0) snapshot = {
|
|
410
|
+
...snapshot,
|
|
411
|
+
toolNames: accumulated.activeTools
|
|
412
|
+
};
|
|
413
|
+
} else if ("error" in parsed) console.warn(`[Think] Extension "${sub.name}" beforeTurn error:`, parsed.error);
|
|
414
|
+
} catch (err) {
|
|
415
|
+
console.warn(`[Think] Extension "${sub.name}" beforeTurn failed:`, err instanceof Error ? err.message : err);
|
|
416
|
+
} finally {
|
|
417
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
return accumulated;
|
|
421
|
+
}
|
|
422
|
+
async _hostReadFile(path) {
|
|
423
|
+
return await this.workspace.readFile(path) ?? null;
|
|
424
|
+
}
|
|
425
|
+
async _hostWriteFile(path, content) {
|
|
426
|
+
await this.workspace.writeFile(path, content);
|
|
427
|
+
}
|
|
428
|
+
async _hostDeleteFile(path) {
|
|
429
|
+
try {
|
|
430
|
+
await this.workspace.rm(path);
|
|
431
|
+
return true;
|
|
432
|
+
} catch {
|
|
433
|
+
return false;
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
async _hostListFiles(dir) {
|
|
437
|
+
return (await this.workspace.readDir(dir)).map((e) => ({
|
|
438
|
+
name: e.name,
|
|
439
|
+
type: e.type,
|
|
440
|
+
size: e.size ?? 0,
|
|
441
|
+
path: e.path ?? `${dir}/${e.name}`
|
|
442
|
+
}));
|
|
443
|
+
}
|
|
444
|
+
async _hostGetContext(label) {
|
|
445
|
+
return this.session.getContextBlock(label)?.content ?? null;
|
|
446
|
+
}
|
|
447
|
+
async _hostSetContext(label, content) {
|
|
448
|
+
await this.session.replaceContextBlock(label, content);
|
|
449
|
+
}
|
|
450
|
+
async _hostGetMessages(limit) {
|
|
451
|
+
const history = this.session.getHistory();
|
|
452
|
+
return (limit !== void 0 && limit !== null ? limit <= 0 ? [] : history.slice(-limit) : history).map((m) => ({
|
|
453
|
+
id: m.id,
|
|
454
|
+
role: m.role,
|
|
455
|
+
content: m.parts.filter((p) => p.type === "text").map((p) => p.text).join("")
|
|
456
|
+
}));
|
|
457
|
+
}
|
|
458
|
+
async _hostSendMessage(content) {
|
|
459
|
+
const msg = {
|
|
460
|
+
id: crypto.randomUUID(),
|
|
461
|
+
role: "user",
|
|
462
|
+
parts: [{
|
|
463
|
+
type: "text",
|
|
464
|
+
text: content
|
|
465
|
+
}]
|
|
466
|
+
};
|
|
467
|
+
await this.session.appendMessage(msg);
|
|
468
|
+
}
|
|
469
|
+
async _hostGetSessionInfo() {
|
|
470
|
+
return { messageCount: this.session.getHistory().length };
|
|
471
|
+
}
|
|
230
472
|
/**
|
|
231
473
|
* Run a chat turn: persist the user message, run the agentic loop,
|
|
232
474
|
* stream UIMessageChunk events via callback, and persist the
|
|
@@ -250,19 +492,29 @@ var Think = class Think extends Agent {
|
|
|
250
492
|
await this.session.appendMessage(userMsg);
|
|
251
493
|
const accumulator = new StreamAccumulator({ messageId: crypto.randomUUID() });
|
|
252
494
|
try {
|
|
253
|
-
const result = await
|
|
495
|
+
const result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
|
|
496
|
+
agent: this,
|
|
497
|
+
connection: void 0,
|
|
498
|
+
request: void 0,
|
|
499
|
+
email: void 0
|
|
500
|
+
}, () => this._runInferenceLoop({
|
|
254
501
|
signal: options?.signal,
|
|
255
|
-
|
|
502
|
+
callerTools: options?.tools,
|
|
256
503
|
continuation: false
|
|
257
|
-
});
|
|
504
|
+
}));
|
|
505
|
+
this._insideInferenceLoop = true;
|
|
258
506
|
let aborted = false;
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
aborted
|
|
262
|
-
|
|
507
|
+
try {
|
|
508
|
+
for await (const chunk of result.toUIMessageStream()) {
|
|
509
|
+
if (options?.signal?.aborted) {
|
|
510
|
+
aborted = true;
|
|
511
|
+
break;
|
|
512
|
+
}
|
|
513
|
+
accumulator.applyChunk(chunk);
|
|
514
|
+
await callback.onEvent(JSON.stringify(chunk));
|
|
263
515
|
}
|
|
264
|
-
|
|
265
|
-
|
|
516
|
+
} finally {
|
|
517
|
+
this._insideInferenceLoop = false;
|
|
266
518
|
}
|
|
267
519
|
const assistantMsg = accumulator.toMessage();
|
|
268
520
|
this._persistAssistantMessage(assistantMsg);
|
|
@@ -361,7 +613,7 @@ var Think = class Think extends Agent {
|
|
|
361
613
|
connection: void 0,
|
|
362
614
|
request: void 0,
|
|
363
615
|
email: void 0
|
|
364
|
-
}, () => this.
|
|
616
|
+
}, () => this._runInferenceLoop({
|
|
365
617
|
signal: abortSignal,
|
|
366
618
|
clientTools,
|
|
367
619
|
body,
|
|
@@ -423,7 +675,7 @@ var Think = class Think extends Agent {
|
|
|
423
675
|
connection: void 0,
|
|
424
676
|
request: void 0,
|
|
425
677
|
email: void 0
|
|
426
|
-
}, () => this.
|
|
678
|
+
}, () => this._runInferenceLoop({
|
|
427
679
|
signal: abortSignal,
|
|
428
680
|
clientTools,
|
|
429
681
|
body: resolvedBody,
|
|
@@ -446,17 +698,6 @@ var Think = class Think extends Agent {
|
|
|
446
698
|
status
|
|
447
699
|
};
|
|
448
700
|
}
|
|
449
|
-
/**
|
|
450
|
-
* Override to apply custom transformations to messages before they are
|
|
451
|
-
* persisted to Session storage. Runs after the built-in sanitization
|
|
452
|
-
* (OpenAI metadata stripping, row size enforcement) but before
|
|
453
|
-
* `session.appendMessage` / `session.updateMessage`.
|
|
454
|
-
*
|
|
455
|
-
* Use for redacting PII, stripping internal metadata, or custom compaction.
|
|
456
|
-
*/
|
|
457
|
-
sanitizeMessageForPersistence(message) {
|
|
458
|
-
return message;
|
|
459
|
-
}
|
|
460
701
|
_setupProtocolHandlers() {
|
|
461
702
|
const _onConnect = this.onConnect.bind(this);
|
|
462
703
|
this.onConnect = async (connection, ctx) => {
|
|
@@ -610,16 +851,12 @@ var Think = class Think extends Agent {
|
|
|
610
851
|
}
|
|
611
852
|
}
|
|
612
853
|
const chatTurnBody = async () => {
|
|
613
|
-
if (this.waitForMcpConnections) {
|
|
614
|
-
const timeout = typeof this.waitForMcpConnections === "object" ? this.waitForMcpConnections.timeout : 1e4;
|
|
615
|
-
await this.mcp.waitForConnections({ timeout });
|
|
616
|
-
}
|
|
617
854
|
const result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
|
|
618
855
|
agent: this,
|
|
619
856
|
connection,
|
|
620
857
|
request: void 0,
|
|
621
858
|
email: void 0
|
|
622
|
-
}, () => this.
|
|
859
|
+
}, () => this._runInferenceLoop({
|
|
623
860
|
signal: abortSignal,
|
|
624
861
|
clientTools: clientToolsForTurn,
|
|
625
862
|
body: bodyForTurn,
|
|
@@ -701,30 +938,35 @@ var Think = class Think extends Agent {
|
|
|
701
938
|
let streamAborted = false;
|
|
702
939
|
let streamError;
|
|
703
940
|
try {
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
941
|
+
this._insideInferenceLoop = true;
|
|
942
|
+
try {
|
|
943
|
+
for await (const chunk of result.toUIMessageStream()) {
|
|
944
|
+
if (abortSignal?.aborted) {
|
|
945
|
+
streamAborted = true;
|
|
946
|
+
break;
|
|
947
|
+
}
|
|
948
|
+
const { action } = accumulator.applyChunk(chunk);
|
|
949
|
+
if (action?.type === "error") {
|
|
950
|
+
this._broadcastChat({
|
|
951
|
+
type: MSG_CHAT_RESPONSE,
|
|
952
|
+
id: requestId,
|
|
953
|
+
body: action.error,
|
|
954
|
+
done: false,
|
|
955
|
+
error: true
|
|
956
|
+
});
|
|
957
|
+
continue;
|
|
958
|
+
}
|
|
959
|
+
const chunkBody = JSON.stringify(chunk);
|
|
960
|
+
this._resumableStream.storeChunk(streamId, chunkBody);
|
|
711
961
|
this._broadcastChat({
|
|
712
962
|
type: MSG_CHAT_RESPONSE,
|
|
713
963
|
id: requestId,
|
|
714
|
-
body:
|
|
715
|
-
done: false
|
|
716
|
-
error: true
|
|
964
|
+
body: chunkBody,
|
|
965
|
+
done: false
|
|
717
966
|
});
|
|
718
|
-
continue;
|
|
719
967
|
}
|
|
720
|
-
|
|
721
|
-
this.
|
|
722
|
-
this._broadcastChat({
|
|
723
|
-
type: MSG_CHAT_RESPONSE,
|
|
724
|
-
id: requestId,
|
|
725
|
-
body: chunkBody,
|
|
726
|
-
done: false
|
|
727
|
-
});
|
|
968
|
+
} finally {
|
|
969
|
+
this._insideInferenceLoop = false;
|
|
728
970
|
}
|
|
729
971
|
this._resumableStream.complete(streamId);
|
|
730
972
|
this._pendingResumeConnections.clear();
|
|
@@ -777,8 +1019,7 @@ var Think = class Think extends Agent {
|
|
|
777
1019
|
}
|
|
778
1020
|
}
|
|
779
1021
|
_persistAssistantMessage(msg, parentId) {
|
|
780
|
-
const
|
|
781
|
-
const safe = this.sanitizeMessageForPersistence(sized);
|
|
1022
|
+
const safe = enforceRowSizeLimit(sanitizeMessage(msg));
|
|
782
1023
|
if (this.session.getMessage(safe.id)) this.session.updateMessage(safe);
|
|
783
1024
|
else this.session.appendMessage(safe, parentId);
|
|
784
1025
|
}
|
|
@@ -1058,7 +1299,7 @@ var Think = class Think extends Agent {
|
|
|
1058
1299
|
connection,
|
|
1059
1300
|
request: void 0,
|
|
1060
1301
|
email: void 0
|
|
1061
|
-
}, () => this.
|
|
1302
|
+
}, () => this._runInferenceLoop({
|
|
1062
1303
|
signal: abortSignal,
|
|
1063
1304
|
clientTools,
|
|
1064
1305
|
body: this._lastBody,
|
|
@@ -1139,6 +1380,6 @@ var Think = class Think extends Agent {
|
|
|
1139
1380
|
Think.CHAT_FIBER_NAME = "__cf_internal_chat_turn";
|
|
1140
1381
|
Think.MESSAGE_DEBOUNCE_MS = 750;
|
|
1141
1382
|
//#endregion
|
|
1142
|
-
export { Session, Think };
|
|
1383
|
+
export { Session, Think, Workspace };
|
|
1143
1384
|
|
|
1144
1385
|
//# sourceMappingURL=think.js.map
|