@cloudflare/think 0.1.2 → 0.2.1
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/{classPrivateFieldSet2-D-GfNNJe.js → classPrivateFieldGet2-DZKvdPZj.js} +6 -6
- 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/{index-CAMRySsy.d.ts → manager-DCbSiSWT.d.ts} +106 -41
- package/dist/{manager-UjPxAz2E.js → manager-dtoAI3A6.js} +115 -8
- package/dist/manager-dtoAI3A6.js.map +1 -0
- package/dist/think.d.ts +518 -82
- package/dist/think.js +1019 -352
- package/dist/think.js.map +1 -1
- 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 +6 -9
- package/dist/manager-UjPxAz2E.js.map +0 -1
package/dist/think.d.ts
CHANGED
|
@@ -1,26 +1,28 @@
|
|
|
1
|
-
import { LanguageModel, ModelMessage, ToolSet, UIMessage } from "ai";
|
|
2
|
-
import { Agent } from "agents";
|
|
3
1
|
import {
|
|
4
|
-
|
|
2
|
+
i as ExtensionManifest,
|
|
3
|
+
t as ExtensionManager
|
|
4
|
+
} from "./manager-DCbSiSWT.js";
|
|
5
|
+
import {
|
|
6
|
+
LanguageModel,
|
|
7
|
+
ModelMessage,
|
|
8
|
+
ToolSet,
|
|
9
|
+
UIMessage,
|
|
10
|
+
streamText
|
|
11
|
+
} from "ai";
|
|
12
|
+
import {
|
|
13
|
+
Agent,
|
|
5
14
|
FiberContext,
|
|
6
|
-
FiberMethods,
|
|
7
|
-
FiberMethods as FiberMethods$1,
|
|
8
15
|
FiberRecoveryContext,
|
|
9
|
-
|
|
10
|
-
} from "agents
|
|
11
|
-
import { ClientToolSchema } from "agents/chat";
|
|
16
|
+
FiberRecoveryContext as FiberRecoveryContext$1
|
|
17
|
+
} from "agents";
|
|
18
|
+
import { ClientToolSchema, MessagePart } from "agents/chat";
|
|
19
|
+
import {
|
|
20
|
+
Session,
|
|
21
|
+
Session as Session$1
|
|
22
|
+
} from "agents/experimental/memory/session";
|
|
23
|
+
import { Workspace, Workspace as Workspace$1 } from "@cloudflare/shell";
|
|
12
24
|
|
|
13
25
|
//#region src/think.d.ts
|
|
14
|
-
type ThinkBaseConstructor = {
|
|
15
|
-
new <
|
|
16
|
-
Env extends Cloudflare.Env = Cloudflare.Env,
|
|
17
|
-
State = unknown,
|
|
18
|
-
Props extends Record<string, unknown> = Record<string, unknown>
|
|
19
|
-
>(
|
|
20
|
-
ctx: DurableObjectState,
|
|
21
|
-
env: Env
|
|
22
|
-
): Agent<Env, State, Props> & FiberMethods$1;
|
|
23
|
-
};
|
|
24
26
|
/**
|
|
25
27
|
* Callback interface for streaming chat events from a Think sub-agent.
|
|
26
28
|
*
|
|
@@ -33,7 +35,7 @@ interface StreamCallback {
|
|
|
33
35
|
onError?(error: string): void | Promise<void>;
|
|
34
36
|
}
|
|
35
37
|
/**
|
|
36
|
-
* Minimal interface for the result of
|
|
38
|
+
* Minimal interface for the result of the inference loop.
|
|
37
39
|
* The AI SDK's `streamText()` result satisfies this interface.
|
|
38
40
|
*/
|
|
39
41
|
interface StreamableResult {
|
|
@@ -47,15 +49,202 @@ interface ChatOptions {
|
|
|
47
49
|
tools?: ToolSet;
|
|
48
50
|
}
|
|
49
51
|
/**
|
|
50
|
-
*
|
|
52
|
+
* Result returned by `saveMessages()` and `continueLastTurn()`.
|
|
53
|
+
*/
|
|
54
|
+
type SaveMessagesResult = {
|
|
55
|
+
requestId: string;
|
|
56
|
+
status: "completed" | "skipped";
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* Context passed to `onChatRecovery` when an interrupted chat stream
|
|
60
|
+
* is detected after DO restart.
|
|
61
|
+
*/
|
|
62
|
+
type ChatRecoveryContext = {
|
|
63
|
+
streamId: string;
|
|
64
|
+
requestId: string;
|
|
65
|
+
partialText: string;
|
|
66
|
+
partialParts: MessagePart[];
|
|
67
|
+
recoveryData: unknown | null;
|
|
68
|
+
messages: UIMessage[];
|
|
69
|
+
lastBody?: Record<string, unknown>;
|
|
70
|
+
lastClientTools?: ClientToolSchema[];
|
|
71
|
+
};
|
|
72
|
+
/**
|
|
73
|
+
* Options returned from `onChatRecovery` to control recovery behavior.
|
|
74
|
+
*/
|
|
75
|
+
type ChatRecoveryOptions = {
|
|
76
|
+
persist?: boolean;
|
|
77
|
+
continue?: boolean;
|
|
78
|
+
};
|
|
79
|
+
/**
|
|
80
|
+
* A chat turn request. Built automatically by each entry path
|
|
81
|
+
* (WebSocket, chat(), saveMessages, auto-continuation) and passed
|
|
82
|
+
* to Think's inference loop.
|
|
51
83
|
*/
|
|
52
|
-
interface
|
|
84
|
+
interface TurnInput {
|
|
53
85
|
signal?: AbortSignal;
|
|
54
|
-
tools
|
|
86
|
+
/** Extra tools from the caller (e.g. chat() options) — highest merge priority. */
|
|
87
|
+
callerTools?: ToolSet;
|
|
55
88
|
/** Client-provided tool schemas for dynamic tool registration. */
|
|
56
89
|
clientTools?: ClientToolSchema[];
|
|
90
|
+
/** Custom body fields from the client request. */
|
|
91
|
+
body?: Record<string, unknown>;
|
|
92
|
+
/** Whether this is a continuation turn (auto-continue after tool result, recovery). */
|
|
93
|
+
continuation: boolean;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Context passed to the `beforeTurn` hook.
|
|
97
|
+
* Contains everything Think assembled — the hook can inspect and override.
|
|
98
|
+
*/
|
|
99
|
+
interface TurnContext {
|
|
100
|
+
/** Assembled system prompt (from context blocks or getSystemPrompt fallback). */
|
|
101
|
+
system: string;
|
|
102
|
+
/** Assembled model messages (truncated, pruned). */
|
|
103
|
+
messages: ModelMessage[];
|
|
104
|
+
/** Merged tool set (workspace + getTools + session + MCP + client + caller). */
|
|
105
|
+
tools: ToolSet;
|
|
106
|
+
/** The language model from getModel(). */
|
|
107
|
+
model: LanguageModel;
|
|
108
|
+
/** Whether this is a continuation turn. */
|
|
109
|
+
continuation: boolean;
|
|
110
|
+
/** Custom body fields from the client request. */
|
|
111
|
+
body?: Record<string, unknown>;
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Configuration returned by the `beforeTurn` hook to override defaults.
|
|
115
|
+
* All fields are optional — return only what you want to change.
|
|
116
|
+
*/
|
|
117
|
+
interface TurnConfig {
|
|
118
|
+
/** Override the model for this turn (e.g. cheap model for continuations). */
|
|
119
|
+
model?: LanguageModel;
|
|
120
|
+
/** Override the assembled system prompt. */
|
|
121
|
+
system?: string;
|
|
122
|
+
/** Override the assembled messages. */
|
|
123
|
+
messages?: ModelMessage[];
|
|
124
|
+
/** Extra tools to merge (additive — spread on top of existing tools). */
|
|
125
|
+
tools?: ToolSet;
|
|
126
|
+
/** Limit which tools the model can call (AI SDK activeTools). */
|
|
127
|
+
activeTools?: string[];
|
|
128
|
+
/** Force a specific tool call (AI SDK toolChoice). */
|
|
129
|
+
toolChoice?: Parameters<typeof streamText>[0]["toolChoice"];
|
|
130
|
+
/** Override maxSteps for this turn. */
|
|
131
|
+
maxSteps?: number;
|
|
132
|
+
/** Provider-specific options (AI SDK providerOptions). */
|
|
133
|
+
providerOptions?: Record<string, unknown>;
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Context passed to the `beforeToolCall` hook when the model
|
|
137
|
+
* produces a tool call, before the tool's execute function runs.
|
|
138
|
+
*/
|
|
139
|
+
interface ToolCallContext {
|
|
140
|
+
/** Name of the tool being called. */
|
|
141
|
+
toolName: string;
|
|
142
|
+
/** Arguments the model provided. */
|
|
143
|
+
args: Record<string, unknown>;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Decision returned by `beforeToolCall` to control tool execution.
|
|
147
|
+
* Return void/undefined to allow execution with original args.
|
|
148
|
+
*
|
|
149
|
+
* Discriminated union — each action has a clear, non-overlapping meaning:
|
|
150
|
+
* - `allow` — execute the tool (optionally with modified args)
|
|
151
|
+
* - `block` — don't execute; return `reason` as the tool result so the model can adjust
|
|
152
|
+
* - `substitute` — don't execute; return `result` as the tool result (afterToolCall still fires)
|
|
153
|
+
*/
|
|
154
|
+
type ToolCallDecision =
|
|
155
|
+
| {
|
|
156
|
+
action: "allow" /** Modified arguments — tool executes with these instead of the originals. */;
|
|
157
|
+
args?: Record<string, unknown>;
|
|
158
|
+
}
|
|
159
|
+
| {
|
|
160
|
+
action: "block" /** Returned as the tool result so the model can adjust. */;
|
|
161
|
+
reason?: string;
|
|
162
|
+
}
|
|
163
|
+
| {
|
|
164
|
+
action: "substitute" /** The substitute tool result — model sees this instead of real execution. */;
|
|
165
|
+
result: unknown /** Optional arg attribution for the afterToolCall log. */;
|
|
166
|
+
args?: Record<string, unknown>;
|
|
167
|
+
};
|
|
168
|
+
/**
|
|
169
|
+
* Context passed to the `afterToolCall` hook after a tool executes.
|
|
170
|
+
*/
|
|
171
|
+
interface ToolCallResultContext {
|
|
172
|
+
/** Name of the tool that was called. */
|
|
173
|
+
toolName: string;
|
|
174
|
+
/** Arguments the tool was called with (may be modified by beforeToolCall). */
|
|
175
|
+
args: Record<string, unknown>;
|
|
176
|
+
/** The result returned by the tool (or substitute from beforeToolCall). */
|
|
177
|
+
result: unknown;
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Context passed to the `onStepFinish` hook after each step completes.
|
|
181
|
+
* Wraps the AI SDK's onStepFinish callback data.
|
|
182
|
+
*/
|
|
183
|
+
type StepContext = {
|
|
184
|
+
/** The type of step that completed. */ stepType:
|
|
185
|
+
| "initial"
|
|
186
|
+
| "continue"
|
|
187
|
+
| "tool-result" /** Text generated in this step. */;
|
|
188
|
+
text: string /** Tool calls made in this step. */;
|
|
189
|
+
toolCalls: unknown[] /** Tool results received in this step. */;
|
|
190
|
+
toolResults: unknown[] /** Why the step finished. */;
|
|
191
|
+
finishReason: string /** Token usage for this step. */;
|
|
192
|
+
usage: {
|
|
193
|
+
inputTokens: number;
|
|
194
|
+
outputTokens: number;
|
|
195
|
+
};
|
|
196
|
+
};
|
|
197
|
+
/**
|
|
198
|
+
* Context passed to the `onChunk` hook for each streaming chunk.
|
|
199
|
+
* Wraps the AI SDK's onChunk callback data.
|
|
200
|
+
*/
|
|
201
|
+
type ChunkContext = {
|
|
202
|
+
/** The chunk data from the AI SDK stream. */ chunk: unknown;
|
|
203
|
+
};
|
|
204
|
+
/**
|
|
205
|
+
* Configuration for a sandboxed extension, returned by getExtensions().
|
|
206
|
+
*/
|
|
207
|
+
interface ExtensionConfig {
|
|
208
|
+
/** Extension manifest (name, version, permissions, contributions). */
|
|
209
|
+
manifest: ExtensionManifest;
|
|
210
|
+
/** JavaScript source code defining the extension's tools. */
|
|
211
|
+
source: string;
|
|
57
212
|
}
|
|
58
|
-
|
|
213
|
+
/**
|
|
214
|
+
* Controls how overlapping user submit requests behave while another
|
|
215
|
+
* chat turn is already active or queued.
|
|
216
|
+
*
|
|
217
|
+
* - `"queue"` (default) — queue every submit and process them in order.
|
|
218
|
+
* - `"latest"` — keep only the latest overlapping submit; superseded submits
|
|
219
|
+
* still persist their user messages, but do not start their own model turn.
|
|
220
|
+
* - `"merge"` — like latest, but all overlapping user messages remain in
|
|
221
|
+
* the conversation history. The model sees them all in one turn.
|
|
222
|
+
* - `"drop"` — ignore overlapping submits entirely (messages not persisted).
|
|
223
|
+
* - `{ strategy: "debounce" }` — trailing-edge latest with a quiet window.
|
|
224
|
+
*
|
|
225
|
+
* Only applies to `submit-message` requests. Regenerations, tool
|
|
226
|
+
* continuations, approvals, clears, `saveMessages`, and `continueLastTurn`
|
|
227
|
+
* keep their existing serialized behavior.
|
|
228
|
+
*/
|
|
229
|
+
type MessageConcurrency =
|
|
230
|
+
| "queue"
|
|
231
|
+
| "latest"
|
|
232
|
+
| "merge"
|
|
233
|
+
| "drop"
|
|
234
|
+
| {
|
|
235
|
+
strategy: "debounce";
|
|
236
|
+
debounceMs?: number;
|
|
237
|
+
};
|
|
238
|
+
/**
|
|
239
|
+
* Result passed to `onChatResponse` after a chat turn completes.
|
|
240
|
+
*/
|
|
241
|
+
type ChatResponseResult = {
|
|
242
|
+
message: UIMessage;
|
|
243
|
+
requestId: string;
|
|
244
|
+
continuation: boolean;
|
|
245
|
+
status: "completed" | "error" | "aborted";
|
|
246
|
+
error?: string;
|
|
247
|
+
};
|
|
59
248
|
/**
|
|
60
249
|
* An opinionated chat agent base class.
|
|
61
250
|
*
|
|
@@ -64,21 +253,11 @@ declare const Think_base: ThinkBaseConstructor;
|
|
|
64
253
|
declare class Think<
|
|
65
254
|
Env extends Cloudflare.Env = Cloudflare.Env,
|
|
66
255
|
Config = Record<string, unknown>
|
|
67
|
-
> extends
|
|
256
|
+
> extends Agent<Env> {
|
|
68
257
|
#private;
|
|
69
|
-
/** In-memory messages for the current conversation. Authoritative after load. */
|
|
70
|
-
messages: UIMessage[];
|
|
71
|
-
/**
|
|
72
|
-
* Enable durable fiber recovery on start. Set to `true` to
|
|
73
|
-
* automatically recover interrupted fibers when the DO restarts.
|
|
74
|
-
*
|
|
75
|
-
* @experimental
|
|
76
|
-
*/
|
|
77
|
-
fibers: boolean;
|
|
78
258
|
/**
|
|
79
|
-
* Wait for MCP server connections to be ready before
|
|
80
|
-
*
|
|
81
|
-
* the full set of MCP-discovered tools inside `onChatMessage`.
|
|
259
|
+
* Wait for MCP server connections to be ready before the inference
|
|
260
|
+
* loop. MCP tools are auto-merged into the tool set.
|
|
82
261
|
*
|
|
83
262
|
* Set to `true` for a default 10s timeout, or `{ timeout: ms }`
|
|
84
263
|
* for a custom timeout. Defaults to `false` (no waiting).
|
|
@@ -89,70 +268,239 @@ declare class Think<
|
|
|
89
268
|
timeout: number;
|
|
90
269
|
};
|
|
91
270
|
/**
|
|
92
|
-
*
|
|
93
|
-
*
|
|
94
|
-
*
|
|
271
|
+
* Controls how overlapping user submit requests behave while another
|
|
272
|
+
* chat turn is already active or queued.
|
|
273
|
+
*
|
|
274
|
+
* @default "queue"
|
|
275
|
+
*/
|
|
276
|
+
messageConcurrency: MessageConcurrency;
|
|
277
|
+
/**
|
|
278
|
+
* When true, chat turns are wrapped in `runFiber` for durable execution.
|
|
279
|
+
* Enables `onChatRecovery` hook and `this.stash()` during streaming.
|
|
280
|
+
*/
|
|
281
|
+
unstable_chatRecovery: boolean;
|
|
282
|
+
static readonly CHAT_FIBER_NAME = "__cf_internal_chat_turn";
|
|
283
|
+
/** The conversation session — messages, context, compaction, search. */
|
|
284
|
+
session: Session$1;
|
|
285
|
+
/**
|
|
286
|
+
* WorkerLoader binding for sandboxed extensions.
|
|
287
|
+
* Set this to enable `getExtensions()` and dynamic extension loading.
|
|
288
|
+
*/
|
|
289
|
+
extensionLoader?: WorkerLoader;
|
|
290
|
+
/**
|
|
291
|
+
* Extension manager — created automatically when `extensionLoader` is set.
|
|
292
|
+
* Use for dynamic `load()` / `unload()` at runtime.
|
|
293
|
+
*/
|
|
294
|
+
extensionManager?: ExtensionManager;
|
|
295
|
+
/**
|
|
296
|
+
* Workspace filesystem backed by the DO's SQLite storage.
|
|
297
|
+
* Available in `getTools()` and lifecycle hooks.
|
|
95
298
|
*
|
|
96
|
-
*
|
|
97
|
-
*
|
|
299
|
+
* Override to add R2 spillover for large files:
|
|
300
|
+
* ```typescript
|
|
301
|
+
* override workspace = new Workspace({
|
|
302
|
+
* sql: this.ctx.storage.sql,
|
|
303
|
+
* r2: this.env.R2,
|
|
304
|
+
* name: () => this.name
|
|
305
|
+
* });
|
|
306
|
+
* ```
|
|
307
|
+
*/
|
|
308
|
+
workspace: Workspace$1;
|
|
309
|
+
constructor(ctx: DurableObjectState, env: Env);
|
|
310
|
+
/**
|
|
311
|
+
* Conversation history. Computed from the active session.
|
|
312
|
+
* Always fresh — reads from Session's tree-structured storage.
|
|
98
313
|
*/
|
|
99
|
-
|
|
100
|
-
private
|
|
101
|
-
private _storageReady;
|
|
102
|
-
private _abortControllers;
|
|
314
|
+
get messages(): UIMessage[];
|
|
315
|
+
private _aborts;
|
|
103
316
|
private _turnQueue;
|
|
104
317
|
private _resumableStream;
|
|
105
318
|
private _pendingResumeConnections;
|
|
106
319
|
private _lastClientTools;
|
|
320
|
+
private _lastBody;
|
|
107
321
|
private _continuation;
|
|
108
322
|
private _continuationTimer;
|
|
109
|
-
private
|
|
323
|
+
private _insideResponseHook;
|
|
324
|
+
private _insideInferenceLoop;
|
|
325
|
+
private _pendingInteractionPromise;
|
|
326
|
+
private _submitSequence;
|
|
327
|
+
private _latestOverlappingSubmitSequence;
|
|
328
|
+
private _activeDebounceTimer;
|
|
329
|
+
private _activeDebounceResolve;
|
|
330
|
+
private static MESSAGE_DEBOUNCE_MS;
|
|
110
331
|
/**
|
|
111
332
|
* Persist a typed configuration object.
|
|
112
|
-
* Stored in
|
|
333
|
+
* Stored in Session's assistant_config table — survives restarts and hibernation.
|
|
113
334
|
*/
|
|
114
335
|
configure(config: Config): void;
|
|
115
336
|
/**
|
|
116
337
|
* Read the persisted configuration, or null if never configured.
|
|
117
338
|
*/
|
|
118
339
|
getConfig(): Config | null;
|
|
119
|
-
|
|
340
|
+
private _configSet;
|
|
341
|
+
private _configGet;
|
|
342
|
+
private _configDelete;
|
|
343
|
+
private _sessionId;
|
|
120
344
|
/**
|
|
121
345
|
* Return the language model to use for inference.
|
|
122
|
-
* Must be overridden by subclasses
|
|
123
|
-
* `onChatMessage` implementation (the agentic loop).
|
|
346
|
+
* Must be overridden by subclasses.
|
|
124
347
|
*/
|
|
125
348
|
getModel(): LanguageModel;
|
|
126
|
-
/**
|
|
349
|
+
/**
|
|
350
|
+
* Return the system prompt for the assistant.
|
|
351
|
+
* Used as fallback when no context blocks are configured via `configureSession`.
|
|
352
|
+
*/
|
|
127
353
|
getSystemPrompt(): string;
|
|
128
354
|
/** Return the tools available to the assistant. */
|
|
129
355
|
getTools(): ToolSet;
|
|
130
|
-
/**
|
|
131
|
-
|
|
356
|
+
/** Maximum number of tool-call steps per turn. Override via property or per-turn via TurnConfig. */
|
|
357
|
+
maxSteps: number;
|
|
358
|
+
/**
|
|
359
|
+
* Configure the session. Called once during `onStart`.
|
|
360
|
+
* Override to add context blocks, compaction, search, skills.
|
|
361
|
+
*
|
|
362
|
+
* @example
|
|
363
|
+
* ```typescript
|
|
364
|
+
* configureSession(session: Session) {
|
|
365
|
+
* return session
|
|
366
|
+
* .withContext("memory", { description: "Learned facts", maxTokens: 2000 })
|
|
367
|
+
* .withCachedPrompt();
|
|
368
|
+
* }
|
|
369
|
+
* ```
|
|
370
|
+
*/
|
|
371
|
+
configureSession(session: Session$1): Session$1 | Promise<Session$1>;
|
|
372
|
+
/**
|
|
373
|
+
* Return sandboxed extension configurations. Defines load order,
|
|
374
|
+
* which determines hook execution order.
|
|
375
|
+
* Requires `extensionLoader` to be set.
|
|
376
|
+
*/
|
|
377
|
+
getExtensions(): ExtensionConfig[];
|
|
132
378
|
/**
|
|
133
|
-
*
|
|
134
|
-
*
|
|
135
|
-
*
|
|
379
|
+
* Called before `streamText` — inspect the assembled context and
|
|
380
|
+
* return overrides. Think assembles tools, system prompt, and messages
|
|
381
|
+
* internally; this hook sees the result and can override any part.
|
|
382
|
+
*
|
|
383
|
+
* Return `void` to accept all defaults.
|
|
384
|
+
*
|
|
385
|
+
* @example Switch model for continuations
|
|
386
|
+
* ```typescript
|
|
387
|
+
* beforeTurn(ctx: TurnContext) {
|
|
388
|
+
* if (ctx.continuation) return { model: this.cheapModel };
|
|
389
|
+
* }
|
|
390
|
+
* ```
|
|
391
|
+
*
|
|
392
|
+
* @example Restrict active tools
|
|
393
|
+
* ```typescript
|
|
394
|
+
* beforeTurn(ctx: TurnContext) {
|
|
395
|
+
* return { activeTools: ["read", "write"] };
|
|
396
|
+
* }
|
|
397
|
+
* ```
|
|
398
|
+
*/
|
|
399
|
+
beforeTurn(_ctx: TurnContext): TurnConfig | void | Promise<TurnConfig | void>;
|
|
400
|
+
/**
|
|
401
|
+
* Called when the model produces a tool call. Currently fires
|
|
402
|
+
* **after** tool execution (via `onStepFinish` data) — observation only.
|
|
403
|
+
*
|
|
404
|
+
* **Known limitation:** `block` and `substitute` actions in the returned
|
|
405
|
+
* `ToolCallDecision` are not yet functional. The AI SDK's `streamText`
|
|
406
|
+
* does not expose a pre-execution interception point for tool calls
|
|
407
|
+
* in the Workers runtime. The types are in place for when this becomes
|
|
408
|
+
* possible (see plan: "Known limitations — Phase 1").
|
|
409
|
+
*
|
|
410
|
+
* Only fires for server-side tools (tools with `execute`).
|
|
411
|
+
* Client tools are handled on the client — Think can't intercept them.
|
|
412
|
+
*
|
|
413
|
+
* Return `void` to accept default behavior.
|
|
414
|
+
*
|
|
415
|
+
* @example Log tool calls
|
|
416
|
+
* ```typescript
|
|
417
|
+
* beforeToolCall(ctx: ToolCallContext) {
|
|
418
|
+
* console.log(`Tool called: ${ctx.toolName}`, ctx.args);
|
|
419
|
+
* }
|
|
420
|
+
* ```
|
|
136
421
|
*/
|
|
137
|
-
|
|
422
|
+
beforeToolCall(
|
|
423
|
+
_ctx: ToolCallContext
|
|
424
|
+
): ToolCallDecision | void | Promise<ToolCallDecision | void>;
|
|
138
425
|
/**
|
|
139
|
-
*
|
|
426
|
+
* Called after a tool executes (or a substitute result is provided).
|
|
427
|
+
* Does NOT fire when `beforeToolCall` blocks with no substitute result.
|
|
140
428
|
*
|
|
141
|
-
*
|
|
142
|
-
|
|
143
|
-
|
|
429
|
+
* Override for logging, metrics, or result inspection.
|
|
430
|
+
*/
|
|
431
|
+
afterToolCall(_ctx: ToolCallResultContext): void | Promise<void>;
|
|
432
|
+
/**
|
|
433
|
+
* Called after each step completes (initial, continue, tool-result).
|
|
434
|
+
* Override for step-level logging or analytics.
|
|
435
|
+
*/
|
|
436
|
+
onStepFinish(_ctx: StepContext): void | Promise<void>;
|
|
437
|
+
/**
|
|
438
|
+
* Called for each streaming chunk. High-frequency — fires per token.
|
|
439
|
+
* Override for streaming analytics, progress indicators, or token counting.
|
|
440
|
+
* Observational only (void return).
|
|
441
|
+
*/
|
|
442
|
+
onChunk(_ctx: ChunkContext): void | Promise<void>;
|
|
443
|
+
/**
|
|
444
|
+
* Called after a chat turn completes and the assistant message has been
|
|
445
|
+
* persisted. The turn lock is released before this hook runs, so it is
|
|
446
|
+
* safe to call other methods from inside.
|
|
144
447
|
*
|
|
145
|
-
*
|
|
448
|
+
* Fires for all turn completion paths: WebSocket chat requests,
|
|
449
|
+
* sub-agent RPC, and auto-continuation.
|
|
146
450
|
*
|
|
147
|
-
*
|
|
148
|
-
* return value satisfies this interface.
|
|
451
|
+
* Override for logging, chaining, analytics, usage tracking.
|
|
149
452
|
*/
|
|
150
|
-
|
|
453
|
+
onChatResponse(_result: ChatResponseResult): void | Promise<void>;
|
|
151
454
|
/**
|
|
152
455
|
* Handle an error that occurred during a chat turn.
|
|
153
456
|
* Override to customize error handling (e.g. logging, metrics).
|
|
154
457
|
*/
|
|
155
458
|
onChatError(error: unknown): unknown;
|
|
459
|
+
private _initializeExtensions;
|
|
460
|
+
/**
|
|
461
|
+
* The single convergence point for all chat turn entry paths.
|
|
462
|
+
* Merges tools, assembles context, fires lifecycle hooks, wraps tools
|
|
463
|
+
* for interception, and calls streamText.
|
|
464
|
+
*/
|
|
465
|
+
private _runInferenceLoop;
|
|
466
|
+
/** @internal Test seam — override in test agents to wrap the stream (e.g. error injection). */
|
|
467
|
+
protected _transformInferenceResult(
|
|
468
|
+
result: StreamableResult
|
|
469
|
+
): StreamableResult;
|
|
470
|
+
/** Default hook timeout in milliseconds. */
|
|
471
|
+
hookTimeout: number;
|
|
472
|
+
/**
|
|
473
|
+
* Pipeline beforeTurn through sandboxed extensions in load order.
|
|
474
|
+
* Each extension sees the accumulated state from prior extensions
|
|
475
|
+
* (snapshot is rebuilt after each extension's modifications).
|
|
476
|
+
* Results are merged with last-write-wins for scalar fields.
|
|
477
|
+
* Extensions that don't subscribe to beforeTurn are skipped.
|
|
478
|
+
*/
|
|
479
|
+
private _pipelineExtensionBeforeTurn;
|
|
480
|
+
_hostReadFile(path: string): Promise<string | null>;
|
|
481
|
+
_hostWriteFile(path: string, content: string): Promise<void>;
|
|
482
|
+
_hostDeleteFile(path: string): Promise<boolean>;
|
|
483
|
+
_hostListFiles(dir: string): Promise<
|
|
484
|
+
Array<{
|
|
485
|
+
name: string;
|
|
486
|
+
type: string;
|
|
487
|
+
size: number;
|
|
488
|
+
path: string;
|
|
489
|
+
}>
|
|
490
|
+
>;
|
|
491
|
+
_hostGetContext(label: string): Promise<string | null>;
|
|
492
|
+
_hostSetContext(label: string, content: string): Promise<void>;
|
|
493
|
+
_hostGetMessages(limit?: number): Promise<
|
|
494
|
+
Array<{
|
|
495
|
+
id: string;
|
|
496
|
+
role: string;
|
|
497
|
+
content: string;
|
|
498
|
+
}>
|
|
499
|
+
>;
|
|
500
|
+
_hostSendMessage(content: string): Promise<void>;
|
|
501
|
+
_hostGetSessionInfo(): Promise<{
|
|
502
|
+
messageCount: number;
|
|
503
|
+
}>;
|
|
156
504
|
/**
|
|
157
505
|
* Run a chat turn: persist the user message, run the agentic loop,
|
|
158
506
|
* stream UIMessageChunk events via callback, and persist the
|
|
@@ -169,30 +517,106 @@ declare class Think<
|
|
|
169
517
|
): Promise<void>;
|
|
170
518
|
/** Get the conversation history as UIMessage[]. */
|
|
171
519
|
getMessages(): UIMessage[];
|
|
172
|
-
/** Clear all messages from storage
|
|
520
|
+
/** Clear all messages from storage. */
|
|
173
521
|
clearMessages(): void;
|
|
522
|
+
/**
|
|
523
|
+
* Inject messages and trigger a model turn — without a WebSocket request.
|
|
524
|
+
*
|
|
525
|
+
* Use for scheduled responses, webhook-triggered turns, proactive agents,
|
|
526
|
+
* or chaining from `onChatResponse`.
|
|
527
|
+
*
|
|
528
|
+
* Accepts static messages or a callback that derives messages from the
|
|
529
|
+
* current state (useful when multiple calls queue up — the callback runs
|
|
530
|
+
* with the latest messages when the turn actually starts).
|
|
531
|
+
*
|
|
532
|
+
* @example Scheduled follow-up
|
|
533
|
+
* ```typescript
|
|
534
|
+
* async onScheduled() {
|
|
535
|
+
* await this.saveMessages([{
|
|
536
|
+
* id: crypto.randomUUID(),
|
|
537
|
+
* role: "user",
|
|
538
|
+
* parts: [{ type: "text", text: "Time for your daily summary." }]
|
|
539
|
+
* }]);
|
|
540
|
+
* }
|
|
541
|
+
* ```
|
|
542
|
+
*
|
|
543
|
+
* @example Function form
|
|
544
|
+
* ```typescript
|
|
545
|
+
* await this.saveMessages((current) => [
|
|
546
|
+
* ...current,
|
|
547
|
+
* { id: crypto.randomUUID(), role: "user", parts: [{ type: "text", text: "Continue." }] }
|
|
548
|
+
* ]);
|
|
549
|
+
* ```
|
|
550
|
+
*/
|
|
551
|
+
saveMessages(
|
|
552
|
+
messages:
|
|
553
|
+
| UIMessage[]
|
|
554
|
+
| ((currentMessages: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>)
|
|
555
|
+
): Promise<SaveMessagesResult>;
|
|
556
|
+
/**
|
|
557
|
+
* Run a new LLM call following the last assistant message.
|
|
558
|
+
*
|
|
559
|
+
* The model sees the full conversation (including the last assistant
|
|
560
|
+
* response) and generates a new response. The new response is persisted
|
|
561
|
+
* as a separate assistant message. Building block for chat recovery
|
|
562
|
+
* (Phase 4), "generate more" buttons, and self-correction.
|
|
563
|
+
*
|
|
564
|
+
* Note: this creates a new message, not an append to the existing one.
|
|
565
|
+
* True continuation-as-append (chunk rewriting) is planned for Phase 4.
|
|
566
|
+
*
|
|
567
|
+
* Returns early with `status: "skipped"` if there is no assistant message
|
|
568
|
+
* to continue from.
|
|
569
|
+
*/
|
|
570
|
+
protected continueLastTurn(
|
|
571
|
+
body?: Record<string, unknown>
|
|
572
|
+
): Promise<SaveMessagesResult>;
|
|
174
573
|
private _setupProtocolHandlers;
|
|
175
|
-
private
|
|
574
|
+
private _handleProtocolEvent;
|
|
575
|
+
private _handleStreamResumeRequest;
|
|
576
|
+
private _handleStreamResumeAck;
|
|
176
577
|
private _handleChatRequest;
|
|
578
|
+
/**
|
|
579
|
+
* Abort the active turn, invalidate queued turns, and reset
|
|
580
|
+
* concurrency/continuation state. Call this when intercepting
|
|
581
|
+
* clear events or implementing custom reset logic.
|
|
582
|
+
*
|
|
583
|
+
* Does NOT clear messages, streams, or persisted state —
|
|
584
|
+
* only turn execution state.
|
|
585
|
+
*/
|
|
586
|
+
protected resetTurnState(): void;
|
|
177
587
|
private _handleClear;
|
|
178
|
-
private _handleCancel;
|
|
179
588
|
private _streamResult;
|
|
180
|
-
private
|
|
181
|
-
private _loadMessages;
|
|
182
|
-
private _appendMessage;
|
|
183
|
-
private _upsertMessage;
|
|
184
|
-
private _clearMessages;
|
|
185
|
-
private _deleteMessages;
|
|
589
|
+
private _persistAssistantMessage;
|
|
186
590
|
private _persistClientTools;
|
|
187
591
|
private _restoreClientTools;
|
|
188
|
-
private
|
|
189
|
-
private
|
|
190
|
-
private _enforceMaxPersistedMessages;
|
|
592
|
+
private _persistBody;
|
|
593
|
+
private _restoreBody;
|
|
191
594
|
private _applyToolResult;
|
|
192
595
|
private _applyToolApproval;
|
|
596
|
+
private _applyToolUpdateToMessages;
|
|
597
|
+
protected hasPendingInteraction(): boolean;
|
|
598
|
+
protected waitUntilStable(options?: { timeout?: number }): Promise<boolean>;
|
|
599
|
+
private _awaitWithDeadline;
|
|
600
|
+
private _messageHasPendingInteraction;
|
|
601
|
+
protected _handleInternalFiberRecovery(
|
|
602
|
+
ctx: FiberRecoveryContext$1
|
|
603
|
+
): Promise<boolean>;
|
|
604
|
+
protected onChatRecovery(
|
|
605
|
+
_ctx: ChatRecoveryContext
|
|
606
|
+
): Promise<ChatRecoveryOptions>;
|
|
607
|
+
_chatRecoveryContinue(data?: { targetAssistantId?: string }): Promise<void>;
|
|
608
|
+
private _getPartialStreamText;
|
|
609
|
+
private _normalizeMessageConcurrency;
|
|
610
|
+
private _getSubmitConcurrencyDecision;
|
|
611
|
+
private _isSupersededSubmit;
|
|
612
|
+
private _waitForTimestamp;
|
|
613
|
+
private _cancelActiveDebounce;
|
|
614
|
+
private _completeSkippedRequest;
|
|
615
|
+
private _rollbackDroppedSubmit;
|
|
193
616
|
private _scheduleAutoContinuation;
|
|
194
617
|
private _fireAutoContinuation;
|
|
195
618
|
private _activateDeferredContinuation;
|
|
619
|
+
private _fireResponseHook;
|
|
196
620
|
private _notifyStreamResuming;
|
|
197
621
|
private _persistOrphanedStream;
|
|
198
622
|
private _broadcastChat;
|
|
@@ -201,15 +625,27 @@ declare class Think<
|
|
|
201
625
|
}
|
|
202
626
|
//#endregion
|
|
203
627
|
export {
|
|
204
|
-
ChatMessageOptions,
|
|
205
628
|
ChatOptions,
|
|
206
|
-
|
|
629
|
+
ChatRecoveryContext,
|
|
630
|
+
ChatRecoveryOptions,
|
|
631
|
+
ChatResponseResult,
|
|
632
|
+
ChunkContext,
|
|
633
|
+
ExtensionConfig,
|
|
207
634
|
type FiberContext,
|
|
208
|
-
type FiberMethods,
|
|
209
635
|
type FiberRecoveryContext,
|
|
210
|
-
|
|
636
|
+
MessageConcurrency,
|
|
637
|
+
SaveMessagesResult,
|
|
638
|
+
Session,
|
|
639
|
+
StepContext,
|
|
211
640
|
StreamCallback,
|
|
212
641
|
StreamableResult,
|
|
213
|
-
Think
|
|
642
|
+
Think,
|
|
643
|
+
ToolCallContext,
|
|
644
|
+
ToolCallDecision,
|
|
645
|
+
ToolCallResultContext,
|
|
646
|
+
TurnConfig,
|
|
647
|
+
TurnContext,
|
|
648
|
+
TurnInput,
|
|
649
|
+
Workspace
|
|
214
650
|
};
|
|
215
651
|
//# sourceMappingURL=think.d.ts.map
|