@cloudflare/think 0.23.0 → 0.25.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.
Files changed (49) hide show
  1. package/README.md +30 -40
  2. package/dist/{chat-sdk-BEjKXjCm.js → chat-sdk-4Nu96eDX.js} +375 -256
  3. package/dist/chat-sdk-4Nu96eDX.js.map +1 -0
  4. package/dist/extensions/index.d.ts +30 -72
  5. package/dist/extensions/index.js +45 -47
  6. package/dist/extensions/index.js.map +1 -1
  7. package/dist/{fetch-DO3uQ9py.js → fetch-BbYxtlff.js} +10 -2
  8. package/dist/fetch-BbYxtlff.js.map +1 -0
  9. package/dist/manager-B3rcb_6p.js +493 -0
  10. package/dist/manager-B3rcb_6p.js.map +1 -0
  11. package/dist/manager-CWGumyKi.d.ts +3391 -0
  12. package/dist/messengers/index.d.ts +54 -66
  13. package/dist/messengers/index.js +2 -2
  14. package/dist/messengers/telegram.d.ts +4 -4
  15. package/dist/messengers/telegram.js +1 -1
  16. package/dist/think.d.ts +2 -2
  17. package/dist/think.js +8493 -10725
  18. package/dist/think.js.map +1 -1
  19. package/dist/tools/browser.d.ts +1 -1
  20. package/dist/tools/browser.js +1 -1
  21. package/dist/tools/browser.js.map +1 -1
  22. package/dist/tools/execute.d.ts +2 -2
  23. package/dist/tools/execute.js +2 -2
  24. package/dist/tools/execute.js.map +1 -1
  25. package/dist/tools/extensions.d.ts +1 -1
  26. package/dist/tools/extensions.js +1 -1
  27. package/dist/tools/fetch.js +1 -1
  28. package/dist/workflows.d.ts +5 -2
  29. package/docs/actions.md +12 -0
  30. package/docs/channels.md +10 -4
  31. package/docs/client-tools.md +57 -27
  32. package/docs/context.md +92 -0
  33. package/docs/getting-started.md +4 -4
  34. package/docs/index.md +112 -52
  35. package/docs/lifecycle-hooks.md +10 -21
  36. package/docs/multi-chat.md +6 -6
  37. package/docs/programmatic-submissions.md +28 -10
  38. package/docs/sub-agents.md +45 -51
  39. package/docs/tools.md +41 -15
  40. package/docs/workflows.md +5 -4
  41. package/package.json +15 -10
  42. package/dist/chat-sdk-BEjKXjCm.js.map +0 -1
  43. package/dist/fetch-DO3uQ9py.js.map +0 -1
  44. package/dist/hook-proxy-DY2sBNa0.js +0 -117
  45. package/dist/hook-proxy-DY2sBNa0.js.map +0 -1
  46. package/dist/index-DDnny6kt.d.ts +0 -5847
  47. package/dist/manager-BubfmA3q.js +0 -313
  48. package/dist/manager-BubfmA3q.js.map +0 -1
  49. package/dist/manager-rze95KCk.d.ts +0 -235
@@ -0,0 +1,3391 @@
1
+ import {
2
+ l as ThinkWorkspace,
3
+ t as CreateFetchToolsOptions
4
+ } from "./fetch-CU2fC7O6.js";
5
+ import {
6
+ Agent,
7
+ AgentContext,
8
+ AgentToolLifecycleResult,
9
+ AgentToolMilestone,
10
+ AgentToolProgress,
11
+ AgentToolRunInfo,
12
+ AgentToolRunInspection,
13
+ AgentToolStoredChunk,
14
+ FiberContext,
15
+ FiberContext as FiberContext$1,
16
+ FiberRecoveryContext,
17
+ FiberRecoveryContext as FiberRecoveryContext$1,
18
+ FiberRecoveryResult,
19
+ RetryOptions,
20
+ StartFiberOptions,
21
+ SubAgentClass,
22
+ SubAgentStub
23
+ } from "agents";
24
+ import { LifecycleCapability } from "agents/lifecycle";
25
+ import { ExtensionManager } from "agents/internal";
26
+ import {
27
+ FlexibleSchema,
28
+ GenerateTextOnStepFinishCallback,
29
+ InferSchema,
30
+ InferToolOutput,
31
+ LanguageModel,
32
+ ModelMessage,
33
+ PrepareStepFunction,
34
+ PrepareStepFunction as PrepareStepFunction$1,
35
+ PrepareStepResult,
36
+ PrepareStepResult as PrepareStepResult$1,
37
+ StepResult,
38
+ StopCondition,
39
+ StopCondition as StopCondition$1,
40
+ StreamTextOnChunkCallback,
41
+ TextStreamPart,
42
+ TextStreamPart as TextStreamPart$1,
43
+ ToolSet,
44
+ TypedToolCall,
45
+ TypedToolCall as TypedToolCall$1,
46
+ TypedToolResult,
47
+ UIMessage,
48
+ streamText
49
+ } from "ai";
50
+ import { CodemodeRuntimeHandle, PendingAction } from "@cloudflare/codemode";
51
+ import {
52
+ ChatRecoveryConfig,
53
+ ChatRecoveryConfig as ChatRecoveryConfig$1,
54
+ ChatRecoveryContext,
55
+ ChatRecoveryContext as ChatRecoveryContext$1,
56
+ ChatRecoveryExhaustedContext,
57
+ ChatRecoveryOptions,
58
+ ChatRecoveryOptions as ChatRecoveryOptions$1,
59
+ ChatRecoveryProgressContext,
60
+ ChatResponseResult,
61
+ ChatResponseResult as ChatResponseResult$1,
62
+ ClientToolExecutor,
63
+ ClientToolSchema,
64
+ MessageConcurrency,
65
+ MessageConcurrency as MessageConcurrency$1,
66
+ ResolvedChatRecoveryConfig,
67
+ SaveMessagesOptions,
68
+ SaveMessagesOptions as SaveMessagesOptions$1,
69
+ SaveMessagesResult,
70
+ SaveMessagesResult as SaveMessagesResult$1,
71
+ SkippedTurnReason
72
+ } from "agents/chat";
73
+ import { ThinkHarness } from "agents/harness/think";
74
+ import {
75
+ ActionEvent,
76
+ Adapter,
77
+ Attachment,
78
+ Author,
79
+ Chat,
80
+ ConcurrencyConfig,
81
+ ConcurrencyStrategy,
82
+ Message,
83
+ Thread
84
+ } from "chat";
85
+ import { ChatSdkStateAdapterOptions, ChatSdkStateAgent } from "agents/chat-sdk";
86
+ import { RpcTarget } from "cloudflare:workers";
87
+ import { Streams } from "agents/streams";
88
+ import { WorkspaceStub } from "@cloudflare/computer";
89
+ import {
90
+ DEFAULT_WORKSPACE_SKILLS_ROOT,
91
+ InvalidSkill,
92
+ InvalidSkillResourcePathError,
93
+ ListedSkill,
94
+ LoadSkillCatalogOptions,
95
+ ParseSkillOptions,
96
+ R2SkillSourceOptions,
97
+ Skill,
98
+ Skill as Skill$1,
99
+ SkillCatalog,
100
+ SkillCatalog as SkillCatalog$1,
101
+ SkillCatalogEntry,
102
+ SkillCatalogResource,
103
+ SkillDiagnostic,
104
+ SkillListing,
105
+ SkillManifest,
106
+ SkillManifestEntry,
107
+ SkillManifestResource,
108
+ SkillName,
109
+ SkillParseError,
110
+ SkillParseErrorCode,
111
+ SkillParseResult,
112
+ SkillResource,
113
+ SkillResourceError,
114
+ SkillResourceInfo,
115
+ SkillResourceKind,
116
+ SkillResourceNotFoundError,
117
+ SkillResourcePath,
118
+ SkillResult,
119
+ SkillRunContext,
120
+ SkillRunContext as SkillRunContext$1,
121
+ SkillScriptContext,
122
+ SkillScriptFile,
123
+ SkillScriptRequest,
124
+ SkillScriptRunner,
125
+ SkillScriptRunner as SkillScriptRunner$1,
126
+ SkillScriptWorkspace,
127
+ SkillSource,
128
+ SkillSource as SkillSource$1,
129
+ SkillSource as SkillSource$2,
130
+ SkillSourceError,
131
+ SkillWorkspace,
132
+ UnknownSkillError,
133
+ WorkspaceSkillSourceOptions,
134
+ formatSkill,
135
+ formatSkillDiagnostic as formatSkillDiagnostic$1,
136
+ fromManifest,
137
+ isModelInvocable,
138
+ loadSkillCatalog as loadSkillCatalog$1,
139
+ manifest,
140
+ parseSkill,
141
+ parseSkillName,
142
+ parseSkillResourcePath,
143
+ r2,
144
+ renderSkillResource,
145
+ workspace
146
+ } from "agents/skills";
147
+ import {
148
+ AppendOptions,
149
+ AppendResult,
150
+ CompactResult,
151
+ CompactionFunction,
152
+ HistoryBatchReadOptions,
153
+ HistoryReadOptions,
154
+ RecentHistoryResult,
155
+ SearchResult,
156
+ Session,
157
+ SessionMessage,
158
+ SessionMessage as SessionMessage$1,
159
+ SessionRowStat,
160
+ Sessions,
161
+ StoredCompaction,
162
+ WriteOptions
163
+ } from "agents/sessions";
164
+ import {
165
+ Context,
166
+ ContextBlock,
167
+ ContextConfig,
168
+ WritableContextProvider
169
+ } from "agents/context";
170
+ import { WorkerSkillScriptRunnerOptions, runner } from "agents/skills/runner";
171
+ //#region src/extensions/types.d.ts
172
+ /**
173
+ * Extension system types.
174
+ *
175
+ * Extensions are sandboxed Workers loaded on demand via WorkerLoader.
176
+ * Each extension provides tools that the agent can use, with controlled
177
+ * access to the host (workspace, network) via permissions.
178
+ */
179
+ /**
180
+ * Manifest declaring an extension's identity, permissions, and contributions.
181
+ * Passed to ExtensionManager.load() alongside the extension source.
182
+ */
183
+ interface ExtensionManifest {
184
+ /** Unique name for this extension (used as namespace prefix for tools and context). */
185
+ name: string;
186
+ /** Semver version string. */
187
+ version: string;
188
+ /** Human-readable description. */
189
+ description?: string;
190
+ /** Permission declarations — controls what the extension can access. */
191
+ permissions?: ExtensionPermissions;
192
+ /**
193
+ * Context blocks contributed by this extension.
194
+ * Labels are namespaced as `{extName}_{label}` at registration.
195
+ * Currently backed by SQLite storage — extensions write via
196
+ * `host.setContext()`. Direct RPC delegation is planned for Phase 4.
197
+ */
198
+ context?: Array<{
199
+ /** Block label (namespaced as {extName}_{label}). */ label: string /** Human-readable description shown in the system prompt header. */;
200
+ description?: string;
201
+ /**
202
+ * @deprecated Ignored, with a warning when set. An extension writes its
203
+ * blocks with `host.setContext()`, which its `context.write` permission
204
+ * governs.
205
+ */
206
+ type?:
207
+ | "readonly"
208
+ | "writable"
209
+ | "searchable" /** Maximum token budget for this block. */;
210
+ maxTokens?: number;
211
+ }>;
212
+ /**
213
+ * Lifecycle hooks this extension provides handlers for.
214
+ * The extension Worker must expose corresponding RPC methods.
215
+ */
216
+ hooks?: Array<
217
+ | "beforeTurn"
218
+ | "beforeToolCall"
219
+ | "afterToolCall"
220
+ | "onStepFinish"
221
+ | "onChunk"
222
+ >;
223
+ }
224
+ interface ExtensionPermissions {
225
+ /**
226
+ * Hosts the extension may fetch: `example.com` matches that host only,
227
+ * `*.example.com` its subdomains, `*` any public host. If empty or
228
+ * undefined, the extension has no outbound network access.
229
+ *
230
+ * Enforced when Think creates the manager and the Worker entry
231
+ * re-exports `HostBridgeLoopback`: every request goes through it, and
232
+ * one to an unlisted host or to a private or local address is refused
233
+ * with `403`. A TCP socket (`connect()`) is then refused too, even to a
234
+ * listed host, because the check reads HTTP requests. Without the
235
+ * re-export, or for an `ExtensionManager` an app creates itself, the
236
+ * hosts are not enforced and the extension can reach any host.
237
+ */
238
+ network?: string[];
239
+ /**
240
+ * Workspace access level.
241
+ * - "none" (default): no workspace access
242
+ * - "read": can read files and list directories
243
+ * - "read-write": can read, write, and delete files
244
+ */
245
+ workspace?: "read" | "read-write" | "none";
246
+ /**
247
+ * Context block access.
248
+ * - `read`: which labels the extension can read ("all" or specific list)
249
+ * - `write`: which labels the extension can write ("own" = only its manifest-declared labels, or specific list)
250
+ */
251
+ context?: {
252
+ read?: string[] | "all";
253
+ write?: string[] | "own";
254
+ };
255
+ /**
256
+ * Message history access.
257
+ * - "none" (default): no access
258
+ * - "read": can read conversation history
259
+ */
260
+ messages?: "none" | "read";
261
+ /**
262
+ * Session-level capabilities.
263
+ * - `sendMessage`: can inject user messages (queued when inside inference loop)
264
+ * - `metadata`: can read session metadata (message count, etc.)
265
+ */
266
+ session?: {
267
+ sendMessage?: boolean;
268
+ metadata?: boolean;
269
+ };
270
+ }
271
+ /**
272
+ * Tool descriptor returned by the extension's describe() method.
273
+ * Uses JSON Schema for input validation.
274
+ */
275
+ interface ExtensionToolDescriptor {
276
+ name: string;
277
+ description: string;
278
+ inputSchema: {
279
+ type: "object";
280
+ properties: Record<string, unknown>;
281
+ required?: string[];
282
+ };
283
+ }
284
+ /**
285
+ * Summary of a loaded extension, returned by ExtensionManager.list().
286
+ */
287
+ interface ExtensionInfo {
288
+ name: string;
289
+ version: string;
290
+ description?: string;
291
+ /** Names of tools provided by this extension. */
292
+ tools: string[];
293
+ /** Namespaced context labels contributed by this extension. */
294
+ contextLabels: string[];
295
+ permissions: ExtensionPermissions;
296
+ }
297
+ //#endregion
298
+ //#region src/actions.d.ts
299
+ declare const ACTION_BRAND: unique symbol;
300
+ type ActionKind =
301
+ | "server"
302
+ | "client"
303
+ | "approval-gated"
304
+ | "durable-pause"
305
+ | "delegated-agent";
306
+ interface ActionContext {
307
+ /** The agent instance currently executing the action. */
308
+ agent: Think;
309
+ env: Cloudflare.Env;
310
+ /** Current turn request id. */
311
+ requestId: string;
312
+ toolCallId: string;
313
+ /** Model messages visible to the tool call. */
314
+ messages: ReadonlyArray<ModelMessage>;
315
+ /** Combined action timeout and turn abort signal. */
316
+ signal: AbortSignal;
317
+ /**
318
+ * Record an advisory delivery hint for this turn's final reply (voice note,
319
+ * card, email draft, ...). Does not change the model-visible tool output.
320
+ * No-op for approval/permission/idempotency policy evaluation and for
321
+ * durable-pause approved-action resumes (their reply is delivered by a
322
+ * later continuation turn in v1).
323
+ */
324
+ attachReply(attachment: ReplyAttachment): void;
325
+ }
326
+ /**
327
+ * The attachment shape accepted by {@link ActionContext.attachReply}. An open
328
+ * union: the named variants give autocomplete for common channels, and the
329
+ * trailing `{ type: string; [k]: unknown }` keeps it extensible. Advisory only
330
+ * — surfaces that don't recognize a `type` ignore it.
331
+ */
332
+ type ReplyAttachment =
333
+ | {
334
+ type: "voice_note";
335
+ }
336
+ | {
337
+ type: "email_draft";
338
+ subject?: string;
339
+ to?: string[];
340
+ }
341
+ | {
342
+ type: "card";
343
+ payload: unknown;
344
+ }
345
+ | {
346
+ type: string;
347
+ [k: string]: unknown;
348
+ };
349
+ type ActionApprovalPolicy<Input> =
350
+ | boolean
351
+ | ((args: {
352
+ input: Input;
353
+ ctx: ActionContext;
354
+ }) => boolean | Promise<boolean>);
355
+ type ActionPermissionSpec<Input> =
356
+ | readonly string[]
357
+ | ((args: {
358
+ input: Input;
359
+ ctx: ActionContext;
360
+ }) => readonly string[] | Promise<readonly string[]>);
361
+ type ActionIdempotencyKey<Input> =
362
+ | string
363
+ | ((args: { input: Input; ctx: ActionContext }) => string | Promise<string>);
364
+ type ActionAuthorizationDecision =
365
+ | boolean
366
+ | {
367
+ allowed: boolean;
368
+ reason?: string;
369
+ grantedPermissions?: readonly string[];
370
+ };
371
+ interface ActionAuthorizationContext {
372
+ requestId: string;
373
+ toolCallId: string;
374
+ action: string;
375
+ kind: ActionKind;
376
+ input: unknown;
377
+ requiredPermissions: readonly string[];
378
+ grantedPermissions?: readonly string[];
379
+ messages: ReadonlyArray<ModelMessage>;
380
+ agent: Think;
381
+ env: Cloudflare.Env;
382
+ }
383
+ interface ActionApprovalDescriptor {
384
+ requestId: string;
385
+ toolCallId: string;
386
+ action: string;
387
+ summary: string;
388
+ input: unknown;
389
+ permissions: string[];
390
+ risk?: "low" | "medium" | "high";
391
+ kind: "approval-gated" | "durable-pause";
392
+ }
393
+ interface ActionConfig<
394
+ InputSchema extends FlexibleSchema = FlexibleSchema,
395
+ Output = unknown
396
+ > {
397
+ /** Defaults to the registration key when returned from getActions(). */
398
+ name?: string;
399
+ description: string;
400
+ inputSchema: InputSchema;
401
+ /** Reserved metadata; output validation is not enforced yet. */
402
+ outputSchema?: FlexibleSchema<Output>;
403
+ /**
404
+ * Stable key used to replay settled action results without re-running side
405
+ * effects. Use domain identifiers that survive recovery retries (for example,
406
+ * an order id or inbound event id); avoid request ids, timestamps, and random
407
+ * values.
408
+ */
409
+ idempotencyKey?: ActionIdempotencyKey<InferSchema<InputSchema>>;
410
+ permissions?: ActionPermissionSpec<InferSchema<InputSchema>>;
411
+ approval?: ActionApprovalPolicy<InferSchema<InputSchema>>;
412
+ approvalSummary?: string;
413
+ approvalRisk?: "low" | "medium" | "high";
414
+ timeoutMs?: number;
415
+ kind?: ActionKind;
416
+ execute(
417
+ input: InferSchema<InputSchema>,
418
+ ctx: ActionContext
419
+ ): Promise<Output> | Output;
420
+ }
421
+ interface Action<
422
+ InputSchema extends FlexibleSchema = FlexibleSchema,
423
+ Output = unknown
424
+ > {
425
+ readonly [ACTION_BRAND]: true;
426
+ readonly config: ActionConfig<InputSchema, Output>;
427
+ }
428
+ declare function action<
429
+ const InputSchema extends FlexibleSchema,
430
+ Output = unknown
431
+ >(config: ActionConfig<InputSchema, Output>): Action<InputSchema, Output>;
432
+ declare function isAction(value: unknown): value is Action;
433
+ //#endregion
434
+ //#region src/messengers/recovered-reply.d.ts
435
+ /** What the messenger host needs to post one part of a recovered reply. */
436
+ type RecoveredReplyPost = {
437
+ messengerId: string;
438
+ threadId: string;
439
+ outcome: "completed" | "interrupted";
440
+ text?: string;
441
+ partialPosted: boolean;
442
+ chunk: number;
443
+ /**
444
+ * Post the messenger's error text instead of the reply: a post of the
445
+ * reply failed and is not sent again.
446
+ */
447
+ notice?: true;
448
+ };
449
+ //#endregion
450
+ //#region src/channels/index.d.ts
451
+ /** Surface family for a channel. Drives the default ingress/delivery wiring. */
452
+ type ChannelKind = "messenger" | "web" | "voice" | "custom";
453
+ /** A channel's capabilities are the same shape as a messenger's. */
454
+ type ChannelCapabilities = MessengerCapabilities;
455
+ /** A channel's delivery policy is the same shape as a messenger's. */
456
+ type ChannelDeliveryPolicy = MessengerDeliveryPolicy;
457
+ /** Where a channel posts replies/notices. */
458
+ type ChannelDeliverySurface = MessengerDeliverySurface;
459
+ /**
460
+ * How events arrive for a channel. A discriminated union so `web`/`voice` do
461
+ * not have to invent webhook fields they don't use. The `webhook` transport is
462
+ * exactly today's messenger ingress (a full {@link MessengerDefinition}).
463
+ */
464
+ type ChannelIngress =
465
+ | ({
466
+ transport: "webhook";
467
+ } & MessengerDefinition)
468
+ | {
469
+ transport: "websocket";
470
+ }
471
+ | {
472
+ transport: "voice";
473
+ };
474
+ /**
475
+ * Turn-scoped context the runtime sets when a turn resolves to a channel. For
476
+ * `kind: "messenger"` it wraps the existing {@link MessengerContext}.
477
+ */
478
+ interface ChannelContext {
479
+ channelId: string;
480
+ kind: ChannelKind;
481
+ capabilities?: ChannelCapabilities;
482
+ messenger?: MessengerContext;
483
+ thread?: string;
484
+ }
485
+ /**
486
+ * The public channel contract — the generalization of a messenger: an ingress,
487
+ * a delivery surface, capabilities, conversation routing, a delivery policy, and
488
+ * (new) per-channel policy.
489
+ */
490
+ interface ChannelDefinition {
491
+ kind: ChannelKind;
492
+ capabilities?: ChannelCapabilities;
493
+ conversation?: MessengerConversationMode | MessengerConversationResolver;
494
+ delivery?: ChannelDeliveryPolicy;
495
+ /** Per-channel instructions, prepended to the system prompt for this channel. */
496
+ instructions?: string | ((ctx: ChannelContext) => string | Promise<string>);
497
+ /** Narrow the assembled tool set for this channel. */
498
+ tools?: (all: ToolSet) => ToolSet;
499
+ /** Per-channel cap on model steps for a turn. */
500
+ maxTurns?: number;
501
+ ingress: ChannelIngress;
502
+ }
503
+ type ThinkChannels = Record<string, ChannelDefinition>;
504
+ type NormalizedChannelDefinition = ChannelDefinition & {
505
+ id: string;
506
+ };
507
+ /** Wrap a {@link MessengerDefinition} as a `kind: "messenger"` channel. */
508
+ declare function messengerChannel(
509
+ definition: MessengerDefinition
510
+ ): ChannelDefinition;
511
+ //#endregion
512
+ //#region src/scheduled-tasks.d.ts
513
+ type Digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";
514
+ type Hour = `0${Digit}` | `1${Digit}` | "20" | "21" | "22" | "23";
515
+ type Minute = `${"0" | "1" | "2" | "3" | "4" | "5"}${Digit}`;
516
+ type ThinkTime = `${Hour}:${Minute}`;
517
+ type ThinkIntervalSchedule =
518
+ | `every ${number} minute${"" | "s"}`
519
+ | `every ${number} hour${"" | "s"}`;
520
+ type ThinkWallClockSchedule =
521
+ | `every day at ${ThinkTime}`
522
+ | `every weekday at ${ThinkTime}`
523
+ | `every week on ${string} at ${ThinkTime}`;
524
+ type ThinkScheduledTaskSchedule =
525
+ | ThinkIntervalSchedule
526
+ | ThinkWallClockSchedule
527
+ | `${ThinkWallClockSchedule} in ${string}`;
528
+ type ThinkScheduledTaskContext = {
529
+ taskId: string;
530
+ scheduledFor: number;
531
+ scheduledForDate: Date;
532
+ occurrenceKey: string;
533
+ idempotencyKey: string;
534
+ schedule: string;
535
+ scheduleKind: "interval" | "wall-clock";
536
+ timezone?: string;
537
+ metadata?: Record<string, unknown>;
538
+ };
539
+ type ThinkScheduledTaskPromptAction = {
540
+ prompt: string | (() => string | Promise<string>);
541
+ handler?: never;
542
+ };
543
+ type ThinkScheduledTaskHandlerAction = {
544
+ handler: (ctx: ThinkScheduledTaskContext) => void | Promise<void>;
545
+ prompt?: never;
546
+ };
547
+ type ThinkScheduledTaskBase = (
548
+ | ThinkScheduledTaskPromptAction
549
+ | ThinkScheduledTaskHandlerAction
550
+ ) & {
551
+ retry?: RetryOptions;
552
+ metadata?: Record<string, unknown>;
553
+ };
554
+ type ThinkScheduledTask =
555
+ | (ThinkScheduledTaskBase & {
556
+ schedule: ThinkIntervalSchedule;
557
+ timezone?: never;
558
+ })
559
+ | (ThinkScheduledTaskBase & {
560
+ schedule: ThinkWallClockSchedule;
561
+ timezone?: string;
562
+ })
563
+ | (ThinkScheduledTaskBase & {
564
+ schedule: `${ThinkWallClockSchedule} in ${string}`;
565
+ timezone?: string;
566
+ });
567
+ type ThinkScheduledTasks = Record<string, ThinkScheduledTask>;
568
+ //#endregion
569
+ //#region src/extensions/host-api.d.ts
570
+ /** @internal */
571
+ interface ThinkHostFileEntry {
572
+ name: string;
573
+ type: string;
574
+ size: number;
575
+ path: string;
576
+ }
577
+ /** @internal */
578
+ interface ThinkHostMessage {
579
+ id: string;
580
+ role: string;
581
+ content: string;
582
+ }
583
+ /**
584
+ * The operations `HostBridgeLoopback` forwards to the agent.
585
+ *
586
+ * @internal
587
+ */
588
+ interface ThinkHostApi {
589
+ readFile(path: string): Promise<string | null>;
590
+ writeFile(path: string, content: string): Promise<void>;
591
+ /** `false` when the file could not be removed. */
592
+ deleteFile(path: string): Promise<boolean>;
593
+ listFiles(dir: string): Promise<ThinkHostFileEntry[]>;
594
+ getContext(label: string): Promise<string | null>;
595
+ setContext(label: string, content: string): Promise<void>;
596
+ /** The last `limit` messages as plain text; all of them when omitted. */
597
+ getMessages(limit?: number): Promise<ThinkHostMessage[]>;
598
+ /** Append a user message, visible to the next turn. */
599
+ sendMessage(content: string): Promise<void>;
600
+ getSessionInfo(): Promise<{
601
+ messageCount: number;
602
+ }>;
603
+ }
604
+ /** @internal */
605
+ type ThinkHostOperation = keyof ThinkHostApi;
606
+ //#endregion
607
+ //#region src/submissions.d.ts
608
+ type ThinkSubmissionStatus =
609
+ | "pending"
610
+ | "running"
611
+ | "completed"
612
+ | "aborted"
613
+ | "skipped"
614
+ | "error";
615
+ type ThinkSubmissionInspection = {
616
+ submissionId: string;
617
+ idempotencyKey?: string;
618
+ requestId?: string;
619
+ status: ThinkSubmissionStatus;
620
+ error?: string;
621
+ metadata?: Record<string, unknown>;
622
+ createdAt: number;
623
+ startedAt?: number;
624
+ completedAt?: number /** Id of the assistant message this submission's turn persisted. */;
625
+ messageId?: string;
626
+ };
627
+ type SubmitMessagesResult = ThinkSubmissionInspection & {
628
+ accepted: boolean;
629
+ };
630
+ type WaitForSubmissionOptions = {
631
+ /**
632
+ * Stop waiting after this many milliseconds and return the submission as it
633
+ * is then, still `pending` or `running`, or `null` if it was deleted.
634
+ */
635
+ timeoutMs?: number;
636
+ };
637
+ /** What {@link Think.cancelSubmission} did. */
638
+ type CancelSubmissionResult =
639
+ | {
640
+ /** No submission has this id. */ outcome: "not_found";
641
+ submissionId: string;
642
+ }
643
+ | {
644
+ /** The submission had already finished; nothing changed. */ outcome: "already_terminal";
645
+ submissionId: string;
646
+ submission: ThinkSubmissionInspection;
647
+ }
648
+ | {
649
+ /** The submission is now `aborted`. */ outcome: "cancelled";
650
+ submissionId: string;
651
+ /**
652
+ * `"pending"`: removed before its turn started. `"running"`: its turn
653
+ * had been claimed and was signalled to abort; side effects already
654
+ * under way may still finish.
655
+ */
656
+ previousStatus: "pending" | "running";
657
+ /**
658
+ * Whether any of the submission's messages were written to the
659
+ * conversation when it was cancelled. A claimed submission can still be
660
+ * `false` when it is cancelled before its turn applies them.
661
+ */
662
+ messagesApplied: boolean;
663
+ submission: ThinkSubmissionInspection;
664
+ };
665
+ type ListSubmissionsOptions = {
666
+ status?: ThinkSubmissionStatus | ThinkSubmissionStatus[];
667
+ limit?: number;
668
+ };
669
+ type DeleteSubmissionsOptions = {
670
+ status?: ThinkSubmissionStatus | ThinkSubmissionStatus[];
671
+ completedBefore?: Date;
672
+ limit?: number;
673
+ };
674
+ //#endregion
675
+ //#region src/workflow-notifications.d.ts
676
+ /**
677
+ * The workflow event a terminal submission owes, delivered until the
678
+ * workflow accepts it.
679
+ *
680
+ * @internal
681
+ */
682
+ type WorkflowNotification = {
683
+ workflowName: string;
684
+ workflowId: string;
685
+ event: {
686
+ type: string;
687
+ payload: WorkflowEventPayload;
688
+ };
689
+ };
690
+ /** What a submission's workflow event carries. */
691
+ type WorkflowEventPayload = {
692
+ submissionId?: string;
693
+ status?: string;
694
+ output?: unknown;
695
+ error?: string;
696
+ [key: string]: unknown;
697
+ };
698
+ /** The sink workflow notifications are delivered through. @internal */
699
+ /**
700
+ * The delivery a queue item or scheduled retry of the released version
701
+ * carries (`_cfDeliverWorkflowNotification`). A retry keeps its give-up
702
+ * window (`firstFailedAt`) and its backoff (`attempts`).
703
+ *
704
+ * TEMPORARY: remove with `_cfDeliverWorkflowNotification` in the next minor.
705
+ *
706
+ * @internal
707
+ */
708
+ declare function legacyWorkflowNotification(
709
+ payload: WorkflowNotification & {
710
+ attempts?: number;
711
+ firstFailedAt?: number;
712
+ }
713
+ ): {
714
+ id: string;
715
+ notification: WorkflowNotification;
716
+ resume?: {
717
+ sentAt: number;
718
+ attempts: number;
719
+ };
720
+ };
721
+ //#endregion
722
+ //#region src/session.d.ts
723
+ /** Options for a block declared through `withContext()` / `addContext()`. */
724
+ type SessionContextOptions = Omit<ContextConfig, "label">;
725
+ /** Receives an error thrown by the registered compaction function. */
726
+ type CompactionErrorHandler = (error: unknown) => void | Promise<void>;
727
+ /**
728
+ * @deprecated `compactAfter()` gates on the token estimate Sessions stamps on
729
+ * each row; a custom counter is no longer consulted. Accepted so existing
730
+ * calls compile.
731
+ */
732
+ interface CompactAfterOptions {
733
+ tokenCounter?: unknown;
734
+ }
735
+ declare class ThinkSession {
736
+ #private;
737
+ /** @internal Constructed by Think during `onStart`. */
738
+ constructor(handle: Session, context: () => Context);
739
+ get sessionId(): string;
740
+ /** @internal Blocks declared through `withContext()` during configuration. */
741
+ internal_takePendingContext(): ContextConfig[];
742
+ /** @internal A custom frozen-prompt store passed to `withCachedPrompt()`. */
743
+ internal_promptStore(): WritableContextProvider | undefined;
744
+ /**
745
+ * Declare a prompt context block.
746
+ *
747
+ * @deprecated Return the block from `configureContext()` instead. Only
748
+ * callable inside `configureSession()`; after startup use
749
+ * `this.context.addBlock()`.
750
+ */
751
+ withContext(label: string, options?: SessionContextOptions): this;
752
+ /**
753
+ * Persist the frozen system prompt.
754
+ *
755
+ * @deprecated The session records the prompt each turn was sent with, so
756
+ * this is not needed. A custom `provider` is still read: a prompt frozen
757
+ * in it before is what the turns sent before are sent. It is not written.
758
+ */
759
+ withCachedPrompt(provider?: WritableContextProvider): this;
760
+ /** Register the function `compact()` calls to summarize a branch. */
761
+ onCompaction(fn: CompactionFunction): this;
762
+ /**
763
+ * Auto-compact after an append once the stamped token estimate crosses the
764
+ * threshold. Requires `onCompaction()`.
765
+ */
766
+ compactAfter(tokenThreshold: number, _options?: CompactAfterOptions): this;
767
+ /**
768
+ * Observe compaction failures. When set, a failing compaction function
769
+ * calls the handler and the compaction is skipped; without one the failure
770
+ * is reported through the `session:error` capability event.
771
+ */
772
+ onCompactionError(handler: CompactionErrorHandler): this;
773
+ history(
774
+ options?: HistoryReadOptions
775
+ ): AsyncGenerator<SessionMessage, void, undefined>;
776
+ historyBatches(
777
+ options?: HistoryBatchReadOptions
778
+ ): AsyncGenerator<SessionMessage[], void, undefined>;
779
+ /**
780
+ * Materialize the whole selected path. Accepts a leaf id positionally, as
781
+ * the pre-Sessions API did, or a read-options object.
782
+ */
783
+ getHistory(
784
+ leafIdOrOptions?: string | null | HistoryReadOptions
785
+ ): Promise<SessionMessage[]>;
786
+ /**
787
+ * Byte-budgeted read of the most recent messages on the active path. The
788
+ * pre-Sessions `minRecentMessages` argument is accepted and ignored: the
789
+ * budget is a hard ceiling, and the newest message is always returned.
790
+ */
791
+ getRecentHistory(
792
+ maxContentBytes: number,
793
+ optionsOrMinRecentMessages?: number | Pick<HistoryReadOptions, "leafId">
794
+ ): Promise<RecentHistoryResult>;
795
+ getHistoryRowStats(leafId?: string | null): Promise<SessionRowStat[]>;
796
+ /** @deprecated Read `getHistoryRowStats()` and take its length. */
797
+ getPathLength(leafId?: string | null): Promise<number>;
798
+ /** @internal A page of the stored path from the newest row back (media eviction). */
799
+ internal_storedPathRows(options: {
800
+ skip: number;
801
+ limit: number;
802
+ measure?: boolean;
803
+ after?: string;
804
+ }): Promise<
805
+ Array<{
806
+ id: string;
807
+ bytes: number;
808
+ }>
809
+ >;
810
+ getMessage(id: string): Promise<SessionMessage | null>;
811
+ getLatestLeaf(): Promise<SessionMessage | null>;
812
+ getBranches(messageId: string): Promise<SessionMessage[]>;
813
+ search(
814
+ query: string,
815
+ options?: {
816
+ limit?: number;
817
+ }
818
+ ): Promise<SearchResult[]>;
819
+ /**
820
+ * Append one message. Accepts the parent id positionally, as the
821
+ * pre-Sessions API did, or an options object.
822
+ */
823
+ appendMessage(
824
+ message: SessionMessage,
825
+ parentIdOrOptions?: string | null | AppendOptions
826
+ ): Promise<AppendResult>;
827
+ updateMessage(
828
+ message: SessionMessage,
829
+ options?: WriteOptions
830
+ ): Promise<SessionMessage | null>;
831
+ upsertMessage(
832
+ message: SessionMessage,
833
+ parentIdOrOptions?: string | null | AppendOptions
834
+ ): Promise<AppendResult>;
835
+ importMessage(
836
+ message: SessionMessage,
837
+ options: {
838
+ parentId: string | null;
839
+ createdAt: number;
840
+ }
841
+ ): Promise<void>;
842
+ deleteMessages(messageIds: string[]): Promise<void>;
843
+ clearMessages(): Promise<void>;
844
+ addCompaction(
845
+ summary: string,
846
+ fromMessageId: string,
847
+ toMessageId: string
848
+ ): Promise<StoredCompaction>;
849
+ getCompactions(): Promise<StoredCompaction[]>;
850
+ compact(leafId?: string | null): Promise<CompactResult | null>;
851
+ /** @deprecated Use `this.context.addBlock({ label, ...options })`. */
852
+ addContext(
853
+ label: string,
854
+ options?: SessionContextOptions
855
+ ): Promise<ContextBlock>;
856
+ /** @deprecated Use `this.context.removeBlock(label)`. */
857
+ removeContext(label: string): boolean;
858
+ /** @deprecated Use `this.context.getBlock(label)`. */
859
+ getContextBlock(label: string): ContextBlock | null;
860
+ /** @deprecated Use `this.context.getBlocks()`. */
861
+ getContextBlocks(): ContextBlock[];
862
+ /** @deprecated Use `this.context.setBlock(label, content)`. */
863
+ replaceContextBlock(label: string, content: string): Promise<ContextBlock>;
864
+ /** @deprecated Use `this.context.appendToBlock(label, content)`. */
865
+ appendContextBlock(label: string, content: string): Promise<ContextBlock>;
866
+ /** @deprecated Use `this.context.freezeSystemPrompt()`. */
867
+ freezeSystemPrompt(): Promise<string>;
868
+ /** @deprecated Use `this.context.refreshSystemPrompt()`. */
869
+ refreshSystemPrompt(): Promise<string>;
870
+ /** @deprecated Use `this.context.tools()`. */
871
+ tools(): Promise<ToolSet>;
872
+ }
873
+ //#endregion
874
+ //#region src/media-eviction.d.ts
875
+ interface MediaEvictionConfig {
876
+ /**
877
+ * Messages at the tail of the active path that are never evicted.
878
+ * Think clamps this to at least the read-time window the model replays at
879
+ * full fidelity, so a misconfigured low value can never strip content the
880
+ * model still sees.
881
+ * @default 8
882
+ */
883
+ keepRecentMessages?: number;
884
+ /**
885
+ * Minimum decoded payload size, in bytes, for a value to be evicted.
886
+ * @default 32 * 1024
887
+ */
888
+ minPartBytes?: number;
889
+ /**
890
+ * Maximum stored rows processed per pass. Bounds how long a single pass
891
+ * can take; remaining rows are picked up by the next pass.
892
+ * @default 64
893
+ */
894
+ maxRowsPerPass?: number;
895
+ /**
896
+ * @deprecated Ignored. Evicted bytes are always preserved in the Workspace
897
+ * under `/workspace/attachments/evicted/`; there is no drop-the-bytes mode. Accepted
898
+ * so existing configurations keep compiling.
899
+ */
900
+ externalizeToWorkspace?: boolean;
901
+ }
902
+ //#endregion
903
+ //#region src/transcript-cache.d.ts
904
+ /**
905
+ * What the last budgeted refresh measured.
906
+ *
907
+ * @internal
908
+ */
909
+ interface HydrationResult {
910
+ /** `true` when the cache is a recent window of a larger transcript. */
911
+ truncated: boolean;
912
+ totalContentBytes: number;
913
+ hydratedMessages: number;
914
+ }
915
+ declare namespace skills_d_exports {
916
+ export {
917
+ DEFAULT_WORKSPACE_SKILLS_ROOT,
918
+ InvalidSkill,
919
+ InvalidSkillResourcePathError,
920
+ ListedSkill,
921
+ LoadSkillCatalogOptions,
922
+ ParseSkillOptions,
923
+ R2SkillSourceOptions,
924
+ Skill$1 as Skill,
925
+ SkillCatalog$1 as SkillCatalog,
926
+ SkillCatalogEntry,
927
+ SkillCatalogResource,
928
+ SkillDiagnostic,
929
+ SkillListing,
930
+ SkillManifest,
931
+ SkillManifestEntry,
932
+ SkillManifestResource,
933
+ SkillName,
934
+ SkillParseError,
935
+ SkillParseErrorCode,
936
+ SkillParseResult,
937
+ SkillResource,
938
+ SkillResourceError,
939
+ SkillResourceInfo,
940
+ SkillResourceKind,
941
+ SkillResourceNotFoundError,
942
+ SkillResourcePath,
943
+ SkillResult,
944
+ SkillRunContext$1 as SkillRunContext,
945
+ SkillScriptContext,
946
+ SkillScriptFile,
947
+ SkillScriptRequest,
948
+ SkillScriptRunner$1 as SkillScriptRunner,
949
+ SkillScriptWorkspace,
950
+ SkillSource$2 as SkillSource,
951
+ SkillSourceError,
952
+ SkillWorkspace,
953
+ UnknownSkillError,
954
+ WorkerSkillScriptRunnerOptions,
955
+ WorkspaceSkillSourceOptions,
956
+ formatSkill,
957
+ formatSkillDiagnostic$1 as formatSkillDiagnostic,
958
+ fromManifest,
959
+ isModelInvocable,
960
+ loadSkillCatalog$1 as loadSkillCatalog,
961
+ manifest,
962
+ parseSkill,
963
+ parseSkillName,
964
+ parseSkillResourcePath,
965
+ r2,
966
+ renderSkillResource,
967
+ runner,
968
+ workspace
969
+ };
970
+ }
971
+ //#endregion
972
+ //#region src/think.d.ts
973
+ /**
974
+ * A single approval awaiting a human decision, unified across pause backends so
975
+ * dashboards/voice/messenger can list and reconcile everything pending with one
976
+ * call. `source: "action"` is a parked `kind: "durable-pause"` action;
977
+ * `source: "codemode"` is a paused `execute`-tool execution. Both resolve via
978
+ * {@link Think.approveExecution} / {@link Think.rejectExecution}.
979
+ */
980
+ interface PendingApproval {
981
+ executionId: string;
982
+ source: "action" | "codemode";
983
+ descriptor: ActionApprovalDescriptor;
984
+ }
985
+ interface RejectExecutionOptions {
986
+ /**
987
+ * Whether Think starts a model continuation after recording the rejection.
988
+ * Defaults to `true`. Set this to `false` when the caller wants the
989
+ * conversation to remain paused until a later user turn.
990
+ */
991
+ autoContinue?: boolean;
992
+ }
993
+ type SubmitMessagesOptions = {
994
+ submissionId?: string;
995
+ idempotencyKey?: string;
996
+ metadata?: Record<
997
+ string,
998
+ unknown
999
+ > /** Channel id this submission belongs to. See the `channel` option of {@link RunTurnOptions}. */;
1000
+ channel?: string;
1001
+ };
1002
+ declare class Think<
1003
+ Env extends Cloudflare.Env = Cloudflare.Env,
1004
+ State = unknown,
1005
+ Props extends object = object
1006
+ > extends Agent<Env, State, Props> {
1007
+ #private;
1008
+ static readonly CHAT_FIBER_NAME = "__cf_internal_chat_turn";
1009
+ /**
1010
+ * How long after its turn started an interrupted submission is still
1011
+ * recovered. Past it, the submission ends `error`.
1012
+ */
1013
+ protected static submissionRecoveryStaleMs: number;
1014
+ /** Model calls per turn. Read per call, so a subclass field applies. */
1015
+ maxSteps: number;
1016
+ /** Whether reasoning reaches the stream, as in 0.24; a turn may say. */
1017
+ sendReasoning: boolean;
1018
+ /** How a messenger thread's burst of messages is answered, as in 0.24. */
1019
+ messengerConcurrency: MessengerConcurrency;
1020
+ /**
1021
+ * Metadata for every assistant message, as in 0.24. A turn's
1022
+ * `beforeTurn` may return its own `messageMetadata` instead.
1023
+ */
1024
+ messageMetadata?: MessageMetadataCallback;
1025
+ /**
1026
+ * Opt-in handling for a turn that overflows the context window, as on
1027
+ * Think. Unset leaves an overflow terminal.
1028
+ */
1029
+ contextOverflow?: ContextOverflowConfig;
1030
+ /** Store model input/output on `chat` spans. */
1031
+ storeMessages: boolean;
1032
+ /** Store tool input/output on `execute_tool` spans. */
1033
+ storeTools: boolean;
1034
+ /** @internal */
1035
+ readonly harness: ThinkHarness;
1036
+ /** The conversation, configured by {@link configureSession}. */
1037
+ session: ThinkSession;
1038
+ /**
1039
+ * The agent's Workspace, as in 0.24: a subclass may assign its own; by
1040
+ * default one on this Durable Object's storage, made at start.
1041
+ */
1042
+ workspace: ThinkWorkspace;
1043
+ /** Offer the connected MCP servers' tools each turn, as in 0.24. */
1044
+ includeMcpTools: boolean;
1045
+ /** Wait for MCP connections before a turn's tools are built, as in 0.24. */
1046
+ waitForMcpConnections:
1047
+ | boolean
1048
+ | {
1049
+ timeout: number;
1050
+ };
1051
+ /** WorkerLoader binding for sandboxed extensions, as in 0.24. */
1052
+ extensionLoader?: WorkerLoader;
1053
+ /** The sandboxed extensions, made at start when `extensionLoader` is set. */
1054
+ extensionManager?: ExtensionManager$1;
1055
+ /** Per-extension hook timeout in milliseconds, as in 0.24. */
1056
+ hookTimeout: number;
1057
+ /** Think's opt-in fetch tools, as in 0.24: off unless set. */
1058
+ fetchTools: false | Omit<CreateFetchToolsOptions, "workspace" | "onEvent">;
1059
+ /**
1060
+ * As in 0.24: the byte budget for the in-memory message view. A stored
1061
+ * transcript larger than this is hydrated as its most recent messages
1062
+ * that fit, and `chat:hydration:windowed` is emitted. Non-finite or
1063
+ * non-positive: always the whole transcript.
1064
+ *
1065
+ * @default 32 * 1024 * 1024
1066
+ */
1067
+ hydrationByteBudget: number;
1068
+ /**
1069
+ * Evict aged media from the conversation, as in 0.24: the bytes go to
1070
+ * the Workspace and a marker stays in the message.
1071
+ */
1072
+ mediaEviction: MediaEvictionConfig | boolean;
1073
+ /** How many messages the media-eviction cutoff moves by at a time. */
1074
+ truncationStep: number;
1075
+ /**
1076
+ * Render a reply attachment for delivery to the turn's channel, as on
1077
+ * Think: the text or markdown to post, or `undefined` to skip it (unknown
1078
+ * types, and types a channel handles itself, such as `voice_note`).
1079
+ */
1080
+ renderAttachment(attachment: ReplyAttachment):
1081
+ | string
1082
+ | {
1083
+ markdown: string;
1084
+ }
1085
+ | undefined;
1086
+ constructor(ctx: AgentContext, env: Env);
1087
+ /**
1088
+ * A chat turn a release ran as a fiber (think@0.24.0 in a sub-agent, and
1089
+ * older releases everywhere), carried forward as a fiber run: recovered
1090
+ * like its Tasks run would be. Every other fiber is the app's.
1091
+ * @internal
1092
+ */
1093
+ protected _handleInternalFiberRecovery(
1094
+ ctx: FiberRecoveryContext
1095
+ ): Promise<boolean>;
1096
+ /**
1097
+ * A queue item or schedule think 0.24 left to run a submission names
1098
+ * this method. This version's carrier runs that submission itself
1099
+ * (`#carryReleasedSubmissions`), so the item has nothing to do: it is
1100
+ * taken and removed. Without the method the queue would log a callback
1101
+ * that is not there, once per item; in a sub-agent the item is held by
1102
+ * its root, where the migration's steps of this class do not run.
1103
+ * @internal Queue and schedule callback.
1104
+ */
1105
+ _cfRunSubmission(): Promise<void>;
1106
+ /**
1107
+ * A queue item or scheduled retry of a workflow notification from the
1108
+ * released version, which names this method: sent as a delivery, which
1109
+ * retries on its own.
1110
+ * @internal Queue and schedule callback.
1111
+ */
1112
+ _cfDeliverWorkflowNotification(
1113
+ payload: Parameters<typeof legacyWorkflowNotification>[0]
1114
+ ): Promise<void>;
1115
+ /**
1116
+ * The onStart steps that failed on this wake and were skipped so the
1117
+ * agent could still come up, as in 0.24. Empty when the start was clean.
1118
+ */
1119
+ getOnStartDegradations(): ReadonlyArray<OnStartDegradation>;
1120
+ /**
1121
+ * @internal Think's steps of the one migration of what think@0.24.0
1122
+ * stored, run in the Agent's constructor: they read nothing of the
1123
+ * instance but whether it is a sub-agent.
1124
+ */
1125
+ protected _releaseMigrationSteps(): readonly ((storage: {
1126
+ readonly sql: SqlStorage;
1127
+ readonly kv: SyncKvStorage;
1128
+ }) => void)[];
1129
+ getModel(): ThinkModel;
1130
+ getAIBinding(): Ai;
1131
+ getGateway(_model: string): GatewayOptions | undefined;
1132
+ /**
1133
+ * Resolve a model value into a concrete AI SDK `LanguageModel`, as on
1134
+ * Think: with no argument, the one `getModel()` returns.
1135
+ */
1136
+ resolveModel(model?: ThinkModel): LanguageModel;
1137
+ getSystemPrompt(): string;
1138
+ getTools(): ToolSet;
1139
+ configureSession(session: ThinkSession): ThinkSession | Promise<ThinkSession>;
1140
+ /**
1141
+ * Persist a JSON-serializable configuration for this agent, as in 0.24:
1142
+ * private to the server, kept across restarts.
1143
+ */
1144
+ configure<T = Record<string, unknown>>(config: T): void;
1145
+ /** The configuration stored by {@link configure}, or null, as in 0.24. */
1146
+ getConfig<T = Record<string, unknown>>(): T | null;
1147
+ /** The skill sources, as in 0.24: none unless overridden. */
1148
+ getSkills(): SkillSource[] | Promise<SkillSource[]>;
1149
+ /** A runner for `run_skill_script`, as in 0.24: none unless overridden. */
1150
+ getSkillScriptRunner(): SkillScriptRunner | null;
1151
+ /** Declare the prompt context blocks, as in 0.24. */
1152
+ configureContext(): ContextConfig[] | Promise<ContextConfig[]>;
1153
+ /** The root session's context blocks. Available once started. */
1154
+ protected get context(): Context;
1155
+ /**
1156
+ * Sandboxed extensions to load at start, in order, as in 0.24. Needs
1157
+ * `extensionLoader`.
1158
+ */
1159
+ getExtensions(): ExtensionConfig[];
1160
+ getActions(): Record<string, Action> | Promise<Record<string, Action>>;
1161
+ /**
1162
+ * Authorize action permissions for the current turn, as in 0.24.
1163
+ * Returning `true` grants all of them; `grantedPermissions` limits the
1164
+ * default `authorizeAction` to that set.
1165
+ */
1166
+ authorizeTurn(
1167
+ _ctx: TurnContext
1168
+ ): ActionAuthorizationDecision | Promise<ActionAuthorizationDecision>;
1169
+ /**
1170
+ * Authorize a single action call, as in 0.24. The default enforces the
1171
+ * grant `authorizeTurn` returned for the turn.
1172
+ */
1173
+ authorizeAction(
1174
+ ctx: ActionAuthorizationContext
1175
+ ): ActionAuthorizationDecision | Promise<ActionAuthorizationDecision>;
1176
+ /**
1177
+ * As in 0.24: how long settled and pending action ledger rows are kept.
1178
+ * Deleting a row ends the idempotency guarantee for its key.
1179
+ */
1180
+ actionLedgerRetention: {
1181
+ settledMs: number | false;
1182
+ pendingMs: number | false;
1183
+ maxSweepRows: number;
1184
+ };
1185
+ /**
1186
+ * As in 0.24: how long a parked durable pause waits for its decision.
1187
+ * Older ones are dropped at start; `false` keeps them.
1188
+ */
1189
+ actionPendingApprovalTtlMs: number | false;
1190
+ /** As in 0.24: how long a stale claim of a keyed action is held. */
1191
+ actionLedgerPendingRetryLeaseMs: number | false;
1192
+ /**
1193
+ * Advisory reply attachments the latest turn's actions recorded through
1194
+ * `ctx.attachReply`, as in 0.24: with a `requestId`, only if they belong
1195
+ * to that turn.
1196
+ */
1197
+ replyAttachments(requestId?: string): ReplyAttachment[];
1198
+ /**
1199
+ * Everything awaiting human approval: the action calls of the latest reply
1200
+ * that wait for a decision, each with its descriptor. Resolve one with
1201
+ * `approveExecution` or `rejectExecution`, by its `executionId`.
1202
+ */
1203
+ pendingApprovals(executionId?: string): Promise<PendingApproval[]>;
1204
+ /**
1205
+ * Enrich the approval descriptor shown for a paused `execute` execution.
1206
+ * The default is derived from the first pending call as
1207
+ * `connector.method` with its args as the input; return a summary, the
1208
+ * permissions it consumes or a risk level to merge over it. Not called
1209
+ * for durable-pause actions, which carry their own descriptor.
1210
+ */
1211
+ describePausedExecution(
1212
+ _pending: PendingAction[],
1213
+ _ctx: {
1214
+ requestId: string;
1215
+ toolCallId: string;
1216
+ }
1217
+ ): Partial<ActionApprovalDescriptor> | undefined;
1218
+ /**
1219
+ * Set by `createExecuteTool(this)`: the codemode runtime whose paused
1220
+ * executions `pendingExecutions`, `approveExecution` and `rejectExecution`
1221
+ * reach, as in 0.24.
1222
+ */
1223
+ codemode?: CodemodeRuntimeHandle;
1224
+ /**
1225
+ * The actions awaiting approval across the execute tool's paused
1226
+ * executions, with their full args, as in 0.24.
1227
+ */
1228
+ pendingExecutions(executionId?: string): Promise<PendingAction[]>;
1229
+ /** Approve a pending action call; the turn continues and runs it. */
1230
+ approveExecution(executionId: string): Promise<unknown>;
1231
+ /**
1232
+ * Reject a pending action call; the turn continues with the refusal, or
1233
+ * waits for a later turn with `{ autoContinue: false }`.
1234
+ */
1235
+ rejectExecution(
1236
+ executionId: string,
1237
+ reason?: string,
1238
+ options?: RejectExecutionOptions
1239
+ ): Promise<unknown>;
1240
+ getMessengers(): ThinkMessengers;
1241
+ /**
1242
+ * Bind a messenger reply's delivery surface, as 0.24 did, so a
1243
+ * `deliverNotice` while it is bound posts there. Returns the restore
1244
+ * function; nested binds restore in order. Called by
1245
+ * `deliverMessengerReply`.
1246
+ */
1247
+ bindActiveDeliverySurface(surface: MessengerDeliverySurface): () => void;
1248
+ /**
1249
+ * Post a notice outside a turn, as 0.24 did: to the web transcript
1250
+ * (`"web"`, the default) as an assistant message that starts no turn, or
1251
+ * to a messenger's `thread`.
1252
+ */
1253
+ deliverNotice(
1254
+ text:
1255
+ | string
1256
+ | {
1257
+ markdown: string;
1258
+ },
1259
+ options?: DeliverNoticeOptions
1260
+ ): Promise<void>;
1261
+ /**
1262
+ * Return the channels for this agent, as in 0.24: the implicit `web`
1263
+ * channel and each messenger are always present; these add surfaces and
1264
+ * per-channel policy (instructions, a narrower tool set, `maxTurns`).
1265
+ */
1266
+ configureChannels(): ThinkChannels | Promise<ThinkChannels>;
1267
+ getScheduledTasks(): ThinkScheduledTasks | Promise<ThinkScheduledTasks>;
1268
+ getDefaultTimezone(): string | undefined | Promise<string | undefined>;
1269
+ /** Reconcile code-declared scheduled tasks, as 0.24 did. */
1270
+ internal_reconcileScheduledTasks(): Promise<void>;
1271
+ beforeTurn(_ctx: TurnContext): TurnConfig | void | Promise<TurnConfig | void>;
1272
+ beforeToolCall(
1273
+ _ctx: ToolCallContext
1274
+ ): ToolCallDecision | void | Promise<ToolCallDecision | void>;
1275
+ afterToolCall(_ctx: ToolCallResultContext): void | Promise<void>;
1276
+ /** Before each model call, as the AI SDK's `prepareStep` in Think. */
1277
+ beforeStep(
1278
+ _ctx: PrepareStepContext
1279
+ ): StepConfig | void | Promise<StepConfig | void>;
1280
+ /** After each step, as in 0.24. */
1281
+ onStepEnd(ctx: StepContext): void | Promise<void>;
1282
+ /** @deprecated Prefer `onStepEnd`, as in 0.24. */
1283
+ onStepFinish(_ctx: StepContext): void | Promise<void>;
1284
+ onChunk(_ctx: ChunkContext): void | Promise<void>;
1285
+ onChatResponse(_result: ChatResponseResult): void | Promise<void>;
1286
+ onChatError(error: unknown, _ctx?: ChatErrorContext): unknown;
1287
+ classifyChatError(
1288
+ _error: unknown,
1289
+ _ctx?: ChatErrorContext
1290
+ ): ChatErrorClassification | void;
1291
+ /**
1292
+ * Result of the most recent refresh when `hydrationByteBudget` applies.
1293
+ * `truncated` means `this.messages` is a recent window of a larger
1294
+ * stored transcript.
1295
+ */
1296
+ protected get _lastHydration(): HydrationResult | null;
1297
+ get messages(): UIMessage[];
1298
+ /** The channel of the running turn, if it resolved to one. */
1299
+ get activeChannel(): ChannelContext | undefined;
1300
+ /**
1301
+ * The server-supplied metadata stamped on the turn's user message, as on
1302
+ * Think: read from the latest user message, so a recovered or continued
1303
+ * turn reads the same value.
1304
+ */
1305
+ get activeTurnMetadata(): Record<string, unknown> | undefined;
1306
+ /** The turn running now, if any. */
1307
+ get activeTurn(): ActiveTurn | undefined;
1308
+ /** Durable conversation history, as in 0.24: the harness's Sessions. */
1309
+ get sessions(): Sessions;
1310
+ /** The durable chunk log replies stream to, as in 0.24. */
1311
+ get streams(): Streams;
1312
+ /**
1313
+ * Hand out an RPC stub to this agent's Workspace, as in 0.24.
1314
+ * `getWorkspace(stub)` from `@cloudflare/computer` calls it to reach the
1315
+ * Workspace from another Worker or Durable Object. Only a Workspace this
1316
+ * agent owns can hand out a stub.
1317
+ */
1318
+ __getWorkspaceStub(): Promise<WorkspaceStub>;
1319
+ /**
1320
+ * Controls how overlapping user submit requests behave while another
1321
+ * chat turn is already active or queued, as in 0.24.
1322
+ *
1323
+ * @default "queue"
1324
+ */
1325
+ messageConcurrency: MessageConcurrency;
1326
+ getMessages(): Promise<UIMessage[]>;
1327
+ /** Re-read the transcript and return it, as in 0.24. */
1328
+ protected syncMessagesFromStorage(): Promise<UIMessage[]>;
1329
+ /** Add messages to the conversation and run a turn over it. */
1330
+ saveMessages(
1331
+ messages:
1332
+ | UIMessage[]
1333
+ | ((current: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>),
1334
+ options?: SaveMessagesOptions
1335
+ ): Promise<SaveMessagesResult>;
1336
+ clearMessages(): Promise<void>;
1337
+ protected continueLastTurn(
1338
+ body?: Record<string, unknown>,
1339
+ options?: SaveMessagesOptions & {
1340
+ trigger?: TurnTrigger;
1341
+ channel?: string;
1342
+ }
1343
+ ): Promise<SaveMessagesResult>;
1344
+ /** Add messages to the conversation without running a turn. */
1345
+ addMessages(
1346
+ messages:
1347
+ | UIMessage[]
1348
+ | ((current: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>),
1349
+ options?: AddMessagesOptions
1350
+ ): Promise<void>;
1351
+ /**
1352
+ * Run one host operation for a sandboxed extension, as in 0.24.
1353
+ * `HostBridgeLoopback` calls this after it checks the extension's
1354
+ * permissions.
1355
+ *
1356
+ * @internal
1357
+ */
1358
+ _cfHostBridge<K extends ThinkHostOperation>(
1359
+ operation: K,
1360
+ args: Parameters<ThinkHostApi[K]>
1361
+ ): Promise<Awaited<ReturnType<ThinkHostApi[K]>>>;
1362
+ /**
1363
+ * Repair a single interrupted tool call: a tool part with no settled
1364
+ * result, left behind when a stream was cut off. Returns the part that
1365
+ * takes its place in the transcript, as in 0.24. A call the
1366
+ * conversation moved past (an approval never given, an approved call no
1367
+ * turn ran, a client's call never answered) is told to the model in
1368
+ * Think's words. For a server tool an interruption cut off, the default
1369
+ * is the harness's repair: a call to a tool safe to run again stays as
1370
+ * it was, any other becomes an errored result.
1371
+ */
1372
+ protected repairInterruptedToolPart(
1373
+ part: UIMessage["parts"][number]
1374
+ ): UIMessage["parts"][number];
1375
+ protected appendMessageToHistory(
1376
+ message: UIMessage,
1377
+ parentId?: string | null
1378
+ ): Promise<UIMessage>;
1379
+ /** Update a stored message, and the message view with it, as in 0.24. */
1380
+ protected updateMessageInHistory(message: UIMessage): Promise<UIMessage>;
1381
+ /**
1382
+ * The running messenger turn's context, as in 0.24; outside one, the
1383
+ * latest message's.
1384
+ */
1385
+ getMessengerContext(): MessengerContext | undefined;
1386
+ /**
1387
+ * Run a turn for a messenger event, as in 0.24: the context is kept on
1388
+ * the user message, and the turn runs on the messenger's channel.
1389
+ */
1390
+ chatWithMessengerContext(
1391
+ userMessage: string | UIMessage,
1392
+ callback: StreamCallback,
1393
+ context: MessengerContext,
1394
+ options?: ChatOptions
1395
+ ): Promise<void>;
1396
+ /**
1397
+ * Whether the latest message has a tool call waiting on a client, as on
1398
+ * Think: an approval, or a call with no result to a tool a client
1399
+ * answers. A call to any other tool was the server's to run; unanswered
1400
+ * in a stored reply, it is dead (a removed tool, or an MCP tool not yet
1401
+ * reconnected, included).
1402
+ */
1403
+ protected hasPendingInteraction(): boolean;
1404
+ /**
1405
+ * Resolve `true` once no operation is open and nothing waits on a client,
1406
+ * or `false` when `timeout` milliseconds pass first, as in 0.24.
1407
+ */
1408
+ protected waitUntilStable(options?: { timeout?: number }): Promise<boolean>;
1409
+ runTurn(options: RunTurnWait): Promise<TurnResult>;
1410
+ runTurn(options: RunTurnSubmit): Promise<SubmitMessagesResult>;
1411
+ runTurn(options: RunTurnStream): Promise<void>;
1412
+ submitMessages(
1413
+ messages: UIMessage[],
1414
+ options?: SubmitMessagesOptions
1415
+ ): Promise<SubmitMessagesResult>;
1416
+ inspectSubmission(
1417
+ submissionId: string
1418
+ ): Promise<ThinkSubmissionInspection | null>;
1419
+ listSubmissions(
1420
+ options?: ListSubmissionsOptions
1421
+ ): Promise<ThinkSubmissionInspection[]>;
1422
+ deleteSubmission(submissionId: string): Promise<boolean>;
1423
+ deleteSubmissions(options?: DeleteSubmissionsOptions): Promise<number>;
1424
+ /** Called when a submission's status changes, as in 0.24. */
1425
+ protected onSubmissionStatus(
1426
+ _submission: ThinkSubmissionInspection
1427
+ ): void | Promise<void>;
1428
+ waitForSubmission(
1429
+ submissionId: string,
1430
+ options?: WaitForSubmissionOptions
1431
+ ): Promise<ThinkSubmissionInspection | null>;
1432
+ chat(
1433
+ userMessage: TurnInputMessages,
1434
+ callback: StreamCallback,
1435
+ options?: ChatOptions
1436
+ ): Promise<void>;
1437
+ cancelSubmission(
1438
+ submissionId: string,
1439
+ reason?: unknown
1440
+ ): Promise<CancelSubmissionResult>;
1441
+ /** Stop one turn by its request id; it ends `aborted`. */
1442
+ protected abortRequest(requestId: string, reason?: unknown): void;
1443
+ /**
1444
+ * Stop one turn by its request id, as 0.24 did. An agent-tool run
1445
+ * whose turn it is reports the reason.
1446
+ */
1447
+ cancelChat(requestId: string, reason?: string): void;
1448
+ /** Stop every turn, running or waiting; each ends `aborted`. */
1449
+ protected abortAllRequests(): void;
1450
+ /**
1451
+ * Stop every turn, running or waiting, and keep the transcript. A
1452
+ * `clearMessages` resets the session as well.
1453
+ */
1454
+ protected resetTurnState(): void;
1455
+ cancelAllChats(): void;
1456
+ /**
1457
+ * Start the continuation a decision asked for: the reply goes on with
1458
+ * the outcomes the transcript holds by now.
1459
+ * @internal Queue callback.
1460
+ */
1461
+ _cfRunConnectionlessContinuation(payload?: {
1462
+ executionId?: string /** The reply that held the paused call when it was decided. */;
1463
+ pausedIn?: string;
1464
+ }): Promise<void>;
1465
+ /**
1466
+ * As in 0.24: how often an interrupted turn is attempted again. `true`
1467
+ * keeps the default budget.
1468
+ */
1469
+ chatRecovery: ChatRecoveryConfig;
1470
+ /**
1471
+ * As in 0.24: decide what an interrupted turn does. Return
1472
+ * `{ continue: false }` to give it up; the default continues it within
1473
+ * the `chatRecovery` budget.
1474
+ */
1475
+ protected onChatRecovery(
1476
+ _ctx: ChatRecoveryContext
1477
+ ): Promise<ChatRecoveryOptions | void>;
1478
+ /**
1479
+ * As in 0.24: how long a model stream may send nothing before the turn
1480
+ * is treated as interrupted. `0`, the default, turns the watchdog off.
1481
+ */
1482
+ chatStreamStallTimeoutMs: number;
1483
+ /**
1484
+ * As in 0.24 (N9): forwarding a sub-agent's chunks is progress for the
1485
+ * turn that waits on it. The child's output goes to the tabs, not into
1486
+ * this turn's stream, so the turn is credited on its run (the credit the
1487
+ * chat turn's recovery budget reads), at most once per throttle window.
1488
+ * A silent child credits nothing, and its parent is still given up.
1489
+ */
1490
+ protected _onAgentToolStreamProgress(): Promise<void>;
1491
+ _chatRecoveryRetry(data?: Record<string, unknown>): Promise<void>;
1492
+ _chatRecoveryContinue(data?: Record<string, unknown>): Promise<void>;
1493
+ /**
1494
+ * Post a piece of a recovered messenger reply, for a thread's sub-agent,
1495
+ * as 0.24 did: only the agent that owns the messenger posts it.
1496
+ *
1497
+ * @internal
1498
+ */
1499
+ _cf_deliverRecoveredMessengerReply(input: RecoveredReplyPost): Promise<{
1500
+ chunks: number;
1501
+ }>;
1502
+ /**
1503
+ * TEMPORARY: remove in the next minor. Think's start step for the
1504
+ * recovered replies think@0.24.0 kept; the shell runs it at start.
1505
+ * @internal
1506
+ */
1507
+ _replayMessengerRecoveryDeliveries(): Promise<void>;
1508
+ /**
1509
+ * TEMPORARY: remove in the next minor. Release the reply held for a
1510
+ * think@0.24.0 recovery incident, as 0.24 did.
1511
+ * @internal
1512
+ */
1513
+ _releaseMessengerRecovery(
1514
+ incidentId: string,
1515
+ outcome: "completed" | "interrupted",
1516
+ text?: string
1517
+ ): Promise<void>;
1518
+ _cfRetryMessengerRecoveryDelivery(): Promise<void>;
1519
+ /**
1520
+ * Run one media-eviction pass queued on the Agent queue, by a sub-agent
1521
+ * facet, as in 0.24.
1522
+ * @internal Queue callback.
1523
+ */
1524
+ _cfEvictAgedMedia(): Promise<void>;
1525
+ /**
1526
+ * The message put back into the chat when a `detached: { notify: true }`
1527
+ * run ends, as 0.24 worded it. Override it (an empty string sends none).
1528
+ */
1529
+ protected formatDetachedCompletion(
1530
+ run: AgentToolRunInfo,
1531
+ result: AgentToolLifecycleResult
1532
+ ): string;
1533
+ /**
1534
+ * The message put into the chat when a `detached: { onMilestones }`
1535
+ * milestone is reached, as 0.24 worded it. Override it (an empty string
1536
+ * sends none).
1537
+ */
1538
+ protected formatDetachedMilestone(
1539
+ run: AgentToolRunInfo,
1540
+ milestone: AgentToolMilestone
1541
+ ): string;
1542
+ /**
1543
+ * `detached: { notify: true }`: the run's end becomes a submitted turn,
1544
+ * once per run and status, as in 0.24.
1545
+ */
1546
+ _cfDetachedNotifyFinish(
1547
+ run: AgentToolRunInfo,
1548
+ result: AgentToolLifecycleResult
1549
+ ): Promise<void>;
1550
+ /**
1551
+ * A milestone of a detached run, as in 0.24: `"narrate"` adds an
1552
+ * assistant line (no model call, once per run and name); `"react"`
1553
+ * submits a user turn (once per run and name).
1554
+ */
1555
+ protected _deliverDetachedMilestone(
1556
+ run: AgentToolRunInfo,
1557
+ milestone: AgentToolMilestone,
1558
+ mode: "react" | "narrate"
1559
+ ): Promise<void>;
1560
+ /**
1561
+ * A detached run's delivery that could land mid-turn (`serialize`) waits
1562
+ * for the turn running now to end, as 0.24 ran it between turns; an
1563
+ * explicit cancel may come from inside a turn, so it runs at once.
1564
+ */
1565
+ protected _runDetachedDelivery(
1566
+ invoke: () => Promise<void>,
1567
+ options?: {
1568
+ serialize?: boolean;
1569
+ }
1570
+ ): Promise<void>;
1571
+ /** The message an agent-tool run's input becomes. */
1572
+ protected formatAgentToolInput(input: unknown): UIMessage;
1573
+ /** A completed agent-tool run's output. Default: none. */
1574
+ protected getAgentToolOutput(_runId: string): unknown;
1575
+ /** A completed agent-tool run's summary. Default: its reply's text. */
1576
+ protected getAgentToolSummary(runId: string, output: unknown): string;
1577
+ reportProgress<T = unknown>(
1578
+ progress: AgentToolProgress<T>,
1579
+ options?: {
1580
+ persist?: boolean;
1581
+ }
1582
+ ): Promise<void>;
1583
+ startAgentToolRun(
1584
+ input: unknown,
1585
+ options: {
1586
+ runId: string;
1587
+ signal?: AbortSignal;
1588
+ eventDelivery?: "full" | "terminal";
1589
+ }
1590
+ ): Promise<AgentToolRunInspection>;
1591
+ cancelAgentToolRun(runId: string, reason?: unknown): Promise<void>;
1592
+ inspectAgentToolRun(
1593
+ runId: string,
1594
+ _options?: {
1595
+ reconcile?: boolean;
1596
+ }
1597
+ ): Promise<AgentToolRunInspection | null>;
1598
+ getAgentToolChunks(
1599
+ runId: string,
1600
+ options?: {
1601
+ afterSequence?: number;
1602
+ }
1603
+ ): Promise<AgentToolStoredChunk[]>;
1604
+ /**
1605
+ * Follow the run: its chunks after `afterSequence`, then each chunk its
1606
+ * reply streams, until the run ends or `signal` aborts. Cancelling the
1607
+ * stream only detaches.
1608
+ *
1609
+ * The stream carries newline-delimited JSON, one chunk a line, as bytes:
1610
+ * a stream that crosses the sub-agent's RPC boundary can carry nothing
1611
+ * else. It is typed as the chunks it encodes, as released.
1612
+ */
1613
+ tailAgentToolRun(
1614
+ runId: string,
1615
+ options?: {
1616
+ afterSequence?: number;
1617
+ signal?: AbortSignal;
1618
+ }
1619
+ ): Promise<ReadableStream<AgentToolStoredChunk>>;
1620
+ }
1621
+ //#endregion
1622
+ //#region src/messengers/events.d.ts
1623
+ type MessengerEventKind =
1624
+ | "direct-message"
1625
+ | "mention"
1626
+ | "subscribed-message"
1627
+ | "action"
1628
+ | "delivery-event";
1629
+ interface MessengerAuthor {
1630
+ fullName?: string;
1631
+ isBot?: boolean | "unknown";
1632
+ isMe?: boolean;
1633
+ userId: string;
1634
+ userName?: string;
1635
+ }
1636
+ interface MessengerAttachment {
1637
+ data?: ArrayBuffer;
1638
+ fetch?: () => Promise<ArrayBuffer>;
1639
+ /**
1640
+ * Platform-specific metadata needed to re-fetch the attachment after the
1641
+ * event has been serialized (e.g. across a sub-agent Durable Object hop).
1642
+ * Adapters store identifiers here — Telegram `fileId`, WhatsApp `mediaId`,
1643
+ * etc. — that survive serialization even when `fetch`, `data`, and `raw`
1644
+ * cannot, so a downstream agent can reconstruct the download closure.
1645
+ */
1646
+ fetchMetadata?: Record<string, string>;
1647
+ id?: string;
1648
+ mediaType?: string;
1649
+ name?: string;
1650
+ raw?: unknown;
1651
+ size?: number;
1652
+ text?: string;
1653
+ url?: string;
1654
+ }
1655
+ interface MessengerThread {
1656
+ channelId?: string;
1657
+ channelName?: string;
1658
+ id: string;
1659
+ isDirectMessage: boolean;
1660
+ providerThreadId: string;
1661
+ title?: string;
1662
+ }
1663
+ interface MessengerMessage {
1664
+ attachments: MessengerAttachment[];
1665
+ author: MessengerAuthor;
1666
+ createdAt?: Date;
1667
+ id: string;
1668
+ isMention?: boolean;
1669
+ providerMessageId: string;
1670
+ raw?: unknown;
1671
+ text: string;
1672
+ }
1673
+ interface MessengerAction {
1674
+ actionId: string;
1675
+ messageId?: string;
1676
+ raw?: unknown;
1677
+ user?: MessengerAuthor;
1678
+ value?: string;
1679
+ }
1680
+ interface MessengerCapabilities {
1681
+ canEditMessages?: boolean;
1682
+ canStream?: boolean;
1683
+ maxMessageLength?: number;
1684
+ supportsActions?: boolean;
1685
+ supportsAttachments?: boolean;
1686
+ supportsEphemeral?: boolean;
1687
+ }
1688
+ interface MessengerContext {
1689
+ action?: MessengerAction;
1690
+ author?: MessengerAuthor;
1691
+ capabilities: MessengerCapabilities;
1692
+ kind: MessengerEventKind;
1693
+ message?: MessengerMessage;
1694
+ messengerId: string;
1695
+ provider: string;
1696
+ /**
1697
+ * Earlier messages folded into this event, oldest first. A quick run of
1698
+ * messages in one thread is answered once, for its newest message (the Chat
1699
+ * SDK `burst` concurrency strategy); the rest arrive here. They are part of
1700
+ * this turn's input: the model-facing user message renders them before
1701
+ * `message`, and their attachments are listed with its own.
1702
+ */
1703
+ skipped?: MessengerMessage[];
1704
+ thread: MessengerThread;
1705
+ }
1706
+ interface MessengerEvent extends MessengerContext {
1707
+ raw?: unknown;
1708
+ }
1709
+ /**
1710
+ * The context persisted on a messenger turn's user message. Built from the
1711
+ * serializable form of the event, so raw platform payloads and attachment
1712
+ * bytes are never stored and a live turn matches its recovered replay.
1713
+ */
1714
+ declare function messengerContextFromEvent(
1715
+ event: MessengerEvent
1716
+ ): MessengerContext;
1717
+ declare function serializableMessengerEvent(
1718
+ event: MessengerEvent
1719
+ ): MessengerEvent;
1720
+ /**
1721
+ * Customizes how channel (non-DM) speaker names are prefixed onto model-facing
1722
+ * text. By default, speaker labels use `fullName || userName || userId`.
1723
+ * Direct messages never get a speaker prefix, regardless of this setting.
1724
+ * Return `null`/empty to suppress the prefix for that author.
1725
+ */
1726
+ type ChannelSpeakerLabel = (
1727
+ author: MessengerAuthor
1728
+ ) => string | null | undefined;
1729
+ declare function resolveChannelSpeakerLabel(
1730
+ author: MessengerAuthor | undefined,
1731
+ channelSpeakerLabel?: ChannelSpeakerLabel
1732
+ ): string | undefined;
1733
+ declare function toMessengerUserMessage(
1734
+ event: MessengerEvent,
1735
+ channelSpeakerLabel?: ChannelSpeakerLabel
1736
+ ): UIMessage;
1737
+ //#endregion
1738
+ //#region src/messengers/delivery.d.ts
1739
+ declare const EMPTY_MESSENGER_RESPONSE =
1740
+ "I couldn't produce a text response. Please try again.";
1741
+ declare const ERROR_MESSENGER_RESPONSE =
1742
+ "Sorry, I couldn't answer that right now. Please try again.";
1743
+ declare const INTERRUPTED_MESSENGER_RESPONSE =
1744
+ "Sorry, my reply was interrupted. Please send your message again if you'd like me to retry.";
1745
+ interface TextStreamCallbackOptions {
1746
+ /**
1747
+ * Streamed as the reply when a turn completes without text, so surfaces that
1748
+ * wait for the first chunk before posting never post an empty message.
1749
+ */
1750
+ emptyText?: string;
1751
+ onVisibleStart?: () => Promise<void> | void;
1752
+ visibleSoftLimit?: number;
1753
+ }
1754
+ declare class TextStreamCallback extends RpcTarget implements StreamCallback {
1755
+ private readonly emptyText?;
1756
+ private readonly onVisibleStart?;
1757
+ private readonly textSegmentJoiner;
1758
+ private readonly visibleChunks;
1759
+ private readonly wakeups;
1760
+ private readonly visibleSoftLimit?;
1761
+ private chatRequestId?;
1762
+ private closed;
1763
+ private interrupted;
1764
+ private recoveredReplyDelivered;
1765
+ private error?;
1766
+ private text;
1767
+ private visibleClosed;
1768
+ private visibleLimitReachedValue;
1769
+ private visibleStarted;
1770
+ private visibleTextValue;
1771
+ constructor(options?: TextStreamCallbackOptions);
1772
+ onStart(event: ChatStartEvent): void;
1773
+ onEvent(json: string): void;
1774
+ onDone(): void;
1775
+ onError(error: string): void;
1776
+ onInterrupted(info?: ChatInterruptedInfo): void;
1777
+ wasInterrupted(): boolean;
1778
+ /** Whether the target posts the recovered reply to the thread itself. */
1779
+ targetDeliversRecoveredReply(): boolean;
1780
+ /** Ends a completed turn, streaming `emptyText` if it produced no text. */
1781
+ complete(): void;
1782
+ close(): void;
1783
+ fail(error: unknown): void;
1784
+ hasText(): boolean;
1785
+ /**
1786
+ * Resolves `true` once there is visible text to post, or `false` when the
1787
+ * stream ends without any, so a caller can avoid posting an empty reply.
1788
+ */
1789
+ hasVisibleOutput(): Promise<boolean>;
1790
+ remainingText(): string;
1791
+ requestId(): string | undefined;
1792
+ textSoFar(): string;
1793
+ visibleLimitReached(): boolean;
1794
+ visibleText(): string;
1795
+ stream(): AsyncIterable<string>;
1796
+ private pushVisibleText;
1797
+ private wake;
1798
+ private markVisibleStarted;
1799
+ }
1800
+ type MessengerReplyStage = "accepted" | "streaming" | "completed";
1801
+ /**
1802
+ * Explicit delivery lifecycle kind, orthogonal to {@link MessengerReplyStage}.
1803
+ * Lets surfaces (voice/CLI especially) tell a final answer from an interim
1804
+ * progress note from a deterministic notice from a control command, rather than
1805
+ * inferring from text shape.
1806
+ */
1807
+ type DeliveryKind = "final" | "interim" | "notice" | "command";
1808
+ /** What a reply cut off at `stage` does on its next attempt. */
1809
+ declare function messengerReplyRecoveryMode(
1810
+ stage: MessengerReplyStage
1811
+ ): "answer" | "apologize" | null;
1812
+ declare function messengerReplyFailureMode(
1813
+ hasStreamedText: boolean,
1814
+ completedModelTurn?: boolean,
1815
+ expectedDeliveryCompletion?: boolean
1816
+ ): "apologize" | "error" | null;
1817
+ interface MessengerDeliveryTarget {
1818
+ cancelChat(
1819
+ requestId: string,
1820
+ reason?: string
1821
+ ): boolean | void | Promise<boolean | void>;
1822
+ chat(
1823
+ userMessage: string | UIMessage,
1824
+ callback: StreamCallback
1825
+ ): Promise<void>;
1826
+ chatWithMessengerContext?(
1827
+ userMessage: string | UIMessage,
1828
+ callback: StreamCallback,
1829
+ context: MessengerEvent
1830
+ ): Promise<void>;
1831
+ /**
1832
+ * Bind the live delivery surface for the duration of the model turn so the
1833
+ * target can reach it from `deliverNotice` while a messenger turn is active.
1834
+ * Returns a restore function (save/restore, so nested turns are safe).
1835
+ */
1836
+ bindActiveDeliverySurface?(surface: MessengerDeliverySurface): () => void;
1837
+ }
1838
+ interface MessengerDeliverySurface {
1839
+ post(
1840
+ message:
1841
+ | string
1842
+ | {
1843
+ markdown: string;
1844
+ }
1845
+ | AsyncIterable<string>
1846
+ ): Promise<unknown>;
1847
+ startTyping?(status?: string): Promise<void>;
1848
+ }
1849
+ interface MessengerDeliveryPolicy {
1850
+ emptyResponseText?: string;
1851
+ errorResponseText?: string;
1852
+ interruptedResponseText?: string;
1853
+ isExpectedDeliveryCompletion?(
1854
+ error: unknown,
1855
+ callback: TextStreamCallback
1856
+ ): boolean;
1857
+ splitText?(text: string): string[];
1858
+ /**
1859
+ * How often, in milliseconds, the typing indicator is re-sent until the
1860
+ * reply's first text is posted. Platforms expire the indicator after a few
1861
+ * seconds. `0` sends it once.
1862
+ * @default 4000
1863
+ */
1864
+ typingRefreshMs?: number;
1865
+ visibleSoftLimit?: number;
1866
+ }
1867
+ interface DeliverMessengerReplyOptions {
1868
+ event: MessengerEvent;
1869
+ /**
1870
+ * Records how far the reply got, for the attempt after a reset:
1871
+ * `"streaming"` once text is visible, `"completed"` once nothing more
1872
+ * should be posted for it.
1873
+ */
1874
+ onStage?: (stage: "streaming" | "completed") => Promise<void> | void;
1875
+ policy?: MessengerDeliveryPolicy;
1876
+ /** The event in its JSON form, handed to `chatWithMessengerContext`. */
1877
+ snapshotEvent?: MessengerEvent;
1878
+ surface: MessengerDeliverySurface;
1879
+ target: MessengerDeliveryTarget;
1880
+ userMessage?: UIMessage;
1881
+ }
1882
+ declare function deliverMessengerReply(
1883
+ options: DeliverMessengerReplyOptions
1884
+ ): Promise<void>;
1885
+ //#endregion
1886
+ //#region src/messengers/reply-task.d.ts
1887
+ /** @internal */
1888
+ type MessengerReplyPayload = {
1889
+ /** The event, as JSON. */ event: MessengerEvent /** The Chat SDK thread, as JSON. */;
1890
+ thread: unknown;
1891
+ };
1892
+ /** Records how far a reply got. @internal */
1893
+ type RecordReplyStage = (stage: "streaming" | "completed") => void;
1894
+ /** The reply the webhook that received its message waits on. @internal */
1895
+ type LiveMessengerReply = {
1896
+ payload: MessengerReplyPayload;
1897
+ answer(record: RecordReplyStage): Promise<void>;
1898
+ };
1899
+ //#endregion
1900
+ //#region src/messengers/chat-sdk.d.ts
1901
+ declare class ThinkMessengerStateAgent extends ChatSdkStateAgent {}
1902
+ type MessengerRespondTo =
1903
+ | "action"
1904
+ | "direct-message"
1905
+ | "mention"
1906
+ | "subscribed-thread";
1907
+ type MessengerConversationMode = "self" | "thread";
1908
+ type MessengerConversationTarget =
1909
+ | {
1910
+ target: "self";
1911
+ }
1912
+ | {
1913
+ agentClass?: SubAgentClass<Agent & MessengerThinkTarget>;
1914
+ name: string;
1915
+ target: "subagent";
1916
+ };
1917
+ type MessengerConversationResolver = (
1918
+ event: MessengerEvent
1919
+ ) => MessengerConversationTarget | Promise<MessengerConversationTarget>;
1920
+ interface MessengerDefinition {
1921
+ adapter: Adapter;
1922
+ adapterName: string;
1923
+ capabilities?: MessengerCapabilities;
1924
+ /**
1925
+ * Customizes how non-DM channel messages are labelled for the model.
1926
+ *
1927
+ * Channel (group) messages use `fullName || userName || userId` by default and
1928
+ * are rendered as `SpeakerName: text` so the model can attribute multi-user
1929
+ * traffic. Direct messages never get a prefix.
1930
+ */
1931
+ channelSpeakerLabel?: ChannelSpeakerLabel;
1932
+ conversation?: MessengerConversationMode | MessengerConversationResolver;
1933
+ delivery?: MessengerDeliveryPolicy;
1934
+ keyShard?: ChatSdkStateAdapterOptions["keyShard"];
1935
+ path?: string;
1936
+ provider: string;
1937
+ respondTo?: readonly MessengerRespondTo[];
1938
+ shardKey?: ChatSdkStateAdapterOptions["shardKey"];
1939
+ subscribeOnMention?: boolean;
1940
+ toEvent?: (
1941
+ input: ChatSdkMessengerEventInput
1942
+ ) => MessengerEvent | Promise<MessengerEvent>;
1943
+ userName: string;
1944
+ verifyWebhook?:
1945
+ | false
1946
+ | ((request: Request) => boolean | Response | Promise<boolean | Response>);
1947
+ }
1948
+ type ThinkMessengers = Record<string, MessengerDefinition>;
1949
+ /** The Chat SDK `concurrency` setting for a Think agent's messengers. */
1950
+ type MessengerConcurrency = ConcurrencyStrategy | ConcurrencyConfig;
1951
+ declare const DEFAULT_MESSENGER_CONCURRENCY: MessengerConcurrency;
1952
+ interface NormalizedMessengerDefinition extends MessengerDefinition {
1953
+ id: string;
1954
+ path: string;
1955
+ respondTo: readonly MessengerRespondTo[];
1956
+ subscribeOnMention: boolean;
1957
+ verifyWebhook:
1958
+ | false
1959
+ | ((request: Request) => boolean | Response | Promise<boolean | Response>);
1960
+ }
1961
+ interface ChatSdkMessengerOptions extends Omit<
1962
+ MessengerDefinition,
1963
+ "adapterName"
1964
+ > {
1965
+ adapterName?: string;
1966
+ }
1967
+ interface ChatSdkMessengerEventInput {
1968
+ action?: ActionEvent;
1969
+ eventKind: MessengerEventKind;
1970
+ message?: Message;
1971
+ raw?: unknown;
1972
+ /**
1973
+ * Earlier messages the Chat SDK's concurrency strategy folded into this one,
1974
+ * oldest first (`MessageContext.skipped`). The runtime's `burst` strategy
1975
+ * answers only the newest message of a quick run and reports the rest here.
1976
+ * {@link defaultChatSdkEvent} carries them on the event's `skipped` so they
1977
+ * reach the model; a custom `toEvent` that ignores them drops them.
1978
+ */
1979
+ skipped?: readonly Message[];
1980
+ thread: Thread;
1981
+ }
1982
+ interface MessengerThinkTarget {
1983
+ cancelChat(
1984
+ requestId: string,
1985
+ reason?: string
1986
+ ): boolean | void | Promise<boolean | void>;
1987
+ chat(
1988
+ userMessage: string | UIMessage,
1989
+ callback: StreamCallback
1990
+ ): Promise<void>;
1991
+ chatWithMessengerContext?(
1992
+ userMessage: string | UIMessage,
1993
+ callback: StreamCallback,
1994
+ context: MessengerEvent
1995
+ ): Promise<void>;
1996
+ }
1997
+ interface MessengerThinkHost extends MessengerThinkTarget {
1998
+ constructor: {
1999
+ name: string;
2000
+ };
2001
+ name: string;
2002
+ parentPath: ReadonlyArray<{
2003
+ className: string;
2004
+ name: string;
2005
+ }>;
2006
+ startFiber(
2007
+ name: string,
2008
+ fn: (ctx: FiberContext) => Promise<void>,
2009
+ options?: StartFiberOptions
2010
+ ): Promise<MessengerFiberStartResult>;
2011
+ resolveFiber(id: string, result: FiberRecoveryResult): Promise<boolean>;
2012
+ /**
2013
+ * Durably accept one messenger reply as a delivery and answer it inline
2014
+ * while this isolate lives. The same id joins a reply still running.
2015
+ */
2016
+ _sendMessengerReply(id: string, live: LiveMessengerReply): Promise<void>;
2017
+ subAgent<T extends Agent>(
2018
+ agentClass: SubAgentClass<T>,
2019
+ name: string
2020
+ ): Promise<SubAgentStub<T>>;
2021
+ /** Keep the host alive while background messenger work runs. */
2022
+ keepAliveWhile?<T>(fn: () => Promise<T>): Promise<T>;
2023
+ }
2024
+ interface MessengerFiberStartResult {
2025
+ accepted: boolean;
2026
+ fiberId: string;
2027
+ snapshot?: unknown;
2028
+ status: string;
2029
+ }
2030
+ declare function chatSdkMessenger(
2031
+ options: ChatSdkMessengerOptions
2032
+ ): MessengerDefinition;
2033
+ declare class ThinkMessengerRuntime {
2034
+ private readonly host;
2035
+ private chat?;
2036
+ private readonly definitionsById;
2037
+ private readonly definitions;
2038
+ private readonly concurrency;
2039
+ constructor(
2040
+ definitions: ThinkMessengers,
2041
+ host: MessengerThinkHost,
2042
+ options?: {
2043
+ concurrency?: MessengerConcurrency;
2044
+ }
2045
+ );
2046
+ get size(): number;
2047
+ initialize(): void;
2048
+ handleRequest(request: Request): Promise<Response | undefined>;
2049
+ /**
2050
+ * Answer again, or apologize, for a reply a reset cut off at `stage`.
2051
+ *
2052
+ * @internal
2053
+ */
2054
+ recoverReply(
2055
+ payload: MessengerReplyPayload,
2056
+ stage: MessengerReplyStage,
2057
+ record: RecordReplyStage
2058
+ ): Promise<void>;
2059
+ /**
2060
+ * After a recovered reply ended or gave up, answer the messages queued
2061
+ * behind it.
2062
+ *
2063
+ * @internal
2064
+ */
2065
+ drainAfterRecovery(payload: MessengerReplyPayload): void;
2066
+ /**
2067
+ * Messages queued behind a reply are drained only by the Chat SDK handler
2068
+ * holding the thread lock. When the isolate running that reply dies, the
2069
+ * queue is stranded until another message arrives, so recovery drains it:
2070
+ * once the dead holder's lock expires, take the lock and hand the queue to
2071
+ * the SDK's own drain. A live holder drains the queue itself, which ends
2072
+ * the wait.
2073
+ */
2074
+ private drainQueuedMessagesInBackground;
2075
+ private drainQueuedMessages;
2076
+ private createChat;
2077
+ private enqueueReply;
2078
+ private answer;
2079
+ /**
2080
+ * Resolve a live delivery surface for an out-of-turn notice (e.g. a scheduled
2081
+ * task or webhook handler calling `deliverNotice`). Uses `chat.thread(id)` —
2082
+ * the chat SDK's supported "post from outside a webhook" primitive, which
2083
+ * returns a postable {@link ChatThread} and infers the adapter from the
2084
+ * thread-id prefix, so it works for every chat-sdk adapter with no per-adapter
2085
+ * wiring. Returns `undefined` when the channel is unregistered or no `threadId`
2086
+ * was supplied so the caller can fail fast.
2087
+ */
2088
+ resolveDeliverySurface(
2089
+ channelId: string,
2090
+ threadId?: string
2091
+ ): Promise<MessengerDeliverySurface | undefined>;
2092
+ /**
2093
+ * Post what chat recovery produced for an interrupted messenger turn: the
2094
+ * text the thread has not seen yet, or the interrupted apology when
2095
+ * recovery gave up. The reply may span several posts; this posts only post
2096
+ * number `chunk` (skipped when out of range) and returns how many there
2097
+ * are, so the caller can checkpoint between posts.
2098
+ */
2099
+ deliverRecoveredReply(input: {
2100
+ messengerId: string;
2101
+ threadId: string;
2102
+ outcome: "completed" | "interrupted";
2103
+ text?: string;
2104
+ partialPosted?: boolean;
2105
+ chunk: number;
2106
+ notice?: true;
2107
+ }): Promise<{
2108
+ chunks: number;
2109
+ }>;
2110
+ private resolveTarget;
2111
+ /**
2112
+ * `ThreadImpl.fromJSON` (what `chat.reviver()` calls) builds the thread
2113
+ * without the Chat's streaming config, so a recovered reply would fall back to
2114
+ * the `"..."` placeholder. Rebuild it from the same fields with that config.
2115
+ */
2116
+ private reviveThread;
2117
+ }
2118
+ declare function normalizeMessengers(
2119
+ messengers: ThinkMessengers
2120
+ ): NormalizedMessengerDefinition[];
2121
+ declare function defaultConversationName(event: MessengerEvent): string;
2122
+ declare function idempotencyKeyForEvent(event: MessengerEvent): string;
2123
+ declare function defaultChatSdkEvent(
2124
+ definition: NormalizedMessengerDefinition,
2125
+ input: ChatSdkMessengerEventInput
2126
+ ): MessengerEvent;
2127
+ /**
2128
+ * Rewrite the bot's own unresolved self-mention to `@<userName>`.
2129
+ *
2130
+ * Adapters resolve every user's `<@id>` mention to a readable `@DisplayName`
2131
+ * except the bot's own, which is deliberately left as a raw id token so mention
2132
+ * detection can still find it. That raw id is therefore the only unresolved
2133
+ * mention that can survive in the text, so once it has served its purpose we
2134
+ * replace it with the bot's configured handle before the model sees it —
2135
+ * reconstructing the readable `@handle` the sender originally typed. Handles
2136
+ * both the angle-bracket form (`<@U123>` / `<@!U123>`, Slack/Discord) and the
2137
+ * bare `@U123` form some adapters normalize to. No-op when the adapter does not
2138
+ * expose a `botUserId`.
2139
+ */
2140
+ declare function resolveSelfMention(
2141
+ text: string,
2142
+ botUserId: string | undefined,
2143
+ userName: string
2144
+ ): string;
2145
+ declare function toMessengerThread(thread: Thread): MessengerThread;
2146
+ declare function toMessengerMessage(message: Message): MessengerMessage;
2147
+ declare function toMessengerAuthor(author: Author): MessengerAuthor;
2148
+ declare function toMessengerAttachment(
2149
+ attachment: Attachment
2150
+ ): MessengerAttachment;
2151
+ //#endregion
2152
+ //#region src/turn-types.d.ts
2153
+ /**
2154
+ * A best-effort internal `onStart` step that failed on this wake and was
2155
+ * skipped so the agent could still come up (#1710).
2156
+ *
2157
+ * - `transcript-hydration` — reading the persisted conversation into the
2158
+ * in-memory message cache failed (e.g. `SQLITE_NOMEM` on an oversized,
2159
+ * media-heavy transcript). The agent starts with an empty in-memory view;
2160
+ * persisted history is untouched and the next safe-boundary sync retries.
2161
+ * - `scheduled-task-reconcile` — declarative scheduled tasks were not
2162
+ * reconciled on this wake; the next successful wake reconciles them.
2163
+ * - `durable-work-recovery` — pending submissions / workflow notifications
2164
+ * were not recovered or drained on this wake.
2165
+ */
2166
+ interface OnStartDegradation {
2167
+ step:
2168
+ | "transcript-hydration"
2169
+ | "scheduled-task-reconcile"
2170
+ | "durable-work-recovery";
2171
+ error: unknown;
2172
+ }
2173
+ /**
2174
+ * Callback interface for streaming chat events from a Think sub-agent.
2175
+ *
2176
+ * Designed to work across the sub-agent RPC boundary — implement as
2177
+ * an RpcTarget in the parent agent and pass to `chat()`.
2178
+ */
2179
+ interface ChatStartEvent {
2180
+ requestId: string;
2181
+ }
2182
+ /**
2183
+ * The sink of a `chat()` turn. The calls are `onStart`, then `onEvent` for
2184
+ * each chunk, then one terminal call: `onDone`, `onError` or
2185
+ * `onInterrupted`.
2186
+ *
2187
+ * A turn the caller cancels itself (its `signal`, or `cancelChat()` with the
2188
+ * id from `onStart`) gets no terminal call. The promise `chat()` returns
2189
+ * resolves, and that is the signal the turn is over. This holds whether the
2190
+ * cancel lands while the reply streams (the partial reply is stored) or
2191
+ * before the turn's message is stored (nothing is stored and the model is
2192
+ * never called).
2193
+ *
2194
+ * A chat cleared under the turn is reported through `onError`, unless the
2195
+ * caller had already cancelled.
2196
+ */
2197
+ interface StreamCallback {
2198
+ onStart(event: ChatStartEvent): void | Promise<void>;
2199
+ onEvent(json: string): void | Promise<void>;
2200
+ onDone(): void | Promise<void>;
2201
+ onError(error: string): void | Promise<void>;
2202
+ /**
2203
+ * The current attempt was interrupted (a stream-stall watchdog abort routed
2204
+ * into bounded recovery, #1626) and its final outcome will NOT arrive through
2205
+ * this callback. One of two things is true:
2206
+ * - a scheduled continuation — running in a LATER isolate invocation, without
2207
+ * this callback — will produce the answer (delivered to other channels,
2208
+ * e.g. WebSocket connections), OR
2209
+ * - the recovery budget was exhausted, so the turn was already terminalized
2210
+ * out-of-band (the configured `terminalMessage` + `onExhausted`) and is
2211
+ * terminally over — there is NO continuation to come.
2212
+ *
2213
+ * This is NOT `onDone` (this attempt did not complete) and NOT `onError` (the
2214
+ * raw stall is not surfaced as a terminal error here); without it the contract
2215
+ * `onStart → onEvent* → (onDone | onError)` is silently abandoned and a
2216
+ * consumer that treats the clean resolve as success finalizes a truncated
2217
+ * partial.
2218
+ *
2219
+ * Consumers should AVOID finalizing the partial on this signal — surface a
2220
+ * "recovering…" / "interrupted, please retry" state, or re-attach via a
2221
+ * durable channel — but must ALSO NOT block indefinitely waiting for a
2222
+ * continuation: per the exhausted case above, one may never come. Optional →
2223
+ * defaults to a no-op, so this is fully backward-compatible.
2224
+ *
2225
+ * Note: a deploy/eviction interruption kills the isolate (and this callback)
2226
+ * before this can fire — the caller observes a transport break instead. This
2227
+ * fires only for an in-isolate interruption (the stall→recovery path).
2228
+ *
2229
+ * `info.deliversRecoveredReply` is true when the interrupted turn was a
2230
+ * messenger turn and this agent will post the recovered answer (or the
2231
+ * interrupted apology, if recovery gives up) to the messenger thread itself.
2232
+ */
2233
+ onInterrupted?(info?: ChatInterruptedInfo): void | Promise<void>;
2234
+ }
2235
+ interface ChatInterruptedInfo {
2236
+ deliversRecoveredReply?: boolean;
2237
+ }
2238
+ /**
2239
+ * Produces server-authored assistant-message metadata from AI SDK stream parts.
2240
+ * Forwarded to the AI SDK `toUIMessageStream` so a Think turn can stamp
2241
+ * structured metadata onto the assistant message it persists. Called for every
2242
+ * stream part; use `part.type` to choose when to return metadata (`start` and
2243
+ * `finish` are the conventional points). Each non-`undefined` return is
2244
+ * shallow-merged into the message's metadata. The return value is broadcast to
2245
+ * clients and persisted, so it must be
2246
+ * JSON-serializable and must not carry server-only secrets.
2247
+ *
2248
+ * `continuation` is true when the turn continues an earlier one (a recovery
2249
+ * continuation or an auto-continue after a tool result). A recovery
2250
+ * continuation streams into the interrupted assistant message, so its `start`
2251
+ * part cannot overwrite keys that message already has: a `createdAt` stamped
2252
+ * on the original `start` survives. Keys the continuation's `start` adds, and
2253
+ * everything from later parts, merge as usual.
2254
+ *
2255
+ * The `Metadata` parameter defaults to the opaque `Record<string, unknown>` used
2256
+ * everywhere metadata rides today; it is the seam a future typed-metadata story
2257
+ * (issue #1676) narrows without a breaking change.
2258
+ */
2259
+ type MessageMetadataCallback<
2260
+ Metadata extends Record<string, unknown> = Record<string, unknown>
2261
+ > = (options: {
2262
+ part: TextStreamPart<ToolSet>;
2263
+ continuation: boolean;
2264
+ }) => Metadata | undefined;
2265
+ /**
2266
+ * Minimal interface for the result of the inference loop.
2267
+ * The AI SDK's `streamText()` result satisfies this interface.
2268
+ */
2269
+ interface StreamableResult {
2270
+ toUIMessageStream(options?: {
2271
+ sendReasoning?: boolean;
2272
+ onError?: (error: unknown) => string;
2273
+ }): AsyncIterable<unknown>;
2274
+ output?: PromiseLike<unknown>;
2275
+ }
2276
+ /**
2277
+ * Options for a chat turn (sub-agent RPC entry point).
2278
+ */
2279
+ interface ChatOptions {
2280
+ signal?: AbortSignal;
2281
+ /**
2282
+ * Client-defined tool schemas to expose to the model for this turn, mirroring
2283
+ * the `clientTools` carried over the WebSocket chat protocol. Use this when a
2284
+ * parent agent delegates to a Think sub-agent over RPC but the sub-agent still
2285
+ * needs access to tools the client (or parent) defines at runtime.
2286
+ *
2287
+ * On their own these are execute-less — the model's call surfaces as a tool
2288
+ * call through the stream callback. Provide {@link ChatOptions.onClientToolCall}
2289
+ * to also resolve those calls inline so the turn can continue to completion.
2290
+ */
2291
+ clientTools?: ClientToolSchema[];
2292
+ /**
2293
+ * Executes a client tool call and returns its output, completing the
2294
+ * round trip for {@link ChatOptions.clientTools} within the same turn.
2295
+ *
2296
+ * Without this, a client-tool call has no result and the turn ends with a
2297
+ * dangling tool call (the RPC stream callback has no inbound result channel).
2298
+ * With it, the model can call a client tool, receive the result, and keep
2299
+ * going — the same multi-step behavior the WebSocket path gets from
2300
+ * `cf_agent_tool_result` messages.
2301
+ */
2302
+ onClientToolCall?: ClientToolExecutor;
2303
+ /** Channel id this turn belongs to. See {@link RunTurnBase.channel}. */
2304
+ channel?: string;
2305
+ /**
2306
+ * Server-supplied metadata for this turn. Persisted on the turn's user
2307
+ * message alongside {@link ChatOptions.channel} (as `metadata.turnMetadata`)
2308
+ * so a recovered/continued turn re-resolves it from durable history, and
2309
+ * readable during the turn via {@link Think.activeTurnMetadata}.
2310
+ *
2311
+ * Trust contract mirrors the channel stamp: only server-side callers can set
2312
+ * it — reserved metadata keys on client-supplied messages are stripped at
2313
+ * intake. This gives messenger/RPC entry points (e.g.
2314
+ * {@link Think.chatWithMessengerContext}) a per-turn, recovery-safe carrier
2315
+ * for facts like "which authenticated principal initiated this turn" without
2316
+ * resorting to mutable agent-wide state.
2317
+ */
2318
+ metadata?: Record<string, unknown>;
2319
+ }
2320
+ /** Input accepted by {@link Think.runTurn}. */
2321
+ type TurnInputMessages =
2322
+ | string
2323
+ | UIMessage
2324
+ | UIMessage[]
2325
+ | ((current: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>);
2326
+ /** Shared base for {@link RunTurnOptions}; only `input` is common across modes. */
2327
+ interface RunTurnBase {
2328
+ input?: TurnInputMessages;
2329
+ /**
2330
+ * Channel id this turn belongs to (resolved against `configureChannels()` /
2331
+ * `getMessengers()`). Sets the turn-scoped channel context and is persisted on
2332
+ * the user message so a recovered/continued turn re-resolves it. Omit it to
2333
+ * run without a channel context. (WebSocket chat turns always run on the
2334
+ * implicit `web` channel.)
2335
+ */
2336
+ channel?: string;
2337
+ }
2338
+ /** Options for {@link Think.runTurn} with `mode: "wait"` (the default). */
2339
+ interface RunTurnWait extends RunTurnBase {
2340
+ mode?: "wait";
2341
+ continuation?: boolean;
2342
+ body?: Record<string, unknown>;
2343
+ signal?: AbortSignal;
2344
+ }
2345
+ /** Options for {@link Think.runTurn} with `mode: "submit"`. */
2346
+ interface RunTurnSubmit extends RunTurnBase {
2347
+ mode: "submit";
2348
+ submissionId?: string;
2349
+ idempotencyKey?: string;
2350
+ metadata?: Record<string, unknown>;
2351
+ }
2352
+ /** Options for {@link Think.runTurn} with `mode: "stream"`. */
2353
+ interface RunTurnStream extends RunTurnBase {
2354
+ mode: "stream";
2355
+ callback: StreamCallback;
2356
+ clientTools?: ClientToolSchema[];
2357
+ onClientToolCall?: ClientToolExecutor;
2358
+ signal?: AbortSignal;
2359
+ }
2360
+ type RunTurnOptions = RunTurnWait | RunTurnSubmit | RunTurnStream;
2361
+ /** Result of {@link Think.runTurn} in `mode: "wait"`. */
2362
+ type TurnResult = SaveMessagesResult & {
2363
+ /** Persisted assistant produced by this completed turn; absent otherwise. */ message?: SessionMessage;
2364
+ /**
2365
+ * Parsed structured output when the turn's `TurnConfig.output` produced
2366
+ * one. A structured output that fails to parse ends the turn with
2367
+ * `status: "error"`.
2368
+ */
2369
+ output?: unknown;
2370
+ continuation: boolean;
2371
+ };
2372
+ /** What admitted a turn. Exposed on {@link ActiveTurn} and {@link TurnContext}. */
2373
+ type TurnTrigger =
2374
+ | "ws-chat"
2375
+ | "rpc"
2376
+ | "programmatic"
2377
+ | "submission"
2378
+ | "scheduled"
2379
+ | "agent-tool"
2380
+ | "auto-continuation"
2381
+ | "recovery-continue"
2382
+ | "recovery-retry";
2383
+ /** Options for {@link Think.addMessages}. */
2384
+ interface AddMessagesOptions {
2385
+ /**
2386
+ * Parent to attach the first message under. Omitted (`undefined`) attaches to
2387
+ * the latest committed leaf at call time; `null` attaches at the root. An
2388
+ * explicit id that does not exist throws (fail fast rather than silently
2389
+ * misattaching). Subsequent messages in an array chain under the previous one.
2390
+ */
2391
+ parentId?: string | null;
2392
+ /**
2393
+ * `"append"` (default) inserts new rows, idempotent by message id.
2394
+ * `"upsert"` inserts, or updates in place when the id already exists (in which
2395
+ * case `parentId` is ignored — re-parenting is not supported).
2396
+ *
2397
+ * Idempotency is by id against the whole session tree, not just the target
2398
+ * path: if a message id already exists *anywhere* in history, `"append"` is a
2399
+ * no-op for it (no new row, no re-parent) and `"upsert"` updates it in place
2400
+ * wherever it lives. In both modes the next message in the array chains under
2401
+ * that existing id, so passing already-present ids mid-array threads new
2402
+ * messages onto the existing branch rather than forking a new one.
2403
+ */
2404
+ mode?: "append" | "upsert";
2405
+ /**
2406
+ * Broadcast the change to connected clients. Default `true`. Has no effect
2407
+ * when called from inside an active turn (e.g. a tool `execute`), where the
2408
+ * live view is intentionally not touched until the next turn's sync.
2409
+ */
2410
+ broadcast?: boolean;
2411
+ }
2412
+ /** Options for {@link Think.deliverNotice}. */
2413
+ interface DeliverNoticeOptions {
2414
+ /**
2415
+ * Target channel id. Defaults to the active turn's channel, else `"web"`.
2416
+ */
2417
+ channel?: string;
2418
+ /**
2419
+ * Also record the notice in the model-visible transcript so the next turn
2420
+ * knows it was said. Default `false`. For the `web` channel the note is always
2421
+ * appended to the transcript (its only render path); `informModel` then only
2422
+ * controls the phrasing.
2423
+ */
2424
+ informModel?: boolean;
2425
+ /** Delivery kind for the wire tag. Default `"notice"`. */
2426
+ kind?: DeliveryKind;
2427
+ /**
2428
+ * Conversation/thread hint, required for out-of-turn delivery to a
2429
+ * multi-thread messenger channel.
2430
+ */
2431
+ thread?: string;
2432
+ }
2433
+ /** @internal Workflow `step.prompt` settings carried on a turn. */
2434
+ type ThinkWorkflowPromptContext = {
2435
+ workflow: {
2436
+ name: string;
2437
+ id: string;
2438
+ stepName: string;
2439
+ eventType: string;
2440
+ };
2441
+ output?: {
2442
+ schema: unknown;
2443
+ };
2444
+ fingerprint?: string;
2445
+ };
2446
+ /**
2447
+ * A chat turn request. Built automatically by each entry path
2448
+ * (WebSocket, chat(), saveMessages, auto-continuation) and passed
2449
+ * to Think's inference loop.
2450
+ */
2451
+ interface TurnInput {
2452
+ signal?: AbortSignal;
2453
+ /** Client-provided tool schemas for dynamic tool registration. */
2454
+ clientTools?: ClientToolSchema[];
2455
+ /**
2456
+ * Executor that resolves client-tool calls inline (RPC `chat()` path). When
2457
+ * present, `clientTools` are built WITH an `execute` that delegates to it, so
2458
+ * the turn completes the tool round trip itself instead of surfacing a
2459
+ * dangling tool call. Not persisted — recovery cannot replay a live executor.
2460
+ */
2461
+ clientToolExecutor?: ClientToolExecutor;
2462
+ /** Custom body fields from the client request. */
2463
+ body?: Record<string, unknown>;
2464
+ /** Internal workflow prompt configuration, never sourced from client body. */
2465
+ workflowPrompt?: ThinkWorkflowPromptContext;
2466
+ /** Whether this is a continuation turn (auto-continue after tool result, recovery). */
2467
+ continuation: boolean;
2468
+ }
2469
+ /**
2470
+ * Context passed to the `beforeTurn` hook.
2471
+ * Contains everything Think assembled — the hook can inspect and override.
2472
+ */
2473
+ interface TurnContext {
2474
+ /** Assembled system prompt: an overridden `getSystemPrompt()`, then context blocks. */
2475
+ system: string;
2476
+ /**
2477
+ * Assembled model messages (truncated, pruned). When a `whenChanged:
2478
+ * "remind"` context block has changed since the prompt froze, its current
2479
+ * value rides at the end, inside the last user message when there is one.
2480
+ */
2481
+ messages: ModelMessage[];
2482
+ /** Merged tool set (workspace + getTools + session + MCP + client + caller). */
2483
+ tools: ToolSet;
2484
+ /**
2485
+ * The language model from getModel(), resolved on first read — a
2486
+ * `beforeTurn` that returns its own `model` without reading this never
2487
+ * resolves the default.
2488
+ */
2489
+ model: LanguageModel;
2490
+ /** Whether this is a continuation turn. */
2491
+ continuation: boolean;
2492
+ /** Custom body fields from the client request. */
2493
+ body?: Record<string, unknown>;
2494
+ /**
2495
+ * The request this turn runs for: the same id `beforePersist`,
2496
+ * `onChatResponse` and `onChatError` see. Undefined for inference that runs
2497
+ * outside an admitted turn.
2498
+ */
2499
+ requestId?: string;
2500
+ /** What admitted this turn. Undefined outside an admitted turn. */
2501
+ trigger?: TurnTrigger;
2502
+ /**
2503
+ * Aborts when the turn is cancelled. Pass it to any I/O `beforeTurn` awaits
2504
+ * so a stopped turn does not wait for it to finish.
2505
+ */
2506
+ abortSignal?: AbortSignal;
2507
+ /**
2508
+ * The messenger thread this turn answers, fixed when the turn was admitted.
2509
+ * Unlike {@link Think.getMessengerContext}, it never falls back to another
2510
+ * turn's message.
2511
+ */
2512
+ messenger?: MessengerContext;
2513
+ }
2514
+ /**
2515
+ * The turn currently running on this agent. See {@link Think.activeTurn}.
2516
+ */
2517
+ interface ActiveTurn {
2518
+ /** Request id shared by every hook, tool call and event of this turn. */
2519
+ requestId: string;
2520
+ trigger: TurnTrigger;
2521
+ continuation: boolean;
2522
+ /** Channel the turn resolved to, when it has one. */
2523
+ channel?: string;
2524
+ }
2525
+ /**
2526
+ * Configuration returned by the `beforeTurn` hook to override defaults.
2527
+ * All fields are optional — return only what you want to change.
2528
+ */
2529
+ interface TurnConfig {
2530
+ /**
2531
+ * Override the model for this turn (e.g. cheap model for continuations).
2532
+ * Accepts a model id string (resolved via the built-in provider, same rules
2533
+ * as {@link Think.getModel}) or a `LanguageModel`.
2534
+ */
2535
+ model?: ThinkModel;
2536
+ /** Override the assembled instructions prompt. */
2537
+ instructions?: string;
2538
+ /** @deprecated Prefer `instructions`. */
2539
+ system?: string;
2540
+ /** Override the assembled messages. */
2541
+ messages?: ModelMessage[];
2542
+ /** Extra tools to merge (additive — spread on top of existing tools). */
2543
+ tools?: ToolSet;
2544
+ /** Limit which tools the model can call (AI SDK activeTools). */
2545
+ activeTools?: string[];
2546
+ /** Force a specific tool call (AI SDK toolChoice). */
2547
+ toolChoice?: Parameters<typeof streamText>[0]["toolChoice"];
2548
+ /** Override maxSteps for this turn. */
2549
+ maxSteps?: number;
2550
+ /**
2551
+ * Additional AI SDK stop conditions for ending the turn early.
2552
+ * Think always keeps its `maxSteps` stop condition as a safety bound.
2553
+ */
2554
+ stopWhen?: StopCondition<ToolSet> | Array<StopCondition<ToolSet>>;
2555
+ /**
2556
+ * Controls whether reasoning chunks are included in the UI message stream
2557
+ * for this turn. Defaults to the instance-level `sendReasoning` setting.
2558
+ */
2559
+ sendReasoning?: boolean;
2560
+ /**
2561
+ * Produces server-authored assistant-message metadata for this turn — the
2562
+ * write path that lets a turn attach structured metadata (e.g. a `createdAt`
2563
+ * timestamp) to the assistant message Think persists, matching the AI SDK
2564
+ * `messageMetadata` callback base `AIChatAgent` + `streamText` already accept.
2565
+ * Overrides the instance-level {@link Think.messageMetadata} for this turn.
2566
+ * Configure from a Think subclass; sandboxed extensions cannot send functions
2567
+ * over RPC. See {@link MessageMetadataCallback} for when it is called and the
2568
+ * serialization constraints on its return value.
2569
+ */
2570
+ messageMetadata?: MessageMetadataCallback;
2571
+ /**
2572
+ * Override the stream-stall inactivity watchdog timeout for THIS turn only
2573
+ * (ms; `0` disables it for this turn). Defaults to the instance-level
2574
+ * `chatStreamStallTimeoutMs`. Because the watchdog measures the gap between
2575
+ * UI-message-stream chunks — which includes server-side tool execution — a
2576
+ * turn known to invoke a slow tool can raise (or disable) the timeout for
2577
+ * just that turn instead of permanently widening the global window. Auto-
2578
+ * resets after the turn.
2579
+ */
2580
+ chatStreamStallTimeoutMs?: number;
2581
+ /** Maximum number of tokens to generate for this turn. */
2582
+ maxOutputTokens?: Parameters<typeof streamText>[0]["maxOutputTokens"];
2583
+ /** Temperature setting for this turn. */
2584
+ temperature?: Parameters<typeof streamText>[0]["temperature"];
2585
+ /** Nucleus sampling setting for this turn. */
2586
+ topP?: Parameters<typeof streamText>[0]["topP"];
2587
+ /** Top-K sampling setting for this turn. */
2588
+ topK?: Parameters<typeof streamText>[0]["topK"];
2589
+ /** Presence penalty setting for this turn. */
2590
+ presencePenalty?: Parameters<typeof streamText>[0]["presencePenalty"];
2591
+ /** Frequency penalty setting for this turn. */
2592
+ frequencyPenalty?: Parameters<typeof streamText>[0]["frequencyPenalty"];
2593
+ /** Stop sequences for this turn. */
2594
+ stopSequences?: Parameters<typeof streamText>[0]["stopSequences"];
2595
+ /** Seed for deterministic sampling when supported by the model. */
2596
+ seed?: Parameters<typeof streamText>[0]["seed"];
2597
+ /** Maximum number of retries for this turn. Set to 0 to disable retries. */
2598
+ maxRetries?: Parameters<typeof streamText>[0]["maxRetries"];
2599
+ /** Timeout configuration for this turn. */
2600
+ timeout?: Parameters<typeof streamText>[0]["timeout"];
2601
+ /** Additional HTTP headers for provider requests on this turn. */
2602
+ headers?: Parameters<typeof streamText>[0]["headers"];
2603
+ /** Provider-specific options (AI SDK providerOptions). */
2604
+ providerOptions?: Record<string, unknown>;
2605
+ /**
2606
+ * Optional AI SDK telemetry configuration for this turn.
2607
+ *
2608
+ * Typed via the `experimental_telemetry` key, which exists in both AI SDK v6
2609
+ * and v7 (`telemetry` is v7-only), so this type resolves under either major.
2610
+ */
2611
+ telemetry?: Parameters<typeof streamText>[0]["experimental_telemetry"];
2612
+ /** @deprecated Prefer `telemetry`. */
2613
+ experimental_telemetry?: Parameters<
2614
+ typeof streamText
2615
+ >[0]["experimental_telemetry"];
2616
+ /**
2617
+ * Optional AI SDK stream transform(s) for this turn (`experimental_transform`).
2618
+ * Forwarded to `streamText` so callers can inspect/rewrite the stream — e.g.
2619
+ * detecting tool results that carry `{ content, sources }` and enqueuing
2620
+ * additional `source` parts via the transform's controller. Accepts a single
2621
+ * transform or an array applied in order.
2622
+ */
2623
+ experimental_transform?: Parameters<
2624
+ typeof streamText
2625
+ >[0]["experimental_transform"];
2626
+ /**
2627
+ * Repairs tool calls that the AI SDK cannot parse or validate before tool
2628
+ * execution. The returned tool call is parsed and validated again. Configure
2629
+ * this function from a Think subclass; sandboxed extensions cannot send
2630
+ * functions over RPC.
2631
+ *
2632
+ * Typed via the `experimental_repairToolCall` key, which exists in both AI
2633
+ * SDK v6 and v7 (`repairToolCall` is v7-only), so this type resolves under
2634
+ * either supported major.
2635
+ */
2636
+ repairToolCall?: Parameters<
2637
+ typeof streamText
2638
+ >[0]["experimental_repairToolCall"];
2639
+ /**
2640
+ * Optional structured-output specification (AI SDK `output`).
2641
+ * Forwarded to `streamText` so the model's final response is parsed
2642
+ * against the supplied schema. Use the AI SDK's `Output.object({ schema })`
2643
+ * / `Output.text()` helpers. Combine with `activeTools: []` on the
2644
+ * terminal turn if your provider strips tools when structured output
2645
+ * is active (e.g. workers-ai-provider).
2646
+ */
2647
+ output?: Parameters<typeof streamText>[0]["output"];
2648
+ }
2649
+ /**
2650
+ * Provider-agnostic semantic classification of a chat-turn error.
2651
+ *
2652
+ * Think ships **no** provider-specific string/code matching — the app owns
2653
+ * that knowledge (it knows which provider/model it talks to), exactly like the
2654
+ * `tokenCounter` it already passes to `compactAfter()`. An app teaches Think
2655
+ * what an error *means* by overriding `classifyChatError()`; Think then reacts
2656
+ * generically (e.g. compact-and-retry on `context_overflow`).
2657
+ *
2658
+ * - `context_overflow` — the prompt exceeded the model's context window
2659
+ * (Anthropic `"prompt is too long"`, OpenAI `context_length_exceeded`, …).
2660
+ * Think compacts and retries when `contextOverflow.reactive` is enabled.
2661
+ * - `rate_limit` / `transient` — a stream error worth retrying (a 429, a
2662
+ * dropped connection). Think routes the turn into bounded chat recovery, like
2663
+ * a stream stall, and schedules the continuation with exponential backoff.
2664
+ * - `fatal` — unrecoverable; surface terminally.
2665
+ * - `unknown` — default; Think applies its existing terminal behavior.
2666
+ */
2667
+ type ChatErrorClassification =
2668
+ | "context_overflow"
2669
+ | "rate_limit"
2670
+ | "transient"
2671
+ | "fatal"
2672
+ | "unknown";
2673
+ /**
2674
+ * Opt-in handling for a turn that overflows the model's context window
2675
+ * mid-flight. Compaction (`compactAfter()`) is only checked between turns, so a
2676
+ * long, tool-heavy turn can grow past the window before the next check; the
2677
+ * provider then rejects the request (`"prompt is too long"` /
2678
+ * `context_length_exceeded`). Both layers reuse the session's compaction
2679
+ * function and are provider-agnostic — the app maps the error via
2680
+ * {@link Think.classifyChatError}; Think never matches provider strings itself.
2681
+ *
2682
+ * Set `Think.contextOverflow` to enable. Leaving it unset disables both layers
2683
+ * (existing terminal behavior).
2684
+ */
2685
+ interface ContextOverflowConfig {
2686
+ /**
2687
+ * Reactive backstop. When a turn fails with an error classified as
2688
+ * `"context_overflow"`, discard the truncated partial, run
2689
+ * `session.compact()`, and re-run the turn from the compacted history. The
2690
+ * partial is intentionally not persisted: the turn restarts from scratch, so
2691
+ * keeping the cut-off assistant message would orphan it beside the recovered
2692
+ * answer (and duplicate any tool work the retry re-issues). If compaction
2693
+ * cannot shorten history or the retry budget is spent, the overflow surfaces
2694
+ * terminally through `onChatError` (classified) — it never loops or ends
2695
+ * silently. Default `false`.
2696
+ */
2697
+ reactive?: boolean;
2698
+ /**
2699
+ * Maximum compact-and-retry attempts for a single overflowing turn (the
2700
+ * reactive backstop). Independent of the proactive guard's cap — see
2701
+ * {@link proactive.maxCompactions}. Default `1`.
2702
+ */
2703
+ maxRetries?: number;
2704
+ /**
2705
+ * Proactive guard. Before each step, read the previous step's model-reported
2706
+ * `usage.inputTokens` and, if it crosses `maxInputTokens * (headroom ?? 0.9)`,
2707
+ * compact in place and feed the recompacted history into the upcoming step —
2708
+ * heading off the provider rejection before it happens. Keys off usage (every
2709
+ * provider reports it), not provider error strings. Unset disables it.
2710
+ *
2711
+ * If a provider omits `inputTokens`, the guard falls back to `usage.totalTokens`
2712
+ * (input + output) — a safe over-approximation that compacts slightly early
2713
+ * rather than missing the threshold. If neither is reported, the guard does
2714
+ * nothing that step (the reactive backstop still catches a genuine overflow).
2715
+ *
2716
+ * `maxCompactions` caps how many times the guard may compact within a single
2717
+ * step loop (default `1`, floored at `1`). It is independent of
2718
+ * {@link maxRetries} (the reactive budget): a no-op compaction would repeat on
2719
+ * every step, so the cap stops the guard from compacting (and emitting
2720
+ * `chat:context:compacted`) on each one.
2721
+ */
2722
+ proactive?: {
2723
+ maxInputTokens: number;
2724
+ headroom?: number;
2725
+ maxCompactions?: number;
2726
+ };
2727
+ }
2728
+ /**
2729
+ * Matches the context-window-overflow error messages of the common providers.
2730
+ * Anthropic (`prompt is too long`), OpenAI (`context_length_exceeded`,
2731
+ * `maximum context length`, `reduce the length of …`), Google Gemini (`exceeds
2732
+ * the maximum number of tokens`, `input token count`), Bedrock / Mistral /
2733
+ * others (`input is too long`, `too many tokens`, `context window`).
2734
+ *
2735
+ * This default deliberately favors recall over precision: a missed overflow
2736
+ * means no recovery (the feature's whole point), whereas a false positive
2737
+ * self-heals — the retry hits the same non-overflow error, the budget is spent,
2738
+ * and it surfaces terminally anyway. The vaguest fragment (`reduce the length`)
2739
+ * is anchored to `of` to match the real OpenAI phrasing without matching
2740
+ * unrelated prose. Apps that need stricter matching can wrap this classifier.
2741
+ */
2742
+ /**
2743
+ * Opt-in default classifier for {@link Think.classifyChatError}. Matches the
2744
+ * context-window-overflow error messages of the common providers (Anthropic,
2745
+ * OpenAI, Google, Bedrock, Mistral, …) and returns `"context_overflow"`.
2746
+ *
2747
+ * Think ships this as an explicitly-imported helper rather than wiring it into
2748
+ * core, so the framework default stays free of provider strings. Assign it (or
2749
+ * delegate to it) when you do not need custom classification:
2750
+ *
2751
+ * @example
2752
+ * ```typescript
2753
+ * import { Think, defaultContextOverflowClassifier } from "@cloudflare/think";
2754
+ *
2755
+ * export class MyAgent extends Think<Env> {
2756
+ * override contextOverflow = { reactive: true };
2757
+ * override classifyChatError = defaultContextOverflowClassifier;
2758
+ * }
2759
+ * ```
2760
+ *
2761
+ * Or combine with your own checks:
2762
+ *
2763
+ * @example
2764
+ * ```typescript
2765
+ * override classifyChatError(error: unknown): ChatErrorClassification | void {
2766
+ * if (isMyRateLimit(error)) return "rate_limit";
2767
+ * return defaultContextOverflowClassifier(error);
2768
+ * }
2769
+ * ```
2770
+ */
2771
+ declare function defaultContextOverflowClassifier(
2772
+ error: unknown
2773
+ ): ChatErrorClassification | undefined;
2774
+ interface ChatErrorContext {
2775
+ requestId?: string;
2776
+ stage: "parse" | "persist" | "turn" | "stream" | "recovery" | "transcript";
2777
+ messagesPersisted?: boolean;
2778
+ /**
2779
+ * `true` when the failed turn was a server-started continuation (for
2780
+ * example after a tool approval or a client tool result) rather than a
2781
+ * turn a client or caller submitted.
2782
+ */
2783
+ continuation?: boolean;
2784
+ /**
2785
+ * App-provided semantic classification (from `classifyChatError`), when
2786
+ * known. Lets `onChatError` overrides and observers distinguish e.g. a
2787
+ * context-overflow from a generic provider failure without re-matching
2788
+ * provider strings.
2789
+ */
2790
+ classification?: ChatErrorClassification;
2791
+ }
2792
+ /**
2793
+ * Context passed to the `beforeStep` hook before each AI SDK step in
2794
+ * the agentic loop. Backed by the AI SDK's `PrepareStepFunction<TOOLS>`
2795
+ * parameter — exposes the previous `steps`, the zero-based `stepNumber`,
2796
+ * the currently selected `model`, the `messages` about to be sent, and
2797
+ * `experimental_context`.
2798
+ *
2799
+ * Pass an explicit `TOOLS` generic for typed previous tool calls / results.
2800
+ *
2801
+ * Limitations (AI SDK boundary, not Think):
2802
+ * - No `abortSignal` is exposed in the context. If you do remote work
2803
+ * inside `beforeStep`, it cannot be cancelled by turn-level abort.
2804
+ * - `experimental_context` is typed `unknown`; users must narrow it.
2805
+ * - `output` cannot be overridden per-step — set it at the turn level
2806
+ * via `TurnConfig.output` (returned from `beforeTurn`).
2807
+ */
2808
+ type PrepareStepContext<TOOLS extends ToolSet = ToolSet> = Parameters<
2809
+ PrepareStepFunction<TOOLS>
2810
+ >[0];
2811
+ /**
2812
+ * Configuration returned by `beforeStep` to override defaults for the
2813
+ * current AI SDK step. This is the AI SDK's `PrepareStepResult<TOOLS>` —
2814
+ * return only the fields you want to override (`model`, `toolChoice`,
2815
+ * `activeTools`, `instructions`, `messages`, `experimental_context`,
2816
+ * `providerOptions`). The previous `system` field remains available as a
2817
+ * deprecated alias.
2818
+ *
2819
+ * `model` is widened to {@link ThinkModel}: like {@link Think.getModel}, you
2820
+ * can return a model id string (resolved via the built-in provider) instead of
2821
+ * a `LanguageModel`. Think resolves it before handing the step to the AI SDK.
2822
+ */
2823
+ type StepConfig<TOOLS extends ToolSet = ToolSet> = Omit<
2824
+ NonNullable<PrepareStepResult<TOOLS>>,
2825
+ "model"
2826
+ > & {
2827
+ model?: ThinkModel;
2828
+ };
2829
+ /**
2830
+ * Context passed to the `beforeToolCall` hook **before** the tool's
2831
+ * `execute` function runs.
2832
+ *
2833
+ * Backed by the AI SDK's `OnToolCallStartEvent` (the parameter of
2834
+ * `experimental_onToolCallStart`). The full `TypedToolCall<TOOLS>`
2835
+ * fields (`toolName`, `toolCallId`, `input`, `providerMetadata`, the
2836
+ * dynamic/invalid/error discriminators) are spread at the top level for
2837
+ * convenience, with the per-call event extras attached:
2838
+ *
2839
+ * - `stepNumber` — index of the current step
2840
+ * - `messages` — conversation messages visible at tool execution time
2841
+ * - `abortSignal` — signal that aborts if the turn is cancelled
2842
+ *
2843
+ * Pass an explicit `TOOLS` generic for full input typing. With a concrete
2844
+ * tool set, narrowing on `ctx.toolName` narrows `ctx.input` to that tool's
2845
+ * input shape:
2846
+ *
2847
+ * ```ts
2848
+ * import type { ToolCallContext } from "@cloudflare/think";
2849
+ * import type { tools } from "./my-tools";
2850
+ *
2851
+ * beforeToolCall(ctx: ToolCallContext<typeof tools>) {
2852
+ * if (ctx.toolName === "search") {
2853
+ * ctx.input.query; // typed as string
2854
+ * }
2855
+ * }
2856
+ * ```
2857
+ */
2858
+ type ToolCallContext<TOOLS extends ToolSet = ToolSet> = PerToolCall<TOOLS> &
2859
+ ToolCallContextExtras;
2860
+ /** Per-call event extras attached to every {@link ToolCallContext}. */
2861
+ type ToolCallContextExtras = {
2862
+ /** Zero-based index of the current step where this tool call occurs. */ readonly stepNumber:
2863
+ | number
2864
+ | undefined /** The conversation messages available at tool execution time. */;
2865
+ readonly messages: ReadonlyArray<ModelMessage> /** Signal for cancelling the operation. */;
2866
+ readonly abortSignal: AbortSignal | undefined;
2867
+ /**
2868
+ * Request id of the turn making this call, matching `TurnContext.requestId`
2869
+ * and `onChatResponse`. Undefined outside an admitted turn.
2870
+ */
2871
+ readonly requestId?: string;
2872
+ };
2873
+ /**
2874
+ * The `TypedToolCall<TOOLS>` union, re-keyed so that discriminating on
2875
+ * `toolName` narrows `input` per tool.
2876
+ *
2877
+ * The AI SDK's `TypedToolCall` includes a `DynamicToolCall` arm whose
2878
+ * `toolName: string` / `input: unknown` overlaps every static tool name —
2879
+ * leaving it in the union collapses `ctx.input` to `unknown` even after a
2880
+ * `toolName` check. When an explicit `TOOLS` generic is passed (so the keys
2881
+ * are a literal union), we distribute over those keys and drop the dynamic
2882
+ * arm so narrowing works. With the default `ToolSet` (keys are `string`) we
2883
+ * fall back to the raw union, preserving the prior loose behavior.
2884
+ */
2885
+ type PerToolCall<TOOLS extends ToolSet> = string extends keyof TOOLS
2886
+ ? TypedToolCall<TOOLS>
2887
+ : {
2888
+ [K in keyof TOOLS]: Extract<
2889
+ TypedToolCall<TOOLS>,
2890
+ {
2891
+ toolName: K;
2892
+ }
2893
+ >;
2894
+ }[keyof TOOLS];
2895
+ /**
2896
+ * Decision returned by `beforeToolCall` to control tool execution.
2897
+ * Return void/undefined to allow execution with original input.
2898
+ *
2899
+ * Discriminated union — each action has a clear, non-overlapping meaning:
2900
+ * - `allow` — execute the tool (optionally with modified input)
2901
+ * - `block` — don't execute; return `reason` as the tool result so the model can adjust
2902
+ * - `substitute` — don't execute; return `output` as the tool result (afterToolCall still fires)
2903
+ */
2904
+ type ToolCallDecision =
2905
+ | {
2906
+ action: "allow" /** Modified input — tool executes with this instead of the original. */;
2907
+ input?: Record<string, unknown>;
2908
+ }
2909
+ | {
2910
+ action: "block" /** Returned as the tool result so the model can adjust. */;
2911
+ reason?: string;
2912
+ }
2913
+ | {
2914
+ action: "substitute" /** The substitute tool output — model sees this instead of real execution. */;
2915
+ output: unknown /** Optional input attribution for the afterToolCall log. */;
2916
+ input?: Record<string, unknown>;
2917
+ };
2918
+ /**
2919
+ * Context passed to the `afterToolCall` hook after a tool executes.
2920
+ *
2921
+ * Backed by the AI SDK's `OnToolExecutionEndEvent`. The full
2922
+ * `TypedToolCall<TOOLS>` fields (`toolName`, `toolCallId`, `input`, …) are
2923
+ * spread at the top level, plus the per-call event extras:
2924
+ *
2925
+ * - `stepNumber` — index of the current step
2926
+ * - `messages` — conversation messages visible at tool execution time
2927
+ * - `toolExecutionMs` — wall-clock execution time in milliseconds
2928
+ * - `durationMs` — deprecated alias for `toolExecutionMs`
2929
+ * - `toolOutput` — AI SDK v7 discriminated outcome
2930
+ * - `success`/`output`/`error` — deprecated normalized outcome aliases:
2931
+ * - on success: `success: true`, `output` typed per tool
2932
+ * - on failure: `success: false`, `error: unknown`
2933
+ *
2934
+ * Pass an explicit `TOOLS` generic for full input **and** output typing.
2935
+ * On the success branch, narrowing on `ctx.toolName` narrows `ctx.output`
2936
+ * to that tool's inferred output type (dynamic tools stay `unknown`):
2937
+ *
2938
+ * ```ts
2939
+ * import type { ToolCallResultContext } from "@cloudflare/think";
2940
+ * import type { tools } from "./my-tools";
2941
+ *
2942
+ * afterToolCall(ctx: ToolCallResultContext<typeof tools>) {
2943
+ * if (ctx.toolName === "search" && ctx.success) {
2944
+ * ctx.output.results; // typed as the `search` tool's output
2945
+ * }
2946
+ * }
2947
+ * ```
2948
+ */
2949
+ type ToolCallResultContext<TOOLS extends ToolSet = ToolSet> =
2950
+ string extends keyof TOOLS
2951
+ ? TypedToolCall<TOOLS> & ToolCallResultBase & ToolCallOutcome<unknown>
2952
+ : {
2953
+ [K in keyof TOOLS]: Extract<
2954
+ TypedToolCall<TOOLS>,
2955
+ {
2956
+ toolName: K;
2957
+ }
2958
+ > &
2959
+ ToolCallResultBase &
2960
+ ToolCallOutcome<InferToolOutput<TOOLS[K]>>;
2961
+ }[keyof TOOLS];
2962
+ /** Per-call extras attached to every {@link ToolCallResultContext}. */
2963
+ type ToolCallResultBase = {
2964
+ readonly stepNumber: number | undefined;
2965
+ readonly messages: ReadonlyArray<ModelMessage> /** Wall-clock execution time in milliseconds. */;
2966
+ readonly toolExecutionMs: number /** @deprecated Prefer `toolExecutionMs`. */;
2967
+ readonly durationMs: number /** Request id of the turn that made this call; see `ToolCallContext`. */;
2968
+ readonly requestId?: string;
2969
+ };
2970
+ /**
2971
+ * The discriminated success/failure outcome of a tool call. On success the
2972
+ * `output` is typed (`O`); on failure the `error` is `unknown`.
2973
+ */
2974
+ type ToolCallOutcome<O> =
2975
+ | {
2976
+ readonly toolOutput: {
2977
+ type: "tool-result";
2978
+ output: O;
2979
+ } /** @deprecated Prefer `toolOutput.type === "tool-result"`. */;
2980
+ readonly success: true /** @deprecated Prefer `toolOutput.output`. */;
2981
+ readonly output: O;
2982
+ readonly error?: never;
2983
+ }
2984
+ | {
2985
+ readonly toolOutput: {
2986
+ type: "tool-error";
2987
+ error: unknown;
2988
+ } /** @deprecated Prefer `toolOutput.type === "tool-error"`. */;
2989
+ readonly success: false;
2990
+ readonly output?: never /** @deprecated Prefer `toolOutput.error`. */;
2991
+ readonly error: unknown;
2992
+ };
2993
+ /**
2994
+ * Context passed to the `onStepFinish` hook after each step completes.
2995
+ *
2996
+ * This is the AI SDK's `StepResult<TOOLS>` (= `OnStepFinishEvent<TOOLS>`) —
2997
+ * the full step record including `text`, `reasoning`, `toolCalls`,
2998
+ * `toolResults`, `files`, `sources`, `usage` (with `cachedInputTokens`,
2999
+ * `reasoningTokens`, `totalTokens`), `finishReason`, `warnings`, `request`,
3000
+ * `response`, and `providerMetadata` (where provider-specific cache
3001
+ * accounting like `cacheCreationInputTokens` lives).
3002
+ *
3003
+ * Pass an explicit `TOOLS` generic for typed `toolCalls`/`toolResults`.
3004
+ */
3005
+ type StepContext<TOOLS extends ToolSet = ToolSet> = Parameters<
3006
+ GenerateTextOnStepFinishCallback<TOOLS>
3007
+ >[0];
3008
+ /**
3009
+ * Context passed to the `onChunk` hook for each streaming chunk.
3010
+ *
3011
+ * This is the AI SDK's `StreamTextOnChunkCallback` event — `{ chunk }`
3012
+ * where `chunk` is a discriminated union of `TextStreamPart` variants
3013
+ * (text-delta, reasoning-delta, source, tool-call, tool-input-start,
3014
+ * tool-input-delta, tool-result, raw).
3015
+ */
3016
+ type ChunkContext<TOOLS extends ToolSet = ToolSet> = Parameters<
3017
+ StreamTextOnChunkCallback<TOOLS>
3018
+ >[0];
3019
+ /**
3020
+ * @internal Re-export of the chunk variant union for consumers that need
3021
+ * to narrow on `chunk.type` without importing `TextStreamPart` directly.
3022
+ */
3023
+ type ChunkPart<TOOLS extends ToolSet = ToolSet> = ChunkContext<TOOLS>["chunk"];
3024
+ /**
3025
+ * Configuration for a sandboxed extension, returned by getExtensions().
3026
+ */
3027
+ interface ExtensionConfig {
3028
+ /** Extension manifest (name, version, permissions, contributions). */
3029
+ manifest: ExtensionManifest;
3030
+ /** JavaScript source code defining the extension's tools. */
3031
+ source: string;
3032
+ }
3033
+ /**
3034
+ * Keys of the global `AiModels` interface (from `@cloudflare/workers-types`)
3035
+ * whose model type extends `T`. Mirrors the derivation `workers-ai-provider`
3036
+ * uses, so the set stays in sync with the installed workers-types version.
3037
+ */
3038
+ type WorkersAIModelIdsExtending<T> = {
3039
+ [K in keyof AiModels]: AiModels[K] extends T ? K : never;
3040
+ }[keyof AiModels];
3041
+ /**
3042
+ * A model id accepted by {@link Think.getModel}.
3043
+ *
3044
+ * Provides editor autocomplete for the Workers AI text-generation catalog
3045
+ * (`@cf/...`) while still accepting **any** string — including
3046
+ * `"<provider>/<model>"` AI Gateway slugs like `"openai/gpt-5.5"`, whose
3047
+ * validity is only known at runtime (the catalog is server-side and changes
3048
+ * independently of these types). The `(string & {})` arm is what keeps
3049
+ * arbitrary strings assignable without collapsing the autocomplete union.
3050
+ */
3051
+ type ThinkModelId =
3052
+ | Exclude<
3053
+ WorkersAIModelIdsExtending<BaseAiTextGeneration>,
3054
+ WorkersAIModelIdsExtending<BaseAiTextToImage>
3055
+ >
3056
+ | (string & {});
3057
+ /**
3058
+ * What {@link Think.getModel} may return: either a fully-constructed AI SDK
3059
+ * `LanguageModel`, or a {@link ThinkModelId} string resolved through Think's
3060
+ * built-in `workers-ai-provider`. Also the input type of {@link Think.resolveModel}.
3061
+ */
3062
+ type ThinkModel = LanguageModel | ThinkModelId;
3063
+ //#endregion
3064
+ //#region src/extensions/released.d.ts
3065
+ /**
3066
+ * Serializable snapshot of TurnContext.
3067
+ * Passed to extension Workers during beforeTurn hook dispatch.
3068
+ * Plain data — no methods, no functions, no classes.
3069
+ */
3070
+ interface TurnContextSnapshot {
3071
+ system: string;
3072
+ toolNames: string[];
3073
+ messageCount: number;
3074
+ continuation: boolean;
3075
+ body?: Record<string, unknown>;
3076
+ modelId: string;
3077
+ requestId?: string;
3078
+ trigger?: string;
3079
+ }
3080
+ /**
3081
+ * Create a serializable snapshot from a TurnContext.
3082
+ *
3083
+ * Pass `model` when `beforeTurn` already overrode it: `ctx.model` lazily
3084
+ * resolves the default model, which may need an AI binding the turn never uses.
3085
+ */
3086
+ declare function createTurnContextSnapshot(
3087
+ ctx: TurnContext,
3088
+ model?: ThinkModel
3089
+ ): TurnContextSnapshot;
3090
+ type TurnSnapshot = ReturnType<typeof createTurnContextSnapshot>;
3091
+ /**
3092
+ * The released hooks, with the snapshot each extension is sent. Only the
3093
+ * snapshot crosses to the extension; `beforeTurn`'s `config` is the fold's
3094
+ * starting point and stays here.
3095
+ *
3096
+ * @internal
3097
+ */
3098
+ type ReleasedHooks = {
3099
+ beforeTurn: [
3100
+ {
3101
+ snapshot: TurnSnapshot;
3102
+ config: TurnConfig;
3103
+ },
3104
+ TurnConfig
3105
+ ];
3106
+ beforeToolCall: [unknown, void];
3107
+ afterToolCall: [unknown, void];
3108
+ onStepFinish: [unknown, void];
3109
+ onChunk: [unknown, void];
3110
+ };
3111
+ //#endregion
3112
+ //#region src/extensions/manager.d.ts
3113
+ interface ExtensionManagerOptions {
3114
+ /** WorkerLoader binding for creating sandboxed extension Workers. */
3115
+ loader: WorkerLoader;
3116
+ /**
3117
+ * Durable Object storage for persisting extensions across hibernation.
3118
+ * If provided, loaded extensions survive DO restarts. Call `restore()`
3119
+ * on each turn to rebuild in-memory state from storage.
3120
+ */
3121
+ storage?: DurableObjectStorage;
3122
+ /**
3123
+ * Factory that creates a loopback Fetcher for workspace access, given
3124
+ * an extension's declared permissions. The returned binding is injected
3125
+ * into the extension worker's `env.host`.
3126
+ *
3127
+ * If not provided, extensions receive no host binding (workspace tools
3128
+ * will get `null` for the host parameter).
3129
+ *
3130
+ * Typically wired up using HostBridgeLoopback via `ctx.exports`:
3131
+ * ```typescript
3132
+ * createHostBinding: (permissions, ownContextLabels) =>
3133
+ * ctx.exports.HostBridgeLoopback({
3134
+ * props: { agentClassName: "ChatSession", agentId: ctx.id.toString(), permissions, ownContextLabels }
3135
+ * })
3136
+ * ```
3137
+ */
3138
+ createHostBinding?: (
3139
+ permissions: ExtensionPermissions,
3140
+ ownContextLabels: string[]
3141
+ ) => Fetcher;
3142
+ /**
3143
+ * Identifies the agent that `createHostBinding` binds to (for example
3144
+ * `${className}:${ctx.id}`). It is part of the Dynamic Worker id of
3145
+ * extensions that receive `env.host`, so a cached worker is never shared
3146
+ * with another agent. Without it, such extensions get a fresh id per
3147
+ * manager instance.
3148
+ */
3149
+ workerIdScope?: string;
3150
+ }
3151
+ declare class ExtensionManager$1 {
3152
+ #private;
3153
+ constructor(options: ExtensionManagerOptions);
3154
+ /**
3155
+ * @internal The extension core these extensions run on, with the agent's
3156
+ * hook timeout per call from now on.
3157
+ */
3158
+ coreFor(timeoutMs: () => number): ExtensionManager<ReleasedHooks>;
3159
+ /**
3160
+ * Restore extensions from DO storage after hibernation.
3161
+ *
3162
+ * Idempotent — skips extensions already in memory. Call this at the
3163
+ * start of each chat turn (e.g. in onChatMessage before getTools).
3164
+ */
3165
+ restore(): Promise<void>;
3166
+ /**
3167
+ * Load an extension from source code.
3168
+ *
3169
+ * The source is a JS object expression with `tools` and `hooks`. Each
3170
+ * tool has `description`, `parameters` (JSON Schema properties), optional
3171
+ * `required` array, and an `execute` async function.
3172
+ *
3173
+ * @returns Summary of the loaded extension including discovered tools.
3174
+ */
3175
+ load(manifest: ExtensionManifest, source: string): Promise<ExtensionInfo>;
3176
+ /**
3177
+ * Unload an extension, removing its tools from the agent.
3178
+ * If an onUnload callback is registered, it fires with the
3179
+ * extension's namespaced context labels so the caller can
3180
+ * remove context blocks from the Session.
3181
+ */
3182
+ unload(name: string): Promise<boolean>;
3183
+ /**
3184
+ * Register a callback invoked when an extension is unloaded.
3185
+ * Think uses this to remove the extension's context blocks from Session.
3186
+ */
3187
+ onUnload(
3188
+ cb: (name: string, contextLabels: string[]) => void | Promise<void>
3189
+ ): void;
3190
+ /**
3191
+ * Get the namespaced context labels for all loaded extensions
3192
+ * that declare context blocks in their manifests.
3193
+ */
3194
+ getContextLabels(): Array<{
3195
+ extName: string;
3196
+ label: string;
3197
+ }>;
3198
+ /**
3199
+ * Get extension manifest by name.
3200
+ */
3201
+ getManifest(name: string): ExtensionManifest | null;
3202
+ /**
3203
+ * Removed: Think calls each loaded extension's hooks itself, on every
3204
+ * turn. Throws an error that says so; delete the call.
3205
+ */
3206
+ getHookSubscribers(_hookName: string): never;
3207
+ /**
3208
+ * List all loaded extensions.
3209
+ */
3210
+ list(): ExtensionInfo[];
3211
+ /**
3212
+ * Get AI SDK tools from all loaded extensions.
3213
+ *
3214
+ * Tool names are prefixed with the sanitized extension name to avoid
3215
+ * collisions: e.g. extension "github" with tool "create_pr" → "github_create_pr".
3216
+ */
3217
+ getTools(): ToolSet;
3218
+ }
3219
+ //#endregion
3220
+ export {
3221
+ ThinkMessengers as $,
3222
+ ActionKind as $n,
3223
+ SaveMessagesResult$1 as $t,
3224
+ ToolCallDecision as A,
3225
+ ThinkScheduledTaskContext as An,
3226
+ MessengerEvent as At,
3227
+ ChatSdkMessengerOptions as B,
3228
+ ChannelIngress as Bn,
3229
+ ChatRecoveryExhaustedContext as Bt,
3230
+ StepConfig as C,
3231
+ ThinkSubmissionInspection as Cn,
3232
+ messengerReplyRecoveryMode as Ct,
3233
+ ThinkModel as D,
3234
+ ThinkHostMessage as Dn,
3235
+ MessengerAuthor as Dt,
3236
+ StreamableResult as E,
3237
+ ThinkHostFileEntry as En,
3238
+ MessengerAttachment as Et,
3239
+ TurnInputMessages as F,
3240
+ ChannelCapabilities as Fn,
3241
+ resolveChannelSpeakerLabel as Ft,
3242
+ MessengerConversationTarget as G,
3243
+ Action as Gn,
3244
+ FiberRecoveryContext$1 as Gt,
3245
+ MessengerConcurrency as H,
3246
+ NormalizedChannelDefinition as Hn,
3247
+ ChatRecoveryProgressContext as Ht,
3248
+ TurnResult as I,
3249
+ ChannelContext as In,
3250
+ serializableMessengerEvent as It,
3251
+ MessengerThinkHost as J,
3252
+ ActionAuthorizationContext as Jn,
3253
+ PrepareStepFunction$1 as Jt,
3254
+ MessengerDefinition as K,
3255
+ ActionApprovalDescriptor as Kn,
3256
+ MessageConcurrency$1 as Kt,
3257
+ TurnTrigger as L,
3258
+ ChannelDefinition as Ln,
3259
+ toMessengerUserMessage as Lt,
3260
+ TurnConfig as M,
3261
+ ThinkScheduledTasks as Mn,
3262
+ MessengerMessage as Mt,
3263
+ TurnContext as N,
3264
+ ThinkTime as Nn,
3265
+ MessengerThread as Nt,
3266
+ ThinkModelId as O,
3267
+ ThinkIntervalSchedule as On,
3268
+ MessengerCapabilities as Ot,
3269
+ TurnInput as P,
3270
+ ThinkWallClockSchedule as Pn,
3271
+ messengerContextFromEvent as Pt,
3272
+ ThinkMessengerStateAgent as Q,
3273
+ ActionIdempotencyKey as Qn,
3274
+ SaveMessagesOptions$1 as Qt,
3275
+ defaultContextOverflowClassifier as R,
3276
+ ChannelDeliveryPolicy as Rn,
3277
+ ChatRecoveryConfig$1 as Rt,
3278
+ RunTurnWait as S,
3279
+ SubmitMessagesResult as Sn,
3280
+ messengerReplyFailureMode as St,
3281
+ StreamCallback as T,
3282
+ WaitForSubmissionOptions as Tn,
3283
+ MessengerAction as Tt,
3284
+ MessengerConversationMode as U,
3285
+ ThinkChannels as Un,
3286
+ ChatResponseResult$1 as Ut,
3287
+ DEFAULT_MESSENGER_CONCURRENCY as V,
3288
+ ChannelKind as Vn,
3289
+ ChatRecoveryOptions$1 as Vt,
3290
+ MessengerConversationResolver as W,
3291
+ messengerChannel as Wn,
3292
+ FiberContext$1 as Wt,
3293
+ NormalizedMessengerDefinition as X,
3294
+ ActionConfig as Xn,
3295
+ RejectExecutionOptions as Xt,
3296
+ MessengerThinkTarget as Y,
3297
+ ActionAuthorizationDecision as Yn,
3298
+ PrepareStepResult$1 as Yt,
3299
+ ThinkMessengerRuntime as Z,
3300
+ ActionContext as Zn,
3301
+ ResolvedChatRecoveryConfig as Zt,
3302
+ PrepareStepContext as _,
3303
+ SessionContextOptions as _n,
3304
+ MessengerDeliveryTarget as _t,
3305
+ ChatErrorClassification as a,
3306
+ SkippedTurnReason as an,
3307
+ ExtensionManifest as ar,
3308
+ resolveSelfMention as at,
3309
+ RunTurnStream as b,
3310
+ DeleteSubmissionsOptions as bn,
3311
+ TextStreamCallbackOptions as bt,
3312
+ ChatOptions as c,
3313
+ SubmitMessagesOptions as cn,
3314
+ toMessengerMessage as ct,
3315
+ ChunkPart as d,
3316
+ TypedToolCall$1 as dn,
3317
+ DeliveryKind as dt,
3318
+ SessionMessage$1 as en,
3319
+ ActionPermissionSpec as er,
3320
+ chatSdkMessenger as et,
3321
+ ContextOverflowConfig as f,
3322
+ TypedToolResult as fn,
3323
+ EMPTY_MESSENGER_RESPONSE as ft,
3324
+ OnStartDegradation as g,
3325
+ CompactionErrorHandler as gn,
3326
+ MessengerDeliverySurface as gt,
3327
+ MessageMetadataCallback as h,
3328
+ CompactAfterOptions as hn,
3329
+ MessengerDeliveryPolicy as ht,
3330
+ AddMessagesOptions as i,
3331
+ SkillSource$1 as in,
3332
+ ExtensionInfo as ir,
3333
+ normalizeMessengers as it,
3334
+ ToolCallResultContext as j,
3335
+ ThinkScheduledTaskSchedule as jn,
3336
+ MessengerEventKind as jt,
3337
+ ToolCallContext as k,
3338
+ ThinkScheduledTask as kn,
3339
+ MessengerContext as kt,
3340
+ ChatStartEvent as l,
3341
+ TextStreamPart$1 as ln,
3342
+ toMessengerThread as lt,
3343
+ ExtensionConfig as m,
3344
+ MediaEvictionConfig as mn,
3345
+ INTERRUPTED_MESSENGER_RESPONSE as mt,
3346
+ ExtensionManagerOptions as n,
3347
+ SkillCatalog as nn,
3348
+ action as nr,
3349
+ defaultConversationName as nt,
3350
+ ChatErrorContext as o,
3351
+ StepResult as on,
3352
+ ExtensionPermissions as or,
3353
+ toMessengerAttachment as ot,
3354
+ DeliverNoticeOptions as p,
3355
+ skills_d_exports as pn,
3356
+ ERROR_MESSENGER_RESPONSE as pt,
3357
+ MessengerRespondTo as q,
3358
+ ActionApprovalPolicy as qn,
3359
+ PendingApproval as qt,
3360
+ ActiveTurn as r,
3361
+ SkillRunContext as rn,
3362
+ isAction as rr,
3363
+ idempotencyKeyForEvent as rt,
3364
+ ChatInterruptedInfo as s,
3365
+ StopCondition$1 as sn,
3366
+ ExtensionToolDescriptor as sr,
3367
+ toMessengerAuthor as st,
3368
+ ExtensionManager$1 as t,
3369
+ Skill as tn,
3370
+ ReplyAttachment as tr,
3371
+ defaultChatSdkEvent as tt,
3372
+ ChunkContext as u,
3373
+ Think as un,
3374
+ DeliverMessengerReplyOptions as ut,
3375
+ RunTurnBase as v,
3376
+ ThinkSession as vn,
3377
+ MessengerReplyStage as vt,
3378
+ StepContext as w,
3379
+ ThinkSubmissionStatus as wn,
3380
+ ChannelSpeakerLabel as wt,
3381
+ RunTurnSubmit as x,
3382
+ ListSubmissionsOptions as xn,
3383
+ deliverMessengerReply as xt,
3384
+ RunTurnOptions as y,
3385
+ CancelSubmissionResult as yn,
3386
+ TextStreamCallback as yt,
3387
+ ChatSdkMessengerEventInput as z,
3388
+ ChannelDeliverySurface as zn,
3389
+ ChatRecoveryContext$1 as zt
3390
+ };
3391
+ //# sourceMappingURL=manager-CWGumyKi.d.ts.map