@cloudflare/think 0.2.5 → 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/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";
@@ -139,74 +146,141 @@ interface TurnConfig {
139
146
  providerOptions?: Record<string, unknown>;
140
147
  }
141
148
  /**
142
- * Context passed to the `beforeToolCall` hook when the model
143
- * produces a tool call, before the tool's execute function runs.
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
+ * ```
144
174
  */
145
- interface ToolCallContext {
146
- /** Name of the tool being called. */
147
- toolName: string;
148
- /** Arguments the model provided. */
149
- args: Record<string, unknown>;
150
- }
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
+ };
151
183
  /**
152
184
  * Decision returned by `beforeToolCall` to control tool execution.
153
- * Return void/undefined to allow execution with original args.
185
+ * Return void/undefined to allow execution with original input.
154
186
  *
155
187
  * Discriminated union — each action has a clear, non-overlapping meaning:
156
- * - `allow` — execute the tool (optionally with modified args)
188
+ * - `allow` — execute the tool (optionally with modified input)
157
189
  * - `block` — don't execute; return `reason` as the tool result so the model can adjust
158
- * - `substitute` — don't execute; return `result` as the tool result (afterToolCall still fires)
190
+ * - `substitute` — don't execute; return `output` as the tool result (afterToolCall still fires)
159
191
  */
160
192
  type ToolCallDecision =
161
193
  | {
162
- action: "allow" /** Modified arguments — tool executes with these instead of the originals. */;
163
- args?: Record<string, unknown>;
194
+ action: "allow" /** Modified input — tool executes with this instead of the original. */;
195
+ input?: Record<string, unknown>;
164
196
  }
165
197
  | {
166
198
  action: "block" /** Returned as the tool result so the model can adjust. */;
167
199
  reason?: string;
168
200
  }
169
201
  | {
170
- action: "substitute" /** The substitute tool result — model sees this instead of real execution. */;
171
- result: unknown /** Optional arg attribution for the afterToolCall log. */;
172
- args?: Record<string, unknown>;
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>;
173
205
  };
174
206
  /**
175
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
+ * ```
176
235
  */
177
- interface ToolCallResultContext {
178
- /** Name of the tool that was called. */
179
- toolName: string;
180
- /** Arguments the tool was called with (may be modified by beforeToolCall). */
181
- args: Record<string, unknown>;
182
- /** The result returned by the tool (or substitute from beforeToolCall). */
183
- result: unknown;
184
- }
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
+ );
185
253
  /**
186
254
  * Context passed to the `onStepFinish` hook after each step completes.
187
- * Wraps the AI SDK's onStepFinish callback data.
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`.
188
264
  */
189
- type StepContext = {
190
- /** The type of step that completed. */ stepType:
191
- | "initial"
192
- | "continue"
193
- | "tool-result" /** Text generated in this step. */;
194
- text: string /** Tool calls made in this step. */;
195
- toolCalls: unknown[] /** Tool results received in this step. */;
196
- toolResults: unknown[] /** Why the step finished. */;
197
- finishReason: string /** Token usage for this step. */;
198
- usage: {
199
- inputTokens: number;
200
- outputTokens: number;
201
- };
202
- };
265
+ type StepContext<TOOLS extends ToolSet = ToolSet> = Parameters<
266
+ StreamTextOnStepFinishCallback<TOOLS>
267
+ >[0];
203
268
  /**
204
269
  * Context passed to the `onChunk` hook for each streaming chunk.
205
- * Wraps the AI SDK's onChunk callback data.
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).
206
275
  */
207
- type ChunkContext = {
208
- /** The chunk data from the AI SDK stream. */ chunk: unknown;
209
- };
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"];
210
284
  /**
211
285
  * Configuration for a sandboxed extension, returned by getExtensions().
212
286
  */
@@ -405,24 +479,49 @@ declare class Think<
405
479
  */
406
480
  beforeTurn(_ctx: TurnContext): TurnConfig | void | Promise<TurnConfig | void>;
407
481
  /**
408
- * Called when the model produces a tool call. Currently fires
409
- * **after** tool execution (via `onStepFinish` data) — observation only.
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`:
410
485
  *
411
- * **Known limitation:** `block` and `substitute` actions in the returned
412
- * `ToolCallDecision` are not yet functional. The AI SDK's `streamText`
413
- * does not expose a pre-execution interception point for tool calls
414
- * in the Workers runtime. The types are in place for when this becomes
415
- * possible (see plan: "Known limitations — Phase 1").
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.
416
494
  *
417
- * Only fires for server-side tools (tools with `execute`).
418
- * Client tools are handled on the client — Think can't intercept them.
495
+ * Only fires for server-side tools (tools with `execute`). Client
496
+ * tools are handled on the client — Think can't intercept them.
419
497
  *
420
- * Return `void` to accept default behavior.
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: ...`.
421
501
  *
422
502
  * @example Log tool calls
423
503
  * ```typescript
424
504
  * beforeToolCall(ctx: ToolCallContext) {
425
- * console.log(`Tool called: ${ctx.toolName}`, ctx.args);
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
+ * }
426
525
  * }
427
526
  * ```
428
527
  */
@@ -430,10 +529,27 @@ declare class Think<
430
529
  _ctx: ToolCallContext
431
530
  ): ToolCallDecision | void | Promise<ToolCallDecision | void>;
432
531
  /**
433
- * Called after a tool executes (or a substitute result is provided).
434
- * Does NOT fire when `beforeToolCall` blocks with no substitute result.
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: ...`.
435
540
  *
436
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
+ * ```
437
553
  */
438
554
  afterToolCall(_ctx: ToolCallResultContext): void | Promise<void>;
439
555
  /**
@@ -484,6 +600,58 @@ declare class Think<
484
600
  * Extensions that don't subscribe to beforeTurn are skipped.
485
601
  */
486
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;
487
655
  _hostReadFile(path: string): Promise<string | null>;
488
656
  _hostWriteFile(path: string, content: string): Promise<void>;
489
657
  _hostDeleteFile(path: string): Promise<boolean>;
@@ -637,6 +805,7 @@ export {
637
805
  ChatRecoveryOptions,
638
806
  ChatResponseResult,
639
807
  ChunkContext,
808
+ ChunkPart,
640
809
  ExtensionConfig,
641
810
  type FiberContext,
642
811
  type FiberRecoveryContext,
@@ -644,8 +813,10 @@ export {
644
813
  SaveMessagesResult,
645
814
  Session,
646
815
  StepContext,
816
+ type StepResult,
647
817
  StreamCallback,
648
818
  StreamableResult,
819
+ type TextStreamPart,
649
820
  Think,
650
821
  ToolCallContext,
651
822
  ToolCallDecision,
@@ -653,6 +824,8 @@ export {
653
824
  TurnConfig,
654
825
  TurnContext,
655
826
  TurnInput,
827
+ type TypedToolCall,
828
+ type TypedToolResult,
656
829
  Workspace
657
830
  };
658
831
  //# sourceMappingURL=think.d.ts.map