@cloudflare/think 0.7.2 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2202 @@
1
+ import {
2
+ i as ExtensionManifest,
3
+ t as ExtensionManager
4
+ } from "./manager-C1zjft70.js";
5
+ import {
6
+ D as createWorkspaceTools,
7
+ h as WorkspaceLike
8
+ } from "./workspace-Bri0ANBX.js";
9
+ import {
10
+ LanguageModel,
11
+ ModelMessage,
12
+ PrepareStepFunction,
13
+ PrepareStepFunction as PrepareStepFunction$1,
14
+ PrepareStepResult,
15
+ PrepareStepResult as PrepareStepResult$1,
16
+ StepResult,
17
+ StopCondition,
18
+ StopCondition as StopCondition$1,
19
+ StreamTextOnChunkCallback,
20
+ StreamTextOnStepFinishCallback,
21
+ TextStreamPart,
22
+ ToolSet,
23
+ TypedToolCall,
24
+ TypedToolCall as TypedToolCall$1,
25
+ TypedToolResult,
26
+ UIMessage,
27
+ streamText
28
+ } from "ai";
29
+ import * as skills from "agents/skills";
30
+ import {
31
+ SkillRunContext,
32
+ SkillScriptRunner,
33
+ SkillSource,
34
+ SkillSource as SkillSource$1
35
+ } from "agents/skills";
36
+ import {
37
+ Agent,
38
+ FiberContext,
39
+ FiberContext as FiberContext$1,
40
+ FiberRecoveryContext,
41
+ FiberRecoveryContext as FiberRecoveryContext$1,
42
+ FiberRecoveryResult,
43
+ RetryOptions,
44
+ StartFiberOptions,
45
+ SubAgentClass,
46
+ SubAgentStub
47
+ } from "agents";
48
+ import {
49
+ ChatRecoveryConfig,
50
+ ChatRecoveryConfig as ChatRecoveryConfig$1,
51
+ ChatRecoveryContext,
52
+ ChatRecoveryContext as ChatRecoveryContext$1,
53
+ ChatRecoveryExhaustedContext,
54
+ ChatRecoveryOptions,
55
+ ChatRecoveryOptions as ChatRecoveryOptions$1,
56
+ ChatResponseResult,
57
+ ChatResponseResult as ChatResponseResult$1,
58
+ ClientToolSchema,
59
+ MessageConcurrency,
60
+ MessageConcurrency as MessageConcurrency$1,
61
+ ResolvedChatRecoveryConfig,
62
+ ResumableStream,
63
+ SaveMessagesOptions,
64
+ SaveMessagesOptions as SaveMessagesOptions$1,
65
+ SaveMessagesResult,
66
+ SaveMessagesResult as SaveMessagesResult$1
67
+ } from "agents/chat";
68
+ import {
69
+ Session,
70
+ Session as Session$1
71
+ } from "agents/experimental/memory/session";
72
+ import { Workspace as Workspace$1 } from "@cloudflare/shell";
73
+ import {
74
+ ActionEvent,
75
+ Adapter,
76
+ Attachment,
77
+ Author,
78
+ Message,
79
+ Thread
80
+ } from "chat";
81
+ import { ChatSdkStateAdapterOptions, ChatSdkStateAgent } from "agents/chat-sdk";
82
+ import { RpcTarget } from "cloudflare:workers";
83
+
84
+ //#region src/think.d.ts
85
+ type ChatRecoveryRetryData = {
86
+ targetUserId?: string;
87
+ originalRequestId?: string;
88
+ incidentId?: string;
89
+ lastBody?: Record<string, unknown> | null;
90
+ lastClientTools?: ClientToolSchema[] | null;
91
+ recoveredRequestId?: string;
92
+ };
93
+ type ChatRecoveryContinueData = {
94
+ targetAssistantId?: string;
95
+ originalRequestId?: string;
96
+ incidentId?: string;
97
+ lastBody?: Record<string, unknown> | null;
98
+ lastClientTools?: ClientToolSchema[] | null;
99
+ recoveredRequestId?: string;
100
+ };
101
+ /**
102
+ * Callback interface for streaming chat events from a Think sub-agent.
103
+ *
104
+ * Designed to work across the sub-agent RPC boundary — implement as
105
+ * an RpcTarget in the parent agent and pass to `chat()`.
106
+ */
107
+ interface ChatStartEvent {
108
+ requestId: string;
109
+ }
110
+ interface StreamCallback {
111
+ onStart(event: ChatStartEvent): void | Promise<void>;
112
+ onEvent(json: string): void | Promise<void>;
113
+ onDone(): void | Promise<void>;
114
+ onError(error: string): void | Promise<void>;
115
+ /**
116
+ * The current attempt was interrupted (a stream-stall watchdog abort routed
117
+ * into bounded recovery, #1626) and its final outcome will NOT arrive through
118
+ * this callback. One of two things is true:
119
+ * - a scheduled continuation — running in a LATER isolate invocation, without
120
+ * this callback — will produce the answer (delivered to other channels,
121
+ * e.g. WebSocket connections), OR
122
+ * - the recovery budget was exhausted, so the turn was already terminalized
123
+ * out-of-band (the configured `terminalMessage` + `onExhausted`) and is
124
+ * terminally over — there is NO continuation to come.
125
+ *
126
+ * This is NOT `onDone` (this attempt did not complete) and NOT `onError` (the
127
+ * raw stall is not surfaced as a terminal error here); without it the contract
128
+ * `onStart → onEvent* → (onDone | onError)` is silently abandoned and a
129
+ * consumer that treats the clean resolve as success finalizes a truncated
130
+ * partial.
131
+ *
132
+ * Consumers should AVOID finalizing the partial on this signal — surface a
133
+ * "recovering…" / "interrupted, please retry" state, or re-attach via a
134
+ * durable channel — but must ALSO NOT block indefinitely waiting for a
135
+ * continuation: per the exhausted case above, one may never come. Optional →
136
+ * defaults to a no-op, so this is fully backward-compatible.
137
+ *
138
+ * Note: a deploy/eviction interruption kills the isolate (and this callback)
139
+ * before this can fire — the caller observes a transport break instead. This
140
+ * fires only for an in-isolate interruption (the stall→recovery path).
141
+ */
142
+ onInterrupted?(): void | Promise<void>;
143
+ }
144
+ /**
145
+ * Minimal interface for the result of the inference loop.
146
+ * The AI SDK's `streamText()` result satisfies this interface.
147
+ */
148
+ interface StreamableResult {
149
+ toUIMessageStream(options?: {
150
+ sendReasoning?: boolean;
151
+ }): AsyncIterable<unknown>;
152
+ output?: PromiseLike<unknown>;
153
+ }
154
+ /**
155
+ * Options for a chat turn (sub-agent RPC entry point).
156
+ */
157
+ interface ChatOptions {
158
+ signal?: AbortSignal;
159
+ }
160
+ type AgentToolChildRunStatus =
161
+ | "starting"
162
+ | "running"
163
+ | "completed"
164
+ | "error"
165
+ | "aborted";
166
+ type AgentToolRunInspection<Output = unknown> = {
167
+ runId: string;
168
+ status: AgentToolChildRunStatus;
169
+ requestId?: string;
170
+ streamId?: string;
171
+ output?: Output;
172
+ summary?: string;
173
+ error?: string;
174
+ startedAt: number;
175
+ completedAt?: number;
176
+ };
177
+ type Digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";
178
+ type Hour = `0${Digit}` | `1${Digit}` | "20" | "21" | "22" | "23";
179
+ type Minute = `${"0" | "1" | "2" | "3" | "4" | "5"}${Digit}`;
180
+ type ThinkTime = `${Hour}:${Minute}`;
181
+ type ThinkIntervalSchedule =
182
+ | `every ${number} minute${"" | "s"}`
183
+ | `every ${number} hour${"" | "s"}`;
184
+ type ThinkWallClockSchedule =
185
+ | `every day at ${ThinkTime}`
186
+ | `every weekday at ${ThinkTime}`
187
+ | `every week on ${string} at ${ThinkTime}`;
188
+ type ThinkScheduledTaskSchedule =
189
+ | ThinkIntervalSchedule
190
+ | ThinkWallClockSchedule
191
+ | `${ThinkWallClockSchedule} in ${string}`;
192
+ type ThinkScheduledTaskContext = {
193
+ taskId: string;
194
+ scheduledFor: number;
195
+ scheduledForDate: Date;
196
+ occurrenceKey: string;
197
+ idempotencyKey: string;
198
+ schedule: string;
199
+ scheduleKind: "interval" | "wall-clock";
200
+ timezone?: string;
201
+ metadata?: Record<string, unknown>;
202
+ };
203
+ type ThinkScheduledTaskPromptAction = {
204
+ prompt: string | (() => string | Promise<string>);
205
+ handler?: never;
206
+ };
207
+ type ThinkScheduledTaskHandlerAction = {
208
+ handler: (ctx: ThinkScheduledTaskContext) => void | Promise<void>;
209
+ prompt?: never;
210
+ };
211
+ type ThinkScheduledTaskBase = (
212
+ | ThinkScheduledTaskPromptAction
213
+ | ThinkScheduledTaskHandlerAction
214
+ ) & {
215
+ retry?: RetryOptions;
216
+ metadata?: Record<string, unknown>;
217
+ };
218
+ type ThinkScheduledTask =
219
+ | (ThinkScheduledTaskBase & {
220
+ schedule: ThinkIntervalSchedule;
221
+ timezone?: never;
222
+ })
223
+ | (ThinkScheduledTaskBase & {
224
+ schedule: ThinkWallClockSchedule;
225
+ timezone?: string;
226
+ })
227
+ | (ThinkScheduledTaskBase & {
228
+ schedule: `${ThinkWallClockSchedule} in ${string}`;
229
+ timezone?: string;
230
+ });
231
+ type ThinkScheduledTasks = Record<string, ThinkScheduledTask>;
232
+ declare function defineScheduledTasks<const T extends ThinkScheduledTasks>(
233
+ tasks: T
234
+ ): T;
235
+ type DeclaredScheduledTaskPayload = {
236
+ taskId: string;
237
+ scheduleHash: string;
238
+ scheduledFor: number;
239
+ };
240
+ type AgentToolStoredChunk = {
241
+ sequence: number;
242
+ body: string;
243
+ };
244
+ type ThinkSubmissionStatus =
245
+ | "pending"
246
+ | "running"
247
+ | "completed"
248
+ | "aborted"
249
+ | "skipped"
250
+ | "error";
251
+ type SubmitMessagesOptions = {
252
+ submissionId?: string;
253
+ idempotencyKey?: string;
254
+ metadata?: Record<string, unknown>;
255
+ };
256
+ type ThinkWorkflowPromptContext = {
257
+ workflow: {
258
+ name: string;
259
+ id: string;
260
+ stepName: string;
261
+ eventType: string;
262
+ };
263
+ output?: {
264
+ schema: unknown;
265
+ };
266
+ fingerprint?: string;
267
+ };
268
+ type ThinkSubmissionInspection = {
269
+ submissionId: string;
270
+ idempotencyKey?: string;
271
+ requestId?: string;
272
+ status: ThinkSubmissionStatus;
273
+ error?: string;
274
+ metadata?: Record<string, unknown>;
275
+ createdAt: number;
276
+ startedAt?: number;
277
+ completedAt?: number;
278
+ };
279
+ type SubmitMessagesResult = ThinkSubmissionInspection & {
280
+ accepted: boolean;
281
+ };
282
+ type ListSubmissionsOptions = {
283
+ status?: ThinkSubmissionStatus | ThinkSubmissionStatus[];
284
+ limit?: number;
285
+ };
286
+ type DeleteSubmissionsOptions = {
287
+ status?: ThinkSubmissionStatus | ThinkSubmissionStatus[];
288
+ completedBefore?: Date;
289
+ limit?: number;
290
+ };
291
+ /**
292
+ * A chat turn request. Built automatically by each entry path
293
+ * (WebSocket, chat(), saveMessages, auto-continuation) and passed
294
+ * to Think's inference loop.
295
+ */
296
+ interface TurnInput {
297
+ signal?: AbortSignal;
298
+ /** Client-provided tool schemas for dynamic tool registration. */
299
+ clientTools?: ClientToolSchema[];
300
+ /** Custom body fields from the client request. */
301
+ body?: Record<string, unknown>;
302
+ /** Internal workflow prompt configuration, never sourced from client body. */
303
+ workflowPrompt?: ThinkWorkflowPromptContext;
304
+ /** Whether this is a continuation turn (auto-continue after tool result, recovery). */
305
+ continuation: boolean;
306
+ }
307
+ /**
308
+ * Context passed to the `beforeTurn` hook.
309
+ * Contains everything Think assembled — the hook can inspect and override.
310
+ */
311
+ interface TurnContext {
312
+ /** Assembled system prompt (from context blocks or getSystemPrompt fallback). */
313
+ system: string;
314
+ /** Assembled model messages (truncated, pruned). */
315
+ messages: ModelMessage[];
316
+ /** Merged tool set (workspace + getTools + session + MCP + client + caller). */
317
+ tools: ToolSet;
318
+ /** The language model from getModel(). */
319
+ model: LanguageModel;
320
+ /** Whether this is a continuation turn. */
321
+ continuation: boolean;
322
+ /** Custom body fields from the client request. */
323
+ body?: Record<string, unknown>;
324
+ }
325
+ /**
326
+ * Configuration returned by the `beforeTurn` hook to override defaults.
327
+ * All fields are optional — return only what you want to change.
328
+ */
329
+ interface TurnConfig {
330
+ /** Override the model for this turn (e.g. cheap model for continuations). */
331
+ model?: LanguageModel;
332
+ /** Override the assembled system prompt. */
333
+ system?: string;
334
+ /** Override the assembled messages. */
335
+ messages?: ModelMessage[];
336
+ /** Extra tools to merge (additive — spread on top of existing tools). */
337
+ tools?: ToolSet;
338
+ /** Limit which tools the model can call (AI SDK activeTools). */
339
+ activeTools?: string[];
340
+ /** Force a specific tool call (AI SDK toolChoice). */
341
+ toolChoice?: Parameters<typeof streamText>[0]["toolChoice"];
342
+ /** Override maxSteps for this turn. */
343
+ maxSteps?: number;
344
+ /**
345
+ * Additional AI SDK stop conditions for ending the turn early.
346
+ * Think always keeps its `maxSteps` stop condition as a safety bound.
347
+ */
348
+ stopWhen?: StopCondition<ToolSet> | Array<StopCondition<ToolSet>>;
349
+ /**
350
+ * Controls whether reasoning chunks are included in the UI message stream
351
+ * for this turn. Defaults to the instance-level `sendReasoning` setting.
352
+ */
353
+ sendReasoning?: boolean;
354
+ /**
355
+ * Override the stream-stall inactivity watchdog timeout for THIS turn only
356
+ * (ms; `0` disables it for this turn). Defaults to the instance-level
357
+ * `chatStreamStallTimeoutMs`. Because the watchdog measures the gap between
358
+ * UI-message-stream chunks — which includes server-side tool execution — a
359
+ * turn known to invoke a slow tool can raise (or disable) the timeout for
360
+ * just that turn instead of permanently widening the global window. Auto-
361
+ * resets after the turn.
362
+ */
363
+ chatStreamStallTimeoutMs?: number;
364
+ /** Maximum number of tokens to generate for this turn. */
365
+ maxOutputTokens?: Parameters<typeof streamText>[0]["maxOutputTokens"];
366
+ /** Temperature setting for this turn. */
367
+ temperature?: Parameters<typeof streamText>[0]["temperature"];
368
+ /** Nucleus sampling setting for this turn. */
369
+ topP?: Parameters<typeof streamText>[0]["topP"];
370
+ /** Top-K sampling setting for this turn. */
371
+ topK?: Parameters<typeof streamText>[0]["topK"];
372
+ /** Presence penalty setting for this turn. */
373
+ presencePenalty?: Parameters<typeof streamText>[0]["presencePenalty"];
374
+ /** Frequency penalty setting for this turn. */
375
+ frequencyPenalty?: Parameters<typeof streamText>[0]["frequencyPenalty"];
376
+ /** Stop sequences for this turn. */
377
+ stopSequences?: Parameters<typeof streamText>[0]["stopSequences"];
378
+ /** Seed for deterministic sampling when supported by the model. */
379
+ seed?: Parameters<typeof streamText>[0]["seed"];
380
+ /** Maximum number of retries for this turn. Set to 0 to disable retries. */
381
+ maxRetries?: Parameters<typeof streamText>[0]["maxRetries"];
382
+ /** Timeout configuration for this turn. */
383
+ timeout?: Parameters<typeof streamText>[0]["timeout"];
384
+ /** Additional HTTP headers for provider requests on this turn. */
385
+ headers?: Parameters<typeof streamText>[0]["headers"];
386
+ /** Provider-specific options (AI SDK providerOptions). */
387
+ providerOptions?: Record<string, unknown>;
388
+ /** Optional AI SDK telemetry configuration for this turn. */
389
+ experimental_telemetry?: Parameters<
390
+ typeof streamText
391
+ >[0]["experimental_telemetry"];
392
+ /**
393
+ * Optional structured-output specification (AI SDK `output`).
394
+ * Forwarded to `streamText` so the model's final response is parsed
395
+ * against the supplied schema. Use the AI SDK's `Output.object({ schema })`
396
+ * / `Output.text()` helpers. Combine with `activeTools: []` on the
397
+ * terminal turn if your provider strips tools when structured output
398
+ * is active (e.g. workers-ai-provider).
399
+ */
400
+ output?: Parameters<typeof streamText>[0]["output"];
401
+ }
402
+ interface ChatErrorContext {
403
+ requestId?: string;
404
+ stage: "parse" | "persist" | "turn" | "stream" | "recovery" | "transcript";
405
+ messagesPersisted?: boolean;
406
+ }
407
+ /**
408
+ * Context passed to the `beforeStep` hook before each AI SDK step in
409
+ * the agentic loop. Backed by the AI SDK's `PrepareStepFunction<TOOLS>`
410
+ * parameter — exposes the previous `steps`, the zero-based `stepNumber`,
411
+ * the currently selected `model`, the `messages` about to be sent, and
412
+ * `experimental_context`.
413
+ *
414
+ * Pass an explicit `TOOLS` generic for typed previous tool calls / results.
415
+ *
416
+ * Limitations (AI SDK boundary, not Think):
417
+ * - No `abortSignal` is exposed in the context. If you do remote work
418
+ * inside `beforeStep`, it cannot be cancelled by turn-level abort.
419
+ * - `experimental_context` is typed `unknown`; users must narrow it.
420
+ * - `output` cannot be overridden per-step — set it at the turn level
421
+ * via `TurnConfig.output` (returned from `beforeTurn`).
422
+ */
423
+ type PrepareStepContext<TOOLS extends ToolSet = ToolSet> = Parameters<
424
+ PrepareStepFunction<TOOLS>
425
+ >[0];
426
+ /**
427
+ * Configuration returned by `beforeStep` to override defaults for the
428
+ * current AI SDK step. This is the AI SDK's `PrepareStepResult<TOOLS>` —
429
+ * return only the fields you want to override (`model`, `toolChoice`,
430
+ * `activeTools`, `system`, `messages`, `experimental_context`,
431
+ * `providerOptions`).
432
+ */
433
+ type StepConfig<TOOLS extends ToolSet = ToolSet> = PrepareStepResult<TOOLS>;
434
+ /**
435
+ * Context passed to the `beforeToolCall` hook **before** the tool's
436
+ * `execute` function runs.
437
+ *
438
+ * Backed by the AI SDK's `OnToolCallStartEvent` (the parameter of
439
+ * `experimental_onToolCallStart`). The full `TypedToolCall<TOOLS>`
440
+ * fields (`toolName`, `toolCallId`, `input`, `providerMetadata`, the
441
+ * dynamic/invalid/error discriminators) are spread at the top level for
442
+ * convenience, with the per-call event extras attached:
443
+ *
444
+ * - `stepNumber` — index of the current step
445
+ * - `messages` — conversation messages visible at tool execution time
446
+ * - `abortSignal` — signal that aborts if the turn is cancelled
447
+ *
448
+ * Pass an explicit `TOOLS` generic for full input typing:
449
+ *
450
+ * ```ts
451
+ * import type { ToolCallContext } from "@cloudflare/think";
452
+ * import type { tools } from "./my-tools";
453
+ *
454
+ * beforeToolCall(ctx: ToolCallContext<typeof tools>) {
455
+ * if (ctx.toolName === "search") {
456
+ * ctx.input.query; // typed
457
+ * }
458
+ * }
459
+ * ```
460
+ */
461
+ type ToolCallContext<TOOLS extends ToolSet = ToolSet> = TypedToolCall<TOOLS> & {
462
+ /** Zero-based index of the current step where this tool call occurs. */ readonly stepNumber:
463
+ | number
464
+ | undefined /** The conversation messages available at tool execution time. */;
465
+ readonly messages: ReadonlyArray<ModelMessage> /** Signal for cancelling the operation. */;
466
+ readonly abortSignal: AbortSignal | undefined;
467
+ };
468
+ /**
469
+ * Decision returned by `beforeToolCall` to control tool execution.
470
+ * Return void/undefined to allow execution with original input.
471
+ *
472
+ * Discriminated union — each action has a clear, non-overlapping meaning:
473
+ * - `allow` — execute the tool (optionally with modified input)
474
+ * - `block` — don't execute; return `reason` as the tool result so the model can adjust
475
+ * - `substitute` — don't execute; return `output` as the tool result (afterToolCall still fires)
476
+ */
477
+ type ToolCallDecision =
478
+ | {
479
+ action: "allow" /** Modified input — tool executes with this instead of the original. */;
480
+ input?: Record<string, unknown>;
481
+ }
482
+ | {
483
+ action: "block" /** Returned as the tool result so the model can adjust. */;
484
+ reason?: string;
485
+ }
486
+ | {
487
+ action: "substitute" /** The substitute tool output — model sees this instead of real execution. */;
488
+ output: unknown /** Optional input attribution for the afterToolCall log. */;
489
+ input?: Record<string, unknown>;
490
+ };
491
+ /**
492
+ * Context passed to the `afterToolCall` hook after a tool executes.
493
+ *
494
+ * Backed by the AI SDK's `OnToolCallFinishEvent` (the parameter of
495
+ * `experimental_onToolCallFinish`). The full `TypedToolCall<TOOLS>`
496
+ * fields (`toolName`, `toolCallId`, `input`, …) are spread at the top
497
+ * level, plus the per-call event extras:
498
+ *
499
+ * - `stepNumber` — index of the current step
500
+ * - `messages` — conversation messages visible at tool execution time
501
+ * - `durationMs` — wall-clock execution time in milliseconds
502
+ * - `success`/`output`/`error` — discriminated outcome:
503
+ * - on success: `success: true`, `output: unknown`
504
+ * - on failure: `success: false`, `error: unknown`
505
+ *
506
+ * Pass an explicit `TOOLS` generic for full input typing:
507
+ *
508
+ * ```ts
509
+ * import type { ToolCallResultContext } from "@cloudflare/think";
510
+ * import type { tools } from "./my-tools";
511
+ *
512
+ * afterToolCall(ctx: ToolCallResultContext<typeof tools>) {
513
+ * if (ctx.success) {
514
+ * console.log(`${ctx.toolName} took ${ctx.durationMs}ms`, ctx.output);
515
+ * } else {
516
+ * console.error(`${ctx.toolName} failed:`, ctx.error);
517
+ * }
518
+ * }
519
+ * ```
520
+ */
521
+ type ToolCallResultContext<TOOLS extends ToolSet = ToolSet> =
522
+ TypedToolCall<TOOLS> & {
523
+ readonly stepNumber: number | undefined;
524
+ readonly messages: ReadonlyArray<ModelMessage> /** Wall-clock execution time in milliseconds. */;
525
+ readonly durationMs: number;
526
+ } & (
527
+ | {
528
+ readonly success: true;
529
+ readonly output: unknown;
530
+ readonly error?: never;
531
+ }
532
+ | {
533
+ readonly success: false;
534
+ readonly output?: never;
535
+ readonly error: unknown;
536
+ }
537
+ );
538
+ /**
539
+ * Context passed to the `onStepFinish` hook after each step completes.
540
+ *
541
+ * This is the AI SDK's `StepResult<TOOLS>` (= `OnStepFinishEvent<TOOLS>`) —
542
+ * the full step record including `text`, `reasoning`, `toolCalls`,
543
+ * `toolResults`, `files`, `sources`, `usage` (with `cachedInputTokens`,
544
+ * `reasoningTokens`, `totalTokens`), `finishReason`, `warnings`, `request`,
545
+ * `response`, and `providerMetadata` (where provider-specific cache
546
+ * accounting like `cacheCreationInputTokens` lives).
547
+ *
548
+ * Pass an explicit `TOOLS` generic for typed `toolCalls`/`toolResults`.
549
+ */
550
+ type StepContext<TOOLS extends ToolSet = ToolSet> = Parameters<
551
+ StreamTextOnStepFinishCallback<TOOLS>
552
+ >[0];
553
+ /**
554
+ * Context passed to the `onChunk` hook for each streaming chunk.
555
+ *
556
+ * This is the AI SDK's `StreamTextOnChunkCallback` event — `{ chunk }`
557
+ * where `chunk` is a discriminated union of `TextStreamPart` variants
558
+ * (text-delta, reasoning-delta, source, tool-call, tool-input-start,
559
+ * tool-input-delta, tool-result, raw).
560
+ */
561
+ type ChunkContext<TOOLS extends ToolSet = ToolSet> = Parameters<
562
+ StreamTextOnChunkCallback<TOOLS>
563
+ >[0];
564
+ /**
565
+ * @internal Re-export of the chunk variant union for consumers that need
566
+ * to narrow on `chunk.type` without importing `TextStreamPart` directly.
567
+ */
568
+ type ChunkPart<TOOLS extends ToolSet = ToolSet> = ChunkContext<TOOLS>["chunk"];
569
+ /**
570
+ * Configuration for a sandboxed extension, returned by getExtensions().
571
+ */
572
+ interface ExtensionConfig {
573
+ /** Extension manifest (name, version, permissions, contributions). */
574
+ manifest: ExtensionManifest;
575
+ /** JavaScript source code defining the extension's tools. */
576
+ source: string;
577
+ }
578
+ /**
579
+ * An opinionated chat agent base class.
580
+ *
581
+ * @experimental The API surface may change before stabilizing.
582
+ */
583
+ declare class Think<
584
+ Env extends Cloudflare.Env = Cloudflare.Env,
585
+ State = unknown,
586
+ Props extends Record<string, unknown> = Record<string, unknown>
587
+ > extends Agent<Env, State, Props> {
588
+ #private;
589
+ private _activeChatRecoveryRootRequestId;
590
+ private static readonly CONFIG_KEYS;
591
+ /**
592
+ * Wait for MCP server connections to be ready before the inference
593
+ * loop. MCP tools are auto-merged into the tool set.
594
+ *
595
+ * Set to `true` for a default 10s timeout, or `{ timeout: ms }`
596
+ * for a custom timeout. Defaults to `false` (no waiting).
597
+ */
598
+ waitForMcpConnections:
599
+ | boolean
600
+ | {
601
+ timeout: number;
602
+ };
603
+ private _skillRegistry;
604
+ private _loggedSkillWarnings;
605
+ /**
606
+ * Controls how overlapping user submit requests behave while another
607
+ * chat turn is already active or queued.
608
+ *
609
+ * @default "queue"
610
+ */
611
+ messageConcurrency: MessageConcurrency;
612
+ /**
613
+ * When true, chat turns are wrapped in `runFiber` for durable execution.
614
+ * Enables `onChatRecovery` hook and `this.stash()` during streaming.
615
+ */
616
+ chatRecovery: ChatRecoveryConfig;
617
+ static readonly CHAT_FIBER_NAME = "__cf_internal_chat_turn";
618
+ /**
619
+ * The conversation session — messages, context, compaction, search.
620
+ *
621
+ * Direct message writes are observed and mirrored into Think's live cache.
622
+ * Prefer the history helpers below when writing UI messages from subclasses;
623
+ * they sanitize content and enforce row-size limits before delegating here.
624
+ */
625
+ session: Session;
626
+ /** Cached messages — kept in sync with session storage. */
627
+ private _cachedMessages;
628
+ private _activeMessengerContext?;
629
+ private _messengerRuntime?;
630
+ /**
631
+ * WorkerLoader binding for sandboxed extensions.
632
+ * Set this to enable `getExtensions()` and dynamic extension loading.
633
+ */
634
+ extensionLoader?: WorkerLoader;
635
+ /**
636
+ * Extension manager — created automatically when `extensionLoader` is set.
637
+ * Use for dynamic `load()` / `unload()` at runtime.
638
+ */
639
+ extensionManager?: ExtensionManager;
640
+ /**
641
+ * Workspace filesystem available in `getTools()` and lifecycle hooks.
642
+ * Defaults to a full `Workspace` backed by the DO's SQLite storage.
643
+ *
644
+ * Typed as `WorkspaceLike` rather than `Workspace` so subclasses can
645
+ * replace it with anything that satisfies the interface — e.g. a proxy
646
+ * that forwards to a shared workspace owned by a parent DO. Override as
647
+ * a class field to skip the default init entirely:
648
+ *
649
+ * ```typescript
650
+ * // Default init with R2 spillover for large files.
651
+ * override workspace = new Workspace({
652
+ * sql: this.ctx.storage.sql,
653
+ * r2: this.env.R2,
654
+ * name: () => this.name
655
+ * });
656
+ *
657
+ * // Or a custom WorkspaceLike — e.g. a parent-owned shared workspace.
658
+ * override workspace: WorkspaceLike = new SharedWorkspace(this);
659
+ * ```
660
+ */
661
+ workspace: WorkspaceLike;
662
+ /**
663
+ * Include the default workspace Bash tool. Enabled by default so models can
664
+ * run shell-style multi-file workflows against the workspace. Set to `false`
665
+ * to omit it from the built-in workspace tools.
666
+ */
667
+ workspaceBash:
668
+ | boolean
669
+ | NonNullable<Parameters<typeof createWorkspaceTools>[1]>["bash"];
670
+ constructor(ctx: DurableObjectState, env: Env);
671
+ /**
672
+ * Conversation history as Think's live in-memory view.
673
+ *
674
+ * Storage remains the durable source of truth, but runtime logic should read
675
+ * through this cache so in-flight turns, tool updates, and recovery state all
676
+ * observe the same message list. Use `_syncMessages()` only at safe
677
+ * boundaries where a full storage reread cannot drop in-flight state.
678
+ */
679
+ get messages(): UIMessage[];
680
+ /** Read the durable message path from session storage. */
681
+ private _readMessagesFromStorage;
682
+ /**
683
+ * Normalize a tool part's `input` into something the provider will accept.
684
+ *
685
+ * Two malformed shapes 400 modern providers (and persist forever once
686
+ * written): a stringified-JSON `input` (e.g. `'{"prompt":"a cat"}'` instead
687
+ * of the object) and a missing/`null` `input` on a settled or interrupted
688
+ * tool call (Anthropic rejects a `tool_use` block whose `input` is absent).
689
+ * We parse the former and default the latter to an empty object so the
690
+ * tool-call/tool-result pair stays valid. Any other value is left untouched.
691
+ */
692
+ private _normalizeToolInput;
693
+ /**
694
+ * Whether a tool part already has a settled result the provider accepts, so
695
+ * it must NOT be re-repaired into an errored result.
696
+ *
697
+ * Single source of truth for the terminal tool states, shared by the repair
698
+ * pass and the backstop detector so they cannot drift. Mirror the AI SDK's
699
+ * terminal states: `convertToModelMessages` emits a `tool-result` for
700
+ * `output-available`, `output-error`, AND `output-denied` (a user-denied
701
+ * approval — its denial reason becomes the tool-result). Omitting any of
702
+ * these makes repair re-flip the part every turn — clobbering a real
703
+ * `errorText`/denial with the generic "interrupted" message — and makes the
704
+ * backstop falsely drop a valid call.
705
+ */
706
+ private _toolPartHasSettledResult;
707
+ /**
708
+ * Tool-call ids that still have no recorded result. After repair this should
709
+ * be empty; a non-empty result means the backstop (`ignoreIncompleteToolCalls`)
710
+ * will drop those calls — i.e. repair missed a shape and should be extended.
711
+ *
712
+ * `approval-responded` is deliberately excluded: an approved server tool has
713
+ * no result *yet*, but it is not incomplete or abandoned — it is waiting for
714
+ * its continuation to run `execute()`. `convertToModelMessages` keeps that
715
+ * call (and the SDK executes it), so flagging it here would log a misleading
716
+ * "repair gap" warning and emit a spurious `chat:transcript:repaired` event
717
+ * on every approval continuation.
718
+ */
719
+ private _incompleteToolCallIds;
720
+ /**
721
+ * Repair a single interrupted tool call — a tool part with no settled result,
722
+ * left behind when a stream was cut off mid-flight. Returns the replacement
723
+ * part that takes its place in the transcript. `input` has already been
724
+ * normalized to a valid object.
725
+ *
726
+ * The default flips it to an errored tool result so the record survives (no
727
+ * "disappearing" tool call) and `convertToModelMessages` still gets a
728
+ * tool-result for it (avoiding `AI_MissingToolResultsError`).
729
+ *
730
+ * Override to customize the repaired shape for client-resolved tools — e.g.
731
+ * convert an interrupted `ask_user` (a question with no server `execute`,
732
+ * normally answered by the user's next message) into a plain text part
733
+ * carrying the question prose, so the model sees it as ordinary conversation
734
+ * rather than a tool error and compaction keeps the question verbatim. This
735
+ * runs DURING transcript repair — before the repaired transcript is persisted
736
+ * and sent to the model — so the conversion shapes the current turn, not just
737
+ * the next one. A returned tool part MUST carry a settled result
738
+ * (`output-available` / `output-error` / `output-denied` or an
739
+ * `output`/`result` field); returning a non-tool part (e.g. text) is fine.
740
+ */
741
+ protected repairInterruptedToolPart(
742
+ part: UIMessage["parts"][number]
743
+ ): UIMessage["parts"][number];
744
+ private _repairToolTranscriptParts;
745
+ private _repairTranscriptForProvider;
746
+ /** Replace the live cache with a durable storage snapshot. */
747
+ private _replaceCachedMessages;
748
+ /** Refresh the live cache from durable storage at a safe boundary. */
749
+ private _syncMessages;
750
+ /** Patch or append one message in the live cache after a durable write. */
751
+ private _upsertCachedMessage;
752
+ /** Patch a message that is already present in the live cache. */
753
+ private _patchCachedMessage;
754
+ private _appendMessageToHistory;
755
+ private _updateMessageInHistory;
756
+ private _upsertMessageInHistory;
757
+ private _clearHistory;
758
+ /** Append a message while keeping Think's live message cache coherent. */
759
+ protected appendMessageToHistory(
760
+ message: UIMessage,
761
+ parentId?: string | null
762
+ ): Promise<UIMessage>;
763
+ /** Update a message while keeping Think's live message cache coherent. */
764
+ protected updateMessageInHistory(message: UIMessage): Promise<UIMessage>;
765
+ /** Refresh Think's live message cache from the durable session path. */
766
+ protected syncMessagesFromStorage(): Promise<UIMessage[]>;
767
+ private _aborts;
768
+ private _turnQueue;
769
+ protected _resumableStream: ResumableStream;
770
+ private _pendingResumeConnections;
771
+ private _lastClientTools;
772
+ private _lastBody;
773
+ private _continuation;
774
+ private _continuationTimer;
775
+ private _continuationBarrierActive;
776
+ private _insideResponseHook;
777
+ private _insideInferenceLoop;
778
+ private _pendingInteractionPromise;
779
+ private _submitConcurrency;
780
+ private static MESSAGE_DEBOUNCE_MS;
781
+ private _agentToolForwarders;
782
+ private _agentToolClosers;
783
+ private _agentToolAbortControllers;
784
+ private _agentToolLastErrors;
785
+ private _agentToolPreTurnAssistantIds;
786
+ private _agentToolLiveSequences;
787
+ private _submissionTableEnsured;
788
+ private _workflowNotificationTableEnsured;
789
+ private _declaredScheduledTasksTableEnsured;
790
+ private _drainingSubmissions;
791
+ private _drainingWorkflowNotifications;
792
+ private _submissionAbortControllers;
793
+ private _programmaticStreamErrors;
794
+ protected static submissionRecoveryStaleMs: number;
795
+ broadcast(
796
+ msg: string | ArrayBuffer | ArrayBufferView,
797
+ without?: string[]
798
+ ): void;
799
+ alarm(): Promise<void>;
800
+ /**
801
+ * Persist an arbitrary JSON-serializable configuration object for this
802
+ * agent instance. Stored in the Think-private `think_config` table —
803
+ * survives
804
+ * restarts and hibernation. Pass the config shape as a method generic
805
+ * for typed call sites:
806
+ *
807
+ * ```ts
808
+ * this.configure<MyConfig>({ modelTier: "fast" });
809
+ * ```
810
+ *
811
+ * Prefer `state` / `setState` from `Agent` when you want the value
812
+ * broadcast to connected clients. Use `configure` for private
813
+ * per-instance config that should stay server-side.
814
+ */
815
+ configure<T = Record<string, unknown>>(config: T): void;
816
+ /**
817
+ * Read the persisted configuration, or null if never configured.
818
+ * Pass the config shape as a method generic for a typed result:
819
+ *
820
+ * ```ts
821
+ * const cfg = this.getConfig<MyConfig>();
822
+ * ```
823
+ */
824
+ getConfig<T = Record<string, unknown>>(): T | null;
825
+ protected _migrateLegacyConfigToThinkTable(): void;
826
+ private _ensureConfigTable;
827
+ private _configSet;
828
+ private _configGet;
829
+ private _configDelete;
830
+ /**
831
+ * Return the language model to use for inference.
832
+ * Must be overridden by subclasses.
833
+ */
834
+ getModel(): LanguageModel;
835
+ /**
836
+ * Return the system prompt for the assistant.
837
+ * Used as fallback when no context blocks are configured via `configureSession`.
838
+ */
839
+ getSystemPrompt(): string;
840
+ /** Return the tools available to the assistant. */
841
+ getTools(): ToolSet;
842
+ /** Return messenger integrations that should be routed through this Think agent. */
843
+ getMessengers(): ThinkMessengers;
844
+ getMessengerContext(): MessengerContext | undefined;
845
+ chatWithMessengerContext(
846
+ userMessage: string | UIMessage,
847
+ callback: StreamCallback,
848
+ context: MessengerContext,
849
+ options?: ChatOptions
850
+ ): Promise<void>;
851
+ private _initializeMessengers;
852
+ /** Return code-declared scheduled tasks for this agent. */
853
+ getScheduledTasks(): ThinkScheduledTasks | Promise<ThinkScheduledTasks>;
854
+ /**
855
+ * Reconcile code-declared scheduled tasks immediately.
856
+ * Static declarations are reconciled on startup automatically; call this
857
+ * after changing app-owned data that `getScheduledTasks()` reads.
858
+ */
859
+ internal_reconcileScheduledTasks(): Promise<void>;
860
+ /**
861
+ * Return the default timezone for wall-clock scheduled tasks.
862
+ * Task-local timezone declarations take precedence.
863
+ */
864
+ getDefaultTimezone(): string | undefined | Promise<string | undefined>;
865
+ private _runChatRecoveryFiber;
866
+ private _systemPromptForTurn;
867
+ private _buildThinkCapabilityBlock;
868
+ /** Maximum number of tool-call steps per turn. Override via property or per-turn via TurnConfig. */
869
+ maxSteps: number;
870
+ /**
871
+ * Whether reasoning chunks are sent to chat clients by default. Override
872
+ * per turn by returning `sendReasoning` from `beforeTurn`.
873
+ */
874
+ sendReasoning: boolean;
875
+ /**
876
+ * Inactivity watchdog for the streaming read loop, in milliseconds.
877
+ *
878
+ * If a turn's model stream produces no chunk for this long, the watchdog
879
+ * aborts the turn and surfaces a terminal stream error instead of letting the
880
+ * loop park forever on a hung provider/transport (the "infinite spinner"
881
+ * failure: the stream never throws, so no error and no `done` ever arrives).
882
+ * A `chat:stream:stalled` observability event is emitted when it fires.
883
+ *
884
+ * This measures the gap *between UI-message-stream chunks*, which includes
885
+ * time spent executing server-side tools (no chunks flow while a tool runs).
886
+ * Set it comfortably above your slowest expected model time-to-first-token
887
+ * and your slowest tool execution, or you will abort healthy long turns.
888
+ *
889
+ * Default `0` (disabled) — opt in by setting a value (e.g. `120_000`).
890
+ *
891
+ * Can be overridden per-turn via `TurnConfig.chatStreamStallTimeoutMs`
892
+ * (returned from `beforeTurn`) for turns with known-slow tools.
893
+ */
894
+ chatStreamStallTimeoutMs: number;
895
+ /**
896
+ * Per-turn stall-watchdog timeout resolved from `TurnConfig` in
897
+ * `_runInferenceLoop`, read by the stream loop when arming the watchdog.
898
+ * `undefined` falls back to the instance-level `chatStreamStallTimeoutMs`.
899
+ * Turns are serialized, so a single active value is safe; it is reset at the
900
+ * top of every `_runInferenceLoop`.
901
+ */
902
+ private _activeStallTimeoutMs;
903
+ /**
904
+ * Configure the session. Called once during `onStart`.
905
+ * Override to add context blocks, compaction, search, skills.
906
+ *
907
+ * @example
908
+ * ```typescript
909
+ * configureSession(session: Session) {
910
+ * return session
911
+ * .withContext("memory", { description: "Learned facts", maxTokens: 2000 })
912
+ * .withCachedPrompt();
913
+ * }
914
+ * ```
915
+ */
916
+ configureSession(session: Session): Session | Promise<Session>;
917
+ /**
918
+ * Return Agent Skills sources for this Think agent.
919
+ *
920
+ * Bundled skills are typically imported with the Agents Vite plugin:
921
+ *
922
+ * ```typescript
923
+ * import productSkills from "agents:skills"; // -> ./skills next to this file
924
+ * ```
925
+ *
926
+ * Sources are applied in order; the first source to register a skill name
927
+ * wins, and later collisions are skipped with a logged warning.
928
+ */
929
+ getSkills(): SkillSource[] | Promise<SkillSource[]>;
930
+ private _initializeSkills;
931
+ /**
932
+ * Log registry diagnostics (duplicate names, sources that failed to list),
933
+ * deduped by message so a new collision after a deploy still surfaces while
934
+ * the same warning is not repeated on every turn.
935
+ */
936
+ private _logSkillWarnings;
937
+ /**
938
+ * Return an optional runner that enables the `run_skill_script` tool.
939
+ *
940
+ * @experimental Skill script execution is experimental and may change
941
+ * before stabilizing.
942
+ */
943
+ getSkillScriptRunner(): SkillScriptRunner | null;
944
+ private _refreshSkillsIfChanged;
945
+ /**
946
+ * Return sandboxed extension configurations. Defines load order,
947
+ * which determines hook execution order.
948
+ * Requires `extensionLoader` to be set.
949
+ */
950
+ getExtensions(): ExtensionConfig[];
951
+ /**
952
+ * Called before `streamText` — inspect the assembled context and
953
+ * return overrides. Think assembles tools, system prompt, and messages
954
+ * internally; this hook sees the result and can override any part.
955
+ *
956
+ * Return `void` to accept all defaults.
957
+ *
958
+ * @example Switch model for continuations
959
+ * ```typescript
960
+ * beforeTurn(ctx: TurnContext) {
961
+ * if (ctx.continuation) return { model: this.cheapModel };
962
+ * }
963
+ * ```
964
+ *
965
+ * @example Restrict active tools
966
+ * ```typescript
967
+ * beforeTurn(ctx: TurnContext) {
968
+ * return { activeTools: ["read", "write"] };
969
+ * }
970
+ * ```
971
+ */
972
+ beforeTurn(_ctx: TurnContext): TurnConfig | void | Promise<TurnConfig | void>;
973
+ /**
974
+ * Called before each AI SDK step in the agentic loop. Backed by
975
+ * `streamText({ prepareStep })`.
976
+ *
977
+ * Return `void` to accept the current step defaults, or return a
978
+ * `StepConfig` to override the model, tool choice, active tools,
979
+ * system prompt, messages, experimental context, or provider options
980
+ * for this step. Use `beforeTurn` for turn-wide assembly and
981
+ * `beforeStep` when the decision depends on the step number or
982
+ * previous step results.
983
+ *
984
+ * @example Force search on the first step
985
+ * ```typescript
986
+ * beforeStep(ctx: PrepareStepContext) {
987
+ * if (ctx.stepNumber === 0) {
988
+ * return {
989
+ * activeTools: ["search"],
990
+ * toolChoice: { type: "tool", toolName: "search" }
991
+ * };
992
+ * }
993
+ * }
994
+ * ```
995
+ *
996
+ * @example Switch to a cheaper model after tool results land
997
+ * ```typescript
998
+ * beforeStep(ctx: PrepareStepContext) {
999
+ * // assumes a `fastSummaryModel` field on your Think subclass
1000
+ * if (ctx.steps.some((s) => s.toolResults.length > 0)) {
1001
+ * return { model: this.fastSummaryModel };
1002
+ * }
1003
+ * }
1004
+ * ```
1005
+ */
1006
+ beforeStep(
1007
+ _ctx: PrepareStepContext
1008
+ ): StepConfig | void | Promise<StepConfig | void>;
1009
+ /**
1010
+ * Called **before** the tool's `execute` function runs. Think wraps
1011
+ * every tool's `execute` so it can consult this hook and act on the
1012
+ * returned `ToolCallDecision`:
1013
+ *
1014
+ * - `void` (or `{ action: "allow" }` with no `input`) — run the
1015
+ * original `execute` with the original input.
1016
+ * - `{ action: "allow", input }` — run the original `execute` with
1017
+ * the substituted input.
1018
+ * - `{ action: "block", reason }` — skip `execute`; the model sees
1019
+ * `reason` as the tool's output.
1020
+ * - `{ action: "substitute", output }` — skip `execute`; the model
1021
+ * sees `output` as the tool's output.
1022
+ *
1023
+ * Only fires for server-side tools (tools with `execute`). Client
1024
+ * tools are handled on the client — Think can't intercept them.
1025
+ *
1026
+ * `afterToolCall` always fires after this hook (or after the original
1027
+ * `execute` when `allow`). For `block`/`substitute`, the substituted
1028
+ * value flows through `afterToolCall` as `success: true, output: ...`.
1029
+ *
1030
+ * @example Log tool calls
1031
+ * ```typescript
1032
+ * beforeToolCall(ctx: ToolCallContext) {
1033
+ * console.log(`Tool called: ${ctx.toolName}`, ctx.input);
1034
+ * }
1035
+ * ```
1036
+ *
1037
+ * @example Block a tool the model shouldn't be calling here
1038
+ * ```typescript
1039
+ * beforeToolCall(ctx: ToolCallContext): ToolCallDecision | void {
1040
+ * if (ctx.toolName === "delete" && this.isReadOnlyMode) {
1041
+ * return { action: "block", reason: "delete is disabled in read-only mode" };
1042
+ * }
1043
+ * }
1044
+ * ```
1045
+ *
1046
+ * @example Substitute a cached result
1047
+ * ```typescript
1048
+ * async beforeToolCall(ctx: ToolCallContext): Promise<ToolCallDecision | void> {
1049
+ * if (ctx.toolName === "weather") {
1050
+ * const cached = await this.cache.get(JSON.stringify(ctx.input));
1051
+ * if (cached) return { action: "substitute", output: cached };
1052
+ * }
1053
+ * }
1054
+ * ```
1055
+ */
1056
+ beforeToolCall(
1057
+ _ctx: ToolCallContext
1058
+ ): ToolCallDecision | void | Promise<ToolCallDecision | void>;
1059
+ /**
1060
+ * Called **after** a tool's outcome is known — for real executions, for
1061
+ * `block` (carries the `reason` as `output`), and for `substitute`
1062
+ * (carries the substituted `output`). Backed by the AI SDK's
1063
+ * `experimental_onToolCallFinish`, so `durationMs` and the discriminated
1064
+ * `success`/`output`/`error` outcome reflect what the model actually
1065
+ * sees: a thrown error from the original `execute` becomes
1066
+ * `success: false, error: ...`; everything else (including blocked /
1067
+ * substituted calls) is `success: true, output: ...`.
1068
+ *
1069
+ * Override for logging, metrics, or result inspection.
1070
+ *
1071
+ * @example
1072
+ * ```typescript
1073
+ * afterToolCall(ctx: ToolCallResultContext) {
1074
+ * if (ctx.success) {
1075
+ * console.log(`${ctx.toolName} ok in ${ctx.durationMs}ms`);
1076
+ * } else {
1077
+ * console.error(`${ctx.toolName} failed:`, ctx.error);
1078
+ * }
1079
+ * }
1080
+ * ```
1081
+ */
1082
+ afterToolCall(_ctx: ToolCallResultContext): void | Promise<void>;
1083
+ /**
1084
+ * Called after each step completes (initial, continue, tool-result).
1085
+ * Override for step-level logging or analytics.
1086
+ */
1087
+ onStepFinish(_ctx: StepContext): void | Promise<void>;
1088
+ /**
1089
+ * Called for each streaming chunk. High-frequency — fires per token.
1090
+ * Override for streaming analytics, progress indicators, or token counting.
1091
+ * Observational only (void return).
1092
+ */
1093
+ onChunk(_ctx: ChunkContext): void | Promise<void>;
1094
+ /**
1095
+ * Called after a chat turn completes and the assistant message has been
1096
+ * persisted. The turn lock is released before this hook runs, so it is
1097
+ * safe to call other methods from inside.
1098
+ *
1099
+ * Fires for all turn completion paths: WebSocket chat requests,
1100
+ * sub-agent RPC, and auto-continuation.
1101
+ *
1102
+ * Override for logging, chaining, analytics, usage tracking.
1103
+ */
1104
+ onChatResponse(_result: ChatResponseResult): void | Promise<void>;
1105
+ /**
1106
+ * Handle an error that occurred during a chat turn.
1107
+ * Override to customize error handling (e.g. logging, metrics).
1108
+ */
1109
+ onChatError(error: unknown, _ctx?: ChatErrorContext): unknown;
1110
+ private _initializeExtensions;
1111
+ /**
1112
+ * The single convergence point for all chat turn entry paths.
1113
+ * Merges tools, assembles context, fires lifecycle hooks, wraps tools
1114
+ * for interception, and calls streamText.
1115
+ */
1116
+ private _runInferenceLoop;
1117
+ /** @internal Test seam — override in test agents to wrap the stream (e.g. error injection). */
1118
+ protected _transformInferenceResult(
1119
+ result: StreamableResult
1120
+ ): StreamableResult;
1121
+ /** Default hook timeout in milliseconds. */
1122
+ hookTimeout: number;
1123
+ /**
1124
+ * Pipeline beforeTurn through sandboxed extensions in load order.
1125
+ * Each extension sees the accumulated state from prior extensions
1126
+ * (snapshot is rebuilt after each extension's modifications).
1127
+ * Results are merged with last-write-wins for scalar fields.
1128
+ * Extensions that don't subscribe to beforeTurn are skipped.
1129
+ */
1130
+ private _pipelineExtensionBeforeTurn;
1131
+ /**
1132
+ * Dispatch an observation hook to all extensions that subscribe to it.
1133
+ *
1134
+ * Used by `_pipelineExtensionToolCallStart`, `_pipelineExtensionToolCallFinish`,
1135
+ * `_pipelineExtensionStepFinish`, and `_pipelineExtensionChunk`. Unlike
1136
+ * `beforeTurn`, these hooks are observation-only — extensions can't
1137
+ * influence the turn — so we ignore return values, log errors, and
1138
+ * apply a per-extension timeout.
1139
+ *
1140
+ * `onChunk` is high-frequency (per token) — extensions that subscribe
1141
+ * to it pay an RPC cost per chunk and should be used sparingly.
1142
+ */
1143
+ private _dispatchExtensionObservation;
1144
+ /**
1145
+ * Wrap each tool's `execute` function so the agent's `beforeToolCall`
1146
+ * hook is consulted before the tool runs. The hook can return a
1147
+ * `ToolCallDecision` to:
1148
+ *
1149
+ * - `allow` (default if `void` is returned) — run the original
1150
+ * `execute`, optionally with a substituted `input`.
1151
+ * - `block` — skip `execute` and return `reason` (or a default string)
1152
+ * as the tool result. The model sees this as the tool's output.
1153
+ * - `substitute` — skip `execute` and return `output` directly. The
1154
+ * model sees this as the tool's output.
1155
+ *
1156
+ * The wrapped `execute` also dispatches the `beforeToolCall`
1157
+ * observation snapshot to subscribed extensions. `afterToolCall` is
1158
+ * still wired through the AI SDK's `experimental_onToolCallFinish`
1159
+ * callback so we get accurate `durationMs` and proper success/error
1160
+ * discrimination — `block` and `substitute` outcomes show up as
1161
+ * `success: true` with the substituted output; uncaught throws from
1162
+ * the original `execute` show up as `success: false` with the error.
1163
+ *
1164
+ * Tools without an `execute` (output-schema-only tools, client tools
1165
+ * routed via `needsApproval`) are left untouched.
1166
+ *
1167
+ * **Streaming tools (AsyncIterable):** the AI SDK supports tools whose
1168
+ * `execute` returns `AsyncIterable<output>` to emit preliminary
1169
+ * results before a final value. This works whether the iterator is
1170
+ * returned directly (sync function, `async function*`) or wrapped in
1171
+ * a Promise (`async function execute(...) { return makeIter(); }`).
1172
+ * Because the wrapper must `await beforeToolCall` first, preliminary
1173
+ * chunks are collapsed — only the *final* yielded value reaches the
1174
+ * model. If you need true preliminary streaming, override
1175
+ * `getTools()` to provide such tools and avoid using `beforeToolCall`
1176
+ * for them (or accept the collapse).
1177
+ */
1178
+ private _wrapToolsWithDecision;
1179
+ private _pipelineExtensionToolCallStart;
1180
+ private _pipelineExtensionToolCallFinish;
1181
+ private _pipelineExtensionStepFinish;
1182
+ private _pipelineExtensionChunk;
1183
+ _hostReadFile(path: string): Promise<string | null>;
1184
+ _hostWriteFile(path: string, content: string): Promise<void>;
1185
+ _hostDeleteFile(path: string): Promise<boolean>;
1186
+ _hostListFiles(dir: string): Promise<
1187
+ Array<{
1188
+ name: string;
1189
+ type: string;
1190
+ size: number;
1191
+ path: string;
1192
+ }>
1193
+ >;
1194
+ _hostGetContext(label: string): Promise<string | null>;
1195
+ _hostSetContext(label: string, content: string): Promise<void>;
1196
+ _hostGetMessages(limit?: number): Promise<
1197
+ Array<{
1198
+ id: string;
1199
+ role: string;
1200
+ content: string;
1201
+ }>
1202
+ >;
1203
+ _hostSendMessage(content: string): Promise<void>;
1204
+ _hostGetSessionInfo(): Promise<{
1205
+ messageCount: number;
1206
+ }>;
1207
+ /**
1208
+ * Run a chat turn: persist the user message, run the agentic loop,
1209
+ * stream UIMessageChunk events via callback, and persist the
1210
+ * assistant's response.
1211
+ *
1212
+ * @param userMessage The user's message (string or UIMessage)
1213
+ * @param callback Streaming callback (typically an RpcTarget from the parent)
1214
+ * @param options Optional chat options (e.g. AbortSignal)
1215
+ */
1216
+ chat(
1217
+ userMessage: string | UIMessage,
1218
+ callback: StreamCallback,
1219
+ options?: ChatOptions
1220
+ ): Promise<void>;
1221
+ /** Get the conversation history as UIMessage[]. */
1222
+ getMessages(): Promise<UIMessage[]>;
1223
+ /** Clear all messages from storage. */
1224
+ clearMessages(): Promise<void>;
1225
+ private _ensureAgentToolChildRunTable;
1226
+ private _addAgentToolChildRunColumnIfMissing;
1227
+ private _readAgentToolChildRun;
1228
+ private _inspectionFromChildRow;
1229
+ protected formatAgentToolInput(input: unknown): UIMessage;
1230
+ protected getAgentToolOutput(_runId: string): unknown;
1231
+ protected getAgentToolSummary(runId: string, output: unknown): string;
1232
+ startAgentToolRun(
1233
+ input: unknown,
1234
+ options: {
1235
+ runId: string;
1236
+ }
1237
+ ): Promise<AgentToolRunInspection>;
1238
+ cancelAgentToolRun(runId: string, reason?: unknown): Promise<void>;
1239
+ /**
1240
+ * Classify any in-flight chat-recovery on this child facet (#1630). A child
1241
+ * facet is dedicated to a single agent-tool run, so any recovery incident is
1242
+ * that run's. `detected`/`scheduled`/`attempting` mean recovery is still
1243
+ * resolving the interrupted turn; `exhausted`/`failed` mean it gave up; a
1244
+ * completed recovery deletes its incident.
1245
+ */
1246
+ private _classifyAgentToolChildRecovery;
1247
+ inspectAgentToolRun(runId: string): Promise<AgentToolRunInspection | null>;
1248
+ private _isStaleAgentToolChildRun;
1249
+ /**
1250
+ * Reconcile a stale (post-eviction) child run row from the child's own
1251
+ * durable recovery (#1630). The child facet self-heals its interrupted turn
1252
+ * via `chatRecovery`, but that path never writes the run row, so without this
1253
+ * the row strands `running` and the parent can only collect `interrupted`.
1254
+ *
1255
+ * Persisting the terminal here (rather than only computing it) is intentional:
1256
+ * it's a lazy materialization of the run's true terminal that also lets a
1257
+ * tailing parent's stream close promptly and makes subsequent inspects cheap.
1258
+ * While recovery is still resolving (active stream or in-progress incident)
1259
+ * the row is left `running` so the parent's bounded re-attach keeps waiting.
1260
+ */
1261
+ private _reconcileStaleAgentToolChildRun;
1262
+ /** Release a re-attached run's live tail + per-run streaming bookkeeping. */
1263
+ private _finalizeAgentToolChildRunTailers;
1264
+ getAgentToolChunks(
1265
+ runId: string,
1266
+ options?: {
1267
+ afterSequence?: number;
1268
+ }
1269
+ ): Promise<AgentToolStoredChunk[]>;
1270
+ tailAgentToolRun(
1271
+ runId: string,
1272
+ options?: {
1273
+ afterSequence?: number;
1274
+ signal?: AbortSignal;
1275
+ }
1276
+ ): Promise<ReadableStream<AgentToolStoredChunk>>;
1277
+ private static _stringifyAgentToolOutput;
1278
+ private static _parseAgentToolOutput;
1279
+ /**
1280
+ * Whether the run produced an assistant turn (text or tool-only). Used by the
1281
+ * post-eviction reconcile to mark a settled run `completed` even when it ended
1282
+ * without final text. A dedicated child facet starts with no assistant
1283
+ * messages, so a missing in-memory pre-turn snapshot is treated as empty.
1284
+ */
1285
+ private _hasRecoveredAgentToolAssistantTurn;
1286
+ private _getAgentToolFinalText;
1287
+ private _ensureDeclaredScheduledTasksTable;
1288
+ private _readDeclaredScheduledTaskRow;
1289
+ private _listDeclaredScheduledTaskRows;
1290
+ private _updateDeclaredScheduledTaskSchedule;
1291
+ private _normalizeDeclaredScheduledTasks;
1292
+ private _declaredScheduledTasksForNow;
1293
+ private _declaredScheduleOwnerKey;
1294
+ private _declaredScheduleValidationError;
1295
+ private _nextDeclaredScheduleTimeForConfig;
1296
+ private _reconcileDeclaredScheduledTasks;
1297
+ private _scheduleDeclaredTaskOccurrence;
1298
+ private _scheduleDeclaredTaskOccurrenceAt;
1299
+ private _advanceDeclaredScheduledTask;
1300
+ private _declaredScheduledTaskContext;
1301
+ _runDeclaredScheduledTask(
1302
+ payload: DeclaredScheduledTaskPayload
1303
+ ): Promise<void>;
1304
+ private _ensureSubmissionTable;
1305
+ private _ensureWorkflowNotificationTable;
1306
+ private _readSubmission;
1307
+ private _readSubmissionByIdempotencyKey;
1308
+ private _normalizeStatusFilter;
1309
+ private _listSubmissionRows;
1310
+ private _listSubmissionRowsByStatus;
1311
+ private _inspectionFromSubmissionRow;
1312
+ private _parseJsonObject;
1313
+ private _parseSubmissionMessages;
1314
+ private _serializeSubmissionMessages;
1315
+ private _serializeMetadata;
1316
+ private _readWorkflowPromptContext;
1317
+ private _emitSubmissionStatus;
1318
+ protected onSubmissionStatus(
1319
+ _submission: ThinkSubmissionInspection
1320
+ ): void | Promise<void>;
1321
+ private _enqueueWorkflowNotification;
1322
+ private _insertWorkflowNotification;
1323
+ private _recoverWorkflowNotifications;
1324
+ private _startWorkflowNotificationDrain;
1325
+ private _drainWorkflowNotifications;
1326
+ private _scheduleWorkflowNotificationAlarm;
1327
+ inspectSubmission(
1328
+ submissionId: string
1329
+ ): Promise<ThinkSubmissionInspection | null>;
1330
+ listSubmissions(
1331
+ options?: ListSubmissionsOptions
1332
+ ): Promise<ThinkSubmissionInspection[]>;
1333
+ deleteSubmission(submissionId: string): Promise<boolean>;
1334
+ deleteSubmissions(options?: DeleteSubmissionsOptions): Promise<number>;
1335
+ private _listTerminalSubmissionRowsForDelete;
1336
+ private _isTerminalSubmissionStatus;
1337
+ cancelSubmission(submissionId: string, reason?: unknown): Promise<void>;
1338
+ submitMessages(
1339
+ messages: UIMessage[],
1340
+ options?: SubmitMessagesOptions
1341
+ ): Promise<SubmitMessagesResult>;
1342
+ private _scheduleSubmissionDrain;
1343
+ private _startSubmissionDrain;
1344
+ _drainThinkSubmissions(): Promise<void>;
1345
+ private _drainSubmissions;
1346
+ private _runSubmission;
1347
+ private _getSubmissionFinalStatus;
1348
+ private _markPendingSubmissionsSkipped;
1349
+ private _emitSkippedSubmissions;
1350
+ private _recoverSubmissionsOnStart;
1351
+ private _getSubmissionMessagesAppliedState;
1352
+ private _hasRecoverableChatTurn;
1353
+ private _hasFreshRecoverableSubmissionEvidence;
1354
+ private _hasScheduledRecoveredContinuation;
1355
+ /**
1356
+ * Inject messages and trigger a model turn — without a WebSocket request.
1357
+ *
1358
+ * Use for scheduled responses, webhook-triggered turns, proactive agents,
1359
+ * or chaining from `onChatResponse`.
1360
+ *
1361
+ * Accepts static messages or a callback that derives messages from the
1362
+ * current state (useful when multiple calls queue up — the callback runs
1363
+ * with the latest messages when the turn actually starts).
1364
+ *
1365
+ * Pass `options.signal` to cancel the turn from outside without knowing
1366
+ * the internally-generated request id. The signal is linked to the
1367
+ * registry's controller for this turn — when it aborts, the inference
1368
+ * loop's signal aborts and the result reports `status: "aborted"`.
1369
+ * Pre-aborted signals short-circuit before any model work runs. See
1370
+ * {@link SaveMessagesOptions} for the integration point.
1371
+ *
1372
+ * @example Scheduled follow-up
1373
+ * ```typescript
1374
+ * async onScheduled() {
1375
+ * await this.saveMessages([{
1376
+ * id: crypto.randomUUID(),
1377
+ * role: "user",
1378
+ * parts: [{ type: "text", text: "Time for your daily summary." }]
1379
+ * }]);
1380
+ * }
1381
+ * ```
1382
+ *
1383
+ * @example Function form
1384
+ * ```typescript
1385
+ * await this.saveMessages((current) => [
1386
+ * ...current,
1387
+ * { id: crypto.randomUUID(), role: "user", parts: [{ type: "text", text: "Continue." }] }
1388
+ * ]);
1389
+ * ```
1390
+ *
1391
+ * @example External cancellation (helper-as-sub-agent)
1392
+ * ```typescript
1393
+ * // Inside a parent agent's tool execute — forward the AI SDK's
1394
+ * // abortSignal so a parent stop / tab close cancels the helper.
1395
+ * await helper.saveMessages([userMsg], { signal: abortSignal });
1396
+ * ```
1397
+ */
1398
+ saveMessages(
1399
+ messages:
1400
+ | UIMessage[]
1401
+ | ((currentMessages: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>),
1402
+ options?: SaveMessagesOptions
1403
+ ): Promise<SaveMessagesResult>;
1404
+ private _runProgrammaticMessagesTurn;
1405
+ /**
1406
+ * Run a new LLM call following the last assistant message.
1407
+ *
1408
+ * The model sees the full conversation (including the last assistant
1409
+ * response) and generates a new response. The new response is persisted
1410
+ * as a separate assistant message. Building block for chat recovery
1411
+ * (Phase 4), "generate more" buttons, and self-correction.
1412
+ *
1413
+ * Note: this creates a new message, not an append to the existing one.
1414
+ * True continuation-as-append (chunk rewriting) is planned for Phase 4.
1415
+ *
1416
+ * Returns early with `status: "skipped"` if there is no assistant message
1417
+ * to continue from.
1418
+ *
1419
+ * Pass `options.signal` to cancel the continuation from outside —
1420
+ * matches the {@link saveMessages} contract.
1421
+ */
1422
+ protected continueLastTurn(
1423
+ body?: Record<string, unknown>,
1424
+ options?: SaveMessagesOptions
1425
+ ): Promise<SaveMessagesResult>;
1426
+ private _retryLastUserTurn;
1427
+ private _setupProtocolHandlers;
1428
+ private _handleProtocolEvent;
1429
+ private _handleStreamResumeRequest;
1430
+ private _handleStreamResumeAck;
1431
+ private _handleChatRequest;
1432
+ /**
1433
+ * Abort the active turn, invalidate queued turns, and reset
1434
+ * concurrency/continuation state. Call this when intercepting
1435
+ * clear events or implementing custom reset logic.
1436
+ *
1437
+ * Does NOT clear messages, streams, or persisted state —
1438
+ * only turn execution state.
1439
+ */
1440
+ protected resetTurnState(): void;
1441
+ /**
1442
+ * Abort a single in-flight chat turn by request id.
1443
+ *
1444
+ * Equivalent to the cancel path that fires when a client sends a
1445
+ * `chat-request-cancel` WebSocket message — the inference loop's
1446
+ * signal aborts, partial chunks already streamed are still
1447
+ * persisted, and the turn's `ChatResponseResult` reports
1448
+ * `status: "aborted"`.
1449
+ *
1450
+ * No-op if no controller exists for `requestId` (the turn already
1451
+ * completed, was never started, or used a different id).
1452
+ *
1453
+ * `chat()` callers can read the request id from
1454
+ * {@link StreamCallback.onStart} and later pass it here from another
1455
+ * RPC call.
1456
+ *
1457
+ * Prefer {@link SaveMessagesOptions.signal} when driving a turn
1458
+ * programmatically — it threads the abort intent in from the start
1459
+ * without requiring the caller to know the id.
1460
+ */
1461
+ cancelChat(requestId: string, reason?: string): void;
1462
+ /** Abort every in-flight chat turn on this agent. */
1463
+ cancelAllChats(): void;
1464
+ protected abortRequest(requestId: string, reason?: unknown): void;
1465
+ /**
1466
+ * Abort every in-flight chat turn on this agent.
1467
+ *
1468
+ * Aborts all controllers in the registry and clears it. Used by
1469
+ * subclasses that drive single-purpose turns (e.g. a sub-agent
1470
+ * helper that runs one turn at a time over RPC) and want a coarse
1471
+ * "cancel whatever is running" handle without tracking request ids.
1472
+ *
1473
+ * Does NOT reset queued turns, continuation timers, or submit
1474
+ * concurrency state — use {@link resetTurnState} for the full
1475
+ * teardown that runs on `chat-clear`.
1476
+ */
1477
+ protected abortAllRequests(): void;
1478
+ private _handleClear;
1479
+ private _streamResultToRpcCallback;
1480
+ /**
1481
+ * Whether storing this chunk should immediately flush the resumable-stream
1482
+ * buffer to SQLite.
1483
+ *
1484
+ * A settled tool result (`tool-output-available` / `tool-output-error` /
1485
+ * `tool-output-denied`) captures a completed, often non-idempotent side
1486
+ * effect — or, for a denial, a user decision — so it is flushed
1487
+ * **immediately**. An isolate eviction (deploy) before the next batch flush
1488
+ * would otherwise lose it, and recovery would re-anchor without it and re-run
1489
+ * the already-completed tool call (or drop the denial). Frequent recoverable
1490
+ * content (text / reasoning / tool-input streaming) is throttled to avoid
1491
+ * write amplification.
1492
+ */
1493
+ private _shouldFlushRecoverableChunk;
1494
+ /**
1495
+ * Store a stream chunk, flushing settled tool results durably and promptly.
1496
+ * Shared by the WebSocket and sub-agent RPC streaming paths so both get
1497
+ * tool-call-level recovery durability (recovery loses at most the in-flight
1498
+ * step, never an already-completed tool call).
1499
+ */
1500
+ private _storeChunkDurably;
1501
+ /**
1502
+ * Wrap a UI-message stream with an inactivity watchdog. If no chunk arrives
1503
+ * within `timeoutMs`, `onStall` runs (aborting the upstream model stream) and
1504
+ * the iterator throws, so the consumer loop exits with a terminal error
1505
+ * instead of parking forever on a hung provider/transport. `timeoutMs <= 0`
1506
+ * passes the source through untouched.
1507
+ */
1508
+ private _iterateWithStallWatchdog;
1509
+ private _streamResult;
1510
+ private _persistAssistantMessage;
1511
+ /**
1512
+ * Persist an incoming message after reconciliation. For assistant
1513
+ * messages, also resolve their ID against any server-side row that
1514
+ * already owns the same `toolCallId` so we update the existing row
1515
+ * instead of inserting an orphan duplicate.
1516
+ */
1517
+ private _persistIncomingMessage;
1518
+ private _persistClientTools;
1519
+ private _restoreClientTools;
1520
+ private _persistBody;
1521
+ private _restoreBody;
1522
+ private _applyToolResult;
1523
+ private _applyToolApproval;
1524
+ private _applyToolUpdateToMessages;
1525
+ protected hasPendingInteraction(): boolean;
1526
+ protected waitUntilStable(options?: { timeout?: number }): Promise<boolean>;
1527
+ private _awaitWithDeadline;
1528
+ private _messageHasPendingInteraction;
1529
+ private _resolveChatRecoveryConfig;
1530
+ private _chatRecoveryIncidentId;
1531
+ private _chatRecoveryIncidentKey;
1532
+ /**
1533
+ * Monotonic forward-progress signal for recovery budget resets.
1534
+ *
1535
+ * This used to count assistant messages in `this.messages`, but that is
1536
+ * recomputed from the live, mutable transcript. Compaction collapses older
1537
+ * assistant messages into a summary, lowering the count — so a turn that had
1538
+ * genuinely advanced could read as "no progress" between attempts and exhaust
1539
+ * its budget prematurely (#1628). Instead we read a durably-persisted counter
1540
+ * that only ever increments — bumped at production time when new content is
1541
+ * durably flushed (see `_storeChunkDurably`), which is genuine forward
1542
+ * progress and is immune to client reconnects / recovery re-persists — so
1543
+ * compaction can never lower it and a reconnect can't fake it (#1637).
1544
+ */
1545
+ private _chatRecoveryProgressMarker;
1546
+ /** Advance the durable recovery-progress counter. Called from
1547
+ * `_storeChunkDurably` when new content is durably flushed (real, reconnect-
1548
+ * immune forward progress). */
1549
+ private _bumpChatRecoveryProgress;
1550
+ /** In-memory wall-clock of the last N9 child-stream progress bump (reset per
1551
+ * isolate so the first forwarded chunk after a restart always credits). */
1552
+ private _lastAgentToolStreamProgressAt;
1553
+ /**
1554
+ * N9: forwarding a sub-agent's chunks IS forward progress for this parent
1555
+ * turn, so credit the parent's recovery progress marker — otherwise a parent
1556
+ * whose turn merely `await`s a child banks no progress of its own and its
1557
+ * no-progress window exhausts while the child is healthily streaming. Only
1558
+ * invoked after a child actually produced output (see
1559
+ * `_forwardAgentToolStream`), so a silent child still lets the parent exhaust.
1560
+ * Throttled (and reset per isolate) so we never write storage per token.
1561
+ */
1562
+ protected _onAgentToolStreamProgress(): Promise<void>;
1563
+ /** Sweep recovery incidents that have been inactive past the TTL. */
1564
+ private _sweepStaleChatRecoveryIncidents;
1565
+ private _beginChatRecoveryIncident;
1566
+ private _updateChatRecoveryIncident;
1567
+ private _exhaustChatRecovery;
1568
+ /**
1569
+ * Route a stream-stall watchdog abort into bounded recovery instead of a
1570
+ * terminal error (#1626). A stall happens inside a LIVE isolate (no DO
1571
+ * restart), so the normal restart-detected recovery path never runs — we
1572
+ * open/advance a recovery incident here and schedule a continuation, reusing
1573
+ * the SAME budget (`maxAttempts` + wall-clock window + progress-aware reset)
1574
+ * as deploy/eviction recovery. A transient hang recovers; a persistently
1575
+ * hanging provider exhausts the budget. Idempotency matches deploy recovery:
1576
+ * settled tool results are durable and won't re-run, but a tool that was
1577
+ * mid-execution when the stall fired re-runs on the continuation.
1578
+ *
1579
+ * Returns:
1580
+ * - `"scheduled"` — a continuation was scheduled; the caller suppresses the
1581
+ * terminal error and closes the stream cleanly.
1582
+ * - `"exhausted"` — the budget is spent; this routes through the SAME
1583
+ * `_exhaustChatRecovery` path as deploy recovery (fires `onExhausted`,
1584
+ * emits `chat:recovery:exhausted`, marks the submission interrupted, and
1585
+ * delivers the configured `terminalMessage`). The caller must NOT run the
1586
+ * generic terminal path — the terminal UX is already delivered.
1587
+ * - `"disabled"` — chat recovery is off; the caller falls through to the
1588
+ * generic terminal error (the watchdog's original "kill the spinner"
1589
+ * behavior, unchanged).
1590
+ */
1591
+ private _routeStallToBoundedRecovery;
1592
+ protected _handleInternalFiberRecovery(
1593
+ ctx: FiberRecoveryContext
1594
+ ): Promise<boolean>;
1595
+ private _recoverablePreStreamUserId;
1596
+ private _hasPersistedRecoveredAssistant;
1597
+ /**
1598
+ * Whether the orphaned stream's partial should be materialized into an
1599
+ * assistant message: there is a stream, and it is either still active or
1600
+ * terminal-but-not-yet-persisted. Shared by the normal recovery path AND the
1601
+ * exhaustion path so neither discards settled work nor duplicates a partial
1602
+ * an earlier attempt already saved.
1603
+ */
1604
+ private _shouldPersistOrphanedPartial;
1605
+ /** Whether a reconstructed partial carries any settled (provider-accepted)
1606
+ * tool result — the completed, often non-idempotent work that a
1607
+ * `{ persist: false }` recovery return would silently discard. */
1608
+ private _partialHasSettledToolResults;
1609
+ /**
1610
+ * Reschedule a recovery callback that timed out waiting for stable state,
1611
+ * consuming one attempt. Returns `true` if rescheduled, `false` if the
1612
+ * attempt budget is exhausted (the caller then fails the turn terminally).
1613
+ *
1614
+ * Shared by `_chatRecoveryRetry` and `_chatRecoveryContinue` so the
1615
+ * non-idempotent scheduling invariant lives in exactly one place — a fix to
1616
+ * one path can't silently diverge from the other. Mirrors the same helper in
1617
+ * `@cloudflare/ai-chat`.
1618
+ */
1619
+ private _rescheduleRecoveryAfterStableTimeout;
1620
+ /**
1621
+ * Resolve the stream id for a recovery turn so the give-up terminalization
1622
+ * can surface whatever partial the turn produced. Prefers the durable stream
1623
+ * row keyed by the recovery-root request id; falls back to the live active
1624
+ * stream. Returns `""` when neither is available (the terminal banner still
1625
+ * fires — `_exhaustChatRecovery` does not require a stream).
1626
+ */
1627
+ private _resolveRecoveryStreamId;
1628
+ /**
1629
+ * Terminalize a recovery turn that has run out of stable-state-timeout retry
1630
+ * budget — or whose incident record has vanished — by routing through the
1631
+ * SAME `_exhaustChatRecovery` path as deploy-recovery and stall exhaustion
1632
+ * (#1626/#1631). It fires `onExhausted`, emits `chat:recovery:exhausted`,
1633
+ * marks the durable submission interrupted, records the terminal chat status,
1634
+ * and delivers the configured `terminalMessage`.
1635
+ *
1636
+ * This replaces the older give-up that only set the incident to `failed` and
1637
+ * completed the recovered submission as `error`, which bypassed
1638
+ * `_exhaustChatRecovery` entirely — so an app relying on `onExhausted` for the
1639
+ * terminal banner regressed to an eternal spinner when recovery gave up under
1640
+ * extreme churn (the stable-state wait timing out every attempt until the
1641
+ * budget drained). Shared by `_chatRecoveryRetry` and `_chatRecoveryContinue`.
1642
+ *
1643
+ * Exactly-once terminalization is defended by two independent guards:
1644
+ * 1. The `stored?.status === "exhausted"` re-entry guard below — once an
1645
+ * incident is sealed, a duplicate stale alarm (or retried callback)
1646
+ * returns before re-firing. The sealed incident is re-persisted even when
1647
+ * the record was found missing, so a swept record is re-armed for the
1648
+ * guard on the next alarm.
1649
+ * 2. The durable-submission paths additionally short-circuit earlier at the
1650
+ * `submission_not_running` check (the submission is already `error` after
1651
+ * the first give-up). This is the ONLY guard `@cloudflare/ai-chat` lacks
1652
+ * (no submission layer), so guard #1 carries it there.
1653
+ *
1654
+ * Two residual at-least-once edges, both deliberately accepted as "deliver a
1655
+ * second banner" ≫ "silently drop the turn":
1656
+ * • No `incidentId` at all in the payload (only reachable via a direct/test
1657
+ * invocation — every production scheduler carries one): the synthesized
1658
+ * incident can't be persisted (no key), so guard #1 can't arm.
1659
+ * • The record is swept AGAIN between two alarms (guard #1 re-persists on the
1660
+ * first, so this needs a second independent sweep) — vanishingly unlikely.
1661
+ */
1662
+ private _exhaustRecoveryAfterStableTimeout;
1663
+ _chatRecoveryRetry(data?: ChatRecoveryRetryData): Promise<void>;
1664
+ private _hasRunningSubmission;
1665
+ private _readRunningSubmissionByRequestId;
1666
+ private _markRecoveredSubmissionInterrupted;
1667
+ private _completeRecoveredSubmission;
1668
+ protected onChatRecovery(
1669
+ _ctx: ChatRecoveryContext
1670
+ ): Promise<ChatRecoveryOptions | void>;
1671
+ _chatRecoveryContinue(data?: ChatRecoveryContinueData): Promise<void>;
1672
+ private _applyRecoveredRequestContext;
1673
+ private _getPartialStreamText;
1674
+ private _getSubmitConcurrencyDecision;
1675
+ private _completeSkippedRequest;
1676
+ private _rollbackDroppedSubmit;
1677
+ private _scheduleAutoContinuation;
1678
+ private _resetAutoContinuationTimer;
1679
+ /**
1680
+ * Fire an auto-continuation, but only once the model's parallel tool-call
1681
+ * batch is fully answered (#1649). When the model emits several tool calls in
1682
+ * one step the client answers each independently, so the first `autoContinue`
1683
+ * arrives while slower siblings are still `input-available`. Continuing then
1684
+ * would feed the provider an incomplete tool-result set
1685
+ * (`MissingToolResultsError`) or, via the transcript-repair backstop, silently
1686
+ * error the in-flight sibling and run a spurious extra continuation. We hold
1687
+ * the continuation on a barrier until the batch settles. The wait is bounded
1688
+ * (`AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS`) so a genuinely orphaned tool
1689
+ * call — e.g. the client disconnected mid-batch — still falls through to the
1690
+ * repair backstop rather than pinning the continuation open forever.
1691
+ */
1692
+ private _fireAutoContinuationWhenStable;
1693
+ /**
1694
+ * Block until the latest assistant step's parallel tool batch is fully
1695
+ * answered, or `AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS` elapses. Awaits the
1696
+ * in-flight tool-result apply when one exists (so a sibling that lands
1697
+ * mid-wait is observed promptly) and polls otherwise.
1698
+ */
1699
+ private _awaitToolBatch;
1700
+ /**
1701
+ * `true` when the latest assistant message is mid-batch: it carries at least
1702
+ * one settled tool result AND at least one tool call/approval still awaiting a
1703
+ * client result. That is the #1649 signature — the model fanned out parallel
1704
+ * tool calls and only some have been answered. Scoped to the leaf (the step
1705
+ * the continuation answers) so an unrelated dangling tool in an earlier
1706
+ * message doesn't block a legitimate follow-up continuation.
1707
+ */
1708
+ private _hasIncompleteToolBatch;
1709
+ private _fireAutoContinuation;
1710
+ private _activateDeferredContinuation;
1711
+ private _fireResponseHook;
1712
+ /**
1713
+ * Persist (on `error`) or clear (on `completed`/`aborted`) a durable record of
1714
+ * the last terminal turn so it can be replayed to clients on connect. A
1715
+ * `completed`/`aborted` turn is conveyed by the persisted messages, so the
1716
+ * record is cleared; an `error`/`interrupted` turn has no durable trace
1717
+ * otherwise, so it is kept until a later turn resolves.
1718
+ */
1719
+ private _recordTerminalChatStatus;
1720
+ private _pendingTerminalChatResponse;
1721
+ /**
1722
+ * Set or clear the live "recovering…" status for a durable chat turn (#1620).
1723
+ * Persists a durable record (replayed on connect via `_buildIdleConnectMessages`)
1724
+ * and broadcasts a `MSG_CHAT_RECOVERING` frame — but only on a genuine
1725
+ * transition, so a deploy/reconnect storm (which re-detects recovery many
1726
+ * times) doesn't spam the wire. Cleared on every terminal outcome so the
1727
+ * indicator can't spin forever.
1728
+ */
1729
+ private _setChatRecovering;
1730
+ /**
1731
+ * Messages sent to a client on connect when no stream is active: the current
1732
+ * transcript, plus a replay of the last terminal error (if any) so a turn
1733
+ * that failed while the client was disconnected is surfaced rather than
1734
+ * silently frozen.
1735
+ */
1736
+ private _buildIdleConnectMessages;
1737
+ private _notifyStreamResuming;
1738
+ private _persistOrphanedStream;
1739
+ private _broadcastChat;
1740
+ private _broadcast;
1741
+ private _broadcastMessages;
1742
+ }
1743
+ //#endregion
1744
+ //#region src/messengers/events.d.ts
1745
+ type MessengerEventKind =
1746
+ | "direct-message"
1747
+ | "mention"
1748
+ | "subscribed-message"
1749
+ | "action"
1750
+ | "delivery-event";
1751
+ interface MessengerAuthor {
1752
+ fullName?: string;
1753
+ isBot?: boolean | "unknown";
1754
+ isMe?: boolean;
1755
+ userId: string;
1756
+ userName?: string;
1757
+ }
1758
+ interface MessengerAttachment {
1759
+ data?: ArrayBuffer;
1760
+ fetch?: () => Promise<ArrayBuffer>;
1761
+ id?: string;
1762
+ mediaType?: string;
1763
+ name?: string;
1764
+ raw?: unknown;
1765
+ size?: number;
1766
+ text?: string;
1767
+ url?: string;
1768
+ }
1769
+ interface MessengerThread {
1770
+ channelId?: string;
1771
+ channelName?: string;
1772
+ id: string;
1773
+ isDirectMessage: boolean;
1774
+ providerThreadId: string;
1775
+ title?: string;
1776
+ }
1777
+ interface MessengerMessage {
1778
+ attachments: MessengerAttachment[];
1779
+ author: MessengerAuthor;
1780
+ createdAt?: Date;
1781
+ id: string;
1782
+ isMention?: boolean;
1783
+ providerMessageId: string;
1784
+ raw?: unknown;
1785
+ text: string;
1786
+ }
1787
+ interface MessengerAction {
1788
+ actionId: string;
1789
+ messageId?: string;
1790
+ raw?: unknown;
1791
+ user?: MessengerAuthor;
1792
+ value?: string;
1793
+ }
1794
+ interface MessengerCapabilities {
1795
+ canEditMessages?: boolean;
1796
+ canStream?: boolean;
1797
+ maxMessageLength?: number;
1798
+ supportsActions?: boolean;
1799
+ supportsAttachments?: boolean;
1800
+ supportsEphemeral?: boolean;
1801
+ }
1802
+ interface MessengerContext {
1803
+ action?: MessengerAction;
1804
+ author?: MessengerAuthor;
1805
+ capabilities: MessengerCapabilities;
1806
+ kind: MessengerEventKind;
1807
+ message?: MessengerMessage;
1808
+ messengerId: string;
1809
+ provider: string;
1810
+ thread: MessengerThread;
1811
+ }
1812
+ interface MessengerEvent extends MessengerContext {
1813
+ raw?: unknown;
1814
+ }
1815
+ declare function messengerContextFromEvent(
1816
+ event: MessengerEvent
1817
+ ): MessengerContext;
1818
+ declare function serializableMessengerEvent(
1819
+ event: MessengerEvent
1820
+ ): MessengerEvent;
1821
+ declare function toMessengerUserMessage(event: MessengerEvent): UIMessage;
1822
+ //#endregion
1823
+ //#region src/messengers/delivery.d.ts
1824
+ declare const MESSENGER_REPLY_FIBER_NAME = "think:messenger-reply";
1825
+ declare const EMPTY_MESSENGER_RESPONSE =
1826
+ "I couldn't produce a text response. Please try again.";
1827
+ declare const ERROR_MESSENGER_RESPONSE =
1828
+ "Sorry, I couldn't answer that right now. Please try again.";
1829
+ declare const INTERRUPTED_MESSENGER_RESPONSE =
1830
+ "Sorry, my reply was interrupted. Please send your message again if you'd like me to retry.";
1831
+ interface TextStreamCallbackOptions {
1832
+ onVisibleStart?: () => Promise<void> | void;
1833
+ visibleSoftLimit?: number;
1834
+ }
1835
+ declare class TextStreamCallback extends RpcTarget implements StreamCallback {
1836
+ private readonly onVisibleStart?;
1837
+ private readonly visibleChunks;
1838
+ private readonly wakeups;
1839
+ private readonly visibleSoftLimit?;
1840
+ private chatRequestId?;
1841
+ private closed;
1842
+ private interrupted;
1843
+ private error?;
1844
+ private text;
1845
+ private visibleClosed;
1846
+ private visibleLimitReachedValue;
1847
+ private visibleStarted;
1848
+ private visibleTextValue;
1849
+ constructor(options?: TextStreamCallbackOptions);
1850
+ onStart(event: ChatStartEvent): void;
1851
+ onEvent(json: string): void;
1852
+ onDone(): void;
1853
+ onError(error: string): void;
1854
+ onInterrupted(): void;
1855
+ wasInterrupted(): boolean;
1856
+ close(): void;
1857
+ fail(error: unknown): void;
1858
+ hasText(): boolean;
1859
+ remainingText(): string;
1860
+ requestId(): string | undefined;
1861
+ textSoFar(): string;
1862
+ visibleLimitReached(): boolean;
1863
+ visibleText(): string;
1864
+ stream(): AsyncIterable<string>;
1865
+ private pushVisibleText;
1866
+ private wake;
1867
+ private markVisibleStarted;
1868
+ }
1869
+ declare function textDeltaFromStreamChunk(json: string): string | null;
1870
+ type MessengerReplyStage = "accepted" | "streaming" | "completed";
1871
+ interface MessengerReplySnapshot {
1872
+ event: MessengerEvent;
1873
+ stage: MessengerReplyStage;
1874
+ thread?: unknown;
1875
+ type: typeof MESSENGER_REPLY_FIBER_NAME;
1876
+ }
1877
+ declare function messengerReplySnapshot(
1878
+ stage: MessengerReplyStage,
1879
+ event: MessengerEvent,
1880
+ thread?: unknown
1881
+ ): MessengerReplySnapshot;
1882
+ declare function parseMessengerReplySnapshot(
1883
+ snapshot: unknown
1884
+ ): MessengerReplySnapshot | null;
1885
+ declare function messengerReplyRecoveryMode(
1886
+ snapshot: MessengerReplySnapshot
1887
+ ): "answer" | "apologize" | null;
1888
+ declare function messengerReplyFailureMode(
1889
+ hasStreamedText: boolean,
1890
+ completedModelTurn?: boolean,
1891
+ expectedDeliveryCompletion?: boolean
1892
+ ): "apologize" | "error" | null;
1893
+ interface MessengerDeliveryTarget {
1894
+ cancelChat(
1895
+ requestId: string,
1896
+ reason?: string
1897
+ ): boolean | void | Promise<boolean | void>;
1898
+ chat(
1899
+ userMessage: string | UIMessage,
1900
+ callback: StreamCallback
1901
+ ): Promise<void>;
1902
+ chatWithMessengerContext?(
1903
+ userMessage: string | UIMessage,
1904
+ callback: StreamCallback,
1905
+ context: MessengerEvent
1906
+ ): Promise<void>;
1907
+ }
1908
+ interface MessengerDeliverySurface {
1909
+ post(
1910
+ message:
1911
+ | string
1912
+ | {
1913
+ markdown: string;
1914
+ }
1915
+ | AsyncIterable<string>
1916
+ ): Promise<unknown>;
1917
+ startTyping?(status?: string): Promise<void>;
1918
+ }
1919
+ interface MessengerDeliveryPolicy {
1920
+ emptyResponseText?: string;
1921
+ errorResponseText?: string;
1922
+ interruptedResponseText?: string;
1923
+ isExpectedDeliveryCompletion?(
1924
+ error: unknown,
1925
+ callback: TextStreamCallback
1926
+ ): boolean;
1927
+ splitText?(text: string): string[];
1928
+ visibleSoftLimit?: number;
1929
+ }
1930
+ interface DeliverMessengerReplyOptions {
1931
+ checkpoint?: (snapshot: MessengerReplySnapshot) => Promise<void> | void;
1932
+ event: MessengerEvent;
1933
+ fiber?: FiberContext;
1934
+ policy?: MessengerDeliveryPolicy;
1935
+ snapshotEvent?: MessengerEvent;
1936
+ snapshotThread?: unknown;
1937
+ surface: MessengerDeliverySurface;
1938
+ target: MessengerDeliveryTarget;
1939
+ userMessage?: UIMessage;
1940
+ }
1941
+ declare function deliverMessengerReply(
1942
+ options: DeliverMessengerReplyOptions
1943
+ ): Promise<void>;
1944
+ //#endregion
1945
+ //#region src/messengers/chat-sdk.d.ts
1946
+ declare class ThinkMessengerStateAgent extends ChatSdkStateAgent {}
1947
+ type MessengerRespondTo =
1948
+ | "action"
1949
+ | "direct-message"
1950
+ | "mention"
1951
+ | "subscribed-thread";
1952
+ type MessengerConversationMode = "self" | "thread";
1953
+ type MessengerConversationTarget =
1954
+ | {
1955
+ target: "self";
1956
+ }
1957
+ | {
1958
+ agentClass?: SubAgentClass<Agent & MessengerThinkTarget>;
1959
+ name: string;
1960
+ target: "subagent";
1961
+ };
1962
+ type MessengerConversationResolver = (
1963
+ event: MessengerEvent
1964
+ ) => MessengerConversationTarget | Promise<MessengerConversationTarget>;
1965
+ interface MessengerDefinition {
1966
+ adapter: Adapter;
1967
+ adapterName: string;
1968
+ capabilities?: MessengerCapabilities;
1969
+ conversation?: MessengerConversationMode | MessengerConversationResolver;
1970
+ delivery?: MessengerDeliveryPolicy;
1971
+ keyShard?: ChatSdkStateAdapterOptions["keyShard"];
1972
+ path?: string;
1973
+ provider: string;
1974
+ respondTo?: readonly MessengerRespondTo[];
1975
+ shardKey?: ChatSdkStateAdapterOptions["shardKey"];
1976
+ subscribeOnMention?: boolean;
1977
+ toEvent?: (
1978
+ input: ChatSdkMessengerEventInput
1979
+ ) => MessengerEvent | Promise<MessengerEvent>;
1980
+ userName: string;
1981
+ verifyWebhook?:
1982
+ | false
1983
+ | ((request: Request) => boolean | Response | Promise<boolean | Response>);
1984
+ }
1985
+ type ThinkMessengers = Record<string, MessengerDefinition>;
1986
+ interface NormalizedMessengerDefinition extends MessengerDefinition {
1987
+ id: string;
1988
+ path: string;
1989
+ respondTo: readonly MessengerRespondTo[];
1990
+ subscribeOnMention: boolean;
1991
+ verifyWebhook:
1992
+ | false
1993
+ | ((request: Request) => boolean | Response | Promise<boolean | Response>);
1994
+ }
1995
+ interface ChatSdkMessengerOptions extends Omit<
1996
+ MessengerDefinition,
1997
+ "adapterName"
1998
+ > {
1999
+ adapterName?: string;
2000
+ }
2001
+ interface ChatSdkMessengerEventInput {
2002
+ action?: ActionEvent;
2003
+ eventKind: MessengerEventKind;
2004
+ message?: Message;
2005
+ raw?: unknown;
2006
+ thread: Thread;
2007
+ }
2008
+ interface MessengerThinkTarget {
2009
+ cancelChat(
2010
+ requestId: string,
2011
+ reason?: string
2012
+ ): boolean | void | Promise<boolean | void>;
2013
+ chat(
2014
+ userMessage: string | UIMessage,
2015
+ callback: StreamCallback
2016
+ ): Promise<void>;
2017
+ chatWithMessengerContext?(
2018
+ userMessage: string | UIMessage,
2019
+ callback: StreamCallback,
2020
+ context: MessengerEvent
2021
+ ): Promise<void>;
2022
+ }
2023
+ interface MessengerThinkHost extends MessengerThinkTarget {
2024
+ constructor: {
2025
+ name: string;
2026
+ };
2027
+ name: string;
2028
+ parentPath: ReadonlyArray<{
2029
+ className: string;
2030
+ name: string;
2031
+ }>;
2032
+ startFiber(
2033
+ name: string,
2034
+ fn: (ctx: FiberContext) => Promise<void>,
2035
+ options?: StartFiberOptions
2036
+ ): Promise<MessengerFiberStartResult>;
2037
+ resolveFiber(id: string, result: FiberRecoveryResult): Promise<boolean>;
2038
+ subAgent<T extends Agent>(
2039
+ agentClass: SubAgentClass<T>,
2040
+ name: string
2041
+ ): Promise<SubAgentStub<T>>;
2042
+ }
2043
+ interface MessengerFiberStartResult {
2044
+ accepted: boolean;
2045
+ fiberId: string;
2046
+ snapshot?: unknown;
2047
+ status: string;
2048
+ }
2049
+ declare function defineMessengers<T extends ThinkMessengers>(messengers: T): T;
2050
+ declare function chatSdkMessenger(
2051
+ options: ChatSdkMessengerOptions
2052
+ ): MessengerDefinition;
2053
+ declare class ThinkMessengerRuntime {
2054
+ private readonly host;
2055
+ private chat?;
2056
+ private readonly definitionsByAdapterName;
2057
+ private readonly definitionsById;
2058
+ private readonly definitions;
2059
+ constructor(definitions: ThinkMessengers, host: MessengerThinkHost);
2060
+ get size(): number;
2061
+ initialize(): void;
2062
+ handleRequest(request: Request): Promise<Response | undefined>;
2063
+ handleFiberRecovery(ctx: FiberRecoveryContext): Promise<boolean>;
2064
+ private createChat;
2065
+ private enqueueReply;
2066
+ private answer;
2067
+ private resolveTarget;
2068
+ private definitionForThread;
2069
+ private definitionForThreadId;
2070
+ private hasUniqueProvider;
2071
+ private shardThread;
2072
+ private shardStateKey;
2073
+ private reviveChatObject;
2074
+ private toEvent;
2075
+ }
2076
+ declare function normalizeMessengers(
2077
+ messengers: ThinkMessengers
2078
+ ): NormalizedMessengerDefinition[];
2079
+ declare function defaultConversationName(event: MessengerEvent): string;
2080
+ declare function idempotencyKeyForEvent(event: MessengerEvent): string;
2081
+ declare function defaultChatSdkEvent(
2082
+ definition: NormalizedMessengerDefinition,
2083
+ input: ChatSdkMessengerEventInput
2084
+ ): MessengerEvent;
2085
+ declare function toMessengerThread(thread: Thread): MessengerThread;
2086
+ declare function toMessengerMessage(message: Message): MessengerMessage;
2087
+ declare function toMessengerAuthor(author: Author): MessengerAuthor;
2088
+ declare function toMessengerAttachment(
2089
+ attachment: Attachment
2090
+ ): MessengerAttachment;
2091
+ //#endregion
2092
+ export {
2093
+ toMessengerUserMessage as $,
2094
+ defineScheduledTasks as $t,
2095
+ MessengerDeliverySurface as A,
2096
+ StreamableResult as At,
2097
+ parseMessengerReplySnapshot as B,
2098
+ ThinkSubmissionInspection as Bt,
2099
+ toMessengerThread as C,
2100
+ SkillRunContext as Ct,
2101
+ INTERRUPTED_MESSENGER_RESPONSE as D,
2102
+ StepResult as Dt,
2103
+ ERROR_MESSENGER_RESPONSE as E,
2104
+ StepContext as Et,
2105
+ TextStreamCallbackOptions as F,
2106
+ ThinkIntervalSchedule as Ft,
2107
+ MessengerCapabilities as G,
2108
+ ToolCallDecision as Gt,
2109
+ MessengerAction as H,
2110
+ ThinkTime as Ht,
2111
+ deliverMessengerReply as I,
2112
+ ThinkScheduledTask as It,
2113
+ MessengerEventKind as J,
2114
+ TurnContext as Jt,
2115
+ MessengerContext as K,
2116
+ ToolCallResultContext as Kt,
2117
+ messengerReplyFailureMode as L,
2118
+ ThinkScheduledTaskContext as Lt,
2119
+ MessengerReplySnapshot as M,
2120
+ SubmitMessagesResult as Mt,
2121
+ MessengerReplyStage as N,
2122
+ TextStreamPart as Nt,
2123
+ MESSENGER_REPLY_FIBER_NAME as O,
2124
+ StopCondition$1 as Ot,
2125
+ TextStreamCallback as P,
2126
+ Think as Pt,
2127
+ serializableMessengerEvent as Q,
2128
+ Workspace$1 as Qt,
2129
+ messengerReplyRecoveryMode as R,
2130
+ ThinkScheduledTaskSchedule as Rt,
2131
+ toMessengerMessage as S,
2132
+ Session$1 as St,
2133
+ EMPTY_MESSENGER_RESPONSE as T,
2134
+ StepConfig as Tt,
2135
+ MessengerAttachment as U,
2136
+ ThinkWallClockSchedule as Ut,
2137
+ textDeltaFromStreamChunk as V,
2138
+ ThinkSubmissionStatus as Vt,
2139
+ MessengerAuthor as W,
2140
+ ToolCallContext as Wt,
2141
+ MessengerThread as X,
2142
+ TypedToolCall$1 as Xt,
2143
+ MessengerMessage as Y,
2144
+ TurnInput as Yt,
2145
+ messengerContextFromEvent as Z,
2146
+ TypedToolResult as Zt,
2147
+ defineMessengers as _,
2148
+ PrepareStepFunction$1 as _t,
2149
+ MessengerConversationTarget as a,
2150
+ ChatRecoveryOptions$1 as at,
2151
+ toMessengerAttachment as b,
2152
+ SaveMessagesOptions$1 as bt,
2153
+ MessengerThinkHost as c,
2154
+ ChunkContext as ct,
2155
+ ThinkMessengerRuntime as d,
2156
+ ExtensionConfig as dt,
2157
+ skills as en,
2158
+ ChatErrorContext as et,
2159
+ ThinkMessengerStateAgent as f,
2160
+ FiberContext$1 as ft,
2161
+ defaultConversationName as g,
2162
+ PrepareStepContext as gt,
2163
+ defaultChatSdkEvent as h,
2164
+ MessageConcurrency$1 as ht,
2165
+ MessengerConversationResolver as i,
2166
+ ChatRecoveryExhaustedContext as it,
2167
+ MessengerDeliveryTarget as j,
2168
+ SubmitMessagesOptions as jt,
2169
+ MessengerDeliveryPolicy as k,
2170
+ StreamCallback as kt,
2171
+ MessengerThinkTarget as l,
2172
+ ChunkPart as lt,
2173
+ chatSdkMessenger as m,
2174
+ ListSubmissionsOptions as mt,
2175
+ ChatSdkMessengerOptions as n,
2176
+ ChatRecoveryConfig$1 as nt,
2177
+ MessengerDefinition as o,
2178
+ ChatResponseResult$1 as ot,
2179
+ ThinkMessengers as p,
2180
+ FiberRecoveryContext$1 as pt,
2181
+ MessengerEvent as q,
2182
+ TurnConfig as qt,
2183
+ MessengerConversationMode as r,
2184
+ ChatRecoveryContext$1 as rt,
2185
+ MessengerRespondTo as s,
2186
+ ChatStartEvent as st,
2187
+ ChatSdkMessengerEventInput as t,
2188
+ ChatOptions as tt,
2189
+ NormalizedMessengerDefinition as u,
2190
+ DeleteSubmissionsOptions as ut,
2191
+ idempotencyKeyForEvent as v,
2192
+ PrepareStepResult$1 as vt,
2193
+ DeliverMessengerReplyOptions as w,
2194
+ SkillSource$1 as wt,
2195
+ toMessengerAuthor as x,
2196
+ SaveMessagesResult$1 as xt,
2197
+ normalizeMessengers as y,
2198
+ ResolvedChatRecoveryConfig as yt,
2199
+ messengerReplySnapshot as z,
2200
+ ThinkScheduledTasks as zt
2201
+ };
2202
+ //# sourceMappingURL=index-CYp8VDIe.d.ts.map