@cloudflare/think 0.10.0 → 0.11.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 (134) hide show
  1. package/README.md +10 -17
  2. package/dist/{chat-sdk-Bb93yaZh.js → chat-sdk-D6cUghsQ.js} +33 -8
  3. package/dist/chat-sdk-D6cUghsQ.js.map +1 -0
  4. package/dist/cli/index.js +224 -55
  5. package/dist/cli/index.js.map +1 -1
  6. package/dist/{codegen-CuPdJRpV.js → codegen-DlA2QQuU.js} +6 -38
  7. package/dist/codegen-DlA2QQuU.js.map +1 -0
  8. package/dist/{config-D512sQYg.d.ts → config-CD7hqncK.d.ts} +5 -5
  9. package/dist/extensions/index.js +1 -1
  10. package/dist/framework/index.d.ts +17 -62
  11. package/dist/framework/index.js +3 -57
  12. package/dist/{think-i1Pkgb1R.d.ts → index-D_S5mETO.d.ts} +1587 -702
  13. package/dist/{manager-BPndMP_6.js → manager-CSk5htym.js} +7 -7
  14. package/dist/{manager-BPndMP_6.js.map → manager-CSk5htym.js.map} +1 -1
  15. package/dist/{manifest-CpB-xngB.d.ts → manifest-DK5HuGga.d.ts} +16 -18
  16. package/dist/messengers/index.d.ts +59 -55
  17. package/dist/messengers/index.js +2 -2
  18. package/dist/messengers/telegram.d.ts +4 -4
  19. package/dist/messengers/telegram.js +1 -1
  20. package/dist/react.d.ts +79 -0
  21. package/dist/react.js +28 -0
  22. package/dist/react.js.map +1 -0
  23. package/dist/server-entry.d.ts +1 -1
  24. package/dist/server-entry.js +1 -1
  25. package/dist/server-entry.js.map +1 -1
  26. package/dist/studio/assets/{angular-html-z-TUogET.js → angular-html-D27LthTc.js} +1 -1
  27. package/dist/studio/assets/{angular-ts-DMGuEVeg.js → angular-ts-DtNL2gQ7.js} +1 -1
  28. package/dist/studio/assets/{apl-KvrEROqd.js → apl-BgEcDqM0.js} +1 -1
  29. package/dist/studio/assets/{astro-Bm_woEti.js → astro-CstbRF9e.js} +1 -1
  30. package/dist/studio/assets/{blade-BdCF3r89.js → blade-CLG-7epG.js} +1 -1
  31. package/dist/studio/assets/{c-CDqDtkvZ.js → c-CssQqwxO.js} +1 -1
  32. package/dist/studio/assets/{cobol-CeFM1vZz.js → cobol-CjmzHCjg.js} +1 -1
  33. package/dist/studio/assets/{coffee-2ed6LBym.js → coffee-B_rqYPkp.js} +1 -1
  34. package/dist/studio/assets/{cpp-Dj3nX0J4.js → cpp-5YyZJlb7.js} +1 -1
  35. package/dist/studio/assets/{crystal-BsIYZMQ3.js → crystal-D7uKze0i.js} +1 -1
  36. package/dist/studio/assets/{css-B48fnuoH.js → css-k9oPgg7G.js} +1 -1
  37. package/dist/studio/assets/{edge-C7qt1aza.js → edge-CGgsSt0x.js} +1 -1
  38. package/dist/studio/assets/{elixir-CiTmwoQ3.js → elixir-BX_d5Evo.js} +1 -1
  39. package/dist/studio/assets/{elm-exDZ-PRY.js → elm-DENxDm5e.js} +1 -1
  40. package/dist/studio/assets/{erb-3fmfgt-Q.js → erb-DvYOup03.js} +1 -1
  41. package/dist/studio/assets/{git-rebase-75I-C7zW.js → git-rebase-BsAdTS5A.js} +1 -1
  42. package/dist/studio/assets/{glimmer-js-JjRzYRv8.js → glimmer-js-e0h98Z67.js} +1 -1
  43. package/dist/studio/assets/{glimmer-ts-DcC_g6bi.js → glimmer-ts-C9s5Kv8m.js} +1 -1
  44. package/dist/studio/assets/{glsl-CHo__hpu.js → glsl-CCiyeTRs.js} +1 -1
  45. package/dist/studio/assets/{graphql-J3cHpSdo.js → graphql-BRtHwsqk.js} +1 -1
  46. package/dist/studio/assets/{hack-or1FCnPg.js → hack-Dnt0QXHh.js} +1 -1
  47. package/dist/studio/assets/{haml-uv3vtlo6.js → haml-EXGmzuB1.js} +1 -1
  48. package/dist/studio/assets/{handlebars--xrOP0sp.js → handlebars-CzyBIDJE.js} +1 -1
  49. package/dist/studio/assets/{highlighted-body-OFNGDK62-D5UBAw6b.js → highlighted-body-OFNGDK62-CQUFKLNu.js} +1 -1
  50. package/dist/studio/assets/{html-CWnTqWKh.js → html-BAT8b_VM.js} +1 -1
  51. package/dist/studio/assets/{html-derivative-DWyLco-z.js → html-derivative-7tkS-r6F.js} +1 -1
  52. package/dist/studio/assets/{http-BGB8mLqf.js → http-Cgka02Qq.js} +1 -1
  53. package/dist/studio/assets/{hurl-BWdvIVUG.js → hurl-Cbkh8WEw.js} +1 -1
  54. package/dist/studio/assets/index-D6n8vpkp.js +390 -0
  55. package/dist/studio/assets/index-DkGWw6ES.css +2 -0
  56. package/dist/studio/assets/{java-BqyrPpKF.js → java-DrRKiUno.js} +1 -1
  57. package/dist/studio/assets/{javascript-D8Aej0xg.js → javascript-9LAnHOxD.js} +1 -1
  58. package/dist/studio/assets/{jinja-SIORrXov.js → jinja-CqRt4prs.js} +1 -1
  59. package/dist/studio/assets/{jison-B2T4v51n.js → jison-BX-IOQpJ.js} +1 -1
  60. package/dist/studio/assets/{json-BFdVRj9r.js → json-dOrE-En8.js} +1 -1
  61. package/dist/studio/assets/{jsx-w4r1xieS.js → jsx-BSTPfqWX.js} +1 -1
  62. package/dist/studio/assets/{julia-BFBtDmmM.js → julia-Dvz-BPmf.js} +1 -1
  63. package/dist/studio/assets/{just-CjAPsU_y.js → just-BHQm0Atq.js} +1 -1
  64. package/dist/studio/assets/{latex-CghDKqKz.js → latex-CxdhxuXv.js} +1 -1
  65. package/dist/studio/assets/{liquid-Cp9loVkE.js → liquid-D-hM-Q_F.js} +1 -1
  66. package/dist/studio/assets/{lua-HNnIDxnY.js → lua-5qtqjLHq.js} +1 -1
  67. package/dist/studio/assets/{marko-BXT10Apm.js → marko-5FJaM2co.js} +1 -1
  68. package/dist/studio/assets/{mdc-CaiOz4_A.js → mdc-BhYW7lCG.js} +1 -1
  69. package/dist/studio/assets/mermaid-GHXKKRXX-CWM2EB-u.js +1 -0
  70. package/dist/studio/assets/{nginx-DgYZ5SY9.js → nginx-rtAXrRye.js} +1 -1
  71. package/dist/studio/assets/{nim-CAMVX-MV.js → nim-DQSmaN9U.js} +1 -1
  72. package/dist/studio/assets/{perl-Dc6Wp7SD.js → perl-B54AdcaE.js} +1 -1
  73. package/dist/studio/assets/{php-DgLi8LNU.js → php-DpvTxCny.js} +1 -1
  74. package/dist/studio/assets/{pug-ZHFv4Vgd.js → pug-Cyffw0Ho.js} +1 -1
  75. package/dist/studio/assets/{qml-DU62cSZp.js → qml-CxRetSkO.js} +1 -1
  76. package/dist/studio/assets/{r-BwU69RSh.js → r-CXWRxrXc.js} +1 -1
  77. package/dist/studio/assets/{razor-BUgi_XZM.js → razor-BJzI-zc9.js} +1 -1
  78. package/dist/studio/assets/{regexp-DuNhqfkW.js → regexp-dqxdfrnE.js} +1 -1
  79. package/dist/studio/assets/{rst-BB3BeaSy.js → rst-BW7eKYj4.js} +1 -1
  80. package/dist/studio/assets/{ruby-T0tkEfUZ.js → ruby-D5Npyj8-.js} +1 -1
  81. package/dist/studio/assets/{sas-CMhZa3S0.js → sas-DZLppjul.js} +1 -1
  82. package/dist/studio/assets/{scss-DtXjZ3vZ.js → scss-CbqoxyAe.js} +1 -1
  83. package/dist/studio/assets/{shellscript-BESt-FLs.js → shellscript-CFHqBeXu.js} +1 -1
  84. package/dist/studio/assets/{shellsession-8irtvYxL.js → shellsession-CbZDA4Bf.js} +1 -1
  85. package/dist/studio/assets/{soy-CIvhOgLR.js → soy-PImjtV58.js} +1 -1
  86. package/dist/studio/assets/{sql-obAOXh1G.js → sql-DhGo8urW.js} +1 -1
  87. package/dist/studio/assets/{stata-D3OCK8xW.js → stata-CjHWbU2v.js} +1 -1
  88. package/dist/studio/assets/{surrealql-Dk_bguB0.js → surrealql-o8Qr4t56.js} +1 -1
  89. package/dist/studio/assets/{svelte-C0-KQt-t.js → svelte-DlSIyEV1.js} +1 -1
  90. package/dist/studio/assets/{templ-lg4nvF9H.js → templ-qizfwU1w.js} +1 -1
  91. package/dist/studio/assets/{tex-BNcQSX7R.js → tex-Ca7T661H.js} +1 -1
  92. package/dist/studio/assets/{ts-tags-AgW9jVv0.js → ts-tags-DUmjLkgl.js} +1 -1
  93. package/dist/studio/assets/{tsx-CL8XyR3d.js → tsx-CfwgIqHW.js} +1 -1
  94. package/dist/studio/assets/{twig-VkSbsH0Y.js → twig-D7NAYUBY.js} +1 -1
  95. package/dist/studio/assets/{typescript-BfD1znAG.js → typescript-Bbz9oX-P.js} +1 -1
  96. package/dist/studio/assets/{vue-html-w3sbjuft.js → vue-html-CcxTb_Jn.js} +1 -1
  97. package/dist/studio/assets/{vue-gv_2i8Vk.js → vue-vYpz06zQ.js} +1 -1
  98. package/dist/studio/assets/{vue-vine-C9sgcRlL.js → vue-vine-DW4RqCKF.js} +1 -1
  99. package/dist/studio/assets/{xml-nNPxMKnG.js → xml-R4LZ_u4f.js} +1 -1
  100. package/dist/studio/assets/{xsl-C7iHP36x.js → xsl-CS-xzp3L.js} +1 -1
  101. package/dist/studio/assets/{yaml-Cq3YaG6o.js → yaml-CqDWbYXd.js} +1 -1
  102. package/dist/studio/index.html +2 -2
  103. package/dist/think.d.ts +2 -2
  104. package/dist/think.js +8292 -2
  105. package/dist/think.js.map +1 -0
  106. package/dist/tools/extensions.js +1 -1
  107. package/dist/tools/workspace.js +2 -2
  108. package/dist/tools/workspace.js.map +1 -1
  109. package/dist/{types-codegen-B6c5KpYH.js → types-codegen-C-9yeFao.js} +9 -33
  110. package/dist/types-codegen-C-9yeFao.js.map +1 -0
  111. package/dist/vite.d.ts +5 -5
  112. package/dist/vite.js +1 -1
  113. package/dist/workflows.d.ts +1 -1
  114. package/docs/actions.md +297 -0
  115. package/docs/channels.md +185 -0
  116. package/docs/client-tools.md +233 -0
  117. package/docs/getting-started.md +314 -0
  118. package/docs/index.md +1272 -0
  119. package/docs/lifecycle-hooks.md +839 -0
  120. package/docs/messengers.md +197 -0
  121. package/docs/programmatic-submissions.md +206 -0
  122. package/docs/sub-agents.md +520 -0
  123. package/docs/tools.md +582 -0
  124. package/docs/workflows.md +217 -0
  125. package/package.json +46 -17
  126. package/dist/chat-sdk-Bb93yaZh.js.map +0 -1
  127. package/dist/codegen-CuPdJRpV.js.map +0 -1
  128. package/dist/framework/index.js.map +0 -1
  129. package/dist/studio/assets/index-Cbb3GlZY.js +0 -496
  130. package/dist/studio/assets/index-DN9_cL01.css +0 -2
  131. package/dist/studio/assets/mermaid-GHXKKRXX-I2ZcYo7k.js +0 -1
  132. package/dist/think-BYZXQ-vm.js +0 -6513
  133. package/dist/think-BYZXQ-vm.js.map +0 -1
  134. package/dist/types-codegen-B6c5KpYH.js.map +0 -1
@@ -7,6 +7,8 @@ import {
7
7
  h as WorkspaceLike
8
8
  } from "./workspace-BZXdZcuw.js";
9
9
  import {
10
+ FlexibleSchema,
11
+ InferSchema,
10
12
  LanguageModel,
11
13
  ModelMessage,
12
14
  PrepareStepFunction,
@@ -35,6 +37,11 @@ import {
35
37
  } from "agents/skills";
36
38
  import {
37
39
  Agent,
40
+ AgentToolLifecycleResult,
41
+ AgentToolMilestone,
42
+ AgentToolProgress,
43
+ AgentToolProgressSnapshot,
44
+ AgentToolRunInfo,
38
45
  FiberContext,
39
46
  FiberContext as FiberContext$1,
40
47
  FiberRecoveryContext,
@@ -60,6 +67,7 @@ import {
60
67
  ClientToolSchema,
61
68
  MessageConcurrency,
62
69
  MessageConcurrency as MessageConcurrency$1,
70
+ OrphanPersistStore,
63
71
  ResolvedChatRecoveryConfig,
64
72
  ResumableStream,
65
73
  SaveMessagesOptions,
@@ -69,7 +77,9 @@ import {
69
77
  } from "agents/chat";
70
78
  import {
71
79
  Session,
72
- Session as Session$1
80
+ Session as Session$1,
81
+ SessionMessage,
82
+ SessionMessage as SessionMessage$1
73
83
  } from "agents/experimental/memory/session";
74
84
  import { Workspace as Workspace$1 } from "@cloudflare/shell";
75
85
  import {
@@ -115,500 +125,439 @@ interface MediaEvictionConfig {
115
125
  maxRowsPerPass?: number;
116
126
  }
117
127
  //#endregion
118
- //#region src/messengers/events.d.ts
119
- type MessengerEventKind =
120
- | "direct-message"
121
- | "mention"
122
- | "subscribed-message"
123
- | "action"
124
- | "delivery-event";
125
- interface MessengerAuthor {
126
- fullName?: string;
127
- isBot?: boolean | "unknown";
128
- isMe?: boolean;
129
- userId: string;
130
- userName?: string;
128
+ //#region src/channels/index.d.ts
129
+ /** Surface family for a channel. Drives the default ingress/delivery wiring. */
130
+ type ChannelKind = "messenger" | "web" | "voice" | "custom";
131
+ /** A channel's capabilities are the same shape as a messenger's. */
132
+ type ChannelCapabilities = MessengerCapabilities;
133
+ /** A channel's delivery policy is the same shape as a messenger's. */
134
+ type ChannelDeliveryPolicy = MessengerDeliveryPolicy;
135
+ /** Where a channel posts replies/notices. */
136
+ type ChannelDeliverySurface = MessengerDeliverySurface;
137
+ /**
138
+ * How events arrive for a channel. A discriminated union so `web`/`voice` do
139
+ * not have to invent webhook fields they don't use. The `webhook` transport is
140
+ * exactly today's messenger ingress (a full {@link MessengerDefinition}).
141
+ */
142
+ type ChannelIngress =
143
+ | ({
144
+ transport: "webhook";
145
+ } & MessengerDefinition)
146
+ | {
147
+ transport: "websocket";
148
+ }
149
+ | {
150
+ transport: "voice";
151
+ };
152
+ /**
153
+ * Turn-scoped context the runtime sets when a turn resolves to a channel. For
154
+ * `kind: "messenger"` it wraps the existing {@link MessengerContext}.
155
+ */
156
+ interface ChannelContext {
157
+ channelId: string;
158
+ kind: ChannelKind;
159
+ capabilities?: ChannelCapabilities;
160
+ messenger?: MessengerContext;
161
+ thread?: string;
131
162
  }
132
- interface MessengerAttachment {
133
- data?: ArrayBuffer;
134
- fetch?: () => Promise<ArrayBuffer>;
135
- id?: string;
136
- mediaType?: string;
137
- name?: string;
138
- raw?: unknown;
139
- size?: number;
140
- text?: string;
141
- url?: string;
163
+ /**
164
+ * The public channel contract — the generalization of a messenger: an ingress,
165
+ * a delivery surface, capabilities, conversation routing, a delivery policy, and
166
+ * (new) per-channel policy.
167
+ */
168
+ interface ChannelDefinition {
169
+ kind: ChannelKind;
170
+ capabilities?: ChannelCapabilities;
171
+ conversation?: MessengerConversationMode | MessengerConversationResolver;
172
+ delivery?: ChannelDeliveryPolicy;
173
+ /** Per-channel instructions, prepended to the system prompt for this channel. */
174
+ instructions?: string | ((ctx: ChannelContext) => string | Promise<string>);
175
+ /** Narrow the assembled tool set for this channel. */
176
+ tools?: (all: ToolSet) => ToolSet;
177
+ /** Per-channel cap on model steps for a turn. */
178
+ maxTurns?: number;
179
+ ingress: ChannelIngress;
142
180
  }
143
- interface MessengerThread {
144
- channelId?: string;
145
- channelName?: string;
181
+ type ThinkChannels = Record<string, ChannelDefinition>;
182
+ type NormalizedChannelDefinition = ChannelDefinition & {
146
183
  id: string;
147
- isDirectMessage: boolean;
148
- providerThreadId: string;
149
- title?: string;
184
+ };
185
+ /** Wrap a {@link MessengerDefinition} as a `kind: "messenger"` channel. */
186
+ declare function messengerChannel(
187
+ definition: MessengerDefinition
188
+ ): ChannelDefinition;
189
+ //#endregion
190
+ //#region src/think.d.ts
191
+ type ChatRecoveryRetryData = {
192
+ targetUserId?: string;
193
+ originalRequestId?: string;
194
+ incidentId?: string;
195
+ lastBody?: Record<string, unknown> | null;
196
+ lastClientTools?: ClientToolSchema[] | null;
197
+ recoveredRequestId?: string;
198
+ };
199
+ type ChatRecoveryContinueData = {
200
+ targetAssistantId?: string;
201
+ originalRequestId?: string;
202
+ incidentId?: string;
203
+ lastBody?: Record<string, unknown> | null;
204
+ lastClientTools?: ClientToolSchema[] | null;
205
+ recoveredRequestId?: string;
206
+ };
207
+ /**
208
+ * A best-effort internal `onStart` step that failed on this wake and was
209
+ * skipped so the agent could still come up (#1710).
210
+ *
211
+ * - `transcript-hydration` — reading the persisted conversation into the
212
+ * in-memory message cache failed (e.g. `SQLITE_NOMEM` on an oversized,
213
+ * media-heavy transcript). The agent starts with an empty in-memory view;
214
+ * persisted history is untouched and the next safe-boundary sync retries.
215
+ * - `scheduled-task-reconcile` — declarative scheduled tasks were not
216
+ * reconciled on this wake; the next successful wake reconciles them.
217
+ * - `durable-work-recovery` — pending submissions / workflow notifications
218
+ * were not recovered or drained on this wake.
219
+ */
220
+ interface OnStartDegradation {
221
+ step:
222
+ | "transcript-hydration"
223
+ | "scheduled-task-reconcile"
224
+ | "durable-work-recovery";
225
+ error: unknown;
150
226
  }
151
- interface MessengerMessage {
152
- attachments: MessengerAttachment[];
153
- author: MessengerAuthor;
154
- createdAt?: Date;
155
- id: string;
156
- isMention?: boolean;
157
- providerMessageId: string;
158
- raw?: unknown;
159
- text: string;
227
+ /**
228
+ * Callback interface for streaming chat events from a Think sub-agent.
229
+ *
230
+ * Designed to work across the sub-agent RPC boundary — implement as
231
+ * an RpcTarget in the parent agent and pass to `chat()`.
232
+ */
233
+ interface ChatStartEvent {
234
+ requestId: string;
160
235
  }
161
- interface MessengerAction {
162
- actionId: string;
163
- messageId?: string;
164
- raw?: unknown;
165
- user?: MessengerAuthor;
166
- value?: string;
236
+ interface StreamCallback {
237
+ onStart(event: ChatStartEvent): void | Promise<void>;
238
+ onEvent(json: string): void | Promise<void>;
239
+ onDone(): void | Promise<void>;
240
+ onError(error: string): void | Promise<void>;
241
+ /**
242
+ * The current attempt was interrupted (a stream-stall watchdog abort routed
243
+ * into bounded recovery, #1626) and its final outcome will NOT arrive through
244
+ * this callback. One of two things is true:
245
+ * - a scheduled continuation — running in a LATER isolate invocation, without
246
+ * this callback — will produce the answer (delivered to other channels,
247
+ * e.g. WebSocket connections), OR
248
+ * - the recovery budget was exhausted, so the turn was already terminalized
249
+ * out-of-band (the configured `terminalMessage` + `onExhausted`) and is
250
+ * terminally over — there is NO continuation to come.
251
+ *
252
+ * This is NOT `onDone` (this attempt did not complete) and NOT `onError` (the
253
+ * raw stall is not surfaced as a terminal error here); without it the contract
254
+ * `onStart → onEvent* → (onDone | onError)` is silently abandoned and a
255
+ * consumer that treats the clean resolve as success finalizes a truncated
256
+ * partial.
257
+ *
258
+ * Consumers should AVOID finalizing the partial on this signal — surface a
259
+ * "recovering…" / "interrupted, please retry" state, or re-attach via a
260
+ * durable channel — but must ALSO NOT block indefinitely waiting for a
261
+ * continuation: per the exhausted case above, one may never come. Optional →
262
+ * defaults to a no-op, so this is fully backward-compatible.
263
+ *
264
+ * Note: a deploy/eviction interruption kills the isolate (and this callback)
265
+ * before this can fire — the caller observes a transport break instead. This
266
+ * fires only for an in-isolate interruption (the stall→recovery path).
267
+ */
268
+ onInterrupted?(): void | Promise<void>;
167
269
  }
168
- interface MessengerCapabilities {
169
- canEditMessages?: boolean;
170
- canStream?: boolean;
171
- maxMessageLength?: number;
172
- supportsActions?: boolean;
173
- supportsAttachments?: boolean;
174
- supportsEphemeral?: boolean;
270
+ /**
271
+ * Minimal interface for the result of the inference loop.
272
+ * The AI SDK's `streamText()` result satisfies this interface.
273
+ */
274
+ interface StreamableResult {
275
+ toUIMessageStream(options?: {
276
+ sendReasoning?: boolean;
277
+ onError?: (error: unknown) => string;
278
+ }): AsyncIterable<unknown>;
279
+ output?: PromiseLike<unknown>;
175
280
  }
176
- interface MessengerContext {
177
- action?: MessengerAction;
178
- author?: MessengerAuthor;
179
- capabilities: MessengerCapabilities;
180
- kind: MessengerEventKind;
181
- message?: MessengerMessage;
182
- messengerId: string;
183
- provider: string;
184
- thread: MessengerThread;
281
+ /**
282
+ * Options for a chat turn (sub-agent RPC entry point).
283
+ */
284
+ interface ChatOptions {
285
+ signal?: AbortSignal;
286
+ /**
287
+ * Client-defined tool schemas to expose to the model for this turn, mirroring
288
+ * the `clientTools` carried over the WebSocket chat protocol. Use this when a
289
+ * parent agent delegates to a Think sub-agent over RPC but the sub-agent still
290
+ * needs access to tools the client (or parent) defines at runtime.
291
+ *
292
+ * On their own these are execute-less — the model's call surfaces as a tool
293
+ * call through the stream callback. Provide {@link ChatOptions.onClientToolCall}
294
+ * to also resolve those calls inline so the turn can continue to completion.
295
+ */
296
+ clientTools?: ClientToolSchema[];
297
+ /**
298
+ * Executes a client tool call and returns its output, completing the
299
+ * round trip for {@link ChatOptions.clientTools} within the same turn.
300
+ *
301
+ * Without this, a client-tool call has no result and the turn ends with a
302
+ * dangling tool call (the RPC stream callback has no inbound result channel).
303
+ * With it, the model can call a client tool, receive the result, and keep
304
+ * going — the same multi-step behavior the WebSocket path gets from
305
+ * `cf_agent_tool_result` messages.
306
+ */
307
+ onClientToolCall?: ClientToolExecutor;
308
+ /** Channel id this turn belongs to. See {@link RunTurnBase.channel}. */
309
+ channel?: string;
185
310
  }
186
- interface MessengerEvent extends MessengerContext {
187
- raw?: unknown;
311
+ /** Input accepted by {@link Think.runTurn}. */
312
+ type TurnInputMessages =
313
+ | string
314
+ | UIMessage
315
+ | UIMessage[]
316
+ | ((current: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>);
317
+ /** Shared base for {@link RunTurnOptions}; only `input` is common across modes. */
318
+ interface RunTurnBase {
319
+ input?: TurnInputMessages;
320
+ /**
321
+ * Channel id this turn belongs to (resolved against `configureChannels()` /
322
+ * `getMessengers()`). Sets the turn-scoped channel context and is persisted on
323
+ * the user message so a recovered/continued turn re-resolves it. Defaults to
324
+ * the implicit `web` channel.
325
+ */
326
+ channel?: string;
188
327
  }
189
- declare function messengerContextFromEvent(
190
- event: MessengerEvent
191
- ): MessengerContext;
192
- declare function serializableMessengerEvent(
193
- event: MessengerEvent
194
- ): MessengerEvent;
195
- declare function toMessengerUserMessage(event: MessengerEvent): UIMessage;
196
- //#endregion
197
- //#region src/messengers/delivery.d.ts
198
- declare const MESSENGER_REPLY_FIBER_NAME = "think:messenger-reply";
199
- declare const EMPTY_MESSENGER_RESPONSE =
200
- "I couldn't produce a text response. Please try again.";
201
- declare const ERROR_MESSENGER_RESPONSE =
202
- "Sorry, I couldn't answer that right now. Please try again.";
203
- declare const INTERRUPTED_MESSENGER_RESPONSE =
204
- "Sorry, my reply was interrupted. Please send your message again if you'd like me to retry.";
205
- interface TextStreamCallbackOptions {
206
- onVisibleStart?: () => Promise<void> | void;
207
- visibleSoftLimit?: number;
328
+ /** Options for {@link Think.runTurn} with `mode: "wait"` (the default). */
329
+ interface RunTurnWait extends RunTurnBase {
330
+ mode?: "wait";
331
+ continuation?: boolean;
332
+ body?: Record<string, unknown>;
333
+ signal?: AbortSignal;
208
334
  }
209
- declare class TextStreamCallback extends RpcTarget implements StreamCallback {
210
- private readonly onVisibleStart?;
211
- private readonly visibleChunks;
212
- private readonly wakeups;
213
- private readonly visibleSoftLimit?;
214
- private chatRequestId?;
215
- private closed;
216
- private interrupted;
217
- private error?;
218
- private text;
219
- private visibleClosed;
220
- private visibleLimitReachedValue;
221
- private visibleStarted;
222
- private visibleTextValue;
223
- constructor(options?: TextStreamCallbackOptions);
224
- onStart(event: ChatStartEvent): void;
225
- onEvent(json: string): void;
226
- onDone(): void;
227
- onError(error: string): void;
228
- onInterrupted(): void;
229
- wasInterrupted(): boolean;
230
- close(): void;
231
- fail(error: unknown): void;
232
- hasText(): boolean;
233
- remainingText(): string;
234
- requestId(): string | undefined;
235
- textSoFar(): string;
236
- visibleLimitReached(): boolean;
237
- visibleText(): string;
238
- stream(): AsyncIterable<string>;
239
- private pushVisibleText;
240
- private wake;
241
- private markVisibleStarted;
335
+ /** Options for {@link Think.runTurn} with `mode: "submit"`. */
336
+ interface RunTurnSubmit extends RunTurnBase {
337
+ mode: "submit";
338
+ submissionId?: string;
339
+ idempotencyKey?: string;
340
+ metadata?: Record<string, unknown>;
242
341
  }
243
- declare function textDeltaFromStreamChunk(json: string): string | null;
244
- type MessengerReplyStage = "accepted" | "streaming" | "completed";
245
- interface MessengerReplySnapshot {
246
- event: MessengerEvent;
247
- stage: MessengerReplyStage;
248
- thread?: unknown;
249
- type: typeof MESSENGER_REPLY_FIBER_NAME;
342
+ /** Options for {@link Think.runTurn} with `mode: "stream"`. */
343
+ interface RunTurnStream extends RunTurnBase {
344
+ mode: "stream";
345
+ callback: StreamCallback;
346
+ clientTools?: ClientToolSchema[];
347
+ onClientToolCall?: ClientToolExecutor;
348
+ signal?: AbortSignal;
250
349
  }
251
- declare function messengerReplySnapshot(
252
- stage: MessengerReplyStage,
253
- event: MessengerEvent,
254
- thread?: unknown
255
- ): MessengerReplySnapshot;
256
- declare function parseMessengerReplySnapshot(
257
- snapshot: unknown
258
- ): MessengerReplySnapshot | null;
259
- declare function messengerReplyRecoveryMode(
260
- snapshot: MessengerReplySnapshot
261
- ): "answer" | "apologize" | null;
262
- declare function messengerReplyFailureMode(
263
- hasStreamedText: boolean,
264
- completedModelTurn?: boolean,
265
- expectedDeliveryCompletion?: boolean
266
- ): "apologize" | "error" | null;
267
- interface MessengerDeliveryTarget {
268
- cancelChat(
269
- requestId: string,
270
- reason?: string
271
- ): boolean | void | Promise<boolean | void>;
272
- chat(
273
- userMessage: string | UIMessage,
274
- callback: StreamCallback
275
- ): Promise<void>;
276
- chatWithMessengerContext?(
277
- userMessage: string | UIMessage,
278
- callback: StreamCallback,
279
- context: MessengerEvent
280
- ): Promise<void>;
281
- }
282
- interface MessengerDeliverySurface {
283
- post(
284
- message:
285
- | string
286
- | {
287
- markdown: string;
288
- }
289
- | AsyncIterable<string>
290
- ): Promise<unknown>;
291
- startTyping?(status?: string): Promise<void>;
292
- }
293
- interface MessengerDeliveryPolicy {
294
- emptyResponseText?: string;
295
- errorResponseText?: string;
296
- interruptedResponseText?: string;
297
- isExpectedDeliveryCompletion?(
298
- error: unknown,
299
- callback: TextStreamCallback
300
- ): boolean;
301
- splitText?(text: string): string[];
302
- visibleSoftLimit?: number;
303
- }
304
- interface DeliverMessengerReplyOptions {
305
- checkpoint?: (snapshot: MessengerReplySnapshot) => Promise<void> | void;
306
- event: MessengerEvent;
307
- fiber?: FiberContext;
308
- policy?: MessengerDeliveryPolicy;
309
- snapshotEvent?: MessengerEvent;
310
- snapshotThread?: unknown;
311
- surface: MessengerDeliverySurface;
312
- target: MessengerDeliveryTarget;
313
- userMessage?: UIMessage;
350
+ type RunTurnOptions = RunTurnWait | RunTurnSubmit | RunTurnStream;
351
+ /** Result of {@link Think.runTurn} in `mode: "wait"`. */
352
+ type TurnResult = SaveMessagesResult & {
353
+ message?: SessionMessage;
354
+ continuation: boolean;
355
+ };
356
+ declare const ACTION_BRAND: unique symbol;
357
+ type ActionKind =
358
+ | "server"
359
+ | "client"
360
+ | "approval-gated"
361
+ | "durable-pause"
362
+ | "delegated-agent";
363
+ interface ActionContext {
364
+ /** The agent instance currently executing the action. */
365
+ agent: Think;
366
+ env: Cloudflare.Env;
367
+ /** Current turn request id. */
368
+ requestId: string;
369
+ toolCallId: string;
370
+ /** Model messages visible to the tool call. */
371
+ messages: ReadonlyArray<ModelMessage>;
372
+ /** Combined action timeout and turn abort signal. */
373
+ signal: AbortSignal;
374
+ /**
375
+ * Record an advisory delivery hint for this turn's final reply (voice note,
376
+ * card, email draft, ...). Does not change the model-visible tool output.
377
+ * No-op for approval/permission/idempotency policy evaluation and for
378
+ * durable-pause approved-action resumes (their reply is delivered by a
379
+ * later continuation turn in v1).
380
+ */
381
+ attachReply(attachment: ReplyAttachment): void;
314
382
  }
315
- declare function deliverMessengerReply(
316
- options: DeliverMessengerReplyOptions
317
- ): Promise<void>;
318
- //#endregion
319
- //#region src/messengers/chat-sdk.d.ts
320
- declare class ThinkMessengerStateAgent extends ChatSdkStateAgent {}
321
- type MessengerRespondTo =
322
- | "action"
323
- | "direct-message"
324
- | "mention"
325
- | "subscribed-thread";
326
- type MessengerConversationMode = "self" | "thread";
327
- type MessengerConversationTarget =
383
+ /**
384
+ * The attachment shape accepted by {@link ActionContext.attachReply}. An open
385
+ * union: the named variants give autocomplete for common channels, and the
386
+ * trailing `{ type: string; [k]: unknown }` keeps it extensible. Advisory only
387
+ * — surfaces that don't recognize a `type` ignore it.
388
+ */
389
+ type ReplyAttachment =
328
390
  | {
329
- target: "self";
391
+ type: "voice_note";
330
392
  }
331
393
  | {
332
- agentClass?: SubAgentClass<Agent & MessengerThinkTarget>;
333
- name: string;
334
- target: "subagent";
394
+ type: "email_draft";
395
+ subject?: string;
396
+ to?: string[];
397
+ }
398
+ | {
399
+ type: "card";
400
+ payload: unknown;
401
+ }
402
+ | {
403
+ type: string;
404
+ [k: string]: unknown;
335
405
  };
336
- type MessengerConversationResolver = (
337
- event: MessengerEvent
338
- ) => MessengerConversationTarget | Promise<MessengerConversationTarget>;
339
- interface MessengerDefinition {
340
- adapter: Adapter;
341
- adapterName: string;
342
- capabilities?: MessengerCapabilities;
343
- conversation?: MessengerConversationMode | MessengerConversationResolver;
344
- delivery?: MessengerDeliveryPolicy;
345
- keyShard?: ChatSdkStateAdapterOptions["keyShard"];
346
- path?: string;
347
- provider: string;
348
- respondTo?: readonly MessengerRespondTo[];
349
- shardKey?: ChatSdkStateAdapterOptions["shardKey"];
350
- subscribeOnMention?: boolean;
351
- toEvent?: (
352
- input: ChatSdkMessengerEventInput
353
- ) => MessengerEvent | Promise<MessengerEvent>;
354
- userName: string;
355
- verifyWebhook?:
356
- | false
357
- | ((request: Request) => boolean | Response | Promise<boolean | Response>);
358
- }
359
- type ThinkMessengers = Record<string, MessengerDefinition>;
360
- interface NormalizedMessengerDefinition extends MessengerDefinition {
361
- id: string;
362
- path: string;
363
- respondTo: readonly MessengerRespondTo[];
364
- subscribeOnMention: boolean;
365
- verifyWebhook:
366
- | false
367
- | ((request: Request) => boolean | Response | Promise<boolean | Response>);
406
+ type ActionApprovalPolicy<Input> =
407
+ | boolean
408
+ | ((args: {
409
+ input: Input;
410
+ ctx: ActionContext;
411
+ }) => boolean | Promise<boolean>);
412
+ type ActionPermissionSpec<Input> =
413
+ | readonly string[]
414
+ | ((args: {
415
+ input: Input;
416
+ ctx: ActionContext;
417
+ }) => readonly string[] | Promise<readonly string[]>);
418
+ type ActionIdempotencyKey<Input> =
419
+ | string
420
+ | ((args: { input: Input; ctx: ActionContext }) => string | Promise<string>);
421
+ type ActionAuthorizationDecision =
422
+ | boolean
423
+ | {
424
+ allowed: boolean;
425
+ reason?: string;
426
+ grantedPermissions?: readonly string[];
427
+ };
428
+ interface ActionAuthorizationContext {
429
+ requestId: string;
430
+ toolCallId: string;
431
+ action: string;
432
+ kind: ActionKind;
433
+ input: unknown;
434
+ requiredPermissions: readonly string[];
435
+ grantedPermissions?: readonly string[];
436
+ messages: ReadonlyArray<ModelMessage>;
437
+ agent: Think;
438
+ env: Cloudflare.Env;
368
439
  }
369
- interface ChatSdkMessengerOptions extends Omit<
370
- MessengerDefinition,
371
- "adapterName"
372
- > {
373
- adapterName?: string;
440
+ interface ActionApprovalDescriptor {
441
+ requestId: string;
442
+ toolCallId: string;
443
+ action: string;
444
+ summary: string;
445
+ input: unknown;
446
+ permissions: string[];
447
+ risk?: "low" | "medium" | "high";
448
+ kind: "approval-gated" | "durable-pause";
374
449
  }
375
- interface ChatSdkMessengerEventInput {
376
- action?: ActionEvent;
377
- eventKind: MessengerEventKind;
378
- message?: Message;
379
- raw?: unknown;
380
- thread: Thread;
450
+ /**
451
+ * A single approval awaiting a human decision, unified across pause backends so
452
+ * dashboards/voice/messenger can list and reconcile everything pending with one
453
+ * call. `source: "action"` is a parked `kind: "durable-pause"` action;
454
+ * `source: "codemode"` is a paused `execute`-tool execution. Both resolve via
455
+ * {@link Think.approveExecution} / {@link Think.rejectExecution}.
456
+ */
457
+ interface PendingApproval {
458
+ executionId: string;
459
+ source: "action" | "codemode";
460
+ descriptor: ActionApprovalDescriptor;
381
461
  }
382
- interface MessengerThinkTarget {
383
- cancelChat(
384
- requestId: string,
385
- reason?: string
386
- ): boolean | void | Promise<boolean | void>;
387
- chat(
388
- userMessage: string | UIMessage,
389
- callback: StreamCallback
390
- ): Promise<void>;
391
- chatWithMessengerContext?(
392
- userMessage: string | UIMessage,
393
- callback: StreamCallback,
394
- context: MessengerEvent
395
- ): Promise<void>;
462
+ interface ActionConfig<
463
+ InputSchema extends FlexibleSchema = FlexibleSchema,
464
+ Output = unknown
465
+ > {
466
+ /** Defaults to the registration key when returned from getActions(). */
467
+ name?: string;
468
+ description: string;
469
+ inputSchema: InputSchema;
470
+ /** Reserved metadata; output validation is not enforced yet. */
471
+ outputSchema?: FlexibleSchema<Output>;
472
+ /**
473
+ * Stable key used to replay settled action results without re-running side
474
+ * effects. Use domain identifiers that survive recovery retries (for example,
475
+ * an order id or inbound event id); avoid request ids, timestamps, and random
476
+ * values.
477
+ */
478
+ idempotencyKey?: ActionIdempotencyKey<InferSchema<InputSchema>>;
479
+ permissions?: ActionPermissionSpec<InferSchema<InputSchema>>;
480
+ approval?: ActionApprovalPolicy<InferSchema<InputSchema>>;
481
+ approvalSummary?: string;
482
+ approvalRisk?: "low" | "medium" | "high";
483
+ timeoutMs?: number;
484
+ kind?: ActionKind;
485
+ execute(
486
+ input: InferSchema<InputSchema>,
487
+ ctx: ActionContext
488
+ ): Promise<Output> | Output;
396
489
  }
397
- interface MessengerThinkHost extends MessengerThinkTarget {
398
- constructor: {
399
- name: string;
400
- };
401
- name: string;
402
- parentPath: ReadonlyArray<{
403
- className: string;
404
- name: string;
405
- }>;
406
- startFiber(
407
- name: string,
408
- fn: (ctx: FiberContext) => Promise<void>,
409
- options?: StartFiberOptions
410
- ): Promise<MessengerFiberStartResult>;
411
- resolveFiber(id: string, result: FiberRecoveryResult): Promise<boolean>;
412
- subAgent<T extends Agent>(
413
- agentClass: SubAgentClass<T>,
414
- name: string
415
- ): Promise<SubAgentStub<T>>;
490
+ interface Action<
491
+ InputSchema extends FlexibleSchema = FlexibleSchema,
492
+ Output = unknown
493
+ > {
494
+ readonly [ACTION_BRAND]: true;
495
+ readonly config: ActionConfig<InputSchema, Output>;
416
496
  }
417
- interface MessengerFiberStartResult {
418
- accepted: boolean;
419
- fiberId: string;
420
- snapshot?: unknown;
421
- status: string;
497
+ declare function action<
498
+ const InputSchema extends FlexibleSchema,
499
+ Output = unknown
500
+ >(config: ActionConfig<InputSchema, Output>): Action<InputSchema, Output>;
501
+ declare function isAction(value: unknown): value is Action;
502
+ type TurnTrigger =
503
+ | "ws-chat"
504
+ | "rpc"
505
+ | "programmatic"
506
+ | "submission"
507
+ | "scheduled"
508
+ | "agent-tool"
509
+ | "auto-continuation"
510
+ | "recovery-continue"
511
+ | "recovery-retry";
512
+ /** Options for {@link Think.addMessages}. */
513
+ interface AddMessagesOptions {
514
+ /**
515
+ * Parent to attach the first message under. Omitted (`undefined`) attaches to
516
+ * the latest committed leaf at call time; `null` attaches at the root. An
517
+ * explicit id that does not exist throws (fail fast rather than silently
518
+ * misattaching). Subsequent messages in an array chain under the previous one.
519
+ */
520
+ parentId?: string | null;
521
+ /**
522
+ * `"append"` (default) inserts new rows, idempotent by message id.
523
+ * `"upsert"` inserts, or updates in place when the id already exists (in which
524
+ * case `parentId` is ignored — re-parenting is not supported).
525
+ *
526
+ * Idempotency is by id against the whole session tree, not just the target
527
+ * path: if a message id already exists *anywhere* in history, `"append"` is a
528
+ * no-op for it (no new row, no re-parent) and `"upsert"` updates it in place
529
+ * wherever it lives. In both modes the next message in the array chains under
530
+ * that existing id, so passing already-present ids mid-array threads new
531
+ * messages onto the existing branch rather than forking a new one.
532
+ */
533
+ mode?: "append" | "upsert";
534
+ /**
535
+ * Broadcast the change to connected clients. Default `true`. Has no effect
536
+ * when called from inside an active turn (e.g. a tool `execute`), where the
537
+ * live view is intentionally not touched until the next turn's sync.
538
+ */
539
+ broadcast?: boolean;
422
540
  }
423
- declare function defineMessengers<T extends ThinkMessengers>(messengers: T): T;
424
- declare function chatSdkMessenger(
425
- options: ChatSdkMessengerOptions
426
- ): MessengerDefinition;
427
- declare class ThinkMessengerRuntime {
428
- private readonly host;
429
- private chat?;
430
- private readonly definitionsByAdapterName;
431
- private readonly definitionsById;
432
- private readonly definitions;
433
- constructor(definitions: ThinkMessengers, host: MessengerThinkHost);
434
- get size(): number;
435
- initialize(): void;
436
- handleRequest(request: Request): Promise<Response | undefined>;
437
- handleFiberRecovery(ctx: FiberRecoveryContext): Promise<boolean>;
438
- private createChat;
439
- private enqueueReply;
440
- private answer;
441
- private resolveTarget;
442
- private definitionForThread;
443
- private definitionForThreadId;
444
- private hasUniqueProvider;
445
- private shardThread;
446
- private shardStateKey;
447
- private reviveChatObject;
448
- private toEvent;
449
- }
450
- declare function normalizeMessengers(
451
- messengers: ThinkMessengers
452
- ): NormalizedMessengerDefinition[];
453
- declare function defaultConversationName(event: MessengerEvent): string;
454
- declare function idempotencyKeyForEvent(event: MessengerEvent): string;
455
- declare function defaultChatSdkEvent(
456
- definition: NormalizedMessengerDefinition,
457
- input: ChatSdkMessengerEventInput
458
- ): MessengerEvent;
459
- declare function toMessengerThread(thread: Thread): MessengerThread;
460
- declare function toMessengerMessage(message: Message): MessengerMessage;
461
- declare function toMessengerAuthor(author: Author): MessengerAuthor;
462
- declare function toMessengerAttachment(
463
- attachment: Attachment
464
- ): MessengerAttachment;
465
- //#endregion
466
- //#region src/think.d.ts
467
- type ChatRecoveryRetryData = {
468
- targetUserId?: string;
469
- originalRequestId?: string;
470
- incidentId?: string;
471
- lastBody?: Record<string, unknown> | null;
472
- lastClientTools?: ClientToolSchema[] | null;
473
- recoveredRequestId?: string;
474
- };
475
- type ChatRecoveryContinueData = {
476
- targetAssistantId?: string;
477
- originalRequestId?: string;
478
- incidentId?: string;
479
- lastBody?: Record<string, unknown> | null;
480
- lastClientTools?: ClientToolSchema[] | null;
481
- recoveredRequestId?: string;
482
- };
483
- /**
484
- * A best-effort internal `onStart` step that failed on this wake and was
485
- * skipped so the agent could still come up (#1710).
486
- *
487
- * - `transcript-hydration` — reading the persisted conversation into the
488
- * in-memory message cache failed (e.g. `SQLITE_NOMEM` on an oversized,
489
- * media-heavy transcript). The agent starts with an empty in-memory view;
490
- * persisted history is untouched and the next safe-boundary sync retries.
491
- * - `scheduled-task-reconcile` — declarative scheduled tasks were not
492
- * reconciled on this wake; the next successful wake reconciles them.
493
- * - `durable-work-recovery` — pending submissions / workflow notifications
494
- * were not recovered or drained on this wake.
495
- */
496
- interface OnStartDegradation {
497
- step:
498
- | "transcript-hydration"
499
- | "scheduled-task-reconcile"
500
- | "durable-work-recovery";
501
- error: unknown;
502
- }
503
- /**
504
- * Callback interface for streaming chat events from a Think sub-agent.
505
- *
506
- * Designed to work across the sub-agent RPC boundary — implement as
507
- * an RpcTarget in the parent agent and pass to `chat()`.
508
- */
509
- interface ChatStartEvent {
510
- requestId: string;
511
- }
512
- interface StreamCallback {
513
- onStart(event: ChatStartEvent): void | Promise<void>;
514
- onEvent(json: string): void | Promise<void>;
515
- onDone(): void | Promise<void>;
516
- onError(error: string): void | Promise<void>;
517
- /**
518
- * The current attempt was interrupted (a stream-stall watchdog abort routed
519
- * into bounded recovery, #1626) and its final outcome will NOT arrive through
520
- * this callback. One of two things is true:
521
- * - a scheduled continuation — running in a LATER isolate invocation, without
522
- * this callback — will produce the answer (delivered to other channels,
523
- * e.g. WebSocket connections), OR
524
- * - the recovery budget was exhausted, so the turn was already terminalized
525
- * out-of-band (the configured `terminalMessage` + `onExhausted`) and is
526
- * terminally over — there is NO continuation to come.
527
- *
528
- * This is NOT `onDone` (this attempt did not complete) and NOT `onError` (the
529
- * raw stall is not surfaced as a terminal error here); without it the contract
530
- * `onStart → onEvent* → (onDone | onError)` is silently abandoned and a
531
- * consumer that treats the clean resolve as success finalizes a truncated
532
- * partial.
533
- *
534
- * Consumers should AVOID finalizing the partial on this signal — surface a
535
- * "recovering…" / "interrupted, please retry" state, or re-attach via a
536
- * durable channel — but must ALSO NOT block indefinitely waiting for a
537
- * continuation: per the exhausted case above, one may never come. Optional →
538
- * defaults to a no-op, so this is fully backward-compatible.
539
- *
540
- * Note: a deploy/eviction interruption kills the isolate (and this callback)
541
- * before this can fire — the caller observes a transport break instead. This
542
- * fires only for an in-isolate interruption (the stall→recovery path).
543
- */
544
- onInterrupted?(): void | Promise<void>;
545
- }
546
- /**
547
- * Minimal interface for the result of the inference loop.
548
- * The AI SDK's `streamText()` result satisfies this interface.
549
- */
550
- interface StreamableResult {
551
- toUIMessageStream(options?: {
552
- sendReasoning?: boolean;
553
- }): AsyncIterable<unknown>;
554
- output?: PromiseLike<unknown>;
555
- }
556
- /**
557
- * Options for a chat turn (sub-agent RPC entry point).
558
- */
559
- interface ChatOptions {
560
- signal?: AbortSignal;
561
- /**
562
- * Client-defined tool schemas to expose to the model for this turn, mirroring
563
- * the `clientTools` carried over the WebSocket chat protocol. Use this when a
564
- * parent agent delegates to a Think sub-agent over RPC but the sub-agent still
565
- * needs access to tools the client (or parent) defines at runtime.
566
- *
567
- * On their own these are execute-less — the model's call surfaces as a tool
568
- * call through the stream callback. Provide {@link ChatOptions.onClientToolCall}
569
- * to also resolve those calls inline so the turn can continue to completion.
570
- */
571
- clientTools?: ClientToolSchema[];
572
- /**
573
- * Executes a client tool call and returns its output, completing the
574
- * round trip for {@link ChatOptions.clientTools} within the same turn.
575
- *
576
- * Without this, a client-tool call has no result and the turn ends with a
577
- * dangling tool call (the RPC stream callback has no inbound result channel).
578
- * With it, the model can call a client tool, receive the result, and keep
579
- * going — the same multi-step behavior the WebSocket path gets from
580
- * `cf_agent_tool_result` messages.
581
- */
582
- onClientToolCall?: ClientToolExecutor;
583
- }
584
- /** Options for {@link Think.addMessages}. */
585
- interface AddMessagesOptions {
586
- /**
587
- * Parent to attach the first message under. Omitted (`undefined`) attaches to
588
- * the latest committed leaf at call time; `null` attaches at the root. An
589
- * explicit id that does not exist throws (fail fast rather than silently
590
- * misattaching). Subsequent messages in an array chain under the previous one.
591
- */
592
- parentId?: string | null;
593
- /**
594
- * `"append"` (default) inserts new rows, idempotent by message id.
595
- * `"upsert"` inserts, or updates in place when the id already exists (in which
596
- * case `parentId` is ignored — re-parenting is not supported).
597
- *
598
- * Idempotency is by id against the whole session tree, not just the target
599
- * path: if a message id already exists *anywhere* in history, `"append"` is a
600
- * no-op for it (no new row, no re-parent) and `"upsert"` updates it in place
601
- * wherever it lives. In both modes the next message in the array chains under
602
- * that existing id, so passing already-present ids mid-array threads new
603
- * messages onto the existing branch rather than forking a new one.
604
- */
605
- mode?: "append" | "upsert";
606
- /**
607
- * Broadcast the change to connected clients. Default `true`. Has no effect
608
- * when called from inside an active turn (e.g. a tool `execute`), where the
609
- * live view is intentionally not touched until the next turn's sync.
610
- */
611
- broadcast?: boolean;
541
+ /** Options for {@link Think.deliverNotice}. */
542
+ interface DeliverNoticeOptions {
543
+ /**
544
+ * Target channel id. Defaults to the active turn's channel, else `"web"`.
545
+ */
546
+ channel?: string;
547
+ /**
548
+ * Also record the notice in the model-visible transcript so the next turn
549
+ * knows it was said. Default `false`. For the `web` channel the note is always
550
+ * appended to the transcript (its only render path); `informModel` then only
551
+ * controls the phrasing.
552
+ */
553
+ informModel?: boolean;
554
+ /** Delivery kind for the wire tag. Default `"notice"`. */
555
+ kind?: DeliveryKind;
556
+ /**
557
+ * Conversation/thread hint, required for out-of-turn delivery to a
558
+ * multi-thread messenger channel.
559
+ */
560
+ thread?: string;
612
561
  }
613
562
  type AgentToolChildRunStatus =
614
563
  | "starting"
@@ -626,6 +575,7 @@ type AgentToolRunInspection<Output = unknown> = {
626
575
  error?: string;
627
576
  startedAt: number;
628
577
  completedAt?: number;
578
+ progress?: AgentToolProgressSnapshot;
629
579
  };
630
580
  type Digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";
631
581
  type Hour = `0${Digit}` | `1${Digit}` | "20" | "21" | "22" | "23";
@@ -682,9 +632,11 @@ type ThinkScheduledTask =
682
632
  timezone?: string;
683
633
  });
684
634
  type ThinkScheduledTasks = Record<string, ThinkScheduledTask>;
685
- declare function defineScheduledTasks<const T extends ThinkScheduledTasks>(
686
- tasks: T
687
- ): T;
635
+ type ActionLedgerRetentionConfig = {
636
+ settledMs: number | false;
637
+ pendingMs: number | false;
638
+ maxSweepRows: number;
639
+ };
688
640
  type DeclaredScheduledTaskPayload = {
689
641
  taskId: string;
690
642
  scheduleHash: string;
@@ -704,7 +656,11 @@ type ThinkSubmissionStatus =
704
656
  type SubmitMessagesOptions = {
705
657
  submissionId?: string;
706
658
  idempotencyKey?: string;
707
- metadata?: Record<string, unknown>;
659
+ metadata?: Record<
660
+ string,
661
+ unknown
662
+ > /** Channel id this submission belongs to. See {@link RunTurnBase.channel}. */;
663
+ channel?: string;
708
664
  };
709
665
  type ThinkWorkflowPromptContext = {
710
666
  workflow: {
@@ -1188,6 +1144,7 @@ declare class Think<
1188
1144
  };
1189
1145
  private _skillRegistry;
1190
1146
  private _loggedSkillWarnings;
1147
+ private _loggedProtocolWarnings;
1191
1148
  /**
1192
1149
  * Controls how overlapping user submit requests behave while another
1193
1150
  * chat turn is already active or queued.
@@ -1295,7 +1252,21 @@ declare class Think<
1295
1252
  */
1296
1253
  getOnStartDegradations(): ReadonlyArray<OnStartDegradation>;
1297
1254
  private _activeMessengerContext?;
1255
+ /**
1256
+ * Turn-scoped channel context (superset of `_activeMessengerContext`). Set on
1257
+ * both the queue and submit admission paths via `_withChannelContext`, read by
1258
+ * `deliverNotice` and per-channel policy. Save/restore keeps nested turns safe.
1259
+ */
1260
+ private _activeChannelContext?;
1261
+ /**
1262
+ * Live delivery surface for the active turn, bound by `deliverMessengerReply`
1263
+ * so `deliverNotice` can post to the originating channel mid-turn. Save/restore
1264
+ * keeps nested turns safe.
1265
+ */
1266
+ private _activeDeliverySurface?;
1298
1267
  private _messengerRuntime?;
1268
+ /** Resolved channel registry (implicit web + configureChannels + messengers). */
1269
+ private _channels?;
1299
1270
  /**
1300
1271
  * WorkerLoader binding for sandboxed extensions.
1301
1272
  * Set this to enable `getExtensions()` and dynamic extension loading.
@@ -1379,31 +1350,12 @@ declare class Think<
1379
1350
  * footprint over time, so the steady-state read size converges down.
1380
1351
  */
1381
1352
  private _readMessagesFromStorage;
1382
- /**
1383
- * Normalize a tool part's `input` into something the provider will accept.
1384
- *
1385
- * Malformed shapes 400 modern providers and persist forever once written:
1386
- * a stringified-JSON `input` (e.g. `'{"prompt":"a cat"}'` instead of the
1387
- * object), and any non-object `input` — `null`, `undefined`, `""`, an array,
1388
- * or a primitive — on a settled or interrupted tool call (Anthropic rejects
1389
- * a `tool_use` block whose `input` is not an object). We parse the former and
1390
- * default the latter to an empty object so the tool-call/tool-result pair
1391
- * stays valid. Delegates to the shared `normalizeToolInput` so the read-side
1392
- * repair and the write-side accumulator guard enforce the same invariant.
1393
- */
1394
- private _normalizeToolInput;
1395
1353
  /**
1396
1354
  * Whether a tool part already has a settled result the provider accepts, so
1397
- * it must NOT be re-repaired into an errored result.
1398
- *
1399
- * Single source of truth for the terminal tool states, shared by the repair
1400
- * pass and the backstop detector so they cannot drift. Mirror the AI SDK's
1401
- * terminal states: `convertToModelMessages` emits a `tool-result` for
1402
- * `output-available`, `output-error`, AND `output-denied` (a user-denied
1403
- * approval — its denial reason becomes the tool-result). Omitting any of
1404
- * these makes repair re-flip the part every turn — clobbering a real
1405
- * `errorText`/denial with the generic "interrupted" message — and makes the
1406
- * backstop falsely drop a valid call.
1355
+ * it must NOT be re-repaired into an errored result. Delegates to the shared
1356
+ * `agents/chat` primitive so the repair pass and the backstop detector
1357
+ * (`_incompleteToolCallIds`) share the single source of truth for terminal
1358
+ * tool states.
1407
1359
  */
1408
1360
  private _toolPartHasSettledResult;
1409
1361
  /**
@@ -1539,9 +1491,21 @@ declare class Think<
1539
1491
  private _upsertCachedMessage;
1540
1492
  /** Patch a message that is already present in the live cache. */
1541
1493
  private _patchCachedMessage;
1494
+ /** Sanitize + row-size-compact a message before it touches storage. */
1495
+ private _rowSafe;
1542
1496
  private _appendMessageToHistory;
1543
1497
  private _updateMessageInHistory;
1544
1498
  private _upsertMessageInHistory;
1499
+ /**
1500
+ * The orphan-persist store adapter — orphan-persist steps **(c)/(d)** route
1501
+ * their write through this shared `OrphanPersistStore` seam (the
1502
+ * `SessionProvider` write-subset). Delegates to `this.session` with `_rowSafe`
1503
+ * applied at the write boundary (sanitize + row-size cap), exactly as Think's
1504
+ * other Session call sites do. The `SessionMessage → UIMessage` read cast is
1505
+ * confined here, matching those call sites.
1506
+ * @internal
1507
+ */
1508
+ protected _orphanStore(): OrphanPersistStore;
1545
1509
  private _clearHistory;
1546
1510
  /** Append a message while keeping Think's live message cache coherent. */
1547
1511
  protected appendMessageToHistory(
@@ -1556,11 +1520,24 @@ declare class Think<
1556
1520
  private _turnQueue;
1557
1521
  protected _resumableStream: ResumableStream;
1558
1522
  private _pendingResumeConnections;
1523
+ /** Lazily-built shared resume-handshake driver (Tier-2). */
1524
+ private _resumeHandshakeInstance;
1559
1525
  private _lastClientTools;
1560
1526
  private _lastBody;
1561
1527
  private _continuation;
1562
- private _continuationTimer;
1563
- private _continuationBarrierActive;
1528
+ /**
1529
+ * Accepted-but-not-yet-streamed turns and the connections parked waiting for
1530
+ * one (#1784). See {@link ResumeHandshake} `preStream`.
1531
+ *
1532
+ * HIBERNATION INVARIANT: in-memory only, NOT persisted. Safe because the
1533
+ * pre-stream window cannot overlap hibernation — a turn between `begin()` and
1534
+ * stream start is an unresolved `onMessage` handler promise that pins the DO,
1535
+ * so eviction only happens once a durable stream exists (resumed via
1536
+ * `ResumableStream`) or the turn finished. Breaks if a pre-stream wait is ever
1537
+ * moved onto a durable alarm that releases the DO; if so, persist this state.
1538
+ */
1539
+ private _preStream;
1540
+ private _autoContinuation;
1564
1541
  private _insideResponseHook;
1565
1542
  private _insideInferenceLoop;
1566
1543
  private _pendingInteractionPromise;
@@ -1586,6 +1563,8 @@ declare class Think<
1586
1563
  private _submissionTableEnsured;
1587
1564
  private _workflowNotificationTableEnsured;
1588
1565
  private _declaredScheduledTasksTableEnsured;
1566
+ private _actionLedgerTableEnsured;
1567
+ private _actionPendingTableEnsured;
1589
1568
  private _drainingSubmissions;
1590
1569
  private _drainingWorkflowNotifications;
1591
1570
  private _submissionAbortControllers;
@@ -1603,6 +1582,37 @@ declare class Think<
1603
1582
  * outcome is cached.
1604
1583
  */
1605
1584
  private _agentToolRunForRequest;
1585
+ /**
1586
+ * Re-bind this facet's in-flight agent-tool child run to the CURRENT turn's
1587
+ * request id.
1588
+ *
1589
+ * When this facet is itself running as an agent-tool child and its turn is
1590
+ * interrupted (e.g. a deploy evicts it mid-run), the recovery continuation
1591
+ * (`continueLastTurn` / `_retryLastUserTurn`) mints a NEW request id. The
1592
+ * `cf_agent_tool_child_runs.request_id` column — and the in-memory attribution
1593
+ * map — still point at the pre-eviction turn, so `broadcast` can no longer
1594
+ * attribute the recovered turn's frames to the run. The parent's re-attach
1595
+ * tail then sees no forwarded chunks, its no-progress budget elapses, and it
1596
+ * abandons a healthy, still-advancing child as `interrupted`
1597
+ * (`agentToolReattachNoProgressTimeoutMs`). Re-binding the row to the recovery
1598
+ * turn's request id keeps frame attribution alive across recovery so the
1599
+ * parent re-attaches and follows the child to its real terminal.
1600
+ *
1601
+ * Safe to call on EVERY recovery continuation:
1602
+ * - Facets that never ran as an agent-tool child have no
1603
+ * `cf_agent_tool_child_runs` table → the guarded SELECT throws → no-op.
1604
+ * - A facet whose run already settled has no `starting`/`running` row → no-op.
1605
+ * - A child DO is addressed by its `runId` (`subAgent(cls, runId)`), so it
1606
+ * owns AT MOST ONE child-run row for its whole lifetime and is never reused
1607
+ * as a top-level chat agent — the single active row is unambiguously this
1608
+ * recovery's run. The `ORDER BY started_at DESC LIMIT 1` is defensive
1609
+ * belt-and-suspenders for that invariant.
1610
+ *
1611
+ * Uses the same `status IN ('starting','running')` active-run predicate as
1612
+ * `_agentToolRunForRequest` and the ai-chat counterpart (see the lifecycle
1613
+ * invariant note there).
1614
+ */
1615
+ private _rebindAgentToolChildRunRequestId;
1606
1616
  alarm(): Promise<void>;
1607
1617
  /**
1608
1618
  * Persist an arbitrary JSON-serializable configuration object for this
@@ -1646,8 +1656,19 @@ declare class Think<
1646
1656
  getSystemPrompt(): string;
1647
1657
  /** Return the tools available to the assistant. */
1648
1658
  getTools(): ToolSet;
1659
+ /** Return action descriptors compiled into tools for the assistant. */
1660
+ getActions(): Record<string, Action> | Promise<Record<string, Action>>;
1649
1661
  /** Return messenger integrations that should be routed through this Think agent. */
1650
1662
  getMessengers(): ThinkMessengers;
1663
+ /**
1664
+ * Return the channels for this agent. Wraps (does not supersede)
1665
+ * {@link getMessengers}: the implicit `web` channel is always present, each
1666
+ * messenger from `getMessengers()` is absorbed as a `kind: "messenger"`
1667
+ * channel, and these entries add `web`/`voice`/`custom` surfaces plus
1668
+ * per-channel policy. A channel id that collides with a `getMessengers()` id
1669
+ * is an error.
1670
+ */
1671
+ configureChannels(): ThinkChannels | Promise<ThinkChannels>;
1651
1672
  getMessengerContext(): MessengerContext | undefined;
1652
1673
  chatWithMessengerContext(
1653
1674
  userMessage: string | UIMessage,
@@ -1655,7 +1676,65 @@ declare class Think<
1655
1676
  context: MessengerContext,
1656
1677
  options?: ChatOptions
1657
1678
  ): Promise<void>;
1658
- private _initializeMessengers;
1679
+ /**
1680
+ * Bind the live messenger delivery surface for the active turn so
1681
+ * `deliverNotice` can post to the originating channel while a messenger turn
1682
+ * is running. Returns a restore function; save/restore keeps nested turns
1683
+ * safe. Called by `deliverMessengerReply`.
1684
+ */
1685
+ bindActiveDeliverySurface(surface: MessengerDeliverySurface): () => void;
1686
+ /**
1687
+ * The channel context for the active turn, if the turn resolved to a channel.
1688
+ * Readable from tools/hooks during a turn (e.g. to branch on `kind`).
1689
+ */
1690
+ get activeChannel(): ChannelContext | undefined;
1691
+ /** Resolve a channel id to a turn-scoped {@link ChannelContext}, if registered. */
1692
+ private _resolveChannelContext;
1693
+ /**
1694
+ * Run `fn` with the turn-scoped channel context set for `channel`. No-op (just
1695
+ * runs `fn`) when the channel is unset or unregistered. Save/restore keeps
1696
+ * nested turns safe — mirrors `chatWithMessengerContext`.
1697
+ */
1698
+ private _withChannelContext;
1699
+ /**
1700
+ * Stamp the channel id onto user messages so a recovered/continued turn can
1701
+ * re-resolve the channel from durable history.
1702
+ */
1703
+ private _stampChannel;
1704
+ /** The channel stamped on the latest user message in the given list, if any. */
1705
+ private _channelFromMessages;
1706
+ /** Re-resolve the channel for a continuation from the latest user message. */
1707
+ private _channelFromLatestUserMessage;
1708
+ /**
1709
+ * Deliver a no-turn, channel-routed message — a deterministic status, fallback,
1710
+ * or notice — straight to the channel's delivery surface WITHOUT invoking the
1711
+ * model and WITHOUT opening a recovery incident.
1712
+ *
1713
+ * Routing precedence for the target channel: explicit `options.channel` → the
1714
+ * active turn's channel → `"web"`. The `web` channel renders via the transcript
1715
+ * (its only client render path), so a web notice is always transcript-visible;
1716
+ * messenger/voice deliver out of band and only touch the transcript when
1717
+ * `informModel: true`.
1718
+ *
1719
+ * Like `addMessages`, this bypasses the turn queue and is safe to call from
1720
+ * inside a tool `execute` without deadlocking.
1721
+ */
1722
+ deliverNotice(
1723
+ text:
1724
+ | string
1725
+ | {
1726
+ markdown: string;
1727
+ },
1728
+ options?: DeliverNoticeOptions
1729
+ ): Promise<void>;
1730
+ /**
1731
+ * The active turn's channel id, if any. Prefers the turn-scoped channel
1732
+ * context, then the active messenger turn's id; web turns have none, so
1733
+ * `deliverNotice` defaults to `"web"`.
1734
+ */
1735
+ private _activeChannelId;
1736
+ private _noticeMessage;
1737
+ private _initializeChannels;
1659
1738
  /** Return code-declared scheduled tasks for this agent. */
1660
1739
  getScheduledTasks(): ThinkScheduledTasks | Promise<ThinkScheduledTasks>;
1661
1740
  /**
@@ -1674,6 +1753,36 @@ declare class Think<
1674
1753
  private _buildThinkCapabilityBlock;
1675
1754
  /** Maximum number of tool-call steps per turn. Override via property or per-turn via TurnConfig. */
1676
1755
  maxSteps: number;
1756
+ /**
1757
+ * Retention window for settled action ledger rows. Deleting a row ends the
1758
+ * idempotency guarantee for that key, so increase these windows for side
1759
+ * effects whose downstream idempotency horizon is longer. Set a status to
1760
+ * `false` to disable sweeping it.
1761
+ */
1762
+ actionLedgerRetention: ActionLedgerRetentionConfig;
1763
+ /**
1764
+ * Lease window after which a durable `pending` action ledger row is assumed
1765
+ * abandoned (its executor isolate died) and may be reclaimed and re-run.
1766
+ * Reclaim re-runs `execute`, so it only applies to actions that declare an
1767
+ * explicit `idempotencyKey` — that key is the developer's assertion that the
1768
+ * keyed side effect is safe to retry. Fallback `tool:${toolCallId}` keys are
1769
+ * never reclaimed. Set to `false` to disable stale-pending reclaim entirely
1770
+ * (a stale row then blocks forever with `ActionPendingError`, the old
1771
+ * behavior). This is a retry lease, not a retention window: retention answers
1772
+ * "when may we delete old rows?"; the lease answers "when may we assume the
1773
+ * previous executor died and retry safely?". Keep `actionLedgerRetention.pendingMs`
1774
+ * well above this lease so reclaim happens before a sweep deletes the row.
1775
+ */
1776
+ actionLedgerPendingRetryLeaseMs: number | false;
1777
+ /**
1778
+ * Retention window for abandoned durable-pause approval rows — a
1779
+ * `kind: "durable-pause"` action that parked but was never approved or
1780
+ * rejected. Deleting a row makes that approval permanently unresolvable, so
1781
+ * default generously: "approve days later from a dashboard" is the use case.
1782
+ * Set to `false` to disable sweeping. Rows are deleted promptly on
1783
+ * approve/reject regardless; this only bounds truly abandoned pauses.
1784
+ */
1785
+ actionPendingApprovalTtlMs: number | false;
1677
1786
  /**
1678
1787
  * Whether reasoning chunks are sent to chat clients by default. Override
1679
1788
  * per turn by returning `sendReasoning` from `beforeTurn`.
@@ -1743,6 +1852,20 @@ declare class Think<
1743
1852
  * Turns are serialized, so a single value is safe.
1744
1853
  */
1745
1854
  private _activeTurnTools;
1855
+ private _activeTurnActionMetadata;
1856
+ private _activeTurnAuthorization;
1857
+ private _activeTurnActionApprovalDescriptors;
1858
+ private _activeTurnApprovedActionInputs;
1859
+ private _activeActionLedgerExecutions;
1860
+ /**
1861
+ * Advisory reply attachments recorded by actions during the current admitted
1862
+ * turn (see `ctx.attachReply`). Single-slot because turns are serialized.
1863
+ * Reset at turn start in `_runInsideAdmittedTurnBody`; intentionally not
1864
+ * cleared at turn end so `onChatResponse` and `replyAttachments()` can read
1865
+ * it — the next turn's reset overwrites it.
1866
+ */
1867
+ private _activeTurnReplyAttachments;
1868
+ private _activeTurnReplyAttachmentsRequestId;
1746
1869
  /**
1747
1870
  * Number of times the proactive guard has compacted within the current
1748
1871
  * `_runInferenceLoop` (reset at the top of each run). Capped at
@@ -1824,6 +1947,40 @@ declare class Think<
1824
1947
  * ```
1825
1948
  */
1826
1949
  beforeTurn(_ctx: TurnContext): TurnConfig | void | Promise<TurnConfig | void>;
1950
+ /**
1951
+ * Authorize action permissions for the current turn. Returning `true` grants
1952
+ * all action permissions. Returning `grantedPermissions` limits the default
1953
+ * `authorizeAction` implementation to that permission set.
1954
+ */
1955
+ authorizeTurn(
1956
+ _ctx: TurnContext
1957
+ ): ActionAuthorizationDecision | Promise<ActionAuthorizationDecision>;
1958
+ /**
1959
+ * Authorize a single action call after its model input and required
1960
+ * permissions are known. Override this for app-specific policy; the default
1961
+ * implementation enforces the grant returned from `authorizeTurn`.
1962
+ */
1963
+ authorizeAction(
1964
+ ctx: ActionAuthorizationContext
1965
+ ): ActionAuthorizationDecision | Promise<ActionAuthorizationDecision>;
1966
+ /**
1967
+ * Enrich the approval descriptor shown in approval UIs for a paused codemode
1968
+ * `execute` execution. The default descriptor is derived from the first
1969
+ * pending action as `connector.method` with its args as the input; override
1970
+ * here to supply a human summary, the permissions it consumes, or a risk
1971
+ * level (returned fields are merged over the derived defaults).
1972
+ *
1973
+ * Not called for `kind: "durable-pause"` actions — those carry their own
1974
+ * descriptor from the `action()` config. Default returns `undefined` (use the
1975
+ * derived descriptor).
1976
+ */
1977
+ describePausedExecution(
1978
+ _pending: import("@cloudflare/codemode").PendingAction[],
1979
+ _ctx: {
1980
+ requestId: string;
1981
+ toolCallId: string;
1982
+ }
1983
+ ): Partial<ActionApprovalDescriptor> | undefined;
1827
1984
  /**
1828
1985
  * Called before each AI SDK step in the agentic loop. Backed by
1829
1986
  * `streamText({ prepareStep })`.
@@ -2068,6 +2225,36 @@ declare class Think<
2068
2225
  protected _transformInferenceResult(
2069
2226
  result: StreamableResult
2070
2227
  ): StreamableResult;
2228
+ private _normalizeActionAuthorization;
2229
+ private _emitActionLedgerEvent;
2230
+ private _emitChannelEvent;
2231
+ private _approvedActionInputsFromTranscript;
2232
+ private _resolveActionPermissions;
2233
+ private _actionContextWithoutReply;
2234
+ private _authorizeActionCall;
2235
+ private _compileActionTools;
2236
+ private _actionToTool;
2237
+ /**
2238
+ * Run an action's `execute` through the action ledger: same-isolate
2239
+ * coalescing, durable claim/replay, settle-on-success, release-on-failure.
2240
+ * Shared by the inline server-action path and the durable-pause-on-approve
2241
+ * path so an action's side effect is replay-safe regardless of how it is
2242
+ * dispatched. `runAction` must already apply timeout/abort and
2243
+ * `prepareActionOutputForModel`.
2244
+ */
2245
+ private _runLedgeredAction;
2246
+ /**
2247
+ * Park a `kind: "durable-pause"` action for human approval. Persists a
2248
+ * compaction-safe pending row (action name + model input + approval
2249
+ * descriptor) so the approval survives history compaction, deploys, and
2250
+ * isolate eviction, then returns the minimal model-visible paused output.
2251
+ *
2252
+ * The action's `execute` does NOT run here — it runs later in
2253
+ * `approveExecution` via `_runLedgeredAction`, so the side effect is gated on
2254
+ * human approval AND remains replay-safe. The rich descriptor lives on the
2255
+ * row and on the transcript part, never embedded in the model-visible output.
2256
+ */
2257
+ private _parkDurablePauseAction;
2071
2258
  /** Default hook timeout in milliseconds. */
2072
2259
  hookTimeout: number;
2073
2260
  /**
@@ -2154,31 +2341,163 @@ declare class Think<
2154
2341
  _hostGetSessionInfo(): Promise<{
2155
2342
  messageCount: number;
2156
2343
  }>;
2344
+ private _admitTurn;
2345
+ private _assertNotInsideAdmittedTurn;
2346
+ private _runInsideAdmittedTurnBody;
2157
2347
  /**
2158
2348
  * Run a chat turn: persist the user message, run the agentic loop,
2159
2349
  * stream UIMessageChunk events via callback, and persist the
2160
2350
  * assistant's response.
2161
2351
  *
2162
- * @param userMessage The user's message (string or UIMessage)
2352
+ * @param userMessage The user's message(s), or a callback that derives them
2353
+ * from the in-queue transcript.
2163
2354
  * @param callback Streaming callback (typically an RpcTarget from the parent)
2164
2355
  * @param options Optional chat options (e.g. AbortSignal)
2165
2356
  */
2166
2357
  chat(
2167
- userMessage: string | UIMessage,
2358
+ userMessage: TurnInputMessages,
2168
2359
  callback: StreamCallback,
2169
2360
  options?: ChatOptions
2170
2361
  ): Promise<void>;
2362
+ /**
2363
+ * Unified turn admission API (Turns RFC, step 2).
2364
+ *
2365
+ * Thin facade over {@link Think.saveMessages}, {@link Think.continueLastTurn},
2366
+ * {@link Think.submitMessages}, and {@link Think.chat}. Each `mode` delegates
2367
+ * to the matching backing method with a narrowed option surface; the full
2368
+ * unified superset lands with `_admitTurn` (step 3).
2369
+ *
2370
+ * - `mode: "wait"` (default) — blocking turn; returns {@link TurnResult}.
2371
+ * - `mode: "submit"` — durable queued turn; returns {@link SubmitMessagesResult}.
2372
+ * - `mode: "stream"` — RPC-style streaming; returns `Promise<void>`.
2373
+ *
2374
+ * **Re-entrancy.** Calling `mode: "wait"` or `continuation: true` from inside
2375
+ * an active turn (a tool `execute`, a lifecycle hook) deadlocks on the turn
2376
+ * queue — identical to calling {@link Think.saveMessages} or
2377
+ * {@link Think.continueLastTurn} from there. Prefer `mode: "submit"` or
2378
+ * {@link Think.addMessages} instead. Precise nested-call detection is deferred
2379
+ * to `_admitTurn` (step 3).
2380
+ *
2381
+ * **Empty input (`wait`).** String, single-message, and array inputs that
2382
+ * normalize to an empty list short-circuit to `{ status: "skipped" }` without
2383
+ * running inference. A function `input` that resolves to `[]` at run time is
2384
+ * not pre-checked (the function must see the in-queue transcript); step 3's
2385
+ * `_admitTurn` centralizes empty-skip inside the queue.
2386
+ *
2387
+ * @experimental
2388
+ */
2389
+ runTurn(options: RunTurnWait): Promise<TurnResult>;
2390
+ runTurn(options: RunTurnSubmit): Promise<SubmitMessagesResult>;
2391
+ runTurn(options: RunTurnStream): Promise<void>;
2392
+ private _resolveRunTurnMode;
2393
+ private _validateRunTurnAdmission;
2394
+ private _userMessageFromText;
2395
+ private _normalizeRunTurnMessages;
2396
+ private _normalizeChatMessages;
2397
+ private _assertRunTurnSubmitInput;
2398
+ private _enrichTurnResult;
2399
+ private _runTurnWait;
2400
+ private _runTurnSubmit;
2401
+ private _runTurnStream;
2171
2402
  /** Get the conversation history as UIMessage[]. */
2172
2403
  getMessages(): Promise<UIMessage[]>;
2173
2404
  /** Clear all messages from storage. */
2174
2405
  clearMessages(): Promise<void>;
2175
2406
  private _ensureAgentToolChildRunTable;
2407
+ private _persistAgentToolMilestone;
2408
+ private _readAgentToolMilestones;
2176
2409
  private _addAgentToolChildRunColumnIfMissing;
2177
2410
  private _readAgentToolChildRun;
2178
2411
  private _inspectionFromChildRow;
2412
+ /**
2413
+ * Rebuild the latest progress snapshot persisted by `reportProgress` from a
2414
+ * child run row, or `undefined` if the child never reported progress.
2415
+ */
2416
+ private static _progressSnapshotFromRow;
2179
2417
  protected formatAgentToolInput(input: unknown): UIMessage;
2418
+ private _agentToolProgressEmitterInstance;
2419
+ private get _agentToolProgressEmitter();
2420
+ reportProgress<T = unknown>(
2421
+ progress: AgentToolProgress<T>,
2422
+ options?: {
2423
+ persist?: boolean;
2424
+ }
2425
+ ): Promise<void>;
2180
2426
  protected getAgentToolOutput(_runId: string): unknown;
2181
2427
  protected getAgentToolSummary(runId: string, output: unknown): string;
2428
+ /**
2429
+ * Format the message injected back into the chat when a `detached:
2430
+ * { notify: true }` run finishes. Override to customize the prose (or return
2431
+ * an empty string to suppress the notification for a given outcome). The
2432
+ * default announces the terminal status and any summary/error so the model
2433
+ * has enough context to react.
2434
+ */
2435
+ protected formatDetachedCompletion(
2436
+ run: AgentToolRunInfo,
2437
+ result: AgentToolLifecycleResult
2438
+ ): string;
2439
+ /**
2440
+ * Serialize detached terminal delivery against the chat turn queue. A
2441
+ * fast-path push or backbone tick can land mid-turn, and an `onFinish` that
2442
+ * mutates state (`setState`, `submitMessages`, a follow-up `runAgentTool`)
2443
+ * running concurrently with an active LLM turn is a data race. Those paths
2444
+ * never run synchronously inside a turn body (they fire from `waitUntil` / a
2445
+ * scheduled alarm), so enqueuing on the turn queue runs the delivery strictly
2446
+ * between turns without risk of self-deadlock.
2447
+ *
2448
+ * An explicit `cancelAgentTool` (`serialize` unset) may be invoked from inside
2449
+ * the very turn that triggers it, where enqueuing WOULD self-deadlock, so it
2450
+ * runs inline in the caller's (or a fresh) `agentContext` instead. The Think
2451
+ * `notify` convenience is unaffected either way: it delivers via
2452
+ * `submitMessages`, which already serializes FIFO behind any active turn.
2453
+ */
2454
+ protected _runDetachedDelivery(
2455
+ invoke: () => Promise<void>,
2456
+ options?: {
2457
+ serialize?: boolean;
2458
+ }
2459
+ ): Promise<void>;
2460
+ /**
2461
+ * Targeted completion hook for `detached: { notify: true }`. Auto-wired by
2462
+ * `runAgentTool` (resolved by name so the base Agent stays decoupled from the
2463
+ * chat layer). Injects the formatted completion as a programmatic turn so the
2464
+ * model reacts to the background result. Idempotent per run + status, so an
2465
+ * exactly-once finish — or a soft give-up followed by a real completion —
2466
+ * never injects a duplicate, while a give-up and a later real completion are
2467
+ * surfaced as two distinct turns.
2468
+ */
2469
+ _cfDetachedNotifyFinish(
2470
+ run: AgentToolRunInfo,
2471
+ result: AgentToolLifecycleResult
2472
+ ): Promise<void>;
2473
+ /**
2474
+ * Format the synthetic message injected when a `detached: { onMilestones }`
2475
+ * milestone is reached. Override to customize the prose (or return an empty
2476
+ * string to suppress a given milestone). The default announces the milestone
2477
+ * name and any structured data so the model can react in-conversation before
2478
+ * the run finishes.
2479
+ */
2480
+ protected formatDetachedMilestone(
2481
+ run: AgentToolRunInfo,
2482
+ milestone: AgentToolMilestone
2483
+ ): string;
2484
+ /**
2485
+ * Targeted milestone hook for `detached: { onMilestones }`. Idempotent per run
2486
+ * + milestone NAME (not sequence — a name surfaces at most once even if
2487
+ * re-emitted), so the warm tail and the backbone reconcile converge. Fired
2488
+ * from both paths.
2489
+ *
2490
+ * - `"narrate"` (default): a synthetic **assistant** message injected directly
2491
+ * — no model turn — using a deterministic message id for idempotency
2492
+ * (`addMessages` is a no-op for an id already in history).
2493
+ * - `"react"`: a **user-role** turn so the model responds to the milestone
2494
+ * (idempotency via `submitMessages` + UNIQUE idempotency key).
2495
+ */
2496
+ protected _deliverDetachedMilestone(
2497
+ run: AgentToolRunInfo,
2498
+ milestone: AgentToolMilestone,
2499
+ mode: "react" | "narrate"
2500
+ ): Promise<void>;
2182
2501
  startAgentToolRun(
2183
2502
  input: unknown,
2184
2503
  options: {
@@ -2250,6 +2569,58 @@ declare class Think<
2250
2569
  */
2251
2570
  private _hasRecoveredAgentToolAssistantTurn;
2252
2571
  private _getAgentToolFinalText;
2572
+ private _ensureActionLedgerTable;
2573
+ private _readActionLedgerRow;
2574
+ /**
2575
+ * Claim a ledger key for execution. Read-then-write with no `await` between
2576
+ * the read and any write, so within the single DO isolate two claims cannot
2577
+ * interleave — the same race-free idiom documented on
2578
+ * {@link _claimActionPendingRow}. The only way a durable `pending` row
2579
+ * outlives its writer is a crashed prior isolate, which has no live writer to
2580
+ * race; that is the row a stale reclaim safely re-runs.
2581
+ */
2582
+ private _claimActionLedgerRow;
2583
+ private _settleActionLedgerRow;
2584
+ private _releaseActionLedgerRow;
2585
+ private _resolveActionLedgerKey;
2586
+ private _actionInputHash;
2587
+ private _actionLedgerRetentionForStatus;
2588
+ private _deleteActionLedgerRows;
2589
+ private _sweepActionLedgerStatus;
2590
+ private _sweepActionLedger;
2591
+ private _emitActionReplyEvent;
2592
+ /**
2593
+ * Record an advisory reply attachment for the active turn. Advisory: a
2594
+ * non-object, a missing/non-string `type`, or exceeding the per-turn cap is
2595
+ * silently ignored. The attachment is JSON-normalized to a safe copy so a
2596
+ * later mutation of the caller's object can't corrupt it and downstream
2597
+ * persistence/RPC can't choke on bigint/circular values.
2598
+ */
2599
+ private _recordReplyAttachment;
2600
+ private _cloneReplyAttachment;
2601
+ /**
2602
+ * Advisory reply attachments recorded during a turn via `ctx.attachReply`.
2603
+ * Returns deep copies. With no `requestId`, returns the most recent turn's
2604
+ * attachments; with a `requestId`, returns them only if they belong to that
2605
+ * turn (else `[]`).
2606
+ */
2607
+ replyAttachments(requestId?: string): ReplyAttachment[];
2608
+ private _emitActionPauseEvent;
2609
+ private _ensureActionPendingTable;
2610
+ private _readActionPendingRow;
2611
+ private _insertActionPendingRow;
2612
+ /**
2613
+ * Atomically claim a pending-approval row for resolution: read it, then
2614
+ * delete it. SQLite calls are synchronous and there is no `await` between the
2615
+ * read and the delete, so within the single DO isolate this is race-free — a
2616
+ * concurrent `approveExecution`/`rejectExecution` for the same id can only run
2617
+ * at an await boundary, by which point the row is already gone (it sees
2618
+ * `null` → "already resolved"). The returned row is the caller's to resolve.
2619
+ */
2620
+ private _claimActionPendingRow;
2621
+ private _listActionPendingRows;
2622
+ private _deleteActionPendingRows;
2623
+ private _sweepActionPendingApprovals;
2253
2624
  private _ensureDeclaredScheduledTasksTable;
2254
2625
  private _readDeclaredScheduledTaskRow;
2255
2626
  private _listDeclaredScheduledTaskRows;
@@ -2312,6 +2683,7 @@ declare class Think<
2312
2683
  _drainThinkSubmissions(): Promise<void>;
2313
2684
  private _drainSubmissions;
2314
2685
  private _runSubmission;
2686
+ private _executeSubmission;
2315
2687
  private _getSubmissionFinalStatus;
2316
2688
  private _markPendingSubmissionsSkipped;
2317
2689
  private _emitSkippedSubmissions;
@@ -2425,7 +2797,10 @@ declare class Think<
2425
2797
  */
2426
2798
  protected continueLastTurn(
2427
2799
  body?: Record<string, unknown>,
2428
- options?: SaveMessagesOptions
2800
+ options?: SaveMessagesOptions & {
2801
+ trigger?: TurnTrigger;
2802
+ channel?: string;
2803
+ }
2429
2804
  ): Promise<SaveMessagesResult>;
2430
2805
  private _retryLastUserTurn;
2431
2806
  private _setupProtocolHandlers;
@@ -2493,6 +2868,17 @@ declare class Think<
2493
2868
  * stored chunk, so it needs no separate stamping.
2494
2869
  */
2495
2870
  private _alignStreamStartId;
2871
+ private _annotateActionApprovalChunk;
2872
+ /**
2873
+ * Build the approval descriptor for a paused tool output, the single source
2874
+ * of truth for rendering a pending approval. Durable-pause actions read the
2875
+ * descriptor persisted on their pending row (resolved permissions, survives
2876
+ * compaction); codemode pauses derive `connector.method` from the first
2877
+ * pending action and let {@link describePausedExecution} enrich it. Returns
2878
+ * `undefined` for non-paused outputs or when no descriptor can be built.
2879
+ */
2880
+ private _descriptorForPausedOutput;
2881
+ private _applyActionApprovalDescriptorToParts;
2496
2882
  private _streamResultToRpcCallback;
2497
2883
  /**
2498
2884
  * Whether storing this chunk should immediately flush the resumable-stream
@@ -2515,15 +2901,22 @@ declare class Think<
2515
2901
  * step, never an already-completed tool call).
2516
2902
  */
2517
2903
  private _storeChunkDurably;
2904
+ /** Per-isolate throttle for crediting recovery progress from mid-segment
2905
+ * streaming-content deltas (the shared `agents/chat` rule); reset per isolate
2906
+ * so the first delta after a restart always credits. */
2907
+ private _streamProgressCredit;
2908
+ private _streamResult;
2518
2909
  /**
2519
- * Wrap a UI-message stream with an inactivity watchdog. If no chunk arrives
2520
- * within `timeoutMs`, `onStall` runs (aborting the upstream model stream) and
2521
- * the iterator throws, so the consumer loop exits with a terminal error
2522
- * instead of parking forever on a hung provider/transport. `timeoutMs <= 0`
2523
- * passes the source through untouched.
2910
+ * Single source of Think's strip + empty-skip persistence rule. Strips the
2911
+ * internal final-answer parts and returns the message to persist (the stripped
2912
+ * copy, or the original when nothing was stripped), or `null` when stripping
2913
+ * leaves nothing user-facing (only structural `step-start` markers, or
2914
+ * nothing) — in which case the caller skips persistence so a structured
2915
+ * workflow turn does not leave an empty assistant message in the conversation.
2916
+ * Shared by `_persistAssistantMessage` and the orphan-persist path so the rule
2917
+ * cannot drift between the live and recovery writes.
2524
2918
  */
2525
- private _iterateWithStallWatchdog;
2526
- private _streamResult;
2919
+ private _strippedForPersist;
2527
2920
  private _persistAssistantMessage;
2528
2921
  /**
2529
2922
  * Remove parts belonging to Think's internal structured-output final-answer
@@ -2588,6 +2981,17 @@ declare class Think<
2588
2981
  pendingExecutions(
2589
2982
  executionId?: string
2590
2983
  ): Promise<import("@cloudflare/codemode").PendingAction[]>;
2984
+ /**
2985
+ * List everything awaiting human approval — parked `kind: "durable-pause"`
2986
+ * actions and paused codemode executions — each carrying its
2987
+ * {@link ActionApprovalDescriptor}. The unified, descriptor-first view a
2988
+ * dashboard, voice backend, or messenger reconciles against; resolve any of
2989
+ * them via {@link approveExecution} / {@link rejectExecution}. Pass an
2990
+ * `executionId` to scope to one.
2991
+ *
2992
+ * Client-callable.
2993
+ */
2994
+ pendingApprovals(executionId?: string): Promise<PendingApproval[]>;
2591
2995
  /**
2592
2996
  * Approve a paused execution and resume it. The run continues from where
2593
2997
  * it stopped (replaying logged work, executing the approved call); the
@@ -2602,6 +3006,26 @@ declare class Think<
2602
3006
  * Client-callable.
2603
3007
  */
2604
3008
  approveExecution(executionId: string): Promise<unknown>;
3009
+ /**
3010
+ * Approve a parked `kind: "durable-pause"` action and run its `execute`.
3011
+ *
3012
+ * Claim-by-delete makes this idempotent across tabs/recovery: only the caller
3013
+ * that removes the row runs the action; a racing approve/reject sees no row
3014
+ * and reports "already resolved". Authorization happened at PAUSE time — the
3015
+ * human approval is the authority now, so we do not re-authorize (the turn
3016
+ * context that `authorizeAction` needs is gone). The action runs through the
3017
+ * ledger so its side effect stays replay-safe, the outcome replaces the
3018
+ * paused transcript part, and the chat continues even with no socket open.
3019
+ */
3020
+ private _approveActionPause;
3021
+ /** Resolve a registered action by its resolved name (config.name ?? key). */
3022
+ private _findRegisteredAction;
3023
+ /**
3024
+ * Run a just-approved durable-pause action's `execute` through the ledger.
3025
+ * Mirrors the inline `_actionToTool` execute wrapper (timeout, abort race,
3026
+ * model-output prep) MINUS authorization — that was settled at pause time.
3027
+ */
3028
+ private _runApprovedActionPause;
2605
3029
  /**
2606
3030
  * Reject a paused execution's pending action, ending the run. The
2607
3031
  * transcript's paused output is replaced with
@@ -2611,6 +3035,13 @@ declare class Think<
2611
3035
  * Client-callable.
2612
3036
  */
2613
3037
  rejectExecution(executionId: string, reason?: string): Promise<unknown>;
3038
+ /**
3039
+ * Reject a parked `kind: "durable-pause"` action. Claim-by-delete consumes
3040
+ * the pending row (idempotent across tabs/recovery), the action's `execute`
3041
+ * never runs, and the paused transcript part is replaced with a `rejected`
3042
+ * outcome so the model can adapt or explain.
3043
+ */
3044
+ private _rejectActionPause;
2614
3045
  /**
2615
3046
  * Replace a paused execute-tool output in the transcript with the
2616
3047
  * execution's new outcome and kick the auto-continuation so the model sees
@@ -2639,6 +3070,14 @@ declare class Think<
2639
3070
  private _findExecutionToolCall;
2640
3071
  private _applyToolUpdateToMessages;
2641
3072
  protected hasPendingInteraction(): boolean;
3073
+ /**
3074
+ * `true` when an auto-continuation is armed but has not yet fired (#1650): a
3075
+ * pending continuation that has not entered its turn (`!pastCoalesce`) whose
3076
+ * coalesce timer is still pending or whose completeness drain is in progress.
3077
+ * Mirrors `@cloudflare/ai-chat`'s `_hasArmedContinuation`, consuming the shared
3078
+ * controller's `isArmed()`.
3079
+ */
3080
+ private _hasArmedContinuation;
2642
3081
  protected waitUntilStable(options?: { timeout?: number }): Promise<boolean>;
2643
3082
  private _awaitWithDeadline;
2644
3083
  private _messageHasPendingInteraction;
@@ -2651,8 +3090,6 @@ declare class Think<
2651
3090
  * ever post its result.
2652
3091
  */
2653
3092
  private _clientResolvableToolNames;
2654
- /** Extract a tool part's name from its `tool-<name>` / `dynamic-tool` shape. */
2655
- private _toolPartName;
2656
3093
  /**
2657
3094
  * Whether a part is still awaiting a CLIENT interaction that can genuinely
2658
3095
  * arrive after a restart, so `waitUntilStable` must keep waiting for it:
@@ -2675,8 +3112,6 @@ declare class Think<
2675
3112
  */
2676
3113
  private _partAwaitsClientInteraction;
2677
3114
  private _resolveChatRecoveryConfig;
2678
- private _chatRecoveryIncidentId;
2679
- private _chatRecoveryIncidentKey;
2680
3115
  /**
2681
3116
  * Monotonic forward-progress signal for recovery budget resets.
2682
3117
  *
@@ -2692,12 +3127,13 @@ declare class Think<
2692
3127
  */
2693
3128
  private _chatRecoveryProgressMarker;
2694
3129
  /** Advance the durable recovery-progress counter. Called from
2695
- * `_storeChunkDurably` when new content is durably flushed (real, reconnect-
2696
- * immune forward progress). */
3130
+ * `_storeChunkDurably` when a stored chunk credits forward progress under the
3131
+ * shared rule (real, reconnect-immune forward progress). The increment lives
3132
+ * in the shared engine (agents/chat); this is the package binding. */
2697
3133
  private _bumpChatRecoveryProgress;
2698
- /** In-memory wall-clock of the last N9 child-stream progress bump (reset per
2699
- * isolate so the first forwarded chunk after a restart always credits). */
2700
- private _lastAgentToolStreamProgressAt;
3134
+ /** Per-isolate N9 throttle gate (shared `agents/chat` helper); reset per
3135
+ * isolate so the first forwarded chunk after a restart always credits. */
3136
+ private _agentToolStreamProgress;
2701
3137
  /**
2702
3138
  * N9: forwarding a sub-agent's chunks IS forward progress for this parent
2703
3139
  * turn, so credit the parent's recovery progress marker — otherwise a parent
@@ -2708,9 +3144,14 @@ declare class Think<
2708
3144
  * Throttled (and reset per isolate) so we never write storage per token.
2709
3145
  */
2710
3146
  protected _onAgentToolStreamProgress(): Promise<void>;
2711
- /** Sweep recovery incidents that have been inactive past the TTL. */
2712
- private _sweepStaleChatRecoveryIncidents;
2713
3147
  private _beginChatRecoveryIncident;
3148
+ /**
3149
+ * Lazily-built shared recovery engine. The adapter arrows capture `this`, so a
3150
+ * single cached instance is correct across calls (and across future engine
3151
+ * methods).
3152
+ */
3153
+ private _chatRecoveryEngineInstance?;
3154
+ private _chatRecoveryEngine;
2714
3155
  private _updateChatRecoveryIncident;
2715
3156
  private _exhaustChatRecovery;
2716
3157
  /**
@@ -2740,6 +3181,31 @@ declare class Think<
2740
3181
  protected _handleInternalFiberRecovery(
2741
3182
  ctx: FiberRecoveryContext
2742
3183
  ): Promise<boolean>;
3184
+ /**
3185
+ * Resolve the orphaned stream + its terminal status for a recovered chat turn.
3186
+ * Drives BOTH the wake path (full result) and the give-up terminalization
3187
+ * (which reads only `.streamId`; the terminal banner still fires when
3188
+ * `streamId` is `""` — `_exhaustChatRecovery` does not require a stream).
3189
+ * Prefers the newest durable stream row keyed by the recovery-root request id;
3190
+ * falls back to the live active stream.
3191
+ */
3192
+ private _resolveThinkRecoveryStream;
3193
+ /**
3194
+ * Classify a recovered turn as `retry` or `continue`. A pre-stream turn with no
3195
+ * partial re-runs its user message (`retryTargetUserId`), unless the stream is
3196
+ * already terminal — a terminal stream is never retried (it completed), only
3197
+ * its submission is reconciled in dispatch.
3198
+ */
3199
+ private _classifyRecoveredThinkTurn;
3200
+ /**
3201
+ * The retry/continue/skip decision for a recovered chat turn, run after the
3202
+ * partial is persisted and the stream completed. Owns `Think`'s substrate
3203
+ * behavior the engine frame stays out of: a terminal stream reconciles the
3204
+ * durable submission (and is never retried/continued), and a `continue: false`
3205
+ * abandonment marks the submission interrupted + records a terminal status +
3206
+ * broadcasts so a reconnecting client is not frozen.
3207
+ */
3208
+ private _dispatchRecoveredThinkTurn;
2743
3209
  private _recoverablePreStreamUserId;
2744
3210
  private _hasPersistedRecoveredAssistant;
2745
3211
  /**
@@ -2750,10 +3216,6 @@ declare class Think<
2750
3216
  * an earlier attempt already saved.
2751
3217
  */
2752
3218
  private _shouldPersistOrphanedPartial;
2753
- /** Whether a reconstructed partial carries any settled (provider-accepted)
2754
- * tool result — the completed, often non-idempotent work that a
2755
- * `{ persist: false }` recovery return would silently discard. */
2756
- private _partialHasSettledToolResults;
2757
3219
  /**
2758
3220
  * Reschedule a recovery callback that timed out waiting for stable state,
2759
3221
  * consuming one attempt. Returns `true` if rescheduled, `false` if the
@@ -2804,14 +3266,6 @@ declare class Think<
2804
3266
  * reschedule / exhaustion path).
2805
3267
  */
2806
3268
  private _parkRecoveryForPendingInteraction;
2807
- /**
2808
- * Resolve the stream id for a recovery turn so the give-up terminalization
2809
- * can surface whatever partial the turn produced. Prefers the durable stream
2810
- * row keyed by the recovery-root request id; falls back to the live active
2811
- * stream. Returns `""` when neither is available (the terminal banner still
2812
- * fires — `_exhaustChatRecovery` does not require a stream).
2813
- */
2814
- private _resolveRecoveryStreamId;
2815
3269
  /**
2816
3270
  * Terminalize a recovery turn that is giving up — whether because the
2817
3271
  * stable-state-timeout retry budget drained, or because the recovery
@@ -2905,6 +3359,15 @@ declare class Think<
2905
3359
  private _getPartialStreamText;
2906
3360
  private _getSubmitConcurrencyDecision;
2907
3361
  private _completeSkippedRequest;
3362
+ /**
3363
+ * Mark an accepted turn (#1784) as settled. When `releaseParked` (the default)
3364
+ * and no accepted turn remains in flight and no stream is active, release every
3365
+ * connection parked on the pre-stream window with STREAM_RESUME_NONE. No-op once
3366
+ * they were flushed into STREAM_RESUMING on stream start. Skip paths pass
3367
+ * `releaseParked: false` so a parked client survives onto the successor turn
3368
+ * (see `_completeSkippedRequest`).
3369
+ */
3370
+ private _settlePreStreamTurn;
2908
3371
  private _rollbackDroppedSubmit;
2909
3372
  private _scheduleAutoContinuation;
2910
3373
  /**
@@ -2934,35 +3397,6 @@ declare class Think<
2934
3397
  * to hold (event-driven) until its remaining siblings answer.
2935
3398
  */
2936
3399
  private _onStreamingTurnFinalized;
2937
- private _resetAutoContinuationTimer;
2938
- /**
2939
- * Fire an auto-continuation, but only once the model's parallel tool-call
2940
- * batch is fully answered (#1649). When the model emits several tool calls in
2941
- * one step the client answers each independently, so the first `autoContinue`
2942
- * arrives while slower siblings are still `input-available`. Continuing then
2943
- * would feed the provider an incomplete tool-result set
2944
- * (`MissingToolResultsError`) or, via the transcript-repair backstop, silently
2945
- * error the in-flight sibling and run a spurious extra continuation.
2946
- *
2947
- * The barrier is event-driven (#1650). Auto-continuation is only ever
2948
- * triggered by a tool-result/approval event, so rather than wait on a fixed
2949
- * timer we drain the in-flight applies, re-check, and — if the batch is still
2950
- * incomplete — return WITHOUT firing and WITHOUT holding the isolate, leaving
2951
- * `_continuation.pending` in place. The next sibling's result re-arms the
2952
- * coalesce timer (`_scheduleAutoContinuation`) and re-runs this check; the
2953
- * continuation fires once the final sibling lands. If the in-memory pending
2954
- * state is lost to eviction between siblings, the final result re-creates it
2955
- * from the persisted transcript and fires with a complete batch — self-healing.
2956
- * A true orphan (a sibling that never arrives) simply never auto-continues,
2957
- * which is correct: there is nothing valid to continue, and a later user turn
2958
- * / chat recovery repairs the transcript.
2959
- *
2960
- * The barrier also holds while the assistant turn is still streaming (the
2961
- * stream-active gate below): mid-stream the batch can still grow with tool
2962
- * calls the model hasn't emitted yet, so no completeness check is meaningful.
2963
- * `_onStreamingTurnFinalized` re-runs the check once the stream ends.
2964
- */
2965
- private _fireAutoContinuationWhenStable;
2966
3400
  /**
2967
3401
  * Drain every in-flight tool-result/approval apply, including any enqueued
2968
3402
  * while we wait, so the subsequent `_hasIncompleteToolBatch()` re-check sees
@@ -2984,6 +3418,38 @@ declare class Think<
2984
3418
  private _hasIncompleteToolBatch;
2985
3419
  private _fireAutoContinuation;
2986
3420
  private _activateDeferredContinuation;
3421
+ /**
3422
+ * Run a continuation turn that does NOT require a live client connection.
3423
+ *
3424
+ * Used when a durable approval (a paused action or codemode execution) is
3425
+ * resolved via RPC from a surface with no open chat socket — e.g. an ops
3426
+ * dashboard, a webhook, or a voice backend approving hours/days later. The
3427
+ * connection-bound auto-continuation barrier (`_fireAutoContinuation`) cannot
3428
+ * fire without a `Connection`, so this mirrors its turn body but streams via
3429
+ * `broadcast` (a no-op when nobody is attached) and always persists, so a
3430
+ * client that reconnects later resumes the continued turn from history.
3431
+ *
3432
+ * Wrapped in `keepAliveWhile` because the resolving RPC returns before the
3433
+ * continuation finishes (mirrors the submission-drain pattern).
3434
+ */
3435
+ private _runConnectionlessContinuation;
3436
+ /**
3437
+ * Render a reply attachment ({@link ReplyAttachment}) for delivery to the
3438
+ * active channel. Returns the text/markdown to post, or `undefined` to skip —
3439
+ * unknown types, or types a channel handles out of band (e.g. `voice_note`
3440
+ * via the voice transport). Override to customize per app/channel.
3441
+ */
3442
+ renderAttachment(attachment: ReplyAttachment):
3443
+ | string
3444
+ | {
3445
+ markdown: string;
3446
+ }
3447
+ | undefined;
3448
+ /**
3449
+ * Deliver known reply attachments to the active channel (best-effort, never
3450
+ * fails the turn). Unknown types are ignored.
3451
+ */
3452
+ private _renderChannelAttachments;
2987
3453
  private _fireResponseHook;
2988
3454
  /**
2989
3455
  * Persist (on `error`/`interrupted`) or clear (on `completed`/`aborted`) the
@@ -3007,23 +3473,6 @@ declare class Think<
3007
3473
  /** Clear the durable terminal record once a later turn supersedes it (#1645). */
3008
3474
  private _clearChatTerminal;
3009
3475
  private _pendingChatTerminal;
3010
- /**
3011
- * Replay a pending terminal outcome (#1645) over the resume handshake so a
3012
- * reconnecting client surfaces it exactly like a live exhaustion. A bare
3013
- * terminal frame sent on connect is dropped by the `useAgentChat` client
3014
- * because it never reaches a transport stream reader; only a frame delivered
3015
- * on a resumed stream becomes `useChat.error` (this is why the terminal is
3016
- * NOT included in `_buildIdleConnectMessages`). So we drive `STREAM_RESUMING`
3017
- * here and send the error frame once the client ACKs (see
3018
- * `_replayTerminalOnAck`). Returns true if a terminal was pending.
3019
- */
3020
- private _replayTerminalOnResume;
3021
- /**
3022
- * Deliver the pending terminal error frame on the resumed stream the client
3023
- * ACKed (#1645). The record is retained (cleared only when a later turn
3024
- * supersedes it) so concurrent reconnects each learn the outcome.
3025
- */
3026
- private _replayTerminalOnAck;
3027
3476
  /**
3028
3477
  * Set or clear the live "recovering…" status for a durable chat turn (#1620).
3029
3478
  * Persists a durable record (replayed on connect via `_buildIdleConnectMessages`)
@@ -3041,11 +3490,25 @@ declare class Think<
3041
3490
  * `MSG_CHAT_RESPONSE` frame on connect is dropped by the `useAgentChat`
3042
3491
  * client because it never reaches a transport stream reader, so it cannot
3043
3492
  * become `useChat.error` — a failed turn would still look frozen (#1645).
3044
- * The terminal outcome is instead surfaced over the resume handshake
3045
- * (`_replayTerminalOnResume` → ACK → `_replayTerminalOnAck`), the only path
3046
- * that lands on the stream reader.
3493
+ * The terminal outcome is instead surfaced over the resume handshake (the
3494
+ * shared {@link ResumeHandshake} drives `STREAM_RESUMING` → ACK → terminal
3495
+ * error frame), the only path that lands on the stream reader.
3047
3496
  */
3048
3497
  private _buildIdleConnectMessages;
3498
+ /**
3499
+ * The shared resume-handshake driver (Tier-2). Lazily built; the
3500
+ * `ResumableStream` / `ContinuationState` / pending set are stable after
3501
+ * `onStart`, so a single instance threads them for the agent's lifetime. The
3502
+ * idle-connect payload (transcript + recovering, `_buildIdleConnectMessages`)
3503
+ * stays host-owned and is NOT part of the driver.
3504
+ */
3505
+ private _resumeHandshake;
3506
+ /**
3507
+ * Notify a connection about an active stream that can be resumed — delegates
3508
+ * to the shared {@link ResumeHandshake}. Kept as a thin method because it is
3509
+ * also called proactively from onConnect and the broadcast loop. See the
3510
+ * driver for the #1733 double-send contract.
3511
+ */
3049
3512
  private _notifyStreamResuming;
3050
3513
  /**
3051
3514
  * Start a resumable stream and arm buffer cleanup. Wrapper around
@@ -3094,8 +3557,8 @@ declare class Think<
3094
3557
  idempotent?: boolean;
3095
3558
  }): Promise<void>;
3096
3559
  /**
3097
- * Alarm callback: sweep aged stream buffers, then re-arm only while rows
3098
- * remain so a fully-swept DO stops waking itself.
3560
+ * Alarm callback: sweep aged stream buffers, re-arming while rows remain (see
3561
+ * the shared {@link cleanupStreamBuffers}).
3099
3562
  */
3100
3563
  _cleanupStreamBuffers(): Promise<void>;
3101
3564
  private _persistOrphanedStream;
@@ -3104,121 +3567,543 @@ declare class Think<
3104
3567
  private _broadcastMessages;
3105
3568
  }
3106
3569
  //#endregion
3570
+ //#region src/messengers/events.d.ts
3571
+ type MessengerEventKind =
3572
+ | "direct-message"
3573
+ | "mention"
3574
+ | "subscribed-message"
3575
+ | "action"
3576
+ | "delivery-event";
3577
+ interface MessengerAuthor {
3578
+ fullName?: string;
3579
+ isBot?: boolean | "unknown";
3580
+ isMe?: boolean;
3581
+ userId: string;
3582
+ userName?: string;
3583
+ }
3584
+ interface MessengerAttachment {
3585
+ data?: ArrayBuffer;
3586
+ fetch?: () => Promise<ArrayBuffer>;
3587
+ id?: string;
3588
+ mediaType?: string;
3589
+ name?: string;
3590
+ raw?: unknown;
3591
+ size?: number;
3592
+ text?: string;
3593
+ url?: string;
3594
+ }
3595
+ interface MessengerThread {
3596
+ channelId?: string;
3597
+ channelName?: string;
3598
+ id: string;
3599
+ isDirectMessage: boolean;
3600
+ providerThreadId: string;
3601
+ title?: string;
3602
+ }
3603
+ interface MessengerMessage {
3604
+ attachments: MessengerAttachment[];
3605
+ author: MessengerAuthor;
3606
+ createdAt?: Date;
3607
+ id: string;
3608
+ isMention?: boolean;
3609
+ providerMessageId: string;
3610
+ raw?: unknown;
3611
+ text: string;
3612
+ }
3613
+ interface MessengerAction {
3614
+ actionId: string;
3615
+ messageId?: string;
3616
+ raw?: unknown;
3617
+ user?: MessengerAuthor;
3618
+ value?: string;
3619
+ }
3620
+ interface MessengerCapabilities {
3621
+ canEditMessages?: boolean;
3622
+ canStream?: boolean;
3623
+ maxMessageLength?: number;
3624
+ supportsActions?: boolean;
3625
+ supportsAttachments?: boolean;
3626
+ supportsEphemeral?: boolean;
3627
+ }
3628
+ interface MessengerContext {
3629
+ action?: MessengerAction;
3630
+ author?: MessengerAuthor;
3631
+ capabilities: MessengerCapabilities;
3632
+ kind: MessengerEventKind;
3633
+ message?: MessengerMessage;
3634
+ messengerId: string;
3635
+ provider: string;
3636
+ thread: MessengerThread;
3637
+ }
3638
+ interface MessengerEvent extends MessengerContext {
3639
+ raw?: unknown;
3640
+ }
3641
+ declare function messengerContextFromEvent(
3642
+ event: MessengerEvent
3643
+ ): MessengerContext;
3644
+ declare function serializableMessengerEvent(
3645
+ event: MessengerEvent
3646
+ ): MessengerEvent;
3647
+ declare function toMessengerUserMessage(event: MessengerEvent): UIMessage;
3648
+ //#endregion
3649
+ //#region src/messengers/delivery.d.ts
3650
+ declare const MESSENGER_REPLY_FIBER_NAME = "think:messenger-reply";
3651
+ declare const EMPTY_MESSENGER_RESPONSE =
3652
+ "I couldn't produce a text response. Please try again.";
3653
+ declare const ERROR_MESSENGER_RESPONSE =
3654
+ "Sorry, I couldn't answer that right now. Please try again.";
3655
+ declare const INTERRUPTED_MESSENGER_RESPONSE =
3656
+ "Sorry, my reply was interrupted. Please send your message again if you'd like me to retry.";
3657
+ interface TextStreamCallbackOptions {
3658
+ onVisibleStart?: () => Promise<void> | void;
3659
+ visibleSoftLimit?: number;
3660
+ }
3661
+ declare class TextStreamCallback extends RpcTarget implements StreamCallback {
3662
+ private readonly onVisibleStart?;
3663
+ private readonly visibleChunks;
3664
+ private readonly wakeups;
3665
+ private readonly visibleSoftLimit?;
3666
+ private chatRequestId?;
3667
+ private closed;
3668
+ private interrupted;
3669
+ private error?;
3670
+ private text;
3671
+ private visibleClosed;
3672
+ private visibleLimitReachedValue;
3673
+ private visibleStarted;
3674
+ private visibleTextValue;
3675
+ constructor(options?: TextStreamCallbackOptions);
3676
+ onStart(event: ChatStartEvent): void;
3677
+ onEvent(json: string): void;
3678
+ onDone(): void;
3679
+ onError(error: string): void;
3680
+ onInterrupted(): void;
3681
+ wasInterrupted(): boolean;
3682
+ close(): void;
3683
+ fail(error: unknown): void;
3684
+ hasText(): boolean;
3685
+ remainingText(): string;
3686
+ requestId(): string | undefined;
3687
+ textSoFar(): string;
3688
+ visibleLimitReached(): boolean;
3689
+ visibleText(): string;
3690
+ stream(): AsyncIterable<string>;
3691
+ private pushVisibleText;
3692
+ private wake;
3693
+ private markVisibleStarted;
3694
+ }
3695
+ declare function textDeltaFromStreamChunk(json: string): string | null;
3696
+ type MessengerReplyStage = "accepted" | "streaming" | "completed";
3697
+ /**
3698
+ * Explicit delivery lifecycle kind, orthogonal to {@link MessengerReplyStage}.
3699
+ * Lets surfaces (voice/CLI especially) tell a final answer from an interim
3700
+ * progress note from a deterministic notice from a control command, rather than
3701
+ * inferring from text shape.
3702
+ */
3703
+ type DeliveryKind = "final" | "interim" | "notice" | "command";
3704
+ /**
3705
+ * Explicit delivery lifecycle tag carried on the wire/snapshot. Orthogonal to,
3706
+ * and additive on top of, {@link MessengerReplyStage}: recovery still switches
3707
+ * on `stage`, while `kind`/`turnEnded` give non-streaming-text surfaces
3708
+ * (voice/CLI) an explicit signal instead of inferring from text shape.
3709
+ */
3710
+ interface DeliveryTag {
3711
+ stage: MessengerReplyStage;
3712
+ kind: DeliveryKind;
3713
+ turnEnded: boolean;
3714
+ }
3715
+ /** Derive a sensible default tag from a reply stage. */
3716
+ declare function defaultDeliveryTag(stage: MessengerReplyStage): DeliveryTag;
3717
+ interface MessengerReplySnapshot {
3718
+ event: MessengerEvent;
3719
+ stage: MessengerReplyStage;
3720
+ tag?: DeliveryTag;
3721
+ thread?: unknown;
3722
+ type: typeof MESSENGER_REPLY_FIBER_NAME;
3723
+ }
3724
+ declare function messengerReplySnapshot(
3725
+ stage: MessengerReplyStage,
3726
+ event: MessengerEvent,
3727
+ thread?: unknown,
3728
+ tag?: DeliveryTag
3729
+ ): MessengerReplySnapshot;
3730
+ declare function parseMessengerReplySnapshot(
3731
+ snapshot: unknown
3732
+ ): MessengerReplySnapshot | null;
3733
+ declare function messengerReplyRecoveryMode(
3734
+ snapshot: MessengerReplySnapshot
3735
+ ): "answer" | "apologize" | null;
3736
+ declare function messengerReplyFailureMode(
3737
+ hasStreamedText: boolean,
3738
+ completedModelTurn?: boolean,
3739
+ expectedDeliveryCompletion?: boolean
3740
+ ): "apologize" | "error" | null;
3741
+ interface MessengerDeliveryTarget {
3742
+ cancelChat(
3743
+ requestId: string,
3744
+ reason?: string
3745
+ ): boolean | void | Promise<boolean | void>;
3746
+ chat(
3747
+ userMessage: string | UIMessage,
3748
+ callback: StreamCallback
3749
+ ): Promise<void>;
3750
+ chatWithMessengerContext?(
3751
+ userMessage: string | UIMessage,
3752
+ callback: StreamCallback,
3753
+ context: MessengerEvent
3754
+ ): Promise<void>;
3755
+ /**
3756
+ * Bind the live delivery surface for the duration of the model turn so the
3757
+ * target can reach it from `deliverNotice` while a messenger turn is active.
3758
+ * Returns a restore function (save/restore, so nested turns are safe).
3759
+ */
3760
+ bindActiveDeliverySurface?(surface: MessengerDeliverySurface): () => void;
3761
+ }
3762
+ interface MessengerDeliverySurface {
3763
+ post(
3764
+ message:
3765
+ | string
3766
+ | {
3767
+ markdown: string;
3768
+ }
3769
+ | AsyncIterable<string>
3770
+ ): Promise<unknown>;
3771
+ startTyping?(status?: string): Promise<void>;
3772
+ }
3773
+ interface MessengerDeliveryPolicy {
3774
+ emptyResponseText?: string;
3775
+ errorResponseText?: string;
3776
+ interruptedResponseText?: string;
3777
+ isExpectedDeliveryCompletion?(
3778
+ error: unknown,
3779
+ callback: TextStreamCallback
3780
+ ): boolean;
3781
+ splitText?(text: string): string[];
3782
+ visibleSoftLimit?: number;
3783
+ }
3784
+ interface DeliverMessengerReplyOptions {
3785
+ checkpoint?: (snapshot: MessengerReplySnapshot) => Promise<void> | void;
3786
+ event: MessengerEvent;
3787
+ fiber?: FiberContext;
3788
+ policy?: MessengerDeliveryPolicy;
3789
+ snapshotEvent?: MessengerEvent;
3790
+ snapshotThread?: unknown;
3791
+ surface: MessengerDeliverySurface;
3792
+ target: MessengerDeliveryTarget;
3793
+ userMessage?: UIMessage;
3794
+ }
3795
+ declare function deliverMessengerReply(
3796
+ options: DeliverMessengerReplyOptions
3797
+ ): Promise<void>;
3798
+ //#endregion
3799
+ //#region src/messengers/chat-sdk.d.ts
3800
+ declare class ThinkMessengerStateAgent extends ChatSdkStateAgent {}
3801
+ type MessengerRespondTo =
3802
+ | "action"
3803
+ | "direct-message"
3804
+ | "mention"
3805
+ | "subscribed-thread";
3806
+ type MessengerConversationMode = "self" | "thread";
3807
+ type MessengerConversationTarget =
3808
+ | {
3809
+ target: "self";
3810
+ }
3811
+ | {
3812
+ agentClass?: SubAgentClass<Agent & MessengerThinkTarget>;
3813
+ name: string;
3814
+ target: "subagent";
3815
+ };
3816
+ type MessengerConversationResolver = (
3817
+ event: MessengerEvent
3818
+ ) => MessengerConversationTarget | Promise<MessengerConversationTarget>;
3819
+ interface MessengerDefinition {
3820
+ adapter: Adapter;
3821
+ adapterName: string;
3822
+ capabilities?: MessengerCapabilities;
3823
+ conversation?: MessengerConversationMode | MessengerConversationResolver;
3824
+ delivery?: MessengerDeliveryPolicy;
3825
+ keyShard?: ChatSdkStateAdapterOptions["keyShard"];
3826
+ path?: string;
3827
+ provider: string;
3828
+ respondTo?: readonly MessengerRespondTo[];
3829
+ shardKey?: ChatSdkStateAdapterOptions["shardKey"];
3830
+ subscribeOnMention?: boolean;
3831
+ toEvent?: (
3832
+ input: ChatSdkMessengerEventInput
3833
+ ) => MessengerEvent | Promise<MessengerEvent>;
3834
+ userName: string;
3835
+ verifyWebhook?:
3836
+ | false
3837
+ | ((request: Request) => boolean | Response | Promise<boolean | Response>);
3838
+ }
3839
+ type ThinkMessengers = Record<string, MessengerDefinition>;
3840
+ interface NormalizedMessengerDefinition extends MessengerDefinition {
3841
+ id: string;
3842
+ path: string;
3843
+ respondTo: readonly MessengerRespondTo[];
3844
+ subscribeOnMention: boolean;
3845
+ verifyWebhook:
3846
+ | false
3847
+ | ((request: Request) => boolean | Response | Promise<boolean | Response>);
3848
+ }
3849
+ interface ChatSdkMessengerOptions extends Omit<
3850
+ MessengerDefinition,
3851
+ "adapterName"
3852
+ > {
3853
+ adapterName?: string;
3854
+ }
3855
+ interface ChatSdkMessengerEventInput {
3856
+ action?: ActionEvent;
3857
+ eventKind: MessengerEventKind;
3858
+ message?: Message;
3859
+ raw?: unknown;
3860
+ thread: Thread;
3861
+ }
3862
+ interface MessengerThinkTarget {
3863
+ cancelChat(
3864
+ requestId: string,
3865
+ reason?: string
3866
+ ): boolean | void | Promise<boolean | void>;
3867
+ chat(
3868
+ userMessage: string | UIMessage,
3869
+ callback: StreamCallback
3870
+ ): Promise<void>;
3871
+ chatWithMessengerContext?(
3872
+ userMessage: string | UIMessage,
3873
+ callback: StreamCallback,
3874
+ context: MessengerEvent
3875
+ ): Promise<void>;
3876
+ }
3877
+ interface MessengerThinkHost extends MessengerThinkTarget {
3878
+ constructor: {
3879
+ name: string;
3880
+ };
3881
+ name: string;
3882
+ parentPath: ReadonlyArray<{
3883
+ className: string;
3884
+ name: string;
3885
+ }>;
3886
+ startFiber(
3887
+ name: string,
3888
+ fn: (ctx: FiberContext) => Promise<void>,
3889
+ options?: StartFiberOptions
3890
+ ): Promise<MessengerFiberStartResult>;
3891
+ resolveFiber(id: string, result: FiberRecoveryResult): Promise<boolean>;
3892
+ subAgent<T extends Agent>(
3893
+ agentClass: SubAgentClass<T>,
3894
+ name: string
3895
+ ): Promise<SubAgentStub<T>>;
3896
+ }
3897
+ interface MessengerFiberStartResult {
3898
+ accepted: boolean;
3899
+ fiberId: string;
3900
+ snapshot?: unknown;
3901
+ status: string;
3902
+ }
3903
+ declare function chatSdkMessenger(
3904
+ options: ChatSdkMessengerOptions
3905
+ ): MessengerDefinition;
3906
+ declare class ThinkMessengerRuntime {
3907
+ private readonly host;
3908
+ private chat?;
3909
+ private readonly definitionsByAdapterName;
3910
+ private readonly definitionsById;
3911
+ private readonly definitions;
3912
+ constructor(definitions: ThinkMessengers, host: MessengerThinkHost);
3913
+ get size(): number;
3914
+ initialize(): void;
3915
+ handleRequest(request: Request): Promise<Response | undefined>;
3916
+ handleFiberRecovery(ctx: FiberRecoveryContext): Promise<boolean>;
3917
+ private createChat;
3918
+ private enqueueReply;
3919
+ private answer;
3920
+ /**
3921
+ * Resolve a live delivery surface for an out-of-turn notice (e.g. a scheduled
3922
+ * task or webhook handler calling `deliverNotice`). Uses `chat.thread(id)` —
3923
+ * the chat SDK's supported "post from outside a webhook" primitive, which
3924
+ * returns a postable {@link ChatThread} and infers the adapter from the
3925
+ * thread-id prefix, so it works for every chat-sdk adapter with no per-adapter
3926
+ * wiring. Returns `undefined` when the channel is unregistered or no `threadId`
3927
+ * was supplied so the caller can fail fast.
3928
+ */
3929
+ resolveDeliverySurface(
3930
+ channelId: string,
3931
+ threadId?: string
3932
+ ): Promise<MessengerDeliverySurface | undefined>;
3933
+ private resolveTarget;
3934
+ private definitionForThread;
3935
+ private definitionForThreadId;
3936
+ private hasUniqueProvider;
3937
+ private shardThread;
3938
+ private shardStateKey;
3939
+ private reviveChatObject;
3940
+ private toEvent;
3941
+ }
3942
+ declare function normalizeMessengers(
3943
+ messengers: ThinkMessengers
3944
+ ): NormalizedMessengerDefinition[];
3945
+ declare function defaultConversationName(event: MessengerEvent): string;
3946
+ declare function idempotencyKeyForEvent(event: MessengerEvent): string;
3947
+ declare function defaultChatSdkEvent(
3948
+ definition: NormalizedMessengerDefinition,
3949
+ input: ChatSdkMessengerEventInput
3950
+ ): MessengerEvent;
3951
+ declare function toMessengerThread(thread: Thread): MessengerThread;
3952
+ declare function toMessengerMessage(message: Message): MessengerMessage;
3953
+ declare function toMessengerAuthor(author: Author): MessengerAuthor;
3954
+ declare function toMessengerAttachment(
3955
+ attachment: Attachment
3956
+ ): MessengerAttachment;
3957
+ //#endregion
3107
3958
  export {
3108
- TurnConfig as $,
3109
- MessengerContext as $t,
3110
- SkillSource$1 as A,
3111
- toMessengerThread as At,
3112
- Think as B,
3113
- MessengerReplyStage as Bt,
3114
- PrepareStepFunction$1 as C,
3115
- defaultConversationName as Ct,
3116
- SaveMessagesResult$1 as D,
3117
- toMessengerAttachment as Dt,
3118
- SaveMessagesOptions$1 as E,
3119
- normalizeMessengers as Et,
3120
- StreamCallback as F,
3121
- MESSENGER_REPLY_FIBER_NAME as Ft,
3122
- ThinkScheduledTasks as G,
3123
- messengerReplyRecoveryMode as Gt,
3124
- ThinkScheduledTask as H,
3125
- TextStreamCallbackOptions as Ht,
3126
- StreamableResult as I,
3127
- MessengerDeliveryPolicy as It,
3128
- ThinkTime as J,
3129
- textDeltaFromStreamChunk as Jt,
3130
- ThinkSubmissionInspection as K,
3131
- messengerReplySnapshot as Kt,
3132
- SubmitMessagesOptions as L,
3133
- MessengerDeliverySurface as Lt,
3134
- StepContext as M,
3135
- EMPTY_MESSENGER_RESPONSE as Mt,
3136
- StepResult as N,
3137
- ERROR_MESSENGER_RESPONSE as Nt,
3138
- Session$1 as O,
3139
- toMessengerAuthor as Ot,
3140
- StopCondition$1 as P,
3141
- INTERRUPTED_MESSENGER_RESPONSE as Pt,
3142
- ToolCallResultContext as Q,
3143
- MessengerCapabilities as Qt,
3144
- SubmitMessagesResult as R,
3145
- MessengerDeliveryTarget as Rt,
3146
- PrepareStepContext as S,
3147
- defaultChatSdkEvent as St,
3148
- ResolvedChatRecoveryConfig as T,
3149
- idempotencyKeyForEvent as Tt,
3150
- ThinkScheduledTaskContext as U,
3151
- deliverMessengerReply as Ut,
3152
- ThinkIntervalSchedule as V,
3153
- TextStreamCallback as Vt,
3154
- ThinkScheduledTaskSchedule as W,
3155
- messengerReplyFailureMode as Wt,
3156
- ToolCallContext as X,
3157
- MessengerAttachment as Xt,
3158
- ThinkWallClockSchedule as Y,
3159
- MessengerAction as Yt,
3160
- ToolCallDecision as Z,
3161
- MessengerAuthor as Zt,
3162
- FiberContext$1 as _,
3163
- NormalizedMessengerDefinition as _t,
3164
- ChatRecoveryConfig$1 as a,
3165
- serializableMessengerEvent as an,
3166
- defaultContextOverflowClassifier as at,
3167
- MessageConcurrency$1 as b,
3168
- ThinkMessengers as bt,
3169
- ChatRecoveryOptions$1 as c,
3170
- ChatSdkMessengerEventInput as ct,
3171
- ChatStartEvent as d,
3172
- MessengerConversationResolver as dt,
3173
- MessengerEvent as en,
3174
- TurnContext as et,
3175
- ChunkContext as f,
3176
- MessengerConversationTarget as ft,
3177
- ExtensionConfig as g,
3178
- MessengerThinkTarget as gt,
3179
- DeleteSubmissionsOptions as h,
3180
- MessengerThinkHost as ht,
3181
- ChatOptions as i,
3182
- messengerContextFromEvent as in,
3183
- Workspace$1 as it,
3184
- StepConfig as j,
3185
- DeliverMessengerReplyOptions as jt,
3186
- SkillRunContext as k,
3187
- toMessengerMessage as kt,
3188
- ChatRecoveryProgressContext as l,
3189
- ChatSdkMessengerOptions as lt,
3190
- ContextOverflowConfig as m,
3191
- MessengerRespondTo as mt,
3192
- ChatErrorClassification as n,
3193
- MessengerMessage as nn,
3194
- TypedToolCall$1 as nt,
3195
- ChatRecoveryContext$1 as o,
3196
- toMessengerUserMessage as on,
3197
- defineScheduledTasks as ot,
3198
- ChunkPart as p,
3199
- MessengerDefinition as pt,
3200
- ThinkSubmissionStatus as q,
3201
- parseMessengerReplySnapshot as qt,
3202
- ChatErrorContext as r,
3203
- MessengerThread as rn,
3204
- TypedToolResult as rt,
3205
- ChatRecoveryExhaustedContext as s,
3206
- MediaEvictionConfig as sn,
3207
- skills as st,
3208
- AddMessagesOptions as t,
3209
- MessengerEventKind as tn,
3210
- TurnInput as tt,
3211
- ChatResponseResult$1 as u,
3212
- MessengerConversationMode as ut,
3213
- FiberRecoveryContext$1 as v,
3214
- ThinkMessengerRuntime as vt,
3215
- PrepareStepResult$1 as w,
3216
- defineMessengers as wt,
3217
- OnStartDegradation as x,
3218
- chatSdkMessenger as xt,
3219
- ListSubmissionsOptions as y,
3220
- ThinkMessengerStateAgent as yt,
3221
- TextStreamPart as z,
3222
- MessengerReplySnapshot as zt
3959
+ messengerContextFromEvent as $,
3960
+ StepResult as $t,
3961
+ MessengerDeliveryPolicy as A,
3962
+ skills as An,
3963
+ FiberRecoveryContext$1 as At,
3964
+ messengerReplyRecoveryMode as B,
3965
+ messengerChannel as Bn,
3966
+ RunTurnBase as Bt,
3967
+ DeliverMessengerReplyOptions as C,
3968
+ TurnResult as Cn,
3969
+ ChunkContext as Ct,
3970
+ ERROR_MESSENGER_RESPONSE as D,
3971
+ action as Dn,
3972
+ DeliverNoticeOptions as Dt,
3973
+ EMPTY_MESSENGER_RESPONSE as E,
3974
+ Workspace$1 as En,
3975
+ DeleteSubmissionsOptions as Et,
3976
+ TextStreamCallback as F,
3977
+ ChannelDeliverySurface as Fn,
3978
+ PrepareStepContext as Ft,
3979
+ MessengerAttachment as G,
3980
+ SaveMessagesOptions$1 as Gt,
3981
+ parseMessengerReplySnapshot as H,
3982
+ RunTurnStream as Ht,
3983
+ TextStreamCallbackOptions as I,
3984
+ ChannelIngress as In,
3985
+ PrepareStepFunction$1 as It,
3986
+ MessengerContext as J,
3987
+ SessionMessage$1 as Jt,
3988
+ MessengerAuthor as K,
3989
+ SaveMessagesResult$1 as Kt,
3990
+ defaultDeliveryTag as L,
3991
+ ChannelKind as Ln,
3992
+ PrepareStepResult$1 as Lt,
3993
+ MessengerDeliveryTarget as M,
3994
+ ChannelContext as Mn,
3995
+ MessageConcurrency$1 as Mt,
3996
+ MessengerReplySnapshot as N,
3997
+ ChannelDefinition as Nn,
3998
+ OnStartDegradation as Nt,
3999
+ INTERRUPTED_MESSENGER_RESPONSE as O,
4000
+ defaultContextOverflowClassifier as On,
4001
+ ExtensionConfig as Ot,
4002
+ MessengerReplyStage as P,
4003
+ ChannelDeliveryPolicy as Pn,
4004
+ PendingApproval as Pt,
4005
+ MessengerThread as Q,
4006
+ StepContext as Qt,
4007
+ deliverMessengerReply as R,
4008
+ NormalizedChannelDefinition as Rn,
4009
+ ReplyAttachment as Rt,
4010
+ toMessengerThread as S,
4011
+ TurnInputMessages as Sn,
4012
+ ChatStartEvent as St,
4013
+ DeliveryTag as T,
4014
+ TypedToolResult as Tn,
4015
+ ContextOverflowConfig as Tt,
4016
+ textDeltaFromStreamChunk as U,
4017
+ RunTurnSubmit as Ut,
4018
+ messengerReplySnapshot as V,
4019
+ MediaEvictionConfig as Vn,
4020
+ RunTurnOptions as Vt,
4021
+ MessengerAction as W,
4022
+ RunTurnWait as Wt,
4023
+ MessengerEventKind as X,
4024
+ SkillSource$1 as Xt,
4025
+ MessengerEvent as Y,
4026
+ SkillRunContext as Yt,
4027
+ MessengerMessage as Z,
4028
+ StepConfig as Zt,
4029
+ idempotencyKeyForEvent as _,
4030
+ ToolCallDecision as _n,
4031
+ ChatRecoveryContext$1 as _t,
4032
+ MessengerConversationTarget as a,
4033
+ TextStreamPart as an,
4034
+ ActionAuthorizationContext as at,
4035
+ toMessengerAuthor as b,
4036
+ TurnContext as bn,
4037
+ ChatRecoveryProgressContext as bt,
4038
+ MessengerThinkHost as c,
4039
+ ThinkScheduledTask as cn,
4040
+ ActionContext as ct,
4041
+ ThinkMessengerRuntime as d,
4042
+ ThinkScheduledTasks as dn,
4043
+ ActionPermissionSpec as dt,
4044
+ StopCondition$1 as en,
4045
+ serializableMessengerEvent as et,
4046
+ ThinkMessengerStateAgent as f,
4047
+ ThinkSubmissionInspection as fn,
4048
+ AddMessagesOptions as ft,
4049
+ defaultConversationName as g,
4050
+ ToolCallContext as gn,
4051
+ ChatRecoveryConfig$1 as gt,
4052
+ defaultChatSdkEvent as h,
4053
+ ThinkWallClockSchedule as hn,
4054
+ ChatOptions as ht,
4055
+ MessengerConversationResolver as i,
4056
+ SubmitMessagesResult as in,
4057
+ ActionApprovalPolicy as it,
4058
+ MessengerDeliverySurface as j,
4059
+ ChannelCapabilities as jn,
4060
+ ListSubmissionsOptions as jt,
4061
+ MESSENGER_REPLY_FIBER_NAME as k,
4062
+ isAction as kn,
4063
+ FiberContext$1 as kt,
4064
+ MessengerThinkTarget as l,
4065
+ ThinkScheduledTaskContext as ln,
4066
+ ActionIdempotencyKey as lt,
4067
+ chatSdkMessenger as m,
4068
+ ThinkTime as mn,
4069
+ ChatErrorContext as mt,
4070
+ ChatSdkMessengerOptions as n,
4071
+ StreamableResult as nn,
4072
+ Action as nt,
4073
+ MessengerDefinition as o,
4074
+ Think as on,
4075
+ ActionAuthorizationDecision as ot,
4076
+ ThinkMessengers as p,
4077
+ ThinkSubmissionStatus as pn,
4078
+ ChatErrorClassification as pt,
4079
+ MessengerCapabilities as q,
4080
+ Session$1 as qt,
4081
+ MessengerConversationMode as r,
4082
+ SubmitMessagesOptions as rn,
4083
+ ActionApprovalDescriptor as rt,
4084
+ MessengerRespondTo as s,
4085
+ ThinkIntervalSchedule as sn,
4086
+ ActionConfig as st,
4087
+ ChatSdkMessengerEventInput as t,
4088
+ StreamCallback as tn,
4089
+ toMessengerUserMessage as tt,
4090
+ NormalizedMessengerDefinition as u,
4091
+ ThinkScheduledTaskSchedule as un,
4092
+ ActionKind as ut,
4093
+ normalizeMessengers as v,
4094
+ ToolCallResultContext as vn,
4095
+ ChatRecoveryExhaustedContext as vt,
4096
+ DeliveryKind as w,
4097
+ TypedToolCall$1 as wn,
4098
+ ChunkPart as wt,
4099
+ toMessengerMessage as x,
4100
+ TurnInput as xn,
4101
+ ChatResponseResult$1 as xt,
4102
+ toMessengerAttachment as y,
4103
+ TurnConfig as yn,
4104
+ ChatRecoveryOptions$1 as yt,
4105
+ messengerReplyFailureMode as z,
4106
+ ThinkChannels as zn,
4107
+ ResolvedChatRecoveryConfig as zt
3223
4108
  };
3224
- //# sourceMappingURL=think-i1Pkgb1R.d.ts.map
4109
+ //# sourceMappingURL=index-D_S5mETO.d.ts.map