@cloudflare/think 0.8.5 → 0.8.7

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.
@@ -82,889 +82,1237 @@ import {
82
82
  import { ChatSdkStateAdapterOptions, ChatSdkStateAgent } from "agents/chat-sdk";
83
83
  import { RpcTarget } from "cloudflare:workers";
84
84
 
85
- //#region src/think.d.ts
86
- type ChatRecoveryRetryData = {
87
- targetUserId?: string;
88
- originalRequestId?: string;
89
- incidentId?: string;
90
- lastBody?: Record<string, unknown> | null;
91
- lastClientTools?: ClientToolSchema[] | null;
92
- recoveredRequestId?: string;
93
- };
94
- type ChatRecoveryContinueData = {
95
- targetAssistantId?: string;
96
- originalRequestId?: string;
97
- incidentId?: string;
98
- lastBody?: Record<string, unknown> | null;
99
- lastClientTools?: ClientToolSchema[] | null;
100
- recoveredRequestId?: string;
101
- };
102
- /**
103
- * Callback interface for streaming chat events from a Think sub-agent.
104
- *
105
- * Designed to work across the sub-agent RPC boundary — implement as
106
- * an RpcTarget in the parent agent and pass to `chat()`.
107
- */
108
- interface ChatStartEvent {
109
- requestId: string;
85
+ //#region src/messengers/events.d.ts
86
+ type MessengerEventKind =
87
+ | "direct-message"
88
+ | "mention"
89
+ | "subscribed-message"
90
+ | "action"
91
+ | "delivery-event";
92
+ interface MessengerAuthor {
93
+ fullName?: string;
94
+ isBot?: boolean | "unknown";
95
+ isMe?: boolean;
96
+ userId: string;
97
+ userName?: string;
110
98
  }
111
- interface StreamCallback {
112
- onStart(event: ChatStartEvent): void | Promise<void>;
113
- onEvent(json: string): void | Promise<void>;
114
- onDone(): void | Promise<void>;
115
- onError(error: string): void | Promise<void>;
116
- /**
117
- * The current attempt was interrupted (a stream-stall watchdog abort routed
118
- * into bounded recovery, #1626) and its final outcome will NOT arrive through
119
- * this callback. One of two things is true:
120
- * - a scheduled continuation — running in a LATER isolate invocation, without
121
- * this callback — will produce the answer (delivered to other channels,
122
- * e.g. WebSocket connections), OR
123
- * - the recovery budget was exhausted, so the turn was already terminalized
124
- * out-of-band (the configured `terminalMessage` + `onExhausted`) and is
125
- * terminally over — there is NO continuation to come.
126
- *
127
- * This is NOT `onDone` (this attempt did not complete) and NOT `onError` (the
128
- * raw stall is not surfaced as a terminal error here); without it the contract
129
- * `onStart → onEvent* → (onDone | onError)` is silently abandoned and a
130
- * consumer that treats the clean resolve as success finalizes a truncated
131
- * partial.
132
- *
133
- * Consumers should AVOID finalizing the partial on this signal — surface a
134
- * "recovering…" / "interrupted, please retry" state, or re-attach via a
135
- * durable channel — but must ALSO NOT block indefinitely waiting for a
136
- * continuation: per the exhausted case above, one may never come. Optional →
137
- * defaults to a no-op, so this is fully backward-compatible.
138
- *
139
- * Note: a deploy/eviction interruption kills the isolate (and this callback)
140
- * before this can fire — the caller observes a transport break instead. This
141
- * fires only for an in-isolate interruption (the stall→recovery path).
142
- */
143
- onInterrupted?(): void | Promise<void>;
99
+ interface MessengerAttachment {
100
+ data?: ArrayBuffer;
101
+ fetch?: () => Promise<ArrayBuffer>;
102
+ id?: string;
103
+ mediaType?: string;
104
+ name?: string;
105
+ raw?: unknown;
106
+ size?: number;
107
+ text?: string;
108
+ url?: string;
144
109
  }
145
- /**
146
- * Minimal interface for the result of the inference loop.
147
- * The AI SDK's `streamText()` result satisfies this interface.
148
- */
149
- interface StreamableResult {
150
- toUIMessageStream(options?: {
151
- sendReasoning?: boolean;
152
- }): AsyncIterable<unknown>;
153
- output?: PromiseLike<unknown>;
110
+ interface MessengerThread {
111
+ channelId?: string;
112
+ channelName?: string;
113
+ id: string;
114
+ isDirectMessage: boolean;
115
+ providerThreadId: string;
116
+ title?: string;
154
117
  }
155
- /**
156
- * Options for a chat turn (sub-agent RPC entry point).
157
- */
158
- interface ChatOptions {
159
- signal?: AbortSignal;
118
+ interface MessengerMessage {
119
+ attachments: MessengerAttachment[];
120
+ author: MessengerAuthor;
121
+ createdAt?: Date;
122
+ id: string;
123
+ isMention?: boolean;
124
+ providerMessageId: string;
125
+ raw?: unknown;
126
+ text: string;
160
127
  }
161
- type AgentToolChildRunStatus =
162
- | "starting"
163
- | "running"
164
- | "completed"
165
- | "error"
166
- | "aborted";
167
- type AgentToolRunInspection<Output = unknown> = {
168
- runId: string;
169
- status: AgentToolChildRunStatus;
170
- requestId?: string;
171
- streamId?: string;
172
- output?: Output;
173
- summary?: string;
174
- error?: string;
175
- startedAt: number;
176
- completedAt?: number;
177
- };
178
- type Digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";
179
- type Hour = `0${Digit}` | `1${Digit}` | "20" | "21" | "22" | "23";
180
- type Minute = `${"0" | "1" | "2" | "3" | "4" | "5"}${Digit}`;
181
- type ThinkTime = `${Hour}:${Minute}`;
182
- type ThinkIntervalSchedule =
183
- | `every ${number} minute${"" | "s"}`
184
- | `every ${number} hour${"" | "s"}`;
185
- type ThinkWallClockSchedule =
186
- | `every day at ${ThinkTime}`
187
- | `every weekday at ${ThinkTime}`
188
- | `every week on ${string} at ${ThinkTime}`;
189
- type ThinkScheduledTaskSchedule =
190
- | ThinkIntervalSchedule
191
- | ThinkWallClockSchedule
192
- | `${ThinkWallClockSchedule} in ${string}`;
193
- type ThinkScheduledTaskContext = {
194
- taskId: string;
195
- scheduledFor: number;
196
- scheduledForDate: Date;
197
- occurrenceKey: string;
198
- idempotencyKey: string;
199
- schedule: string;
200
- scheduleKind: "interval" | "wall-clock";
201
- timezone?: string;
202
- metadata?: Record<string, unknown>;
203
- };
204
- type ThinkScheduledTaskPromptAction = {
205
- prompt: string | (() => string | Promise<string>);
206
- handler?: never;
207
- };
208
- type ThinkScheduledTaskHandlerAction = {
209
- handler: (ctx: ThinkScheduledTaskContext) => void | Promise<void>;
210
- prompt?: never;
211
- };
212
- type ThinkScheduledTaskBase = (
213
- | ThinkScheduledTaskPromptAction
214
- | ThinkScheduledTaskHandlerAction
215
- ) & {
216
- retry?: RetryOptions;
217
- metadata?: Record<string, unknown>;
218
- };
219
- type ThinkScheduledTask =
220
- | (ThinkScheduledTaskBase & {
221
- schedule: ThinkIntervalSchedule;
222
- timezone?: never;
223
- })
224
- | (ThinkScheduledTaskBase & {
225
- schedule: ThinkWallClockSchedule;
226
- timezone?: string;
227
- })
228
- | (ThinkScheduledTaskBase & {
229
- schedule: `${ThinkWallClockSchedule} in ${string}`;
230
- timezone?: string;
231
- });
232
- type ThinkScheduledTasks = Record<string, ThinkScheduledTask>;
233
- declare function defineScheduledTasks<const T extends ThinkScheduledTasks>(
234
- tasks: T
235
- ): T;
236
- type DeclaredScheduledTaskPayload = {
237
- taskId: string;
238
- scheduleHash: string;
239
- scheduledFor: number;
240
- };
241
- type AgentToolStoredChunk = {
242
- sequence: number;
243
- body: string;
244
- };
245
- type ThinkSubmissionStatus =
246
- | "pending"
247
- | "running"
248
- | "completed"
249
- | "aborted"
250
- | "skipped"
251
- | "error";
252
- type SubmitMessagesOptions = {
253
- submissionId?: string;
254
- idempotencyKey?: string;
255
- metadata?: Record<string, unknown>;
256
- };
257
- type ThinkWorkflowPromptContext = {
258
- workflow: {
259
- name: string;
260
- id: string;
261
- stepName: string;
262
- eventType: string;
263
- };
264
- output?: {
265
- schema: unknown;
266
- };
267
- fingerprint?: string;
268
- };
269
- type ThinkSubmissionInspection = {
270
- submissionId: string;
271
- idempotencyKey?: string;
272
- requestId?: string;
273
- status: ThinkSubmissionStatus;
274
- error?: string;
275
- metadata?: Record<string, unknown>;
276
- createdAt: number;
277
- startedAt?: number;
278
- completedAt?: number;
279
- };
280
- type SubmitMessagesResult = ThinkSubmissionInspection & {
281
- accepted: boolean;
282
- };
283
- type ListSubmissionsOptions = {
284
- status?: ThinkSubmissionStatus | ThinkSubmissionStatus[];
285
- limit?: number;
286
- };
287
- type DeleteSubmissionsOptions = {
288
- status?: ThinkSubmissionStatus | ThinkSubmissionStatus[];
289
- completedBefore?: Date;
290
- limit?: number;
291
- };
292
- /**
293
- * A chat turn request. Built automatically by each entry path
294
- * (WebSocket, chat(), saveMessages, auto-continuation) and passed
295
- * to Think's inference loop.
296
- */
297
- interface TurnInput {
298
- signal?: AbortSignal;
299
- /** Client-provided tool schemas for dynamic tool registration. */
300
- clientTools?: ClientToolSchema[];
301
- /** Custom body fields from the client request. */
302
- body?: Record<string, unknown>;
303
- /** Internal workflow prompt configuration, never sourced from client body. */
304
- workflowPrompt?: ThinkWorkflowPromptContext;
305
- /** Whether this is a continuation turn (auto-continue after tool result, recovery). */
306
- continuation: boolean;
128
+ interface MessengerAction {
129
+ actionId: string;
130
+ messageId?: string;
131
+ raw?: unknown;
132
+ user?: MessengerAuthor;
133
+ value?: string;
307
134
  }
308
- /**
309
- * Context passed to the `beforeTurn` hook.
310
- * Contains everything Think assembled — the hook can inspect and override.
311
- */
312
- interface TurnContext {
313
- /** Assembled system prompt (from context blocks or getSystemPrompt fallback). */
314
- system: string;
315
- /** Assembled model messages (truncated, pruned). */
316
- messages: ModelMessage[];
317
- /** Merged tool set (workspace + getTools + session + MCP + client + caller). */
318
- tools: ToolSet;
319
- /** The language model from getModel(). */
320
- model: LanguageModel;
321
- /** Whether this is a continuation turn. */
322
- continuation: boolean;
323
- /** Custom body fields from the client request. */
324
- body?: Record<string, unknown>;
135
+ interface MessengerCapabilities {
136
+ canEditMessages?: boolean;
137
+ canStream?: boolean;
138
+ maxMessageLength?: number;
139
+ supportsActions?: boolean;
140
+ supportsAttachments?: boolean;
141
+ supportsEphemeral?: boolean;
325
142
  }
326
- /**
327
- * Configuration returned by the `beforeTurn` hook to override defaults.
328
- * All fields are optional — return only what you want to change.
329
- */
330
- interface TurnConfig {
331
- /** Override the model for this turn (e.g. cheap model for continuations). */
332
- model?: LanguageModel;
333
- /** Override the assembled system prompt. */
334
- system?: string;
335
- /** Override the assembled messages. */
336
- messages?: ModelMessage[];
337
- /** Extra tools to merge (additive — spread on top of existing tools). */
338
- tools?: ToolSet;
339
- /** Limit which tools the model can call (AI SDK activeTools). */
340
- activeTools?: string[];
341
- /** Force a specific tool call (AI SDK toolChoice). */
342
- toolChoice?: Parameters<typeof streamText>[0]["toolChoice"];
343
- /** Override maxSteps for this turn. */
344
- maxSteps?: number;
345
- /**
346
- * Additional AI SDK stop conditions for ending the turn early.
347
- * Think always keeps its `maxSteps` stop condition as a safety bound.
348
- */
349
- stopWhen?: StopCondition<ToolSet> | Array<StopCondition<ToolSet>>;
350
- /**
351
- * Controls whether reasoning chunks are included in the UI message stream
352
- * for this turn. Defaults to the instance-level `sendReasoning` setting.
353
- */
354
- sendReasoning?: boolean;
355
- /**
356
- * Override the stream-stall inactivity watchdog timeout for THIS turn only
357
- * (ms; `0` disables it for this turn). Defaults to the instance-level
358
- * `chatStreamStallTimeoutMs`. Because the watchdog measures the gap between
359
- * UI-message-stream chunks — which includes server-side tool execution — a
360
- * turn known to invoke a slow tool can raise (or disable) the timeout for
361
- * just that turn instead of permanently widening the global window. Auto-
362
- * resets after the turn.
363
- */
364
- chatStreamStallTimeoutMs?: number;
365
- /** Maximum number of tokens to generate for this turn. */
366
- maxOutputTokens?: Parameters<typeof streamText>[0]["maxOutputTokens"];
367
- /** Temperature setting for this turn. */
368
- temperature?: Parameters<typeof streamText>[0]["temperature"];
369
- /** Nucleus sampling setting for this turn. */
370
- topP?: Parameters<typeof streamText>[0]["topP"];
371
- /** Top-K sampling setting for this turn. */
372
- topK?: Parameters<typeof streamText>[0]["topK"];
373
- /** Presence penalty setting for this turn. */
374
- presencePenalty?: Parameters<typeof streamText>[0]["presencePenalty"];
375
- /** Frequency penalty setting for this turn. */
376
- frequencyPenalty?: Parameters<typeof streamText>[0]["frequencyPenalty"];
377
- /** Stop sequences for this turn. */
378
- stopSequences?: Parameters<typeof streamText>[0]["stopSequences"];
379
- /** Seed for deterministic sampling when supported by the model. */
380
- seed?: Parameters<typeof streamText>[0]["seed"];
381
- /** Maximum number of retries for this turn. Set to 0 to disable retries. */
382
- maxRetries?: Parameters<typeof streamText>[0]["maxRetries"];
383
- /** Timeout configuration for this turn. */
384
- timeout?: Parameters<typeof streamText>[0]["timeout"];
385
- /** Additional HTTP headers for provider requests on this turn. */
386
- headers?: Parameters<typeof streamText>[0]["headers"];
387
- /** Provider-specific options (AI SDK providerOptions). */
388
- providerOptions?: Record<string, unknown>;
389
- /** Optional AI SDK telemetry configuration for this turn. */
390
- experimental_telemetry?: Parameters<
391
- typeof streamText
392
- >[0]["experimental_telemetry"];
393
- /**
394
- * Optional structured-output specification (AI SDK `output`).
395
- * Forwarded to `streamText` so the model's final response is parsed
396
- * against the supplied schema. Use the AI SDK's `Output.object({ schema })`
397
- * / `Output.text()` helpers. Combine with `activeTools: []` on the
398
- * terminal turn if your provider strips tools when structured output
399
- * is active (e.g. workers-ai-provider).
400
- */
401
- output?: Parameters<typeof streamText>[0]["output"];
143
+ interface MessengerContext {
144
+ action?: MessengerAction;
145
+ author?: MessengerAuthor;
146
+ capabilities: MessengerCapabilities;
147
+ kind: MessengerEventKind;
148
+ message?: MessengerMessage;
149
+ messengerId: string;
150
+ provider: string;
151
+ thread: MessengerThread;
402
152
  }
403
- /**
404
- * Provider-agnostic semantic classification of a chat-turn error.
405
- *
406
- * Think ships **no** provider-specific string/code matching — the app owns
407
- * that knowledge (it knows which provider/model it talks to), exactly like the
408
- * `tokenCounter` it already passes to `compactAfter()`. An app teaches Think
409
- * what an error *means* by overriding `classifyChatError()`; Think then reacts
410
- * generically (e.g. compact-and-retry on `context_overflow`).
411
- *
412
- * - `context_overflow` — the prompt exceeded the model's context window
413
- * (Anthropic `"prompt is too long"`, OpenAI `context_length_exceeded`, …).
414
- * The only category Think currently acts on (auto-compact + retry).
415
- * - `rate_limit` / `transient` — reserved for future backoff/retry policies.
416
- * - `fatal` — unrecoverable; surface terminally.
417
- * - `unknown` — default; Think applies its existing terminal behavior.
418
- */
419
- type ChatErrorClassification =
420
- | "context_overflow"
421
- | "rate_limit"
422
- | "transient"
423
- | "fatal"
424
- | "unknown";
425
- /**
426
- * Opt-in handling for a turn that overflows the model's context window
427
- * mid-flight. Compaction (`compactAfter()`) is only checked between turns, so a
428
- * long, tool-heavy turn can grow past the window before the next check; the
429
- * provider then rejects the request (`"prompt is too long"` /
430
- * `context_length_exceeded`). Both layers reuse the session's compaction
431
- * function and are provider-agnostic — the app maps the error via
432
- * {@link Think.classifyChatError}; Think never matches provider strings itself.
433
- *
434
- * Set `Think.contextOverflow` to enable. Leaving it unset disables both layers
435
- * (existing terminal behavior).
436
- */
437
- interface ContextOverflowConfig {
438
- /**
439
- * Reactive backstop. When a turn fails with an error classified as
440
- * `"context_overflow"`, discard the truncated partial, run
441
- * `session.compact()`, and re-run the turn from the compacted history. The
442
- * partial is intentionally not persisted: the turn restarts from scratch, so
443
- * keeping the cut-off assistant message would orphan it beside the recovered
444
- * answer (and duplicate any tool work the retry re-issues). If compaction
445
- * cannot shorten history or the retry budget is spent, the overflow surfaces
446
- * terminally through `onChatError` (classified) — it never loops or ends
447
- * silently. Default `false`.
448
- */
449
- reactive?: boolean;
450
- /**
451
- * Maximum compact-and-retry attempts for a single overflowing turn (the
452
- * reactive backstop). Independent of the proactive guard's cap — see
453
- * {@link proactive.maxCompactions}. Default `1`.
454
- */
455
- maxRetries?: number;
456
- /**
457
- * Proactive guard. Before each step, read the previous step's model-reported
458
- * `usage.inputTokens` and, if it crosses `maxInputTokens * (headroom ?? 0.9)`,
459
- * compact in place and feed the recompacted history into the upcoming step —
460
- * heading off the provider rejection before it happens. Keys off usage (every
461
- * provider reports it), not provider error strings. Unset disables it.
462
- *
463
- * If a provider omits `inputTokens`, the guard falls back to `usage.totalTokens`
464
- * (input + output) — a safe over-approximation that compacts slightly early
465
- * rather than missing the threshold. If neither is reported, the guard does
466
- * nothing that step (the reactive backstop still catches a genuine overflow).
467
- *
468
- * `maxCompactions` caps how many times the guard may compact within a single
469
- * step loop (default `1`, floored at `1`). It is independent of
470
- * {@link maxRetries} (the reactive budget): a no-op compaction would repeat on
471
- * every step, so the cap stops the guard from compacting (and emitting
472
- * `chat:context:compacted`) on each one.
473
- */
474
- proactive?: {
475
- maxInputTokens: number;
476
- headroom?: number;
477
- maxCompactions?: number;
478
- };
153
+ interface MessengerEvent extends MessengerContext {
154
+ raw?: unknown;
479
155
  }
480
- /**
481
- * Opt-in default classifier for {@link Think.classifyChatError}. Matches the
482
- * context-window-overflow error messages of the common providers (Anthropic,
483
- * OpenAI, Google, Bedrock, Mistral, …) and returns `"context_overflow"`.
484
- *
485
- * Think ships this as an explicitly-imported helper rather than wiring it into
486
- * core, so the framework default stays free of provider strings. Assign it (or
487
- * delegate to it) when you do not need custom classification:
488
- *
489
- * @example
490
- * ```typescript
491
- * import { Think, defaultContextOverflowClassifier } from "@cloudflare/think";
492
- *
493
- * export class MyAgent extends Think<Env> {
494
- * override contextOverflow = { reactive: true };
495
- * override classifyChatError = defaultContextOverflowClassifier;
496
- * }
497
- * ```
498
- *
499
- * Or combine with your own checks:
500
- *
501
- * @example
502
- * ```typescript
503
- * override classifyChatError(error: unknown): ChatErrorClassification | void {
504
- * if (isMyRateLimit(error)) return "rate_limit";
505
- * return defaultContextOverflowClassifier(error);
506
- * }
507
- * ```
508
- */
509
- declare function defaultContextOverflowClassifier(
510
- error: unknown
511
- ): ChatErrorClassification | undefined;
512
- interface ChatErrorContext {
513
- requestId?: string;
514
- stage: "parse" | "persist" | "turn" | "stream" | "recovery" | "transcript";
515
- messagesPersisted?: boolean;
516
- /**
517
- * App-provided semantic classification (from `classifyChatError`), when
518
- * known. Lets `onChatError` overrides and observers distinguish e.g. a
519
- * context-overflow from a generic provider failure without re-matching
520
- * provider strings.
521
- */
522
- classification?: ChatErrorClassification;
156
+ declare function messengerContextFromEvent(
157
+ event: MessengerEvent
158
+ ): MessengerContext;
159
+ declare function serializableMessengerEvent(
160
+ event: MessengerEvent
161
+ ): MessengerEvent;
162
+ declare function toMessengerUserMessage(event: MessengerEvent): UIMessage;
163
+ //#endregion
164
+ //#region src/messengers/delivery.d.ts
165
+ declare const MESSENGER_REPLY_FIBER_NAME = "think:messenger-reply";
166
+ declare const EMPTY_MESSENGER_RESPONSE =
167
+ "I couldn't produce a text response. Please try again.";
168
+ declare const ERROR_MESSENGER_RESPONSE =
169
+ "Sorry, I couldn't answer that right now. Please try again.";
170
+ declare const INTERRUPTED_MESSENGER_RESPONSE =
171
+ "Sorry, my reply was interrupted. Please send your message again if you'd like me to retry.";
172
+ interface TextStreamCallbackOptions {
173
+ onVisibleStart?: () => Promise<void> | void;
174
+ visibleSoftLimit?: number;
523
175
  }
524
- /**
525
- * Context passed to the `beforeStep` hook before each AI SDK step in
526
- * the agentic loop. Backed by the AI SDK's `PrepareStepFunction<TOOLS>`
527
- * parameter — exposes the previous `steps`, the zero-based `stepNumber`,
528
- * the currently selected `model`, the `messages` about to be sent, and
529
- * `experimental_context`.
530
- *
531
- * Pass an explicit `TOOLS` generic for typed previous tool calls / results.
532
- *
533
- * Limitations (AI SDK boundary, not Think):
534
- * - No `abortSignal` is exposed in the context. If you do remote work
535
- * inside `beforeStep`, it cannot be cancelled by turn-level abort.
536
- * - `experimental_context` is typed `unknown`; users must narrow it.
537
- * - `output` cannot be overridden per-step — set it at the turn level
538
- * via `TurnConfig.output` (returned from `beforeTurn`).
539
- */
540
- type PrepareStepContext<TOOLS extends ToolSet = ToolSet> = Parameters<
541
- PrepareStepFunction<TOOLS>
542
- >[0];
543
- /**
544
- * Configuration returned by `beforeStep` to override defaults for the
545
- * current AI SDK step. This is the AI SDK's `PrepareStepResult<TOOLS>` —
546
- * return only the fields you want to override (`model`, `toolChoice`,
547
- * `activeTools`, `system`, `messages`, `experimental_context`,
548
- * `providerOptions`).
549
- */
550
- type StepConfig<TOOLS extends ToolSet = ToolSet> = PrepareStepResult<TOOLS>;
551
- /**
552
- * Context passed to the `beforeToolCall` hook **before** the tool's
553
- * `execute` function runs.
554
- *
555
- * Backed by the AI SDK's `OnToolCallStartEvent` (the parameter of
556
- * `experimental_onToolCallStart`). The full `TypedToolCall<TOOLS>`
557
- * fields (`toolName`, `toolCallId`, `input`, `providerMetadata`, the
558
- * dynamic/invalid/error discriminators) are spread at the top level for
559
- * convenience, with the per-call event extras attached:
560
- *
561
- * - `stepNumber` — index of the current step
562
- * - `messages` — conversation messages visible at tool execution time
563
- * - `abortSignal` — signal that aborts if the turn is cancelled
564
- *
565
- * Pass an explicit `TOOLS` generic for full input typing:
566
- *
567
- * ```ts
568
- * import type { ToolCallContext } from "@cloudflare/think";
569
- * import type { tools } from "./my-tools";
570
- *
571
- * beforeToolCall(ctx: ToolCallContext<typeof tools>) {
572
- * if (ctx.toolName === "search") {
573
- * ctx.input.query; // typed
574
- * }
575
- * }
576
- * ```
577
- */
578
- type ToolCallContext<TOOLS extends ToolSet = ToolSet> = TypedToolCall<TOOLS> & {
579
- /** Zero-based index of the current step where this tool call occurs. */ readonly stepNumber:
580
- | number
581
- | undefined /** The conversation messages available at tool execution time. */;
582
- readonly messages: ReadonlyArray<ModelMessage> /** Signal for cancelling the operation. */;
583
- readonly abortSignal: AbortSignal | undefined;
584
- };
585
- /**
586
- * Decision returned by `beforeToolCall` to control tool execution.
587
- * Return void/undefined to allow execution with original input.
588
- *
589
- * Discriminated union — each action has a clear, non-overlapping meaning:
590
- * - `allow` — execute the tool (optionally with modified input)
591
- * - `block` — don't execute; return `reason` as the tool result so the model can adjust
592
- * - `substitute` — don't execute; return `output` as the tool result (afterToolCall still fires)
593
- */
594
- type ToolCallDecision =
595
- | {
596
- action: "allow" /** Modified input — tool executes with this instead of the original. */;
597
- input?: Record<string, unknown>;
598
- }
176
+ declare class TextStreamCallback extends RpcTarget implements StreamCallback {
177
+ private readonly onVisibleStart?;
178
+ private readonly visibleChunks;
179
+ private readonly wakeups;
180
+ private readonly visibleSoftLimit?;
181
+ private chatRequestId?;
182
+ private closed;
183
+ private interrupted;
184
+ private error?;
185
+ private text;
186
+ private visibleClosed;
187
+ private visibleLimitReachedValue;
188
+ private visibleStarted;
189
+ private visibleTextValue;
190
+ constructor(options?: TextStreamCallbackOptions);
191
+ onStart(event: ChatStartEvent): void;
192
+ onEvent(json: string): void;
193
+ onDone(): void;
194
+ onError(error: string): void;
195
+ onInterrupted(): void;
196
+ wasInterrupted(): boolean;
197
+ close(): void;
198
+ fail(error: unknown): void;
199
+ hasText(): boolean;
200
+ remainingText(): string;
201
+ requestId(): string | undefined;
202
+ textSoFar(): string;
203
+ visibleLimitReached(): boolean;
204
+ visibleText(): string;
205
+ stream(): AsyncIterable<string>;
206
+ private pushVisibleText;
207
+ private wake;
208
+ private markVisibleStarted;
209
+ }
210
+ declare function textDeltaFromStreamChunk(json: string): string | null;
211
+ type MessengerReplyStage = "accepted" | "streaming" | "completed";
212
+ interface MessengerReplySnapshot {
213
+ event: MessengerEvent;
214
+ stage: MessengerReplyStage;
215
+ thread?: unknown;
216
+ type: typeof MESSENGER_REPLY_FIBER_NAME;
217
+ }
218
+ declare function messengerReplySnapshot(
219
+ stage: MessengerReplyStage,
220
+ event: MessengerEvent,
221
+ thread?: unknown
222
+ ): MessengerReplySnapshot;
223
+ declare function parseMessengerReplySnapshot(
224
+ snapshot: unknown
225
+ ): MessengerReplySnapshot | null;
226
+ declare function messengerReplyRecoveryMode(
227
+ snapshot: MessengerReplySnapshot
228
+ ): "answer" | "apologize" | null;
229
+ declare function messengerReplyFailureMode(
230
+ hasStreamedText: boolean,
231
+ completedModelTurn?: boolean,
232
+ expectedDeliveryCompletion?: boolean
233
+ ): "apologize" | "error" | null;
234
+ interface MessengerDeliveryTarget {
235
+ cancelChat(
236
+ requestId: string,
237
+ reason?: string
238
+ ): boolean | void | Promise<boolean | void>;
239
+ chat(
240
+ userMessage: string | UIMessage,
241
+ callback: StreamCallback
242
+ ): Promise<void>;
243
+ chatWithMessengerContext?(
244
+ userMessage: string | UIMessage,
245
+ callback: StreamCallback,
246
+ context: MessengerEvent
247
+ ): Promise<void>;
248
+ }
249
+ interface MessengerDeliverySurface {
250
+ post(
251
+ message:
252
+ | string
253
+ | {
254
+ markdown: string;
255
+ }
256
+ | AsyncIterable<string>
257
+ ): Promise<unknown>;
258
+ startTyping?(status?: string): Promise<void>;
259
+ }
260
+ interface MessengerDeliveryPolicy {
261
+ emptyResponseText?: string;
262
+ errorResponseText?: string;
263
+ interruptedResponseText?: string;
264
+ isExpectedDeliveryCompletion?(
265
+ error: unknown,
266
+ callback: TextStreamCallback
267
+ ): boolean;
268
+ splitText?(text: string): string[];
269
+ visibleSoftLimit?: number;
270
+ }
271
+ interface DeliverMessengerReplyOptions {
272
+ checkpoint?: (snapshot: MessengerReplySnapshot) => Promise<void> | void;
273
+ event: MessengerEvent;
274
+ fiber?: FiberContext;
275
+ policy?: MessengerDeliveryPolicy;
276
+ snapshotEvent?: MessengerEvent;
277
+ snapshotThread?: unknown;
278
+ surface: MessengerDeliverySurface;
279
+ target: MessengerDeliveryTarget;
280
+ userMessage?: UIMessage;
281
+ }
282
+ declare function deliverMessengerReply(
283
+ options: DeliverMessengerReplyOptions
284
+ ): Promise<void>;
285
+ //#endregion
286
+ //#region src/messengers/chat-sdk.d.ts
287
+ declare class ThinkMessengerStateAgent extends ChatSdkStateAgent {}
288
+ type MessengerRespondTo =
289
+ | "action"
290
+ | "direct-message"
291
+ | "mention"
292
+ | "subscribed-thread";
293
+ type MessengerConversationMode = "self" | "thread";
294
+ type MessengerConversationTarget =
599
295
  | {
600
- action: "block" /** Returned as the tool result so the model can adjust. */;
601
- reason?: string;
296
+ target: "self";
602
297
  }
603
298
  | {
604
- action: "substitute" /** The substitute tool output — model sees this instead of real execution. */;
605
- output: unknown /** Optional input attribution for the afterToolCall log. */;
606
- input?: Record<string, unknown>;
299
+ agentClass?: SubAgentClass<Agent & MessengerThinkTarget>;
300
+ name: string;
301
+ target: "subagent";
607
302
  };
608
- /**
609
- * Context passed to the `afterToolCall` hook after a tool executes.
610
- *
611
- * Backed by the AI SDK's `OnToolCallFinishEvent` (the parameter of
612
- * `experimental_onToolCallFinish`). The full `TypedToolCall<TOOLS>`
613
- * fields (`toolName`, `toolCallId`, `input`, …) are spread at the top
614
- * level, plus the per-call event extras:
615
- *
616
- * - `stepNumber` — index of the current step
617
- * - `messages` — conversation messages visible at tool execution time
618
- * - `durationMs` — wall-clock execution time in milliseconds
619
- * - `success`/`output`/`error` — discriminated outcome:
620
- * - on success: `success: true`, `output: unknown`
621
- * - on failure: `success: false`, `error: unknown`
622
- *
623
- * Pass an explicit `TOOLS` generic for full input typing:
624
- *
625
- * ```ts
626
- * import type { ToolCallResultContext } from "@cloudflare/think";
627
- * import type { tools } from "./my-tools";
628
- *
629
- * afterToolCall(ctx: ToolCallResultContext<typeof tools>) {
630
- * if (ctx.success) {
631
- * console.log(`${ctx.toolName} took ${ctx.durationMs}ms`, ctx.output);
632
- * } else {
633
- * console.error(`${ctx.toolName} failed:`, ctx.error);
634
- * }
635
- * }
636
- * ```
637
- */
638
- type ToolCallResultContext<TOOLS extends ToolSet = ToolSet> =
639
- TypedToolCall<TOOLS> & {
640
- readonly stepNumber: number | undefined;
641
- readonly messages: ReadonlyArray<ModelMessage> /** Wall-clock execution time in milliseconds. */;
642
- readonly durationMs: number;
643
- } & (
644
- | {
645
- readonly success: true;
646
- readonly output: unknown;
647
- readonly error?: never;
648
- }
649
- | {
650
- readonly success: false;
651
- readonly output?: never;
652
- readonly error: unknown;
653
- }
654
- );
655
- /**
656
- * Context passed to the `onStepFinish` hook after each step completes.
657
- *
658
- * This is the AI SDK's `StepResult<TOOLS>` (= `OnStepFinishEvent<TOOLS>`) —
659
- * the full step record including `text`, `reasoning`, `toolCalls`,
660
- * `toolResults`, `files`, `sources`, `usage` (with `cachedInputTokens`,
661
- * `reasoningTokens`, `totalTokens`), `finishReason`, `warnings`, `request`,
662
- * `response`, and `providerMetadata` (where provider-specific cache
663
- * accounting like `cacheCreationInputTokens` lives).
664
- *
665
- * Pass an explicit `TOOLS` generic for typed `toolCalls`/`toolResults`.
666
- */
667
- type StepContext<TOOLS extends ToolSet = ToolSet> = Parameters<
668
- StreamTextOnStepFinishCallback<TOOLS>
669
- >[0];
670
- /**
671
- * Context passed to the `onChunk` hook for each streaming chunk.
672
- *
673
- * This is the AI SDK's `StreamTextOnChunkCallback` event — `{ chunk }`
674
- * where `chunk` is a discriminated union of `TextStreamPart` variants
675
- * (text-delta, reasoning-delta, source, tool-call, tool-input-start,
676
- * tool-input-delta, tool-result, raw).
677
- */
678
- type ChunkContext<TOOLS extends ToolSet = ToolSet> = Parameters<
679
- StreamTextOnChunkCallback<TOOLS>
680
- >[0];
681
- /**
682
- * @internal Re-export of the chunk variant union for consumers that need
683
- * to narrow on `chunk.type` without importing `TextStreamPart` directly.
684
- */
685
- type ChunkPart<TOOLS extends ToolSet = ToolSet> = ChunkContext<TOOLS>["chunk"];
686
- /**
687
- * Configuration for a sandboxed extension, returned by getExtensions().
688
- */
689
- interface ExtensionConfig {
690
- /** Extension manifest (name, version, permissions, contributions). */
691
- manifest: ExtensionManifest;
692
- /** JavaScript source code defining the extension's tools. */
693
- source: string;
303
+ type MessengerConversationResolver = (
304
+ event: MessengerEvent
305
+ ) => MessengerConversationTarget | Promise<MessengerConversationTarget>;
306
+ interface MessengerDefinition {
307
+ adapter: Adapter;
308
+ adapterName: string;
309
+ capabilities?: MessengerCapabilities;
310
+ conversation?: MessengerConversationMode | MessengerConversationResolver;
311
+ delivery?: MessengerDeliveryPolicy;
312
+ keyShard?: ChatSdkStateAdapterOptions["keyShard"];
313
+ path?: string;
314
+ provider: string;
315
+ respondTo?: readonly MessengerRespondTo[];
316
+ shardKey?: ChatSdkStateAdapterOptions["shardKey"];
317
+ subscribeOnMention?: boolean;
318
+ toEvent?: (
319
+ input: ChatSdkMessengerEventInput
320
+ ) => MessengerEvent | Promise<MessengerEvent>;
321
+ userName: string;
322
+ verifyWebhook?:
323
+ | false
324
+ | ((request: Request) => boolean | Response | Promise<boolean | Response>);
325
+ }
326
+ type ThinkMessengers = Record<string, MessengerDefinition>;
327
+ interface NormalizedMessengerDefinition extends MessengerDefinition {
328
+ id: string;
329
+ path: string;
330
+ respondTo: readonly MessengerRespondTo[];
331
+ subscribeOnMention: boolean;
332
+ verifyWebhook:
333
+ | false
334
+ | ((request: Request) => boolean | Response | Promise<boolean | Response>);
335
+ }
336
+ interface ChatSdkMessengerOptions extends Omit<
337
+ MessengerDefinition,
338
+ "adapterName"
339
+ > {
340
+ adapterName?: string;
341
+ }
342
+ interface ChatSdkMessengerEventInput {
343
+ action?: ActionEvent;
344
+ eventKind: MessengerEventKind;
345
+ message?: Message;
346
+ raw?: unknown;
347
+ thread: Thread;
348
+ }
349
+ interface MessengerThinkTarget {
350
+ cancelChat(
351
+ requestId: string,
352
+ reason?: string
353
+ ): boolean | void | Promise<boolean | void>;
354
+ chat(
355
+ userMessage: string | UIMessage,
356
+ callback: StreamCallback
357
+ ): Promise<void>;
358
+ chatWithMessengerContext?(
359
+ userMessage: string | UIMessage,
360
+ callback: StreamCallback,
361
+ context: MessengerEvent
362
+ ): Promise<void>;
363
+ }
364
+ interface MessengerThinkHost extends MessengerThinkTarget {
365
+ constructor: {
366
+ name: string;
367
+ };
368
+ name: string;
369
+ parentPath: ReadonlyArray<{
370
+ className: string;
371
+ name: string;
372
+ }>;
373
+ startFiber(
374
+ name: string,
375
+ fn: (ctx: FiberContext) => Promise<void>,
376
+ options?: StartFiberOptions
377
+ ): Promise<MessengerFiberStartResult>;
378
+ resolveFiber(id: string, result: FiberRecoveryResult): Promise<boolean>;
379
+ subAgent<T extends Agent>(
380
+ agentClass: SubAgentClass<T>,
381
+ name: string
382
+ ): Promise<SubAgentStub<T>>;
383
+ }
384
+ interface MessengerFiberStartResult {
385
+ accepted: boolean;
386
+ fiberId: string;
387
+ snapshot?: unknown;
388
+ status: string;
389
+ }
390
+ declare function defineMessengers<T extends ThinkMessengers>(messengers: T): T;
391
+ declare function chatSdkMessenger(
392
+ options: ChatSdkMessengerOptions
393
+ ): MessengerDefinition;
394
+ declare class ThinkMessengerRuntime {
395
+ private readonly host;
396
+ private chat?;
397
+ private readonly definitionsByAdapterName;
398
+ private readonly definitionsById;
399
+ private readonly definitions;
400
+ constructor(definitions: ThinkMessengers, host: MessengerThinkHost);
401
+ get size(): number;
402
+ initialize(): void;
403
+ handleRequest(request: Request): Promise<Response | undefined>;
404
+ handleFiberRecovery(ctx: FiberRecoveryContext): Promise<boolean>;
405
+ private createChat;
406
+ private enqueueReply;
407
+ private answer;
408
+ private resolveTarget;
409
+ private definitionForThread;
410
+ private definitionForThreadId;
411
+ private hasUniqueProvider;
412
+ private shardThread;
413
+ private shardStateKey;
414
+ private reviveChatObject;
415
+ private toEvent;
694
416
  }
417
+ declare function normalizeMessengers(
418
+ messengers: ThinkMessengers
419
+ ): NormalizedMessengerDefinition[];
420
+ declare function defaultConversationName(event: MessengerEvent): string;
421
+ declare function idempotencyKeyForEvent(event: MessengerEvent): string;
422
+ declare function defaultChatSdkEvent(
423
+ definition: NormalizedMessengerDefinition,
424
+ input: ChatSdkMessengerEventInput
425
+ ): MessengerEvent;
426
+ declare function toMessengerThread(thread: Thread): MessengerThread;
427
+ declare function toMessengerMessage(message: Message): MessengerMessage;
428
+ declare function toMessengerAuthor(author: Author): MessengerAuthor;
429
+ declare function toMessengerAttachment(
430
+ attachment: Attachment
431
+ ): MessengerAttachment;
432
+ //#endregion
433
+ //#region src/think.d.ts
434
+ type ChatRecoveryRetryData = {
435
+ targetUserId?: string;
436
+ originalRequestId?: string;
437
+ incidentId?: string;
438
+ lastBody?: Record<string, unknown> | null;
439
+ lastClientTools?: ClientToolSchema[] | null;
440
+ recoveredRequestId?: string;
441
+ };
442
+ type ChatRecoveryContinueData = {
443
+ targetAssistantId?: string;
444
+ originalRequestId?: string;
445
+ incidentId?: string;
446
+ lastBody?: Record<string, unknown> | null;
447
+ lastClientTools?: ClientToolSchema[] | null;
448
+ recoveredRequestId?: string;
449
+ };
695
450
  /**
696
- * An opinionated chat agent base class.
451
+ * Callback interface for streaming chat events from a Think sub-agent.
697
452
  *
698
- * @experimental The API surface may change before stabilizing.
453
+ * Designed to work across the sub-agent RPC boundary — implement as
454
+ * an RpcTarget in the parent agent and pass to `chat()`.
699
455
  */
700
- declare class Think<
701
- Env extends Cloudflare.Env = Cloudflare.Env,
702
- State = unknown,
703
- Props extends Record<string, unknown> = Record<string, unknown>
704
- > extends Agent<Env, State, Props> {
705
- #private;
706
- private _activeChatRecoveryRootRequestId;
707
- private static readonly CONFIG_KEYS;
456
+ interface ChatStartEvent {
457
+ requestId: string;
458
+ }
459
+ interface StreamCallback {
460
+ onStart(event: ChatStartEvent): void | Promise<void>;
461
+ onEvent(json: string): void | Promise<void>;
462
+ onDone(): void | Promise<void>;
463
+ onError(error: string): void | Promise<void>;
708
464
  /**
709
- * Wait for MCP server connections to be ready before the inference
710
- * loop. MCP tools are auto-merged into the tool set.
465
+ * The current attempt was interrupted (a stream-stall watchdog abort routed
466
+ * into bounded recovery, #1626) and its final outcome will NOT arrive through
467
+ * this callback. One of two things is true:
468
+ * - a scheduled continuation — running in a LATER isolate invocation, without
469
+ * this callback — will produce the answer (delivered to other channels,
470
+ * e.g. WebSocket connections), OR
471
+ * - the recovery budget was exhausted, so the turn was already terminalized
472
+ * out-of-band (the configured `terminalMessage` + `onExhausted`) and is
473
+ * terminally over — there is NO continuation to come.
711
474
  *
712
- * Set to `true` for a default 10s timeout, or `{ timeout: ms }`
713
- * for a custom timeout. Defaults to `false` (no waiting).
714
- */
715
- waitForMcpConnections:
716
- | boolean
717
- | {
718
- timeout: number;
719
- };
720
- private _skillRegistry;
721
- private _loggedSkillWarnings;
722
- /**
723
- * Controls how overlapping user submit requests behave while another
724
- * chat turn is already active or queued.
475
+ * This is NOT `onDone` (this attempt did not complete) and NOT `onError` (the
476
+ * raw stall is not surfaced as a terminal error here); without it the contract
477
+ * `onStart → onEvent* → (onDone | onError)` is silently abandoned and a
478
+ * consumer that treats the clean resolve as success finalizes a truncated
479
+ * partial.
725
480
  *
726
- * @default "queue"
727
- */
728
- messageConcurrency: MessageConcurrency;
729
- /**
730
- * When true, chat turns are wrapped in `runFiber` for durable execution.
731
- * Enables `onChatRecovery` hook and `this.stash()` during streaming.
481
+ * Consumers should AVOID finalizing the partial on this signal — surface a
482
+ * "recovering…" / "interrupted, please retry" state, or re-attach via a
483
+ * durable channel — but must ALSO NOT block indefinitely waiting for a
484
+ * continuation: per the exhausted case above, one may never come. Optional →
485
+ * defaults to a no-op, so this is fully backward-compatible.
732
486
  *
733
- * Assign this as a class field or in the constructor — NOT in `onStart()`.
734
- * On every wake the SDK evaluates recovery budgets (and may seal an
735
- * interrupted turn, firing `onExhausted`) before `onStart()` runs, so a config
736
- * set in `onStart()` is applied too late and the built-in defaults are used
737
- * for the recovery that matters. See {@link ChatRecoveryConfig}.
487
+ * Note: a deploy/eviction interruption kills the isolate (and this callback)
488
+ * before this can fire — the caller observes a transport break instead. This
489
+ * fires only for an in-isolate interruption (the stall→recovery path).
738
490
  */
739
- chatRecovery: ChatRecoveryConfig;
740
- static readonly CHAT_FIBER_NAME = "__cf_internal_chat_turn";
741
- /**
742
- * The conversation session — messages, context, compaction, search.
743
- *
744
- * Direct message writes are observed and mirrored into Think's live cache.
745
- * Prefer the history helpers below when writing UI messages from subclasses;
746
- * they sanitize content and enforce row-size limits before delegating here.
747
- */
748
- session: Session;
749
- /** Cached messages — kept in sync with session storage. */
750
- private _cachedMessages;
751
- private _activeMessengerContext?;
752
- private _messengerRuntime?;
753
- /**
754
- * WorkerLoader binding for sandboxed extensions.
755
- * Set this to enable `getExtensions()` and dynamic extension loading.
756
- */
757
- extensionLoader?: WorkerLoader;
491
+ onInterrupted?(): void | Promise<void>;
492
+ }
493
+ /**
494
+ * Minimal interface for the result of the inference loop.
495
+ * The AI SDK's `streamText()` result satisfies this interface.
496
+ */
497
+ interface StreamableResult {
498
+ toUIMessageStream(options?: {
499
+ sendReasoning?: boolean;
500
+ }): AsyncIterable<unknown>;
501
+ output?: PromiseLike<unknown>;
502
+ }
503
+ /**
504
+ * Options for a chat turn (sub-agent RPC entry point).
505
+ */
506
+ interface ChatOptions {
507
+ signal?: AbortSignal;
508
+ }
509
+ type AgentToolChildRunStatus =
510
+ | "starting"
511
+ | "running"
512
+ | "completed"
513
+ | "error"
514
+ | "aborted";
515
+ type AgentToolRunInspection<Output = unknown> = {
516
+ runId: string;
517
+ status: AgentToolChildRunStatus;
518
+ requestId?: string;
519
+ streamId?: string;
520
+ output?: Output;
521
+ summary?: string;
522
+ error?: string;
523
+ startedAt: number;
524
+ completedAt?: number;
525
+ };
526
+ type Digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";
527
+ type Hour = `0${Digit}` | `1${Digit}` | "20" | "21" | "22" | "23";
528
+ type Minute = `${"0" | "1" | "2" | "3" | "4" | "5"}${Digit}`;
529
+ type ThinkTime = `${Hour}:${Minute}`;
530
+ type ThinkIntervalSchedule =
531
+ | `every ${number} minute${"" | "s"}`
532
+ | `every ${number} hour${"" | "s"}`;
533
+ type ThinkWallClockSchedule =
534
+ | `every day at ${ThinkTime}`
535
+ | `every weekday at ${ThinkTime}`
536
+ | `every week on ${string} at ${ThinkTime}`;
537
+ type ThinkScheduledTaskSchedule =
538
+ | ThinkIntervalSchedule
539
+ | ThinkWallClockSchedule
540
+ | `${ThinkWallClockSchedule} in ${string}`;
541
+ type ThinkScheduledTaskContext = {
542
+ taskId: string;
543
+ scheduledFor: number;
544
+ scheduledForDate: Date;
545
+ occurrenceKey: string;
546
+ idempotencyKey: string;
547
+ schedule: string;
548
+ scheduleKind: "interval" | "wall-clock";
549
+ timezone?: string;
550
+ metadata?: Record<string, unknown>;
551
+ };
552
+ type ThinkScheduledTaskPromptAction = {
553
+ prompt: string | (() => string | Promise<string>);
554
+ handler?: never;
555
+ };
556
+ type ThinkScheduledTaskHandlerAction = {
557
+ handler: (ctx: ThinkScheduledTaskContext) => void | Promise<void>;
558
+ prompt?: never;
559
+ };
560
+ type ThinkScheduledTaskBase = (
561
+ | ThinkScheduledTaskPromptAction
562
+ | ThinkScheduledTaskHandlerAction
563
+ ) & {
564
+ retry?: RetryOptions;
565
+ metadata?: Record<string, unknown>;
566
+ };
567
+ type ThinkScheduledTask =
568
+ | (ThinkScheduledTaskBase & {
569
+ schedule: ThinkIntervalSchedule;
570
+ timezone?: never;
571
+ })
572
+ | (ThinkScheduledTaskBase & {
573
+ schedule: ThinkWallClockSchedule;
574
+ timezone?: string;
575
+ })
576
+ | (ThinkScheduledTaskBase & {
577
+ schedule: `${ThinkWallClockSchedule} in ${string}`;
578
+ timezone?: string;
579
+ });
580
+ type ThinkScheduledTasks = Record<string, ThinkScheduledTask>;
581
+ declare function defineScheduledTasks<const T extends ThinkScheduledTasks>(
582
+ tasks: T
583
+ ): T;
584
+ type DeclaredScheduledTaskPayload = {
585
+ taskId: string;
586
+ scheduleHash: string;
587
+ scheduledFor: number;
588
+ };
589
+ type AgentToolStoredChunk = {
590
+ sequence: number;
591
+ body: string;
592
+ };
593
+ type ThinkSubmissionStatus =
594
+ | "pending"
595
+ | "running"
596
+ | "completed"
597
+ | "aborted"
598
+ | "skipped"
599
+ | "error";
600
+ type SubmitMessagesOptions = {
601
+ submissionId?: string;
602
+ idempotencyKey?: string;
603
+ metadata?: Record<string, unknown>;
604
+ };
605
+ type ThinkWorkflowPromptContext = {
606
+ workflow: {
607
+ name: string;
608
+ id: string;
609
+ stepName: string;
610
+ eventType: string;
611
+ };
612
+ output?: {
613
+ schema: unknown;
614
+ };
615
+ fingerprint?: string;
616
+ };
617
+ type ThinkSubmissionInspection = {
618
+ submissionId: string;
619
+ idempotencyKey?: string;
620
+ requestId?: string;
621
+ status: ThinkSubmissionStatus;
622
+ error?: string;
623
+ metadata?: Record<string, unknown>;
624
+ createdAt: number;
625
+ startedAt?: number;
626
+ completedAt?: number;
627
+ };
628
+ type SubmitMessagesResult = ThinkSubmissionInspection & {
629
+ accepted: boolean;
630
+ };
631
+ type ListSubmissionsOptions = {
632
+ status?: ThinkSubmissionStatus | ThinkSubmissionStatus[];
633
+ limit?: number;
634
+ };
635
+ type DeleteSubmissionsOptions = {
636
+ status?: ThinkSubmissionStatus | ThinkSubmissionStatus[];
637
+ completedBefore?: Date;
638
+ limit?: number;
639
+ };
640
+ /**
641
+ * A chat turn request. Built automatically by each entry path
642
+ * (WebSocket, chat(), saveMessages, auto-continuation) and passed
643
+ * to Think's inference loop.
644
+ */
645
+ interface TurnInput {
646
+ signal?: AbortSignal;
647
+ /** Client-provided tool schemas for dynamic tool registration. */
648
+ clientTools?: ClientToolSchema[];
649
+ /** Custom body fields from the client request. */
650
+ body?: Record<string, unknown>;
651
+ /** Internal workflow prompt configuration, never sourced from client body. */
652
+ workflowPrompt?: ThinkWorkflowPromptContext;
653
+ /** Whether this is a continuation turn (auto-continue after tool result, recovery). */
654
+ continuation: boolean;
655
+ }
656
+ /**
657
+ * Context passed to the `beforeTurn` hook.
658
+ * Contains everything Think assembled — the hook can inspect and override.
659
+ */
660
+ interface TurnContext {
661
+ /** Assembled system prompt (from context blocks or getSystemPrompt fallback). */
662
+ system: string;
663
+ /** Assembled model messages (truncated, pruned). */
664
+ messages: ModelMessage[];
665
+ /** Merged tool set (workspace + getTools + session + MCP + client + caller). */
666
+ tools: ToolSet;
667
+ /** The language model from getModel(). */
668
+ model: LanguageModel;
669
+ /** Whether this is a continuation turn. */
670
+ continuation: boolean;
671
+ /** Custom body fields from the client request. */
672
+ body?: Record<string, unknown>;
673
+ }
674
+ /**
675
+ * Configuration returned by the `beforeTurn` hook to override defaults.
676
+ * All fields are optional — return only what you want to change.
677
+ */
678
+ interface TurnConfig {
679
+ /** Override the model for this turn (e.g. cheap model for continuations). */
680
+ model?: LanguageModel;
681
+ /** Override the assembled system prompt. */
682
+ system?: string;
683
+ /** Override the assembled messages. */
684
+ messages?: ModelMessage[];
685
+ /** Extra tools to merge (additive — spread on top of existing tools). */
686
+ tools?: ToolSet;
687
+ /** Limit which tools the model can call (AI SDK activeTools). */
688
+ activeTools?: string[];
689
+ /** Force a specific tool call (AI SDK toolChoice). */
690
+ toolChoice?: Parameters<typeof streamText>[0]["toolChoice"];
691
+ /** Override maxSteps for this turn. */
692
+ maxSteps?: number;
758
693
  /**
759
- * Extension manager — created automatically when `extensionLoader` is set.
760
- * Use for dynamic `load()` / `unload()` at runtime.
694
+ * Additional AI SDK stop conditions for ending the turn early.
695
+ * Think always keeps its `maxSteps` stop condition as a safety bound.
761
696
  */
762
- extensionManager?: ExtensionManager;
697
+ stopWhen?: StopCondition<ToolSet> | Array<StopCondition<ToolSet>>;
763
698
  /**
764
- * Workspace filesystem available in `getTools()` and lifecycle hooks.
765
- * Defaults to a full `Workspace` backed by the DO's SQLite storage.
766
- *
767
- * Typed as `WorkspaceLike` rather than `Workspace` so subclasses can
768
- * replace it with anything that satisfies the interface — e.g. a proxy
769
- * that forwards to a shared workspace owned by a parent DO. Override as
770
- * a class field to skip the default init entirely:
771
- *
772
- * ```typescript
773
- * // Default init with R2 spillover for large files.
774
- * override workspace = new Workspace({
775
- * sql: this.ctx.storage.sql,
776
- * r2: this.env.R2,
777
- * name: () => this.name
778
- * });
779
- *
780
- * // Or a custom WorkspaceLike — e.g. a parent-owned shared workspace.
781
- * override workspace: WorkspaceLike = new SharedWorkspace(this);
782
- * ```
699
+ * Controls whether reasoning chunks are included in the UI message stream
700
+ * for this turn. Defaults to the instance-level `sendReasoning` setting.
783
701
  */
784
- workspace: WorkspaceLike;
702
+ sendReasoning?: boolean;
785
703
  /**
786
- * Include the default workspace Bash tool. Enabled by default so models can
787
- * run shell-style multi-file workflows against the workspace. Set to `false`
788
- * to omit it from the built-in workspace tools.
704
+ * Override the stream-stall inactivity watchdog timeout for THIS turn only
705
+ * (ms; `0` disables it for this turn). Defaults to the instance-level
706
+ * `chatStreamStallTimeoutMs`. Because the watchdog measures the gap between
707
+ * UI-message-stream chunks — which includes server-side tool execution — a
708
+ * turn known to invoke a slow tool can raise (or disable) the timeout for
709
+ * just that turn instead of permanently widening the global window. Auto-
710
+ * resets after the turn.
789
711
  */
790
- workspaceBash:
791
- | boolean
792
- | NonNullable<Parameters<typeof createWorkspaceTools>[1]>["bash"];
793
- constructor(ctx: DurableObjectState, env: Env);
712
+ chatStreamStallTimeoutMs?: number;
713
+ /** Maximum number of tokens to generate for this turn. */
714
+ maxOutputTokens?: Parameters<typeof streamText>[0]["maxOutputTokens"];
715
+ /** Temperature setting for this turn. */
716
+ temperature?: Parameters<typeof streamText>[0]["temperature"];
717
+ /** Nucleus sampling setting for this turn. */
718
+ topP?: Parameters<typeof streamText>[0]["topP"];
719
+ /** Top-K sampling setting for this turn. */
720
+ topK?: Parameters<typeof streamText>[0]["topK"];
721
+ /** Presence penalty setting for this turn. */
722
+ presencePenalty?: Parameters<typeof streamText>[0]["presencePenalty"];
723
+ /** Frequency penalty setting for this turn. */
724
+ frequencyPenalty?: Parameters<typeof streamText>[0]["frequencyPenalty"];
725
+ /** Stop sequences for this turn. */
726
+ stopSequences?: Parameters<typeof streamText>[0]["stopSequences"];
727
+ /** Seed for deterministic sampling when supported by the model. */
728
+ seed?: Parameters<typeof streamText>[0]["seed"];
729
+ /** Maximum number of retries for this turn. Set to 0 to disable retries. */
730
+ maxRetries?: Parameters<typeof streamText>[0]["maxRetries"];
731
+ /** Timeout configuration for this turn. */
732
+ timeout?: Parameters<typeof streamText>[0]["timeout"];
733
+ /** Additional HTTP headers for provider requests on this turn. */
734
+ headers?: Parameters<typeof streamText>[0]["headers"];
735
+ /** Provider-specific options (AI SDK providerOptions). */
736
+ providerOptions?: Record<string, unknown>;
737
+ /** Optional AI SDK telemetry configuration for this turn. */
738
+ experimental_telemetry?: Parameters<
739
+ typeof streamText
740
+ >[0]["experimental_telemetry"];
794
741
  /**
795
- * Conversation history as Think's live in-memory view.
796
- *
797
- * Storage remains the durable source of truth, but runtime logic should read
798
- * through this cache so in-flight turns, tool updates, and recovery state all
799
- * observe the same message list. Use `_syncMessages()` only at safe
800
- * boundaries where a full storage reread cannot drop in-flight state.
742
+ * Optional structured-output specification (AI SDK `output`).
743
+ * Forwarded to `streamText` so the model's final response is parsed
744
+ * against the supplied schema. Use the AI SDK's `Output.object({ schema })`
745
+ * / `Output.text()` helpers. Combine with `activeTools: []` on the
746
+ * terminal turn if your provider strips tools when structured output
747
+ * is active (e.g. workers-ai-provider).
801
748
  */
802
- get messages(): UIMessage[];
803
- /** Read the durable message path from session storage. */
804
- private _readMessagesFromStorage;
749
+ output?: Parameters<typeof streamText>[0]["output"];
750
+ }
751
+ /**
752
+ * Provider-agnostic semantic classification of a chat-turn error.
753
+ *
754
+ * Think ships **no** provider-specific string/code matching — the app owns
755
+ * that knowledge (it knows which provider/model it talks to), exactly like the
756
+ * `tokenCounter` it already passes to `compactAfter()`. An app teaches Think
757
+ * what an error *means* by overriding `classifyChatError()`; Think then reacts
758
+ * generically (e.g. compact-and-retry on `context_overflow`).
759
+ *
760
+ * - `context_overflow` — the prompt exceeded the model's context window
761
+ * (Anthropic `"prompt is too long"`, OpenAI `context_length_exceeded`, …).
762
+ * The only category Think currently acts on (auto-compact + retry).
763
+ * - `rate_limit` / `transient` — reserved for future backoff/retry policies.
764
+ * - `fatal` — unrecoverable; surface terminally.
765
+ * - `unknown` — default; Think applies its existing terminal behavior.
766
+ */
767
+ type ChatErrorClassification =
768
+ | "context_overflow"
769
+ | "rate_limit"
770
+ | "transient"
771
+ | "fatal"
772
+ | "unknown";
773
+ /**
774
+ * Opt-in handling for a turn that overflows the model's context window
775
+ * mid-flight. Compaction (`compactAfter()`) is only checked between turns, so a
776
+ * long, tool-heavy turn can grow past the window before the next check; the
777
+ * provider then rejects the request (`"prompt is too long"` /
778
+ * `context_length_exceeded`). Both layers reuse the session's compaction
779
+ * function and are provider-agnostic — the app maps the error via
780
+ * {@link Think.classifyChatError}; Think never matches provider strings itself.
781
+ *
782
+ * Set `Think.contextOverflow` to enable. Leaving it unset disables both layers
783
+ * (existing terminal behavior).
784
+ */
785
+ interface ContextOverflowConfig {
805
786
  /**
806
- * Normalize a tool part's `input` into something the provider will accept.
807
- *
808
- * Malformed shapes 400 modern providers and persist forever once written:
809
- * a stringified-JSON `input` (e.g. `'{"prompt":"a cat"}'` instead of the
810
- * object), and any non-object `input` — `null`, `undefined`, `""`, an array,
811
- * or a primitive — on a settled or interrupted tool call (Anthropic rejects
812
- * a `tool_use` block whose `input` is not an object). We parse the former and
813
- * default the latter to an empty object so the tool-call/tool-result pair
814
- * stays valid. Delegates to the shared `normalizeToolInput` so the read-side
815
- * repair and the write-side accumulator guard enforce the same invariant.
787
+ * Reactive backstop. When a turn fails with an error classified as
788
+ * `"context_overflow"`, discard the truncated partial, run
789
+ * `session.compact()`, and re-run the turn from the compacted history. The
790
+ * partial is intentionally not persisted: the turn restarts from scratch, so
791
+ * keeping the cut-off assistant message would orphan it beside the recovered
792
+ * answer (and duplicate any tool work the retry re-issues). If compaction
793
+ * cannot shorten history or the retry budget is spent, the overflow surfaces
794
+ * terminally through `onChatError` (classified) — it never loops or ends
795
+ * silently. Default `false`.
816
796
  */
817
- private _normalizeToolInput;
797
+ reactive?: boolean;
818
798
  /**
819
- * Whether a tool part already has a settled result the provider accepts, so
820
- * it must NOT be re-repaired into an errored result.
821
- *
822
- * Single source of truth for the terminal tool states, shared by the repair
823
- * pass and the backstop detector so they cannot drift. Mirror the AI SDK's
824
- * terminal states: `convertToModelMessages` emits a `tool-result` for
825
- * `output-available`, `output-error`, AND `output-denied` (a user-denied
826
- * approval — its denial reason becomes the tool-result). Omitting any of
827
- * these makes repair re-flip the part every turn — clobbering a real
828
- * `errorText`/denial with the generic "interrupted" message — and makes the
829
- * backstop falsely drop a valid call.
799
+ * Maximum compact-and-retry attempts for a single overflowing turn (the
800
+ * reactive backstop). Independent of the proactive guard's cap — see
801
+ * {@link proactive.maxCompactions}. Default `1`.
830
802
  */
831
- private _toolPartHasSettledResult;
803
+ maxRetries?: number;
832
804
  /**
833
- * Tool-call ids that still have no recorded result. After repair this should
834
- * be empty; a non-empty result means the backstop (`ignoreIncompleteToolCalls`)
835
- * will drop those calls — i.e. repair missed a shape and should be extended.
805
+ * Proactive guard. Before each step, read the previous step's model-reported
806
+ * `usage.inputTokens` and, if it crosses `maxInputTokens * (headroom ?? 0.9)`,
807
+ * compact in place and feed the recompacted history into the upcoming step —
808
+ * heading off the provider rejection before it happens. Keys off usage (every
809
+ * provider reports it), not provider error strings. Unset disables it.
836
810
  *
837
- * `approval-responded` is deliberately excluded: an approved server tool has
838
- * no result *yet*, but it is not incomplete or abandoned — it is waiting for
839
- * its continuation to run `execute()`. `convertToModelMessages` keeps that
840
- * call (and the SDK executes it), so flagging it here would log a misleading
841
- * "repair gap" warning and emit a spurious `chat:transcript:repaired` event
842
- * on every approval continuation.
811
+ * If a provider omits `inputTokens`, the guard falls back to `usage.totalTokens`
812
+ * (input + output) — a safe over-approximation that compacts slightly early
813
+ * rather than missing the threshold. If neither is reported, the guard does
814
+ * nothing that step (the reactive backstop still catches a genuine overflow).
815
+ *
816
+ * `maxCompactions` caps how many times the guard may compact within a single
817
+ * step loop (default `1`, floored at `1`). It is independent of
818
+ * {@link maxRetries} (the reactive budget): a no-op compaction would repeat on
819
+ * every step, so the cap stops the guard from compacting (and emitting
820
+ * `chat:context:compacted`) on each one.
843
821
  */
844
- private _incompleteToolCallIds;
822
+ proactive?: {
823
+ maxInputTokens: number;
824
+ headroom?: number;
825
+ maxCompactions?: number;
826
+ };
827
+ }
828
+ /**
829
+ * Opt-in default classifier for {@link Think.classifyChatError}. Matches the
830
+ * context-window-overflow error messages of the common providers (Anthropic,
831
+ * OpenAI, Google, Bedrock, Mistral, …) and returns `"context_overflow"`.
832
+ *
833
+ * Think ships this as an explicitly-imported helper rather than wiring it into
834
+ * core, so the framework default stays free of provider strings. Assign it (or
835
+ * delegate to it) when you do not need custom classification:
836
+ *
837
+ * @example
838
+ * ```typescript
839
+ * import { Think, defaultContextOverflowClassifier } from "@cloudflare/think";
840
+ *
841
+ * export class MyAgent extends Think<Env> {
842
+ * override contextOverflow = { reactive: true };
843
+ * override classifyChatError = defaultContextOverflowClassifier;
844
+ * }
845
+ * ```
846
+ *
847
+ * Or combine with your own checks:
848
+ *
849
+ * @example
850
+ * ```typescript
851
+ * override classifyChatError(error: unknown): ChatErrorClassification | void {
852
+ * if (isMyRateLimit(error)) return "rate_limit";
853
+ * return defaultContextOverflowClassifier(error);
854
+ * }
855
+ * ```
856
+ */
857
+ declare function defaultContextOverflowClassifier(
858
+ error: unknown
859
+ ): ChatErrorClassification | undefined;
860
+ interface ChatErrorContext {
861
+ requestId?: string;
862
+ stage: "parse" | "persist" | "turn" | "stream" | "recovery" | "transcript";
863
+ messagesPersisted?: boolean;
845
864
  /**
846
- * Repair a single interrupted tool call — a tool part with no settled result,
847
- * left behind when a stream was cut off mid-flight. Returns the replacement
848
- * part that takes its place in the transcript. `input` has already been
849
- * normalized to a valid object.
850
- *
851
- * The default flips it to an errored tool result so the record survives (no
852
- * "disappearing" tool call) and `convertToModelMessages` still gets a
853
- * tool-result for it (avoiding `AI_MissingToolResultsError`).
854
- *
855
- * Override to customize the repaired shape for client-resolved tools — e.g.
856
- * convert an interrupted `ask_user` (a question with no server `execute`,
857
- * normally answered by the user's next message) into a plain text part
858
- * carrying the question prose, so the model sees it as ordinary conversation
859
- * rather than a tool error and compaction keeps the question verbatim. This
860
- * runs DURING transcript repair — before the repaired transcript is persisted
861
- * and sent to the model — so the conversion shapes the current turn, not just
862
- * the next one. A returned tool part MUST carry a settled result
863
- * (`output-available` / `output-error` / `output-denied` or an
864
- * `output`/`result` field); returning a non-tool part (e.g. text) is fine.
865
+ * App-provided semantic classification (from `classifyChatError`), when
866
+ * known. Lets `onChatError` overrides and observers distinguish e.g. a
867
+ * context-overflow from a generic provider failure without re-matching
868
+ * provider strings.
865
869
  */
866
- protected repairInterruptedToolPart(
867
- part: UIMessage["parts"][number]
868
- ): UIMessage["parts"][number];
869
- private _repairToolTranscriptParts;
870
- private _repairTranscriptForProvider;
871
- /** Replace the live cache with a durable storage snapshot. */
872
- private _replaceCachedMessages;
873
- /** Refresh the live cache from durable storage at a safe boundary. */
874
- private _syncMessages;
875
- /** Patch or append one message in the live cache after a durable write. */
876
- private _upsertCachedMessage;
877
- /** Patch a message that is already present in the live cache. */
878
- private _patchCachedMessage;
879
- private _appendMessageToHistory;
880
- private _updateMessageInHistory;
881
- private _upsertMessageInHistory;
882
- private _clearHistory;
883
- /** Append a message while keeping Think's live message cache coherent. */
884
- protected appendMessageToHistory(
885
- message: UIMessage,
886
- parentId?: string | null
887
- ): Promise<UIMessage>;
888
- /** Update a message while keeping Think's live message cache coherent. */
889
- protected updateMessageInHistory(message: UIMessage): Promise<UIMessage>;
890
- /** Refresh Think's live message cache from the durable session path. */
891
- protected syncMessagesFromStorage(): Promise<UIMessage[]>;
892
- private _aborts;
893
- private _turnQueue;
894
- protected _resumableStream: ResumableStream;
895
- private _pendingResumeConnections;
896
- private _lastClientTools;
897
- private _lastBody;
898
- private _continuation;
899
- private _continuationTimer;
900
- private _continuationBarrierActive;
901
- private _insideResponseHook;
902
- private _insideInferenceLoop;
903
- private _pendingInteractionPromise;
904
- private _interactionApplyTail;
905
- private _streamingAssistant;
906
- private _submitConcurrency;
907
- private static MESSAGE_DEBOUNCE_MS;
908
- private _agentToolForwarders;
909
- private _agentToolClosers;
910
- private _agentToolAbortControllers;
911
- private _agentToolLastErrors;
912
- private _agentToolPreTurnAssistantIds;
913
- private _agentToolLiveSequences;
914
- private _submissionTableEnsured;
915
- private _workflowNotificationTableEnsured;
916
- private _declaredScheduledTasksTableEnsured;
917
- private _drainingSubmissions;
918
- private _drainingWorkflowNotifications;
919
- private _submissionAbortControllers;
920
- private _programmaticStreamErrors;
921
- protected static submissionRecoveryStaleMs: number;
922
- broadcast(
923
- msg: string | ArrayBuffer | ArrayBufferView,
924
- without?: string[]
925
- ): void;
926
- alarm(): Promise<void>;
870
+ classification?: ChatErrorClassification;
871
+ }
872
+ /**
873
+ * Context passed to the `beforeStep` hook before each AI SDK step in
874
+ * the agentic loop. Backed by the AI SDK's `PrepareStepFunction<TOOLS>`
875
+ * parameter — exposes the previous `steps`, the zero-based `stepNumber`,
876
+ * the currently selected `model`, the `messages` about to be sent, and
877
+ * `experimental_context`.
878
+ *
879
+ * Pass an explicit `TOOLS` generic for typed previous tool calls / results.
880
+ *
881
+ * Limitations (AI SDK boundary, not Think):
882
+ * - No `abortSignal` is exposed in the context. If you do remote work
883
+ * inside `beforeStep`, it cannot be cancelled by turn-level abort.
884
+ * - `experimental_context` is typed `unknown`; users must narrow it.
885
+ * - `output` cannot be overridden per-step — set it at the turn level
886
+ * via `TurnConfig.output` (returned from `beforeTurn`).
887
+ */
888
+ type PrepareStepContext<TOOLS extends ToolSet = ToolSet> = Parameters<
889
+ PrepareStepFunction<TOOLS>
890
+ >[0];
891
+ /**
892
+ * Configuration returned by `beforeStep` to override defaults for the
893
+ * current AI SDK step. This is the AI SDK's `PrepareStepResult<TOOLS>` —
894
+ * return only the fields you want to override (`model`, `toolChoice`,
895
+ * `activeTools`, `system`, `messages`, `experimental_context`,
896
+ * `providerOptions`).
897
+ */
898
+ type StepConfig<TOOLS extends ToolSet = ToolSet> = PrepareStepResult<TOOLS>;
899
+ /**
900
+ * Context passed to the `beforeToolCall` hook **before** the tool's
901
+ * `execute` function runs.
902
+ *
903
+ * Backed by the AI SDK's `OnToolCallStartEvent` (the parameter of
904
+ * `experimental_onToolCallStart`). The full `TypedToolCall<TOOLS>`
905
+ * fields (`toolName`, `toolCallId`, `input`, `providerMetadata`, the
906
+ * dynamic/invalid/error discriminators) are spread at the top level for
907
+ * convenience, with the per-call event extras attached:
908
+ *
909
+ * - `stepNumber` — index of the current step
910
+ * - `messages` — conversation messages visible at tool execution time
911
+ * - `abortSignal` — signal that aborts if the turn is cancelled
912
+ *
913
+ * Pass an explicit `TOOLS` generic for full input typing:
914
+ *
915
+ * ```ts
916
+ * import type { ToolCallContext } from "@cloudflare/think";
917
+ * import type { tools } from "./my-tools";
918
+ *
919
+ * beforeToolCall(ctx: ToolCallContext<typeof tools>) {
920
+ * if (ctx.toolName === "search") {
921
+ * ctx.input.query; // typed
922
+ * }
923
+ * }
924
+ * ```
925
+ */
926
+ type ToolCallContext<TOOLS extends ToolSet = ToolSet> = TypedToolCall<TOOLS> & {
927
+ /** Zero-based index of the current step where this tool call occurs. */ readonly stepNumber:
928
+ | number
929
+ | undefined /** The conversation messages available at tool execution time. */;
930
+ readonly messages: ReadonlyArray<ModelMessage> /** Signal for cancelling the operation. */;
931
+ readonly abortSignal: AbortSignal | undefined;
932
+ };
933
+ /**
934
+ * Decision returned by `beforeToolCall` to control tool execution.
935
+ * Return void/undefined to allow execution with original input.
936
+ *
937
+ * Discriminated union — each action has a clear, non-overlapping meaning:
938
+ * - `allow` — execute the tool (optionally with modified input)
939
+ * - `block` — don't execute; return `reason` as the tool result so the model can adjust
940
+ * - `substitute` — don't execute; return `output` as the tool result (afterToolCall still fires)
941
+ */
942
+ type ToolCallDecision =
943
+ | {
944
+ action: "allow" /** Modified input — tool executes with this instead of the original. */;
945
+ input?: Record<string, unknown>;
946
+ }
947
+ | {
948
+ action: "block" /** Returned as the tool result so the model can adjust. */;
949
+ reason?: string;
950
+ }
951
+ | {
952
+ action: "substitute" /** The substitute tool output — model sees this instead of real execution. */;
953
+ output: unknown /** Optional input attribution for the afterToolCall log. */;
954
+ input?: Record<string, unknown>;
955
+ };
956
+ /**
957
+ * Context passed to the `afterToolCall` hook after a tool executes.
958
+ *
959
+ * Backed by the AI SDK's `OnToolCallFinishEvent` (the parameter of
960
+ * `experimental_onToolCallFinish`). The full `TypedToolCall<TOOLS>`
961
+ * fields (`toolName`, `toolCallId`, `input`, …) are spread at the top
962
+ * level, plus the per-call event extras:
963
+ *
964
+ * - `stepNumber` — index of the current step
965
+ * - `messages` — conversation messages visible at tool execution time
966
+ * - `durationMs` — wall-clock execution time in milliseconds
967
+ * - `success`/`output`/`error` — discriminated outcome:
968
+ * - on success: `success: true`, `output: unknown`
969
+ * - on failure: `success: false`, `error: unknown`
970
+ *
971
+ * Pass an explicit `TOOLS` generic for full input typing:
972
+ *
973
+ * ```ts
974
+ * import type { ToolCallResultContext } from "@cloudflare/think";
975
+ * import type { tools } from "./my-tools";
976
+ *
977
+ * afterToolCall(ctx: ToolCallResultContext<typeof tools>) {
978
+ * if (ctx.success) {
979
+ * console.log(`${ctx.toolName} took ${ctx.durationMs}ms`, ctx.output);
980
+ * } else {
981
+ * console.error(`${ctx.toolName} failed:`, ctx.error);
982
+ * }
983
+ * }
984
+ * ```
985
+ */
986
+ type ToolCallResultContext<TOOLS extends ToolSet = ToolSet> =
987
+ TypedToolCall<TOOLS> & {
988
+ readonly stepNumber: number | undefined;
989
+ readonly messages: ReadonlyArray<ModelMessage> /** Wall-clock execution time in milliseconds. */;
990
+ readonly durationMs: number;
991
+ } & (
992
+ | {
993
+ readonly success: true;
994
+ readonly output: unknown;
995
+ readonly error?: never;
996
+ }
997
+ | {
998
+ readonly success: false;
999
+ readonly output?: never;
1000
+ readonly error: unknown;
1001
+ }
1002
+ );
1003
+ /**
1004
+ * Context passed to the `onStepFinish` hook after each step completes.
1005
+ *
1006
+ * This is the AI SDK's `StepResult<TOOLS>` (= `OnStepFinishEvent<TOOLS>`) —
1007
+ * the full step record including `text`, `reasoning`, `toolCalls`,
1008
+ * `toolResults`, `files`, `sources`, `usage` (with `cachedInputTokens`,
1009
+ * `reasoningTokens`, `totalTokens`), `finishReason`, `warnings`, `request`,
1010
+ * `response`, and `providerMetadata` (where provider-specific cache
1011
+ * accounting like `cacheCreationInputTokens` lives).
1012
+ *
1013
+ * Pass an explicit `TOOLS` generic for typed `toolCalls`/`toolResults`.
1014
+ */
1015
+ type StepContext<TOOLS extends ToolSet = ToolSet> = Parameters<
1016
+ StreamTextOnStepFinishCallback<TOOLS>
1017
+ >[0];
1018
+ /**
1019
+ * Context passed to the `onChunk` hook for each streaming chunk.
1020
+ *
1021
+ * This is the AI SDK's `StreamTextOnChunkCallback` event — `{ chunk }`
1022
+ * where `chunk` is a discriminated union of `TextStreamPart` variants
1023
+ * (text-delta, reasoning-delta, source, tool-call, tool-input-start,
1024
+ * tool-input-delta, tool-result, raw).
1025
+ */
1026
+ type ChunkContext<TOOLS extends ToolSet = ToolSet> = Parameters<
1027
+ StreamTextOnChunkCallback<TOOLS>
1028
+ >[0];
1029
+ /**
1030
+ * @internal Re-export of the chunk variant union for consumers that need
1031
+ * to narrow on `chunk.type` without importing `TextStreamPart` directly.
1032
+ */
1033
+ type ChunkPart<TOOLS extends ToolSet = ToolSet> = ChunkContext<TOOLS>["chunk"];
1034
+ /**
1035
+ * Configuration for a sandboxed extension, returned by getExtensions().
1036
+ */
1037
+ interface ExtensionConfig {
1038
+ /** Extension manifest (name, version, permissions, contributions). */
1039
+ manifest: ExtensionManifest;
1040
+ /** JavaScript source code defining the extension's tools. */
1041
+ source: string;
1042
+ }
1043
+ /**
1044
+ * An opinionated chat agent base class.
1045
+ *
1046
+ * @experimental The API surface may change before stabilizing.
1047
+ */
1048
+ declare class Think<
1049
+ Env extends Cloudflare.Env = Cloudflare.Env,
1050
+ State = unknown,
1051
+ Props extends Record<string, unknown> = Record<string, unknown>
1052
+ > extends Agent<Env, State, Props> {
1053
+ #private;
1054
+ private _activeChatRecoveryRootRequestId;
1055
+ private static readonly CONFIG_KEYS;
927
1056
  /**
928
- * Persist an arbitrary JSON-serializable configuration object for this
929
- * agent instance. Stored in the Think-private `think_config` table —
930
- * survives
931
- * restarts and hibernation. Pass the config shape as a method generic
932
- * for typed call sites:
933
- *
934
- * ```ts
935
- * this.configure<MyConfig>({ modelTier: "fast" });
936
- * ```
1057
+ * Wait for MCP server connections to be ready before the inference
1058
+ * loop. MCP tools are auto-merged into the tool set.
937
1059
  *
938
- * Prefer `state` / `setState` from `Agent` when you want the value
939
- * broadcast to connected clients. Use `configure` for private
940
- * per-instance config that should stay server-side.
1060
+ * Set to `true` for a default 10s timeout, or `{ timeout: ms }`
1061
+ * for a custom timeout. Defaults to `false` (no waiting).
941
1062
  */
942
- configure<T = Record<string, unknown>>(config: T): void;
1063
+ waitForMcpConnections:
1064
+ | boolean
1065
+ | {
1066
+ timeout: number;
1067
+ };
1068
+ private _skillRegistry;
1069
+ private _loggedSkillWarnings;
943
1070
  /**
944
- * Read the persisted configuration, or null if never configured.
945
- * Pass the config shape as a method generic for a typed result:
1071
+ * Controls how overlapping user submit requests behave while another
1072
+ * chat turn is already active or queued.
946
1073
  *
947
- * ```ts
948
- * const cfg = this.getConfig<MyConfig>();
949
- * ```
1074
+ * @default "queue"
950
1075
  */
951
- getConfig<T = Record<string, unknown>>(): T | null;
952
- protected _migrateLegacyConfigToThinkTable(): void;
953
- private _ensureConfigTable;
954
- private _configSet;
955
- private _configGet;
956
- private _configDelete;
1076
+ messageConcurrency: MessageConcurrency;
957
1077
  /**
958
- * Return the language model to use for inference.
959
- * Must be overridden by subclasses.
1078
+ * When true, chat turns are wrapped in `runFiber` for durable execution.
1079
+ * Enables `onChatRecovery` hook and `this.stash()` during streaming.
1080
+ *
1081
+ * Assign this as a class field or in the constructor — NOT in `onStart()`.
1082
+ * On every wake the SDK evaluates recovery budgets (and may seal an
1083
+ * interrupted turn, firing `onExhausted`) before `onStart()` runs, so a config
1084
+ * set in `onStart()` is applied too late and the built-in defaults are used
1085
+ * for the recovery that matters. See {@link ChatRecoveryConfig}.
960
1086
  */
961
- getModel(): LanguageModel;
1087
+ chatRecovery: ChatRecoveryConfig;
1088
+ static readonly CHAT_FIBER_NAME = "__cf_internal_chat_turn";
962
1089
  /**
963
- * Return the system prompt for the assistant.
964
- * Used as fallback when no context blocks are configured via `configureSession`.
965
- */
966
- getSystemPrompt(): string;
967
- /** Return the tools available to the assistant. */
1090
+ * The conversation session — messages, context, compaction, search.
1091
+ *
1092
+ * Direct message writes are observed and mirrored into Think's live cache.
1093
+ * Prefer the history helpers below when writing UI messages from subclasses;
1094
+ * they sanitize content and enforce row-size limits before delegating here.
1095
+ */
1096
+ session: Session;
1097
+ /** Cached messages — kept in sync with session storage. */
1098
+ private _cachedMessages;
1099
+ private _activeMessengerContext?;
1100
+ private _messengerRuntime?;
1101
+ /**
1102
+ * WorkerLoader binding for sandboxed extensions.
1103
+ * Set this to enable `getExtensions()` and dynamic extension loading.
1104
+ */
1105
+ extensionLoader?: WorkerLoader;
1106
+ /**
1107
+ * Extension manager — created automatically when `extensionLoader` is set.
1108
+ * Use for dynamic `load()` / `unload()` at runtime.
1109
+ */
1110
+ extensionManager?: ExtensionManager;
1111
+ /**
1112
+ * Workspace filesystem available in `getTools()` and lifecycle hooks.
1113
+ * Defaults to a full `Workspace` backed by the DO's SQLite storage.
1114
+ *
1115
+ * Typed as `WorkspaceLike` rather than `Workspace` so subclasses can
1116
+ * replace it with anything that satisfies the interface — e.g. a proxy
1117
+ * that forwards to a shared workspace owned by a parent DO. Override as
1118
+ * a class field to skip the default init entirely:
1119
+ *
1120
+ * ```typescript
1121
+ * // Default init with R2 spillover for large files.
1122
+ * override workspace = new Workspace({
1123
+ * sql: this.ctx.storage.sql,
1124
+ * r2: this.env.R2,
1125
+ * name: () => this.name
1126
+ * });
1127
+ *
1128
+ * // Or a custom WorkspaceLike — e.g. a parent-owned shared workspace.
1129
+ * override workspace: WorkspaceLike = new SharedWorkspace(this);
1130
+ * ```
1131
+ */
1132
+ workspace: WorkspaceLike;
1133
+ /**
1134
+ * Include the default workspace Bash tool. Enabled by default so models can
1135
+ * run shell-style multi-file workflows against the workspace. Set to `false`
1136
+ * to omit it from the built-in workspace tools.
1137
+ */
1138
+ workspaceBash:
1139
+ | boolean
1140
+ | NonNullable<Parameters<typeof createWorkspaceTools>[1]>["bash"];
1141
+ constructor(ctx: DurableObjectState, env: Env);
1142
+ /**
1143
+ * Conversation history as Think's live in-memory view.
1144
+ *
1145
+ * Storage remains the durable source of truth, but runtime logic should read
1146
+ * through this cache so in-flight turns, tool updates, and recovery state all
1147
+ * observe the same message list. Use `_syncMessages()` only at safe
1148
+ * boundaries where a full storage reread cannot drop in-flight state.
1149
+ */
1150
+ get messages(): UIMessage[];
1151
+ /** Read the durable message path from session storage. */
1152
+ private _readMessagesFromStorage;
1153
+ /**
1154
+ * Normalize a tool part's `input` into something the provider will accept.
1155
+ *
1156
+ * Malformed shapes 400 modern providers and persist forever once written:
1157
+ * a stringified-JSON `input` (e.g. `'{"prompt":"a cat"}'` instead of the
1158
+ * object), and any non-object `input` — `null`, `undefined`, `""`, an array,
1159
+ * or a primitive — on a settled or interrupted tool call (Anthropic rejects
1160
+ * a `tool_use` block whose `input` is not an object). We parse the former and
1161
+ * default the latter to an empty object so the tool-call/tool-result pair
1162
+ * stays valid. Delegates to the shared `normalizeToolInput` so the read-side
1163
+ * repair and the write-side accumulator guard enforce the same invariant.
1164
+ */
1165
+ private _normalizeToolInput;
1166
+ /**
1167
+ * Whether a tool part already has a settled result the provider accepts, so
1168
+ * it must NOT be re-repaired into an errored result.
1169
+ *
1170
+ * Single source of truth for the terminal tool states, shared by the repair
1171
+ * pass and the backstop detector so they cannot drift. Mirror the AI SDK's
1172
+ * terminal states: `convertToModelMessages` emits a `tool-result` for
1173
+ * `output-available`, `output-error`, AND `output-denied` (a user-denied
1174
+ * approval — its denial reason becomes the tool-result). Omitting any of
1175
+ * these makes repair re-flip the part every turn — clobbering a real
1176
+ * `errorText`/denial with the generic "interrupted" message — and makes the
1177
+ * backstop falsely drop a valid call.
1178
+ */
1179
+ private _toolPartHasSettledResult;
1180
+ /**
1181
+ * Tool-call ids that still have no recorded result. After repair this should
1182
+ * be empty; a non-empty result means the backstop (`ignoreIncompleteToolCalls`)
1183
+ * will drop those calls — i.e. repair missed a shape and should be extended.
1184
+ *
1185
+ * `approval-responded` is deliberately excluded: an approved server tool has
1186
+ * no result *yet*, but it is not incomplete or abandoned — it is waiting for
1187
+ * its continuation to run `execute()`. `convertToModelMessages` keeps that
1188
+ * call (and the SDK executes it), so flagging it here would log a misleading
1189
+ * "repair gap" warning and emit a spurious `chat:transcript:repaired` event
1190
+ * on every approval continuation.
1191
+ */
1192
+ private _incompleteToolCallIds;
1193
+ /**
1194
+ * Repair a single interrupted tool call — a tool part with no settled result,
1195
+ * left behind when a stream was cut off mid-flight. Returns the replacement
1196
+ * part that takes its place in the transcript. `input` has already been
1197
+ * normalized to a valid object.
1198
+ *
1199
+ * The default flips it to an errored tool result so the record survives (no
1200
+ * "disappearing" tool call) and `convertToModelMessages` still gets a
1201
+ * tool-result for it (avoiding `AI_MissingToolResultsError`).
1202
+ *
1203
+ * Override to customize the repaired shape for client-resolved tools — e.g.
1204
+ * convert an interrupted `ask_user` (a question with no server `execute`,
1205
+ * normally answered by the user's next message) into a plain text part
1206
+ * carrying the question prose, so the model sees it as ordinary conversation
1207
+ * rather than a tool error and compaction keeps the question verbatim. This
1208
+ * runs DURING transcript repair — before the repaired transcript is persisted
1209
+ * and sent to the model — so the conversion shapes the current turn, not just
1210
+ * the next one. A returned tool part MUST carry a settled result
1211
+ * (`output-available` / `output-error` / `output-denied` or an
1212
+ * `output`/`result` field); returning a non-tool part (e.g. text) is fine.
1213
+ */
1214
+ protected repairInterruptedToolPart(
1215
+ part: UIMessage["parts"][number]
1216
+ ): UIMessage["parts"][number];
1217
+ private _repairToolTranscriptParts;
1218
+ private _repairTranscriptForProvider;
1219
+ /** Replace the live cache with a durable storage snapshot. */
1220
+ private _replaceCachedMessages;
1221
+ /** Refresh the live cache from durable storage at a safe boundary. */
1222
+ private _syncMessages;
1223
+ /** Patch or append one message in the live cache after a durable write. */
1224
+ private _upsertCachedMessage;
1225
+ /** Patch a message that is already present in the live cache. */
1226
+ private _patchCachedMessage;
1227
+ private _appendMessageToHistory;
1228
+ private _updateMessageInHistory;
1229
+ private _upsertMessageInHistory;
1230
+ private _clearHistory;
1231
+ /** Append a message while keeping Think's live message cache coherent. */
1232
+ protected appendMessageToHistory(
1233
+ message: UIMessage,
1234
+ parentId?: string | null
1235
+ ): Promise<UIMessage>;
1236
+ /** Update a message while keeping Think's live message cache coherent. */
1237
+ protected updateMessageInHistory(message: UIMessage): Promise<UIMessage>;
1238
+ /** Refresh Think's live message cache from the durable session path. */
1239
+ protected syncMessagesFromStorage(): Promise<UIMessage[]>;
1240
+ private _aborts;
1241
+ private _turnQueue;
1242
+ protected _resumableStream: ResumableStream;
1243
+ private _pendingResumeConnections;
1244
+ private _lastClientTools;
1245
+ private _lastBody;
1246
+ private _continuation;
1247
+ private _continuationTimer;
1248
+ private _continuationBarrierActive;
1249
+ private _insideResponseHook;
1250
+ private _insideInferenceLoop;
1251
+ private _pendingInteractionPromise;
1252
+ private _interactionApplyTail;
1253
+ private _streamingAssistant;
1254
+ private _submitConcurrency;
1255
+ private static MESSAGE_DEBOUNCE_MS;
1256
+ private _agentToolForwarders;
1257
+ private _agentToolClosers;
1258
+ private _agentToolAbortControllers;
1259
+ private _agentToolLastErrors;
1260
+ private _agentToolPreTurnAssistantIds;
1261
+ private _agentToolLiveSequences;
1262
+ private _submissionTableEnsured;
1263
+ private _workflowNotificationTableEnsured;
1264
+ private _declaredScheduledTasksTableEnsured;
1265
+ private _drainingSubmissions;
1266
+ private _drainingWorkflowNotifications;
1267
+ private _submissionAbortControllers;
1268
+ private _programmaticStreamErrors;
1269
+ protected static submissionRecoveryStaleMs: number;
1270
+ broadcast(
1271
+ msg: string | ArrayBuffer | ArrayBufferView,
1272
+ without?: string[]
1273
+ ): void;
1274
+ alarm(): Promise<void>;
1275
+ /**
1276
+ * Persist an arbitrary JSON-serializable configuration object for this
1277
+ * agent instance. Stored in the Think-private `think_config` table —
1278
+ * survives
1279
+ * restarts and hibernation. Pass the config shape as a method generic
1280
+ * for typed call sites:
1281
+ *
1282
+ * ```ts
1283
+ * this.configure<MyConfig>({ modelTier: "fast" });
1284
+ * ```
1285
+ *
1286
+ * Prefer `state` / `setState` from `Agent` when you want the value
1287
+ * broadcast to connected clients. Use `configure` for private
1288
+ * per-instance config that should stay server-side.
1289
+ */
1290
+ configure<T = Record<string, unknown>>(config: T): void;
1291
+ /**
1292
+ * Read the persisted configuration, or null if never configured.
1293
+ * Pass the config shape as a method generic for a typed result:
1294
+ *
1295
+ * ```ts
1296
+ * const cfg = this.getConfig<MyConfig>();
1297
+ * ```
1298
+ */
1299
+ getConfig<T = Record<string, unknown>>(): T | null;
1300
+ protected _migrateLegacyConfigToThinkTable(): void;
1301
+ private _ensureConfigTable;
1302
+ private _configSet;
1303
+ private _configGet;
1304
+ private _configDelete;
1305
+ /**
1306
+ * Return the language model to use for inference.
1307
+ * Must be overridden by subclasses.
1308
+ */
1309
+ getModel(): LanguageModel;
1310
+ /**
1311
+ * Return the system prompt for the assistant.
1312
+ * Used as fallback when no context blocks are configured via `configureSession`.
1313
+ */
1314
+ getSystemPrompt(): string;
1315
+ /** Return the tools available to the assistant. */
968
1316
  getTools(): ToolSet;
969
1317
  /** Return messenger integrations that should be routed through this Think agent. */
970
1318
  getMessengers(): ThinkMessengers;
@@ -2259,466 +2607,118 @@ declare class Think<
2259
2607
  private _broadcastMessages;
2260
2608
  }
2261
2609
  //#endregion
2262
- //#region src/messengers/events.d.ts
2263
- type MessengerEventKind =
2264
- | "direct-message"
2265
- | "mention"
2266
- | "subscribed-message"
2267
- | "action"
2268
- | "delivery-event";
2269
- interface MessengerAuthor {
2270
- fullName?: string;
2271
- isBot?: boolean | "unknown";
2272
- isMe?: boolean;
2273
- userId: string;
2274
- userName?: string;
2275
- }
2276
- interface MessengerAttachment {
2277
- data?: ArrayBuffer;
2278
- fetch?: () => Promise<ArrayBuffer>;
2279
- id?: string;
2280
- mediaType?: string;
2281
- name?: string;
2282
- raw?: unknown;
2283
- size?: number;
2284
- text?: string;
2285
- url?: string;
2286
- }
2287
- interface MessengerThread {
2288
- channelId?: string;
2289
- channelName?: string;
2290
- id: string;
2291
- isDirectMessage: boolean;
2292
- providerThreadId: string;
2293
- title?: string;
2294
- }
2295
- interface MessengerMessage {
2296
- attachments: MessengerAttachment[];
2297
- author: MessengerAuthor;
2298
- createdAt?: Date;
2299
- id: string;
2300
- isMention?: boolean;
2301
- providerMessageId: string;
2302
- raw?: unknown;
2303
- text: string;
2304
- }
2305
- interface MessengerAction {
2306
- actionId: string;
2307
- messageId?: string;
2308
- raw?: unknown;
2309
- user?: MessengerAuthor;
2310
- value?: string;
2311
- }
2312
- interface MessengerCapabilities {
2313
- canEditMessages?: boolean;
2314
- canStream?: boolean;
2315
- maxMessageLength?: number;
2316
- supportsActions?: boolean;
2317
- supportsAttachments?: boolean;
2318
- supportsEphemeral?: boolean;
2319
- }
2320
- interface MessengerContext {
2321
- action?: MessengerAction;
2322
- author?: MessengerAuthor;
2323
- capabilities: MessengerCapabilities;
2324
- kind: MessengerEventKind;
2325
- message?: MessengerMessage;
2326
- messengerId: string;
2327
- provider: string;
2328
- thread: MessengerThread;
2329
- }
2330
- interface MessengerEvent extends MessengerContext {
2331
- raw?: unknown;
2332
- }
2333
- declare function messengerContextFromEvent(
2334
- event: MessengerEvent
2335
- ): MessengerContext;
2336
- declare function serializableMessengerEvent(
2337
- event: MessengerEvent
2338
- ): MessengerEvent;
2339
- declare function toMessengerUserMessage(event: MessengerEvent): UIMessage;
2340
- //#endregion
2341
- //#region src/messengers/delivery.d.ts
2342
- declare const MESSENGER_REPLY_FIBER_NAME = "think:messenger-reply";
2343
- declare const EMPTY_MESSENGER_RESPONSE =
2344
- "I couldn't produce a text response. Please try again.";
2345
- declare const ERROR_MESSENGER_RESPONSE =
2346
- "Sorry, I couldn't answer that right now. Please try again.";
2347
- declare const INTERRUPTED_MESSENGER_RESPONSE =
2348
- "Sorry, my reply was interrupted. Please send your message again if you'd like me to retry.";
2349
- interface TextStreamCallbackOptions {
2350
- onVisibleStart?: () => Promise<void> | void;
2351
- visibleSoftLimit?: number;
2352
- }
2353
- declare class TextStreamCallback extends RpcTarget implements StreamCallback {
2354
- private readonly onVisibleStart?;
2355
- private readonly visibleChunks;
2356
- private readonly wakeups;
2357
- private readonly visibleSoftLimit?;
2358
- private chatRequestId?;
2359
- private closed;
2360
- private interrupted;
2361
- private error?;
2362
- private text;
2363
- private visibleClosed;
2364
- private visibleLimitReachedValue;
2365
- private visibleStarted;
2366
- private visibleTextValue;
2367
- constructor(options?: TextStreamCallbackOptions);
2368
- onStart(event: ChatStartEvent): void;
2369
- onEvent(json: string): void;
2370
- onDone(): void;
2371
- onError(error: string): void;
2372
- onInterrupted(): void;
2373
- wasInterrupted(): boolean;
2374
- close(): void;
2375
- fail(error: unknown): void;
2376
- hasText(): boolean;
2377
- remainingText(): string;
2378
- requestId(): string | undefined;
2379
- textSoFar(): string;
2380
- visibleLimitReached(): boolean;
2381
- visibleText(): string;
2382
- stream(): AsyncIterable<string>;
2383
- private pushVisibleText;
2384
- private wake;
2385
- private markVisibleStarted;
2386
- }
2387
- declare function textDeltaFromStreamChunk(json: string): string | null;
2388
- type MessengerReplyStage = "accepted" | "streaming" | "completed";
2389
- interface MessengerReplySnapshot {
2390
- event: MessengerEvent;
2391
- stage: MessengerReplyStage;
2392
- thread?: unknown;
2393
- type: typeof MESSENGER_REPLY_FIBER_NAME;
2394
- }
2395
- declare function messengerReplySnapshot(
2396
- stage: MessengerReplyStage,
2397
- event: MessengerEvent,
2398
- thread?: unknown
2399
- ): MessengerReplySnapshot;
2400
- declare function parseMessengerReplySnapshot(
2401
- snapshot: unknown
2402
- ): MessengerReplySnapshot | null;
2403
- declare function messengerReplyRecoveryMode(
2404
- snapshot: MessengerReplySnapshot
2405
- ): "answer" | "apologize" | null;
2406
- declare function messengerReplyFailureMode(
2407
- hasStreamedText: boolean,
2408
- completedModelTurn?: boolean,
2409
- expectedDeliveryCompletion?: boolean
2410
- ): "apologize" | "error" | null;
2411
- interface MessengerDeliveryTarget {
2412
- cancelChat(
2413
- requestId: string,
2414
- reason?: string
2415
- ): boolean | void | Promise<boolean | void>;
2416
- chat(
2417
- userMessage: string | UIMessage,
2418
- callback: StreamCallback
2419
- ): Promise<void>;
2420
- chatWithMessengerContext?(
2421
- userMessage: string | UIMessage,
2422
- callback: StreamCallback,
2423
- context: MessengerEvent
2424
- ): Promise<void>;
2425
- }
2426
- interface MessengerDeliverySurface {
2427
- post(
2428
- message:
2429
- | string
2430
- | {
2431
- markdown: string;
2432
- }
2433
- | AsyncIterable<string>
2434
- ): Promise<unknown>;
2435
- startTyping?(status?: string): Promise<void>;
2436
- }
2437
- interface MessengerDeliveryPolicy {
2438
- emptyResponseText?: string;
2439
- errorResponseText?: string;
2440
- interruptedResponseText?: string;
2441
- isExpectedDeliveryCompletion?(
2442
- error: unknown,
2443
- callback: TextStreamCallback
2444
- ): boolean;
2445
- splitText?(text: string): string[];
2446
- visibleSoftLimit?: number;
2447
- }
2448
- interface DeliverMessengerReplyOptions {
2449
- checkpoint?: (snapshot: MessengerReplySnapshot) => Promise<void> | void;
2450
- event: MessengerEvent;
2451
- fiber?: FiberContext;
2452
- policy?: MessengerDeliveryPolicy;
2453
- snapshotEvent?: MessengerEvent;
2454
- snapshotThread?: unknown;
2455
- surface: MessengerDeliverySurface;
2456
- target: MessengerDeliveryTarget;
2457
- userMessage?: UIMessage;
2458
- }
2459
- declare function deliverMessengerReply(
2460
- options: DeliverMessengerReplyOptions
2461
- ): Promise<void>;
2462
- //#endregion
2463
- //#region src/messengers/chat-sdk.d.ts
2464
- declare class ThinkMessengerStateAgent extends ChatSdkStateAgent {}
2465
- type MessengerRespondTo =
2466
- | "action"
2467
- | "direct-message"
2468
- | "mention"
2469
- | "subscribed-thread";
2470
- type MessengerConversationMode = "self" | "thread";
2471
- type MessengerConversationTarget =
2472
- | {
2473
- target: "self";
2474
- }
2475
- | {
2476
- agentClass?: SubAgentClass<Agent & MessengerThinkTarget>;
2477
- name: string;
2478
- target: "subagent";
2479
- };
2480
- type MessengerConversationResolver = (
2481
- event: MessengerEvent
2482
- ) => MessengerConversationTarget | Promise<MessengerConversationTarget>;
2483
- interface MessengerDefinition {
2484
- adapter: Adapter;
2485
- adapterName: string;
2486
- capabilities?: MessengerCapabilities;
2487
- conversation?: MessengerConversationMode | MessengerConversationResolver;
2488
- delivery?: MessengerDeliveryPolicy;
2489
- keyShard?: ChatSdkStateAdapterOptions["keyShard"];
2490
- path?: string;
2491
- provider: string;
2492
- respondTo?: readonly MessengerRespondTo[];
2493
- shardKey?: ChatSdkStateAdapterOptions["shardKey"];
2494
- subscribeOnMention?: boolean;
2495
- toEvent?: (
2496
- input: ChatSdkMessengerEventInput
2497
- ) => MessengerEvent | Promise<MessengerEvent>;
2498
- userName: string;
2499
- verifyWebhook?:
2500
- | false
2501
- | ((request: Request) => boolean | Response | Promise<boolean | Response>);
2502
- }
2503
- type ThinkMessengers = Record<string, MessengerDefinition>;
2504
- interface NormalizedMessengerDefinition extends MessengerDefinition {
2505
- id: string;
2506
- path: string;
2507
- respondTo: readonly MessengerRespondTo[];
2508
- subscribeOnMention: boolean;
2509
- verifyWebhook:
2510
- | false
2511
- | ((request: Request) => boolean | Response | Promise<boolean | Response>);
2512
- }
2513
- interface ChatSdkMessengerOptions extends Omit<
2514
- MessengerDefinition,
2515
- "adapterName"
2516
- > {
2517
- adapterName?: string;
2518
- }
2519
- interface ChatSdkMessengerEventInput {
2520
- action?: ActionEvent;
2521
- eventKind: MessengerEventKind;
2522
- message?: Message;
2523
- raw?: unknown;
2524
- thread: Thread;
2525
- }
2526
- interface MessengerThinkTarget {
2527
- cancelChat(
2528
- requestId: string,
2529
- reason?: string
2530
- ): boolean | void | Promise<boolean | void>;
2531
- chat(
2532
- userMessage: string | UIMessage,
2533
- callback: StreamCallback
2534
- ): Promise<void>;
2535
- chatWithMessengerContext?(
2536
- userMessage: string | UIMessage,
2537
- callback: StreamCallback,
2538
- context: MessengerEvent
2539
- ): Promise<void>;
2540
- }
2541
- interface MessengerThinkHost extends MessengerThinkTarget {
2542
- constructor: {
2543
- name: string;
2544
- };
2545
- name: string;
2546
- parentPath: ReadonlyArray<{
2547
- className: string;
2548
- name: string;
2549
- }>;
2550
- startFiber(
2551
- name: string,
2552
- fn: (ctx: FiberContext) => Promise<void>,
2553
- options?: StartFiberOptions
2554
- ): Promise<MessengerFiberStartResult>;
2555
- resolveFiber(id: string, result: FiberRecoveryResult): Promise<boolean>;
2556
- subAgent<T extends Agent>(
2557
- agentClass: SubAgentClass<T>,
2558
- name: string
2559
- ): Promise<SubAgentStub<T>>;
2560
- }
2561
- interface MessengerFiberStartResult {
2562
- accepted: boolean;
2563
- fiberId: string;
2564
- snapshot?: unknown;
2565
- status: string;
2566
- }
2567
- declare function defineMessengers<T extends ThinkMessengers>(messengers: T): T;
2568
- declare function chatSdkMessenger(
2569
- options: ChatSdkMessengerOptions
2570
- ): MessengerDefinition;
2571
- declare class ThinkMessengerRuntime {
2572
- private readonly host;
2573
- private chat?;
2574
- private readonly definitionsByAdapterName;
2575
- private readonly definitionsById;
2576
- private readonly definitions;
2577
- constructor(definitions: ThinkMessengers, host: MessengerThinkHost);
2578
- get size(): number;
2579
- initialize(): void;
2580
- handleRequest(request: Request): Promise<Response | undefined>;
2581
- handleFiberRecovery(ctx: FiberRecoveryContext): Promise<boolean>;
2582
- private createChat;
2583
- private enqueueReply;
2584
- private answer;
2585
- private resolveTarget;
2586
- private definitionForThread;
2587
- private definitionForThreadId;
2588
- private hasUniqueProvider;
2589
- private shardThread;
2590
- private shardStateKey;
2591
- private reviveChatObject;
2592
- private toEvent;
2593
- }
2594
- declare function normalizeMessengers(
2595
- messengers: ThinkMessengers
2596
- ): NormalizedMessengerDefinition[];
2597
- declare function defaultConversationName(event: MessengerEvent): string;
2598
- declare function idempotencyKeyForEvent(event: MessengerEvent): string;
2599
- declare function defaultChatSdkEvent(
2600
- definition: NormalizedMessengerDefinition,
2601
- input: ChatSdkMessengerEventInput
2602
- ): MessengerEvent;
2603
- declare function toMessengerThread(thread: Thread): MessengerThread;
2604
- declare function toMessengerMessage(message: Message): MessengerMessage;
2605
- declare function toMessengerAuthor(author: Author): MessengerAuthor;
2606
- declare function toMessengerAttachment(
2607
- attachment: Attachment
2608
- ): MessengerAttachment;
2609
- //#endregion
2610
2610
  export {
2611
- toMessengerUserMessage as $,
2612
- TypedToolCall$1 as $t,
2613
- MessengerDeliverySurface as A,
2614
- StepResult as At,
2615
- parseMessengerReplySnapshot as B,
2616
- ThinkScheduledTaskContext as Bt,
2617
- toMessengerThread as C,
2618
- SaveMessagesOptions$1 as Ct,
2619
- INTERRUPTED_MESSENGER_RESPONSE as D,
2620
- SkillSource$1 as Dt,
2621
- ERROR_MESSENGER_RESPONSE as E,
2622
- SkillRunContext as Et,
2623
- TextStreamCallbackOptions as F,
2624
- SubmitMessagesResult as Ft,
2625
- MessengerCapabilities as G,
2626
- ThinkTime as Gt,
2627
- MessengerAction as H,
2628
- ThinkScheduledTasks as Ht,
2629
- deliverMessengerReply as I,
2630
- TextStreamPart as It,
2631
- MessengerEventKind as J,
2632
- ToolCallDecision as Jt,
2633
- MessengerContext as K,
2634
- ThinkWallClockSchedule as Kt,
2635
- messengerReplyFailureMode as L,
2636
- Think as Lt,
2637
- MessengerReplySnapshot as M,
2638
- StreamCallback as Mt,
2639
- MessengerReplyStage as N,
2640
- StreamableResult as Nt,
2641
- MESSENGER_REPLY_FIBER_NAME as O,
2642
- StepConfig as Ot,
2643
- TextStreamCallback as P,
2644
- SubmitMessagesOptions as Pt,
2645
- serializableMessengerEvent as Q,
2646
- TurnInput as Qt,
2647
- messengerReplyRecoveryMode as R,
2648
- ThinkIntervalSchedule as Rt,
2649
- toMessengerMessage as S,
2650
- ResolvedChatRecoveryConfig as St,
2651
- EMPTY_MESSENGER_RESPONSE as T,
2652
- Session$1 as Tt,
2653
- MessengerAttachment as U,
2654
- ThinkSubmissionInspection as Ut,
2655
- textDeltaFromStreamChunk as V,
2656
- ThinkScheduledTaskSchedule as Vt,
2657
- MessengerAuthor as W,
2658
- ThinkSubmissionStatus as Wt,
2659
- MessengerThread as X,
2660
- TurnConfig as Xt,
2661
- MessengerMessage as Y,
2662
- ToolCallResultContext as Yt,
2663
- messengerContextFromEvent as Z,
2664
- TurnContext as Zt,
2665
- defineMessengers as _,
2666
- ListSubmissionsOptions as _t,
2667
- MessengerConversationTarget as a,
2668
- ChatRecoveryExhaustedContext as at,
2669
- toMessengerAttachment as b,
2670
- PrepareStepFunction$1 as bt,
2671
- MessengerThinkHost as c,
2672
- ChatResponseResult$1 as ct,
2673
- ThinkMessengerRuntime as d,
2674
- ChunkPart as dt,
2675
- TypedToolResult as en,
2676
- ChatErrorClassification as et,
2677
- ThinkMessengerStateAgent as f,
2678
- ContextOverflowConfig as ft,
2679
- defaultConversationName as g,
2680
- FiberRecoveryContext$1 as gt,
2681
- defaultChatSdkEvent as h,
2682
- FiberContext$1 as ht,
2683
- MessengerConversationResolver as i,
2684
- skills as in,
2685
- ChatRecoveryContext$1 as it,
2686
- MessengerDeliveryTarget as j,
2687
- StopCondition$1 as jt,
2688
- MessengerDeliveryPolicy as k,
2689
- StepContext as kt,
2690
- MessengerThinkTarget as l,
2691
- ChatStartEvent as lt,
2692
- chatSdkMessenger as m,
2693
- ExtensionConfig as mt,
2694
- ChatSdkMessengerOptions as n,
2695
- defaultContextOverflowClassifier as nn,
2696
- ChatOptions as nt,
2697
- MessengerDefinition as o,
2698
- ChatRecoveryOptions$1 as ot,
2699
- ThinkMessengers as p,
2700
- DeleteSubmissionsOptions as pt,
2701
- MessengerEvent as q,
2702
- ToolCallContext as qt,
2703
- MessengerConversationMode as r,
2704
- defineScheduledTasks as rn,
2705
- ChatRecoveryConfig$1 as rt,
2706
- MessengerRespondTo as s,
2707
- ChatRecoveryProgressContext as st,
2708
- ChatSdkMessengerEventInput as t,
2709
- Workspace$1 as tn,
2710
- ChatErrorContext as tt,
2711
- NormalizedMessengerDefinition as u,
2712
- ChunkContext as ut,
2713
- idempotencyKeyForEvent as v,
2714
- MessageConcurrency$1 as vt,
2715
- DeliverMessengerReplyOptions as w,
2716
- SaveMessagesResult$1 as wt,
2717
- toMessengerAuthor as x,
2718
- PrepareStepResult$1 as xt,
2719
- normalizeMessengers as y,
2720
- PrepareStepContext as yt,
2721
- messengerReplySnapshot as z,
2722
- ThinkScheduledTask as zt
2611
+ TurnInput as $,
2612
+ MessengerEventKind as $t,
2613
+ StepContext as A,
2614
+ EMPTY_MESSENGER_RESPONSE as At,
2615
+ ThinkScheduledTask as B,
2616
+ TextStreamCallbackOptions as Bt,
2617
+ ResolvedChatRecoveryConfig as C,
2618
+ idempotencyKeyForEvent as Ct,
2619
+ SkillRunContext as D,
2620
+ toMessengerMessage as Dt,
2621
+ Session$1 as E,
2622
+ toMessengerAuthor as Et,
2623
+ SubmitMessagesOptions as F,
2624
+ MessengerDeliverySurface as Ft,
2625
+ ThinkSubmissionStatus as G,
2626
+ parseMessengerReplySnapshot as Gt,
2627
+ ThinkScheduledTaskSchedule as H,
2628
+ messengerReplyFailureMode as Ht,
2629
+ SubmitMessagesResult as I,
2630
+ MessengerDeliveryTarget as It,
2631
+ ToolCallContext as J,
2632
+ MessengerAttachment as Jt,
2633
+ ThinkTime as K,
2634
+ textDeltaFromStreamChunk as Kt,
2635
+ TextStreamPart as L,
2636
+ MessengerReplySnapshot as Lt,
2637
+ StopCondition$1 as M,
2638
+ INTERRUPTED_MESSENGER_RESPONSE as Mt,
2639
+ StreamCallback as N,
2640
+ MESSENGER_REPLY_FIBER_NAME as Nt,
2641
+ SkillSource$1 as O,
2642
+ toMessengerThread as Ot,
2643
+ StreamableResult as P,
2644
+ MessengerDeliveryPolicy as Pt,
2645
+ TurnContext as Q,
2646
+ MessengerEvent as Qt,
2647
+ Think as R,
2648
+ MessengerReplyStage as Rt,
2649
+ PrepareStepResult$1 as S,
2650
+ defineMessengers as St,
2651
+ SaveMessagesResult$1 as T,
2652
+ toMessengerAttachment as Tt,
2653
+ ThinkScheduledTasks as U,
2654
+ messengerReplyRecoveryMode as Ut,
2655
+ ThinkScheduledTaskContext as V,
2656
+ deliverMessengerReply as Vt,
2657
+ ThinkSubmissionInspection as W,
2658
+ messengerReplySnapshot as Wt,
2659
+ ToolCallResultContext as X,
2660
+ MessengerCapabilities as Xt,
2661
+ ToolCallDecision as Y,
2662
+ MessengerAuthor as Yt,
2663
+ TurnConfig as Z,
2664
+ MessengerContext as Zt,
2665
+ FiberRecoveryContext$1 as _,
2666
+ ThinkMessengerStateAgent as _t,
2667
+ ChatRecoveryContext$1 as a,
2668
+ skills as at,
2669
+ PrepareStepContext as b,
2670
+ defaultChatSdkEvent as bt,
2671
+ ChatRecoveryProgressContext as c,
2672
+ MessengerConversationMode as ct,
2673
+ ChunkContext as d,
2674
+ MessengerDefinition as dt,
2675
+ MessengerMessage as en,
2676
+ TypedToolCall$1 as et,
2677
+ ChunkPart as f,
2678
+ MessengerRespondTo as ft,
2679
+ FiberContext$1 as g,
2680
+ ThinkMessengerRuntime as gt,
2681
+ ExtensionConfig as h,
2682
+ NormalizedMessengerDefinition as ht,
2683
+ ChatRecoveryConfig$1 as i,
2684
+ toMessengerUserMessage as in,
2685
+ defineScheduledTasks as it,
2686
+ StepResult as j,
2687
+ ERROR_MESSENGER_RESPONSE as jt,
2688
+ StepConfig as k,
2689
+ DeliverMessengerReplyOptions as kt,
2690
+ ChatResponseResult$1 as l,
2691
+ MessengerConversationResolver as lt,
2692
+ DeleteSubmissionsOptions as m,
2693
+ MessengerThinkTarget as mt,
2694
+ ChatErrorContext as n,
2695
+ messengerContextFromEvent as nn,
2696
+ Workspace$1 as nt,
2697
+ ChatRecoveryExhaustedContext as o,
2698
+ ChatSdkMessengerEventInput as ot,
2699
+ ContextOverflowConfig as p,
2700
+ MessengerThinkHost as pt,
2701
+ ThinkWallClockSchedule as q,
2702
+ MessengerAction as qt,
2703
+ ChatOptions as r,
2704
+ serializableMessengerEvent as rn,
2705
+ defaultContextOverflowClassifier as rt,
2706
+ ChatRecoveryOptions$1 as s,
2707
+ ChatSdkMessengerOptions as st,
2708
+ ChatErrorClassification as t,
2709
+ MessengerThread as tn,
2710
+ TypedToolResult as tt,
2711
+ ChatStartEvent as u,
2712
+ MessengerConversationTarget as ut,
2713
+ ListSubmissionsOptions as v,
2714
+ ThinkMessengers as vt,
2715
+ SaveMessagesOptions$1 as w,
2716
+ normalizeMessengers as wt,
2717
+ PrepareStepFunction$1 as x,
2718
+ defaultConversationName as xt,
2719
+ MessageConcurrency$1 as y,
2720
+ chatSdkMessenger as yt,
2721
+ ThinkIntervalSchedule as z,
2722
+ TextStreamCallback as zt
2723
2723
  };
2724
- //# sourceMappingURL=index-BzPfnYMr.d.ts.map
2724
+ //# sourceMappingURL=think-8jik2oZ5.d.ts.map