@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.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createWorkspaceTools } from "./tools/workspace.js";
2
- import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-fyJ3k1Ht.js";
2
+ import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-C7fYS0JL.js";
3
3
  import { convertToModelMessages, pruneMessages, stepCountIs, streamText } from "ai";
4
4
  import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext } from "agents";
5
5
  import { AbortRegistry, CHAT_MESSAGE_TYPES, ContinuationState, ResumableStream, StreamAccumulator, TurnQueue, applyChunkToParts, applyToolUpdate, createToolsFromClientSchemas, enforceRowSizeLimit, parseProtocolMessage, sanitizeMessage, toolApprovalUpdate, toolResultUpdate } from "agents/chat";
@@ -192,33 +192,75 @@ var Think = class Think extends Agent {
192
192
  */
193
193
  beforeTurn(_ctx) {}
194
194
  /**
195
- * Called when the model produces a tool call. Currently fires
196
- * **after** tool execution (via `onStepFinish` data) — observation only.
195
+ * Called **before** the tool's `execute` function runs. Think wraps
196
+ * every tool's `execute` so it can consult this hook and act on the
197
+ * returned `ToolCallDecision`:
197
198
  *
198
- * **Known limitation:** `block` and `substitute` actions in the returned
199
- * `ToolCallDecision` are not yet functional. The AI SDK's `streamText`
200
- * does not expose a pre-execution interception point for tool calls
201
- * in the Workers runtime. The types are in place for when this becomes
202
- * possible (see plan: "Known limitations — Phase 1").
199
+ * - `void` (or `{ action: "allow" }` with no `input`) — run the
200
+ * original `execute` with the original input.
201
+ * - `{ action: "allow", input }` — run the original `execute` with
202
+ * the substituted input.
203
+ * - `{ action: "block", reason }` — skip `execute`; the model sees
204
+ * `reason` as the tool's output.
205
+ * - `{ action: "substitute", output }` — skip `execute`; the model
206
+ * sees `output` as the tool's output.
203
207
  *
204
- * Only fires for server-side tools (tools with `execute`).
205
- * Client tools are handled on the client — Think can't intercept them.
208
+ * Only fires for server-side tools (tools with `execute`). Client
209
+ * tools are handled on the client — Think can't intercept them.
206
210
  *
207
- * Return `void` to accept default behavior.
211
+ * `afterToolCall` always fires after this hook (or after the original
212
+ * `execute` when `allow`). For `block`/`substitute`, the substituted
213
+ * value flows through `afterToolCall` as `success: true, output: ...`.
208
214
  *
209
215
  * @example Log tool calls
210
216
  * ```typescript
211
217
  * beforeToolCall(ctx: ToolCallContext) {
212
- * console.log(`Tool called: ${ctx.toolName}`, ctx.args);
218
+ * console.log(`Tool called: ${ctx.toolName}`, ctx.input);
219
+ * }
220
+ * ```
221
+ *
222
+ * @example Block a tool the model shouldn't be calling here
223
+ * ```typescript
224
+ * beforeToolCall(ctx: ToolCallContext): ToolCallDecision | void {
225
+ * if (ctx.toolName === "delete" && this.isReadOnlyMode) {
226
+ * return { action: "block", reason: "delete is disabled in read-only mode" };
227
+ * }
228
+ * }
229
+ * ```
230
+ *
231
+ * @example Substitute a cached result
232
+ * ```typescript
233
+ * async beforeToolCall(ctx: ToolCallContext): Promise<ToolCallDecision | void> {
234
+ * if (ctx.toolName === "weather") {
235
+ * const cached = await this.cache.get(JSON.stringify(ctx.input));
236
+ * if (cached) return { action: "substitute", output: cached };
237
+ * }
213
238
  * }
214
239
  * ```
215
240
  */
216
241
  beforeToolCall(_ctx) {}
217
242
  /**
218
- * Called after a tool executes (or a substitute result is provided).
219
- * Does NOT fire when `beforeToolCall` blocks with no substitute result.
243
+ * Called **after** a tool's outcome is known — for real executions, for
244
+ * `block` (carries the `reason` as `output`), and for `substitute`
245
+ * (carries the substituted `output`). Backed by the AI SDK's
246
+ * `experimental_onToolCallFinish`, so `durationMs` and the discriminated
247
+ * `success`/`output`/`error` outcome reflect what the model actually
248
+ * sees: a thrown error from the original `execute` becomes
249
+ * `success: false, error: ...`; everything else (including blocked /
250
+ * substituted calls) is `success: true, output: ...`.
220
251
  *
221
252
  * Override for logging, metrics, or result inspection.
253
+ *
254
+ * @example
255
+ * ```typescript
256
+ * afterToolCall(ctx: ToolCallResultContext) {
257
+ * if (ctx.success) {
258
+ * console.log(`${ctx.toolName} ok in ${ctx.durationMs}ms`);
259
+ * } else {
260
+ * console.error(`${ctx.toolName} failed:`, ctx.error);
261
+ * }
262
+ * }
263
+ * ```
222
264
  */
223
265
  afterToolCall(_ctx) {}
224
266
  /**
@@ -251,8 +293,8 @@ var Think = class Think extends Agent {
251
293
  return error;
252
294
  }
253
295
  async _initializeExtensions() {
254
- const { ExtensionManager } = await import("./manager-BTBhPS6g.js").then((n) => n.n);
255
- const { sanitizeName } = await import("./manager-BTBhPS6g.js").then((n) => n.n);
296
+ const { ExtensionManager } = await import("./manager-CR9ZdLiu.js").then((n) => n.n);
297
+ const { sanitizeName } = await import("./manager-CR9ZdLiu.js").then((n) => n.n);
256
298
  const agentClassName = this.constructor.name;
257
299
  const agentId = this.ctx.id.toString();
258
300
  const ctxExports = this.ctx.exports;
@@ -331,10 +373,11 @@ var Think = class Think extends Agent {
331
373
  const finalModel = config.model ?? model;
332
374
  const finalSystem = config.system ?? system;
333
375
  const finalMessages = config.messages ?? messages;
334
- const finalTools = config.tools ? {
376
+ const mergedTools = config.tools ? {
335
377
  ...tools,
336
378
  ...config.tools
337
379
  } : tools;
380
+ const finalTools = this._wrapToolsWithDecision(mergedTools);
338
381
  const finalMaxSteps = config.maxSteps ?? this.maxSteps;
339
382
  const result = streamText({
340
383
  model: finalModel,
@@ -347,39 +390,32 @@ var Think = class Think extends Agent {
347
390
  providerOptions: config.providerOptions,
348
391
  abortSignal: input.signal,
349
392
  onChunk: async (event) => {
350
- await this.onChunk({ chunk: event.chunk });
393
+ await this.onChunk(event);
394
+ await this._pipelineExtensionChunk(event);
351
395
  },
352
396
  onStepFinish: async (event) => {
353
- const toolCalls = event.toolCalls ?? [];
354
- const toolResults = event.toolResults ?? [];
355
- for (let i = 0; i < toolCalls.length; i++) {
356
- const tc = toolCalls[i];
357
- if (tc) await this.beforeToolCall({
358
- toolName: tc.toolName ?? tc.name ?? "",
359
- args: tc.args ?? {}
360
- });
361
- }
362
- for (let i = 0; i < toolResults.length; i++) {
363
- const tr = toolResults[i];
364
- const tc = toolCalls[i];
365
- if (tr) await this.afterToolCall({
366
- toolName: tc?.toolName ?? tc?.name ?? tr?.toolName ?? "",
367
- args: tc?.args ?? {},
368
- result: tr.result
369
- });
370
- }
371
- await this.onStepFinish({
372
- stepType: event.stepType ?? "initial",
373
- text: event.text ?? "",
374
- toolCalls,
375
- toolResults,
376
- finishReason: event.finishReason ?? "stop",
377
- usage: {
378
- inputTokens: event.usage?.inputTokens ?? 0,
379
- outputTokens: event.usage?.outputTokens ?? 0
380
- }
381
- });
382
- }
397
+ await this.onStepFinish(event);
398
+ await this._pipelineExtensionStepFinish(event);
399
+ },
400
+ experimental_onToolCallFinish: (async (event) => {
401
+ const base = {
402
+ ...event.toolCall,
403
+ stepNumber: event.stepNumber,
404
+ messages: event.messages,
405
+ durationMs: event.durationMs
406
+ };
407
+ const ctx = event.success ? {
408
+ ...base,
409
+ success: true,
410
+ output: event.output
411
+ } : {
412
+ ...base,
413
+ success: false,
414
+ error: event.error
415
+ };
416
+ await this.afterToolCall(ctx);
417
+ await this._pipelineExtensionToolCallFinish(event);
418
+ })
383
419
  });
384
420
  return this._transformInferenceResult(result);
385
421
  }
@@ -398,7 +434,7 @@ var Think = class Think extends Agent {
398
434
  if (!this.extensionManager) return subclassConfig;
399
435
  const subscribers = this.extensionManager.getHookSubscribers("beforeTurn");
400
436
  if (subscribers.length === 0) return subclassConfig;
401
- const { createTurnContextSnapshot, parseHookResult } = await import("./hook-proxy-f_DqtJ9u.js");
437
+ const { createTurnContextSnapshot, parseHookResult } = await import("./hook-proxy-5248W-ea.js");
402
438
  let snapshot = createTurnContextSnapshot(ctx);
403
439
  let accumulated = { ...subclassConfig };
404
440
  if (accumulated.system !== void 0) snapshot.system = accumulated.system;
@@ -436,6 +472,145 @@ var Think = class Think extends Agent {
436
472
  }
437
473
  return accumulated;
438
474
  }
475
+ /**
476
+ * Dispatch an observation hook to all extensions that subscribe to it.
477
+ *
478
+ * Used by `_pipelineExtensionToolCallStart`, `_pipelineExtensionToolCallFinish`,
479
+ * `_pipelineExtensionStepFinish`, and `_pipelineExtensionChunk`. Unlike
480
+ * `beforeTurn`, these hooks are observation-only — extensions can't
481
+ * influence the turn — so we ignore return values, log errors, and
482
+ * apply a per-extension timeout.
483
+ *
484
+ * `onChunk` is high-frequency (per token) — extensions that subscribe
485
+ * to it pay an RPC cost per chunk and should be used sparingly.
486
+ */
487
+ async _dispatchExtensionObservation(hookName, snapshot) {
488
+ if (!this.extensionManager) return;
489
+ const subscribers = this.extensionManager.getHookSubscribers(hookName);
490
+ if (subscribers.length === 0) return;
491
+ for (const sub of subscribers) {
492
+ let timer;
493
+ try {
494
+ await Promise.race([sub.entrypoint.hook(hookName, snapshot), new Promise((_, reject) => {
495
+ timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`Hook timeout: ${sub.name}`)), this.hookTimeout);
496
+ })]);
497
+ } catch (err) {
498
+ console.warn(`[Think] Extension "${sub.name}" ${hookName} failed:`, err instanceof Error ? err.message : err);
499
+ } finally {
500
+ if (timer !== void 0) clearTimeout(timer);
501
+ }
502
+ }
503
+ }
504
+ /**
505
+ * Wrap each tool's `execute` function so the agent's `beforeToolCall`
506
+ * hook is consulted before the tool runs. The hook can return a
507
+ * `ToolCallDecision` to:
508
+ *
509
+ * - `allow` (default if `void` is returned) — run the original
510
+ * `execute`, optionally with a substituted `input`.
511
+ * - `block` — skip `execute` and return `reason` (or a default string)
512
+ * as the tool result. The model sees this as the tool's output.
513
+ * - `substitute` — skip `execute` and return `output` directly. The
514
+ * model sees this as the tool's output.
515
+ *
516
+ * The wrapped `execute` also dispatches the `beforeToolCall`
517
+ * observation snapshot to subscribed extensions. `afterToolCall` is
518
+ * still wired through the AI SDK's `experimental_onToolCallFinish`
519
+ * callback so we get accurate `durationMs` and proper success/error
520
+ * discrimination — `block` and `substitute` outcomes show up as
521
+ * `success: true` with the substituted output; uncaught throws from
522
+ * the original `execute` show up as `success: false` with the error.
523
+ *
524
+ * Tools without an `execute` (output-schema-only tools, client tools
525
+ * routed via `needsApproval`) are left untouched.
526
+ *
527
+ * **Streaming tools (AsyncIterable):** the AI SDK supports tools whose
528
+ * `execute` returns `AsyncIterable<output>` to emit preliminary
529
+ * results before a final value. This works whether the iterator is
530
+ * returned directly (sync function, `async function*`) or wrapped in
531
+ * a Promise (`async function execute(...) { return makeIter(); }`).
532
+ * Because the wrapper must `await beforeToolCall` first, preliminary
533
+ * chunks are collapsed — only the *final* yielded value reaches the
534
+ * model. If you need true preliminary streaming, override
535
+ * `getTools()` to provide such tools and avoid using `beforeToolCall`
536
+ * for them (or accept the collapse).
537
+ */
538
+ _wrapToolsWithDecision(tools) {
539
+ const wrapped = {};
540
+ for (const [toolName, originalTool] of Object.entries(tools)) {
541
+ const t = originalTool;
542
+ const originalExecute = t.execute;
543
+ if (typeof originalExecute !== "function") {
544
+ wrapped[toolName] = originalTool;
545
+ continue;
546
+ }
547
+ const isDynamic = t.type === "dynamic";
548
+ const wrappedExecute = async (input, options) => {
549
+ const toolCallBase = {
550
+ type: "tool-call",
551
+ toolCallId: options.toolCallId,
552
+ toolName,
553
+ input,
554
+ ...isDynamic ? { dynamic: true } : {}
555
+ };
556
+ const ctx = {
557
+ ...toolCallBase,
558
+ stepNumber: void 0,
559
+ messages: options.messages,
560
+ abortSignal: options.abortSignal
561
+ };
562
+ const decision = await this.beforeToolCall(ctx);
563
+ const dispatchInput = decision && decision.action === "allow" && decision.input ? decision.input : input;
564
+ await this._pipelineExtensionToolCallStart({
565
+ toolCall: {
566
+ ...toolCallBase,
567
+ input: dispatchInput
568
+ },
569
+ stepNumber: void 0
570
+ });
571
+ if (!decision || decision.action === "allow") {
572
+ const result = await originalExecute(decision?.input ?? input, options);
573
+ if (result != null && typeof result === "object" && Symbol.asyncIterator in result) {
574
+ let last;
575
+ for await (const part of result) last = part;
576
+ return last;
577
+ }
578
+ return result;
579
+ }
580
+ if (decision.action === "block") return decision.reason ?? `Tool "${toolName}" was blocked by beforeToolCall.`;
581
+ return decision.output;
582
+ };
583
+ wrapped[toolName] = {
584
+ ...originalTool,
585
+ execute: wrappedExecute
586
+ };
587
+ }
588
+ return wrapped;
589
+ }
590
+ async _pipelineExtensionToolCallStart(event) {
591
+ if (!this.extensionManager) return;
592
+ if (this.extensionManager.getHookSubscribers("beforeToolCall").length === 0) return;
593
+ const { createToolCallStartSnapshot } = await import("./hook-proxy-5248W-ea.js");
594
+ await this._dispatchExtensionObservation("beforeToolCall", createToolCallStartSnapshot(event));
595
+ }
596
+ async _pipelineExtensionToolCallFinish(event) {
597
+ if (!this.extensionManager) return;
598
+ if (this.extensionManager.getHookSubscribers("afterToolCall").length === 0) return;
599
+ const { createToolCallFinishSnapshot } = await import("./hook-proxy-5248W-ea.js");
600
+ await this._dispatchExtensionObservation("afterToolCall", createToolCallFinishSnapshot(event));
601
+ }
602
+ async _pipelineExtensionStepFinish(event) {
603
+ if (!this.extensionManager) return;
604
+ if (this.extensionManager.getHookSubscribers("onStepFinish").length === 0) return;
605
+ const { createStepFinishSnapshot } = await import("./hook-proxy-5248W-ea.js");
606
+ await this._dispatchExtensionObservation("onStepFinish", createStepFinishSnapshot(event));
607
+ }
608
+ async _pipelineExtensionChunk(event) {
609
+ if (!this.extensionManager) return;
610
+ if (this.extensionManager.getHookSubscribers("onChunk").length === 0) return;
611
+ const { createChunkSnapshot } = await import("./hook-proxy-5248W-ea.js");
612
+ await this._dispatchExtensionObservation("onChunk", createChunkSnapshot(event));
613
+ }
439
614
  async _hostReadFile(path) {
440
615
  return await this.workspace.readFile(path) ?? null;
441
616
  }
@@ -839,7 +1014,8 @@ var Think = class Think extends Agent {
839
1014
  this._lastClientTools = void 0;
840
1015
  this._persistClientTools();
841
1016
  }
842
- this._lastBody = Object.keys(customBody).length > 0 ? customBody : void 0;
1017
+ const requestBody = Object.keys(customBody).length > 0 ? customBody : void 0;
1018
+ this._lastBody = requestBody;
843
1019
  this._persistBody();
844
1020
  const clientToolsForTurn = this._lastClientTools;
845
1021
  const bodyForTurn = this._lastBody;