@cloudflare/think 0.0.0 → 0.1.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.
@@ -0,0 +1,317 @@
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 "@cloudflare/shell";
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): Promise<
157
+ Array<{
158
+ name: string;
159
+ type: string;
160
+ size: number;
161
+ path: string;
162
+ }>
163
+ >;
164
+ /**
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).
168
+ */
169
+ assembleContext(): Promise<ModelMessage[]>;
170
+ /**
171
+ * Handle a chat turn and return the streaming result.
172
+ *
173
+ * 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.).
179
+ *
180
+ * When this is called, `this.messages` already contains the user's
181
+ * latest message persisted to the current session.
182
+ *
183
+ * @returns A result with `toUIMessageStream()` — AI SDK's `streamText()`
184
+ * return value satisfies this interface.
185
+ */
186
+ onChatMessage(options?: ChatMessageOptions): Promise<StreamableResult>;
187
+ /**
188
+ * Handle an error that occurred during a chat turn.
189
+ * 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
+ */
194
+ onChatError(error: unknown): unknown;
195
+ /**
196
+ * Run a chat turn: persist the user message, run the agentic loop,
197
+ * stream UIMessageChunk events via callback, and persist the
198
+ * assistant's response.
199
+ *
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)
204
+ * @param callback Streaming callback (typically an RpcTarget from the parent)
205
+ * @param options Optional chat options (e.g. AbortSignal)
206
+ */
207
+ chat(
208
+ userMessage: string | UIMessage,
209
+ callback: StreamCallback,
210
+ options?: ChatOptions
211
+ ): 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
+ */
233
+ 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
+ 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
+ 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
+ private _handleChatRequest;
257
+ /**
258
+ * Handle CF_AGENT_CHAT_CLEAR: abort streams, clear current session messages.
259
+ * @internal
260
+ */
261
+ 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
+ private _streamResult;
273
+ /**
274
+ * Persist an assistant message with sanitization, size enforcement,
275
+ * and incremental persistence.
276
+ * @internal
277
+ */
278
+ 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
+ */
296
+ private _broadcast;
297
+ /**
298
+ * Broadcast the current message list to all connected clients.
299
+ * @internal
300
+ */
301
+ private _broadcastMessages;
302
+ }
303
+ //#endregion
304
+ export {
305
+ ChatMessageOptions,
306
+ ChatOptions,
307
+ type FiberCompleteContext,
308
+ type FiberContext,
309
+ type FiberMethods,
310
+ type FiberRecoveryContext,
311
+ type FiberState,
312
+ type Session,
313
+ StreamCallback,
314
+ StreamableResult,
315
+ Think
316
+ };
317
+ //# sourceMappingURL=think.d.ts.map