@cloudflare/think 0.17.0 → 0.19.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 +133 -31
- package/dist/{chat-sdk-C8BvREXn.js → chat-sdk-B77QwYuj.js} +49 -31
- package/dist/chat-sdk-B77QwYuj.js.map +1 -0
- package/dist/extensions/index.d.ts +1 -1
- package/dist/extensions/index.js +1 -1
- package/dist/extensions/index.js.map +1 -1
- package/dist/{index-B7zEkBBM.d.ts → index-BLkPlEbF.d.ts} +720 -218
- package/dist/{manager-CSk5htym.js → manager-Cb3DNZgp.js} +10 -10
- package/dist/{manager-CSk5htym.js.map → manager-Cb3DNZgp.js.map} +1 -1
- package/dist/messengers/index.d.ts +1 -1
- package/dist/messengers/index.js +1 -1
- package/dist/messengers/telegram.d.ts +1 -1
- package/dist/messengers/telegram.js +1 -1
- package/dist/think.d.ts +3 -3
- package/dist/think.js +1580 -735
- package/dist/think.js.map +1 -1
- package/dist/tools/execute.d.ts +1 -1
- package/dist/tools/extensions.js +1 -1
- package/dist/tools/workspace.d.ts +1 -1
- package/dist/tools/workspace.js.map +1 -1
- package/dist/workflows.d.ts +1 -1
- package/dist/{workspace-DxZQSbko.d.ts → workspace-CNeXc2vl.d.ts} +8 -2
- package/docs/client-tools.md +1 -1
- package/docs/getting-started.md +19 -14
- package/docs/index.md +98 -28
- package/docs/lifecycle-hooks.md +51 -15
- package/docs/tools.md +2 -2
- package/package.json +6 -6
- package/dist/chat-sdk-C8BvREXn.js.map +0 -1
package/docs/index.md
CHANGED
|
@@ -204,18 +204,18 @@ Both Think and [`AIChatAgent`](https://github.com/cloudflare/agents/blob/main/do
|
|
|
204
204
|
|
|
205
205
|
**AIChatAgent** is a protocol adapter. You override `onChatMessage` and are responsible for calling `streamText`, wiring tools, converting messages, and returning a `Response`. AIChatAgent handles the plumbing — message persistence, streaming, abort, resume — but the LLM call is entirely your concern.
|
|
206
206
|
|
|
207
|
-
**Think** is an opinionated framework. It makes decisions for you: `getModel()` returns the model, `getSystemPrompt()` or `
|
|
208
|
-
|
|
209
|
-
| Concern | AIChatAgent | Think
|
|
210
|
-
| ---------------------- | ---------------------------------------------------------------- |
|
|
211
|
-
| **Minimal subclass** | ~15 lines (wire `streamText` + tools + system prompt + response) | 3 lines (`getModel()` only)
|
|
212
|
-
| **Storage** | Flat SQL table |
|
|
213
|
-
| **Regeneration** | Destructive (old response deleted) | Non-destructive branching (old responses preserved)
|
|
214
|
-
| **Context management** | Manual | Context blocks with LLM-writable persistent memory
|
|
215
|
-
| **Sub-agent RPC** | Not built in | `chat()` with `StreamCallback`
|
|
216
|
-
| **Programmatic turns** | `saveMessages()` | `saveMessages()`, `submitMessages()`, `continueLastTurn()`
|
|
217
|
-
| **Compaction** | `maxPersistedMessages` (deletes oldest) | Non-destructive summaries via overlays
|
|
218
|
-
| **Search** | Not available | FTS5 full-text search per-session and cross-session
|
|
207
|
+
**Think** is an opinionated framework. It makes decisions for you: `getModel()` returns the model, `getSystemPrompt()` or `configureContext()` sets the prompt, `getTools()` returns tools. The default `onChatMessage` runs the complete agentic loop. You override individual pieces, not the whole pipeline.
|
|
208
|
+
|
|
209
|
+
| Concern | AIChatAgent | Think |
|
|
210
|
+
| ---------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------- |
|
|
211
|
+
| **Minimal subclass** | ~15 lines (wire `streamText` + tools + system prompt + response) | 3 lines (`getModel()` only) |
|
|
212
|
+
| **Storage** | Flat SQL table | Sessions: tree-structured messages, compaction, FTS5 |
|
|
213
|
+
| **Regeneration** | Destructive (old response deleted) | Non-destructive branching (old responses preserved) |
|
|
214
|
+
| **Context management** | Manual | Context blocks with LLM-writable persistent memory |
|
|
215
|
+
| **Sub-agent RPC** | Not built in | `chat()` with `StreamCallback` |
|
|
216
|
+
| **Programmatic turns** | `saveMessages()` | `saveMessages()`, `submitMessages()`, `continueLastTurn()` |
|
|
217
|
+
| **Compaction** | `maxPersistedMessages` (deletes oldest) | Non-destructive summaries via overlays |
|
|
218
|
+
| **Search** | Not available | FTS5 full-text search per-session and cross-session |
|
|
219
219
|
|
|
220
220
|
### When to use AIChatAgent
|
|
221
221
|
|
|
@@ -403,8 +403,12 @@ path.
|
|
|
403
403
|
| `configureChannels()` | `{}` | Per-channel policy and surfaces beyond the implicit `web` channel — see [Channels](./channels.md) |
|
|
404
404
|
| `maxSteps` | `10` | Max tool-call rounds per turn |
|
|
405
405
|
| `sendReasoning` | `true` | Send reasoning chunks to chat clients |
|
|
406
|
-
| `configureSession()` | identity |
|
|
406
|
+
| `configureSession()` | identity | Configure the default session handle: compaction and search — see [Sessions](https://github.com/cloudflare/agents/blob/main/docs/agents/sessions.md) |
|
|
407
|
+
| `configureContext()` | `[]` | Declare prompt context blocks — see [Session and context](#session-and-context) |
|
|
408
|
+
| `hydrationByteBudget` | 32 MiB | Byte budget for startup transcript hydration. Charges each row its stored bytes plus the attachment bytes it re-inflates |
|
|
409
|
+
| `mediaEviction` | `true` | Media eviction policy: aged media leaves the conversation and is preserved as a Workspace file. `false` keeps aged media in the conversation |
|
|
407
410
|
| `getSkills()` | `[]` | Return Agent Skills sources for on-demand skill activation |
|
|
411
|
+
| `skillWorkspace` | `false` | Project skills into the Workspace as files; `{}` enables with defaults |
|
|
408
412
|
| `getSkillScriptRunner()` | `null` | Enable the optional `run_skill_script` tool |
|
|
409
413
|
| `workspaceBash` | `true` | Include or configure the default workspace `bash` tool |
|
|
410
414
|
| `fetchTools` | `false` | Opt-in allowlisted, read-only HTTP fetch tools (`fetch_url` + per-binding `fetch_<name>`). Set to a config object; see [Fetch tool](#fetch-tool) |
|
|
@@ -486,6 +490,18 @@ agent (including a plain `@cloudflare/ai-chat` `onChatMessage`) can build a
|
|
|
486
490
|
`SkillRegistry`; `@cloudflare/think` re-exports it as `skills` and wires
|
|
487
491
|
`getSkills()` into the turn automatically.
|
|
488
492
|
|
|
493
|
+
Think can also project each resolved `SKILL.md` into the active workspace so
|
|
494
|
+
the agent can read and edit skills as files. This is off by default: skills
|
|
495
|
+
load from their sources and nothing is written to the Workspace. Set
|
|
496
|
+
`skillWorkspace = {}` to enable it. Computer uses `/workspace/.agents/skills`;
|
|
497
|
+
legacy Shell uses `/.agents/skills`. Existing workspace edits are preserved and
|
|
498
|
+
affect later activation. Resources copy into the workspace when first requested
|
|
499
|
+
rather than at startup. A durable source fingerprint lets unchanged cold wakes
|
|
500
|
+
attach to the existing projection without statting or rewriting every file.
|
|
501
|
+
|
|
502
|
+
Set `skillWorkspace = { root: "/workspace/.agents/skills" }` when a custom
|
|
503
|
+
Computer proxy presents Think's legacy direct-method shape.
|
|
504
|
+
|
|
489
505
|
Sources are applied in order; the first source to register a skill name wins,
|
|
490
506
|
and later duplicates (or a source that fails to load) are skipped with a logged
|
|
491
507
|
warning rather than failing the agent.
|
|
@@ -507,9 +523,9 @@ When skills are available, Think exposes:
|
|
|
507
523
|
| `run_skill_script` | Run a bundled script when `getSkillScriptRunner()` returns a runner |
|
|
508
524
|
|
|
509
525
|
Skills are not always-on system prompt text. Use `getSystemPrompt()` or a
|
|
510
|
-
|
|
511
|
-
for task-specific procedures, references, scripts, templates,
|
|
512
|
-
should be loaded only when relevant.
|
|
526
|
+
context block from `configureContext()` for behavior that should apply to every
|
|
527
|
+
turn. Use skills for task-specific procedures, references, scripts, templates,
|
|
528
|
+
and assets that should be loaded only when relevant.
|
|
513
529
|
|
|
514
530
|
Script execution is opt-in and requires a Worker Loader binding:
|
|
515
531
|
|
|
@@ -646,7 +662,7 @@ export class MyAgent extends Think<Env> {
|
|
|
646
662
|
|
|
647
663
|
Use either layer alone, or both together: the proactive guard avoids most overflows, and the reactive backstop catches any that still slip through (for example, a turn that starts already over budget, or a single tool result so large that compaction cannot help — in which case it terminalizes cleanly). Both apply to every turn entry path (WebSocket, sub-agent `chat()`, and programmatic `saveMessages()` / `submitMessages()`), and both emit a `chat:context:compacted` [observability event](https://github.com/cloudflare/agents/blob/main/docs/agents/observability.md#chat-context-events).
|
|
648
664
|
|
|
649
|
-
> A no-op compaction cannot rescue an over-budget turn, so recovery is only as effective as your compaction configuration. For tool-heavy histories,
|
|
665
|
+
> A no-op compaction cannot rescue an over-budget turn, so recovery is only as effective as your compaction configuration. For tool-heavy histories, lower the `compactAfter()` threshold and the `keepRecentTokens` budget of your compaction function (see [Sessions](https://github.com/cloudflare/agents/blob/main/docs/agents/sessions.md#compaction)).
|
|
650
666
|
|
|
651
667
|
For a runnable demo against a real Workers AI model, see [`examples/context-overflow-recovery`](https://github.com/cloudflare/agents/tree/main/examples/context-overflow-recovery).
|
|
652
668
|
|
|
@@ -817,12 +833,15 @@ You do not need new machinery to gate egress per call: `beforeToolCall` can `blo
|
|
|
817
833
|
| Browser Run (`tools/browser`) | Rendered pages, auth flows, screenshots, CDP automation |
|
|
818
834
|
| Typed tools / `agentTool()` | Calling a `WorkerEntrypoint`/DO method with a typed schema, or delegating to a sub-agent |
|
|
819
835
|
|
|
820
|
-
## Session
|
|
836
|
+
## Session and context
|
|
837
|
+
|
|
838
|
+
Think splits conversation storage from prompt assembly. [`agents/sessions`](https://github.com/cloudflare/agents/blob/main/docs/agents/sessions.md) stores messages; [`agents/context`](https://github.com/cloudflare/agents/blob/main/docs/agents/context.md) builds the system prompt. Think wires both during `onStart`.
|
|
821
839
|
|
|
822
|
-
|
|
840
|
+
`configureSession()` configures the default session handle: compaction and search.
|
|
823
841
|
|
|
824
842
|
```typescript
|
|
825
843
|
import { Think, Session } from "@cloudflare/think";
|
|
844
|
+
import { createCompactFunction } from "agents/sessions";
|
|
826
845
|
|
|
827
846
|
export class MyAgent extends Think<Env> {
|
|
828
847
|
getModel() {
|
|
@@ -831,19 +850,70 @@ export class MyAgent extends Think<Env> {
|
|
|
831
850
|
|
|
832
851
|
configureSession(session: Session) {
|
|
833
852
|
return session
|
|
834
|
-
.
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
.withCachedPrompt();
|
|
853
|
+
.onCompaction(
|
|
854
|
+
createCompactFunction({
|
|
855
|
+
summarize: (prompt) => this.summarize(prompt),
|
|
856
|
+
keepRecentTokens: 20_000
|
|
857
|
+
})
|
|
858
|
+
)
|
|
859
|
+
.compactAfter(100_000);
|
|
842
860
|
}
|
|
843
861
|
}
|
|
844
862
|
```
|
|
845
863
|
|
|
846
|
-
|
|
864
|
+
`configureContext()` declares the prompt blocks:
|
|
865
|
+
|
|
866
|
+
```typescript
|
|
867
|
+
import type { ContextConfig } from "agents/context";
|
|
868
|
+
|
|
869
|
+
export class MyAgent extends Think<Env> {
|
|
870
|
+
configureContext(): ContextConfig[] {
|
|
871
|
+
return [
|
|
872
|
+
{ label: "soul", provider: { get: async () => "You are helpful." } },
|
|
873
|
+
{ label: "memory", description: "Learned facts", maxTokens: 2_000 }
|
|
874
|
+
];
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
```
|
|
878
|
+
|
|
879
|
+
A block declared without a `provider` is auto-wired to durable per-agent SQLite, so `memory` above is writable through the `set_context` tool with no extra wiring. The frozen system prompt is always persisted, so there is nothing to opt into: a cold wake reuses the exact prompt string the model already cached.
|
|
880
|
+
|
|
881
|
+
The assembled blocks are available as `this.context` once the Lifecycle has started.
|
|
882
|
+
|
|
883
|
+
### Upgrading from 0.17
|
|
884
|
+
|
|
885
|
+
A subclass written against 0.17 keeps compiling and running. `configureSession(session)` still accepts the `withContext()` / `withCachedPrompt()` chain, and `this.session` still carries the context methods (`addContext`, `getContextBlock`, `replaceContextBlock`, `refreshSystemPrompt`, `freezeSystemPrompt`, `tools()`), which now forward to `this.context`. They are deprecated; move blocks into `configureContext()` and read `this.context` at your own pace. Blocks from both hooks are merged, `configureContext()` first.
|
|
886
|
+
|
|
887
|
+
Two things do change on upgrade:
|
|
888
|
+
|
|
889
|
+
- **Storage migrates on first wake and cannot be rolled back.** Each Durable Object lifts its `assistant_*` tables into `cf_agents_session_*`, verifies every row, and drops the old tables. An object that has woken on this version has an empty conversation if you roll back; rolling forward again is safe. Canary the deploy if you need a rollback path.
|
|
890
|
+
- **Hydration has no message-count floor.** `hydrationByteBudget` (now 32 MiB) is a hard ceiling that charges each row its stored size plus attachments, so a run of very large messages can hydrate fewer than four. `getHistory()` still reads the full path.
|
|
891
|
+
|
|
892
|
+
Annotate a `configureSession` override with `Session` imported from `@cloudflare/think`. The `Session` class exported by `agents/sessions` is the raw storage handle and is not assignable to Think's.
|
|
893
|
+
|
|
894
|
+
`sessionAttachments` is gone (Sessions stores media out of the row on its own), `MediaEvictionConfig.externalizeToWorkspace` is ignored (bytes are always preserved), and `WorkspaceLike.writeFileBytes` is optional (a workspace without it disables media eviction and skills projection with a one-time warning).
|
|
895
|
+
|
|
896
|
+
Think's `this.messages` getter reads directly from the Session tree. Compaction overlays and search are handled by Sessions.
|
|
897
|
+
|
|
898
|
+
### Message storage
|
|
899
|
+
|
|
900
|
+
Sessions stores MESSAGES; it is not a file store. A message rides in one SQLite row until its serialized JSON exceeds the 1.5 MiB row budget; a message larger than that is split across continuation rows and reassembled on read, byte for byte. Nothing is truncated and no message is too large to store, so there is no size error to handle and nothing to configure. Splitting never reclaims database space — the continuation rows live in the same Durable Object as the message — and Sessions imposes no upper bound on a single message, so a Durable Object's 10 GB ceiling is the real bound on how much one conversation can hold and bounding untrusted input is the application's job. Files belong in the Workspace, which spills to R2; put a reference to one in the message. This is a storage detail: it is invisible to the model, and it is unrelated to media eviction.
|
|
901
|
+
|
|
902
|
+
### Media eviction
|
|
903
|
+
|
|
904
|
+
Media eviction is a different concern: a context-window technique, not a storage one. Sending a screenshot the model has already looked at back through the context on every subsequent turn is pure cost, so once a message has aged past `mediaEviction.keepRecentMessages` (8 by default) on the active path, Think takes the media out of the conversation and leaves a marker in its place:
|
|
905
|
+
|
|
906
|
+
```
|
|
907
|
+
[evicted image/png, 812004 bytes; preserved at /attachments/evicted/msg_01H8-0.png]
|
|
908
|
+
```
|
|
909
|
+
|
|
910
|
+
The bytes are written to the Workspace at that path, raw and with their real mime type — not as a `data:` URL string. The workspace `read` tool recognises `image/*`, so when the agent decides it needs to look at the picture again it reads the path out of the marker and the actual image goes back into context. Eviction is visible to the model and lossy on purpose; nothing reconstructs it behind the model's back.
|
|
911
|
+
|
|
912
|
+
Passes are bounded (`maxRowsPerPass`, 64 by default) and run in the background after a turn or a hydration read, rescheduling themselves while a backlog remains. Only payloads of at least `minPartBytes` are evicted, and `keepRecentMessages` is clamped to the four messages the model replays at full fidelity, so eviction can never rewrite content the model is still reading. Once a row is rewritten, the Sessions attachment reference is dropped and the blob is reaped: the bytes exist in exactly one place, the Workspace file.
|
|
913
|
+
|
|
914
|
+
`mediaEviction: false` keeps aged media in the conversation, so the model keeps seeing it. It does not change where Sessions keeps the bytes — a large payload may still be stored as a pointer, which is unobservable.
|
|
915
|
+
|
|
916
|
+
Startup hydration reads a recent window bounded by `hydrationByteBudget` (32 MiB by default). The budget charges each row its stored bytes plus the attachment bytes it re-inflates, so it bounds isolate memory rather than the on-disk footprint.
|
|
847
917
|
|
|
848
918
|
## Package Exports
|
|
849
919
|
|
package/docs/lifecycle-hooks.md
CHANGED
|
@@ -7,6 +7,7 @@ Think owns the `streamText` call and provides hooks at each stage of the chat tu
|
|
|
7
7
|
| Hook | When it fires | Return | Async |
|
|
8
8
|
| -------------------------------- | ----------------------------------------------------------- | --------------------------------- | ----- |
|
|
9
9
|
| `configureSession(session)` | Once during `onStart` | `Session` | yes |
|
|
10
|
+
| `configureContext()` | Once during `onStart` | `ContextConfig[]` | yes |
|
|
10
11
|
| `beforeTurn(ctx)` | Before `streamText` | `TurnConfig` or void | yes |
|
|
11
12
|
| `beforeStep(ctx)` | Before each model step | `StepConfig` or void | yes |
|
|
12
13
|
| `beforeToolCall(ctx)` | When model calls a tool | `ToolCallDecision` or void | yes |
|
|
@@ -23,6 +24,7 @@ For a turn with two tool calls:
|
|
|
23
24
|
|
|
24
25
|
```
|
|
25
26
|
configureSession() ← once at startup, not per-turn
|
|
27
|
+
configureContext() ← once at startup, not per-turn
|
|
26
28
|
│
|
|
27
29
|
beforeTurn() ← inspect assembled context, override model/tools/prompt
|
|
28
30
|
│
|
|
@@ -53,7 +55,7 @@ onChatResponse() ← message persisted, turn lock released
|
|
|
53
55
|
|
|
54
56
|
## configureSession
|
|
55
57
|
|
|
56
|
-
Called once during Durable Object initialization (`onStart`).
|
|
58
|
+
Called once during Durable Object initialization (`onStart`). Configures the default session handle: compaction and search. Prompt context is declared by [`configureContext`](#configurecontext) instead.
|
|
57
59
|
|
|
58
60
|
```typescript
|
|
59
61
|
configureSession(session: Session): Session | Promise<Session>
|
|
@@ -61,7 +63,7 @@ configureSession(session: Session): Session | Promise<Session>
|
|
|
61
63
|
|
|
62
64
|
```typescript
|
|
63
65
|
import { Think, Session } from "@cloudflare/think";
|
|
64
|
-
import { createCompactFunction } from "agents/
|
|
66
|
+
import { createCompactFunction } from "agents/sessions";
|
|
65
67
|
import { generateText } from "ai";
|
|
66
68
|
|
|
67
69
|
export class MyAgent extends Think<Env> {
|
|
@@ -71,28 +73,62 @@ export class MyAgent extends Think<Env> {
|
|
|
71
73
|
|
|
72
74
|
configureSession(session: Session) {
|
|
73
75
|
return session
|
|
74
|
-
.withContext("soul", {
|
|
75
|
-
provider: { get: async () => "You are a helpful coding assistant." }
|
|
76
|
-
})
|
|
77
|
-
.withContext("memory", {
|
|
78
|
-
description: "Learned facts about the user.",
|
|
79
|
-
maxTokens: 1100
|
|
80
|
-
})
|
|
81
76
|
.onCompaction(
|
|
82
77
|
createCompactFunction({
|
|
83
78
|
summarize: (prompt) =>
|
|
84
79
|
generateText({ model: this.resolveModel(), prompt }).then(
|
|
85
80
|
(r) => r.text
|
|
86
|
-
)
|
|
81
|
+
),
|
|
82
|
+
keepRecentTokens: 20_000
|
|
87
83
|
})
|
|
88
84
|
)
|
|
89
|
-
.compactAfter(100_000)
|
|
90
|
-
.withCachedPrompt();
|
|
85
|
+
.compactAfter(100_000);
|
|
91
86
|
}
|
|
92
87
|
}
|
|
93
88
|
```
|
|
94
89
|
|
|
95
|
-
|
|
90
|
+
The handle also accepts the 0.17 `withContext()` / `withCachedPrompt()` chain and the positional `appendMessage(message, parentId)` form, so an existing override keeps working; see [Upgrading from 0.17](./index.md#upgrading-from-017).
|
|
91
|
+
|
|
92
|
+
`createCompactFunction` takes exactly two options: `summarize`, which calls the model with a prompt and returns its text, and `keepRecentTokens`, the token budget for the recent tail kept verbatim (default `20_000`). `compactAfter(threshold)` gates on the O(1) token estimate Sessions stamps on each row. See the [Sessions documentation](https://github.com/cloudflare/agents/blob/main/docs/agents/sessions.md) for the full API.
|
|
93
|
+
|
|
94
|
+
---
|
|
95
|
+
|
|
96
|
+
## configureContext
|
|
97
|
+
|
|
98
|
+
Called once during Durable Object initialization (`onStart`). Declares the prompt context blocks for this agent.
|
|
99
|
+
|
|
100
|
+
```typescript
|
|
101
|
+
configureContext(): ContextConfig[] | Promise<ContextConfig[]>
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
```typescript
|
|
105
|
+
import { Think } from "@cloudflare/think";
|
|
106
|
+
import type { ContextConfig } from "agents/context";
|
|
107
|
+
|
|
108
|
+
export class MyAgent extends Think<Env> {
|
|
109
|
+
getModel() {
|
|
110
|
+
/* ... */
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
configureContext(): ContextConfig[] {
|
|
114
|
+
return [
|
|
115
|
+
{
|
|
116
|
+
label: "soul",
|
|
117
|
+
provider: { get: async () => "You are a helpful coding assistant." }
|
|
118
|
+
},
|
|
119
|
+
{
|
|
120
|
+
label: "memory",
|
|
121
|
+
description: "Learned facts about the user.",
|
|
122
|
+
maxTokens: 1100
|
|
123
|
+
}
|
|
124
|
+
];
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
A block declared without a `provider` is auto-wired to durable per-agent SQLite, so `memory` above is writable through the `set_context` tool with no extra wiring. When context blocks are configured, Think builds the system prompt from those blocks instead of using `getSystemPrompt()`. The frozen system prompt is always persisted, so a cold wake reuses the exact prompt string the model already cached.
|
|
130
|
+
|
|
131
|
+
The assembled blocks are available as `this.context` once the Lifecycle has started. See the [Context documentation](https://github.com/cloudflare/agents/blob/main/docs/agents/context.md) for providers, tools, and frozen-prompt behavior.
|
|
96
132
|
|
|
97
133
|
---
|
|
98
134
|
|
|
@@ -110,7 +146,7 @@ beforeTurn(ctx: TurnContext): TurnConfig | void | Promise<TurnConfig | void>
|
|
|
110
146
|
| -------------- | ------------------------- | ------------------------------------------------------------------------ |
|
|
111
147
|
| `system` | `string` | Assembled system prompt (from context blocks or `getSystemPrompt()`) |
|
|
112
148
|
| `messages` | `ModelMessage[]` | Assembled model messages (truncated) |
|
|
113
|
-
| `tools` | `ToolSet` | Merged tool set (workspace + getTools +
|
|
149
|
+
| `tools` | `ToolSet` | Merged tool set (workspace + getTools + context + MCP + client + caller) |
|
|
114
150
|
| `model` | `LanguageModel` | The resolved model (a string from `getModel()` is already resolved here) |
|
|
115
151
|
| `continuation` | `boolean` | Whether this is a continuation turn (auto-continue after tool result) |
|
|
116
152
|
| `body` | `Record<string, unknown>` | Custom body fields from the client request |
|
|
@@ -783,7 +819,7 @@ onChatError(error: unknown, ctx?: ChatErrorContext) {
|
|
|
783
819
|
|
|
784
820
|
## classifyChatError
|
|
785
821
|
|
|
786
|
-
Called when an error occurs during a turn, **before** `onChatError`. Maps a raw provider error into a provider-agnostic category so Think can react without baking provider-specific strings into the framework
|
|
822
|
+
Called when an error occurs during a turn, **before** `onChatError`. Maps a raw provider error into a provider-agnostic category so Think can react without baking provider-specific strings into the framework. The app owns the mapping because it knows which provider and model it talks to.
|
|
787
823
|
|
|
788
824
|
```typescript
|
|
789
825
|
classifyChatError(error: unknown, ctx?: ChatErrorContext): ChatErrorClassification | void
|
package/docs/tools.md
CHANGED
|
@@ -9,7 +9,7 @@ On every turn, Think merges tools from multiple sources. Later sources override
|
|
|
9
9
|
1. **Workspace tools** — `read`, `write`, `edit`, `list`, `find`, `grep`, `delete`, `bash` (built-in)
|
|
10
10
|
2. **`getTools()`** — your custom server-side tools
|
|
11
11
|
3. **Extension tools** — tools from loaded extensions (prefixed by extension name)
|
|
12
|
-
4. **
|
|
12
|
+
4. **Context tools** — `set_context`, `search_context` (from `configureContext`)
|
|
13
13
|
5. **Skill tools** — `activate_skill`, `read_skill_resource`, `run_skill_script` (from `getSkills()`)
|
|
14
14
|
6. **MCP tools** — from connected MCP servers (when `includeMcpTools` is enabled)
|
|
15
15
|
7. **Client tools** — from the browser (see [Client Tools](./client-tools.md))
|
|
@@ -530,7 +530,7 @@ Loaded extensions persist across DO restarts via `extensionManager.restore()`.
|
|
|
530
530
|
|
|
531
531
|
### Extension Context Blocks
|
|
532
532
|
|
|
533
|
-
Extensions can declare context blocks in their manifest. These are automatically
|
|
533
|
+
Extensions can declare context blocks in their manifest. These are automatically added to the agent's context blocks:
|
|
534
534
|
|
|
535
535
|
```typescript
|
|
536
536
|
getExtensions() {
|
package/package.json
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
"tools"
|
|
10
10
|
],
|
|
11
11
|
"type": "module",
|
|
12
|
-
"version": "0.
|
|
12
|
+
"version": "0.19.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.2",
|
|
27
27
|
"@cloudflare/shell": "^0.4.3",
|
|
28
28
|
"chat": "^4.31.0",
|
|
29
29
|
"just-bash": "^3.0.2",
|
|
@@ -32,23 +32,23 @@
|
|
|
32
32
|
"devDependencies": {
|
|
33
33
|
"@ai-sdk/react": "^4.0.0",
|
|
34
34
|
"@chat-adapter/telegram": "^4.31.0",
|
|
35
|
-
"@cloudflare/ai-chat": "^0.
|
|
35
|
+
"@cloudflare/ai-chat": "^0.12.0",
|
|
36
36
|
"@testing-library/react": "^16.3.2",
|
|
37
37
|
"@types/react": "^19.2.17",
|
|
38
38
|
"@types/react-dom": "^19.2.3",
|
|
39
39
|
"@vitejs/plugin-react": "^6.0.3",
|
|
40
|
-
"agents": "^0.
|
|
40
|
+
"agents": "^0.24.0",
|
|
41
41
|
"ai": "^7.0.0",
|
|
42
42
|
"jsdom": "^29.1.1",
|
|
43
43
|
"react": "^19.2.7",
|
|
44
44
|
"react-dom": "^19.2.7",
|
|
45
45
|
"vite": "^8.1.0",
|
|
46
|
-
"zod": "^4.4
|
|
46
|
+
"zod": "^4.5.4"
|
|
47
47
|
},
|
|
48
48
|
"peerDependencies": {
|
|
49
49
|
"@ai-sdk/react": "^3.0.0 || ^4.0.0",
|
|
50
50
|
"@chat-adapter/telegram": "^4.29.0",
|
|
51
|
-
"agents": ">=0.
|
|
51
|
+
"agents": ">=0.24.0 <1.0.0",
|
|
52
52
|
"ai": "^6.0.0 || ^7.0.0",
|
|
53
53
|
"react": "^19.0.0",
|
|
54
54
|
"zod": "^4.0.0"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"chat-sdk-C8BvREXn.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 thread: MessengerThread;\n}\n\nexport interface MessengerEvent extends MessengerContext {\n raw?: unknown;\n}\n\nexport function messengerContextFromEvent(\n event: MessengerEvent\n): MessengerContext {\n return {\n action: event.action,\n author: event.message?.author ?? event.action?.user,\n capabilities: event.capabilities,\n kind: event.kind,\n message: event.message,\n messengerId: event.messengerId,\n provider: event.provider,\n thread: event.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 ? {\n attachments: event.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: { ...event.message.author },\n createdAt: event.message.createdAt,\n id: event.message.id,\n isMention: event.message.isMention,\n providerMessageId: event.message.providerMessageId,\n text: event.message.text\n }\n : undefined\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 text = message.text.trim();\n const displayName = resolveChannelSpeakerLabel(\n message.author,\n channelSpeakerLabel\n );\n const content =\n event.thread.isDirectMessage || !displayName\n ? text\n : `${displayName}: ${text}`;\n const attachmentText = describeAttachments(message.attachments);\n const fullText = [content || text, attachmentText]\n .filter(Boolean)\n .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\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 { ChatStartEvent, StreamCallback } 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 onVisibleStart?: () => Promise<void> | void;\n visibleSoftLimit?: number;\n}\n\nexport class TextStreamCallback extends RpcTarget implements StreamCallback {\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 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.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.close();\n }\n\n onError(error: string): void {\n this.fail(new Error(error));\n }\n\n onInterrupted(): void {\n // The attempt was interrupted and a continuation (not this callback) owns\n // the real answer — delivered only to WebSocket connections, never to this\n // surface. Mark interrupted and stop the visible stream WITHOUT failing it,\n // so delivery surfaces the interrupted apology instead of treating the\n // partial as the final reply (#1644).\n this.interrupted = true;\n this.close();\n }\n\n wasInterrupted(): boolean {\n return this.interrupted;\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 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 visibleSoftLimit?: number;\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 onVisibleStart: async () => {\n await checkpoint(\n messengerReplySnapshot(\n \"streaming\",\n snapshotEvent,\n options.snapshotThread\n )\n );\n },\n visibleSoftLimit: options.policy?.visibleSoftLimit\n });\n const post = options.surface\n .post(callback.stream())\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 await options.surface.startTyping?.(\"Thinking...\");\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 and\n // broadcast only to WebSocket connections, NOT to this one-shot messenger\n // delivery. Do NOT mark the turn complete or finalize the truncated\n // partial as the reply — surface the interrupted apology so the user\n // knows to retry (#1644). `completedModelTurn` stays false.\n callback.close();\n await post.catch(() => undefined);\n await options.surface\n .post(interruptedResponseText)\n .catch(() => undefined);\n await checkpoint(\n messengerReplySnapshot(\n \"completed\",\n snapshotEvent,\n options.snapshotThread\n )\n );\n return;\n }\n completedModelTurn = true;\n callback.close();\n await post;\n if (!callback.hasText()) {\n await options.surface.post(emptyResponseText);\n }\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 if (failureMode === \"apologize\") {\n await options.surface\n .post(interruptedResponseText)\n .catch(() => undefined);\n await checkpoint(\n messengerReplySnapshot(\n \"completed\",\n snapshotEvent,\n options.snapshotThread\n )\n );\n return;\n }\n\n await options.surface\n .post({\n markdown: errorResponseText\n })\n .catch(() => undefined);\n await checkpoint(\n messengerReplySnapshot(\"completed\", snapshotEvent, options.snapshotThread)\n );\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 Message as ChatMessage,\n Thread as ChatThread\n} from \"chat\";\nimport { Chat } 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 MESSENGER_REPLY_FIBER_NAME,\n messengerReplyRecoveryMode,\n messengerReplySnapshot,\n parseMessengerReplySnapshot,\n type MessengerDeliveryPolicy,\n type MessengerDeliverySurface,\n type MessengerDeliveryTarget\n} from \"./delivery\";\n\nexport class ThinkMessengerStateAgent extends ChatSdkStateAgent {}\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\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 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 subAgent<T extends Agent>(\n agentClass: SubAgentClass<T>,\n name: string\n ): Promise<SubAgentStub<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 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 constructor(\n definitions: ThinkMessengers,\n private readonly host: MessengerThinkHost\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(ctx: FiberRecoveryContext): 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.reviveChatObject<ChatThread>(snapshot.thread);\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 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 \"Sorry, my reply was interrupted. Please send your message again if you'd like me to retry.\"\n );\n await this.host.resolveFiber(ctx.id, { status: \"completed\" });\n return true;\n }\n\n await this.host.resolveFiber(ctx.id, { status: \"completed\" });\n return true;\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: { debounceMs: 600, strategy: \"burst\" },\n state: createChatSdkState({\n agent: ThinkMessengerStateAgent,\n keyShard: (key) => this.shardStateKey(key),\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) => {\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 thread\n }),\n thread\n );\n }\n });\n\n chat.onNewMention(async (thread, message) => {\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 thread\n }),\n thread\n );\n }\n });\n\n chat.onSubscribedMessage(async (thread, message) => {\n const definition = this.definitionForThread(thread);\n if (!definition) return;\n if (\n definition.respondTo.includes(\"subscribed-thread\") ||\n (message.isMention && definition.respondTo.includes(\"mention\"))\n ) {\n await this.enqueueReply(\n definition,\n await this.toEvent(definition, {\n eventKind: message.isMention ? \"mention\" : \"subscribed-message\",\n message,\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 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 result = await this.host.startFiber(\n MESSENGER_REPLY_FIBER_NAME,\n async (fiber) => {\n fiber.stash(\n messengerReplySnapshot(\"accepted\", snapshotEvent, snapshotThread)\n );\n await this.answer(definition, event, thread, fiber, snapshotEvent);\n },\n {\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 waitForCompletion: true\n }\n );\n\n if (result.accepted || result.status !== \"interrupted\") {\n return;\n }\n\n const snapshot = parseMessengerReplySnapshot(result.snapshot);\n if (!snapshot) {\n return;\n }\n\n const mode = messengerReplyRecoveryMode(snapshot);\n if (mode === \"answer\") {\n await this.answer(\n definition,\n snapshot.event,\n thread,\n undefined,\n snapshot.event,\n async (nextSnapshot) => {\n await this.host.resolveFiber(result.fiberId, {\n snapshot: nextSnapshot,\n status:\n nextSnapshot.stage === \"completed\" ? \"completed\" : \"interrupted\"\n });\n }\n );\n return;\n }\n\n if (mode === \"apologize\") {\n await thread\n .post(\n definition.delivery?.interruptedResponseText ??\n \"Sorry, my reply was interrupted. Please send your message again if you'd like me to retry.\"\n )\n .catch(() => undefined);\n await this.host.resolveFiber(result.fiberId, { status: \"completed\" });\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 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 return (await this.host.subAgent(\n agentClass,\n target.name\n )) as unknown as MessengerDeliveryTarget;\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 private reviveChatObject<T>(value: unknown): T {\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 this.chat = chat;\n return JSON.parse(JSON.stringify(value), chat.reviver()) as T;\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 message = input.message && toMessengerMessage(input.message);\n if (message) {\n message.text = resolveSelfMention(\n message.text,\n definition.adapter.botUserId,\n definition.userName\n );\n }\n return {\n capabilities: definition.capabilities ?? {},\n action: input.action && toMessengerAction(input.action),\n kind: input.eventKind,\n message,\n messengerId: definition.id,\n provider: definition.provider,\n raw: input.raw ?? input.message?.raw,\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\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 return {\n fetch: attachment.fetchData\n ? async () => {\n const data = await attachment.fetchData?.();\n if (!data) {\n return new ArrayBuffer(0);\n }\n const copy = data.buffer.slice(\n data.byteOffset,\n data.byteOffset + data.byteLength\n );\n return copy instanceof ArrayBuffer ? copy : new ArrayBuffer(0);\n }\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\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":";;;;;AAyFA,SAAgB,0BACd,OACkB;CAClB,OAAO;EACL,QAAQ,MAAM;EACd,QAAQ,MAAM,SAAS,UAAU,MAAM,QAAQ;EAC/C,cAAc,MAAM;EACpB,MAAM,MAAM;EACZ,SAAS,MAAM;EACf,aAAa,MAAM;EACnB,UAAU,MAAM;EAChB,QAAQ,MAAM;CAChB;AACF;AAEA,SAAgB,2BACd,OACgB;CAChB,OAAO;EACL,cAAc,EAAE,GAAG,MAAM,aAAa;EACtC,MAAM,MAAM;EACZ,aAAa,MAAM;EACnB,UAAU,MAAM;EAChB,QAAQ,EAAE,GAAG,MAAM,OAAO;EAC1B,QAAQ,MAAM,SACV;GACE,UAAU,MAAM,OAAO;GACvB,WAAW,MAAM,OAAO;GACxB,MAAM,MAAM,OAAO,OAAO,EAAE,GAAG,MA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