@cloudflare/think 0.1.1 → 0.2.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
@@ -1,48 +1,30 @@
1
- import { l as Session, t as SessionManager } from "./index-C4OTSwUW.js";
2
1
  import { LanguageModel, ModelMessage, ToolSet, UIMessage } from "ai";
3
- import { Agent } from "agents";
4
2
  import {
5
- FiberCompleteContext,
3
+ Agent,
6
4
  FiberContext,
7
- FiberMethods,
8
- FiberMethods as FiberMethods$1,
9
5
  FiberRecoveryContext,
10
- FiberState
11
- } from "agents/experimental/forever";
12
- import { Workspace } from "@cloudflare/shell";
6
+ FiberRecoveryContext as FiberRecoveryContext$1
7
+ } from "agents";
8
+ import { ClientToolSchema, MessagePart } from "agents/chat";
9
+ import {
10
+ Session,
11
+ Session as Session$1
12
+ } from "agents/experimental/memory/session";
13
13
 
14
14
  //#region src/think.d.ts
15
- type ThinkBaseConstructor = {
16
- new <
17
- Env extends Cloudflare.Env = Cloudflare.Env,
18
- State = unknown,
19
- Props extends Record<string, unknown> = Record<string, unknown>
20
- >(
21
- ctx: DurableObjectState,
22
- env: Env
23
- ): Agent<Env, State, Props> & FiberMethods$1;
24
- };
25
15
  /**
26
- * Callback interface for streaming chat events from a Think.
16
+ * Callback interface for streaming chat events from a Think sub-agent.
27
17
  *
28
18
  * Designed to work across the sub-agent RPC boundary — implement as
29
19
  * an RpcTarget in the parent agent and pass to `chat()`.
30
- *
31
- * Methods may return a Promise for async RPC callbacks.
32
20
  */
33
21
  interface StreamCallback {
34
- /** Called for each UIMessageChunk event during streaming. */
35
22
  onEvent(json: string): void | Promise<void>;
36
- /** Called when the stream completes successfully (not called on abort). */
37
23
  onDone(): void | Promise<void>;
38
- /** Called when an error occurs during streaming. */
39
24
  onError?(error: string): void | Promise<void>;
40
25
  }
41
26
  /**
42
27
  * Minimal interface for the result of `onChatMessage()`.
43
- * Must provide a `toUIMessageStream()` method that returns an
44
- * async-iterable stream of UI message chunks.
45
- *
46
28
  * The AI SDK's `streamText()` result satisfies this interface.
47
29
  */
48
30
  interface StreamableResult {
@@ -52,77 +34,158 @@ interface StreamableResult {
52
34
  * Options for a chat turn (sub-agent RPC entry point).
53
35
  */
54
36
  interface ChatOptions {
55
- /** AbortSignal — fires when the caller wants to cancel the turn. */
56
37
  signal?: AbortSignal;
57
- /** Extra tools to merge with getTools() for this turn only. */
58
38
  tools?: ToolSet;
59
39
  }
60
40
  /**
61
41
  * Options passed to the onChatMessage handler.
62
42
  */
63
43
  interface ChatMessageOptions {
64
- /** AbortSignal for cancelling the request */
65
44
  signal?: AbortSignal;
66
- /** Extra tools to merge with getTools() for this turn only. */
67
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>;
68
53
  }
69
- declare const Think_base: ThinkBaseConstructor;
70
54
  /**
71
- * A unified Agent base class for chat sessions.
55
+ * Result returned by `saveMessages()` and `continueLastTurn()`.
56
+ */
57
+ type SaveMessagesResult = {
58
+ requestId: string;
59
+ status: "completed" | "skipped";
60
+ };
61
+ /**
62
+ * Context passed to `onChatRecovery` when an interrupted chat stream
63
+ * is detected after DO restart.
64
+ */
65
+ type ChatRecoveryContext = {
66
+ streamId: string;
67
+ requestId: string;
68
+ partialText: string;
69
+ partialParts: MessagePart[];
70
+ recoveryData: unknown | null;
71
+ messages: UIMessage[];
72
+ lastBody?: Record<string, unknown>;
73
+ lastClientTools?: ClientToolSchema[];
74
+ };
75
+ /**
76
+ * Options returned from `onChatRecovery` to control recovery behavior.
77
+ */
78
+ type ChatRecoveryOptions = {
79
+ persist?: boolean;
80
+ continue?: boolean;
81
+ };
82
+ /**
83
+ * Controls how overlapping user submit requests behave while another
84
+ * chat turn is already active or queued.
85
+ *
86
+ * - `"queue"` (default) — queue every submit and process them in order.
87
+ * - `"latest"` — keep only the latest overlapping submit; superseded submits
88
+ * still persist their user messages, but do not start their own model turn.
89
+ * - `"merge"` — like latest, but all overlapping user messages remain in
90
+ * the conversation history. The model sees them all in one turn.
91
+ * - `"drop"` — ignore overlapping submits entirely (messages not persisted).
92
+ * - `{ strategy: "debounce" }` — trailing-edge latest with a quiet window.
72
93
  *
73
- * Works as both a top-level agent (WebSocket chat protocol) and a
74
- * sub-agent (RPC streaming via `chat()`).
94
+ * Only applies to `submit-message` requests. Regenerations, tool
95
+ * continuations, approvals, clears, `saveMessages`, and `continueLastTurn`
96
+ * keep their existing serialized behavior.
97
+ */
98
+ type MessageConcurrency =
99
+ | "queue"
100
+ | "latest"
101
+ | "merge"
102
+ | "drop"
103
+ | {
104
+ strategy: "debounce";
105
+ debounceMs?: number;
106
+ };
107
+ /**
108
+ * Result passed to `onChatResponse` after a chat turn completes.
109
+ */
110
+ type ChatResponseResult = {
111
+ message: UIMessage;
112
+ requestId: string;
113
+ continuation: boolean;
114
+ status: "completed" | "error" | "aborted";
115
+ error?: string;
116
+ };
117
+ /**
118
+ * An opinionated chat agent base class.
75
119
  *
76
120
  * @experimental Requires the `"experimental"` compatibility flag.
77
121
  */
78
122
  declare class Think<
79
123
  Env extends Cloudflare.Env = Cloudflare.Env,
80
124
  Config = Record<string, unknown>
81
- > extends Think_base<Env> {
125
+ > extends Agent<Env> {
82
126
  #private;
83
- /** Session manager — persistence layer with branching and compaction. */
84
- sessions: SessionManager;
85
- /** In-memory messages for the current conversation. Authoritative after load. */
86
- messages: UIMessage[];
87
127
  /**
88
- * Enable durable fiber recovery on start. Set to `true` to
89
- * automatically recover interrupted fibers when the DO restarts.
90
- *
91
- * Fiber methods (`spawnFiber()`, `stashFiber()`, etc.) are always
92
- * available — this flag only controls automatic recovery.
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`.
93
131
  *
94
- * @experimental
132
+ * Set to `true` for a default 10s timeout, or `{ timeout: ms }`
133
+ * for a custom timeout. Defaults to `false` (no waiting).
95
134
  */
96
- fibers: boolean;
135
+ waitForMcpConnections:
136
+ | boolean
137
+ | {
138
+ timeout: number;
139
+ };
97
140
  /**
98
- * Maximum number of messages to keep in storage per session.
99
- * When exceeded, oldest messages are deleted after each persist.
100
- * Set to `undefined` (default) for no limit.
141
+ * Controls how overlapping user submit requests behave while another
142
+ * chat turn is already active or queued.
101
143
  *
102
- * This controls storage only — it does not affect what's sent to the LLM.
103
- * Use `pruneMessages()` in `assembleContext()` to control LLM context.
144
+ * @default "queue"
104
145
  */
105
- maxPersistedMessages: number | undefined;
146
+ messageConcurrency: MessageConcurrency;
106
147
  /**
107
- * Cache of last-persisted JSON for each message ID.
108
- * Used for incremental persistence: skip SQL writes for unchanged messages.
109
- * @internal
148
+ * When true, chat turns are wrapped in `runFiber` for durable execution.
149
+ * Enables `onChatRecovery` hook and `this.stash()` during streaming.
110
150
  */
111
- private _persistedMessageCache;
112
- private _sessionId;
113
- private _abortControllers;
114
- private _clearGeneration;
115
- private _ensureConfigTable;
151
+ unstable_chatRecovery: boolean;
152
+ static readonly CHAT_FIBER_NAME = "__cf_internal_chat_turn";
153
+ /** The conversation session — messages, context, compaction, search. */
154
+ session: Session$1;
155
+ constructor(ctx: DurableObjectState, env: Env);
156
+ /**
157
+ * Conversation history. Computed from the active session.
158
+ * Always fresh — reads from Session's tree-structured storage.
159
+ */
160
+ get messages(): UIMessage[];
161
+ private _aborts;
162
+ private _turnQueue;
163
+ private _resumableStream;
164
+ private _pendingResumeConnections;
165
+ private _lastClientTools;
166
+ private _lastBody;
167
+ private _continuation;
168
+ private _continuationTimer;
169
+ private _insideResponseHook;
170
+ private _pendingInteractionPromise;
171
+ private _submitSequence;
172
+ private _latestOverlappingSubmitSequence;
173
+ private _activeDebounceTimer;
174
+ private _activeDebounceResolve;
175
+ private static MESSAGE_DEBOUNCE_MS;
116
176
  /**
117
177
  * Persist a typed configuration object.
118
- * Stored in SQLite so it survives restarts and hibernation.
178
+ * Stored in Session's assistant_config table — survives restarts and hibernation.
119
179
  */
120
180
  configure(config: Config): void;
121
181
  /**
122
182
  * Read the persisted configuration, or null if never configured.
123
183
  */
124
184
  getConfig(): Config | null;
125
- onStart(): void;
185
+ private _configSet;
186
+ private _configGet;
187
+ private _configDelete;
188
+ private _sessionId;
126
189
  /**
127
190
  * Return the language model to use for inference.
128
191
  * Must be overridden by subclasses that rely on the default
@@ -131,65 +194,86 @@ declare class Think<
131
194
  getModel(): LanguageModel;
132
195
  /**
133
196
  * Return the system prompt for the assistant.
134
- * Override to customize instructions.
197
+ * Used as fallback when no context blocks are configured via `configureSession`.
135
198
  */
136
199
  getSystemPrompt(): string;
137
- /**
138
- * Return the tools available to the assistant.
139
- * Override to provide workspace tools, custom tools, etc.
140
- */
200
+ /** Return the tools available to the assistant. */
141
201
  getTools(): ToolSet;
142
- /**
143
- * Return the maximum number of tool-call steps per turn.
144
- */
202
+ /** Return the maximum number of tool-call steps per turn. */
145
203
  getMaxSteps(): number;
146
204
  /**
147
- * Return the workspace instance for this session, or null if none.
205
+ * Configure the session. Called once during `onStart`.
206
+ * Override to add context blocks, compaction, search, skills.
207
+ *
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.
148
213
  *
149
- * Override in subclasses that create a Workspace. Used by
150
- * HostBridgeLoopback to provide workspace access to extension Workers.
214
+ * @example
215
+ * ```typescript
216
+ * configureSession(session: Session) {
217
+ * return session
218
+ * .withContext("memory", { description: "Learned facts", maxTokens: 2000 })
219
+ * .withCachedPrompt();
220
+ * }
221
+ * ```
222
+ *
223
+ * @example Async configuration from KV
224
+ * ```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();
230
+ * }
231
+ * ```
151
232
  */
152
- getWorkspace(): Workspace | null;
153
- _hostReadFile(path: string): Promise<string | null>;
154
- _hostWriteFile(path: string, content: string): Promise<void>;
155
- _hostDeleteFile(path: string): Promise<boolean>;
156
- _hostListFiles(dir: string): Promise<
157
- Array<{
158
- name: string;
159
- type: string;
160
- size: number;
161
- path: string;
162
- }>
163
- >;
233
+ configureSession(session: Session$1): Session$1 | Promise<Session$1>;
164
234
  /**
165
- * Assemble the model messages from the current conversation history.
166
- * Override to customize context assembly (e.g. inject memory,
167
- * project context, or apply compaction).
235
+ * Assemble context for the LLM from the current session state.
236
+ *
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
242
+ *
243
+ * Returns { system, messages } so the caller has both.
168
244
  */
169
- assembleContext(): Promise<ModelMessage[]>;
245
+ assembleContext(): Promise<{
246
+ system: string;
247
+ messages: ModelMessage[];
248
+ }>;
170
249
  /**
171
250
  * Handle a chat turn and return the streaming result.
172
251
  *
173
252
  * The default implementation runs the agentic loop:
174
- * 1. Assemble context from `this.messages`
175
- * 2. Call `streamText` with the model, system prompt, tools, and step limit
176
- *
177
- * Override for full control over inference (e.g. different models per turn,
178
- * RAG pipelines, routing to specialized sub-agents, etc.).
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
179
256
  *
180
- * When this is called, `this.messages` already contains the user's
181
- * latest message persisted to the current session.
257
+ * Override for full control over inference.
182
258
  *
183
259
  * @returns A result with `toUIMessageStream()` — AI SDK's `streamText()`
184
260
  * return value satisfies this interface.
185
261
  */
186
262
  onChatMessage(options?: ChatMessageOptions): Promise<StreamableResult>;
263
+ /**
264
+ * Called after a chat turn completes and the assistant message has been
265
+ * persisted. The turn lock is released before this hook runs, so it is
266
+ * safe to call other methods from inside.
267
+ *
268
+ * Fires for all turn completion paths: WebSocket chat requests,
269
+ * sub-agent RPC, and auto-continuation.
270
+ *
271
+ * Override for logging, chaining, analytics, usage tracking.
272
+ */
273
+ onChatResponse(_result: ChatResponseResult): void | Promise<void>;
187
274
  /**
188
275
  * Handle an error that occurred during a chat turn.
189
276
  * Override to customize error handling (e.g. logging, metrics).
190
- *
191
- * @param error The error that occurred
192
- * @returns The error (or a wrapped version) to propagate
193
277
  */
194
278
  onChatError(error: unknown): unknown;
195
279
  /**
@@ -197,10 +281,7 @@ declare class Think<
197
281
  * stream UIMessageChunk events via callback, and persist the
198
282
  * assistant's response.
199
283
  *
200
- * On error or abort, the partial assistant message is still persisted
201
- * so the user doesn't lose context.
202
- *
203
- * @param userMessage The user's message (string or UIMessage for multi-modal)
284
+ * @param userMessage The user's message (string or UIMessage)
204
285
  * @param callback Streaming callback (typically an RpcTarget from the parent)
205
286
  * @param options Optional chat options (e.g. AbortSignal)
206
287
  */
@@ -209,107 +290,135 @@ declare class Think<
209
290
  callback: StreamCallback,
210
291
  options?: ChatOptions
211
292
  ): Promise<void>;
212
- getSessions(): Session[];
213
- createSession(name: string): Session;
214
- switchSession(sessionId: string): UIMessage[];
215
- deleteSession(sessionId: string): void;
216
- renameSession(sessionId: string, name: string): void;
217
- getCurrentSessionId(): string | null;
218
- /**
219
- * Get the current session info, or null if no session exists yet.
220
- */
221
- getSession(): Session | null;
222
- /**
223
- * Get the conversation history as UIMessage[].
224
- */
225
- getHistory(): UIMessage[];
226
- /**
227
- * Get the total message count for this session.
228
- */
229
- getMessageCount(): number;
230
- /**
231
- * Clear all messages from this session (preserves the session itself).
232
- */
293
+ /** Get the conversation history as UIMessage[]. */
294
+ getMessages(): UIMessage[];
295
+ /** Clear all messages from storage. */
233
296
  clearMessages(): void;
234
297
  /**
235
- * Wrap onMessage and onRequest to intercept the chat protocol.
236
- * Unrecognized messages are forwarded to the user's handlers.
237
- * @internal
298
+ * Inject messages and trigger a model turn — without a WebSocket request.
299
+ *
300
+ * Use for scheduled responses, webhook-triggered turns, proactive agents,
301
+ * or chaining from `onChatResponse`.
302
+ *
303
+ * Accepts static messages or a callback that derives messages from the
304
+ * current state (useful when multiple calls queue up — the callback runs
305
+ * with the latest messages when the turn actually starts).
306
+ *
307
+ * @example Scheduled follow-up
308
+ * ```typescript
309
+ * async onScheduled() {
310
+ * await this.saveMessages([{
311
+ * id: crypto.randomUUID(),
312
+ * role: "user",
313
+ * parts: [{ type: "text", text: "Time for your daily summary." }]
314
+ * }]);
315
+ * }
316
+ * ```
317
+ *
318
+ * @example Function form
319
+ * ```typescript
320
+ * await this.saveMessages((current) => [
321
+ * ...current,
322
+ * { id: crypto.randomUUID(), role: "user", parts: [{ type: "text", text: "Continue." }] }
323
+ * ]);
324
+ * ```
238
325
  */
239
- private _setupProtocolHandlers;
326
+ saveMessages(
327
+ messages:
328
+ | UIMessage[]
329
+ | ((currentMessages: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>)
330
+ ): Promise<SaveMessagesResult>;
240
331
  /**
241
- * Route an incoming WebSocket message to the appropriate handler.
242
- * Returns true if the message was handled by the protocol.
243
- * @internal
332
+ * Run a new LLM call following the last assistant message.
333
+ *
334
+ * The model sees the full conversation (including the last assistant
335
+ * response) and generates a new response. The new response is persisted
336
+ * as a separate assistant message. Building block for chat recovery
337
+ * (Phase 4), "generate more" buttons, and self-correction.
338
+ *
339
+ * Note: this creates a new message, not an append to the existing one.
340
+ * True continuation-as-append (chunk rewriting) is planned for Phase 4.
341
+ *
342
+ * Returns early with `status: "skipped"` if there is no assistant message
343
+ * to continue from.
244
344
  */
245
- private _handleProtocol;
345
+ protected continueLastTurn(
346
+ body?: Record<string, unknown>
347
+ ): Promise<SaveMessagesResult>;
246
348
  /**
247
- * Handle CF_AGENT_USE_CHAT_REQUEST:
248
- * 1. Parse incoming messages
249
- * 2. Ensure a session exists
250
- * 3. Persist user messages to session
251
- * 4. Call onChatMessage
252
- * 5. Stream response back to clients
253
- * 6. Persist assistant message to session
254
- * @internal
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.
255
355
  */
356
+ protected sanitizeMessageForPersistence(message: UIMessage): UIMessage;
357
+ private _setupProtocolHandlers;
358
+ private _handleProtocolEvent;
359
+ private _handleStreamResumeRequest;
360
+ private _handleStreamResumeAck;
256
361
  private _handleChatRequest;
257
362
  /**
258
- * Handle CF_AGENT_CHAT_CLEAR: abort streams, clear current session messages.
259
- * @internal
363
+ * Abort the active turn, invalidate queued turns, and reset
364
+ * concurrency/continuation state. Call this when intercepting
365
+ * clear events or implementing custom reset logic.
366
+ *
367
+ * Does NOT clear messages, streams, or persisted state —
368
+ * only turn execution state.
260
369
  */
370
+ protected resetTurnState(): void;
261
371
  private _handleClear;
262
- /**
263
- * Handle CF_AGENT_CHAT_REQUEST_CANCEL: abort a specific request.
264
- * @internal
265
- */
266
- private _handleCancel;
267
- /**
268
- * Iterate a StreamableResult, broadcast chunks to clients,
269
- * build a UIMessage, and persist it to the session.
270
- * @internal
271
- */
272
372
  private _streamResult;
273
- /**
274
- * Persist an assistant message with sanitization, size enforcement,
275
- * and incremental persistence.
276
- * @internal
277
- */
278
373
  private _persistAssistantMessage;
279
- /**
280
- * Rebuild the persistence cache from current messages.
281
- * Called on startup to enable incremental persistence.
282
- * @internal
283
- */
284
- private _rebuildPersistenceCache;
285
- /**
286
- * Delete oldest messages on the current branch when count exceeds
287
- * maxPersistedMessages. Uses path-based count (not total across all
288
- * branches) and individual deletes to preserve branch structure.
289
- * @internal
290
- */
291
- private _enforceMaxPersistedMessages;
292
- /**
293
- * Broadcast a JSON message to all connected clients.
294
- * @internal
295
- */
374
+ private _persistClientTools;
375
+ private _restoreClientTools;
376
+ private _persistBody;
377
+ private _restoreBody;
378
+ private _applyToolResult;
379
+ private _applyToolApproval;
380
+ private _applyToolUpdateToMessages;
381
+ protected hasPendingInteraction(): boolean;
382
+ protected waitUntilStable(options?: { timeout?: number }): Promise<boolean>;
383
+ private _awaitWithDeadline;
384
+ private _messageHasPendingInteraction;
385
+ protected _handleInternalFiberRecovery(
386
+ ctx: FiberRecoveryContext$1
387
+ ): Promise<boolean>;
388
+ protected onChatRecovery(
389
+ _ctx: ChatRecoveryContext
390
+ ): Promise<ChatRecoveryOptions>;
391
+ _chatRecoveryContinue(data?: { targetAssistantId?: string }): Promise<void>;
392
+ private _getPartialStreamText;
393
+ private _normalizeMessageConcurrency;
394
+ private _getSubmitConcurrencyDecision;
395
+ private _isSupersededSubmit;
396
+ private _waitForTimestamp;
397
+ private _cancelActiveDebounce;
398
+ private _completeSkippedRequest;
399
+ private _rollbackDroppedSubmit;
400
+ private _scheduleAutoContinuation;
401
+ private _fireAutoContinuation;
402
+ private _activateDeferredContinuation;
403
+ private _fireResponseHook;
404
+ private _notifyStreamResuming;
405
+ private _persistOrphanedStream;
406
+ private _broadcastChat;
296
407
  private _broadcast;
297
- /**
298
- * Broadcast the current message list to all connected clients.
299
- * @internal
300
- */
301
408
  private _broadcastMessages;
302
409
  }
303
410
  //#endregion
304
411
  export {
305
412
  ChatMessageOptions,
306
413
  ChatOptions,
307
- type FiberCompleteContext,
414
+ ChatRecoveryContext,
415
+ ChatRecoveryOptions,
416
+ ChatResponseResult,
308
417
  type FiberContext,
309
- type FiberMethods,
310
418
  type FiberRecoveryContext,
311
- type FiberState,
312
- type Session,
419
+ MessageConcurrency,
420
+ SaveMessagesResult,
421
+ Session,
313
422
  StreamCallback,
314
423
  StreamableResult,
315
424
  Think