@cloudflare/think 0.2.5 → 0.4.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 +90 -6
- package/dist/{classPrivateFieldGet2-fyJ3k1Ht.js → classPrivateFieldGet2-C7fYS0JL.js} +5 -5
- package/dist/extensions/index.js +2 -2
- 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 +275 -143
- package/dist/think.js +244 -53
- package/dist/think.js.map +1 -1
- package/dist/tools/browser.d.ts +1 -1
- package/dist/tools/browser.js +1 -1
- package/dist/tools/browser.js.map +1 -1
- package/dist/tools/extensions.js +1 -1
- package/package.json +2 -2
- package/dist/hook-proxy-f_DqtJ9u.js +0 -32
- package/dist/hook-proxy-f_DqtJ9u.js.map +0 -1
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-
|
|
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";
|
|
@@ -68,8 +68,18 @@ var Think = class Think extends Agent {
|
|
|
68
68
|
return this.session.getHistory();
|
|
69
69
|
}
|
|
70
70
|
/**
|
|
71
|
-
* Persist
|
|
72
|
-
* Stored in
|
|
71
|
+
* Persist an arbitrary JSON-serializable configuration object for this
|
|
72
|
+
* agent instance. Stored in the assistant_config table — survives
|
|
73
|
+
* restarts and hibernation. Pass the config shape as a method generic
|
|
74
|
+
* for typed call sites:
|
|
75
|
+
*
|
|
76
|
+
* ```ts
|
|
77
|
+
* this.configure<MyConfig>({ modelTier: "fast" });
|
|
78
|
+
* ```
|
|
79
|
+
*
|
|
80
|
+
* Prefer `state` / `setState` from `Agent` when you want the value
|
|
81
|
+
* broadcast to connected clients. Use `configure` for private
|
|
82
|
+
* per-instance config that should stay server-side.
|
|
73
83
|
*/
|
|
74
84
|
configure(config) {
|
|
75
85
|
const json = JSON.stringify(config);
|
|
@@ -78,9 +88,14 @@ var Think = class Think extends Agent {
|
|
|
78
88
|
}
|
|
79
89
|
/**
|
|
80
90
|
* Read the persisted configuration, or null if never configured.
|
|
91
|
+
* Pass the config shape as a method generic for a typed result:
|
|
92
|
+
*
|
|
93
|
+
* ```ts
|
|
94
|
+
* const cfg = this.getConfig<MyConfig>();
|
|
95
|
+
* ```
|
|
81
96
|
*/
|
|
82
97
|
getConfig() {
|
|
83
|
-
if (_classPrivateFieldGet2(_configCache, this)) return _classPrivateFieldGet2(_configCache, this);
|
|
98
|
+
if (_classPrivateFieldGet2(_configCache, this) !== null) return _classPrivateFieldGet2(_configCache, this);
|
|
84
99
|
const raw = this._configGet("_think_config");
|
|
85
100
|
if (raw !== void 0) {
|
|
86
101
|
_classPrivateFieldSet2(_configCache, this, JSON.parse(raw));
|
|
@@ -192,33 +207,75 @@ var Think = class Think extends Agent {
|
|
|
192
207
|
*/
|
|
193
208
|
beforeTurn(_ctx) {}
|
|
194
209
|
/**
|
|
195
|
-
* Called
|
|
196
|
-
*
|
|
210
|
+
* Called **before** the tool's `execute` function runs. Think wraps
|
|
211
|
+
* every tool's `execute` so it can consult this hook and act on the
|
|
212
|
+
* returned `ToolCallDecision`:
|
|
197
213
|
*
|
|
198
|
-
*
|
|
199
|
-
* `
|
|
200
|
-
*
|
|
201
|
-
*
|
|
202
|
-
*
|
|
214
|
+
* - `void` (or `{ action: "allow" }` with no `input`) — run the
|
|
215
|
+
* original `execute` with the original input.
|
|
216
|
+
* - `{ action: "allow", input }` — run the original `execute` with
|
|
217
|
+
* the substituted input.
|
|
218
|
+
* - `{ action: "block", reason }` — skip `execute`; the model sees
|
|
219
|
+
* `reason` as the tool's output.
|
|
220
|
+
* - `{ action: "substitute", output }` — skip `execute`; the model
|
|
221
|
+
* sees `output` as the tool's output.
|
|
203
222
|
*
|
|
204
|
-
* Only fires for server-side tools (tools with `execute`).
|
|
205
|
-
*
|
|
223
|
+
* Only fires for server-side tools (tools with `execute`). Client
|
|
224
|
+
* tools are handled on the client — Think can't intercept them.
|
|
206
225
|
*
|
|
207
|
-
*
|
|
226
|
+
* `afterToolCall` always fires after this hook (or after the original
|
|
227
|
+
* `execute` when `allow`). For `block`/`substitute`, the substituted
|
|
228
|
+
* value flows through `afterToolCall` as `success: true, output: ...`.
|
|
208
229
|
*
|
|
209
230
|
* @example Log tool calls
|
|
210
231
|
* ```typescript
|
|
211
232
|
* beforeToolCall(ctx: ToolCallContext) {
|
|
212
|
-
* console.log(`Tool called: ${ctx.toolName}`, ctx.
|
|
233
|
+
* console.log(`Tool called: ${ctx.toolName}`, ctx.input);
|
|
234
|
+
* }
|
|
235
|
+
* ```
|
|
236
|
+
*
|
|
237
|
+
* @example Block a tool the model shouldn't be calling here
|
|
238
|
+
* ```typescript
|
|
239
|
+
* beforeToolCall(ctx: ToolCallContext): ToolCallDecision | void {
|
|
240
|
+
* if (ctx.toolName === "delete" && this.isReadOnlyMode) {
|
|
241
|
+
* return { action: "block", reason: "delete is disabled in read-only mode" };
|
|
242
|
+
* }
|
|
243
|
+
* }
|
|
244
|
+
* ```
|
|
245
|
+
*
|
|
246
|
+
* @example Substitute a cached result
|
|
247
|
+
* ```typescript
|
|
248
|
+
* async beforeToolCall(ctx: ToolCallContext): Promise<ToolCallDecision | void> {
|
|
249
|
+
* if (ctx.toolName === "weather") {
|
|
250
|
+
* const cached = await this.cache.get(JSON.stringify(ctx.input));
|
|
251
|
+
* if (cached) return { action: "substitute", output: cached };
|
|
252
|
+
* }
|
|
213
253
|
* }
|
|
214
254
|
* ```
|
|
215
255
|
*/
|
|
216
256
|
beforeToolCall(_ctx) {}
|
|
217
257
|
/**
|
|
218
|
-
* Called after a tool
|
|
219
|
-
*
|
|
258
|
+
* Called **after** a tool's outcome is known — for real executions, for
|
|
259
|
+
* `block` (carries the `reason` as `output`), and for `substitute`
|
|
260
|
+
* (carries the substituted `output`). Backed by the AI SDK's
|
|
261
|
+
* `experimental_onToolCallFinish`, so `durationMs` and the discriminated
|
|
262
|
+
* `success`/`output`/`error` outcome reflect what the model actually
|
|
263
|
+
* sees: a thrown error from the original `execute` becomes
|
|
264
|
+
* `success: false, error: ...`; everything else (including blocked /
|
|
265
|
+
* substituted calls) is `success: true, output: ...`.
|
|
220
266
|
*
|
|
221
267
|
* Override for logging, metrics, or result inspection.
|
|
268
|
+
*
|
|
269
|
+
* @example
|
|
270
|
+
* ```typescript
|
|
271
|
+
* afterToolCall(ctx: ToolCallResultContext) {
|
|
272
|
+
* if (ctx.success) {
|
|
273
|
+
* console.log(`${ctx.toolName} ok in ${ctx.durationMs}ms`);
|
|
274
|
+
* } else {
|
|
275
|
+
* console.error(`${ctx.toolName} failed:`, ctx.error);
|
|
276
|
+
* }
|
|
277
|
+
* }
|
|
278
|
+
* ```
|
|
222
279
|
*/
|
|
223
280
|
afterToolCall(_ctx) {}
|
|
224
281
|
/**
|
|
@@ -251,8 +308,8 @@ var Think = class Think extends Agent {
|
|
|
251
308
|
return error;
|
|
252
309
|
}
|
|
253
310
|
async _initializeExtensions() {
|
|
254
|
-
const { ExtensionManager } = await import("./manager-
|
|
255
|
-
const { sanitizeName } = await import("./manager-
|
|
311
|
+
const { ExtensionManager } = await import("./manager-CR9ZdLiu.js").then((n) => n.n);
|
|
312
|
+
const { sanitizeName } = await import("./manager-CR9ZdLiu.js").then((n) => n.n);
|
|
256
313
|
const agentClassName = this.constructor.name;
|
|
257
314
|
const agentId = this.ctx.id.toString();
|
|
258
315
|
const ctxExports = this.ctx.exports;
|
|
@@ -331,10 +388,11 @@ var Think = class Think extends Agent {
|
|
|
331
388
|
const finalModel = config.model ?? model;
|
|
332
389
|
const finalSystem = config.system ?? system;
|
|
333
390
|
const finalMessages = config.messages ?? messages;
|
|
334
|
-
const
|
|
391
|
+
const mergedTools = config.tools ? {
|
|
335
392
|
...tools,
|
|
336
393
|
...config.tools
|
|
337
394
|
} : tools;
|
|
395
|
+
const finalTools = this._wrapToolsWithDecision(mergedTools);
|
|
338
396
|
const finalMaxSteps = config.maxSteps ?? this.maxSteps;
|
|
339
397
|
const result = streamText({
|
|
340
398
|
model: finalModel,
|
|
@@ -347,39 +405,32 @@ var Think = class Think extends Agent {
|
|
|
347
405
|
providerOptions: config.providerOptions,
|
|
348
406
|
abortSignal: input.signal,
|
|
349
407
|
onChunk: async (event) => {
|
|
350
|
-
await this.onChunk(
|
|
408
|
+
await this.onChunk(event);
|
|
409
|
+
await this._pipelineExtensionChunk(event);
|
|
351
410
|
},
|
|
352
411
|
onStepFinish: async (event) => {
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
toolResults,
|
|
376
|
-
finishReason: event.finishReason ?? "stop",
|
|
377
|
-
usage: {
|
|
378
|
-
inputTokens: event.usage?.inputTokens ?? 0,
|
|
379
|
-
outputTokens: event.usage?.outputTokens ?? 0
|
|
380
|
-
}
|
|
381
|
-
});
|
|
382
|
-
}
|
|
412
|
+
await this.onStepFinish(event);
|
|
413
|
+
await this._pipelineExtensionStepFinish(event);
|
|
414
|
+
},
|
|
415
|
+
experimental_onToolCallFinish: (async (event) => {
|
|
416
|
+
const base = {
|
|
417
|
+
...event.toolCall,
|
|
418
|
+
stepNumber: event.stepNumber,
|
|
419
|
+
messages: event.messages,
|
|
420
|
+
durationMs: event.durationMs
|
|
421
|
+
};
|
|
422
|
+
const ctx = event.success ? {
|
|
423
|
+
...base,
|
|
424
|
+
success: true,
|
|
425
|
+
output: event.output
|
|
426
|
+
} : {
|
|
427
|
+
...base,
|
|
428
|
+
success: false,
|
|
429
|
+
error: event.error
|
|
430
|
+
};
|
|
431
|
+
await this.afterToolCall(ctx);
|
|
432
|
+
await this._pipelineExtensionToolCallFinish(event);
|
|
433
|
+
})
|
|
383
434
|
});
|
|
384
435
|
return this._transformInferenceResult(result);
|
|
385
436
|
}
|
|
@@ -398,7 +449,7 @@ var Think = class Think extends Agent {
|
|
|
398
449
|
if (!this.extensionManager) return subclassConfig;
|
|
399
450
|
const subscribers = this.extensionManager.getHookSubscribers("beforeTurn");
|
|
400
451
|
if (subscribers.length === 0) return subclassConfig;
|
|
401
|
-
const { createTurnContextSnapshot, parseHookResult } = await import("./hook-proxy-
|
|
452
|
+
const { createTurnContextSnapshot, parseHookResult } = await import("./hook-proxy-5248W-ea.js");
|
|
402
453
|
let snapshot = createTurnContextSnapshot(ctx);
|
|
403
454
|
let accumulated = { ...subclassConfig };
|
|
404
455
|
if (accumulated.system !== void 0) snapshot.system = accumulated.system;
|
|
@@ -436,6 +487,145 @@ var Think = class Think extends Agent {
|
|
|
436
487
|
}
|
|
437
488
|
return accumulated;
|
|
438
489
|
}
|
|
490
|
+
/**
|
|
491
|
+
* Dispatch an observation hook to all extensions that subscribe to it.
|
|
492
|
+
*
|
|
493
|
+
* Used by `_pipelineExtensionToolCallStart`, `_pipelineExtensionToolCallFinish`,
|
|
494
|
+
* `_pipelineExtensionStepFinish`, and `_pipelineExtensionChunk`. Unlike
|
|
495
|
+
* `beforeTurn`, these hooks are observation-only — extensions can't
|
|
496
|
+
* influence the turn — so we ignore return values, log errors, and
|
|
497
|
+
* apply a per-extension timeout.
|
|
498
|
+
*
|
|
499
|
+
* `onChunk` is high-frequency (per token) — extensions that subscribe
|
|
500
|
+
* to it pay an RPC cost per chunk and should be used sparingly.
|
|
501
|
+
*/
|
|
502
|
+
async _dispatchExtensionObservation(hookName, snapshot) {
|
|
503
|
+
if (!this.extensionManager) return;
|
|
504
|
+
const subscribers = this.extensionManager.getHookSubscribers(hookName);
|
|
505
|
+
if (subscribers.length === 0) return;
|
|
506
|
+
for (const sub of subscribers) {
|
|
507
|
+
let timer;
|
|
508
|
+
try {
|
|
509
|
+
await Promise.race([sub.entrypoint.hook(hookName, snapshot), new Promise((_, reject) => {
|
|
510
|
+
timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`Hook timeout: ${sub.name}`)), this.hookTimeout);
|
|
511
|
+
})]);
|
|
512
|
+
} catch (err) {
|
|
513
|
+
console.warn(`[Think] Extension "${sub.name}" ${hookName} failed:`, err instanceof Error ? err.message : err);
|
|
514
|
+
} finally {
|
|
515
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
/**
|
|
520
|
+
* Wrap each tool's `execute` function so the agent's `beforeToolCall`
|
|
521
|
+
* hook is consulted before the tool runs. The hook can return a
|
|
522
|
+
* `ToolCallDecision` to:
|
|
523
|
+
*
|
|
524
|
+
* - `allow` (default if `void` is returned) — run the original
|
|
525
|
+
* `execute`, optionally with a substituted `input`.
|
|
526
|
+
* - `block` — skip `execute` and return `reason` (or a default string)
|
|
527
|
+
* as the tool result. The model sees this as the tool's output.
|
|
528
|
+
* - `substitute` — skip `execute` and return `output` directly. The
|
|
529
|
+
* model sees this as the tool's output.
|
|
530
|
+
*
|
|
531
|
+
* The wrapped `execute` also dispatches the `beforeToolCall`
|
|
532
|
+
* observation snapshot to subscribed extensions. `afterToolCall` is
|
|
533
|
+
* still wired through the AI SDK's `experimental_onToolCallFinish`
|
|
534
|
+
* callback so we get accurate `durationMs` and proper success/error
|
|
535
|
+
* discrimination — `block` and `substitute` outcomes show up as
|
|
536
|
+
* `success: true` with the substituted output; uncaught throws from
|
|
537
|
+
* the original `execute` show up as `success: false` with the error.
|
|
538
|
+
*
|
|
539
|
+
* Tools without an `execute` (output-schema-only tools, client tools
|
|
540
|
+
* routed via `needsApproval`) are left untouched.
|
|
541
|
+
*
|
|
542
|
+
* **Streaming tools (AsyncIterable):** the AI SDK supports tools whose
|
|
543
|
+
* `execute` returns `AsyncIterable<output>` to emit preliminary
|
|
544
|
+
* results before a final value. This works whether the iterator is
|
|
545
|
+
* returned directly (sync function, `async function*`) or wrapped in
|
|
546
|
+
* a Promise (`async function execute(...) { return makeIter(); }`).
|
|
547
|
+
* Because the wrapper must `await beforeToolCall` first, preliminary
|
|
548
|
+
* chunks are collapsed — only the *final* yielded value reaches the
|
|
549
|
+
* model. If you need true preliminary streaming, override
|
|
550
|
+
* `getTools()` to provide such tools and avoid using `beforeToolCall`
|
|
551
|
+
* for them (or accept the collapse).
|
|
552
|
+
*/
|
|
553
|
+
_wrapToolsWithDecision(tools) {
|
|
554
|
+
const wrapped = {};
|
|
555
|
+
for (const [toolName, originalTool] of Object.entries(tools)) {
|
|
556
|
+
const t = originalTool;
|
|
557
|
+
const originalExecute = t.execute;
|
|
558
|
+
if (typeof originalExecute !== "function") {
|
|
559
|
+
wrapped[toolName] = originalTool;
|
|
560
|
+
continue;
|
|
561
|
+
}
|
|
562
|
+
const isDynamic = t.type === "dynamic";
|
|
563
|
+
const wrappedExecute = async (input, options) => {
|
|
564
|
+
const toolCallBase = {
|
|
565
|
+
type: "tool-call",
|
|
566
|
+
toolCallId: options.toolCallId,
|
|
567
|
+
toolName,
|
|
568
|
+
input,
|
|
569
|
+
...isDynamic ? { dynamic: true } : {}
|
|
570
|
+
};
|
|
571
|
+
const ctx = {
|
|
572
|
+
...toolCallBase,
|
|
573
|
+
stepNumber: void 0,
|
|
574
|
+
messages: options.messages,
|
|
575
|
+
abortSignal: options.abortSignal
|
|
576
|
+
};
|
|
577
|
+
const decision = await this.beforeToolCall(ctx);
|
|
578
|
+
const dispatchInput = decision && decision.action === "allow" && decision.input ? decision.input : input;
|
|
579
|
+
await this._pipelineExtensionToolCallStart({
|
|
580
|
+
toolCall: {
|
|
581
|
+
...toolCallBase,
|
|
582
|
+
input: dispatchInput
|
|
583
|
+
},
|
|
584
|
+
stepNumber: void 0
|
|
585
|
+
});
|
|
586
|
+
if (!decision || decision.action === "allow") {
|
|
587
|
+
const result = await originalExecute(decision?.input ?? input, options);
|
|
588
|
+
if (result != null && typeof result === "object" && Symbol.asyncIterator in result) {
|
|
589
|
+
let last;
|
|
590
|
+
for await (const part of result) last = part;
|
|
591
|
+
return last;
|
|
592
|
+
}
|
|
593
|
+
return result;
|
|
594
|
+
}
|
|
595
|
+
if (decision.action === "block") return decision.reason ?? `Tool "${toolName}" was blocked by beforeToolCall.`;
|
|
596
|
+
return decision.output;
|
|
597
|
+
};
|
|
598
|
+
wrapped[toolName] = {
|
|
599
|
+
...originalTool,
|
|
600
|
+
execute: wrappedExecute
|
|
601
|
+
};
|
|
602
|
+
}
|
|
603
|
+
return wrapped;
|
|
604
|
+
}
|
|
605
|
+
async _pipelineExtensionToolCallStart(event) {
|
|
606
|
+
if (!this.extensionManager) return;
|
|
607
|
+
if (this.extensionManager.getHookSubscribers("beforeToolCall").length === 0) return;
|
|
608
|
+
const { createToolCallStartSnapshot } = await import("./hook-proxy-5248W-ea.js");
|
|
609
|
+
await this._dispatchExtensionObservation("beforeToolCall", createToolCallStartSnapshot(event));
|
|
610
|
+
}
|
|
611
|
+
async _pipelineExtensionToolCallFinish(event) {
|
|
612
|
+
if (!this.extensionManager) return;
|
|
613
|
+
if (this.extensionManager.getHookSubscribers("afterToolCall").length === 0) return;
|
|
614
|
+
const { createToolCallFinishSnapshot } = await import("./hook-proxy-5248W-ea.js");
|
|
615
|
+
await this._dispatchExtensionObservation("afterToolCall", createToolCallFinishSnapshot(event));
|
|
616
|
+
}
|
|
617
|
+
async _pipelineExtensionStepFinish(event) {
|
|
618
|
+
if (!this.extensionManager) return;
|
|
619
|
+
if (this.extensionManager.getHookSubscribers("onStepFinish").length === 0) return;
|
|
620
|
+
const { createStepFinishSnapshot } = await import("./hook-proxy-5248W-ea.js");
|
|
621
|
+
await this._dispatchExtensionObservation("onStepFinish", createStepFinishSnapshot(event));
|
|
622
|
+
}
|
|
623
|
+
async _pipelineExtensionChunk(event) {
|
|
624
|
+
if (!this.extensionManager) return;
|
|
625
|
+
if (this.extensionManager.getHookSubscribers("onChunk").length === 0) return;
|
|
626
|
+
const { createChunkSnapshot } = await import("./hook-proxy-5248W-ea.js");
|
|
627
|
+
await this._dispatchExtensionObservation("onChunk", createChunkSnapshot(event));
|
|
628
|
+
}
|
|
439
629
|
async _hostReadFile(path) {
|
|
440
630
|
return await this.workspace.readFile(path) ?? null;
|
|
441
631
|
}
|
|
@@ -839,7 +1029,8 @@ var Think = class Think extends Agent {
|
|
|
839
1029
|
this._lastClientTools = void 0;
|
|
840
1030
|
this._persistClientTools();
|
|
841
1031
|
}
|
|
842
|
-
|
|
1032
|
+
const requestBody = Object.keys(customBody).length > 0 ? customBody : void 0;
|
|
1033
|
+
this._lastBody = requestBody;
|
|
843
1034
|
this._persistBody();
|
|
844
1035
|
const clientToolsForTurn = this._lastClientTools;
|
|
845
1036
|
const bodyForTurn = this._lastBody;
|