@cloudflare/think 0.7.2 → 0.8.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 +420 -43
- package/dist/chat-sdk-CJwYlbp9.js +669 -0
- package/dist/chat-sdk-CJwYlbp9.js.map +1 -0
- package/dist/extensions/index.d.ts +2 -2
- package/dist/{hook-proxy-5248W-ea.js → hook-proxy-DHwqL8MV.js} +1 -1
- package/dist/{hook-proxy-5248W-ea.js.map → hook-proxy-DHwqL8MV.js.map} +1 -1
- package/dist/index-CYp8VDIe.d.ts +2202 -0
- package/dist/{index-BsB4GUsL.d.ts → index-DS00xJwR.d.ts} +2 -2
- package/dist/{manager-DCbSiSWT.d.ts → manager-C1zjft70.d.ts} +1 -1
- package/dist/messengers/index.d.ts +110 -0
- package/dist/messengers/index.js +2 -0
- package/dist/messengers/telegram.d.ts +62 -0
- package/dist/messengers/telegram.js +84 -0
- package/dist/messengers/telegram.js.map +1 -0
- package/dist/think.d.ts +73 -1144
- package/dist/think.js +2370 -179
- package/dist/think.js.map +1 -1
- package/dist/tools/extensions.d.ts +1 -1
- package/dist/tools/workspace.d.ts +35 -334
- package/dist/tools/workspace.js +283 -3
- package/dist/tools/workspace.js.map +1 -1
- package/dist/workflows.d.ts +78 -0
- package/dist/workflows.js +119 -0
- package/dist/workflows.js.map +1 -0
- package/dist/workspace-Bri0ANBX.d.ts +342 -0
- package/package.json +24 -7
package/dist/think.d.ts
CHANGED
|
@@ -1,1149 +1,67 @@
|
|
|
1
|
+
import { h as WorkspaceLike } from "./workspace-Bri0ANBX.js";
|
|
1
2
|
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
* Designed to work across the sub-agent RPC boundary — implement as
|
|
59
|
-
* an RpcTarget in the parent agent and pass to `chat()`.
|
|
60
|
-
*/
|
|
61
|
-
interface ChatStartEvent {
|
|
62
|
-
requestId: string;
|
|
63
|
-
}
|
|
64
|
-
interface StreamCallback {
|
|
65
|
-
onStart?(event: ChatStartEvent): void | Promise<void>;
|
|
66
|
-
onEvent(json: string): void | Promise<void>;
|
|
67
|
-
onDone(): void | Promise<void>;
|
|
68
|
-
onError?(error: string): void | Promise<void>;
|
|
69
|
-
}
|
|
70
|
-
/**
|
|
71
|
-
* Minimal interface for the result of the inference loop.
|
|
72
|
-
* The AI SDK's `streamText()` result satisfies this interface.
|
|
73
|
-
*/
|
|
74
|
-
interface StreamableResult {
|
|
75
|
-
toUIMessageStream(options?: {
|
|
76
|
-
sendReasoning?: boolean;
|
|
77
|
-
}): AsyncIterable<unknown>;
|
|
78
|
-
}
|
|
79
|
-
/**
|
|
80
|
-
* Options for a chat turn (sub-agent RPC entry point).
|
|
81
|
-
*/
|
|
82
|
-
interface ChatOptions {
|
|
83
|
-
signal?: AbortSignal;
|
|
84
|
-
}
|
|
85
|
-
type AgentToolChildRunStatus =
|
|
86
|
-
| "starting"
|
|
87
|
-
| "running"
|
|
88
|
-
| "completed"
|
|
89
|
-
| "error"
|
|
90
|
-
| "aborted";
|
|
91
|
-
type AgentToolRunInspection<Output = unknown> = {
|
|
92
|
-
runId: string;
|
|
93
|
-
status: AgentToolChildRunStatus;
|
|
94
|
-
requestId?: string;
|
|
95
|
-
streamId?: string;
|
|
96
|
-
output?: Output;
|
|
97
|
-
summary?: string;
|
|
98
|
-
error?: string;
|
|
99
|
-
startedAt: number;
|
|
100
|
-
completedAt?: number;
|
|
101
|
-
};
|
|
102
|
-
type AgentToolStoredChunk = {
|
|
103
|
-
sequence: number;
|
|
104
|
-
body: string;
|
|
105
|
-
};
|
|
106
|
-
type ThinkSubmissionStatus =
|
|
107
|
-
| "pending"
|
|
108
|
-
| "running"
|
|
109
|
-
| "completed"
|
|
110
|
-
| "aborted"
|
|
111
|
-
| "skipped"
|
|
112
|
-
| "error";
|
|
113
|
-
type SubmitMessagesOptions = {
|
|
114
|
-
submissionId?: string;
|
|
115
|
-
idempotencyKey?: string;
|
|
116
|
-
metadata?: Record<string, unknown>;
|
|
117
|
-
};
|
|
118
|
-
type ThinkSubmissionInspection = {
|
|
119
|
-
submissionId: string;
|
|
120
|
-
idempotencyKey?: string;
|
|
121
|
-
requestId?: string;
|
|
122
|
-
status: ThinkSubmissionStatus;
|
|
123
|
-
error?: string;
|
|
124
|
-
metadata?: Record<string, unknown>;
|
|
125
|
-
createdAt: number;
|
|
126
|
-
startedAt?: number;
|
|
127
|
-
completedAt?: number;
|
|
128
|
-
};
|
|
129
|
-
type SubmitMessagesResult = ThinkSubmissionInspection & {
|
|
130
|
-
accepted: boolean;
|
|
131
|
-
};
|
|
132
|
-
type ListSubmissionsOptions = {
|
|
133
|
-
status?: ThinkSubmissionStatus | ThinkSubmissionStatus[];
|
|
134
|
-
limit?: number;
|
|
135
|
-
};
|
|
136
|
-
type DeleteSubmissionsOptions = {
|
|
137
|
-
status?: ThinkSubmissionStatus | ThinkSubmissionStatus[];
|
|
138
|
-
completedBefore?: Date;
|
|
139
|
-
limit?: number;
|
|
140
|
-
};
|
|
141
|
-
/**
|
|
142
|
-
* A chat turn request. Built automatically by each entry path
|
|
143
|
-
* (WebSocket, chat(), saveMessages, auto-continuation) and passed
|
|
144
|
-
* to Think's inference loop.
|
|
145
|
-
*/
|
|
146
|
-
interface TurnInput {
|
|
147
|
-
signal?: AbortSignal;
|
|
148
|
-
/** Client-provided tool schemas for dynamic tool registration. */
|
|
149
|
-
clientTools?: ClientToolSchema[];
|
|
150
|
-
/** Custom body fields from the client request. */
|
|
151
|
-
body?: Record<string, unknown>;
|
|
152
|
-
/** Whether this is a continuation turn (auto-continue after tool result, recovery). */
|
|
153
|
-
continuation: boolean;
|
|
154
|
-
}
|
|
155
|
-
/**
|
|
156
|
-
* Context passed to the `beforeTurn` hook.
|
|
157
|
-
* Contains everything Think assembled — the hook can inspect and override.
|
|
158
|
-
*/
|
|
159
|
-
interface TurnContext {
|
|
160
|
-
/** Assembled system prompt (from context blocks or getSystemPrompt fallback). */
|
|
161
|
-
system: string;
|
|
162
|
-
/** Assembled model messages (truncated, pruned). */
|
|
163
|
-
messages: ModelMessage[];
|
|
164
|
-
/** Merged tool set (workspace + getTools + session + MCP + client + caller). */
|
|
165
|
-
tools: ToolSet;
|
|
166
|
-
/** The language model from getModel(). */
|
|
167
|
-
model: LanguageModel;
|
|
168
|
-
/** Whether this is a continuation turn. */
|
|
169
|
-
continuation: boolean;
|
|
170
|
-
/** Custom body fields from the client request. */
|
|
171
|
-
body?: Record<string, unknown>;
|
|
172
|
-
}
|
|
173
|
-
/**
|
|
174
|
-
* Configuration returned by the `beforeTurn` hook to override defaults.
|
|
175
|
-
* All fields are optional — return only what you want to change.
|
|
176
|
-
*/
|
|
177
|
-
interface TurnConfig {
|
|
178
|
-
/** Override the model for this turn (e.g. cheap model for continuations). */
|
|
179
|
-
model?: LanguageModel;
|
|
180
|
-
/** Override the assembled system prompt. */
|
|
181
|
-
system?: string;
|
|
182
|
-
/** Override the assembled messages. */
|
|
183
|
-
messages?: ModelMessage[];
|
|
184
|
-
/** Extra tools to merge (additive — spread on top of existing tools). */
|
|
185
|
-
tools?: ToolSet;
|
|
186
|
-
/** Limit which tools the model can call (AI SDK activeTools). */
|
|
187
|
-
activeTools?: string[];
|
|
188
|
-
/** Force a specific tool call (AI SDK toolChoice). */
|
|
189
|
-
toolChoice?: Parameters<typeof streamText>[0]["toolChoice"];
|
|
190
|
-
/** Override maxSteps for this turn. */
|
|
191
|
-
maxSteps?: number;
|
|
192
|
-
/**
|
|
193
|
-
* Additional AI SDK stop conditions for ending the turn early.
|
|
194
|
-
* Think always keeps its `maxSteps` stop condition as a safety bound.
|
|
195
|
-
*/
|
|
196
|
-
stopWhen?: StopCondition$1<ToolSet> | Array<StopCondition$1<ToolSet>>;
|
|
197
|
-
/**
|
|
198
|
-
* Controls whether reasoning chunks are included in the UI message stream
|
|
199
|
-
* for this turn. Defaults to the instance-level `sendReasoning` setting.
|
|
200
|
-
*/
|
|
201
|
-
sendReasoning?: boolean;
|
|
202
|
-
/** Maximum number of tokens to generate for this turn. */
|
|
203
|
-
maxOutputTokens?: Parameters<typeof streamText>[0]["maxOutputTokens"];
|
|
204
|
-
/** Temperature setting for this turn. */
|
|
205
|
-
temperature?: Parameters<typeof streamText>[0]["temperature"];
|
|
206
|
-
/** Nucleus sampling setting for this turn. */
|
|
207
|
-
topP?: Parameters<typeof streamText>[0]["topP"];
|
|
208
|
-
/** Top-K sampling setting for this turn. */
|
|
209
|
-
topK?: Parameters<typeof streamText>[0]["topK"];
|
|
210
|
-
/** Presence penalty setting for this turn. */
|
|
211
|
-
presencePenalty?: Parameters<typeof streamText>[0]["presencePenalty"];
|
|
212
|
-
/** Frequency penalty setting for this turn. */
|
|
213
|
-
frequencyPenalty?: Parameters<typeof streamText>[0]["frequencyPenalty"];
|
|
214
|
-
/** Stop sequences for this turn. */
|
|
215
|
-
stopSequences?: Parameters<typeof streamText>[0]["stopSequences"];
|
|
216
|
-
/** Seed for deterministic sampling when supported by the model. */
|
|
217
|
-
seed?: Parameters<typeof streamText>[0]["seed"];
|
|
218
|
-
/** Maximum number of retries for this turn. Set to 0 to disable retries. */
|
|
219
|
-
maxRetries?: Parameters<typeof streamText>[0]["maxRetries"];
|
|
220
|
-
/** Timeout configuration for this turn. */
|
|
221
|
-
timeout?: Parameters<typeof streamText>[0]["timeout"];
|
|
222
|
-
/** Additional HTTP headers for provider requests on this turn. */
|
|
223
|
-
headers?: Parameters<typeof streamText>[0]["headers"];
|
|
224
|
-
/** Provider-specific options (AI SDK providerOptions). */
|
|
225
|
-
providerOptions?: Record<string, unknown>;
|
|
226
|
-
/** Optional AI SDK telemetry configuration for this turn. */
|
|
227
|
-
experimental_telemetry?: Parameters<
|
|
228
|
-
typeof streamText
|
|
229
|
-
>[0]["experimental_telemetry"];
|
|
230
|
-
/**
|
|
231
|
-
* Optional structured-output specification (AI SDK `output`).
|
|
232
|
-
* Forwarded to `streamText` so the model's final response is parsed
|
|
233
|
-
* against the supplied schema. Use the AI SDK's `Output.object({ schema })`
|
|
234
|
-
* / `Output.text()` helpers. Combine with `activeTools: []` on the
|
|
235
|
-
* terminal turn if your provider strips tools when structured output
|
|
236
|
-
* is active (e.g. workers-ai-provider).
|
|
237
|
-
*/
|
|
238
|
-
output?: Parameters<typeof streamText>[0]["output"];
|
|
239
|
-
}
|
|
240
|
-
/**
|
|
241
|
-
* Context passed to the `beforeStep` hook before each AI SDK step in
|
|
242
|
-
* the agentic loop. Backed by the AI SDK's `PrepareStepFunction<TOOLS>`
|
|
243
|
-
* parameter — exposes the previous `steps`, the zero-based `stepNumber`,
|
|
244
|
-
* the currently selected `model`, the `messages` about to be sent, and
|
|
245
|
-
* `experimental_context`.
|
|
246
|
-
*
|
|
247
|
-
* Pass an explicit `TOOLS` generic for typed previous tool calls / results.
|
|
248
|
-
*
|
|
249
|
-
* Limitations (AI SDK boundary, not Think):
|
|
250
|
-
* - No `abortSignal` is exposed in the context. If you do remote work
|
|
251
|
-
* inside `beforeStep`, it cannot be cancelled by turn-level abort.
|
|
252
|
-
* - `experimental_context` is typed `unknown`; users must narrow it.
|
|
253
|
-
* - `output` cannot be overridden per-step — set it at the turn level
|
|
254
|
-
* via `TurnConfig.output` (returned from `beforeTurn`).
|
|
255
|
-
*/
|
|
256
|
-
type PrepareStepContext<TOOLS extends ToolSet = ToolSet> = Parameters<
|
|
257
|
-
PrepareStepFunction$1<TOOLS>
|
|
258
|
-
>[0];
|
|
259
|
-
/**
|
|
260
|
-
* Configuration returned by `beforeStep` to override defaults for the
|
|
261
|
-
* current AI SDK step. This is the AI SDK's `PrepareStepResult<TOOLS>` —
|
|
262
|
-
* return only the fields you want to override (`model`, `toolChoice`,
|
|
263
|
-
* `activeTools`, `system`, `messages`, `experimental_context`,
|
|
264
|
-
* `providerOptions`).
|
|
265
|
-
*/
|
|
266
|
-
type StepConfig<TOOLS extends ToolSet = ToolSet> = PrepareStepResult$1<TOOLS>;
|
|
267
|
-
/**
|
|
268
|
-
* Context passed to the `beforeToolCall` hook **before** the tool's
|
|
269
|
-
* `execute` function runs.
|
|
270
|
-
*
|
|
271
|
-
* Backed by the AI SDK's `OnToolCallStartEvent` (the parameter of
|
|
272
|
-
* `experimental_onToolCallStart`). The full `TypedToolCall<TOOLS>`
|
|
273
|
-
* fields (`toolName`, `toolCallId`, `input`, `providerMetadata`, the
|
|
274
|
-
* dynamic/invalid/error discriminators) are spread at the top level for
|
|
275
|
-
* convenience, with the per-call event extras attached:
|
|
276
|
-
*
|
|
277
|
-
* - `stepNumber` — index of the current step
|
|
278
|
-
* - `messages` — conversation messages visible at tool execution time
|
|
279
|
-
* - `abortSignal` — signal that aborts if the turn is cancelled
|
|
280
|
-
*
|
|
281
|
-
* Pass an explicit `TOOLS` generic for full input typing:
|
|
282
|
-
*
|
|
283
|
-
* ```ts
|
|
284
|
-
* import type { ToolCallContext } from "@cloudflare/think";
|
|
285
|
-
* import type { tools } from "./my-tools";
|
|
286
|
-
*
|
|
287
|
-
* beforeToolCall(ctx: ToolCallContext<typeof tools>) {
|
|
288
|
-
* if (ctx.toolName === "search") {
|
|
289
|
-
* ctx.input.query; // typed
|
|
290
|
-
* }
|
|
291
|
-
* }
|
|
292
|
-
* ```
|
|
293
|
-
*/
|
|
294
|
-
type ToolCallContext<TOOLS extends ToolSet = ToolSet> =
|
|
295
|
-
TypedToolCall$1<TOOLS> & {
|
|
296
|
-
/** Zero-based index of the current step where this tool call occurs. */ readonly stepNumber:
|
|
297
|
-
| number
|
|
298
|
-
| undefined /** The conversation messages available at tool execution time. */;
|
|
299
|
-
readonly messages: ReadonlyArray<ModelMessage> /** Signal for cancelling the operation. */;
|
|
300
|
-
readonly abortSignal: AbortSignal | undefined;
|
|
301
|
-
};
|
|
302
|
-
/**
|
|
303
|
-
* Decision returned by `beforeToolCall` to control tool execution.
|
|
304
|
-
* Return void/undefined to allow execution with original input.
|
|
305
|
-
*
|
|
306
|
-
* Discriminated union — each action has a clear, non-overlapping meaning:
|
|
307
|
-
* - `allow` — execute the tool (optionally with modified input)
|
|
308
|
-
* - `block` — don't execute; return `reason` as the tool result so the model can adjust
|
|
309
|
-
* - `substitute` — don't execute; return `output` as the tool result (afterToolCall still fires)
|
|
310
|
-
*/
|
|
311
|
-
type ToolCallDecision =
|
|
312
|
-
| {
|
|
313
|
-
action: "allow" /** Modified input — tool executes with this instead of the original. */;
|
|
314
|
-
input?: Record<string, unknown>;
|
|
315
|
-
}
|
|
316
|
-
| {
|
|
317
|
-
action: "block" /** Returned as the tool result so the model can adjust. */;
|
|
318
|
-
reason?: string;
|
|
319
|
-
}
|
|
320
|
-
| {
|
|
321
|
-
action: "substitute" /** The substitute tool output — model sees this instead of real execution. */;
|
|
322
|
-
output: unknown /** Optional input attribution for the afterToolCall log. */;
|
|
323
|
-
input?: Record<string, unknown>;
|
|
324
|
-
};
|
|
325
|
-
/**
|
|
326
|
-
* Context passed to the `afterToolCall` hook after a tool executes.
|
|
327
|
-
*
|
|
328
|
-
* Backed by the AI SDK's `OnToolCallFinishEvent` (the parameter of
|
|
329
|
-
* `experimental_onToolCallFinish`). The full `TypedToolCall<TOOLS>`
|
|
330
|
-
* fields (`toolName`, `toolCallId`, `input`, …) are spread at the top
|
|
331
|
-
* level, plus the per-call event extras:
|
|
332
|
-
*
|
|
333
|
-
* - `stepNumber` — index of the current step
|
|
334
|
-
* - `messages` — conversation messages visible at tool execution time
|
|
335
|
-
* - `durationMs` — wall-clock execution time in milliseconds
|
|
336
|
-
* - `success`/`output`/`error` — discriminated outcome:
|
|
337
|
-
* - on success: `success: true`, `output: unknown`
|
|
338
|
-
* - on failure: `success: false`, `error: unknown`
|
|
339
|
-
*
|
|
340
|
-
* Pass an explicit `TOOLS` generic for full input typing:
|
|
341
|
-
*
|
|
342
|
-
* ```ts
|
|
343
|
-
* import type { ToolCallResultContext } from "@cloudflare/think";
|
|
344
|
-
* import type { tools } from "./my-tools";
|
|
345
|
-
*
|
|
346
|
-
* afterToolCall(ctx: ToolCallResultContext<typeof tools>) {
|
|
347
|
-
* if (ctx.success) {
|
|
348
|
-
* console.log(`${ctx.toolName} took ${ctx.durationMs}ms`, ctx.output);
|
|
349
|
-
* } else {
|
|
350
|
-
* console.error(`${ctx.toolName} failed:`, ctx.error);
|
|
351
|
-
* }
|
|
352
|
-
* }
|
|
353
|
-
* ```
|
|
354
|
-
*/
|
|
355
|
-
type ToolCallResultContext<TOOLS extends ToolSet = ToolSet> =
|
|
356
|
-
TypedToolCall$1<TOOLS> & {
|
|
357
|
-
readonly stepNumber: number | undefined;
|
|
358
|
-
readonly messages: ReadonlyArray<ModelMessage> /** Wall-clock execution time in milliseconds. */;
|
|
359
|
-
readonly durationMs: number;
|
|
360
|
-
} & (
|
|
361
|
-
| {
|
|
362
|
-
readonly success: true;
|
|
363
|
-
readonly output: unknown;
|
|
364
|
-
readonly error?: never;
|
|
365
|
-
}
|
|
366
|
-
| {
|
|
367
|
-
readonly success: false;
|
|
368
|
-
readonly output?: never;
|
|
369
|
-
readonly error: unknown;
|
|
370
|
-
}
|
|
371
|
-
);
|
|
372
|
-
/**
|
|
373
|
-
* Context passed to the `onStepFinish` hook after each step completes.
|
|
374
|
-
*
|
|
375
|
-
* This is the AI SDK's `StepResult<TOOLS>` (= `OnStepFinishEvent<TOOLS>`) —
|
|
376
|
-
* the full step record including `text`, `reasoning`, `toolCalls`,
|
|
377
|
-
* `toolResults`, `files`, `sources`, `usage` (with `cachedInputTokens`,
|
|
378
|
-
* `reasoningTokens`, `totalTokens`), `finishReason`, `warnings`, `request`,
|
|
379
|
-
* `response`, and `providerMetadata` (where provider-specific cache
|
|
380
|
-
* accounting like `cacheCreationInputTokens` lives).
|
|
381
|
-
*
|
|
382
|
-
* Pass an explicit `TOOLS` generic for typed `toolCalls`/`toolResults`.
|
|
383
|
-
*/
|
|
384
|
-
type StepContext<TOOLS extends ToolSet = ToolSet> = Parameters<
|
|
385
|
-
StreamTextOnStepFinishCallback<TOOLS>
|
|
386
|
-
>[0];
|
|
387
|
-
/**
|
|
388
|
-
* Context passed to the `onChunk` hook for each streaming chunk.
|
|
389
|
-
*
|
|
390
|
-
* This is the AI SDK's `StreamTextOnChunkCallback` event — `{ chunk }`
|
|
391
|
-
* where `chunk` is a discriminated union of `TextStreamPart` variants
|
|
392
|
-
* (text-delta, reasoning-delta, source, tool-call, tool-input-start,
|
|
393
|
-
* tool-input-delta, tool-result, raw).
|
|
394
|
-
*/
|
|
395
|
-
type ChunkContext<TOOLS extends ToolSet = ToolSet> = Parameters<
|
|
396
|
-
StreamTextOnChunkCallback<TOOLS>
|
|
397
|
-
>[0];
|
|
398
|
-
/**
|
|
399
|
-
* @internal Re-export of the chunk variant union for consumers that need
|
|
400
|
-
* to narrow on `chunk.type` without importing `TextStreamPart` directly.
|
|
401
|
-
*/
|
|
402
|
-
type ChunkPart<TOOLS extends ToolSet = ToolSet> = ChunkContext<TOOLS>["chunk"];
|
|
403
|
-
/**
|
|
404
|
-
* Configuration for a sandboxed extension, returned by getExtensions().
|
|
405
|
-
*/
|
|
406
|
-
interface ExtensionConfig {
|
|
407
|
-
/** Extension manifest (name, version, permissions, contributions). */
|
|
408
|
-
manifest: ExtensionManifest;
|
|
409
|
-
/** JavaScript source code defining the extension's tools. */
|
|
410
|
-
source: string;
|
|
411
|
-
}
|
|
412
|
-
/**
|
|
413
|
-
* An opinionated chat agent base class.
|
|
414
|
-
*
|
|
415
|
-
* @experimental The API surface may change before stabilizing.
|
|
416
|
-
*/
|
|
417
|
-
declare class Think<
|
|
418
|
-
Env extends Cloudflare.Env = Cloudflare.Env,
|
|
419
|
-
State = unknown,
|
|
420
|
-
Props extends Record<string, unknown> = Record<string, unknown>
|
|
421
|
-
> extends Agent<Env, State, Props> {
|
|
422
|
-
#private;
|
|
423
|
-
private static readonly CONFIG_KEYS;
|
|
424
|
-
/**
|
|
425
|
-
* Wait for MCP server connections to be ready before the inference
|
|
426
|
-
* loop. MCP tools are auto-merged into the tool set.
|
|
427
|
-
*
|
|
428
|
-
* Set to `true` for a default 10s timeout, or `{ timeout: ms }`
|
|
429
|
-
* for a custom timeout. Defaults to `false` (no waiting).
|
|
430
|
-
*/
|
|
431
|
-
waitForMcpConnections:
|
|
432
|
-
| boolean
|
|
433
|
-
| {
|
|
434
|
-
timeout: number;
|
|
435
|
-
};
|
|
436
|
-
/**
|
|
437
|
-
* Controls how overlapping user submit requests behave while another
|
|
438
|
-
* chat turn is already active or queued.
|
|
439
|
-
*
|
|
440
|
-
* @default "queue"
|
|
441
|
-
*/
|
|
442
|
-
messageConcurrency: MessageConcurrency$1;
|
|
443
|
-
/**
|
|
444
|
-
* When true, chat turns are wrapped in `runFiber` for durable execution.
|
|
445
|
-
* Enables `onChatRecovery` hook and `this.stash()` during streaming.
|
|
446
|
-
*/
|
|
447
|
-
chatRecovery: boolean;
|
|
448
|
-
static readonly CHAT_FIBER_NAME = "__cf_internal_chat_turn";
|
|
449
|
-
/**
|
|
450
|
-
* The conversation session — messages, context, compaction, search.
|
|
451
|
-
*
|
|
452
|
-
* Direct message writes are observed and mirrored into Think's live cache.
|
|
453
|
-
* Prefer the history helpers below when writing UI messages from subclasses;
|
|
454
|
-
* they sanitize content and enforce row-size limits before delegating here.
|
|
455
|
-
*/
|
|
456
|
-
session: Session$1;
|
|
457
|
-
/** Cached messages — kept in sync with session storage. */
|
|
458
|
-
private _cachedMessages;
|
|
459
|
-
/**
|
|
460
|
-
* WorkerLoader binding for sandboxed extensions.
|
|
461
|
-
* Set this to enable `getExtensions()` and dynamic extension loading.
|
|
462
|
-
*/
|
|
463
|
-
extensionLoader?: WorkerLoader;
|
|
464
|
-
/**
|
|
465
|
-
* Extension manager — created automatically when `extensionLoader` is set.
|
|
466
|
-
* Use for dynamic `load()` / `unload()` at runtime.
|
|
467
|
-
*/
|
|
468
|
-
extensionManager?: ExtensionManager;
|
|
469
|
-
/**
|
|
470
|
-
* Workspace filesystem available in `getTools()` and lifecycle hooks.
|
|
471
|
-
* Defaults to a full `Workspace` backed by the DO's SQLite storage.
|
|
472
|
-
*
|
|
473
|
-
* Typed as `WorkspaceLike` rather than `Workspace` so subclasses can
|
|
474
|
-
* replace it with anything that satisfies the interface — e.g. a proxy
|
|
475
|
-
* that forwards to a shared workspace owned by a parent DO. Override as
|
|
476
|
-
* a class field to skip the default init entirely:
|
|
477
|
-
*
|
|
478
|
-
* ```typescript
|
|
479
|
-
* // Default init with R2 spillover for large files.
|
|
480
|
-
* override workspace = new Workspace({
|
|
481
|
-
* sql: this.ctx.storage.sql,
|
|
482
|
-
* r2: this.env.R2,
|
|
483
|
-
* name: () => this.name
|
|
484
|
-
* });
|
|
485
|
-
*
|
|
486
|
-
* // Or a custom WorkspaceLike — e.g. a parent-owned shared workspace.
|
|
487
|
-
* override workspace: WorkspaceLike = new SharedWorkspace(this);
|
|
488
|
-
* ```
|
|
489
|
-
*/
|
|
490
|
-
workspace: WorkspaceLike;
|
|
491
|
-
constructor(ctx: DurableObjectState, env: Env);
|
|
492
|
-
/**
|
|
493
|
-
* Conversation history as Think's live in-memory view.
|
|
494
|
-
*
|
|
495
|
-
* Storage remains the durable source of truth, but runtime logic should read
|
|
496
|
-
* through this cache so in-flight turns, tool updates, and recovery state all
|
|
497
|
-
* observe the same message list. Use `_syncMessages()` only at safe
|
|
498
|
-
* boundaries where a full storage reread cannot drop in-flight state.
|
|
499
|
-
*/
|
|
500
|
-
get messages(): UIMessage[];
|
|
501
|
-
/** Read the durable message path from session storage. */
|
|
502
|
-
private _readMessagesFromStorage;
|
|
503
|
-
/** Replace the live cache with a durable storage snapshot. */
|
|
504
|
-
private _replaceCachedMessages;
|
|
505
|
-
/** Refresh the live cache from durable storage at a safe boundary. */
|
|
506
|
-
private _syncMessages;
|
|
507
|
-
/** Patch or append one message in the live cache after a durable write. */
|
|
508
|
-
private _upsertCachedMessage;
|
|
509
|
-
/** Patch a message that is already present in the live cache. */
|
|
510
|
-
private _patchCachedMessage;
|
|
511
|
-
private _appendMessageToHistory;
|
|
512
|
-
private _updateMessageInHistory;
|
|
513
|
-
private _upsertMessageInHistory;
|
|
514
|
-
private _clearHistory;
|
|
515
|
-
/** Append a message while keeping Think's live message cache coherent. */
|
|
516
|
-
protected appendMessageToHistory(
|
|
517
|
-
message: UIMessage,
|
|
518
|
-
parentId?: string | null
|
|
519
|
-
): Promise<UIMessage>;
|
|
520
|
-
/** Update a message while keeping Think's live message cache coherent. */
|
|
521
|
-
protected updateMessageInHistory(message: UIMessage): Promise<UIMessage>;
|
|
522
|
-
/** Refresh Think's live message cache from the durable session path. */
|
|
523
|
-
protected syncMessagesFromStorage(): Promise<UIMessage[]>;
|
|
524
|
-
private _aborts;
|
|
525
|
-
private _turnQueue;
|
|
526
|
-
protected _resumableStream: ResumableStream;
|
|
527
|
-
private _pendingResumeConnections;
|
|
528
|
-
private _lastClientTools;
|
|
529
|
-
private _lastBody;
|
|
530
|
-
private _continuation;
|
|
531
|
-
private _continuationTimer;
|
|
532
|
-
private _insideResponseHook;
|
|
533
|
-
private _insideInferenceLoop;
|
|
534
|
-
private _pendingInteractionPromise;
|
|
535
|
-
private _submitConcurrency;
|
|
536
|
-
private static MESSAGE_DEBOUNCE_MS;
|
|
537
|
-
private _agentToolForwarders;
|
|
538
|
-
private _agentToolClosers;
|
|
539
|
-
private _agentToolAbortControllers;
|
|
540
|
-
private _agentToolLastErrors;
|
|
541
|
-
private _agentToolPreTurnAssistantIds;
|
|
542
|
-
private _agentToolLiveSequences;
|
|
543
|
-
private _submissionTableEnsured;
|
|
544
|
-
private _drainingSubmissions;
|
|
545
|
-
private _submissionAbortControllers;
|
|
546
|
-
private _programmaticStreamErrors;
|
|
547
|
-
protected static submissionRecoveryStaleMs: number;
|
|
548
|
-
broadcast(
|
|
549
|
-
msg: string | ArrayBuffer | ArrayBufferView,
|
|
550
|
-
without?: string[]
|
|
551
|
-
): void;
|
|
552
|
-
/**
|
|
553
|
-
* Persist an arbitrary JSON-serializable configuration object for this
|
|
554
|
-
* agent instance. Stored in the Think-private `think_config` table —
|
|
555
|
-
* survives
|
|
556
|
-
* restarts and hibernation. Pass the config shape as a method generic
|
|
557
|
-
* for typed call sites:
|
|
558
|
-
*
|
|
559
|
-
* ```ts
|
|
560
|
-
* this.configure<MyConfig>({ modelTier: "fast" });
|
|
561
|
-
* ```
|
|
562
|
-
*
|
|
563
|
-
* Prefer `state` / `setState` from `Agent` when you want the value
|
|
564
|
-
* broadcast to connected clients. Use `configure` for private
|
|
565
|
-
* per-instance config that should stay server-side.
|
|
566
|
-
*/
|
|
567
|
-
configure<T = Record<string, unknown>>(config: T): void;
|
|
568
|
-
/**
|
|
569
|
-
* Read the persisted configuration, or null if never configured.
|
|
570
|
-
* Pass the config shape as a method generic for a typed result:
|
|
571
|
-
*
|
|
572
|
-
* ```ts
|
|
573
|
-
* const cfg = this.getConfig<MyConfig>();
|
|
574
|
-
* ```
|
|
575
|
-
*/
|
|
576
|
-
getConfig<T = Record<string, unknown>>(): T | null;
|
|
577
|
-
protected _migrateLegacyConfigToThinkTable(): void;
|
|
578
|
-
private _ensureConfigTable;
|
|
579
|
-
private _configSet;
|
|
580
|
-
private _configGet;
|
|
581
|
-
private _configDelete;
|
|
582
|
-
/**
|
|
583
|
-
* Return the language model to use for inference.
|
|
584
|
-
* Must be overridden by subclasses.
|
|
585
|
-
*/
|
|
586
|
-
getModel(): LanguageModel;
|
|
587
|
-
/**
|
|
588
|
-
* Return the system prompt for the assistant.
|
|
589
|
-
* Used as fallback when no context blocks are configured via `configureSession`.
|
|
590
|
-
*/
|
|
591
|
-
getSystemPrompt(): string;
|
|
592
|
-
/** Return the tools available to the assistant. */
|
|
593
|
-
getTools(): ToolSet;
|
|
594
|
-
private _systemPromptForTurn;
|
|
595
|
-
private _buildThinkCapabilityBlock;
|
|
596
|
-
/** Maximum number of tool-call steps per turn. Override via property or per-turn via TurnConfig. */
|
|
597
|
-
maxSteps: number;
|
|
598
|
-
/**
|
|
599
|
-
* Whether reasoning chunks are sent to chat clients by default. Override
|
|
600
|
-
* per turn by returning `sendReasoning` from `beforeTurn`.
|
|
601
|
-
*/
|
|
602
|
-
sendReasoning: boolean;
|
|
603
|
-
/**
|
|
604
|
-
* Configure the session. Called once during `onStart`.
|
|
605
|
-
* Override to add context blocks, compaction, search, skills.
|
|
606
|
-
*
|
|
607
|
-
* @example
|
|
608
|
-
* ```typescript
|
|
609
|
-
* configureSession(session: Session) {
|
|
610
|
-
* return session
|
|
611
|
-
* .withContext("memory", { description: "Learned facts", maxTokens: 2000 })
|
|
612
|
-
* .withCachedPrompt();
|
|
613
|
-
* }
|
|
614
|
-
* ```
|
|
615
|
-
*/
|
|
616
|
-
configureSession(session: Session$1): Session$1 | Promise<Session$1>;
|
|
617
|
-
/**
|
|
618
|
-
* Return sandboxed extension configurations. Defines load order,
|
|
619
|
-
* which determines hook execution order.
|
|
620
|
-
* Requires `extensionLoader` to be set.
|
|
621
|
-
*/
|
|
622
|
-
getExtensions(): ExtensionConfig[];
|
|
623
|
-
/**
|
|
624
|
-
* Called before `streamText` — inspect the assembled context and
|
|
625
|
-
* return overrides. Think assembles tools, system prompt, and messages
|
|
626
|
-
* internally; this hook sees the result and can override any part.
|
|
627
|
-
*
|
|
628
|
-
* Return `void` to accept all defaults.
|
|
629
|
-
*
|
|
630
|
-
* @example Switch model for continuations
|
|
631
|
-
* ```typescript
|
|
632
|
-
* beforeTurn(ctx: TurnContext) {
|
|
633
|
-
* if (ctx.continuation) return { model: this.cheapModel };
|
|
634
|
-
* }
|
|
635
|
-
* ```
|
|
636
|
-
*
|
|
637
|
-
* @example Restrict active tools
|
|
638
|
-
* ```typescript
|
|
639
|
-
* beforeTurn(ctx: TurnContext) {
|
|
640
|
-
* return { activeTools: ["read", "write"] };
|
|
641
|
-
* }
|
|
642
|
-
* ```
|
|
643
|
-
*/
|
|
644
|
-
beforeTurn(_ctx: TurnContext): TurnConfig | void | Promise<TurnConfig | void>;
|
|
645
|
-
/**
|
|
646
|
-
* Called before each AI SDK step in the agentic loop. Backed by
|
|
647
|
-
* `streamText({ prepareStep })`.
|
|
648
|
-
*
|
|
649
|
-
* Return `void` to accept the current step defaults, or return a
|
|
650
|
-
* `StepConfig` to override the model, tool choice, active tools,
|
|
651
|
-
* system prompt, messages, experimental context, or provider options
|
|
652
|
-
* for this step. Use `beforeTurn` for turn-wide assembly and
|
|
653
|
-
* `beforeStep` when the decision depends on the step number or
|
|
654
|
-
* previous step results.
|
|
655
|
-
*
|
|
656
|
-
* @example Force search on the first step
|
|
657
|
-
* ```typescript
|
|
658
|
-
* beforeStep(ctx: PrepareStepContext) {
|
|
659
|
-
* if (ctx.stepNumber === 0) {
|
|
660
|
-
* return {
|
|
661
|
-
* activeTools: ["search"],
|
|
662
|
-
* toolChoice: { type: "tool", toolName: "search" }
|
|
663
|
-
* };
|
|
664
|
-
* }
|
|
665
|
-
* }
|
|
666
|
-
* ```
|
|
667
|
-
*
|
|
668
|
-
* @example Switch to a cheaper model after tool results land
|
|
669
|
-
* ```typescript
|
|
670
|
-
* beforeStep(ctx: PrepareStepContext) {
|
|
671
|
-
* // assumes a `fastSummaryModel` field on your Think subclass
|
|
672
|
-
* if (ctx.steps.some((s) => s.toolResults.length > 0)) {
|
|
673
|
-
* return { model: this.fastSummaryModel };
|
|
674
|
-
* }
|
|
675
|
-
* }
|
|
676
|
-
* ```
|
|
677
|
-
*/
|
|
678
|
-
beforeStep(
|
|
679
|
-
_ctx: PrepareStepContext
|
|
680
|
-
): StepConfig | void | Promise<StepConfig | void>;
|
|
681
|
-
/**
|
|
682
|
-
* Called **before** the tool's `execute` function runs. Think wraps
|
|
683
|
-
* every tool's `execute` so it can consult this hook and act on the
|
|
684
|
-
* returned `ToolCallDecision`:
|
|
685
|
-
*
|
|
686
|
-
* - `void` (or `{ action: "allow" }` with no `input`) — run the
|
|
687
|
-
* original `execute` with the original input.
|
|
688
|
-
* - `{ action: "allow", input }` — run the original `execute` with
|
|
689
|
-
* the substituted input.
|
|
690
|
-
* - `{ action: "block", reason }` — skip `execute`; the model sees
|
|
691
|
-
* `reason` as the tool's output.
|
|
692
|
-
* - `{ action: "substitute", output }` — skip `execute`; the model
|
|
693
|
-
* sees `output` as the tool's output.
|
|
694
|
-
*
|
|
695
|
-
* Only fires for server-side tools (tools with `execute`). Client
|
|
696
|
-
* tools are handled on the client — Think can't intercept them.
|
|
697
|
-
*
|
|
698
|
-
* `afterToolCall` always fires after this hook (or after the original
|
|
699
|
-
* `execute` when `allow`). For `block`/`substitute`, the substituted
|
|
700
|
-
* value flows through `afterToolCall` as `success: true, output: ...`.
|
|
701
|
-
*
|
|
702
|
-
* @example Log tool calls
|
|
703
|
-
* ```typescript
|
|
704
|
-
* beforeToolCall(ctx: ToolCallContext) {
|
|
705
|
-
* console.log(`Tool called: ${ctx.toolName}`, ctx.input);
|
|
706
|
-
* }
|
|
707
|
-
* ```
|
|
708
|
-
*
|
|
709
|
-
* @example Block a tool the model shouldn't be calling here
|
|
710
|
-
* ```typescript
|
|
711
|
-
* beforeToolCall(ctx: ToolCallContext): ToolCallDecision | void {
|
|
712
|
-
* if (ctx.toolName === "delete" && this.isReadOnlyMode) {
|
|
713
|
-
* return { action: "block", reason: "delete is disabled in read-only mode" };
|
|
714
|
-
* }
|
|
715
|
-
* }
|
|
716
|
-
* ```
|
|
717
|
-
*
|
|
718
|
-
* @example Substitute a cached result
|
|
719
|
-
* ```typescript
|
|
720
|
-
* async beforeToolCall(ctx: ToolCallContext): Promise<ToolCallDecision | void> {
|
|
721
|
-
* if (ctx.toolName === "weather") {
|
|
722
|
-
* const cached = await this.cache.get(JSON.stringify(ctx.input));
|
|
723
|
-
* if (cached) return { action: "substitute", output: cached };
|
|
724
|
-
* }
|
|
725
|
-
* }
|
|
726
|
-
* ```
|
|
727
|
-
*/
|
|
728
|
-
beforeToolCall(
|
|
729
|
-
_ctx: ToolCallContext
|
|
730
|
-
): ToolCallDecision | void | Promise<ToolCallDecision | void>;
|
|
731
|
-
/**
|
|
732
|
-
* Called **after** a tool's outcome is known — for real executions, for
|
|
733
|
-
* `block` (carries the `reason` as `output`), and for `substitute`
|
|
734
|
-
* (carries the substituted `output`). Backed by the AI SDK's
|
|
735
|
-
* `experimental_onToolCallFinish`, so `durationMs` and the discriminated
|
|
736
|
-
* `success`/`output`/`error` outcome reflect what the model actually
|
|
737
|
-
* sees: a thrown error from the original `execute` becomes
|
|
738
|
-
* `success: false, error: ...`; everything else (including blocked /
|
|
739
|
-
* substituted calls) is `success: true, output: ...`.
|
|
740
|
-
*
|
|
741
|
-
* Override for logging, metrics, or result inspection.
|
|
742
|
-
*
|
|
743
|
-
* @example
|
|
744
|
-
* ```typescript
|
|
745
|
-
* afterToolCall(ctx: ToolCallResultContext) {
|
|
746
|
-
* if (ctx.success) {
|
|
747
|
-
* console.log(`${ctx.toolName} ok in ${ctx.durationMs}ms`);
|
|
748
|
-
* } else {
|
|
749
|
-
* console.error(`${ctx.toolName} failed:`, ctx.error);
|
|
750
|
-
* }
|
|
751
|
-
* }
|
|
752
|
-
* ```
|
|
753
|
-
*/
|
|
754
|
-
afterToolCall(_ctx: ToolCallResultContext): void | Promise<void>;
|
|
755
|
-
/**
|
|
756
|
-
* Called after each step completes (initial, continue, tool-result).
|
|
757
|
-
* Override for step-level logging or analytics.
|
|
758
|
-
*/
|
|
759
|
-
onStepFinish(_ctx: StepContext): void | Promise<void>;
|
|
760
|
-
/**
|
|
761
|
-
* Called for each streaming chunk. High-frequency — fires per token.
|
|
762
|
-
* Override for streaming analytics, progress indicators, or token counting.
|
|
763
|
-
* Observational only (void return).
|
|
764
|
-
*/
|
|
765
|
-
onChunk(_ctx: ChunkContext): void | Promise<void>;
|
|
766
|
-
/**
|
|
767
|
-
* Called after a chat turn completes and the assistant message has been
|
|
768
|
-
* persisted. The turn lock is released before this hook runs, so it is
|
|
769
|
-
* safe to call other methods from inside.
|
|
770
|
-
*
|
|
771
|
-
* Fires for all turn completion paths: WebSocket chat requests,
|
|
772
|
-
* sub-agent RPC, and auto-continuation.
|
|
773
|
-
*
|
|
774
|
-
* Override for logging, chaining, analytics, usage tracking.
|
|
775
|
-
*/
|
|
776
|
-
onChatResponse(_result: ChatResponseResult$1): void | Promise<void>;
|
|
777
|
-
/**
|
|
778
|
-
* Handle an error that occurred during a chat turn.
|
|
779
|
-
* Override to customize error handling (e.g. logging, metrics).
|
|
780
|
-
*/
|
|
781
|
-
onChatError(error: unknown): unknown;
|
|
782
|
-
private _initializeExtensions;
|
|
783
|
-
/**
|
|
784
|
-
* The single convergence point for all chat turn entry paths.
|
|
785
|
-
* Merges tools, assembles context, fires lifecycle hooks, wraps tools
|
|
786
|
-
* for interception, and calls streamText.
|
|
787
|
-
*/
|
|
788
|
-
private _runInferenceLoop;
|
|
789
|
-
/** @internal Test seam — override in test agents to wrap the stream (e.g. error injection). */
|
|
790
|
-
protected _transformInferenceResult(
|
|
791
|
-
result: StreamableResult
|
|
792
|
-
): StreamableResult;
|
|
793
|
-
/** Default hook timeout in milliseconds. */
|
|
794
|
-
hookTimeout: number;
|
|
795
|
-
/**
|
|
796
|
-
* Pipeline beforeTurn through sandboxed extensions in load order.
|
|
797
|
-
* Each extension sees the accumulated state from prior extensions
|
|
798
|
-
* (snapshot is rebuilt after each extension's modifications).
|
|
799
|
-
* Results are merged with last-write-wins for scalar fields.
|
|
800
|
-
* Extensions that don't subscribe to beforeTurn are skipped.
|
|
801
|
-
*/
|
|
802
|
-
private _pipelineExtensionBeforeTurn;
|
|
803
|
-
/**
|
|
804
|
-
* Dispatch an observation hook to all extensions that subscribe to it.
|
|
805
|
-
*
|
|
806
|
-
* Used by `_pipelineExtensionToolCallStart`, `_pipelineExtensionToolCallFinish`,
|
|
807
|
-
* `_pipelineExtensionStepFinish`, and `_pipelineExtensionChunk`. Unlike
|
|
808
|
-
* `beforeTurn`, these hooks are observation-only — extensions can't
|
|
809
|
-
* influence the turn — so we ignore return values, log errors, and
|
|
810
|
-
* apply a per-extension timeout.
|
|
811
|
-
*
|
|
812
|
-
* `onChunk` is high-frequency (per token) — extensions that subscribe
|
|
813
|
-
* to it pay an RPC cost per chunk and should be used sparingly.
|
|
814
|
-
*/
|
|
815
|
-
private _dispatchExtensionObservation;
|
|
816
|
-
/**
|
|
817
|
-
* Wrap each tool's `execute` function so the agent's `beforeToolCall`
|
|
818
|
-
* hook is consulted before the tool runs. The hook can return a
|
|
819
|
-
* `ToolCallDecision` to:
|
|
820
|
-
*
|
|
821
|
-
* - `allow` (default if `void` is returned) — run the original
|
|
822
|
-
* `execute`, optionally with a substituted `input`.
|
|
823
|
-
* - `block` — skip `execute` and return `reason` (or a default string)
|
|
824
|
-
* as the tool result. The model sees this as the tool's output.
|
|
825
|
-
* - `substitute` — skip `execute` and return `output` directly. The
|
|
826
|
-
* model sees this as the tool's output.
|
|
827
|
-
*
|
|
828
|
-
* The wrapped `execute` also dispatches the `beforeToolCall`
|
|
829
|
-
* observation snapshot to subscribed extensions. `afterToolCall` is
|
|
830
|
-
* still wired through the AI SDK's `experimental_onToolCallFinish`
|
|
831
|
-
* callback so we get accurate `durationMs` and proper success/error
|
|
832
|
-
* discrimination — `block` and `substitute` outcomes show up as
|
|
833
|
-
* `success: true` with the substituted output; uncaught throws from
|
|
834
|
-
* the original `execute` show up as `success: false` with the error.
|
|
835
|
-
*
|
|
836
|
-
* Tools without an `execute` (output-schema-only tools, client tools
|
|
837
|
-
* routed via `needsApproval`) are left untouched.
|
|
838
|
-
*
|
|
839
|
-
* **Streaming tools (AsyncIterable):** the AI SDK supports tools whose
|
|
840
|
-
* `execute` returns `AsyncIterable<output>` to emit preliminary
|
|
841
|
-
* results before a final value. This works whether the iterator is
|
|
842
|
-
* returned directly (sync function, `async function*`) or wrapped in
|
|
843
|
-
* a Promise (`async function execute(...) { return makeIter(); }`).
|
|
844
|
-
* Because the wrapper must `await beforeToolCall` first, preliminary
|
|
845
|
-
* chunks are collapsed — only the *final* yielded value reaches the
|
|
846
|
-
* model. If you need true preliminary streaming, override
|
|
847
|
-
* `getTools()` to provide such tools and avoid using `beforeToolCall`
|
|
848
|
-
* for them (or accept the collapse).
|
|
849
|
-
*/
|
|
850
|
-
private _wrapToolsWithDecision;
|
|
851
|
-
private _pipelineExtensionToolCallStart;
|
|
852
|
-
private _pipelineExtensionToolCallFinish;
|
|
853
|
-
private _pipelineExtensionStepFinish;
|
|
854
|
-
private _pipelineExtensionChunk;
|
|
855
|
-
_hostReadFile(path: string): Promise<string | null>;
|
|
856
|
-
_hostWriteFile(path: string, content: string): Promise<void>;
|
|
857
|
-
_hostDeleteFile(path: string): Promise<boolean>;
|
|
858
|
-
_hostListFiles(dir: string): Promise<
|
|
859
|
-
Array<{
|
|
860
|
-
name: string;
|
|
861
|
-
type: string;
|
|
862
|
-
size: number;
|
|
863
|
-
path: string;
|
|
864
|
-
}>
|
|
865
|
-
>;
|
|
866
|
-
_hostGetContext(label: string): Promise<string | null>;
|
|
867
|
-
_hostSetContext(label: string, content: string): Promise<void>;
|
|
868
|
-
_hostGetMessages(limit?: number): Promise<
|
|
869
|
-
Array<{
|
|
870
|
-
id: string;
|
|
871
|
-
role: string;
|
|
872
|
-
content: string;
|
|
873
|
-
}>
|
|
874
|
-
>;
|
|
875
|
-
_hostSendMessage(content: string): Promise<void>;
|
|
876
|
-
_hostGetSessionInfo(): Promise<{
|
|
877
|
-
messageCount: number;
|
|
878
|
-
}>;
|
|
879
|
-
/**
|
|
880
|
-
* Run a chat turn: persist the user message, run the agentic loop,
|
|
881
|
-
* stream UIMessageChunk events via callback, and persist the
|
|
882
|
-
* assistant's response.
|
|
883
|
-
*
|
|
884
|
-
* @param userMessage The user's message (string or UIMessage)
|
|
885
|
-
* @param callback Streaming callback (typically an RpcTarget from the parent)
|
|
886
|
-
* @param options Optional chat options (e.g. AbortSignal)
|
|
887
|
-
*/
|
|
888
|
-
chat(
|
|
889
|
-
userMessage: string | UIMessage,
|
|
890
|
-
callback: StreamCallback,
|
|
891
|
-
options?: ChatOptions
|
|
892
|
-
): Promise<void>;
|
|
893
|
-
/** Get the conversation history as UIMessage[]. */
|
|
894
|
-
getMessages(): Promise<UIMessage[]>;
|
|
895
|
-
/** Clear all messages from storage. */
|
|
896
|
-
clearMessages(): Promise<void>;
|
|
897
|
-
private _ensureAgentToolChildRunTable;
|
|
898
|
-
private _addAgentToolChildRunColumnIfMissing;
|
|
899
|
-
private _readAgentToolChildRun;
|
|
900
|
-
private _inspectionFromChildRow;
|
|
901
|
-
protected formatAgentToolInput(input: unknown): UIMessage;
|
|
902
|
-
protected getAgentToolOutput(_runId: string): unknown;
|
|
903
|
-
protected getAgentToolSummary(runId: string, output: unknown): string;
|
|
904
|
-
startAgentToolRun(
|
|
905
|
-
input: unknown,
|
|
906
|
-
options: {
|
|
907
|
-
runId: string;
|
|
908
|
-
}
|
|
909
|
-
): Promise<AgentToolRunInspection>;
|
|
910
|
-
cancelAgentToolRun(runId: string, reason?: unknown): Promise<void>;
|
|
911
|
-
inspectAgentToolRun(runId: string): Promise<AgentToolRunInspection | null>;
|
|
912
|
-
getAgentToolChunks(
|
|
913
|
-
runId: string,
|
|
914
|
-
options?: {
|
|
915
|
-
afterSequence?: number;
|
|
916
|
-
}
|
|
917
|
-
): Promise<AgentToolStoredChunk[]>;
|
|
918
|
-
tailAgentToolRun(
|
|
919
|
-
runId: string,
|
|
920
|
-
options?: {
|
|
921
|
-
afterSequence?: number;
|
|
922
|
-
}
|
|
923
|
-
): Promise<ReadableStream<AgentToolStoredChunk>>;
|
|
924
|
-
private static _stringifyAgentToolOutput;
|
|
925
|
-
private static _parseAgentToolOutput;
|
|
926
|
-
private _getAgentToolFinalText;
|
|
927
|
-
private _ensureSubmissionTable;
|
|
928
|
-
private _readSubmission;
|
|
929
|
-
private _readSubmissionByIdempotencyKey;
|
|
930
|
-
private _normalizeStatusFilter;
|
|
931
|
-
private _listSubmissionRows;
|
|
932
|
-
private _listSubmissionRowsByStatus;
|
|
933
|
-
private _inspectionFromSubmissionRow;
|
|
934
|
-
private _parseJsonObject;
|
|
935
|
-
private _parseSubmissionMessages;
|
|
936
|
-
private _serializeSubmissionMessages;
|
|
937
|
-
private _serializeMetadata;
|
|
938
|
-
private _emitSubmissionStatus;
|
|
939
|
-
protected onSubmissionStatus(
|
|
940
|
-
_submission: ThinkSubmissionInspection
|
|
941
|
-
): void | Promise<void>;
|
|
942
|
-
inspectSubmission(
|
|
943
|
-
submissionId: string
|
|
944
|
-
): Promise<ThinkSubmissionInspection | null>;
|
|
945
|
-
listSubmissions(
|
|
946
|
-
options?: ListSubmissionsOptions
|
|
947
|
-
): Promise<ThinkSubmissionInspection[]>;
|
|
948
|
-
deleteSubmission(submissionId: string): Promise<boolean>;
|
|
949
|
-
deleteSubmissions(options?: DeleteSubmissionsOptions): Promise<number>;
|
|
950
|
-
private _listTerminalSubmissionRowsForDelete;
|
|
951
|
-
private _isTerminalSubmissionStatus;
|
|
952
|
-
cancelSubmission(submissionId: string, reason?: unknown): Promise<void>;
|
|
953
|
-
submitMessages(
|
|
954
|
-
messages: UIMessage[],
|
|
955
|
-
options?: SubmitMessagesOptions
|
|
956
|
-
): Promise<SubmitMessagesResult>;
|
|
957
|
-
private _scheduleSubmissionDrain;
|
|
958
|
-
private _startSubmissionDrain;
|
|
959
|
-
_drainThinkSubmissions(): Promise<void>;
|
|
960
|
-
private _drainSubmissions;
|
|
961
|
-
private _runSubmission;
|
|
962
|
-
private _getSubmissionFinalStatus;
|
|
963
|
-
private _markPendingSubmissionsSkipped;
|
|
964
|
-
private _emitSkippedSubmissions;
|
|
965
|
-
private _recoverSubmissionsOnStart;
|
|
966
|
-
private _getSubmissionMessagesAppliedState;
|
|
967
|
-
private _hasRecoverableChatTurn;
|
|
968
|
-
private _hasFreshRecoverableSubmissionEvidence;
|
|
969
|
-
private _hasScheduledRecoveredContinuation;
|
|
970
|
-
/**
|
|
971
|
-
* Inject messages and trigger a model turn — without a WebSocket request.
|
|
972
|
-
*
|
|
973
|
-
* Use for scheduled responses, webhook-triggered turns, proactive agents,
|
|
974
|
-
* or chaining from `onChatResponse`.
|
|
975
|
-
*
|
|
976
|
-
* Accepts static messages or a callback that derives messages from the
|
|
977
|
-
* current state (useful when multiple calls queue up — the callback runs
|
|
978
|
-
* with the latest messages when the turn actually starts).
|
|
979
|
-
*
|
|
980
|
-
* Pass `options.signal` to cancel the turn from outside without knowing
|
|
981
|
-
* the internally-generated request id. The signal is linked to the
|
|
982
|
-
* registry's controller for this turn — when it aborts, the inference
|
|
983
|
-
* loop's signal aborts and the result reports `status: "aborted"`.
|
|
984
|
-
* Pre-aborted signals short-circuit before any model work runs. See
|
|
985
|
-
* {@link SaveMessagesOptions} for the integration point.
|
|
986
|
-
*
|
|
987
|
-
* @example Scheduled follow-up
|
|
988
|
-
* ```typescript
|
|
989
|
-
* async onScheduled() {
|
|
990
|
-
* await this.saveMessages([{
|
|
991
|
-
* id: crypto.randomUUID(),
|
|
992
|
-
* role: "user",
|
|
993
|
-
* parts: [{ type: "text", text: "Time for your daily summary." }]
|
|
994
|
-
* }]);
|
|
995
|
-
* }
|
|
996
|
-
* ```
|
|
997
|
-
*
|
|
998
|
-
* @example Function form
|
|
999
|
-
* ```typescript
|
|
1000
|
-
* await this.saveMessages((current) => [
|
|
1001
|
-
* ...current,
|
|
1002
|
-
* { id: crypto.randomUUID(), role: "user", parts: [{ type: "text", text: "Continue." }] }
|
|
1003
|
-
* ]);
|
|
1004
|
-
* ```
|
|
1005
|
-
*
|
|
1006
|
-
* @example External cancellation (helper-as-sub-agent)
|
|
1007
|
-
* ```typescript
|
|
1008
|
-
* // Inside a parent agent's tool execute — forward the AI SDK's
|
|
1009
|
-
* // abortSignal so a parent stop / tab close cancels the helper.
|
|
1010
|
-
* await helper.saveMessages([userMsg], { signal: abortSignal });
|
|
1011
|
-
* ```
|
|
1012
|
-
*/
|
|
1013
|
-
saveMessages(
|
|
1014
|
-
messages:
|
|
1015
|
-
| UIMessage[]
|
|
1016
|
-
| ((currentMessages: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>),
|
|
1017
|
-
options?: SaveMessagesOptions$1
|
|
1018
|
-
): Promise<SaveMessagesResult$1>;
|
|
1019
|
-
private _runProgrammaticMessagesTurn;
|
|
1020
|
-
/**
|
|
1021
|
-
* Run a new LLM call following the last assistant message.
|
|
1022
|
-
*
|
|
1023
|
-
* The model sees the full conversation (including the last assistant
|
|
1024
|
-
* response) and generates a new response. The new response is persisted
|
|
1025
|
-
* as a separate assistant message. Building block for chat recovery
|
|
1026
|
-
* (Phase 4), "generate more" buttons, and self-correction.
|
|
1027
|
-
*
|
|
1028
|
-
* Note: this creates a new message, not an append to the existing one.
|
|
1029
|
-
* True continuation-as-append (chunk rewriting) is planned for Phase 4.
|
|
1030
|
-
*
|
|
1031
|
-
* Returns early with `status: "skipped"` if there is no assistant message
|
|
1032
|
-
* to continue from.
|
|
1033
|
-
*
|
|
1034
|
-
* Pass `options.signal` to cancel the continuation from outside —
|
|
1035
|
-
* matches the {@link saveMessages} contract.
|
|
1036
|
-
*/
|
|
1037
|
-
protected continueLastTurn(
|
|
1038
|
-
body?: Record<string, unknown>,
|
|
1039
|
-
options?: SaveMessagesOptions$1
|
|
1040
|
-
): Promise<SaveMessagesResult$1>;
|
|
1041
|
-
private _setupProtocolHandlers;
|
|
1042
|
-
private _handleProtocolEvent;
|
|
1043
|
-
private _handleStreamResumeRequest;
|
|
1044
|
-
private _handleStreamResumeAck;
|
|
1045
|
-
private _handleChatRequest;
|
|
1046
|
-
/**
|
|
1047
|
-
* Abort the active turn, invalidate queued turns, and reset
|
|
1048
|
-
* concurrency/continuation state. Call this when intercepting
|
|
1049
|
-
* clear events or implementing custom reset logic.
|
|
1050
|
-
*
|
|
1051
|
-
* Does NOT clear messages, streams, or persisted state —
|
|
1052
|
-
* only turn execution state.
|
|
1053
|
-
*/
|
|
1054
|
-
protected resetTurnState(): void;
|
|
1055
|
-
/**
|
|
1056
|
-
* Abort a single in-flight chat turn by request id.
|
|
1057
|
-
*
|
|
1058
|
-
* Equivalent to the cancel path that fires when a client sends a
|
|
1059
|
-
* `chat-request-cancel` WebSocket message — the inference loop's
|
|
1060
|
-
* signal aborts, partial chunks already streamed are still
|
|
1061
|
-
* persisted, and the turn's `ChatResponseResult` reports
|
|
1062
|
-
* `status: "aborted"`.
|
|
1063
|
-
*
|
|
1064
|
-
* No-op if no controller exists for `requestId` (the turn already
|
|
1065
|
-
* completed, was never started, or used a different id).
|
|
1066
|
-
*
|
|
1067
|
-
* `chat()` callers can read the request id from
|
|
1068
|
-
* {@link StreamCallback.onStart} and later pass it here from another
|
|
1069
|
-
* RPC call.
|
|
1070
|
-
*
|
|
1071
|
-
* Prefer {@link SaveMessagesOptions.signal} when driving a turn
|
|
1072
|
-
* programmatically — it threads the abort intent in from the start
|
|
1073
|
-
* without requiring the caller to know the id.
|
|
1074
|
-
*/
|
|
1075
|
-
cancelChat(requestId: string, reason?: string): void;
|
|
1076
|
-
/** Abort every in-flight chat turn on this agent. */
|
|
1077
|
-
cancelAllChats(): void;
|
|
1078
|
-
protected abortRequest(requestId: string, reason?: unknown): void;
|
|
1079
|
-
/**
|
|
1080
|
-
* Abort every in-flight chat turn on this agent.
|
|
1081
|
-
*
|
|
1082
|
-
* Aborts all controllers in the registry and clears it. Used by
|
|
1083
|
-
* subclasses that drive single-purpose turns (e.g. a sub-agent
|
|
1084
|
-
* helper that runs one turn at a time over RPC) and want a coarse
|
|
1085
|
-
* "cancel whatever is running" handle without tracking request ids.
|
|
1086
|
-
*
|
|
1087
|
-
* Does NOT reset queued turns, continuation timers, or submit
|
|
1088
|
-
* concurrency state — use {@link resetTurnState} for the full
|
|
1089
|
-
* teardown that runs on `chat-clear`.
|
|
1090
|
-
*/
|
|
1091
|
-
protected abortAllRequests(): void;
|
|
1092
|
-
private _handleClear;
|
|
1093
|
-
private _streamResultToRpcCallback;
|
|
1094
|
-
private _shouldFlushRpcStreamChunk;
|
|
1095
|
-
private _streamResult;
|
|
1096
|
-
private _persistAssistantMessage;
|
|
1097
|
-
/**
|
|
1098
|
-
* Persist an incoming message after reconciliation. For assistant
|
|
1099
|
-
* messages, also resolve their ID against any server-side row that
|
|
1100
|
-
* already owns the same `toolCallId` so we update the existing row
|
|
1101
|
-
* instead of inserting an orphan duplicate.
|
|
1102
|
-
*/
|
|
1103
|
-
private _persistIncomingMessage;
|
|
1104
|
-
private _persistClientTools;
|
|
1105
|
-
private _restoreClientTools;
|
|
1106
|
-
private _persistBody;
|
|
1107
|
-
private _restoreBody;
|
|
1108
|
-
private _applyToolResult;
|
|
1109
|
-
private _applyToolApproval;
|
|
1110
|
-
private _applyToolUpdateToMessages;
|
|
1111
|
-
protected hasPendingInteraction(): boolean;
|
|
1112
|
-
protected waitUntilStable(options?: { timeout?: number }): Promise<boolean>;
|
|
1113
|
-
private _awaitWithDeadline;
|
|
1114
|
-
private _messageHasPendingInteraction;
|
|
1115
|
-
protected _handleInternalFiberRecovery(
|
|
1116
|
-
ctx: FiberRecoveryContext$1
|
|
1117
|
-
): Promise<boolean>;
|
|
1118
|
-
private _hasRunningSubmission;
|
|
1119
|
-
private _readRunningSubmissionByRequestId;
|
|
1120
|
-
private _markRecoveredSubmissionInterrupted;
|
|
1121
|
-
private _completeRecoveredSubmission;
|
|
1122
|
-
protected onChatRecovery(
|
|
1123
|
-
_ctx: ChatRecoveryContext$1
|
|
1124
|
-
): Promise<ChatRecoveryOptions$1>;
|
|
1125
|
-
_chatRecoveryContinue(data?: {
|
|
1126
|
-
targetAssistantId?: string;
|
|
1127
|
-
recoveredRequestId?: string;
|
|
1128
|
-
}): Promise<void>;
|
|
1129
|
-
private _getPartialStreamText;
|
|
1130
|
-
private _getSubmitConcurrencyDecision;
|
|
1131
|
-
private _completeSkippedRequest;
|
|
1132
|
-
private _rollbackDroppedSubmit;
|
|
1133
|
-
private _scheduleAutoContinuation;
|
|
1134
|
-
private _fireAutoContinuation;
|
|
1135
|
-
private _activateDeferredContinuation;
|
|
1136
|
-
private _fireResponseHook;
|
|
1137
|
-
private _notifyStreamResuming;
|
|
1138
|
-
private _persistOrphanedStream;
|
|
1139
|
-
private _broadcastChat;
|
|
1140
|
-
private _broadcast;
|
|
1141
|
-
private _broadcastMessages;
|
|
1142
|
-
}
|
|
1143
|
-
//#endregion
|
|
3
|
+
$t as defineScheduledTasks,
|
|
4
|
+
At as StreamableResult,
|
|
5
|
+
Bt as ThinkSubmissionInspection,
|
|
6
|
+
Ct as SkillRunContext,
|
|
7
|
+
Dt as StepResult,
|
|
8
|
+
Et as StepContext,
|
|
9
|
+
Ft as ThinkIntervalSchedule,
|
|
10
|
+
Gt as ToolCallDecision,
|
|
11
|
+
Ht as ThinkTime,
|
|
12
|
+
It as ThinkScheduledTask,
|
|
13
|
+
Jt as TurnContext,
|
|
14
|
+
Kt as ToolCallResultContext,
|
|
15
|
+
Lt as ThinkScheduledTaskContext,
|
|
16
|
+
Mt as SubmitMessagesResult,
|
|
17
|
+
Nt as TextStreamPart,
|
|
18
|
+
Ot as StopCondition,
|
|
19
|
+
Pt as Think,
|
|
20
|
+
Qt as Workspace,
|
|
21
|
+
Rt as ThinkScheduledTaskSchedule,
|
|
22
|
+
St as Session,
|
|
23
|
+
Tt as StepConfig,
|
|
24
|
+
Ut as ThinkWallClockSchedule,
|
|
25
|
+
Vt as ThinkSubmissionStatus,
|
|
26
|
+
Wt as ToolCallContext,
|
|
27
|
+
Xt as TypedToolCall,
|
|
28
|
+
Yt as TurnInput,
|
|
29
|
+
Zt as TypedToolResult,
|
|
30
|
+
_t as PrepareStepFunction,
|
|
31
|
+
at as ChatRecoveryOptions,
|
|
32
|
+
bt as SaveMessagesOptions,
|
|
33
|
+
ct as ChunkContext,
|
|
34
|
+
dt as ExtensionConfig,
|
|
35
|
+
en as skills,
|
|
36
|
+
et as ChatErrorContext,
|
|
37
|
+
ft as FiberContext,
|
|
38
|
+
gt as PrepareStepContext,
|
|
39
|
+
ht as MessageConcurrency,
|
|
40
|
+
it as ChatRecoveryExhaustedContext,
|
|
41
|
+
jt as SubmitMessagesOptions,
|
|
42
|
+
kt as StreamCallback,
|
|
43
|
+
lt as ChunkPart,
|
|
44
|
+
mt as ListSubmissionsOptions,
|
|
45
|
+
nt as ChatRecoveryConfig,
|
|
46
|
+
ot as ChatResponseResult,
|
|
47
|
+
pt as FiberRecoveryContext,
|
|
48
|
+
qt as TurnConfig,
|
|
49
|
+
rt as ChatRecoveryContext,
|
|
50
|
+
st as ChatStartEvent,
|
|
51
|
+
tt as ChatOptions,
|
|
52
|
+
ut as DeleteSubmissionsOptions,
|
|
53
|
+
vt as PrepareStepResult,
|
|
54
|
+
wt as SkillSource,
|
|
55
|
+
xt as SaveMessagesResult,
|
|
56
|
+
yt as ResolvedChatRecoveryConfig,
|
|
57
|
+
zt as ThinkScheduledTasks
|
|
58
|
+
} from "./index-CYp8VDIe.js";
|
|
1144
59
|
export {
|
|
60
|
+
ChatErrorContext,
|
|
1145
61
|
ChatOptions,
|
|
62
|
+
type ChatRecoveryConfig,
|
|
1146
63
|
type ChatRecoveryContext,
|
|
64
|
+
type ChatRecoveryExhaustedContext,
|
|
1147
65
|
type ChatRecoveryOptions,
|
|
1148
66
|
type ChatResponseResult,
|
|
1149
67
|
ChatStartEvent,
|
|
@@ -1158,9 +76,12 @@ export {
|
|
|
1158
76
|
PrepareStepContext,
|
|
1159
77
|
type PrepareStepFunction,
|
|
1160
78
|
type PrepareStepResult,
|
|
79
|
+
type ResolvedChatRecoveryConfig,
|
|
1161
80
|
type SaveMessagesOptions,
|
|
1162
81
|
type SaveMessagesResult,
|
|
1163
82
|
Session,
|
|
83
|
+
type SkillRunContext,
|
|
84
|
+
type SkillSource,
|
|
1164
85
|
StepConfig,
|
|
1165
86
|
StepContext,
|
|
1166
87
|
type StepResult,
|
|
@@ -1171,8 +92,15 @@ export {
|
|
|
1171
92
|
SubmitMessagesResult,
|
|
1172
93
|
type TextStreamPart,
|
|
1173
94
|
Think,
|
|
95
|
+
ThinkIntervalSchedule,
|
|
96
|
+
ThinkScheduledTask,
|
|
97
|
+
ThinkScheduledTaskContext,
|
|
98
|
+
ThinkScheduledTaskSchedule,
|
|
99
|
+
ThinkScheduledTasks,
|
|
1174
100
|
ThinkSubmissionInspection,
|
|
1175
101
|
ThinkSubmissionStatus,
|
|
102
|
+
ThinkTime,
|
|
103
|
+
ThinkWallClockSchedule,
|
|
1176
104
|
ToolCallContext,
|
|
1177
105
|
ToolCallDecision,
|
|
1178
106
|
ToolCallResultContext,
|
|
@@ -1182,6 +110,7 @@ export {
|
|
|
1182
110
|
type TypedToolCall,
|
|
1183
111
|
type TypedToolResult,
|
|
1184
112
|
Workspace,
|
|
1185
|
-
type WorkspaceLike
|
|
113
|
+
type WorkspaceLike,
|
|
114
|
+
defineScheduledTasks,
|
|
115
|
+
skills
|
|
1186
116
|
};
|
|
1187
|
-
//# sourceMappingURL=think.d.ts.map
|