@cloudflare/think 0.2.0 → 0.2.2

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
@@ -1,4 +1,14 @@
1
- import { LanguageModel, ModelMessage, ToolSet, UIMessage } from "ai";
1
+ import {
2
+ i as ExtensionManifest,
3
+ t as ExtensionManager
4
+ } from "./manager-DCbSiSWT.js";
5
+ import {
6
+ LanguageModel,
7
+ ModelMessage,
8
+ ToolSet,
9
+ UIMessage,
10
+ streamText
11
+ } from "ai";
2
12
  import {
3
13
  Agent,
4
14
  FiberContext,
@@ -10,6 +20,7 @@ import {
10
20
  Session,
11
21
  Session as Session$1
12
22
  } from "agents/experimental/memory/session";
23
+ import { Workspace, Workspace as Workspace$1 } from "@cloudflare/shell";
13
24
 
14
25
  //#region src/think.d.ts
15
26
  /**
@@ -24,7 +35,7 @@ interface StreamCallback {
24
35
  onError?(error: string): void | Promise<void>;
25
36
  }
26
37
  /**
27
- * Minimal interface for the result of `onChatMessage()`.
38
+ * Minimal interface for the result of the inference loop.
28
39
  * The AI SDK's `streamText()` result satisfies this interface.
29
40
  */
30
41
  interface StreamableResult {
@@ -37,20 +48,6 @@ interface ChatOptions {
37
48
  signal?: AbortSignal;
38
49
  tools?: ToolSet;
39
50
  }
40
- /**
41
- * Options passed to the onChatMessage handler.
42
- */
43
- interface ChatMessageOptions {
44
- signal?: AbortSignal;
45
- tools?: ToolSet;
46
- /** Client-provided tool schemas for dynamic tool registration. */
47
- clientTools?: ClientToolSchema[];
48
- /** Whether this is a continuation turn (auto-continue after tool result, recovery).
49
- * Explicitly set to `false` for initial turns and `true` for continuations. */
50
- continuation?: boolean;
51
- /** Custom body fields from the client request. Persisted across hibernation. */
52
- body?: Record<string, unknown>;
53
- }
54
51
  /**
55
52
  * Result returned by `saveMessages()` and `continueLastTurn()`.
56
53
  */
@@ -79,6 +76,140 @@ type ChatRecoveryOptions = {
79
76
  persist?: boolean;
80
77
  continue?: boolean;
81
78
  };
79
+ /**
80
+ * A chat turn request. Built automatically by each entry path
81
+ * (WebSocket, chat(), saveMessages, auto-continuation) and passed
82
+ * to Think's inference loop.
83
+ */
84
+ interface TurnInput {
85
+ signal?: AbortSignal;
86
+ /** Extra tools from the caller (e.g. chat() options) — highest merge priority. */
87
+ callerTools?: ToolSet;
88
+ /** Client-provided tool schemas for dynamic tool registration. */
89
+ clientTools?: ClientToolSchema[];
90
+ /** Custom body fields from the client request. */
91
+ body?: Record<string, unknown>;
92
+ /** Whether this is a continuation turn (auto-continue after tool result, recovery). */
93
+ continuation: boolean;
94
+ }
95
+ /**
96
+ * Context passed to the `beforeTurn` hook.
97
+ * Contains everything Think assembled — the hook can inspect and override.
98
+ */
99
+ interface TurnContext {
100
+ /** Assembled system prompt (from context blocks or getSystemPrompt fallback). */
101
+ system: string;
102
+ /** Assembled model messages (truncated, pruned). */
103
+ messages: ModelMessage[];
104
+ /** Merged tool set (workspace + getTools + session + MCP + client + caller). */
105
+ tools: ToolSet;
106
+ /** The language model from getModel(). */
107
+ model: LanguageModel;
108
+ /** Whether this is a continuation turn. */
109
+ continuation: boolean;
110
+ /** Custom body fields from the client request. */
111
+ body?: Record<string, unknown>;
112
+ }
113
+ /**
114
+ * Configuration returned by the `beforeTurn` hook to override defaults.
115
+ * All fields are optional — return only what you want to change.
116
+ */
117
+ interface TurnConfig {
118
+ /** Override the model for this turn (e.g. cheap model for continuations). */
119
+ model?: LanguageModel;
120
+ /** Override the assembled system prompt. */
121
+ system?: string;
122
+ /** Override the assembled messages. */
123
+ messages?: ModelMessage[];
124
+ /** Extra tools to merge (additive — spread on top of existing tools). */
125
+ tools?: ToolSet;
126
+ /** Limit which tools the model can call (AI SDK activeTools). */
127
+ activeTools?: string[];
128
+ /** Force a specific tool call (AI SDK toolChoice). */
129
+ toolChoice?: Parameters<typeof streamText>[0]["toolChoice"];
130
+ /** Override maxSteps for this turn. */
131
+ maxSteps?: number;
132
+ /** Provider-specific options (AI SDK providerOptions). */
133
+ providerOptions?: Record<string, unknown>;
134
+ }
135
+ /**
136
+ * Context passed to the `beforeToolCall` hook when the model
137
+ * produces a tool call, before the tool's execute function runs.
138
+ */
139
+ interface ToolCallContext {
140
+ /** Name of the tool being called. */
141
+ toolName: string;
142
+ /** Arguments the model provided. */
143
+ args: Record<string, unknown>;
144
+ }
145
+ /**
146
+ * Decision returned by `beforeToolCall` to control tool execution.
147
+ * Return void/undefined to allow execution with original args.
148
+ *
149
+ * Discriminated union — each action has a clear, non-overlapping meaning:
150
+ * - `allow` — execute the tool (optionally with modified args)
151
+ * - `block` — don't execute; return `reason` as the tool result so the model can adjust
152
+ * - `substitute` — don't execute; return `result` as the tool result (afterToolCall still fires)
153
+ */
154
+ type ToolCallDecision =
155
+ | {
156
+ action: "allow" /** Modified arguments — tool executes with these instead of the originals. */;
157
+ args?: Record<string, unknown>;
158
+ }
159
+ | {
160
+ action: "block" /** Returned as the tool result so the model can adjust. */;
161
+ reason?: string;
162
+ }
163
+ | {
164
+ action: "substitute" /** The substitute tool result — model sees this instead of real execution. */;
165
+ result: unknown /** Optional arg attribution for the afterToolCall log. */;
166
+ args?: Record<string, unknown>;
167
+ };
168
+ /**
169
+ * Context passed to the `afterToolCall` hook after a tool executes.
170
+ */
171
+ interface ToolCallResultContext {
172
+ /** Name of the tool that was called. */
173
+ toolName: string;
174
+ /** Arguments the tool was called with (may be modified by beforeToolCall). */
175
+ args: Record<string, unknown>;
176
+ /** The result returned by the tool (or substitute from beforeToolCall). */
177
+ result: unknown;
178
+ }
179
+ /**
180
+ * Context passed to the `onStepFinish` hook after each step completes.
181
+ * Wraps the AI SDK's onStepFinish callback data.
182
+ */
183
+ type StepContext = {
184
+ /** The type of step that completed. */ stepType:
185
+ | "initial"
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
+ };
197
+ /**
198
+ * Context passed to the `onChunk` hook for each streaming chunk.
199
+ * Wraps the AI SDK's onChunk callback data.
200
+ */
201
+ type ChunkContext = {
202
+ /** The chunk data from the AI SDK stream. */ chunk: unknown;
203
+ };
204
+ /**
205
+ * Configuration for a sandboxed extension, returned by getExtensions().
206
+ */
207
+ interface ExtensionConfig {
208
+ /** Extension manifest (name, version, permissions, contributions). */
209
+ manifest: ExtensionManifest;
210
+ /** JavaScript source code defining the extension's tools. */
211
+ source: string;
212
+ }
82
213
  /**
83
214
  * Controls how overlapping user submit requests behave while another
84
215
  * chat turn is already active or queued.
@@ -125,9 +256,8 @@ declare class Think<
125
256
  > extends Agent<Env> {
126
257
  #private;
127
258
  /**
128
- * Wait for MCP server connections to be ready before calling
129
- * `onChatMessage`. When enabled, `this.mcp.getAITools()` returns
130
- * the full set of MCP-discovered tools inside `onChatMessage`.
259
+ * Wait for MCP server connections to be ready before the inference
260
+ * loop. MCP tools are auto-merged into the tool set.
131
261
  *
132
262
  * Set to `true` for a default 10s timeout, or `{ timeout: ms }`
133
263
  * for a custom timeout. Defaults to `false` (no waiting).
@@ -152,6 +282,30 @@ declare class Think<
152
282
  static readonly CHAT_FIBER_NAME = "__cf_internal_chat_turn";
153
283
  /** The conversation session — messages, context, compaction, search. */
154
284
  session: Session$1;
285
+ /**
286
+ * WorkerLoader binding for sandboxed extensions.
287
+ * Set this to enable `getExtensions()` and dynamic extension loading.
288
+ */
289
+ extensionLoader?: WorkerLoader;
290
+ /**
291
+ * Extension manager — created automatically when `extensionLoader` is set.
292
+ * Use for dynamic `load()` / `unload()` at runtime.
293
+ */
294
+ extensionManager?: ExtensionManager;
295
+ /**
296
+ * Workspace filesystem backed by the DO's SQLite storage.
297
+ * Available in `getTools()` and lifecycle hooks.
298
+ *
299
+ * Override to add R2 spillover for large files:
300
+ * ```typescript
301
+ * override workspace = new Workspace({
302
+ * sql: this.ctx.storage.sql,
303
+ * r2: this.env.R2,
304
+ * name: () => this.name
305
+ * });
306
+ * ```
307
+ */
308
+ workspace: Workspace$1;
155
309
  constructor(ctx: DurableObjectState, env: Env);
156
310
  /**
157
311
  * Conversation history. Computed from the active session.
@@ -167,6 +321,7 @@ declare class Think<
167
321
  private _continuation;
168
322
  private _continuationTimer;
169
323
  private _insideResponseHook;
324
+ private _insideInferenceLoop;
170
325
  private _pendingInteractionPromise;
171
326
  private _submitSequence;
172
327
  private _latestOverlappingSubmitSequence;
@@ -188,8 +343,7 @@ declare class Think<
188
343
  private _sessionId;
189
344
  /**
190
345
  * Return the language model to use for inference.
191
- * Must be overridden by subclasses that rely on the default
192
- * `onChatMessage` implementation (the agentic loop).
346
+ * Must be overridden by subclasses.
193
347
  */
194
348
  getModel(): LanguageModel;
195
349
  /**
@@ -199,18 +353,12 @@ declare class Think<
199
353
  getSystemPrompt(): string;
200
354
  /** Return the tools available to the assistant. */
201
355
  getTools(): ToolSet;
202
- /** Return the maximum number of tool-call steps per turn. */
203
- getMaxSteps(): number;
356
+ /** Maximum number of tool-call steps per turn. Override via property or per-turn via TurnConfig. */
357
+ maxSteps: number;
204
358
  /**
205
359
  * Configure the session. Called once during `onStart`.
206
360
  * Override to add context blocks, compaction, search, skills.
207
361
  *
208
- * The base session is pre-created with `Session.create(this)`.
209
- * Return it with builder methods chained.
210
- *
211
- * Async is supported — use it to read configuration from KV, D1,
212
- * or R2 before setting up context blocks.
213
- *
214
362
  * @example
215
363
  * ```typescript
216
364
  * configureSession(session: Session) {
@@ -219,47 +367,79 @@ declare class Think<
219
367
  * .withCachedPrompt();
220
368
  * }
221
369
  * ```
370
+ */
371
+ configureSession(session: Session$1): Session$1 | Promise<Session$1>;
372
+ /**
373
+ * Return sandboxed extension configurations. Defines load order,
374
+ * which determines hook execution order.
375
+ * Requires `extensionLoader` to be set.
376
+ */
377
+ getExtensions(): ExtensionConfig[];
378
+ /**
379
+ * Called before `streamText` — inspect the assembled context and
380
+ * return overrides. Think assembles tools, system prompt, and messages
381
+ * internally; this hook sees the result and can override any part.
222
382
  *
223
- * @example Async configuration from KV
383
+ * Return `void` to accept all defaults.
384
+ *
385
+ * @example Switch model for continuations
224
386
  * ```typescript
225
- * async configureSession(session: Session) {
226
- * const config = await this.env.KV.get("agent-config", "json");
227
- * return session
228
- * .withContext("memory", { maxTokens: config.memoryTokens })
229
- * .withCachedPrompt();
387
+ * beforeTurn(ctx: TurnContext) {
388
+ * if (ctx.continuation) return { model: this.cheapModel };
389
+ * }
390
+ * ```
391
+ *
392
+ * @example Restrict active tools
393
+ * ```typescript
394
+ * beforeTurn(ctx: TurnContext) {
395
+ * return { activeTools: ["read", "write"] };
230
396
  * }
231
397
  * ```
232
398
  */
233
- configureSession(session: Session$1): Session$1 | Promise<Session$1>;
399
+ beforeTurn(_ctx: TurnContext): TurnConfig | void | Promise<TurnConfig | void>;
234
400
  /**
235
- * Assemble context for the LLM from the current session state.
401
+ * Called when the model produces a tool call. Currently fires
402
+ * **after** tool execution (via `onStepFinish` data) — observation only.
236
403
  *
237
- * Default implementation:
238
- * 1. Freezes the system prompt from context blocks (falls back to getSystemPrompt())
239
- * 2. Gets history from session
240
- * 3. Applies read-time truncation (old tool outputs, long text)
241
- * 4. Converts to model messages with tool call pruning
404
+ * **Known limitation:** `block` and `substitute` actions in the returned
405
+ * `ToolCallDecision` are not yet functional. The AI SDK's `streamText`
406
+ * does not expose a pre-execution interception point for tool calls
407
+ * in the Workers runtime. The types are in place for when this becomes
408
+ * possible (see plan: "Known limitations — Phase 1").
242
409
  *
243
- * Returns { system, messages } so the caller has both.
244
- */
245
- assembleContext(): Promise<{
246
- system: string;
247
- messages: ModelMessage[];
248
- }>;
249
- /**
250
- * Handle a chat turn and return the streaming result.
410
+ * Only fires for server-side tools (tools with `execute`).
411
+ * Client tools are handled on the client — Think can't intercept them.
251
412
  *
252
- * The default implementation runs the agentic loop:
253
- * 1. Merge tools: getTools() + clientTools + session context tools + options.tools
254
- * 2. Assemble context (system prompt + messages) from session state
255
- * 3. Call `streamText` with the model, system prompt, tools, and step limit
413
+ * Return `void` to accept default behavior.
256
414
  *
257
- * Override for full control over inference.
415
+ * @example Log tool calls
416
+ * ```typescript
417
+ * beforeToolCall(ctx: ToolCallContext) {
418
+ * console.log(`Tool called: ${ctx.toolName}`, ctx.args);
419
+ * }
420
+ * ```
421
+ */
422
+ beforeToolCall(
423
+ _ctx: ToolCallContext
424
+ ): ToolCallDecision | void | Promise<ToolCallDecision | void>;
425
+ /**
426
+ * Called after a tool executes (or a substitute result is provided).
427
+ * Does NOT fire when `beforeToolCall` blocks with no substitute result.
258
428
  *
259
- * @returns A result with `toUIMessageStream()` — AI SDK's `streamText()`
260
- * return value satisfies this interface.
429
+ * Override for logging, metrics, or result inspection.
261
430
  */
262
- onChatMessage(options?: ChatMessageOptions): Promise<StreamableResult>;
431
+ afterToolCall(_ctx: ToolCallResultContext): void | Promise<void>;
432
+ /**
433
+ * Called after each step completes (initial, continue, tool-result).
434
+ * Override for step-level logging or analytics.
435
+ */
436
+ onStepFinish(_ctx: StepContext): void | Promise<void>;
437
+ /**
438
+ * Called for each streaming chunk. High-frequency — fires per token.
439
+ * Override for streaming analytics, progress indicators, or token counting.
440
+ * Observational only (void return).
441
+ */
442
+ onChunk(_ctx: ChunkContext): void | Promise<void>;
263
443
  /**
264
444
  * Called after a chat turn completes and the assistant message has been
265
445
  * persisted. The turn lock is released before this hook runs, so it is
@@ -276,6 +456,51 @@ declare class Think<
276
456
  * Override to customize error handling (e.g. logging, metrics).
277
457
  */
278
458
  onChatError(error: unknown): unknown;
459
+ private _initializeExtensions;
460
+ /**
461
+ * The single convergence point for all chat turn entry paths.
462
+ * Merges tools, assembles context, fires lifecycle hooks, wraps tools
463
+ * for interception, and calls streamText.
464
+ */
465
+ private _runInferenceLoop;
466
+ /** @internal Test seam — override in test agents to wrap the stream (e.g. error injection). */
467
+ protected _transformInferenceResult(
468
+ result: StreamableResult
469
+ ): StreamableResult;
470
+ /** Default hook timeout in milliseconds. */
471
+ hookTimeout: number;
472
+ /**
473
+ * Pipeline beforeTurn through sandboxed extensions in load order.
474
+ * Each extension sees the accumulated state from prior extensions
475
+ * (snapshot is rebuilt after each extension's modifications).
476
+ * Results are merged with last-write-wins for scalar fields.
477
+ * Extensions that don't subscribe to beforeTurn are skipped.
478
+ */
479
+ private _pipelineExtensionBeforeTurn;
480
+ _hostReadFile(path: string): Promise<string | null>;
481
+ _hostWriteFile(path: string, content: string): Promise<void>;
482
+ _hostDeleteFile(path: string): Promise<boolean>;
483
+ _hostListFiles(dir: string): Promise<
484
+ Array<{
485
+ name: string;
486
+ type: string;
487
+ size: number;
488
+ path: string;
489
+ }>
490
+ >;
491
+ _hostGetContext(label: string): Promise<string | null>;
492
+ _hostSetContext(label: string, content: string): Promise<void>;
493
+ _hostGetMessages(limit?: number): Promise<
494
+ Array<{
495
+ id: string;
496
+ role: string;
497
+ content: string;
498
+ }>
499
+ >;
500
+ _hostSendMessage(content: string): Promise<void>;
501
+ _hostGetSessionInfo(): Promise<{
502
+ messageCount: number;
503
+ }>;
279
504
  /**
280
505
  * Run a chat turn: persist the user message, run the agentic loop,
281
506
  * stream UIMessageChunk events via callback, and persist the
@@ -345,15 +570,6 @@ declare class Think<
345
570
  protected continueLastTurn(
346
571
  body?: Record<string, unknown>
347
572
  ): Promise<SaveMessagesResult>;
348
- /**
349
- * Override to apply custom transformations to messages before they are
350
- * persisted to Session storage. Runs after the built-in sanitization
351
- * (OpenAI metadata stripping, row size enforcement) but before
352
- * `session.appendMessage` / `session.updateMessage`.
353
- *
354
- * Use for redacting PII, stripping internal metadata, or custom compaction.
355
- */
356
- protected sanitizeMessageForPersistence(message: UIMessage): UIMessage;
357
573
  private _setupProtocolHandlers;
358
574
  private _handleProtocolEvent;
359
575
  private _handleStreamResumeRequest;
@@ -409,18 +625,27 @@ declare class Think<
409
625
  }
410
626
  //#endregion
411
627
  export {
412
- ChatMessageOptions,
413
628
  ChatOptions,
414
629
  ChatRecoveryContext,
415
630
  ChatRecoveryOptions,
416
631
  ChatResponseResult,
632
+ ChunkContext,
633
+ ExtensionConfig,
417
634
  type FiberContext,
418
635
  type FiberRecoveryContext,
419
636
  MessageConcurrency,
420
637
  SaveMessagesResult,
421
638
  Session,
639
+ StepContext,
422
640
  StreamCallback,
423
641
  StreamableResult,
424
- Think
642
+ Think,
643
+ ToolCallContext,
644
+ ToolCallDecision,
645
+ ToolCallResultContext,
646
+ TurnConfig,
647
+ TurnContext,
648
+ TurnInput,
649
+ Workspace
425
650
  };
426
651
  //# sourceMappingURL=think.d.ts.map