@cloudflare/think 0.0.0 → 0.0.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.
@@ -0,0 +1,315 @@
1
+ import { l as Session, t as SessionManager } from "./index-C4OTSwUW.js";
2
+ import { LanguageModel, ModelMessage, ToolSet, UIMessage } from "ai";
3
+ import { Agent } from "agents";
4
+ import {
5
+ FiberCompleteContext,
6
+ FiberContext,
7
+ FiberMethods,
8
+ FiberMethods as FiberMethods$1,
9
+ FiberRecoveryContext,
10
+ FiberState
11
+ } from "agents/experimental/forever";
12
+ import { Workspace } from "agents/experimental/workspace";
13
+
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
+ /**
26
+ * Callback interface for streaming chat events from a Think.
27
+ *
28
+ * Designed to work across the sub-agent RPC boundary — implement as
29
+ * an RpcTarget in the parent agent and pass to `chat()`.
30
+ *
31
+ * Methods may return a Promise for async RPC callbacks.
32
+ */
33
+ interface StreamCallback {
34
+ /** Called for each UIMessageChunk event during streaming. */
35
+ onEvent(json: string): void | Promise<void>;
36
+ /** Called when the stream completes successfully (not called on abort). */
37
+ onDone(): void | Promise<void>;
38
+ /** Called when an error occurs during streaming. */
39
+ onError?(error: string): void | Promise<void>;
40
+ }
41
+ /**
42
+ * 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
+ * The AI SDK's `streamText()` result satisfies this interface.
47
+ */
48
+ interface StreamableResult {
49
+ toUIMessageStream(): AsyncIterable<unknown>;
50
+ }
51
+ /**
52
+ * Options for a chat turn (sub-agent RPC entry point).
53
+ */
54
+ interface ChatOptions {
55
+ /** AbortSignal — fires when the caller wants to cancel the turn. */
56
+ signal?: AbortSignal;
57
+ /** Extra tools to merge with getTools() for this turn only. */
58
+ tools?: ToolSet;
59
+ }
60
+ /**
61
+ * Options passed to the onChatMessage handler.
62
+ */
63
+ interface ChatMessageOptions {
64
+ /** AbortSignal for cancelling the request */
65
+ signal?: AbortSignal;
66
+ /** Extra tools to merge with getTools() for this turn only. */
67
+ tools?: ToolSet;
68
+ }
69
+ declare const Think_base: ThinkBaseConstructor;
70
+ /**
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()`).
75
+ *
76
+ * @experimental Requires the `"experimental"` compatibility flag.
77
+ */
78
+ declare class Think<
79
+ Env extends Cloudflare.Env = Cloudflare.Env,
80
+ Config = Record<string, unknown>
81
+ > extends Think_base<Env> {
82
+ #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
+ /**
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.
93
+ *
94
+ * @experimental
95
+ */
96
+ fibers: boolean;
97
+ /**
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.
101
+ *
102
+ * This controls storage only — it does not affect what's sent to the LLM.
103
+ * Use `pruneMessages()` in `assembleContext()` to control LLM context.
104
+ */
105
+ 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
+ private _persistedMessageCache;
112
+ private _sessionId;
113
+ private _abortControllers;
114
+ private _clearGeneration;
115
+ private _ensureConfigTable;
116
+ /**
117
+ * Persist a typed configuration object.
118
+ * Stored in SQLite so it survives restarts and hibernation.
119
+ */
120
+ configure(config: Config): void;
121
+ /**
122
+ * Read the persisted configuration, or null if never configured.
123
+ */
124
+ getConfig(): Config | null;
125
+ onStart(): void;
126
+ /**
127
+ * Return the language model to use for inference.
128
+ * Must be overridden by subclasses that rely on the default
129
+ * `onChatMessage` implementation (the agentic loop).
130
+ */
131
+ getModel(): LanguageModel;
132
+ /**
133
+ * Return the system prompt for the assistant.
134
+ * Override to customize instructions.
135
+ */
136
+ getSystemPrompt(): string;
137
+ /**
138
+ * Return the tools available to the assistant.
139
+ * Override to provide workspace tools, custom tools, etc.
140
+ */
141
+ getTools(): ToolSet;
142
+ /**
143
+ * Return the maximum number of tool-call steps per turn.
144
+ */
145
+ 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): Array<{
157
+ name: string;
158
+ type: string;
159
+ size: number;
160
+ path: string;
161
+ }>;
162
+ /**
163
+ * Assemble the model messages from the current conversation history.
164
+ * Override to customize context assembly (e.g. inject memory,
165
+ * project context, or apply compaction).
166
+ */
167
+ assembleContext(): Promise<ModelMessage[]>;
168
+ /**
169
+ * Handle a chat turn and return the streaming result.
170
+ *
171
+ * The default implementation runs the agentic loop:
172
+ * 1. Assemble context from `this.messages`
173
+ * 2. Call `streamText` with the model, system prompt, tools, and step limit
174
+ *
175
+ * Override for full control over inference (e.g. different models per turn,
176
+ * RAG pipelines, routing to specialized sub-agents, etc.).
177
+ *
178
+ * When this is called, `this.messages` already contains the user's
179
+ * latest message persisted to the current session.
180
+ *
181
+ * @returns A result with `toUIMessageStream()` — AI SDK's `streamText()`
182
+ * return value satisfies this interface.
183
+ */
184
+ onChatMessage(options?: ChatMessageOptions): Promise<StreamableResult>;
185
+ /**
186
+ * Handle an error that occurred during a chat turn.
187
+ * Override to customize error handling (e.g. logging, metrics).
188
+ *
189
+ * @param error The error that occurred
190
+ * @returns The error (or a wrapped version) to propagate
191
+ */
192
+ onChatError(error: unknown): unknown;
193
+ /**
194
+ * Run a chat turn: persist the user message, run the agentic loop,
195
+ * stream UIMessageChunk events via callback, and persist the
196
+ * assistant's response.
197
+ *
198
+ * On error or abort, the partial assistant message is still persisted
199
+ * so the user doesn't lose context.
200
+ *
201
+ * @param userMessage The user's message (string or UIMessage for multi-modal)
202
+ * @param callback Streaming callback (typically an RpcTarget from the parent)
203
+ * @param options Optional chat options (e.g. AbortSignal)
204
+ */
205
+ chat(
206
+ userMessage: string | UIMessage,
207
+ callback: StreamCallback,
208
+ options?: ChatOptions
209
+ ): Promise<void>;
210
+ getSessions(): Session[];
211
+ createSession(name: string): Session;
212
+ switchSession(sessionId: string): UIMessage[];
213
+ deleteSession(sessionId: string): void;
214
+ renameSession(sessionId: string, name: string): void;
215
+ getCurrentSessionId(): string | null;
216
+ /**
217
+ * Get the current session info, or null if no session exists yet.
218
+ */
219
+ getSession(): Session | null;
220
+ /**
221
+ * Get the conversation history as UIMessage[].
222
+ */
223
+ getHistory(): UIMessage[];
224
+ /**
225
+ * Get the total message count for this session.
226
+ */
227
+ getMessageCount(): number;
228
+ /**
229
+ * Clear all messages from this session (preserves the session itself).
230
+ */
231
+ clearMessages(): void;
232
+ /**
233
+ * Wrap onMessage and onRequest to intercept the chat protocol.
234
+ * Unrecognized messages are forwarded to the user's handlers.
235
+ * @internal
236
+ */
237
+ private _setupProtocolHandlers;
238
+ /**
239
+ * Route an incoming WebSocket message to the appropriate handler.
240
+ * Returns true if the message was handled by the protocol.
241
+ * @internal
242
+ */
243
+ private _handleProtocol;
244
+ /**
245
+ * Handle CF_AGENT_USE_CHAT_REQUEST:
246
+ * 1. Parse incoming messages
247
+ * 2. Ensure a session exists
248
+ * 3. Persist user messages to session
249
+ * 4. Call onChatMessage
250
+ * 5. Stream response back to clients
251
+ * 6. Persist assistant message to session
252
+ * @internal
253
+ */
254
+ private _handleChatRequest;
255
+ /**
256
+ * Handle CF_AGENT_CHAT_CLEAR: abort streams, clear current session messages.
257
+ * @internal
258
+ */
259
+ private _handleClear;
260
+ /**
261
+ * Handle CF_AGENT_CHAT_REQUEST_CANCEL: abort a specific request.
262
+ * @internal
263
+ */
264
+ private _handleCancel;
265
+ /**
266
+ * Iterate a StreamableResult, broadcast chunks to clients,
267
+ * build a UIMessage, and persist it to the session.
268
+ * @internal
269
+ */
270
+ private _streamResult;
271
+ /**
272
+ * Persist an assistant message with sanitization, size enforcement,
273
+ * and incremental persistence.
274
+ * @internal
275
+ */
276
+ private _persistAssistantMessage;
277
+ /**
278
+ * Rebuild the persistence cache from current messages.
279
+ * Called on startup to enable incremental persistence.
280
+ * @internal
281
+ */
282
+ private _rebuildPersistenceCache;
283
+ /**
284
+ * Delete oldest messages on the current branch when count exceeds
285
+ * maxPersistedMessages. Uses path-based count (not total across all
286
+ * branches) and individual deletes to preserve branch structure.
287
+ * @internal
288
+ */
289
+ private _enforceMaxPersistedMessages;
290
+ /**
291
+ * Broadcast a JSON message to all connected clients.
292
+ * @internal
293
+ */
294
+ private _broadcast;
295
+ /**
296
+ * Broadcast the current message list to all connected clients.
297
+ * @internal
298
+ */
299
+ private _broadcastMessages;
300
+ }
301
+ //#endregion
302
+ export {
303
+ ChatMessageOptions,
304
+ ChatOptions,
305
+ type FiberCompleteContext,
306
+ type FiberContext,
307
+ type FiberMethods,
308
+ type FiberRecoveryContext,
309
+ type FiberState,
310
+ type Session,
311
+ StreamCallback,
312
+ StreamableResult,
313
+ Think
314
+ };
315
+ //# sourceMappingURL=think.d.ts.map