@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
@@ -0,0 +1,297 @@
1
+ # Actions
2
+
3
+ > **Experimental.** The API surface may evolve before Think graduates out of
4
+ > experimental.
5
+
6
+ Actions are server-side tools with batteries included. Where a plain AI SDK
7
+ `tool()` is just a description, a schema, and an `execute` function, an
8
+ `action()` adds the things that are tedious and dangerous to get right by hand
9
+ for a tool that has real side effects:
10
+
11
+ - **Idempotency** — a durable ledger replays a settled result by a stable key
12
+ instead of re-running the side effect on a recovery retry.
13
+ - **Approvals** — gate a call behind a human, either inline (the turn waits) or
14
+ durably (the turn parks and resumes later, even from a dashboard with no live
15
+ socket).
16
+ - **Authorization** — declare the permissions a call requires and grant them
17
+ per-turn.
18
+ - **Reply attachments** — record advisory delivery metadata (a drafted email, a
19
+ card, a voice note) without changing what the model sees.
20
+
21
+ Actions compile into Think tools, so the model calls them exactly like any other
22
+ tool. Return them from `getActions()`; Think merges them into the tool set
23
+ alongside `getTools()`, workspace tools, extensions, and MCP tools.
24
+
25
+ ## Define an action
26
+
27
+ Use the `action()` descriptor factory and return a map of actions from
28
+ `getActions()`. The map key is the tool name the model sees (unless you set
29
+ `name`). The `execute` input type is inferred from `inputSchema`:
30
+
31
+ ```typescript
32
+ import { Think, action } from "@cloudflare/think";
33
+ import { z } from "zod";
34
+
35
+ export class Support extends Think<Env> {
36
+ getActions() {
37
+ return {
38
+ refundOrder: action({
39
+ description: "Refund a customer order.",
40
+ inputSchema: z.object({
41
+ orderId: z.string(),
42
+ amountCents: z.number().int().positive()
43
+ }),
44
+ execute: async ({ orderId, amountCents }, ctx) => {
45
+ const result = await refund(orderId, amountCents);
46
+ return { refundId: result.id, status: result.status };
47
+ }
48
+ })
49
+ };
50
+ }
51
+ }
52
+ ```
53
+
54
+ The `execute` callback receives the validated input and an `ActionContext`:
55
+
56
+ ```typescript
57
+ type ActionContext = {
58
+ agent: Think;
59
+ env: Cloudflare.Env;
60
+ requestId: string;
61
+ toolCallId: string;
62
+ messages: ReadonlyArray<ModelMessage>;
63
+ signal: AbortSignal; // aborts on turn cancel or after `timeoutMs`
64
+ attachReply(attachment: ReplyAttachment): void;
65
+ };
66
+ ```
67
+
68
+ The action output is normalized to JSON and truncated before it is shown to the
69
+ model (long outputs are capped). Anything thrown from `execute` becomes a
70
+ structured `{ error: { name, message } }` tool result rather than crashing the
71
+ turn. Each action has a default timeout of 30 seconds; override it per action
72
+ with `timeoutMs`.
73
+
74
+ ### Actions versus plain tools
75
+
76
+ A plain `tool()` from `getTools()` still works and is the right choice for a
77
+ read-only or trivial tool. Reach for `action()` when a tool has side effects you
78
+ must not run twice, needs human approval, or needs declarative authorization —
79
+ the ledger, approval descriptors, default timeout, and structured error mapping
80
+ only apply to actions.
81
+
82
+ ## Idempotency and the action ledger
83
+
84
+ When an action declares an `idempotencyKey`, Think records the settled result in
85
+ a durable ledger keyed by `action:<name>:<key>`. If the same key is seen again —
86
+ on a recovery retry, a reconnect, or a duplicate inbound event — Think returns
87
+ the stored result **without** re-running `execute`, so the side effect happens
88
+ at most once on the happy path.
89
+
90
+ ```typescript
91
+ chargeInvoice: action({
92
+ description: "Charge an invoice.",
93
+ inputSchema: z.object({ invoiceId: z.string() }),
94
+ // Use a stable domain identifier — never a timestamp, request id, or random value.
95
+ idempotencyKey: ({ input }) => `invoice:${input.invoiceId}`,
96
+ execute: async ({ invoiceId }) => charge(invoiceId)
97
+ });
98
+ ```
99
+
100
+ `idempotencyKey` is a string, or a function `({ input, ctx }) => string`. Choose
101
+ a key that survives recovery retries — an order id, an inbound event id — and
102
+ not a value that changes per attempt. An action with no `idempotencyKey` falls
103
+ back to a per-`toolCallId` key, which only deduplicates within the same tool
104
+ call, not across retries.
105
+
106
+ ### Pending rows and the retry lease
107
+
108
+ A ledger row is written as `pending` before `execute` runs and flipped to
109
+ `settled` on success (a thrown or timed-out `execute` deletes the row so the
110
+ call can be retried cleanly). If the isolate dies mid-execute, the row is left
111
+ `pending`. By default such a stale row is reclaimed and the action re-run once
112
+ the row is older than `actionLedgerPendingRetryLeaseMs` (default 5 minutes) —
113
+ **but only for actions that declare an explicit `idempotencyKey`**, since that
114
+ key is your assertion that re-running the keyed side effect is safe. A fresh
115
+ pending row (or one without an explicit key) instead returns an
116
+ `ActionPendingError` result so the model does not blindly retry an unknown
117
+ state. Set `actionLedgerPendingRetryLeaseMs = false` to disable reclaim entirely
118
+ and always surface `ActionPendingError` for a stale row.
119
+
120
+ ## Approvals
121
+
122
+ Gate an action behind a human with `approval`. There are two mechanisms,
123
+ selected by `kind`.
124
+
125
+ ### Approval-gated (the turn waits)
126
+
127
+ The default when you set `approval` without a `kind`. The action compiles to a
128
+ tool with the AI SDK `needsApproval` flag: the stream pauses with an
129
+ `approval-requested` part, the client approves or rejects, and the turn
130
+ continues inline. `execute` runs only after approval.
131
+
132
+ ```typescript
133
+ deleteAccount: action({
134
+ description: "Permanently delete a user account.",
135
+ inputSchema: z.object({ userId: z.string() }),
136
+ approval: true, // or ({ input }) => input.userId !== currentUser
137
+ approvalSummary: "Delete an account",
138
+ approvalRisk: "high",
139
+ execute: async ({ userId }) => deleteAccount(userId)
140
+ });
141
+ ```
142
+
143
+ `approval` is a boolean or a predicate `({ input, ctx }) => boolean`, so you can
144
+ require approval only for risky inputs. `approvalSummary` and `approvalRisk`
145
+ (`"low" | "medium" | "high"`) populate the approval descriptor your UI renders.
146
+
147
+ ### Durable-pause (the turn parks and resumes later)
148
+
149
+ Set `kind: "durable-pause"` when approval may take minutes or days and you do not
150
+ want to hold a connection open. The action parks into a durable store and the
151
+ turn ends; `execute` does not run yet. Resume later — from anywhere, including a
152
+ dashboard with no live WebSocket — with `approveExecution()` or
153
+ `rejectExecution()`:
154
+
155
+ ```typescript
156
+ deploy: action({
157
+ description: "Deploy to production.",
158
+ inputSchema: z.object({ ref: z.string() }),
159
+ kind: "durable-pause",
160
+ approvalSummary: "Deploy to production",
161
+ approvalRisk: "high",
162
+ permissions: ["deploy:run"],
163
+ execute: async ({ ref }) => deploy(ref)
164
+ });
165
+ ```
166
+
167
+ ```typescript
168
+ // List everything waiting on a human (cold-load reconciliation):
169
+ const pending = await agent.pendingApprovals();
170
+ // [{ executionId, source: "action" | "codemode", descriptor }]
171
+
172
+ // Approve or reject by execution id (idempotent — a second call is a no-op):
173
+ await agent.approveExecution(executionId);
174
+ await agent.rejectExecution(executionId, "Not this release");
175
+ ```
176
+
177
+ `approveExecution()` runs `execute` once and auto-continues the turn even if no
178
+ client is connected; `rejectExecution()` resolves the action without running it.
179
+ `pendingApprovals()` merges parked actions and paused Codemode executions, so a
180
+ single approval UI can drive both. (`durable-pause` requires an `approval`
181
+ policy — an action that would never park is rejected at definition time.)
182
+
183
+ Both approval-gated and durable-pause parts carry a stable
184
+ `ActionApprovalDescriptor` (`{ requestId, toolCallId, action, summary, input,
185
+ permissions, risk, kind }`) so your UI has everything it needs to render the
186
+ prompt.
187
+
188
+ ## Authorization
189
+
190
+ Declare the permissions an action requires with `permissions`, then grant them
191
+ per turn. By default every turn is fully authorized, so authorization is opt-in.
192
+
193
+ ```typescript
194
+ refundOrder: action({
195
+ description: "Refund a customer order.",
196
+ inputSchema: z.object({ orderId: z.string() }),
197
+ permissions: ["billing:refund"], // or ({ input }) => [...]
198
+ execute: async ({ orderId }) => refund(orderId)
199
+ });
200
+ ```
201
+
202
+ Override `authorizeTurn()` to decide, once per turn, which permissions are
203
+ granted. Returning a list narrows the grant; any action requiring a permission
204
+ outside the set is denied with a structured `ActionAuthorizationError` (the model
205
+ never calls `execute`):
206
+
207
+ ```typescript
208
+ export class Support extends Think<Env> {
209
+ override authorizeTurn(ctx: TurnContext): ActionAuthorizationDecision {
210
+ const role = (ctx.body as { role?: string })?.role;
211
+ if (role === "admin") return true; // full grant (the default)
212
+ return { allowed: true, grantedPermissions: ["billing:read"] };
213
+ }
214
+ }
215
+ ```
216
+
217
+ `authorizeTurn()` returns `true` (full grant), `false` (deny all), or
218
+ `{ allowed, reason?, grantedPermissions? }`. For per-call logic, override
219
+ `authorizeAction(ctx)` instead — it receives the action name, kind, input, and
220
+ required and granted permissions.
221
+
222
+ ## Reply attachments
223
+
224
+ An action can record advisory delivery metadata for the turn — a drafted email,
225
+ a card, a voice note — with `ctx.attachReply()`. Attachments never change the
226
+ tool output the model sees; they ride alongside the response for your delivery
227
+ layer to render.
228
+
229
+ ```typescript
230
+ draftReply: action({
231
+ description: "Draft an email reply.",
232
+ inputSchema: z.object({ to: z.string(), subject: z.string() }),
233
+ execute: async ({ to, subject }, ctx) => {
234
+ ctx.attachReply({ type: "email_draft", to: [to], subject });
235
+ return { drafted: true };
236
+ }
237
+ });
238
+ ```
239
+
240
+ Read the attachments after the turn from the `onChatResponse()` hook, or from the
241
+ `replyAttachments(requestId?)` getter:
242
+
243
+ ```typescript
244
+ override async onChatResponse(result: ChatResponseResult) {
245
+ for (const attachment of result.attachments ?? []) {
246
+ // attachment.type === "email_draft" | "card" | "voice_note" | custom
247
+ }
248
+ }
249
+ ```
250
+
251
+ Attachments are JSON-normalized and deep-copied on read, capped per turn, and
252
+ discarded if the `execute` that recorded them fails. A ledger replay does not
253
+ re-fire attachments (the side effect already happened), and `attachReply()` is a
254
+ no-op when called from a `permissions`, `approval`, or `idempotencyKey` callback
255
+ — record attachments from `execute`.
256
+
257
+ A built-in `ReplyAttachment` covers `email_draft`, `card`, and `voice_note`; any
258
+ `{ type: string; ... }` shape is allowed for custom delivery. Override
259
+ [`renderAttachment()`](./channels.md#deliver-out-of-band) to turn an attachment
260
+ into a channel notice.
261
+
262
+ ## Reference
263
+
264
+ ### `action(config)`
265
+
266
+ | Field | Type | Required | Default | Description |
267
+ | ----------------- | ------------------------------------------------------------ | -------- | ------------- | --------------------------------------------------------------------------------------- |
268
+ | `description` | `string` | Yes | — | Tool description shown to the model. |
269
+ | `inputSchema` | `FlexibleSchema` (Zod or AI SDK `jsonSchema`) | Yes | — | Validates and types the `execute` input. |
270
+ | `execute` | `(input, ctx) => Output \| Promise<Output>` | Yes | — | The action body. Receives validated input and an `ActionContext`. |
271
+ | `name` | `string` | No | map key | Overrides the tool name. |
272
+ | `idempotencyKey` | `string \| ({ input, ctx }) => string` | No | per tool call | Stable key for ledger replay. Use a domain identifier. |
273
+ | `permissions` | `readonly string[] \| ({ input, ctx }) => readonly string[]` | No | none | Permissions this call requires (see Authorization). |
274
+ | `approval` | `boolean \| ({ input, ctx }) => boolean` | No | none | Gate the call behind a human. |
275
+ | `approvalSummary` | `string` | No | `description` | Human-readable summary in the approval descriptor. |
276
+ | `approvalRisk` | `"low" \| "medium" \| "high"` | No | — | Risk hint in the approval descriptor. |
277
+ | `kind` | `"server" \| "approval-gated" \| "durable-pause"` | No | inferred | `approval-gated` when `approval` is set, else `server`; set `durable-pause` explicitly. |
278
+ | `timeoutMs` | `number` | No | `30000` | Per-action execution timeout (also drives `ctx.signal`). |
279
+
280
+ ### Hooks and methods on the agent
281
+
282
+ | Member | Description |
283
+ | --------------------------------------- | ---------------------------------------------------------------------------------- |
284
+ | `getActions()` | Return the action descriptors to compile into tools. |
285
+ | `authorizeTurn(ctx)` | Decide granted permissions once per turn. Defaults to full grant. |
286
+ | `authorizeAction(ctx)` | Decide authorization per action call. Defaults to checking `authorizeTurn` grants. |
287
+ | `pendingApprovals(executionId?)` | List parked actions and paused Codemode executions awaiting approval. |
288
+ | `approveExecution(executionId)` | Approve a parked execution; runs `execute` and auto-continues the turn. |
289
+ | `rejectExecution(executionId, reason?)` | Reject a parked execution without running it. |
290
+ | `replyAttachments(requestId?)` | Read the advisory attachments recorded during a turn. |
291
+ | `actionLedgerPendingRetryLeaseMs` | Stale-pending reclaim window (default `300000`; `false` to disable). |
292
+
293
+ ## Related
294
+
295
+ - [Tools](./tools.md) — workspace tools, code execution, and extensions.
296
+ - [Human in the Loop](https://github.com/cloudflare/agents/blob/main/docs/agents/human-in-the-loop.md) — the approval flow end to end.
297
+ - [Channels](./channels.md) — deliver attachments and out-of-band notices.
@@ -0,0 +1,185 @@
1
+ # Channels
2
+
3
+ > **Experimental.** The API surface may evolve before Think graduates out of
4
+ > experimental.
5
+
6
+ A channel is a surface a Think agent talks over: the browser WebSocket, a
7
+ messenger webhook (Telegram, Slack, and so on), voice, or your own custom
8
+ transport. Channels generalize [messengers](./messengers.md) into one vocabulary
9
+ so you can apply per-channel policy (a different system prompt, a narrowed tool
10
+ set, a step cap) and deliver out-of-band notices, regardless of the surface a
11
+ turn arrived on.
12
+
13
+ Every Think agent always has an implicit `web` channel (the WebSocket chat your
14
+ browser clients use). You declare additional channels — and override the `web`
15
+ policy — with `configureChannels()`. Messengers returned from `getMessengers()`
16
+ are automatically absorbed as `messenger` channels, so existing messenger apps
17
+ keep working unchanged.
18
+
19
+ ## Configure channels
20
+
21
+ Override `configureChannels()` to return a map of channel id to
22
+ `ChannelDefinition`. The id is how you select the channel on a turn:
23
+
24
+ ```typescript
25
+ import { Think, messengerChannel } from "@cloudflare/think";
26
+ import { telegram } from "@chat-adapter/telegram";
27
+
28
+ export class Assistant extends Think<Env> {
29
+ configureChannels() {
30
+ return {
31
+ // Override policy for the built-in web channel.
32
+ web: {
33
+ kind: "web",
34
+ ingress: { transport: "websocket" },
35
+ instructions: "You are chatting in a web app. Use markdown freely."
36
+ },
37
+ // A voice channel with tighter limits.
38
+ voice: {
39
+ kind: "voice",
40
+ ingress: { transport: "voice" },
41
+ instructions: "Keep replies short and speakable. No markdown.",
42
+ maxTurns: 3
43
+ },
44
+ // A messenger channel (Chat SDK webhook).
45
+ telegram: messengerChannel(
46
+ telegram({
47
+ /* adapter config */
48
+ })
49
+ )
50
+ };
51
+ }
52
+ }
53
+ ```
54
+
55
+ A `ChannelDefinition` has these fields:
56
+
57
+ | Field | Type | Description |
58
+ | -------------- | ------------------------------------------------------------------- | ----------------------------------------------------------------------------------- |
59
+ | `kind` | `"web" \| "messenger" \| "voice" \| "custom"` | The surface category. |
60
+ | `ingress` | `{ transport: "websocket" \| "voice" }` or a webhook messenger spec | How turns arrive. `messengerChannel()` builds the webhook form for you. |
61
+ | `instructions` | `string \| (ctx: ChannelContext) => string \| Promise<string>` | Prepended to the system prompt for turns on this channel. |
62
+ | `tools` | `(all: ToolSet) => ToolSet` | Narrow the assembled tool set for this channel (filter only — it cannot add tools). |
63
+ | `maxTurns` | `number` | Per-channel cap on model steps for a turn. |
64
+ | `capabilities` | `ChannelCapabilities` | Surface capabilities (streaming, message editing). Defaulted for `web`. |
65
+ | `conversation` | messenger conversation mode or resolver | Messenger thread routing (see [Messengers](./messengers.md)). |
66
+ | `delivery` | channel delivery policy | Messenger delivery policy. |
67
+
68
+ Use `messengerChannel()` to wrap a Chat SDK adapter definition as a `kind: "messenger"` channel. Add a `ThinkChannels` return type or `satisfies ThinkChannels` when you want compile-time checks for inline channel maps.
69
+
70
+ ### Channel kinds
71
+
72
+ | Kind | Ingress | Notes |
73
+ | ----------- | --------------------------------- | --------------------------------------------------------------------------------------------- |
74
+ | `web` | `{ transport: "websocket" }` | Always present. Declare it in `configureChannels()` only to set policy; you cannot remove it. |
75
+ | `messenger` | webhook (`messengerChannel(...)`) | Fed into the messenger runtime. Equivalent to a `getMessengers()` entry. |
76
+ | `voice` | `{ transport: "voice" }` | Applies policy and turn context; out-of-band delivery is not yet wired. |
77
+ | `custom` | app-defined | For your own transport. Same delivery limitations as `voice` today. |
78
+
79
+ ## Per-channel policy
80
+
81
+ Channel policy is applied as an **overridable default** before
82
+ [`beforeTurn`](./lifecycle-hooks.md) runs, so a `beforeTurn` override still wins:
83
+
84
+ - `instructions` is prepended to the base system prompt for the turn.
85
+ - `tools` filters the assembled tool set (it can only remove tools — the
86
+ `getTools()` seam adds them).
87
+ - `maxTurns` caps model steps: `beforeTurn`'s `maxSteps` wins, then the channel
88
+ `maxTurns`, then the instance `maxSteps` default.
89
+
90
+ ## Select a channel on a turn
91
+
92
+ Pass `channel` to [`runTurn()`](./index.md#runturn) (or `chat()`) to run a turn
93
+ on a specific channel. The channel id is stamped onto the user message, so a
94
+ continued or recovered turn re-resolves the same channel and re-applies its
95
+ policy:
96
+
97
+ ```typescript
98
+ await this.runTurn({ input: "Read this out loud", channel: "voice" });
99
+ ```
100
+
101
+ Inside a turn, the active channel is available as `this.activeChannel` (a
102
+ `ChannelContext` with `channelId`, `kind`, and messenger details when relevant).
103
+ A turn with no `channel` runs without a channel context and applies no channel
104
+ policy.
105
+
106
+ ## Deliver out of band
107
+
108
+ `deliverNotice()` sends a message to a channel **without** starting a model turn.
109
+ Use it for status updates ("your import finished") or to surface an action's
110
+ [reply attachment](./actions.md#reply-attachments) — it does not run inference,
111
+ does not enter the turn queue, and is therefore safe to call from inside a tool's
112
+ `execute`:
113
+
114
+ ```typescript
115
+ await this.deliverNotice("Your export is ready to download.");
116
+
117
+ await this.deliverNotice("Background research finished.", {
118
+ informModel: true // also record it in the transcript so the next turn knows
119
+ });
120
+ ```
121
+
122
+ ```typescript
123
+ type DeliverNoticeOptions = {
124
+ channel?: string; // defaults to the active turn's channel, else "web"
125
+ informModel?: boolean; // also write to the model-visible transcript (default false)
126
+ kind?: "final" | "interim" | "notice" | "command"; // wire tag (default "notice")
127
+ thread?: string; // required for out-of-turn delivery to a multi-thread messenger
128
+ };
129
+ ```
130
+
131
+ Behavior depends on the target channel:
132
+
133
+ - **`web`** — the notice is always appended to the transcript (that is its only
134
+ render path). `informModel` then only controls the phrasing.
135
+ - **`messenger`** — the notice is posted to the provider. Out of turn, pass
136
+ `thread` to target a conversation. With `informModel: true`, it is also written
137
+ to the transcript.
138
+ - **`voice` / `custom`** — out-of-turn delivery throws, because these surfaces
139
+ have no delivery target yet.
140
+
141
+ Override `renderAttachment(attachment)` to turn an action reply attachment into a
142
+ notice; Think calls it at the end of a turn and delivers the rendered text as a
143
+ trailing `interim` notice. Return `undefined` to skip an attachment type.
144
+
145
+ ## Relationship to messengers
146
+
147
+ `configureChannels()` wraps `getMessengers()` — it does not replace it. Each
148
+ `getMessengers()` entry becomes a `kind: "messenger"` channel, and everything in
149
+ the [Messengers](./messengers.md) guide (Telegram setup, webhook routing,
150
+ conversation targets, delivery and recovery) continues to apply. A channel id in
151
+ `configureChannels()` that collides with a `getMessengers()` id is an error. Keep
152
+ using `getMessengers()` for messenger-only apps; reach for `configureChannels()`
153
+ when you also want `web`/`voice`/`custom` policy or out-of-band notices.
154
+
155
+ ## Observability
156
+
157
+ Channel activity is reported on the `channel` observability channel:
158
+
159
+ ```typescript
160
+ import { subscribe } from "agents/observability";
161
+
162
+ const unsubscribe = subscribe("channel", (event) => {
163
+ // event.type is one of:
164
+ // "channel:resolved" — a turn resolved a registered channel
165
+ // "channel:delivered" — a turn's final reply was delivered
166
+ // "notice:delivered" — deliverNotice() succeeded
167
+ // "notice:failed" — deliverNotice() threw
168
+ });
169
+ ```
170
+
171
+ ## Reference
172
+
173
+ | Member | Description |
174
+ | ------------------------------- | --------------------------------------------------------------------------- |
175
+ | `configureChannels()` | Return the channel map. Defaults to `{}` (the implicit `web` channel only). |
176
+ | `deliverNotice(text, options?)` | Send an out-of-band message to a channel with no model turn. |
177
+ | `activeChannel` | The `ChannelContext` for the in-flight turn, or `undefined`. |
178
+ | `renderAttachment(attachment)` | Map a reply attachment to channel notice text (or `undefined` to skip). |
179
+ | `messengerChannel(definition)` | Wrap a Chat SDK adapter as a `kind: "messenger"` channel. |
180
+
181
+ ## Related
182
+
183
+ - [Messengers](./messengers.md) — Chat SDK webhook setup and delivery in depth.
184
+ - [Actions](./actions.md) — record reply attachments for `renderAttachment()`.
185
+ - [Voice Agents](https://github.com/cloudflare/agents/blob/main/docs/voice/index.md) — real-time speech surfaces.