@cloudflare/think 0.1.0 → 0.1.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,3 @@
1
- import { l as Session, t as SessionManager } from "./index-C4OTSwUW.js";
2
1
  import { LanguageModel, ModelMessage, ToolSet, UIMessage } from "ai";
3
2
  import { Agent } from "agents";
4
3
  import {
@@ -9,7 +8,7 @@ import {
9
8
  FiberRecoveryContext,
10
9
  FiberState
11
10
  } from "agents/experimental/forever";
12
- import { Workspace } from "@cloudflare/shell";
11
+ import { ClientToolSchema } from "agents/chat";
13
12
 
14
13
  //#region src/think.d.ts
15
14
  type ThinkBaseConstructor = {
@@ -23,26 +22,18 @@ type ThinkBaseConstructor = {
23
22
  ): Agent<Env, State, Props> & FiberMethods$1;
24
23
  };
25
24
  /**
26
- * Callback interface for streaming chat events from a Think.
25
+ * Callback interface for streaming chat events from a Think sub-agent.
27
26
  *
28
27
  * Designed to work across the sub-agent RPC boundary — implement as
29
28
  * an RpcTarget in the parent agent and pass to `chat()`.
30
- *
31
- * Methods may return a Promise for async RPC callbacks.
32
29
  */
33
30
  interface StreamCallback {
34
- /** Called for each UIMessageChunk event during streaming. */
35
31
  onEvent(json: string): void | Promise<void>;
36
- /** Called when the stream completes successfully (not called on abort). */
37
32
  onDone(): void | Promise<void>;
38
- /** Called when an error occurs during streaming. */
39
33
  onError?(error: string): void | Promise<void>;
40
34
  }
41
35
  /**
42
36
  * 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
37
  * The AI SDK's `streamText()` result satisfies this interface.
47
38
  */
48
39
  interface StreamableResult {
@@ -52,26 +43,21 @@ interface StreamableResult {
52
43
  * Options for a chat turn (sub-agent RPC entry point).
53
44
  */
54
45
  interface ChatOptions {
55
- /** AbortSignal — fires when the caller wants to cancel the turn. */
56
46
  signal?: AbortSignal;
57
- /** Extra tools to merge with getTools() for this turn only. */
58
47
  tools?: ToolSet;
59
48
  }
60
49
  /**
61
50
  * Options passed to the onChatMessage handler.
62
51
  */
63
52
  interface ChatMessageOptions {
64
- /** AbortSignal for cancelling the request */
65
53
  signal?: AbortSignal;
66
- /** Extra tools to merge with getTools() for this turn only. */
67
54
  tools?: ToolSet;
55
+ /** Client-provided tool schemas for dynamic tool registration. */
56
+ clientTools?: ClientToolSchema[];
68
57
  }
69
58
  declare const Think_base: ThinkBaseConstructor;
70
59
  /**
71
- * A unified Agent base class for chat sessions.
72
- *
73
- * Works as both a top-level agent (WebSocket chat protocol) and a
74
- * sub-agent (RPC streaming via `chat()`).
60
+ * An opinionated chat agent base class.
75
61
  *
76
62
  * @experimental Requires the `"experimental"` compatibility flag.
77
63
  */
@@ -80,22 +66,30 @@ declare class Think<
80
66
  Config = Record<string, unknown>
81
67
  > extends Think_base<Env> {
82
68
  #private;
83
- /** Session manager — persistence layer with branching and compaction. */
84
- sessions: SessionManager;
85
69
  /** In-memory messages for the current conversation. Authoritative after load. */
86
70
  messages: UIMessage[];
87
71
  /**
88
72
  * Enable durable fiber recovery on start. Set to `true` to
89
73
  * automatically recover interrupted fibers when the DO restarts.
90
74
  *
91
- * Fiber methods (`spawnFiber()`, `stashFiber()`, etc.) are always
92
- * available — this flag only controls automatic recovery.
93
- *
94
75
  * @experimental
95
76
  */
96
77
  fibers: boolean;
97
78
  /**
98
- * Maximum number of messages to keep in storage per session.
79
+ * Wait for MCP server connections to be ready before calling
80
+ * `onChatMessage`. When enabled, `this.mcp.getAITools()` returns
81
+ * the full set of MCP-discovered tools inside `onChatMessage`.
82
+ *
83
+ * Set to `true` for a default 10s timeout, or `{ timeout: ms }`
84
+ * for a custom timeout. Defaults to `false` (no waiting).
85
+ */
86
+ waitForMcpConnections:
87
+ | boolean
88
+ | {
89
+ timeout: number;
90
+ };
91
+ /**
92
+ * Maximum number of messages to keep in storage.
99
93
  * When exceeded, oldest messages are deleted after each persist.
100
94
  * Set to `undefined` (default) for no limit.
101
95
  *
@@ -103,15 +97,15 @@ declare class Think<
103
97
  * Use `pruneMessages()` in `assembleContext()` to control LLM context.
104
98
  */
105
99
  maxPersistedMessages: number | undefined;
106
- /**
107
- * Cache of last-persisted JSON for each message ID.
108
- * Used for incremental persistence: skip SQL writes for unchanged messages.
109
- * @internal
110
- */
111
100
  private _persistedMessageCache;
112
- private _sessionId;
101
+ private _storageReady;
113
102
  private _abortControllers;
114
- private _clearGeneration;
103
+ private _turnQueue;
104
+ private _resumableStream;
105
+ private _pendingResumeConnections;
106
+ private _lastClientTools;
107
+ private _continuation;
108
+ private _continuationTimer;
115
109
  private _ensureConfigTable;
116
110
  /**
117
111
  * Persist a typed configuration object.
@@ -129,38 +123,12 @@ declare class Think<
129
123
  * `onChatMessage` implementation (the agentic loop).
130
124
  */
131
125
  getModel(): LanguageModel;
132
- /**
133
- * Return the system prompt for the assistant.
134
- * Override to customize instructions.
135
- */
126
+ /** Return the system prompt for the assistant. */
136
127
  getSystemPrompt(): string;
137
- /**
138
- * Return the tools available to the assistant.
139
- * Override to provide workspace tools, custom tools, etc.
140
- */
128
+ /** Return the tools available to the assistant. */
141
129
  getTools(): ToolSet;
142
- /**
143
- * Return the maximum number of tool-call steps per turn.
144
- */
130
+ /** Return the maximum number of tool-call steps per turn. */
145
131
  getMaxSteps(): number;
146
- /**
147
- * Return the workspace instance for this session, or null if none.
148
- *
149
- * Override in subclasses that create a Workspace. Used by
150
- * HostBridgeLoopback to provide workspace access to extension Workers.
151
- */
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
- >;
164
132
  /**
165
133
  * Assemble the model messages from the current conversation history.
166
134
  * Override to customize context assembly (e.g. inject memory,
@@ -174,11 +142,7 @@ declare class Think<
174
142
  * 1. Assemble context from `this.messages`
175
143
  * 2. Call `streamText` with the model, system prompt, tools, and step limit
176
144
  *
177
- * Override for full control over inference (e.g. different models per turn,
178
- * RAG pipelines, routing to specialized sub-agents, etc.).
179
- *
180
- * When this is called, `this.messages` already contains the user's
181
- * latest message persisted to the current session.
145
+ * Override for full control over inference.
182
146
  *
183
147
  * @returns A result with `toUIMessageStream()` — AI SDK's `streamText()`
184
148
  * return value satisfies this interface.
@@ -187,9 +151,6 @@ declare class Think<
187
151
  /**
188
152
  * Handle an error that occurred during a chat turn.
189
153
  * 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
154
  */
194
155
  onChatError(error: unknown): unknown;
195
156
  /**
@@ -197,10 +158,7 @@ declare class Think<
197
158
  * stream UIMessageChunk events via callback, and persist the
198
159
  * assistant's response.
199
160
  *
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)
161
+ * @param userMessage The user's message (string or UIMessage)
204
162
  * @param callback Streaming callback (typically an RpcTarget from the parent)
205
163
  * @param options Optional chat options (e.g. AbortSignal)
206
164
  */
@@ -209,95 +167,36 @@ declare class Think<
209
167
  callback: StreamCallback,
210
168
  options?: ChatOptions
211
169
  ): 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
- */
170
+ /** Get the conversation history as UIMessage[]. */
171
+ getMessages(): UIMessage[];
172
+ /** Clear all messages from storage and memory. */
233
173
  clearMessages(): void;
234
- /**
235
- * Wrap onMessage and onRequest to intercept the chat protocol.
236
- * Unrecognized messages are forwarded to the user's handlers.
237
- * @internal
238
- */
239
174
  private _setupProtocolHandlers;
240
- /**
241
- * Route an incoming WebSocket message to the appropriate handler.
242
- * Returns true if the message was handled by the protocol.
243
- * @internal
244
- */
245
175
  private _handleProtocol;
246
- /**
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
255
- */
256
176
  private _handleChatRequest;
257
- /**
258
- * Handle CF_AGENT_CHAT_CLEAR: abort streams, clear current session messages.
259
- * @internal
260
- */
261
177
  private _handleClear;
262
- /**
263
- * Handle CF_AGENT_CHAT_REQUEST_CANCEL: abort a specific request.
264
- * @internal
265
- */
266
178
  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
179
  private _streamResult;
273
- /**
274
- * Persist an assistant message with sanitization, size enforcement,
275
- * and incremental persistence.
276
- * @internal
277
- */
180
+ private _initStorage;
181
+ private _loadMessages;
182
+ private _appendMessage;
183
+ private _upsertMessage;
184
+ private _clearMessages;
185
+ private _deleteMessages;
186
+ private _persistClientTools;
187
+ private _restoreClientTools;
278
188
  private _persistAssistantMessage;
279
- /**
280
- * Rebuild the persistence cache from current messages.
281
- * Called on startup to enable incremental persistence.
282
- * @internal
283
- */
284
189
  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
190
  private _enforceMaxPersistedMessages;
292
- /**
293
- * Broadcast a JSON message to all connected clients.
294
- * @internal
295
- */
191
+ private _applyToolResult;
192
+ private _applyToolApproval;
193
+ private _scheduleAutoContinuation;
194
+ private _fireAutoContinuation;
195
+ private _activateDeferredContinuation;
196
+ private _notifyStreamResuming;
197
+ private _persistOrphanedStream;
198
+ private _broadcastChat;
296
199
  private _broadcast;
297
- /**
298
- * Broadcast the current message list to all connected clients.
299
- * @internal
300
- */
301
200
  private _broadcastMessages;
302
201
  }
303
202
  //#endregion
@@ -309,7 +208,6 @@ export {
309
208
  type FiberMethods,
310
209
  type FiberRecoveryContext,
311
210
  type FiberState,
312
- type Session,
313
211
  StreamCallback,
314
212
  StreamableResult,
315
213
  Think