@cloudflare/think 0.24.0 → 0.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -26
- package/dist/{chat-sdk-BEjKXjCm.js → chat-sdk-4Nu96eDX.js} +375 -256
- package/dist/chat-sdk-4Nu96eDX.js.map +1 -0
- package/dist/extensions/index.d.ts +30 -72
- package/dist/extensions/index.js +45 -47
- package/dist/extensions/index.js.map +1 -1
- package/dist/{fetch-DO3uQ9py.js → fetch-BbYxtlff.js} +10 -2
- package/dist/fetch-BbYxtlff.js.map +1 -0
- package/dist/manager-B3rcb_6p.js +493 -0
- package/dist/manager-B3rcb_6p.js.map +1 -0
- package/dist/manager-CWGumyKi.d.ts +3391 -0
- package/dist/messengers/index.d.ts +54 -66
- package/dist/messengers/index.js +2 -2
- package/dist/messengers/telegram.d.ts +4 -4
- package/dist/messengers/telegram.js +1 -1
- package/dist/think.d.ts +2 -2
- package/dist/think.js +8493 -10759
- package/dist/think.js.map +1 -1
- package/dist/tools/extensions.d.ts +1 -1
- package/dist/tools/extensions.js +1 -1
- package/dist/tools/fetch.js +1 -1
- package/dist/workflows.d.ts +5 -2
- package/docs/actions.md +12 -0
- package/docs/channels.md +10 -4
- package/docs/client-tools.md +57 -27
- package/docs/context.md +92 -0
- package/docs/getting-started.md +2 -2
- package/docs/index.md +109 -49
- package/docs/lifecycle-hooks.md +10 -21
- package/docs/multi-chat.md +5 -5
- package/docs/programmatic-submissions.md +28 -10
- package/docs/sub-agents.md +45 -51
- package/docs/tools.md +31 -3
- package/docs/workflows.md +4 -3
- package/package.json +13 -8
- package/dist/chat-sdk-BEjKXjCm.js.map +0 -1
- package/dist/fetch-DO3uQ9py.js.map +0 -1
- package/dist/hook-proxy-DY2sBNa0.js +0 -117
- package/dist/hook-proxy-DY2sBNa0.js.map +0 -1
- package/dist/index-DIQ9oY1t.d.ts +0 -5864
- package/dist/manager-CtXhU1fK.d.ts +0 -243
- package/dist/manager-sfWIcYJT.js +0 -333
- package/dist/manager-sfWIcYJT.js.map +0 -1
package/docs/sub-agents.md
CHANGED
|
@@ -41,6 +41,8 @@ interface StreamCallback {
|
|
|
41
41
|
|
|
42
42
|
Each call ends with exactly one of `onDone`, `onError`, or `onInterrupted`. If you bridge `chat()` to an HTTP response (for example, a server-sent events stream), close the response in `onInterrupted` as well. Otherwise a stalled turn leaves the response open. The recovered answer is persisted and broadcast to WebSocket clients, not sent to this callback.
|
|
43
43
|
|
|
44
|
+
That holds for a call you do not cancel (see [Cancelling a sub-agent turn](#cancelling-a-sub-agent-turn)), while the parent's isolate lives. `onInterrupted` is optional: a caller that leaves it out hears nothing for an interrupted turn. If the parent restarts in the middle of a call (a deploy or another reset), the call ends with the parent and no callback follows; the child's turn is not ended by it, and the child's own recovery continues it or gives it up as for any interrupted turn. A parent that must know how it ended asks the child after its own restart.
|
|
45
|
+
|
|
44
46
|
### ChatOptions
|
|
45
47
|
|
|
46
48
|
```typescript
|
|
@@ -164,6 +166,10 @@ await child.chat("Long analysis task", callback, {
|
|
|
164
166
|
|
|
165
167
|
When aborted, the partial assistant message is still persisted.
|
|
166
168
|
|
|
169
|
+
A turn you cancel gets no `onDone` and no `onError`, whatever reason the abort carries: `controller.abort()`, `controller.abort("moved on")` and `controller.abort(new Error("moved on"))` all end the turn `aborted`. The promise `chat()` returns resolves, and that is the signal the turn is over. A turn cancelled before it started, while it waited behind another turn, stores nothing, the user message included, and never calls the model.
|
|
170
|
+
|
|
171
|
+
If the chat is cleared while the turn waits or streams, the callback gets `onError("The chat was cleared before the turn finished.")` and nothing of the turn is stored.
|
|
172
|
+
|
|
167
173
|
---
|
|
168
174
|
|
|
169
175
|
## Programmatic Turns with saveMessages
|
|
@@ -177,14 +183,19 @@ async saveMessages(
|
|
|
177
183
|
): Promise<SaveMessagesResult>
|
|
178
184
|
```
|
|
179
185
|
|
|
180
|
-
Returns `{ requestId, status, error? }` where `status` is `"completed"`, `"error"`, `"skipped"`, or `"aborted"`.
|
|
186
|
+
Returns `{ requestId, status, error?, reason? }` where `status` is `"completed"`, `"error"`, `"skipped"`, or `"aborted"`.
|
|
187
|
+
|
|
188
|
+
| `status` | When |
|
|
189
|
+
| ------------- | ------------------------------------------------------------------------------------------------------------ |
|
|
190
|
+
| `"completed"` | Turn ran to completion. |
|
|
191
|
+
| `"error"` | Turn started but the stream reported an error. `error` contains the stream error message when available. |
|
|
192
|
+
| `"skipped"` | The chat was cleared (`chat-clear`) before the turn finished, whether it was waiting or already streaming. |
|
|
193
|
+
| `"aborted"` | The turn did not run to completion. `reason` says why (see below). Partial assistant chunks still persisted. |
|
|
181
194
|
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
| `"skipped"` | Turn invalidated mid-flight (e.g. by `chat-clear`); user message persisted, no model run. |
|
|
187
|
-
| `"aborted"` | Turn cancelled before completion via `options.signal` or `chat-request-cancel`. Partial assistant chunks still persisted. |
|
|
195
|
+
An `aborted` result carries a `reason`:
|
|
196
|
+
|
|
197
|
+
- `"stopped"`: something stopped the turn (`options.signal`, `chat-request-cancel`, `abortAllRequests()`). No reply will follow.
|
|
198
|
+
- `"interrupted"`: the reply was cut off, for example by a stalled or dropped provider stream, and handed to [chat recovery](/agents/api-reference/durable-execution/). Nobody stopped it, and the reply may still arrive, because recovery continues or retries the turn on its own. Do not treat this as a user cancel.
|
|
188
199
|
|
|
189
200
|
### Static messages
|
|
190
201
|
|
|
@@ -215,11 +226,9 @@ await this.saveMessages((current) => [
|
|
|
215
226
|
|
|
216
227
|
### Scheduled responses
|
|
217
228
|
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
each occurrence once per live sub-agent on top of the root. Declare the task on
|
|
222
|
-
the root and let it fan out to sub-agents itself:
|
|
229
|
+
A sub-agent that declares scheduled tasks arms its own, and its root wakes it
|
|
230
|
+
when one is due. For a schedule that runs once and fans out, declare the task
|
|
231
|
+
on the root:
|
|
223
232
|
|
|
224
233
|
```typescript
|
|
225
234
|
export class MyAgent extends Think<Env> {
|
|
@@ -227,7 +236,7 @@ export class MyAgent extends Think<Env> {
|
|
|
227
236
|
/* ... */
|
|
228
237
|
}
|
|
229
238
|
|
|
230
|
-
getScheduledTasks() {
|
|
239
|
+
getScheduledTasks(): ThinkScheduledTasks {
|
|
231
240
|
return {
|
|
232
241
|
dailyReport: {
|
|
233
242
|
schedule: "every day at 09:00",
|
|
@@ -250,25 +259,8 @@ export class MyAgent extends Think<Env> {
|
|
|
250
259
|
}
|
|
251
260
|
```
|
|
252
261
|
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
`getScheduledTasksScope()` and each sub-agent owns an independent schedule:
|
|
256
|
-
|
|
257
|
-
```typescript
|
|
258
|
-
export class PerUserAgent extends Think<Env> {
|
|
259
|
-
getScheduledTasksScope() {
|
|
260
|
-
return "all" as const;
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
async getScheduledTasks() {
|
|
264
|
-
const reminder = await this.getReminderForThisUser();
|
|
265
|
-
return reminder ? { reminder } : {};
|
|
266
|
-
}
|
|
267
|
-
}
|
|
268
|
-
```
|
|
269
|
-
|
|
270
|
-
A sub-agent that declares tasks without opting in logs a warning naming this
|
|
271
|
-
hook, so an inert schedule is never silent.
|
|
262
|
+
For a schedule per user, give each user their own Durable Object and declare
|
|
263
|
+
the task there.
|
|
272
264
|
|
|
273
265
|
### Chaining from onChatResponse
|
|
274
266
|
|
|
@@ -292,10 +284,10 @@ async onChatResponse(result: ChatResponseResult) {
|
|
|
292
284
|
|
|
293
285
|
- the inference loop's signal aborts (the same path `chat-request-cancel` takes);
|
|
294
286
|
- partial chunks already streamed are persisted to the resumable stream;
|
|
295
|
-
- `saveMessages` resolves with `{ status: "aborted" }`;
|
|
287
|
+
- `saveMessages` resolves with `{ status: "aborted", reason: "stopped" }`;
|
|
296
288
|
- `onChatResponse` fires with `status: "aborted"`.
|
|
297
289
|
|
|
298
|
-
If the signal is **already aborted** when `saveMessages` is called, no
|
|
290
|
+
If the signal is **already aborted** when `saveMessages` is called, or aborts while the turn waits behind another turn, the turn does not start. Nothing is stored, the model is not called, and `onChatResponse` does not fire. A stop that lands after the messages are stored and before the model is called leaves the messages in the transcript and also fires no `onChatResponse`. A stop that lands after the reply finished changes nothing: the result is `completed`.
|
|
299
291
|
|
|
300
292
|
```typescript
|
|
301
293
|
class MyAgent extends Think<Env> {
|
|
@@ -384,10 +376,12 @@ protected abortRequest(requestId: string, reason?: unknown): void
|
|
|
384
376
|
protected abortAllRequests(): void
|
|
385
377
|
```
|
|
386
378
|
|
|
387
|
-
- **`abortRequest(id, reason?)`** —
|
|
388
|
-
- **`abortAllRequests()`** — abort every
|
|
379
|
+
- **`abortRequest(id, reason?)`** — stop the request `id`, the same as a client `chat-request-cancel` or `cancelChat(id)`: its turn if one is running or queued, and a chat recovery of it that is scheduled or running.
|
|
380
|
+
- **`abortAllRequests()`** — abort every turn, running or waiting in the queue. A turn that had not started ends `aborted`: it stores nothing and does not call the model. Used by single-purpose sub-agents that don't track ids.
|
|
381
|
+
|
|
382
|
+
A stop ends the turn `aborted` whatever `reason` is. The model call or a hook that waits on the turn's `abortSignal` fails with that reason, and that failure is the stop, not an error: `onChatError` is not called and clients get no error frame.
|
|
389
383
|
|
|
390
|
-
|
|
384
|
+
For a turn that is running, both methods produce the same end state as `chat-request-cancel`: inference loop terminates, partial chunks persist, the turn's `ChatResponseResult` reports `status: "aborted"`. A turn that had not started has no `ChatResponseResult`. Prefer `options.signal` on `saveMessages` / `continueLastTurn` when driving a turn programmatically — it threads the abort intent in from turn start without requiring the caller to know the id.
|
|
391
385
|
|
|
392
386
|
---
|
|
393
387
|
|
|
@@ -402,7 +396,7 @@ Every turn entry path is wrapped in `runFiber`: WebSocket chat, sub-agent `chat(
|
|
|
402
396
|
When an interrupted chat fiber is detected after DO restart, or when the stream-stall watchdog (`chatStreamStallTimeoutMs`) aborts a live turn, Think calls the `onChatRecovery` hook:
|
|
403
397
|
|
|
404
398
|
```typescript
|
|
405
|
-
onChatRecovery(ctx: ChatRecoveryContext): ChatRecoveryOptions | void
|
|
399
|
+
onChatRecovery(ctx: ChatRecoveryContext): Promise<ChatRecoveryOptions | void>
|
|
406
400
|
```
|
|
407
401
|
|
|
408
402
|
### ChatRecoveryContext
|
|
@@ -438,7 +432,7 @@ export class MyAgent extends Think<Env> {
|
|
|
438
432
|
/* ... */
|
|
439
433
|
}
|
|
440
434
|
|
|
441
|
-
onChatRecovery(ctx: ChatRecoveryContext) {
|
|
435
|
+
async onChatRecovery(ctx: ChatRecoveryContext) {
|
|
442
436
|
console.log(
|
|
443
437
|
`Recovering turn ${ctx.requestId}, partial: ${ctx.partialText.length} chars`
|
|
444
438
|
);
|
|
@@ -455,7 +449,7 @@ With `persist: true`, the partial message is saved. With `continue: true`, Think
|
|
|
455
449
|
For pre-stream interruptions, where `ctx.streamId === ""` and `ctx.partialText === ""` but the latest persisted message is still the unanswered user message, Think retries that turn automatically unless `continue` is `false`.
|
|
456
450
|
|
|
457
451
|
```typescript
|
|
458
|
-
onChatRecovery(ctx: ChatRecoveryContext): ChatRecoveryOptions {
|
|
452
|
+
async onChatRecovery(ctx: ChatRecoveryContext): Promise<ChatRecoveryOptions> {
|
|
459
453
|
if (!ctx.streamId && !ctx.partialText) {
|
|
460
454
|
console.log("Recovering a pre-stream interruption");
|
|
461
455
|
}
|
|
@@ -466,7 +460,7 @@ onChatRecovery(ctx: ChatRecoveryContext): ChatRecoveryOptions {
|
|
|
466
460
|
To suppress continuation for turns that have been orphaned too long to safely replay, gate on `ctx.createdAt`:
|
|
467
461
|
|
|
468
462
|
```typescript
|
|
469
|
-
onChatRecovery(ctx: ChatRecoveryContext): ChatRecoveryOptions {
|
|
463
|
+
async onChatRecovery(ctx: ChatRecoveryContext): Promise<ChatRecoveryOptions> {
|
|
470
464
|
if (Date.now() - ctx.createdAt > 2 * 60 * 1000) {
|
|
471
465
|
return { continue: false };
|
|
472
466
|
}
|
|
@@ -502,16 +496,16 @@ export class MyAgent extends Think<Env> {
|
|
|
502
496
|
}
|
|
503
497
|
```
|
|
504
498
|
|
|
505
|
-
| Field | Default | Description
|
|
506
|
-
| ------------------------ | ----------------- |
|
|
507
|
-
| `maxAttempts` | `10` | Attempt cap. Resets on forward progress, so it catches a tight no-progress alarm loop, not a healthy long turn.
|
|
508
|
-
| `stableTimeoutMs` | `10_000` | How long an attempt waits for the isolate to reach stable state before rescheduling.
|
|
509
|
-
| `noProgressTimeoutMs` | `300_000` (5 min) | Primary stuck-turn bound: max time without forward progress before sealing. **Resets on every progress-bearing attempt.**
|
|
510
|
-
| `maxRecoveryWork` | `10000` | Runaway-loop guard: max recovery work since the incident opened before a still-progressing turn is sealed (`work_budget_exceeded`), counted in
|
|
511
|
-
| `maxInterruptedAttempts` | `5` | How many of one turn's attempts may be interrupted (their isolate died before they finished, for example a memory-limit reset or a deploy) before recovery seals with `interrupted_attempts_exceeded`. The original turn counts. Progress never resets it. Replaces `maxOomRetries`, which is still read as `maxOomRetries + 1`.
|
|
512
|
-
| `shouldKeepRecovering` | — | Caller policy consulted from the second attempt onward. Return `false` to stop recovery. The hook point for a token/cost budget (`ctx.work`
|
|
513
|
-
| `terminalMessage` | generic message | Message shown to the user when recovery is given up on.
|
|
514
|
-
| `onExhausted` | — | Called once when recovery is given up on. Inspect `ctx.reason`.
|
|
499
|
+
| Field | Default | Description |
|
|
500
|
+
| ------------------------ | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
501
|
+
| `maxAttempts` | `10` | Attempt cap. Resets on forward progress, so it catches a tight no-progress alarm loop, not a healthy long turn. |
|
|
502
|
+
| `stableTimeoutMs` | `10_000` | How long an attempt waits for the isolate to reach stable state before rescheduling. |
|
|
503
|
+
| `noProgressTimeoutMs` | `300_000` (5 min) | Primary stuck-turn bound: max time without forward progress before sealing. **Resets on every progress-bearing attempt.** |
|
|
504
|
+
| `maxRecoveryWork` | `10000` | Runaway-loop guard: max recovery work since the incident opened before a still-progressing turn is sealed (`work_budget_exceeded`), counted in units of ten stored stream chunks (see [Recovery work units](https://github.com/cloudflare/agents/blob/main/docs/agents/chat-agents.md#recovery-work-units)). A generous finite backstop so a turn that keeps emitting content but never converges cannot loop forever. Raise it, or set `Infinity`, for a very long agentic turn. |
|
|
505
|
+
| `maxInterruptedAttempts` | `5` | How many of one turn's attempts may be interrupted (their isolate died before they finished, for example a memory-limit reset or a deploy) before recovery seals with `interrupted_attempts_exceeded`. The original turn counts. Progress never resets it. Replaces `maxOomRetries`, which is still read as `maxOomRetries + 1`. |
|
|
506
|
+
| `shouldKeepRecovering` | — | Caller policy consulted from the second attempt onward. Return `false` to stop recovery. The hook point for a token/cost budget (`ctx.work` counts stored chunks, not tokens). |
|
|
507
|
+
| `terminalMessage` | generic message | Message shown to the user when recovery is given up on. |
|
|
508
|
+
| `onExhausted` | — | Called once when recovery is given up on. Inspect `ctx.reason`. |
|
|
515
509
|
|
|
516
510
|
`ctx.reason` on the exhausted hook is one of: `no_progress_timeout` (stuck), `max_attempts_exceeded` (no-progress alarm loop), `work_budget_exceeded` (runaway), `interrupted_attempts_exceeded` (the turn's attempts kept dying, for example to memory-limit resets), `out_of_memory` (sealed by the alarm memory-limit breaker), `recovery_aborted` (your `shouldKeepRecovering` returned `false`), or `stable_timeout` (extreme churn). See [`chat-agents.md`](https://github.com/cloudflare/agents/blob/main/docs/agents/chat-agents.md#stream-recovery) for the full shared reference — Think and `@cloudflare/ai-chat` use the same recovery configuration.
|
|
517
511
|
|
package/docs/tools.md
CHANGED
|
@@ -489,7 +489,7 @@ export class MyAgent extends Think<Env> {
|
|
|
489
489
|
manifest: {
|
|
490
490
|
name: "math",
|
|
491
491
|
version: "1.0.0",
|
|
492
|
-
permissions: { network:
|
|
492
|
+
permissions: { network: [] }
|
|
493
493
|
},
|
|
494
494
|
source: `({
|
|
495
495
|
tools: {
|
|
@@ -511,6 +511,8 @@ export class MyAgent extends Think<Env> {
|
|
|
511
511
|
|
|
512
512
|
Extension tools are namespaced — `math` extension with `add` tool becomes `math_add` in the model's tool set.
|
|
513
513
|
|
|
514
|
+
`permissions.network` lists the hosts an extension may fetch: `api.example.com` matches that host only, `*.example.com` its subdomains. An empty list, or none, means no network at all. To enforce the list, re-export `HostBridgeLoopback` from your Worker entry (`export { HostBridgeLoopback } from "@cloudflare/think/extensions";`). Every request the extension makes then goes through it, and a request to an unlisted host or to a private or local address gets a `403`. Without the re-export the list is not enforced: an extension with any host listed can reach every host, and Think logs a warning.
|
|
515
|
+
|
|
514
516
|
### LLM-Driven Extensions
|
|
515
517
|
|
|
516
518
|
Give the model `createExtensionTools` so it can load extensions dynamically:
|
|
@@ -551,7 +553,7 @@ getExtensions() {
|
|
|
551
553
|
manifest: {
|
|
552
554
|
name: "notes",
|
|
553
555
|
version: "1.0.0",
|
|
554
|
-
permissions: { network:
|
|
556
|
+
permissions: { network: [] },
|
|
555
557
|
context: [
|
|
556
558
|
{ label: "scratchpad", description: "Extension scratch space", maxTokens: 500 }
|
|
557
559
|
]
|
|
@@ -561,4 +563,30 @@ getExtensions() {
|
|
|
561
563
|
}
|
|
562
564
|
```
|
|
563
565
|
|
|
564
|
-
The context block is registered as `notes_scratchpad` (namespaced by extension name).
|
|
566
|
+
The context block is registered as `notes_scratchpad` (namespaced by extension name). The extension writes it with `host.setContext()`, which needs the `context.write` permission. A block's `type` is ignored, with a warning.
|
|
567
|
+
|
|
568
|
+
### Upgrading extensions from Think 0.24
|
|
569
|
+
|
|
570
|
+
Extensions installed under Think 0.24 load as before; their source, manifest and context blocks do not change. Two kinds of host code do:
|
|
571
|
+
|
|
572
|
+
- `ExtensionManager.getHookSubscribers()` throws. Think calls each loaded extension's hooks on every turn, so delete the call and the code that called the hooks it returned:
|
|
573
|
+
|
|
574
|
+
```typescript
|
|
575
|
+
// Before (Think 0.24)
|
|
576
|
+
for (const { entrypoint } of manager.getHookSubscribers("beforeTurn")) {
|
|
577
|
+
await entrypoint.hook("beforeTurn", snapshot);
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
// After: nothing. Think runs the extension's beforeTurn hook itself.
|
|
581
|
+
```
|
|
582
|
+
|
|
583
|
+
- `createBridgeProvider`, `ExtensionContextBridge` and `ExtensionWritableBridge` are no longer exported from `@cloudflare/think/extensions`. Think registers an extension's context blocks itself, and the extension's Worker no longer has a method to read a block through. If your code built a context provider over an extension with them, delete it:
|
|
584
|
+
|
|
585
|
+
```typescript
|
|
586
|
+
// Before (Think 0.24)
|
|
587
|
+
import { createBridgeProvider } from "@cloudflare/think/extensions";
|
|
588
|
+
const provider = createBridgeProvider("notes", "readonly", entrypoint);
|
|
589
|
+
|
|
590
|
+
// After: nothing. Declare the block in the extension's manifest
|
|
591
|
+
// (`context`, as above) and Think registers it when the extension loads.
|
|
592
|
+
```
|
package/docs/workflows.md
CHANGED
|
@@ -136,8 +136,9 @@ Object RPC open.
|
|
|
136
136
|
2. Think runs the submitted turn through the normal submission queue.
|
|
137
137
|
3. When the submission reaches `completed`, `error`, `aborted`, or `skipped`,
|
|
138
138
|
Think records a pending workflow notification.
|
|
139
|
-
4. Think
|
|
140
|
-
Object alarms until
|
|
139
|
+
4. Think sends the notification with `sendWorkflowEvent()` at once. A failed
|
|
140
|
+
send is retried from Durable Object alarms with backoff until it succeeds,
|
|
141
|
+
for up to twelve hours.
|
|
141
142
|
5. `step.waitForEvent("<name>:wait", ...)` resumes the Workflow.
|
|
142
143
|
6. `step.prompt()` validates the structured output or throws a typed error.
|
|
143
144
|
|
|
@@ -189,7 +190,7 @@ Use `getScheduledTasks()` for recurring prompt submissions or deterministic
|
|
|
189
190
|
scheduled handlers:
|
|
190
191
|
|
|
191
192
|
```typescript
|
|
192
|
-
getScheduledTasks() {
|
|
193
|
+
getScheduledTasks(): ThinkScheduledTasks {
|
|
193
194
|
return {
|
|
194
195
|
dailySummary: {
|
|
195
196
|
schedule: "every day at 09:00",
|
package/package.json
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
"tools"
|
|
10
10
|
],
|
|
11
11
|
"type": "module",
|
|
12
|
-
"version": "0.
|
|
12
|
+
"version": "0.25.0",
|
|
13
13
|
"license": "MIT",
|
|
14
14
|
"repository": {
|
|
15
15
|
"directory": "packages/think",
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
"dependencies": {
|
|
24
24
|
"@ai-sdk/anthropic": "^4.0.0",
|
|
25
25
|
"@ai-sdk/openai": "^4.0.0",
|
|
26
|
-
"@cloudflare/codemode": "^0.5.
|
|
26
|
+
"@cloudflare/codemode": "^0.5.7",
|
|
27
27
|
"chat": "^4.31.0",
|
|
28
28
|
"workers-ai-provider": "^4.0.0"
|
|
29
29
|
},
|
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
"@types/react": "^19.2.17",
|
|
36
36
|
"@types/react-dom": "^19.2.3",
|
|
37
37
|
"@vitejs/plugin-react": "^6.0.3",
|
|
38
|
-
"agents": "^0.
|
|
38
|
+
"agents": "^0.35.0",
|
|
39
39
|
"ai": "^7.0.0",
|
|
40
40
|
"jsdom": "^29.1.1",
|
|
41
41
|
"react": "^19.2.7",
|
|
@@ -47,7 +47,7 @@
|
|
|
47
47
|
"@ai-sdk/react": "^4.0.0",
|
|
48
48
|
"@chat-adapter/telegram": "^4.29.0",
|
|
49
49
|
"@cloudflare/computer": "^0.10.0",
|
|
50
|
-
"agents": ">=0.
|
|
50
|
+
"agents": ">=0.35.0 <1.0.0",
|
|
51
51
|
"ai": "^7.0.0",
|
|
52
52
|
"react": "^19.0.0",
|
|
53
53
|
"zod": "^4.0.0"
|
|
@@ -116,6 +116,13 @@
|
|
|
116
116
|
],
|
|
117
117
|
"nx": {
|
|
118
118
|
"targets": {
|
|
119
|
+
"test": {
|
|
120
|
+
"inputs": [
|
|
121
|
+
"default",
|
|
122
|
+
"^production",
|
|
123
|
+
"{workspaceRoot}/design/models/traces/**/*"
|
|
124
|
+
]
|
|
125
|
+
},
|
|
119
126
|
"build": {
|
|
120
127
|
"inputs": [
|
|
121
128
|
"production",
|
|
@@ -134,9 +141,7 @@
|
|
|
134
141
|
"build": "tsx ./scripts/build.ts",
|
|
135
142
|
"test": "npm run test:workers && npm run test:react",
|
|
136
143
|
"test:react": "vitest --run -c src/react-tests/vitest.config.ts",
|
|
137
|
-
"test:workers": "vitest --run -c src/tests/vitest.config.ts",
|
|
138
|
-
"test:e2e": "vitest --run -c src/e2e-tests/vitest.config.ts"
|
|
139
|
-
"test:harness": "tsx scripts/harness-compat.ts",
|
|
140
|
-
"test:harness:check": "tsx scripts/harness-compat.ts --check"
|
|
144
|
+
"test:workers": "vitest --run -c src/tests/vitest.config.ts && vitest --run -c src/tests/vitest.replay.config.ts",
|
|
145
|
+
"test:e2e": "vitest --run -c src/e2e-tests/vitest.config.ts"
|
|
141
146
|
}
|
|
142
147
|
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"chat-sdk-BEjKXjCm.js","names":[],"sources":["../src/messengers/events.ts","../src/messengers/delivery.ts","../src/messengers/chat-sdk.ts"],"sourcesContent":["import type { UIMessage } from \"ai\";\n\nexport type MessengerEventKind =\n | \"direct-message\"\n | \"mention\"\n | \"subscribed-message\"\n | \"action\"\n | \"delivery-event\";\n\nexport interface MessengerAuthor {\n fullName?: string;\n isBot?: boolean | \"unknown\";\n isMe?: boolean;\n userId: string;\n userName?: string;\n}\n\nexport interface MessengerAttachment {\n data?: ArrayBuffer;\n fetch?: () => Promise<ArrayBuffer>;\n /**\n * Platform-specific metadata needed to re-fetch the attachment after the\n * event has been serialized (e.g. across a sub-agent Durable Object hop).\n * Adapters store identifiers here — Telegram `fileId`, WhatsApp `mediaId`,\n * etc. — that survive serialization even when `fetch`, `data`, and `raw`\n * cannot, so a downstream agent can reconstruct the download closure.\n */\n fetchMetadata?: Record<string, string>;\n id?: string;\n mediaType?: string;\n name?: string;\n raw?: unknown;\n size?: number;\n text?: string;\n url?: string;\n}\n\nexport interface MessengerThread {\n channelId?: string;\n channelName?: string;\n id: string;\n isDirectMessage: boolean;\n providerThreadId: string;\n title?: string;\n}\n\nexport interface MessengerMessage {\n attachments: MessengerAttachment[];\n author: MessengerAuthor;\n createdAt?: Date;\n id: string;\n isMention?: boolean;\n providerMessageId: string;\n raw?: unknown;\n text: string;\n}\n\nexport interface MessengerAction {\n actionId: string;\n messageId?: string;\n raw?: unknown;\n user?: MessengerAuthor;\n value?: string;\n}\n\nexport interface MessengerCapabilities {\n canEditMessages?: boolean;\n canStream?: boolean;\n maxMessageLength?: number;\n supportsActions?: boolean;\n supportsAttachments?: boolean;\n supportsEphemeral?: boolean;\n}\n\nexport interface MessengerContext {\n action?: MessengerAction;\n author?: MessengerAuthor;\n capabilities: MessengerCapabilities;\n kind: MessengerEventKind;\n message?: MessengerMessage;\n messengerId: string;\n provider: string;\n /**\n * Earlier messages folded into this event, oldest first. A quick run of\n * messages in one thread is answered once, for its newest message (the Chat\n * SDK `burst` concurrency strategy); the rest arrive here. They are part of\n * this turn's input: the model-facing user message renders them before\n * `message`, and their attachments are listed with its own.\n */\n skipped?: MessengerMessage[];\n thread: MessengerThread;\n}\n\nexport interface MessengerEvent extends MessengerContext {\n raw?: unknown;\n}\n\n/**\n * The context persisted on a messenger turn's user message. Built from the\n * serializable form of the event, so raw platform payloads and attachment\n * bytes are never stored and a live turn matches its recovered replay.\n */\nexport function messengerContextFromEvent(\n event: MessengerEvent\n): MessengerContext {\n const serializable = serializableMessengerEvent(event);\n return {\n action: serializable.action,\n author: serializable.message?.author ?? serializable.action?.user,\n capabilities: serializable.capabilities,\n kind: serializable.kind,\n message: serializable.message,\n messengerId: serializable.messengerId,\n provider: serializable.provider,\n skipped: serializable.skipped,\n thread: serializable.thread\n };\n}\n\nexport function serializableMessengerEvent(\n event: MessengerEvent\n): MessengerEvent {\n return {\n capabilities: { ...event.capabilities },\n kind: event.kind,\n messengerId: event.messengerId,\n provider: event.provider,\n thread: { ...event.thread },\n action: event.action\n ? {\n actionId: event.action.actionId,\n messageId: event.action.messageId,\n user: event.action.user ? { ...event.action.user } : undefined,\n value: event.action.value\n }\n : undefined,\n message: event.message\n ? serializableMessengerMessage(event.message)\n : undefined,\n skipped: event.skipped?.map(serializableMessengerMessage)\n };\n}\n\nfunction serializableMessengerMessage(\n message: MessengerMessage\n): MessengerMessage {\n return {\n attachments: message.attachments.map((attachment) => ({\n fetchMetadata: attachment.fetchMetadata\n ? { ...attachment.fetchMetadata }\n : undefined,\n id: attachment.id,\n mediaType: attachment.mediaType,\n name: attachment.name,\n size: attachment.size,\n text: attachment.text,\n url: attachment.url\n })),\n author: { ...message.author },\n createdAt: message.createdAt,\n id: message.id,\n isMention: message.isMention,\n providerMessageId: message.providerMessageId,\n text: message.text\n };\n}\n\n/**\n * Customizes how channel (non-DM) speaker names are prefixed onto model-facing\n * text. By default, speaker labels use `fullName || userName || userId`.\n * Direct messages never get a speaker prefix, regardless of this setting.\n * Return `null`/empty to suppress the prefix for that author.\n */\nexport type ChannelSpeakerLabel = (\n author: MessengerAuthor\n) => string | null | undefined;\n\nexport function resolveChannelSpeakerLabel(\n author: MessengerAuthor | undefined,\n channelSpeakerLabel?: ChannelSpeakerLabel\n): string | undefined {\n if (!author) {\n return undefined;\n }\n\n if (channelSpeakerLabel) {\n const label = channelSpeakerLabel(author);\n return label ? label : undefined;\n }\n\n return author.fullName || author.userName || author.userId || undefined;\n}\n\nexport function toMessengerUserMessage(\n event: MessengerEvent,\n channelSpeakerLabel?: ChannelSpeakerLabel\n): UIMessage {\n const message = event.message;\n if (event.action) {\n const user = event.action.user;\n const displayName = event.thread.isDirectMessage\n ? undefined\n : resolveChannelSpeakerLabel(user, channelSpeakerLabel);\n const details = [\n `Action selected: ${event.action.actionId}`,\n event.action.value ? `Value: ${event.action.value}` : undefined,\n event.action.messageId\n ? `Source message: ${event.action.messageId}`\n : undefined\n ].filter(Boolean);\n const text = displayName\n ? `${displayName}: ${details.join(\"\\n\")}`\n : details.join(\"\\n\");\n\n return {\n id: [\n event.messengerId,\n \"action\",\n event.thread.id,\n event.action.messageId,\n event.action.actionId\n ]\n .filter(Boolean)\n .join(\":\"),\n role: \"user\",\n parts: [{ type: \"text\", text }],\n metadata: {\n messenger: messengerContextFromEvent(event)\n }\n } as UIMessage;\n }\n\n if (!message) {\n throw new Error(`Messenger event ${event.kind} does not contain a message`);\n }\n\n const messages = [...(event.skipped ?? []), message];\n const runs = speakerRuns(messages).map((run) => ({\n author: run[0].author,\n text: run\n .map((entry) => entry.text.trim())\n .filter(Boolean)\n .join(\"\\n\")\n }));\n const content = runs\n .filter((run) => runs.length === 1 || run.text)\n .map((run) => {\n const displayName = event.thread.isDirectMessage\n ? undefined\n : resolveChannelSpeakerLabel(run.author, channelSpeakerLabel);\n return displayName ? `${displayName}: ${run.text}` : run.text;\n })\n .join(\"\\n\");\n const attachmentText = describeAttachments(\n messages.flatMap((entry) => entry.attachments)\n );\n const fullText = [content, attachmentText].filter(Boolean).join(\"\\n\\n\");\n\n return {\n id: `${event.messengerId}:${message.id}`,\n role: \"user\",\n parts: [{ type: \"text\", text: fullText }],\n metadata: {\n messenger: messengerContextFromEvent(event)\n }\n } as UIMessage;\n}\n\n/** Consecutive messages from the same author, in order. */\nfunction speakerRuns(messages: MessengerMessage[]): MessengerMessage[][] {\n const runs: MessengerMessage[][] = [];\n for (const message of messages) {\n const run = runs.at(-1);\n if (run && run[0].author.userId === message.author.userId) {\n run.push(message);\n } else {\n runs.push([message]);\n }\n }\n return runs;\n}\n\nfunction describeAttachments(attachments: MessengerAttachment[]): string {\n if (attachments.length === 0) {\n return \"\";\n }\n\n const lines = attachments.map((attachment, index) => {\n const label = attachment.name || attachment.id || `attachment ${index + 1}`;\n const details = [\n attachment.mediaType,\n attachment.size === undefined ? undefined : `${attachment.size} bytes`,\n attachment.url\n ].filter(Boolean);\n return `- ${label}${details.length ? ` (${details.join(\", \")})` : \"\"}`;\n });\n\n return [\"Attachments:\", ...lines].join(\"\\n\");\n}\n","import { RpcTarget } from \"cloudflare:workers\";\nimport type { FiberContext } from \"agents\";\nimport { TextSegmentJoiner } from \"agents/chat\";\nimport type { UIMessage } from \"ai\";\nimport type {\n ChatInterruptedInfo,\n ChatStartEvent,\n StreamCallback\n} from \"../think\";\nimport type { MessengerEvent } from \"./events\";\nimport { toMessengerUserMessage } from \"./events\";\n\nexport const MESSENGER_REPLY_FIBER_NAME = \"think:messenger-reply\";\n\nexport const EMPTY_MESSENGER_RESPONSE =\n \"I couldn't produce a text response. Please try again.\";\nexport const ERROR_MESSENGER_RESPONSE =\n \"Sorry, I couldn't answer that right now. Please try again.\";\nexport const INTERRUPTED_MESSENGER_RESPONSE =\n \"Sorry, my reply was interrupted. Please send your message again if you'd like me to retry.\";\n\ntype Wake = () => void;\n\nexport interface TextStreamCallbackOptions {\n /**\n * Streamed as the reply when a turn completes without text, so surfaces that\n * wait for the first chunk before posting never post an empty message.\n */\n emptyText?: string;\n onVisibleStart?: () => Promise<void> | void;\n visibleSoftLimit?: number;\n}\n\nexport class TextStreamCallback extends RpcTarget implements StreamCallback {\n private readonly emptyText?: string;\n private readonly onVisibleStart?: () => Promise<void> | void;\n private readonly textSegmentJoiner = new TextSegmentJoiner();\n private readonly visibleChunks: string[] = [];\n private readonly wakeups: Wake[] = [];\n private readonly visibleSoftLimit?: number;\n private chatRequestId?: string;\n private closed = false;\n private interrupted = false;\n private recoveredReplyDelivered = false;\n private error?: Error;\n private text = \"\";\n private visibleClosed = false;\n private visibleLimitReachedValue = false;\n private visibleStarted = false;\n private visibleTextValue = \"\";\n\n constructor(options: TextStreamCallbackOptions = {}) {\n super();\n this.emptyText = options.emptyText;\n this.onVisibleStart = options.onVisibleStart;\n this.visibleSoftLimit = options.visibleSoftLimit;\n }\n\n onStart(event: ChatStartEvent): void {\n this.chatRequestId = event.requestId;\n }\n\n onEvent(json: string): void {\n const chunk = streamChunkFromJson(json);\n if (!chunk) return;\n\n let pushedText = false;\n for (const event of this.textSegmentJoiner.pushChunk(chunk)) {\n if (event.type !== \"text\") continue;\n this.text += event.text;\n this.pushVisibleText(event.text);\n pushedText = true;\n }\n if (pushedText) this.wake();\n }\n\n onDone(): void {\n this.complete();\n }\n\n onError(error: string): void {\n this.fail(new Error(error));\n }\n\n onInterrupted(info?: ChatInterruptedInfo): void {\n // The attempt was interrupted and a continuation (not this callback) owns\n // the real answer. Mark interrupted and stop the visible stream WITHOUT\n // failing it, so delivery does not treat the partial as the final reply\n // (#1644).\n this.interrupted = true;\n this.recoveredReplyDelivered = info?.deliversRecoveredReply === true;\n this.close();\n }\n\n wasInterrupted(): boolean {\n return this.interrupted;\n }\n\n /** Whether the target posts the recovered reply to the thread itself. */\n targetDeliversRecoveredReply(): boolean {\n return this.recoveredReplyDelivered;\n }\n\n /** Ends a completed turn, streaming `emptyText` if it produced no text. */\n complete(): void {\n if (!this.closed && this.emptyText !== undefined && !this.hasText()) {\n this.visibleChunks.push(this.emptyText);\n }\n this.close();\n }\n\n close(): void {\n this.closed = true;\n this.visibleClosed = true;\n this.wake();\n }\n\n fail(error: unknown): void {\n this.error = error instanceof Error ? error : new Error(String(error));\n this.closed = true;\n this.visibleClosed = true;\n this.wake();\n }\n\n hasText(): boolean {\n return this.text.trim().length > 0;\n }\n\n /**\n * Resolves `true` once there is visible text to post, or `false` when the\n * stream ends without any, so a caller can avoid posting an empty reply.\n */\n async hasVisibleOutput(): Promise<boolean> {\n while (true) {\n if (this.visibleChunks.length > 0) return true;\n if (this.error || this.closed || this.visibleClosed) return false;\n await new Promise<void>((resolve) => {\n this.wakeups.push(resolve);\n });\n }\n }\n\n remainingText(): string {\n return this.text.slice(this.visibleTextValue.length);\n }\n\n requestId(): string | undefined {\n return this.chatRequestId;\n }\n\n textSoFar(): string {\n return this.text;\n }\n\n visibleLimitReached(): boolean {\n return this.visibleLimitReachedValue;\n }\n\n visibleText(): string {\n return this.visibleTextValue;\n }\n\n async *stream(): AsyncIterable<string> {\n while (true) {\n const next = this.visibleChunks.shift();\n if (next !== undefined) {\n await this.markVisibleStarted();\n yield next;\n continue;\n }\n\n if (this.error) {\n throw this.error;\n }\n\n if (this.closed || this.visibleClosed) {\n return;\n }\n\n await new Promise<void>((resolve) => {\n this.wakeups.push(resolve);\n });\n }\n }\n\n private pushVisibleText(text: string): void {\n if (this.visibleClosed) {\n return;\n }\n\n if (this.visibleSoftLimit === undefined) {\n this.visibleChunks.push(text);\n this.visibleTextValue += text;\n return;\n }\n\n const remaining = this.visibleSoftLimit - this.visibleTextValue.length;\n if (remaining <= 0) {\n this.visibleClosed = true;\n this.visibleLimitReachedValue = true;\n return;\n }\n\n const visible = text.slice(0, remaining);\n if (visible) {\n this.visibleChunks.push(visible);\n this.visibleTextValue += visible;\n }\n\n if (\n visible.length < text.length ||\n this.visibleTextValue.length >= this.visibleSoftLimit\n ) {\n this.visibleClosed = true;\n this.visibleLimitReachedValue = true;\n }\n }\n\n private wake(): void {\n for (const wake of this.wakeups.splice(0)) {\n wake();\n }\n }\n\n private async markVisibleStarted(): Promise<void> {\n if (this.visibleStarted) {\n return;\n }\n this.visibleStarted = true;\n await this.onVisibleStart?.();\n }\n}\n\nfunction streamChunkFromJson(\n json: string\n): { delta?: unknown; type?: unknown } | null {\n try {\n const chunk: unknown = JSON.parse(json);\n return typeof chunk === \"object\" && chunk !== null\n ? (chunk as { delta?: unknown; type?: unknown })\n : null;\n } catch {\n return null;\n }\n}\n\nexport type MessengerReplyStage = \"accepted\" | \"streaming\" | \"completed\";\n\n/**\n * Explicit delivery lifecycle kind, orthogonal to {@link MessengerReplyStage}.\n * Lets surfaces (voice/CLI especially) tell a final answer from an interim\n * progress note from a deterministic notice from a control command, rather than\n * inferring from text shape.\n */\nexport type DeliveryKind = \"final\" | \"interim\" | \"notice\" | \"command\";\n\n/**\n * Explicit delivery lifecycle tag carried on the wire/snapshot. Orthogonal to,\n * and additive on top of, {@link MessengerReplyStage}: recovery still switches\n * on `stage`, while `kind`/`turnEnded` give non-streaming-text surfaces\n * (voice/CLI) an explicit signal instead of inferring from text shape.\n */\nexport interface DeliveryTag {\n stage: MessengerReplyStage;\n kind: DeliveryKind;\n turnEnded: boolean;\n}\n\n/** Derive a sensible default tag from a reply stage. */\nexport function defaultDeliveryTag(stage: MessengerReplyStage): DeliveryTag {\n return {\n stage,\n kind: stage === \"completed\" ? \"final\" : \"interim\",\n turnEnded: stage === \"completed\"\n };\n}\n\nexport interface MessengerReplySnapshot {\n event: MessengerEvent;\n stage: MessengerReplyStage;\n tag?: DeliveryTag;\n thread?: unknown;\n type: typeof MESSENGER_REPLY_FIBER_NAME;\n}\n\nexport function messengerReplySnapshot(\n stage: MessengerReplyStage,\n event: MessengerEvent,\n thread?: unknown,\n tag?: DeliveryTag\n): MessengerReplySnapshot {\n return {\n event,\n stage,\n tag: tag ?? defaultDeliveryTag(stage),\n thread,\n type: MESSENGER_REPLY_FIBER_NAME\n };\n}\n\nexport function parseMessengerReplySnapshot(\n snapshot: unknown\n): MessengerReplySnapshot | null {\n if (snapshot === null || typeof snapshot !== \"object\") {\n return null;\n }\n\n const candidate = snapshot as Partial<MessengerReplySnapshot>;\n if (\n candidate.type !== MESSENGER_REPLY_FIBER_NAME ||\n (candidate.stage !== \"accepted\" &&\n candidate.stage !== \"streaming\" &&\n candidate.stage !== \"completed\") ||\n candidate.event === undefined\n ) {\n return null;\n }\n\n return {\n event: candidate.event,\n stage: candidate.stage,\n tag: candidate.tag ?? defaultDeliveryTag(candidate.stage),\n thread: candidate.thread,\n type: MESSENGER_REPLY_FIBER_NAME\n };\n}\n\nexport function messengerReplyRecoveryMode(\n snapshot: MessengerReplySnapshot\n): \"answer\" | \"apologize\" | null {\n if (snapshot.stage === \"accepted\") {\n return \"answer\";\n }\n if (snapshot.stage === \"streaming\") {\n return \"apologize\";\n }\n return null;\n}\n\nexport function messengerReplyFailureMode(\n hasStreamedText: boolean,\n completedModelTurn = false,\n expectedDeliveryCompletion = false\n): \"apologize\" | \"error\" | null {\n if (expectedDeliveryCompletion) {\n return null;\n }\n\n if (completedModelTurn) {\n return \"error\";\n }\n\n return hasStreamedText ? \"apologize\" : \"error\";\n}\n\nexport interface MessengerDeliveryTarget {\n cancelChat(\n requestId: string,\n reason?: string\n ): boolean | void | Promise<boolean | void>;\n chat(\n userMessage: string | UIMessage,\n callback: StreamCallback\n ): Promise<void>;\n chatWithMessengerContext?(\n userMessage: string | UIMessage,\n callback: StreamCallback,\n context: MessengerEvent\n ): Promise<void>;\n /**\n * Bind the live delivery surface for the duration of the model turn so the\n * target can reach it from `deliverNotice` while a messenger turn is active.\n * Returns a restore function (save/restore, so nested turns are safe).\n */\n bindActiveDeliverySurface?(surface: MessengerDeliverySurface): () => void;\n}\n\nexport interface MessengerDeliverySurface {\n post(\n message: string | { markdown: string } | AsyncIterable<string>\n ): Promise<unknown>;\n startTyping?(status?: string): Promise<void>;\n}\n\nexport interface MessengerDeliveryPolicy {\n emptyResponseText?: string;\n errorResponseText?: string;\n interruptedResponseText?: string;\n isExpectedDeliveryCompletion?(\n error: unknown,\n callback: TextStreamCallback\n ): boolean;\n splitText?(text: string): string[];\n /**\n * How often, in milliseconds, the typing indicator is re-sent until the\n * reply's first text is posted. Platforms expire the indicator after a few\n * seconds. `0` sends it once.\n * @default 4000\n */\n typingRefreshMs?: number;\n visibleSoftLimit?: number;\n}\n\nconst DEFAULT_TYPING_REFRESH_MS = 4_000;\n/** Longest the reply waits on a typing request an adapter never settles. */\nconst TYPING_SETTLE_TIMEOUT_MS = 1_000;\n\nasync function settleTyping(pending: Promise<void> | undefined) {\n if (!pending) return;\n let timer: ReturnType<typeof setTimeout> | undefined;\n await Promise.race([\n pending,\n new Promise<void>((resolve) => {\n timer = setTimeout(resolve, TYPING_SETTLE_TIMEOUT_MS);\n })\n ]);\n clearTimeout(timer);\n}\n\nexport interface DeliverMessengerReplyOptions {\n checkpoint?: (snapshot: MessengerReplySnapshot) => Promise<void> | void;\n event: MessengerEvent;\n fiber?: FiberContext;\n policy?: MessengerDeliveryPolicy;\n snapshotEvent?: MessengerEvent;\n snapshotThread?: unknown;\n surface: MessengerDeliverySurface;\n target: MessengerDeliveryTarget;\n userMessage?: UIMessage;\n}\n\nexport async function deliverMessengerReply(\n options: DeliverMessengerReplyOptions\n): Promise<void> {\n const emptyResponseText =\n options.policy?.emptyResponseText ?? EMPTY_MESSENGER_RESPONSE;\n const errorResponseText =\n options.policy?.errorResponseText ?? ERROR_MESSENGER_RESPONSE;\n const interruptedResponseText =\n options.policy?.interruptedResponseText ?? INTERRUPTED_MESSENGER_RESPONSE;\n let completedModelTurn = false;\n const snapshotEvent = options.snapshotEvent ?? options.event;\n const checkpoint =\n options.checkpoint ??\n ((snapshot: MessengerReplySnapshot) => {\n options.fiber?.stash(snapshot);\n });\n\n const callback = new TextStreamCallback({\n emptyText: emptyResponseText,\n onVisibleStart: async () => {\n await checkpoint(\n messengerReplySnapshot(\n \"streaming\",\n snapshotEvent,\n options.snapshotThread\n )\n );\n },\n visibleSoftLimit: options.policy?.visibleSoftLimit\n });\n\n // The typing indicator is cosmetic: a failure to show it must not stop the\n // turn. It is re-sent until the reply's first text is posted, one request\n // at a time so a slow one cannot land after the post and re-show it.\n let typingInFlight: Promise<void> | undefined;\n let typingStopped = false;\n const sendTyping = (): Promise<void> => {\n if (typingStopped) return Promise.resolve();\n typingInFlight ??= (async () => {\n try {\n await options.surface.startTyping?.(\"Thinking...\");\n } catch (error) {\n console.warn(\"[Think] Messenger typing indicator failed\", error);\n } finally {\n typingInFlight = undefined;\n }\n })();\n return typingInFlight;\n };\n const typingRefreshMs =\n options.policy?.typingRefreshMs ?? DEFAULT_TYPING_REFRESH_MS;\n let typingTimer: ReturnType<typeof setInterval> | undefined;\n const stopTyping = () => {\n typingStopped = true;\n clearInterval(typingTimer);\n typingTimer = undefined;\n };\n\n // Posting waits for the first visible text: a stream that ends without any\n // (an interrupted turn, a failure) would otherwise post a blank message\n // ahead of the apology on adapters without native streaming.\n const post = callback\n .hasVisibleOutput()\n .then(async (visible) => {\n stopTyping();\n await settleTyping(typingInFlight);\n return visible ? options.surface.post(callback.stream()) : undefined;\n })\n .catch(async (error: unknown) => {\n if (options.policy?.isExpectedDeliveryCompletion?.(error, callback)) {\n return;\n }\n\n const requestId = callback.requestId();\n if (requestId) {\n await Promise.resolve(\n options.target.cancelChat(requestId, toError(error).message)\n ).catch(() => undefined);\n }\n callback.fail(error);\n throw error;\n });\n\n try {\n if (options.surface.startTyping && typingRefreshMs > 0) {\n typingTimer = setInterval(() => void sendTyping(), typingRefreshMs);\n }\n await settleTyping(sendTyping());\n const userMessage =\n options.userMessage ?? toMessengerUserMessage(options.event);\n const restoreSurface = options.target.bindActiveDeliverySurface?.(\n options.surface\n );\n try {\n if (options.target.chatWithMessengerContext) {\n await options.target.chatWithMessengerContext(\n userMessage,\n callback,\n snapshotEvent\n );\n } else {\n await options.target.chat(userMessage, callback);\n }\n } finally {\n restoreSurface?.();\n }\n if (callback.wasInterrupted()) {\n // The model turn was interrupted and routed into bounded recovery; the\n // recovered answer is produced later by a scheduled continuation. Do NOT\n // mark the turn complete or finalize the truncated partial as the reply\n // (#1644). When the target posts the recovered answer (or the apology,\n // if recovery gives up) itself, stay quiet (#2106); otherwise surface\n // the interrupted apology so the user knows to retry.\n callback.close();\n const streamRejected = await post.then(\n () => false,\n () => true\n );\n // Checkpoint before the post: a reset after it must not let recovery\n // (which apologizes for a `streaming` snapshot) post a second apology.\n await checkpoint(\n messengerReplySnapshot(\n \"completed\",\n snapshotEvent,\n options.snapshotThread\n )\n );\n if (callback.targetDeliversRecoveredReply()) {\n // The target subtracts every streamed character from the recovered\n // reply, including any past `visibleSoftLimit` or in a rejected\n // stream post, so post that text now.\n for (const chunk of options.policy?.splitText?.(\n streamRejected ? callback.textSoFar() : callback.remainingText()\n ) ?? []) {\n await options.surface.post(chunk).catch(() => undefined);\n }\n return;\n }\n await options.surface\n .post(interruptedResponseText)\n .catch(() => undefined);\n return;\n }\n completedModelTurn = true;\n callback.complete();\n await post;\n for (const chunk of options.policy?.splitText?.(callback.remainingText()) ??\n []) {\n await options.surface.post(chunk);\n }\n await checkpoint(\n messengerReplySnapshot(\"completed\", snapshotEvent, options.snapshotThread)\n );\n } catch (error) {\n callback.fail(error);\n await post.catch(() => undefined);\n const failureMode = messengerReplyFailureMode(\n callback.hasText(),\n completedModelTurn,\n options.policy?.isExpectedDeliveryCompletion?.(error, callback)\n );\n\n if (failureMode === null) {\n await checkpoint(\n messengerReplySnapshot(\n \"completed\",\n snapshotEvent,\n options.snapshotThread\n )\n );\n return;\n }\n\n await checkpoint(\n messengerReplySnapshot(\"completed\", snapshotEvent, options.snapshotThread)\n );\n if (failureMode === \"apologize\") {\n await options.surface\n .post(interruptedResponseText)\n .catch(() => undefined);\n return;\n }\n\n await options.surface\n .post({\n markdown: errorResponseText\n })\n .catch(() => undefined);\n } finally {\n stopTyping();\n }\n}\n\nfunction toError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error));\n}\n","import type { UIMessage } from \"ai\";\nimport type {\n Adapter,\n ActionEvent as ChatActionEvent,\n Attachment as ChatAttachment,\n Author as ChatAuthor,\n ChatConfig,\n ConcurrencyConfig,\n ConcurrencyStrategy,\n Lock as ChatLock,\n Message as ChatMessage,\n SerializedThread,\n Thread as ChatThread\n} from \"chat\";\nimport { Chat, Message, ThreadImpl } from \"chat\";\nimport type {\n Agent,\n FiberContext,\n FiberRecoveryContext,\n FiberRecoveryResult,\n StartFiberOptions,\n SubAgentClass,\n SubAgentStub\n} from \"agents\";\nimport { createChatSdkState, defaultKeyShard } from \"agents/chat-sdk\";\nimport type { ChatSdkStateAdapterOptions } from \"agents/chat-sdk\";\nimport { ChatSdkStateAgent } from \"agents/chat-sdk\";\nimport type { StreamCallback } from \"../think\";\nimport type {\n MessengerAttachment,\n MessengerAction,\n MessengerAuthor,\n MessengerCapabilities,\n MessengerEvent,\n MessengerEventKind,\n MessengerMessage,\n MessengerThread\n} from \"./events\";\nimport {\n serializableMessengerEvent,\n toMessengerUserMessage,\n type ChannelSpeakerLabel\n} from \"./events\";\nimport {\n deliverMessengerReply,\n EMPTY_MESSENGER_RESPONSE,\n INTERRUPTED_MESSENGER_RESPONSE,\n MESSENGER_REPLY_FIBER_NAME,\n messengerReplyRecoveryMode,\n messengerReplySnapshot,\n parseMessengerReplySnapshot,\n type MessengerReplySnapshot,\n type MessengerDeliveryPolicy,\n type MessengerDeliverySurface,\n type MessengerDeliveryTarget\n} from \"./delivery\";\n\nexport class ThinkMessengerStateAgent extends ChatSdkStateAgent {}\n\n/**\n * Adapters without native streaming would otherwise post `\"...\"` and edit it,\n * and platforms such as Slack keep that first text as the notification\n * preview. Delivery already shows a typing indicator before the reply starts.\n */\nconst FALLBACK_STREAMING_PLACEHOLDER_TEXT = null;\n\n/** The posts that deliver a recovered messenger reply, in order. */\nfunction recoveredReplyPosts(\n definition: { delivery?: MessengerDeliveryPolicy },\n input: {\n outcome: \"completed\" | \"interrupted\";\n text?: string;\n partialPosted?: boolean;\n }\n): Array<string | { markdown: string }> {\n if (input.outcome === \"interrupted\") {\n return [\n definition.delivery?.interruptedResponseText ??\n INTERRUPTED_MESSENGER_RESPONSE\n ];\n }\n const text = input.text?.trim() ? input.text : \"\";\n if (!text) {\n return input.partialPosted\n ? []\n : [definition.delivery?.emptyResponseText ?? EMPTY_MESSENGER_RESPONSE];\n }\n return (definition.delivery?.splitText?.(text) ?? [text]).map((chunk) => ({\n markdown: chunk\n }));\n}\n\nexport type MessengerRespondTo =\n | \"action\"\n | \"direct-message\"\n | \"mention\"\n | \"subscribed-thread\";\n\nexport type MessengerConversationMode = \"self\" | \"thread\";\n\nexport type MessengerConversationTarget =\n | { target: \"self\" }\n | {\n agentClass?: SubAgentClass<Agent & MessengerThinkTarget>;\n name: string;\n target: \"subagent\";\n };\n\nexport type MessengerConversationResolver = (\n event: MessengerEvent\n) => MessengerConversationTarget | Promise<MessengerConversationTarget>;\n\nexport interface MessengerDefinition {\n adapter: Adapter;\n adapterName: string;\n capabilities?: MessengerCapabilities;\n /**\n * Customizes how non-DM channel messages are labelled for the model.\n *\n * Channel (group) messages use `fullName || userName || userId` by default and\n * are rendered as `SpeakerName: text` so the model can attribute multi-user\n * traffic. Direct messages never get a prefix.\n */\n channelSpeakerLabel?: ChannelSpeakerLabel;\n conversation?: MessengerConversationMode | MessengerConversationResolver;\n delivery?: MessengerDeliveryPolicy;\n keyShard?: ChatSdkStateAdapterOptions[\"keyShard\"];\n path?: string;\n provider: string;\n respondTo?: readonly MessengerRespondTo[];\n shardKey?: ChatSdkStateAdapterOptions[\"shardKey\"];\n subscribeOnMention?: boolean;\n toEvent?: (\n input: ChatSdkMessengerEventInput\n ) => MessengerEvent | Promise<MessengerEvent>;\n userName: string;\n verifyWebhook?:\n | false\n | ((request: Request) => boolean | Response | Promise<boolean | Response>);\n}\n\nexport type ThinkMessengers = Record<string, MessengerDefinition>;\n\n/** The Chat SDK `concurrency` setting for a Think agent's messengers. */\nexport type MessengerConcurrency = ConcurrencyStrategy | ConcurrencyConfig;\n\n/**\n * How long a message queued behind a running reply stays answerable. The\n * Chat SDK default (90 seconds) drops follow-ups sent early in a long turn,\n * so Think applies this unless `queueEntryTtlMs` is set explicitly.\n */\nexport const MESSENGER_QUEUE_ENTRY_TTL_MS = 30 * 60 * 1000;\n\nexport const DEFAULT_MESSENGER_CONCURRENCY: MessengerConcurrency = {\n debounceMs: 600,\n queueEntryTtlMs: MESSENGER_QUEUE_ENTRY_TTL_MS,\n strategy: \"burst\"\n};\n\n/** The Chat SDK's thread lock TTL (`DEFAULT_LOCK_TTL_MS`). */\nconst CHAT_SDK_LOCK_TTL_MS = 30_000;\n\n/**\n * Private `Chat` methods the post-recovery drain reuses so a stranded queue\n * is dispatched exactly as the SDK would (lock scope, expiry, `skipped`).\n * Feature-checked at runtime: a `chat` release without them skips the drain.\n */\ninterface ChatSdkQueueInternals {\n getLockKey(adapter: Adapter, threadId: string): Promise<string>;\n drainQueue(\n lock: ChatLock,\n adapter: Adapter,\n threadId: string,\n lockKey: string\n ): Promise<void>;\n}\n\n/** Fill in Think's queue-entry TTL where the setting leaves it unset. */\nexport function withMessengerQueueTtl(\n concurrency: MessengerConcurrency\n): MessengerConcurrency {\n if (typeof concurrency === \"string\") {\n return {\n queueEntryTtlMs: MESSENGER_QUEUE_ENTRY_TTL_MS,\n strategy: concurrency\n };\n }\n return {\n ...concurrency,\n queueEntryTtlMs: concurrency.queueEntryTtlMs ?? MESSENGER_QUEUE_ENTRY_TTL_MS\n };\n}\n\nexport interface NormalizedMessengerDefinition extends MessengerDefinition {\n id: string;\n path: string;\n respondTo: readonly MessengerRespondTo[];\n subscribeOnMention: boolean;\n verifyWebhook:\n | false\n | ((request: Request) => boolean | Response | Promise<boolean | Response>);\n}\n\nexport interface ChatSdkMessengerOptions extends Omit<\n MessengerDefinition,\n \"adapterName\"\n> {\n adapterName?: string;\n}\n\nexport interface ChatSdkMessengerEventInput {\n action?: ChatActionEvent;\n eventKind: MessengerEventKind;\n message?: ChatMessage;\n raw?: unknown;\n /**\n * Earlier messages the Chat SDK's concurrency strategy folded into this one,\n * oldest first (`MessageContext.skipped`). The runtime's `burst` strategy\n * answers only the newest message of a quick run and reports the rest here.\n * {@link defaultChatSdkEvent} carries them on the event's `skipped` so they\n * reach the model; a custom `toEvent` that ignores them drops them.\n */\n skipped?: readonly ChatMessage[];\n thread: ChatThread;\n}\n\nexport interface MessengerThinkTarget {\n cancelChat(\n requestId: string,\n reason?: string\n ): boolean | void | Promise<boolean | void>;\n chat(\n userMessage: string | UIMessage,\n callback: StreamCallback\n ): Promise<void>;\n chatWithMessengerContext?(\n userMessage: string | UIMessage,\n callback: StreamCallback,\n context: MessengerEvent\n ): Promise<void>;\n}\n\nexport interface MessengerThinkHost extends MessengerThinkTarget {\n constructor: { name: string };\n name: string;\n parentPath: ReadonlyArray<{ className: string; name: string }>;\n startFiber(\n name: string,\n fn: (ctx: FiberContext) => Promise<void>,\n options?: StartFiberOptions\n ): Promise<MessengerFiberStartResult>;\n resolveFiber(id: string, result: FiberRecoveryResult): Promise<boolean>;\n /**\n * Durably accept one messenger reply run on the host's Tasks capability\n * and execute it inline while this isolate lives. The same idempotency key\n * joins the existing run (`accepted: false`).\n */\n _runMessengerReplyTask(input: {\n nonce: string;\n idempotencyKey: string;\n metadata: Record<string, unknown>;\n }): Promise<{ accepted: boolean }>;\n subAgent<T extends Agent>(\n agentClass: SubAgentClass<T>,\n name: string\n ): Promise<SubAgentStub<T>>;\n /** Keep the host alive while background messenger work runs. */\n keepAliveWhile?<T>(fn: () => Promise<T>): Promise<T>;\n}\n\nexport interface MessengerFiberStartResult {\n accepted: boolean;\n fiberId: string;\n snapshot?: unknown;\n status: string;\n}\n\nexport function chatSdkMessenger(\n options: ChatSdkMessengerOptions\n): MessengerDefinition {\n return {\n ...options,\n adapterName: options.adapterName ?? options.provider\n };\n}\n\nexport class ThinkMessengerRuntime {\n private chat?: Chat<Record<string, Adapter>>;\n /**\n * Live reply closures keyed by run nonce. A closure exists only in the\n * isolate that accepted the webhook; an interrupted reply is recovered on\n * wake through {@link handleFiberRecovery} from its persisted snapshot.\n */\n private readonly liveReplies = new Map<\n string,\n {\n definition: NormalizedMessengerDefinition;\n event: MessengerEvent;\n thread: ChatThread;\n snapshotEvent: ReturnType<typeof serializableMessengerEvent>;\n snapshotThread: ReturnType<ChatThread[\"toJSON\"]>;\n }\n >();\n private readonly definitionsByAdapterName = new Map<\n string,\n NormalizedMessengerDefinition\n >();\n private readonly definitionsById = new Map<\n string,\n NormalizedMessengerDefinition\n >();\n private readonly definitions: NormalizedMessengerDefinition[];\n\n private readonly concurrency: MessengerConcurrency;\n\n constructor(\n definitions: ThinkMessengers,\n private readonly host: MessengerThinkHost,\n options?: { concurrency?: MessengerConcurrency }\n ) {\n this.concurrency = withMessengerQueueTtl(\n options?.concurrency ?? DEFAULT_MESSENGER_CONCURRENCY\n );\n this.definitions = normalizeMessengers(definitions);\n for (const definition of this.definitions) {\n this.definitionsByAdapterName.set(definition.adapterName, definition);\n this.definitionsById.set(definition.id, definition);\n }\n }\n\n get size(): number {\n return this.definitions.length;\n }\n\n initialize(): void {\n if (this.host.parentPath.length > 0) {\n return;\n }\n\n this.chat = this.createChat();\n }\n\n async handleRequest(request: Request): Promise<Response | undefined> {\n if (this.host.parentPath.length > 0) {\n return undefined;\n }\n\n const url = new URL(request.url);\n const definition = this.definitions.find(\n (candidate) => candidate.path === url.pathname\n );\n if (!definition) {\n return undefined;\n }\n\n if (request.method !== \"POST\") {\n return new Response(\"Method not allowed\", { status: 405 });\n }\n\n if (definition.verifyWebhook !== false) {\n const verification = await definition.verifyWebhook(\n request.clone() as Request\n );\n if (verification instanceof Response) {\n return verification;\n }\n if (verification === false) {\n return new Response(\"Unauthorized\", { status: 401 });\n }\n }\n\n const chat = this.chat ?? this.createChat();\n this.chat = chat;\n return chat.webhooks[definition.adapterName](request);\n }\n\n async handleFiberRecovery(\n ctx: FiberRecoveryContext,\n options?: {\n /**\n * Capability-run recovery: persist re-entry checkpoints here instead\n * of the legacy managed-fiber ledger, whose row does not exist for\n * runs on the Tasks capability. Terminal settlement is implied by the\n * caller's recovery decision, so the legacy `resolveFiber` completion\n * calls are skipped when this hook is present.\n */\n persistRecoverySnapshot?: (\n snapshot: ReturnType<typeof messengerReplySnapshot>\n ) => Promise<void> | void;\n /**\n * Whether the caller replays this recovery after it throws `error`.\n * Messages queued behind the reply are drained only once it settles,\n * so they are never answered ahead of it. Default: no replay.\n */\n retriesAfter?: (error: unknown) => boolean;\n }\n ): Promise<boolean> {\n if (ctx.name !== MESSENGER_REPLY_FIBER_NAME) {\n return false;\n }\n\n const snapshot = parseMessengerReplySnapshot(ctx.snapshot);\n if (!snapshot) {\n return false;\n }\n\n const definition = this.definitionsById.get(snapshot.event.messengerId);\n if (!definition) {\n throw new Error(\n `No messenger definition found for recovered messenger ${snapshot.event.messengerId}`\n );\n }\n\n const thread = this.reviveThread(definition, snapshot.thread);\n let handled: boolean;\n try {\n handled = await this.recoverReply(\n ctx,\n definition,\n thread,\n snapshot,\n options\n );\n } catch (error) {\n if (!options?.retriesAfter?.(error)) {\n this.drainQueuedMessagesInBackground(definition, thread.id);\n }\n throw error;\n }\n this.drainQueuedMessagesInBackground(definition, thread.id);\n return handled;\n }\n\n private async recoverReply(\n ctx: FiberRecoveryContext,\n definition: NormalizedMessengerDefinition,\n thread: ChatThread,\n snapshot: MessengerReplySnapshot,\n options:\n | {\n persistRecoverySnapshot?: (\n snapshot: ReturnType<typeof messengerReplySnapshot>\n ) => Promise<void> | void;\n }\n | undefined\n ): Promise<boolean> {\n const mode = messengerReplyRecoveryMode(snapshot);\n\n if (mode === \"answer\") {\n await this.answer(\n definition,\n snapshot.event,\n thread,\n undefined,\n snapshot.event,\n async (nextSnapshot) => {\n if (options?.persistRecoverySnapshot) {\n await options.persistRecoverySnapshot(nextSnapshot);\n return;\n }\n await this.host.resolveFiber(ctx.id, {\n snapshot: nextSnapshot,\n status:\n nextSnapshot.stage === \"completed\" ? \"completed\" : \"interrupted\"\n });\n }\n );\n return true;\n }\n\n if (mode === \"apologize\") {\n await thread.post(\n definition.delivery?.interruptedResponseText ??\n INTERRUPTED_MESSENGER_RESPONSE\n );\n if (!options?.persistRecoverySnapshot) {\n await this.host.resolveFiber(ctx.id, { status: \"completed\" });\n }\n return true;\n }\n\n if (!options?.persistRecoverySnapshot) {\n await this.host.resolveFiber(ctx.id, { status: \"completed\" });\n }\n return true;\n }\n\n /**\n * Messages queued behind a reply are drained only by the Chat SDK handler\n * holding the thread lock. When the isolate running that reply dies, the\n * queue is stranded until another message arrives, so recovery drains it:\n * once the dead holder's lock expires, take the lock and hand the queue to\n * the SDK's own drain. A live holder drains the queue itself, which ends\n * the wait.\n */\n private drainQueuedMessagesInBackground(\n definition: NormalizedMessengerDefinition,\n threadId: string\n ): void {\n const drain = () => this.drainQueuedMessages(definition, threadId);\n const running = this.host.keepAliveWhile?.(drain) ?? drain();\n void running.catch((error: unknown) => {\n console.error(\n `[Think] Failed to drain messages queued on ${threadId} after recovery`,\n error\n );\n });\n }\n\n private async drainQueuedMessages(\n definition: NormalizedMessengerDefinition,\n threadId: string\n ): Promise<void> {\n const chat = (this.chat ??= this.createChat());\n const internals = chat as unknown as Partial<ChatSdkQueueInternals>;\n if (\n typeof internals.getLockKey !== \"function\" ||\n typeof internals.drainQueue !== \"function\"\n ) {\n return;\n }\n await chat.initialize();\n const state = chat.getState();\n const lockKey = await internals.getLockKey.call(\n chat,\n definition.adapter,\n threadId\n );\n const deadline = Date.now() + CHAT_SDK_LOCK_TTL_MS + 5_000;\n while ((await state.queueDepth(lockKey)) > 0) {\n const lock = await state.acquireLock(lockKey, CHAT_SDK_LOCK_TTL_MS);\n if (lock) {\n try {\n await internals.drainQueue.call(\n chat,\n lock,\n definition.adapter,\n threadId,\n lockKey\n );\n } finally {\n await state.releaseLock(lock);\n }\n return;\n }\n if (Date.now() >= deadline) return;\n await new Promise((resolve) => setTimeout(resolve, 1_000));\n }\n }\n\n private createChat(): Chat<Record<string, Adapter>> {\n const adapters = Object.fromEntries(\n this.definitions.map((definition) => [\n definition.adapterName,\n definition.adapter\n ])\n ) as Record<string, Adapter>;\n const chat = new Chat({\n adapters,\n concurrency: this.concurrency,\n fallbackStreamingPlaceholderText: FALLBACK_STREAMING_PLACEHOLDER_TEXT,\n state: createChatSdkState({\n agent: ThinkMessengerStateAgent,\n keyShard: (key) => this.shardStateKey(key),\n // The Chat SDK never extends its 30 second thread lock while a\n // handler runs; a Think turn often takes longer.\n lockHeartbeat: true,\n parent: this.host as unknown as ChatSdkStateAdapterOptions[\"parent\"],\n shardKey: (threadId) => this.shardThread(threadId)\n }),\n userName: this.definitions[0]?.userName ?? \"think\"\n } satisfies ChatConfig<Record<string, Adapter>>);\n\n chat.onDirectMessage(async (thread, message, _channel, context) => {\n const definition = this.definitionForThread(thread);\n if (!definition) return;\n if (definition.respondTo.includes(\"direct-message\")) {\n await this.enqueueReply(\n definition,\n await this.toEvent(definition, {\n eventKind: \"direct-message\",\n message,\n skipped: context?.skipped,\n thread\n }),\n thread\n );\n }\n });\n\n chat.onNewMention(async (thread, message, context) => {\n const definition = this.definitionForThread(thread);\n if (!definition) return;\n if (definition.subscribeOnMention) {\n await thread.subscribe();\n }\n if (definition.respondTo.includes(\"mention\")) {\n await this.enqueueReply(\n definition,\n await this.toEvent(definition, {\n eventKind: \"mention\",\n message,\n skipped: context?.skipped,\n thread\n }),\n thread\n );\n }\n });\n\n // A burst is routed on its newest message only. When an earlier message\n // in an unsubscribed thread mentioned the bot, answer the burst as that\n // mention instead of letting it fall through unanswered.\n chat.onNewMessage(/[\\s\\S]*/, async (thread, message, context) => {\n const definition = this.definitionForThread(thread);\n if (!definition || !definition.respondTo.includes(\"mention\")) return;\n if (!context?.skipped.some((skipped) => mentionsBot(definition, skipped)))\n return;\n if (definition.subscribeOnMention) {\n await thread.subscribe();\n }\n await this.enqueueReply(\n definition,\n await this.toEvent(definition, {\n eventKind: \"mention\",\n message,\n skipped: context.skipped,\n thread\n }),\n thread\n );\n });\n\n chat.onSubscribedMessage(async (thread, message, context) => {\n const definition = this.definitionForThread(thread);\n if (!definition) return;\n const mentioned =\n message.isMention ||\n (context?.skipped.some((skipped) => mentionsBot(definition, skipped)) ??\n false);\n if (\n definition.respondTo.includes(\"subscribed-thread\") ||\n (mentioned && definition.respondTo.includes(\"mention\"))\n ) {\n await this.enqueueReply(\n definition,\n await this.toEvent(definition, {\n eventKind: mentioned ? \"mention\" : \"subscribed-message\",\n message,\n skipped: context?.skipped,\n thread\n }),\n thread\n );\n }\n });\n\n chat.onAction(async (event) => {\n if (!event.thread) return;\n const thread = event.thread as ChatThread;\n const definition = this.definitionForThread(thread);\n if (!definition) return;\n if (definition.respondTo.includes(\"action\")) {\n await this.enqueueReply(\n definition,\n await this.toEvent(definition, {\n action: event,\n eventKind: \"action\",\n raw: event.raw,\n thread\n }),\n thread\n );\n }\n });\n\n return chat.registerSingleton();\n }\n\n /** Whether this isolate still holds the live closure for one reply. */\n hasLiveReply(nonce: string): boolean {\n return this.liveReplies.has(nonce);\n }\n\n /**\n * The durable \"accepted\" snapshot for one live reply, when its closure is\n * still held. The task definition persists this BEFORE delivery begins:\n * an isolate lost mid-answer recovers through it, and without it replay\n * could neither deliver nor apologize.\n */\n initialReplySnapshot(nonce: string): unknown | undefined {\n const entry = this.liveReplies.get(nonce);\n if (!entry) return undefined;\n return messengerReplySnapshot(\n \"accepted\",\n entry.snapshotEvent,\n entry.snapshotThread\n );\n }\n\n /** Execute one live (same-isolate) reply under the given fiber context. */\n async executeLiveReply(nonce: string, fiber: FiberContext): Promise<void> {\n const entry = this.liveReplies.get(nonce);\n if (!entry) {\n throw new Error(\n \"Messenger reply closure is no longer available in this isolate\"\n );\n }\n await this.answer(\n entry.definition,\n entry.event,\n entry.thread,\n fiber,\n entry.snapshotEvent\n );\n }\n\n private async enqueueReply(\n definition: NormalizedMessengerDefinition,\n event: MessengerEvent,\n thread: ChatThread\n ): Promise<void> {\n const snapshotEvent = serializableMessengerEvent(event);\n const snapshotThread = thread.toJSON();\n const nonce = crypto.randomUUID();\n this.liveReplies.set(nonce, {\n definition,\n event,\n thread,\n snapshotEvent,\n snapshotThread\n });\n try {\n // Durable acceptance plus inline execution on the host's Fibers\n // capability. A duplicate webhook joins the existing run\n // (`accepted: false`) and returns; an interrupted run is recovered on\n // wake by the reply definition's `recover` callback, which replaces\n // the legacy join-time recovery branch.\n await this.host._runMessengerReplyTask({\n nonce,\n idempotencyKey: idempotencyKeyForEvent(event),\n metadata: {\n messengerId: event.messengerId,\n messageId: event.message?.id,\n provider: event.provider,\n threadId: event.thread.id\n }\n });\n } finally {\n this.liveReplies.delete(nonce);\n }\n }\n\n private async answer(\n definition: NormalizedMessengerDefinition,\n event: MessengerEvent,\n thread: ChatThread,\n fiber?: FiberContext,\n snapshotEvent = serializableMessengerEvent(event),\n checkpoint?: (\n snapshot: ReturnType<typeof messengerReplySnapshot>\n ) => Promise<void> | void\n ): Promise<void> {\n const target = await this.resolveTarget(definition, event);\n await deliverMessengerReply({\n event,\n checkpoint,\n fiber,\n policy: definition.delivery,\n snapshotEvent,\n snapshotThread: thread.toJSON(),\n surface: thread satisfies MessengerDeliverySurface,\n target,\n userMessage: toMessengerUserMessage(event, definition.channelSpeakerLabel)\n });\n }\n\n /**\n * Resolve a live delivery surface for an out-of-turn notice (e.g. a scheduled\n * task or webhook handler calling `deliverNotice`). Uses `chat.thread(id)` —\n * the chat SDK's supported \"post from outside a webhook\" primitive, which\n * returns a postable {@link ChatThread} and infers the adapter from the\n * thread-id prefix, so it works for every chat-sdk adapter with no per-adapter\n * wiring. Returns `undefined` when the channel is unregistered or no `threadId`\n * was supplied so the caller can fail fast.\n */\n async resolveDeliverySurface(\n channelId: string,\n threadId?: string\n ): Promise<MessengerDeliverySurface | undefined> {\n const definition = this.definitionsById.get(channelId);\n if (!definition || !threadId) {\n return undefined;\n }\n const chat = this.chat ?? this.createChat();\n return chat.thread(threadId) satisfies MessengerDeliverySurface;\n }\n\n /**\n * Post what chat recovery produced for an interrupted messenger turn: the\n * text the thread has not seen yet, or the interrupted apology when\n * recovery gave up. The reply may span several posts; this posts only post\n * number `chunk` (skipped when out of range) and returns how many there\n * are, so the caller can checkpoint between posts.\n */\n async deliverRecoveredReply(input: {\n messengerId: string;\n threadId: string;\n outcome: \"completed\" | \"interrupted\";\n text?: string;\n partialPosted?: boolean;\n chunk: number;\n }): Promise<{ chunks: number }> {\n const definition = this.definitionsById.get(input.messengerId);\n const surface = await this.resolveDeliverySurface(\n input.messengerId,\n input.threadId\n );\n if (!definition || !surface) {\n throw new Error(\n `No messenger delivery surface for ${input.messengerId} thread ${input.threadId}`\n );\n }\n const posts = recoveredReplyPosts(definition, input);\n const post = posts[input.chunk];\n if (post !== undefined) await surface.post(post);\n return { chunks: posts.length };\n }\n\n private async resolveTarget(\n definition: NormalizedMessengerDefinition,\n event: MessengerEvent\n ): Promise<MessengerDeliveryTarget> {\n const conversation = definition.conversation ?? \"thread\";\n const target =\n typeof conversation === \"function\"\n ? await conversation(event)\n : conversation === \"self\"\n ? { target: \"self\" as const }\n : {\n name: defaultConversationName(event),\n target: \"subagent\" as const\n };\n\n if (target.target === \"self\") {\n return this.host;\n }\n\n const agentClass =\n target.agentClass ??\n (this.host.constructor as unknown as SubAgentClass<\n Agent & MessengerThinkTarget\n >);\n const stub = (await this.host.subAgent(\n agentClass,\n target.name\n )) as unknown as Required<MessengerThinkTarget>;\n // A live thread cannot cross the sub-agent RPC boundary, so the stub's\n // `bindActiveDeliverySurface` must not be offered to delivery.\n return {\n cancelChat: (requestId, reason) => stub.cancelChat(requestId, reason),\n chat: (userMessage, callback) => stub.chat(userMessage, callback),\n chatWithMessengerContext: (userMessage, callback, context) =>\n stub.chatWithMessengerContext(userMessage, callback, context)\n };\n }\n\n private definitionForThread(\n thread: ChatThread\n ): NormalizedMessengerDefinition | undefined {\n return (\n this.definitionsByAdapterName.get(thread.toJSON().adapterName) ??\n this.definitionForThreadId(thread.id) ??\n this.definitionForThreadId(thread.channelId)\n );\n }\n\n private definitionForThreadId(\n threadId: string | undefined\n ): NormalizedMessengerDefinition | undefined {\n if (!threadId) {\n return undefined;\n }\n\n if (this.definitions.length === 1) {\n return this.definitions[0];\n }\n\n return this.definitions.find(\n (definition) =>\n threadId === definition.id ||\n threadId.startsWith(`${definition.id}:`) ||\n (this.hasUniqueProvider(definition.provider) &&\n (threadId === definition.provider ||\n threadId.startsWith(`${definition.provider}:`))) ||\n threadId === definition.adapterName ||\n threadId.startsWith(`${definition.adapterName}:`)\n );\n }\n\n private hasUniqueProvider(provider: string): boolean {\n return (\n this.definitions.filter((definition) => definition.provider === provider)\n .length === 1\n );\n }\n\n private shardThread(threadId: string): string {\n const definition = this.definitionForThreadId(threadId);\n return (\n definition?.shardKey?.(threadId) ||\n threadId.split(\":\").slice(0, 2).join(\":\") ||\n \"default\"\n );\n }\n\n private shardStateKey(key: string): string | undefined {\n for (const definition of this.definitions) {\n const shard = definition.keyShard?.(key);\n if (shard) {\n return shard;\n }\n }\n\n return defaultKeyShard(key, (threadId) => this.shardThread(threadId));\n }\n\n /**\n * `ThreadImpl.fromJSON` (what `chat.reviver()` calls) builds the thread\n * without the Chat's streaming config, so a recovered reply would fall back to\n * the `\"...\"` placeholder. Rebuild it from the same fields with that config.\n */\n private reviveThread(\n definition: NormalizedMessengerDefinition,\n value: unknown\n ): ChatThread {\n if (value === undefined) {\n throw new Error(\n \"Messenger recovery snapshot is missing chat object data\"\n );\n }\n const chat = (this.chat ??= this.createChat());\n const json = JSON.parse(JSON.stringify(value)) as SerializedThread;\n // Bound explicitly: a lazy thread resolves its adapter from the\n // module-global Chat singleton on first use, which another runtime in\n // this isolate can replace while recovery awaits.\n return new ThreadImpl({\n adapter: definition.adapter,\n stateAdapter: chat.getState(),\n channelId: json.channelId,\n channelVisibility: json.channelVisibility,\n currentMessage: json.currentMessage\n ? Message.fromJSON(json.currentMessage)\n : undefined,\n fallbackStreamingPlaceholderText: FALLBACK_STREAMING_PLACEHOLDER_TEXT,\n id: json.id,\n isDM: json.isDM\n });\n }\n\n private async toEvent(\n definition: NormalizedMessengerDefinition,\n input: ChatSdkMessengerEventInput\n ): Promise<MessengerEvent> {\n return (\n (await definition.toEvent?.(input)) ??\n defaultChatSdkEvent(definition, input)\n );\n }\n}\n\nexport function normalizeMessengers(\n messengers: ThinkMessengers\n): NormalizedMessengerDefinition[] {\n const ids = new Set<string>();\n const adapterNames = new Set<string>();\n const paths = new Set<string>();\n const normalized: NormalizedMessengerDefinition[] = [];\n\n for (const [id, definition] of Object.entries(messengers)) {\n if (ids.has(id)) {\n throw new Error(`Duplicate messenger id: ${id}`);\n }\n ids.add(id);\n\n const path = definition.path ?? `/messengers/${id}/webhook`;\n validatePath(path, id);\n if (definition.verifyWebhook === undefined) {\n throw new Error(\n `Messenger ${id} requires verifyWebhook, or verifyWebhook: false to opt out explicitly`\n );\n }\n const verifyWebhook = definition.verifyWebhook;\n if (adapterNames.has(definition.adapterName)) {\n throw new Error(\n `Duplicate messenger adapter name: ${definition.adapterName}`\n );\n }\n adapterNames.add(definition.adapterName);\n if (paths.has(path)) {\n throw new Error(`Duplicate messenger path: ${path}`);\n }\n paths.add(path);\n\n normalized.push({\n ...definition,\n id,\n path,\n respondTo: definition.respondTo ?? [\"direct-message\", \"mention\"],\n subscribeOnMention: definition.subscribeOnMention ?? true,\n verifyWebhook\n });\n }\n\n return normalized;\n}\n\nexport function defaultConversationName(event: MessengerEvent): string {\n return `messenger:${event.messengerId}:${stableNamePart(event.thread.id)}`;\n}\n\nexport function idempotencyKeyForEvent(event: MessengerEvent): string {\n return [\n \"messenger\",\n event.messengerId,\n \"message\",\n event.thread.id,\n idempotencyEventPart(event)\n ].join(\":\");\n}\n\nfunction idempotencyEventPart(event: MessengerEvent): string {\n if (event.message) {\n return event.message.id;\n }\n\n if (event.action) {\n return [\n \"action\",\n stableNamePart(event.action.messageId ?? \"unknown-message\"),\n stableNamePart(event.action.actionId),\n stableNamePart(event.action.user?.userId ?? \"unknown-user\"),\n stableNamePart(event.action.value ?? \"no-value\")\n ].join(\":\");\n }\n\n return event.kind;\n}\n\nexport function defaultChatSdkEvent(\n definition: NormalizedMessengerDefinition,\n input: ChatSdkMessengerEventInput\n): MessengerEvent {\n const convert = (chatMessage: ChatMessage): MessengerMessage => {\n const message = toMessengerMessage(chatMessage);\n message.text = resolveSelfMention(\n message.text,\n definition.adapter.botUserId,\n definition.userName\n );\n return message;\n };\n const skipped = input.skipped?.length\n ? input.skipped.map(convert)\n : undefined;\n return {\n capabilities: definition.capabilities ?? {},\n action: input.action && toMessengerAction(input.action),\n kind: input.eventKind,\n message: input.message && convert(input.message),\n messengerId: definition.id,\n provider: definition.provider,\n raw: input.raw ?? input.message?.raw,\n ...(skipped && { skipped }),\n thread: toMessengerThread(input.thread)\n };\n}\n\n/**\n * Rewrite the bot's own unresolved self-mention to `@<userName>`.\n *\n * Adapters resolve every user's `<@id>` mention to a readable `@DisplayName`\n * except the bot's own, which is deliberately left as a raw id token so mention\n * detection can still find it. That raw id is therefore the only unresolved\n * mention that can survive in the text, so once it has served its purpose we\n * replace it with the bot's configured handle before the model sees it —\n * reconstructing the readable `@handle` the sender originally typed. Handles\n * both the angle-bracket form (`<@U123>` / `<@!U123>`, Slack/Discord) and the\n * bare `@U123` form some adapters normalize to. No-op when the adapter does not\n * expose a `botUserId`.\n */\nexport function resolveSelfMention(\n text: string,\n botUserId: string | undefined,\n userName: string\n): string {\n if (!botUserId) {\n return text;\n }\n const id = escapeRegExp(botUserId);\n const replacement = `@${userName}`;\n return text\n .replace(new RegExp(`<@!?${id}>`, \"g\"), replacement)\n .replace(new RegExp(`@${id}\\\\b`, \"g\"), replacement);\n}\n\n/**\n * Whether a message mentions the bot. The Chat SDK only runs its own mention\n * detection on the message it dispatches, so messages a burst folded into\n * `skipped` carry `isMention` only when their adapter set it. This mirrors the\n * SDK's check (`@userName`, `@botUserId`, `<@botUserId>`) for them.\n */\nexport function mentionsBot(\n definition: Pick<NormalizedMessengerDefinition, \"adapter\" | \"userName\">,\n message: Pick<ChatMessage, \"isMention\" | \"text\">\n): boolean {\n if (message.isMention) return true;\n const userName = definition.adapter.userName || definition.userName;\n const patterns = [new RegExp(`@${escapeRegExp(userName)}\\\\b`, \"i\")];\n const botUserId = definition.adapter.botUserId;\n if (botUserId) {\n const id = escapeRegExp(botUserId);\n patterns.push(new RegExp(`@${id}\\\\b`, \"i\"), new RegExp(`<@!?${id}>`, \"i\"));\n }\n return patterns.some((pattern) => pattern.test(message.text));\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nexport function toMessengerAction(action: ChatActionEvent): MessengerAction {\n return {\n actionId: action.actionId,\n messageId: action.messageId,\n raw: action.raw,\n user: toMessengerAuthor(action.user),\n value: action.value\n };\n}\n\nexport function toMessengerThread(thread: ChatThread): MessengerThread {\n return {\n channelId: thread.channelId,\n channelName: thread.channel.name ?? undefined,\n id: thread.id,\n isDirectMessage: thread.isDM,\n providerThreadId: thread.id\n };\n}\n\nexport function toMessengerMessage(message: ChatMessage): MessengerMessage {\n return {\n attachments: message.attachments.map(toMessengerAttachment),\n author: toMessengerAuthor(message.author),\n createdAt: message.metadata.dateSent,\n id: message.id,\n isMention: message.isMention,\n providerMessageId: message.id,\n raw: message.raw,\n text: message.text\n };\n}\n\nexport function toMessengerAuthor(author: ChatAuthor): MessengerAuthor {\n return {\n fullName: author.fullName || undefined,\n isBot: author.isBot,\n isMe: author.isMe,\n userId: author.userId,\n userName: author.userName || undefined\n };\n}\n\nexport function toMessengerAttachment(\n attachment: ChatAttachment\n): MessengerAttachment {\n const fetchMetadata = attachment.fetchMetadata;\n const inline: unknown = attachment.data;\n const data =\n inline instanceof ArrayBuffer || ArrayBuffer.isView(inline)\n ? attachmentBytes(inline)\n : undefined;\n const blob = inline instanceof Blob ? inline : undefined;\n return {\n data,\n fetch: attachment.fetchData\n ? async () => {\n const fetched = await attachment.fetchData?.();\n return fetched ? attachmentBytes(fetched) : new ArrayBuffer(0);\n }\n : data\n ? () => Promise.resolve(data)\n : blob\n ? () => blob.arrayBuffer()\n : undefined,\n fetchMetadata: fetchMetadata ? { ...fetchMetadata } : undefined,\n id: identifierFromFetchMetadata(fetchMetadata),\n mediaType: attachment.mimeType,\n name: attachment.name,\n raw: attachment,\n size: attachment.size,\n url: attachment.url\n };\n}\n\n/**\n * `chat` adapters resolve `fetchData` to a `Buffer` or, from `chat@4.41`\n * (inside this package's `^4.31.0` range), a plain `ArrayBuffer`. A `Buffer` is\n * a view that may share a pooled or `SharedArrayBuffer` backing store with\n * unrelated bytes, so only its own range is copied out; a view spanning its\n * whole `ArrayBuffer` hands that buffer over as is.\n */\nfunction attachmentBytes(data: ArrayBuffer | ArrayBufferView): ArrayBuffer {\n if (data instanceof ArrayBuffer) {\n return data;\n }\n if (\n data.buffer instanceof ArrayBuffer &&\n data.byteOffset === 0 &&\n data.byteLength === data.buffer.byteLength\n ) {\n return data.buffer;\n }\n const copy = new Uint8Array(data.byteLength);\n copy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));\n return copy.buffer;\n}\n\nconst FETCH_METADATA_ID_KEYS = [\"id\", \"fileId\", \"mediaId\", \"fileUniqueId\"];\n\n/**\n * Best-effort top-level id for an attachment whose adapter only records its\n * identifier in `fetchMetadata` (e.g. Telegram `fileId`). This keeps id-based\n * consumers working without per-adapter knowledge, while the full\n * `fetchMetadata` is preserved verbatim for precise re-fetching.\n */\nfunction identifierFromFetchMetadata(\n fetchMetadata: Record<string, string> | undefined\n): string | undefined {\n if (!fetchMetadata) {\n return undefined;\n }\n for (const key of FETCH_METADATA_ID_KEYS) {\n const value = fetchMetadata[key];\n if (typeof value === \"string\" && value.length > 0) {\n return value;\n }\n }\n return undefined;\n}\n\nfunction stableNamePart(value: string): string {\n const safe = value.replace(/[^a-zA-Z0-9:_-]/g, \"_\");\n if (safe.length <= 80) {\n return safe;\n }\n return `${safe.slice(0, 48)}_${hashString(value)}`;\n}\n\nfunction hashString(value: string): string {\n let hash = 5381;\n for (let index = 0; index < value.length; index += 1) {\n hash = (hash * 33) ^ value.charCodeAt(index);\n }\n return (hash >>> 0).toString(36);\n}\n\nfunction validatePath(path: string, id: string): void {\n if (!path.startsWith(\"/\")) {\n throw new Error(`Messenger ${id} path must start with \"/\"`);\n }\n if (path.includes(\"?\") || path.includes(\"#\")) {\n throw new Error(`Messenger ${id} path must not include query or hash`);\n }\n}\n"],"mappings":";;;;;;;;;;AAsGA,SAAgB,0BACd,OACkB;CAClB,MAAM,eAAe,2BAA2B,KAAK;CACrD,OAAO;EACL,QAAQ,aAAa;EACrB,QAAQ,aAAa,SAAS,UAAU,aAAa,QAAQ;EAC7D,cAAc,aAAa;EAC3B,MAAM,aAAa;EACnB,SAAS,aAAa;EACtB,aAAa,aAAa;EAC1B,UAAU,aAAa;EACvB,SAAS,aAAa;EACtB,QAAQ,aAAa;CACvB;AACF;AAEA,SAAgB,2BACd,OACgB;CAChB,OAAO;EACL,cAAc,EAAE,GAAG,MAAM,aAAa;EACtC,MAAM,MAAM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