@cloudflare/think 0.2.4 → 0.3.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 +89 -3
- package/dist/{classPrivateFieldGet2-fyJ3k1Ht.js → classPrivateFieldGet2-C7fYS0JL.js} +5 -5
- package/dist/extensions/index.js +3 -3
- package/dist/extensions/index.js.map +1 -1
- package/dist/hook-proxy-5248W-ea.js +112 -0
- package/dist/hook-proxy-5248W-ea.js.map +1 -0
- package/dist/{manager-BTBhPS6g.js → manager-CR9ZdLiu.js} +8 -4
- package/dist/{manager-BTBhPS6g.js.map → manager-CR9ZdLiu.js.map} +1 -1
- package/dist/think.d.ts +236 -57
- package/dist/think.js +229 -52
- package/dist/think.js.map +1 -1
- package/dist/tools/extensions.js +1 -1
- package/package.json +3 -3
- package/dist/hook-proxy-f_DqtJ9u.js +0 -32
- package/dist/hook-proxy-f_DqtJ9u.js.map +0 -1
package/dist/think.d.ts
CHANGED
|
@@ -5,7 +5,14 @@ import {
|
|
|
5
5
|
import {
|
|
6
6
|
LanguageModel,
|
|
7
7
|
ModelMessage,
|
|
8
|
+
StepResult,
|
|
9
|
+
StreamTextOnChunkCallback,
|
|
10
|
+
StreamTextOnStepFinishCallback,
|
|
11
|
+
TextStreamPart,
|
|
8
12
|
ToolSet,
|
|
13
|
+
TypedToolCall,
|
|
14
|
+
TypedToolCall as TypedToolCall$1,
|
|
15
|
+
TypedToolResult,
|
|
9
16
|
UIMessage,
|
|
10
17
|
streamText
|
|
11
18
|
} from "ai";
|
|
@@ -68,6 +75,12 @@ type ChatRecoveryContext = {
|
|
|
68
75
|
messages: UIMessage[];
|
|
69
76
|
lastBody?: Record<string, unknown>;
|
|
70
77
|
lastClientTools?: ClientToolSchema[];
|
|
78
|
+
/**
|
|
79
|
+
* Epoch milliseconds when the underlying fiber was started. Compare against
|
|
80
|
+
* `Date.now()` to suppress continuations for turns that have been orphaned
|
|
81
|
+
* too long to safely replay.
|
|
82
|
+
*/
|
|
83
|
+
createdAt: number;
|
|
71
84
|
};
|
|
72
85
|
/**
|
|
73
86
|
* Options returned from `onChatRecovery` to control recovery behavior.
|
|
@@ -133,74 +146,141 @@ interface TurnConfig {
|
|
|
133
146
|
providerOptions?: Record<string, unknown>;
|
|
134
147
|
}
|
|
135
148
|
/**
|
|
136
|
-
* Context passed to the `beforeToolCall` hook
|
|
137
|
-
*
|
|
149
|
+
* Context passed to the `beforeToolCall` hook **before** the tool's
|
|
150
|
+
* `execute` function runs.
|
|
151
|
+
*
|
|
152
|
+
* Backed by the AI SDK's `OnToolCallStartEvent` (the parameter of
|
|
153
|
+
* `experimental_onToolCallStart`). The full `TypedToolCall<TOOLS>`
|
|
154
|
+
* fields (`toolName`, `toolCallId`, `input`, `providerMetadata`, the
|
|
155
|
+
* dynamic/invalid/error discriminators) are spread at the top level for
|
|
156
|
+
* convenience, with the per-call event extras attached:
|
|
157
|
+
*
|
|
158
|
+
* - `stepNumber` — index of the current step
|
|
159
|
+
* - `messages` — conversation messages visible at tool execution time
|
|
160
|
+
* - `abortSignal` — signal that aborts if the turn is cancelled
|
|
161
|
+
*
|
|
162
|
+
* Pass an explicit `TOOLS` generic for full input typing:
|
|
163
|
+
*
|
|
164
|
+
* ```ts
|
|
165
|
+
* import type { ToolCallContext } from "@cloudflare/think";
|
|
166
|
+
* import type { tools } from "./my-tools";
|
|
167
|
+
*
|
|
168
|
+
* beforeToolCall(ctx: ToolCallContext<typeof tools>) {
|
|
169
|
+
* if (ctx.toolName === "search") {
|
|
170
|
+
* ctx.input.query; // typed
|
|
171
|
+
* }
|
|
172
|
+
* }
|
|
173
|
+
* ```
|
|
138
174
|
*/
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
175
|
+
type ToolCallContext<TOOLS extends ToolSet = ToolSet> =
|
|
176
|
+
TypedToolCall$1<TOOLS> & {
|
|
177
|
+
/** Zero-based index of the current step where this tool call occurs. */ readonly stepNumber:
|
|
178
|
+
| number
|
|
179
|
+
| undefined /** The conversation messages available at tool execution time. */;
|
|
180
|
+
readonly messages: ReadonlyArray<ModelMessage> /** Signal for cancelling the operation. */;
|
|
181
|
+
readonly abortSignal: AbortSignal | undefined;
|
|
182
|
+
};
|
|
145
183
|
/**
|
|
146
184
|
* Decision returned by `beforeToolCall` to control tool execution.
|
|
147
|
-
* Return void/undefined to allow execution with original
|
|
185
|
+
* Return void/undefined to allow execution with original input.
|
|
148
186
|
*
|
|
149
187
|
* Discriminated union — each action has a clear, non-overlapping meaning:
|
|
150
|
-
* - `allow` — execute the tool (optionally with modified
|
|
188
|
+
* - `allow` — execute the tool (optionally with modified input)
|
|
151
189
|
* - `block` — don't execute; return `reason` as the tool result so the model can adjust
|
|
152
|
-
* - `substitute` — don't execute; return `
|
|
190
|
+
* - `substitute` — don't execute; return `output` as the tool result (afterToolCall still fires)
|
|
153
191
|
*/
|
|
154
192
|
type ToolCallDecision =
|
|
155
193
|
| {
|
|
156
|
-
action: "allow" /** Modified
|
|
157
|
-
|
|
194
|
+
action: "allow" /** Modified input — tool executes with this instead of the original. */;
|
|
195
|
+
input?: Record<string, unknown>;
|
|
158
196
|
}
|
|
159
197
|
| {
|
|
160
198
|
action: "block" /** Returned as the tool result so the model can adjust. */;
|
|
161
199
|
reason?: string;
|
|
162
200
|
}
|
|
163
201
|
| {
|
|
164
|
-
action: "substitute" /** The substitute tool
|
|
165
|
-
|
|
166
|
-
|
|
202
|
+
action: "substitute" /** The substitute tool output — model sees this instead of real execution. */;
|
|
203
|
+
output: unknown /** Optional input attribution for the afterToolCall log. */;
|
|
204
|
+
input?: Record<string, unknown>;
|
|
167
205
|
};
|
|
168
206
|
/**
|
|
169
207
|
* Context passed to the `afterToolCall` hook after a tool executes.
|
|
208
|
+
*
|
|
209
|
+
* Backed by the AI SDK's `OnToolCallFinishEvent` (the parameter of
|
|
210
|
+
* `experimental_onToolCallFinish`). The full `TypedToolCall<TOOLS>`
|
|
211
|
+
* fields (`toolName`, `toolCallId`, `input`, …) are spread at the top
|
|
212
|
+
* level, plus the per-call event extras:
|
|
213
|
+
*
|
|
214
|
+
* - `stepNumber` — index of the current step
|
|
215
|
+
* - `messages` — conversation messages visible at tool execution time
|
|
216
|
+
* - `durationMs` — wall-clock execution time in milliseconds
|
|
217
|
+
* - `success`/`output`/`error` — discriminated outcome:
|
|
218
|
+
* - on success: `success: true`, `output: unknown`
|
|
219
|
+
* - on failure: `success: false`, `error: unknown`
|
|
220
|
+
*
|
|
221
|
+
* Pass an explicit `TOOLS` generic for full input typing:
|
|
222
|
+
*
|
|
223
|
+
* ```ts
|
|
224
|
+
* import type { ToolCallResultContext } from "@cloudflare/think";
|
|
225
|
+
* import type { tools } from "./my-tools";
|
|
226
|
+
*
|
|
227
|
+
* afterToolCall(ctx: ToolCallResultContext<typeof tools>) {
|
|
228
|
+
* if (ctx.success) {
|
|
229
|
+
* console.log(`${ctx.toolName} took ${ctx.durationMs}ms`, ctx.output);
|
|
230
|
+
* } else {
|
|
231
|
+
* console.error(`${ctx.toolName} failed:`, ctx.error);
|
|
232
|
+
* }
|
|
233
|
+
* }
|
|
234
|
+
* ```
|
|
170
235
|
*/
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
236
|
+
type ToolCallResultContext<TOOLS extends ToolSet = ToolSet> =
|
|
237
|
+
TypedToolCall$1<TOOLS> & {
|
|
238
|
+
readonly stepNumber: number | undefined;
|
|
239
|
+
readonly messages: ReadonlyArray<ModelMessage> /** Wall-clock execution time in milliseconds. */;
|
|
240
|
+
readonly durationMs: number;
|
|
241
|
+
} & (
|
|
242
|
+
| {
|
|
243
|
+
readonly success: true;
|
|
244
|
+
readonly output: unknown;
|
|
245
|
+
readonly error?: never;
|
|
246
|
+
}
|
|
247
|
+
| {
|
|
248
|
+
readonly success: false;
|
|
249
|
+
readonly output?: never;
|
|
250
|
+
readonly error: unknown;
|
|
251
|
+
}
|
|
252
|
+
);
|
|
179
253
|
/**
|
|
180
254
|
* Context passed to the `onStepFinish` hook after each step completes.
|
|
181
|
-
*
|
|
255
|
+
*
|
|
256
|
+
* This is the AI SDK's `StepResult<TOOLS>` (= `OnStepFinishEvent<TOOLS>`) —
|
|
257
|
+
* the full step record including `text`, `reasoning`, `toolCalls`,
|
|
258
|
+
* `toolResults`, `files`, `sources`, `usage` (with `cachedInputTokens`,
|
|
259
|
+
* `reasoningTokens`, `totalTokens`), `finishReason`, `warnings`, `request`,
|
|
260
|
+
* `response`, and `providerMetadata` (where provider-specific cache
|
|
261
|
+
* accounting like `cacheCreationInputTokens` lives).
|
|
262
|
+
*
|
|
263
|
+
* Pass an explicit `TOOLS` generic for typed `toolCalls`/`toolResults`.
|
|
182
264
|
*/
|
|
183
|
-
type StepContext =
|
|
184
|
-
|
|
185
|
-
|
|
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
|
-
};
|
|
265
|
+
type StepContext<TOOLS extends ToolSet = ToolSet> = Parameters<
|
|
266
|
+
StreamTextOnStepFinishCallback<TOOLS>
|
|
267
|
+
>[0];
|
|
197
268
|
/**
|
|
198
269
|
* Context passed to the `onChunk` hook for each streaming chunk.
|
|
199
|
-
*
|
|
270
|
+
*
|
|
271
|
+
* This is the AI SDK's `StreamTextOnChunkCallback` event — `{ chunk }`
|
|
272
|
+
* where `chunk` is a discriminated union of `TextStreamPart` variants
|
|
273
|
+
* (text-delta, reasoning-delta, source, tool-call, tool-input-start,
|
|
274
|
+
* tool-input-delta, tool-result, raw).
|
|
200
275
|
*/
|
|
201
|
-
type ChunkContext =
|
|
202
|
-
|
|
203
|
-
|
|
276
|
+
type ChunkContext<TOOLS extends ToolSet = ToolSet> = Parameters<
|
|
277
|
+
StreamTextOnChunkCallback<TOOLS>
|
|
278
|
+
>[0];
|
|
279
|
+
/**
|
|
280
|
+
* @internal Re-export of the chunk variant union for consumers that need
|
|
281
|
+
* to narrow on `chunk.type` without importing `TextStreamPart` directly.
|
|
282
|
+
*/
|
|
283
|
+
type ChunkPart<TOOLS extends ToolSet = ToolSet> = ChunkContext<TOOLS>["chunk"];
|
|
204
284
|
/**
|
|
205
285
|
* Configuration for a sandboxed extension, returned by getExtensions().
|
|
206
286
|
*/
|
|
@@ -248,7 +328,7 @@ type ChatResponseResult = {
|
|
|
248
328
|
/**
|
|
249
329
|
* An opinionated chat agent base class.
|
|
250
330
|
*
|
|
251
|
-
* @experimental
|
|
331
|
+
* @experimental The API surface may change before stabilizing.
|
|
252
332
|
*/
|
|
253
333
|
declare class Think<
|
|
254
334
|
Env extends Cloudflare.Env = Cloudflare.Env,
|
|
@@ -399,24 +479,49 @@ declare class Think<
|
|
|
399
479
|
*/
|
|
400
480
|
beforeTurn(_ctx: TurnContext): TurnConfig | void | Promise<TurnConfig | void>;
|
|
401
481
|
/**
|
|
402
|
-
* Called
|
|
403
|
-
*
|
|
482
|
+
* Called **before** the tool's `execute` function runs. Think wraps
|
|
483
|
+
* every tool's `execute` so it can consult this hook and act on the
|
|
484
|
+
* returned `ToolCallDecision`:
|
|
404
485
|
*
|
|
405
|
-
*
|
|
406
|
-
* `
|
|
407
|
-
*
|
|
408
|
-
*
|
|
409
|
-
*
|
|
486
|
+
* - `void` (or `{ action: "allow" }` with no `input`) — run the
|
|
487
|
+
* original `execute` with the original input.
|
|
488
|
+
* - `{ action: "allow", input }` — run the original `execute` with
|
|
489
|
+
* the substituted input.
|
|
490
|
+
* - `{ action: "block", reason }` — skip `execute`; the model sees
|
|
491
|
+
* `reason` as the tool's output.
|
|
492
|
+
* - `{ action: "substitute", output }` — skip `execute`; the model
|
|
493
|
+
* sees `output` as the tool's output.
|
|
410
494
|
*
|
|
411
|
-
* Only fires for server-side tools (tools with `execute`).
|
|
412
|
-
*
|
|
495
|
+
* Only fires for server-side tools (tools with `execute`). Client
|
|
496
|
+
* tools are handled on the client — Think can't intercept them.
|
|
413
497
|
*
|
|
414
|
-
*
|
|
498
|
+
* `afterToolCall` always fires after this hook (or after the original
|
|
499
|
+
* `execute` when `allow`). For `block`/`substitute`, the substituted
|
|
500
|
+
* value flows through `afterToolCall` as `success: true, output: ...`.
|
|
415
501
|
*
|
|
416
502
|
* @example Log tool calls
|
|
417
503
|
* ```typescript
|
|
418
504
|
* beforeToolCall(ctx: ToolCallContext) {
|
|
419
|
-
* console.log(`Tool called: ${ctx.toolName}`, ctx.
|
|
505
|
+
* console.log(`Tool called: ${ctx.toolName}`, ctx.input);
|
|
506
|
+
* }
|
|
507
|
+
* ```
|
|
508
|
+
*
|
|
509
|
+
* @example Block a tool the model shouldn't be calling here
|
|
510
|
+
* ```typescript
|
|
511
|
+
* beforeToolCall(ctx: ToolCallContext): ToolCallDecision | void {
|
|
512
|
+
* if (ctx.toolName === "delete" && this.isReadOnlyMode) {
|
|
513
|
+
* return { action: "block", reason: "delete is disabled in read-only mode" };
|
|
514
|
+
* }
|
|
515
|
+
* }
|
|
516
|
+
* ```
|
|
517
|
+
*
|
|
518
|
+
* @example Substitute a cached result
|
|
519
|
+
* ```typescript
|
|
520
|
+
* async beforeToolCall(ctx: ToolCallContext): Promise<ToolCallDecision | void> {
|
|
521
|
+
* if (ctx.toolName === "weather") {
|
|
522
|
+
* const cached = await this.cache.get(JSON.stringify(ctx.input));
|
|
523
|
+
* if (cached) return { action: "substitute", output: cached };
|
|
524
|
+
* }
|
|
420
525
|
* }
|
|
421
526
|
* ```
|
|
422
527
|
*/
|
|
@@ -424,10 +529,27 @@ declare class Think<
|
|
|
424
529
|
_ctx: ToolCallContext
|
|
425
530
|
): ToolCallDecision | void | Promise<ToolCallDecision | void>;
|
|
426
531
|
/**
|
|
427
|
-
* Called after a tool
|
|
428
|
-
*
|
|
532
|
+
* Called **after** a tool's outcome is known — for real executions, for
|
|
533
|
+
* `block` (carries the `reason` as `output`), and for `substitute`
|
|
534
|
+
* (carries the substituted `output`). Backed by the AI SDK's
|
|
535
|
+
* `experimental_onToolCallFinish`, so `durationMs` and the discriminated
|
|
536
|
+
* `success`/`output`/`error` outcome reflect what the model actually
|
|
537
|
+
* sees: a thrown error from the original `execute` becomes
|
|
538
|
+
* `success: false, error: ...`; everything else (including blocked /
|
|
539
|
+
* substituted calls) is `success: true, output: ...`.
|
|
429
540
|
*
|
|
430
541
|
* Override for logging, metrics, or result inspection.
|
|
542
|
+
*
|
|
543
|
+
* @example
|
|
544
|
+
* ```typescript
|
|
545
|
+
* afterToolCall(ctx: ToolCallResultContext) {
|
|
546
|
+
* if (ctx.success) {
|
|
547
|
+
* console.log(`${ctx.toolName} ok in ${ctx.durationMs}ms`);
|
|
548
|
+
* } else {
|
|
549
|
+
* console.error(`${ctx.toolName} failed:`, ctx.error);
|
|
550
|
+
* }
|
|
551
|
+
* }
|
|
552
|
+
* ```
|
|
431
553
|
*/
|
|
432
554
|
afterToolCall(_ctx: ToolCallResultContext): void | Promise<void>;
|
|
433
555
|
/**
|
|
@@ -478,6 +600,58 @@ declare class Think<
|
|
|
478
600
|
* Extensions that don't subscribe to beforeTurn are skipped.
|
|
479
601
|
*/
|
|
480
602
|
private _pipelineExtensionBeforeTurn;
|
|
603
|
+
/**
|
|
604
|
+
* Dispatch an observation hook to all extensions that subscribe to it.
|
|
605
|
+
*
|
|
606
|
+
* Used by `_pipelineExtensionToolCallStart`, `_pipelineExtensionToolCallFinish`,
|
|
607
|
+
* `_pipelineExtensionStepFinish`, and `_pipelineExtensionChunk`. Unlike
|
|
608
|
+
* `beforeTurn`, these hooks are observation-only — extensions can't
|
|
609
|
+
* influence the turn — so we ignore return values, log errors, and
|
|
610
|
+
* apply a per-extension timeout.
|
|
611
|
+
*
|
|
612
|
+
* `onChunk` is high-frequency (per token) — extensions that subscribe
|
|
613
|
+
* to it pay an RPC cost per chunk and should be used sparingly.
|
|
614
|
+
*/
|
|
615
|
+
private _dispatchExtensionObservation;
|
|
616
|
+
/**
|
|
617
|
+
* Wrap each tool's `execute` function so the agent's `beforeToolCall`
|
|
618
|
+
* hook is consulted before the tool runs. The hook can return a
|
|
619
|
+
* `ToolCallDecision` to:
|
|
620
|
+
*
|
|
621
|
+
* - `allow` (default if `void` is returned) — run the original
|
|
622
|
+
* `execute`, optionally with a substituted `input`.
|
|
623
|
+
* - `block` — skip `execute` and return `reason` (or a default string)
|
|
624
|
+
* as the tool result. The model sees this as the tool's output.
|
|
625
|
+
* - `substitute` — skip `execute` and return `output` directly. The
|
|
626
|
+
* model sees this as the tool's output.
|
|
627
|
+
*
|
|
628
|
+
* The wrapped `execute` also dispatches the `beforeToolCall`
|
|
629
|
+
* observation snapshot to subscribed extensions. `afterToolCall` is
|
|
630
|
+
* still wired through the AI SDK's `experimental_onToolCallFinish`
|
|
631
|
+
* callback so we get accurate `durationMs` and proper success/error
|
|
632
|
+
* discrimination — `block` and `substitute` outcomes show up as
|
|
633
|
+
* `success: true` with the substituted output; uncaught throws from
|
|
634
|
+
* the original `execute` show up as `success: false` with the error.
|
|
635
|
+
*
|
|
636
|
+
* Tools without an `execute` (output-schema-only tools, client tools
|
|
637
|
+
* routed via `needsApproval`) are left untouched.
|
|
638
|
+
*
|
|
639
|
+
* **Streaming tools (AsyncIterable):** the AI SDK supports tools whose
|
|
640
|
+
* `execute` returns `AsyncIterable<output>` to emit preliminary
|
|
641
|
+
* results before a final value. This works whether the iterator is
|
|
642
|
+
* returned directly (sync function, `async function*`) or wrapped in
|
|
643
|
+
* a Promise (`async function execute(...) { return makeIter(); }`).
|
|
644
|
+
* Because the wrapper must `await beforeToolCall` first, preliminary
|
|
645
|
+
* chunks are collapsed — only the *final* yielded value reaches the
|
|
646
|
+
* model. If you need true preliminary streaming, override
|
|
647
|
+
* `getTools()` to provide such tools and avoid using `beforeToolCall`
|
|
648
|
+
* for them (or accept the collapse).
|
|
649
|
+
*/
|
|
650
|
+
private _wrapToolsWithDecision;
|
|
651
|
+
private _pipelineExtensionToolCallStart;
|
|
652
|
+
private _pipelineExtensionToolCallFinish;
|
|
653
|
+
private _pipelineExtensionStepFinish;
|
|
654
|
+
private _pipelineExtensionChunk;
|
|
481
655
|
_hostReadFile(path: string): Promise<string | null>;
|
|
482
656
|
_hostWriteFile(path: string, content: string): Promise<void>;
|
|
483
657
|
_hostDeleteFile(path: string): Promise<boolean>;
|
|
@@ -631,6 +805,7 @@ export {
|
|
|
631
805
|
ChatRecoveryOptions,
|
|
632
806
|
ChatResponseResult,
|
|
633
807
|
ChunkContext,
|
|
808
|
+
ChunkPart,
|
|
634
809
|
ExtensionConfig,
|
|
635
810
|
type FiberContext,
|
|
636
811
|
type FiberRecoveryContext,
|
|
@@ -638,8 +813,10 @@ export {
|
|
|
638
813
|
SaveMessagesResult,
|
|
639
814
|
Session,
|
|
640
815
|
StepContext,
|
|
816
|
+
type StepResult,
|
|
641
817
|
StreamCallback,
|
|
642
818
|
StreamableResult,
|
|
819
|
+
type TextStreamPart,
|
|
643
820
|
Think,
|
|
644
821
|
ToolCallContext,
|
|
645
822
|
ToolCallDecision,
|
|
@@ -647,6 +824,8 @@ export {
|
|
|
647
824
|
TurnConfig,
|
|
648
825
|
TurnContext,
|
|
649
826
|
TurnInput,
|
|
827
|
+
type TypedToolCall,
|
|
828
|
+
type TypedToolResult,
|
|
650
829
|
Workspace
|
|
651
830
|
};
|
|
652
831
|
//# sourceMappingURL=think.d.ts.map
|