@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/README.md
CHANGED
|
@@ -261,6 +261,23 @@ plain `@cloudflare/ai-chat` `onChatMessage`, can build a `SkillRegistry`);
|
|
|
261
261
|
`@cloudflare/think` re-exports it as `skills` and wires `getSkills()` into the
|
|
262
262
|
turn automatically.
|
|
263
263
|
|
|
264
|
+
Think can also project each resolved `SKILL.md` into the active workspace so
|
|
265
|
+
the agent can read and edit skills as files. This is off by default: skills
|
|
266
|
+
load from their sources and nothing is written to the Workspace. Computer uses
|
|
267
|
+
`/workspace/.agents/skills`; legacy Shell uses `/.agents/skills`. Existing
|
|
268
|
+
workspace edits are preserved and affect later activation. Resources copy into
|
|
269
|
+
the workspace on first use rather than at startup. Think records a durable
|
|
270
|
+
source fingerprint, so unchanged cold wakes do not stat or rewrite every skill
|
|
271
|
+
file.
|
|
272
|
+
|
|
273
|
+
Enable projection, or override its path, with:
|
|
274
|
+
|
|
275
|
+
```ts
|
|
276
|
+
skillWorkspace = {};
|
|
277
|
+
// or, for a custom Computer proxy that presents legacy direct methods:
|
|
278
|
+
skillWorkspace = { root: "/workspace/.agents/skills" };
|
|
279
|
+
```
|
|
280
|
+
|
|
264
281
|
The imported directory should contain one child directory per skill:
|
|
265
282
|
|
|
266
283
|
```text
|
|
@@ -277,9 +294,10 @@ from other skills.
|
|
|
277
294
|
|
|
278
295
|
Skills are on-demand instructions, not always-on system prompt text. The model
|
|
279
296
|
sees the catalog first, then calls `activate_skill` when a user task matches a
|
|
280
|
-
skill description. Use a
|
|
281
|
-
every turn, especially when the agent also uses skills.
|
|
282
|
-
legacy fallback and is ignored once
|
|
297
|
+
skill description. Use a context block from `configureContext()` for behavior
|
|
298
|
+
that should apply to every turn, especially when the agent also uses skills.
|
|
299
|
+
`getSystemPrompt()` is a legacy fallback and is ignored once context blocks are
|
|
300
|
+
configured.
|
|
283
301
|
|
|
284
302
|
Script execution is opt-in and **experimental**. `getSkillScriptRunner()`
|
|
285
303
|
enables `run_skill_script`, which can run JavaScript, TypeScript, Python, and
|
|
@@ -325,6 +343,8 @@ Script execution requires a Worker Loader binding:
|
|
|
325
343
|
| Export | Description |
|
|
326
344
|
| --------------------------------------- | ------------------------------------------------------------- |
|
|
327
345
|
| `@cloudflare/think` | `Think`, `Session`, `Workspace` — main class + re-exports |
|
|
346
|
+
| `agents/sessions` | `Sessions`, `Session`, `createCompactFunction`, attachments |
|
|
347
|
+
| `agents/context` | `ContextBlocks`, providers, `ContextConfig` — prompt assembly |
|
|
328
348
|
| `@cloudflare/think/messengers` | Messenger contracts, Chat SDK bridge, state agent, delivery |
|
|
329
349
|
| `@cloudflare/think/messengers/telegram` | Telegram messenger provider and delivery helpers |
|
|
330
350
|
| `@cloudflare/think/tools/workspace` | `createWorkspaceTools()` — for custom storage backends |
|
|
@@ -347,8 +367,12 @@ Script execution requires a Worker Loader binding:
|
|
|
347
367
|
| `getDefaultTimezone()` | `undefined` | Default timezone for wall-clock schedules |
|
|
348
368
|
| `maxSteps` | `10` | Max tool-call rounds per turn (property) |
|
|
349
369
|
| `sendReasoning` | `true` | Send reasoning chunks to chat clients |
|
|
350
|
-
| `configureSession()` | identity |
|
|
370
|
+
| `configureSession()` | identity | Configure the default session handle: compaction and search |
|
|
371
|
+
| `configureContext()` | `[]` | Declare prompt context blocks. See [Session and context](#session-and-context) |
|
|
372
|
+
| `hydrationByteBudget` | 32 MiB | Byte budget for startup transcript hydration. Charges each row its full stored size, including the continuation rows a large message is split across |
|
|
373
|
+
| `mediaEviction` | `true` | Media eviction policy: aged media leaves the conversation and is preserved as a Workspace file. `false` keeps aged media in the conversation |
|
|
351
374
|
| `getSkills()` | `[]` | First-class Agent Skills sources |
|
|
375
|
+
| `skillWorkspace` | `false` | Project skills into the Workspace as files; `{}` enables with defaults |
|
|
352
376
|
| `getSkillScriptRunner()` | `null` | Optional runner for `run_skill_script` |
|
|
353
377
|
| `getExtensions()` | `[]` | Sandboxed extension declarations (load order) |
|
|
354
378
|
| `extensionLoader` | `undefined` | `WorkerLoader` binding — enables extensions |
|
|
@@ -555,8 +579,8 @@ overflow could not be recovered, and `undefined` otherwise.
|
|
|
555
579
|
|
|
556
580
|
`classifyChatError` maps a raw provider error to a provider-agnostic category
|
|
557
581
|
(`"context_overflow" | "rate_limit" | "transient" | "fatal" | "unknown"`).
|
|
558
|
-
Think ships no provider-specific matching in core
|
|
559
|
-
split as the `
|
|
582
|
+
Think ships no provider-specific matching in core: the app owns it, the same
|
|
583
|
+
split as the `summarize` function passed to `createCompactFunction()`. Today it drives only
|
|
560
584
|
context-overflow recovery: it is consulted when a turn errors and
|
|
561
585
|
`contextOverflow.reactive` is enabled, and only `"context_overflow"` is acted on
|
|
562
586
|
(other categories are reserved for future use). For the common case, assign the
|
|
@@ -729,53 +753,131 @@ When the LLM calls a client tool, the tool call chunk is sent to the client. The
|
|
|
729
753
|
|
|
730
754
|
Tool approval flows are also supported via `CF_AGENT_TOOL_APPROVAL`.
|
|
731
755
|
|
|
732
|
-
### Session and context
|
|
756
|
+
### Session and context
|
|
757
|
+
|
|
758
|
+
Think splits conversation storage from prompt assembly. `agents/sessions` stores
|
|
759
|
+
messages; `agents/context` builds the system prompt. Think wires both during
|
|
760
|
+
`onStart`.
|
|
733
761
|
|
|
734
|
-
|
|
762
|
+
`configureSession()` configures the default session handle: compaction and
|
|
763
|
+
search.
|
|
735
764
|
|
|
736
765
|
```ts
|
|
766
|
+
import { createCompactFunction, type Session } from "agents/sessions";
|
|
767
|
+
|
|
737
768
|
export class MyAgent extends Think<Env> {
|
|
738
769
|
getModel() { ... }
|
|
739
770
|
|
|
740
771
|
configureSession(session: Session) {
|
|
741
772
|
return session
|
|
742
|
-
.
|
|
743
|
-
|
|
773
|
+
.onCompaction(
|
|
774
|
+
createCompactFunction({
|
|
775
|
+
summarize: (prompt) => this.summarize(prompt),
|
|
776
|
+
keepRecentTokens: 20_000
|
|
777
|
+
})
|
|
778
|
+
)
|
|
779
|
+
.compactAfter(100_000);
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
```
|
|
783
|
+
|
|
784
|
+
`configureContext()` declares the prompt blocks:
|
|
785
|
+
|
|
786
|
+
```ts
|
|
787
|
+
import type { ContextConfig } from "agents/context";
|
|
788
|
+
|
|
789
|
+
export class MyAgent extends Think<Env> {
|
|
790
|
+
configureContext(): ContextConfig[] {
|
|
791
|
+
return [
|
|
792
|
+
{ label: "soul", provider: { get: async () => "You are helpful." } },
|
|
793
|
+
{ label: "memory", description: "Learned facts", maxTokens: 2_000 }
|
|
794
|
+
];
|
|
744
795
|
}
|
|
745
796
|
}
|
|
746
797
|
```
|
|
747
798
|
|
|
799
|
+
A block declared without a `provider` is auto-wired to durable per-agent SQLite,
|
|
800
|
+
so `memory` above is writable through the `set_context` tool with no extra
|
|
801
|
+
wiring. The frozen system prompt is always persisted, so there is nothing to opt
|
|
802
|
+
into: a cold wake reuses the exact prompt string the model already cached.
|
|
803
|
+
|
|
804
|
+
The assembled blocks are available as `this.context` once the Lifecycle has
|
|
805
|
+
started. See [Context](https://github.com/cloudflare/agents/blob/main/docs/agents/context.md)
|
|
806
|
+
for providers, tools, and frozen-prompt behavior.
|
|
807
|
+
|
|
808
|
+
### Upgrading from 0.17
|
|
809
|
+
|
|
810
|
+
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.
|
|
811
|
+
|
|
812
|
+
Two things do change on upgrade:
|
|
813
|
+
|
|
814
|
+
- **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.
|
|
815
|
+
- **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.
|
|
816
|
+
|
|
817
|
+
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.
|
|
818
|
+
|
|
819
|
+
`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).
|
|
820
|
+
|
|
748
821
|
#### Dynamic context blocks
|
|
749
822
|
|
|
750
|
-
|
|
823
|
+
Blocks can be added at runtime, for example by extensions:
|
|
751
824
|
|
|
752
825
|
```ts
|
|
753
|
-
await
|
|
754
|
-
await
|
|
826
|
+
await this.context.addBlock({ label: "notes", description: "User notes" });
|
|
827
|
+
await this.context.refreshSystemPrompt(); // rebuild the prompt
|
|
755
828
|
|
|
756
|
-
|
|
757
|
-
await
|
|
829
|
+
this.context.removeBlock("notes");
|
|
830
|
+
await this.context.refreshSystemPrompt();
|
|
758
831
|
```
|
|
759
832
|
|
|
760
|
-
####
|
|
833
|
+
#### Message storage
|
|
761
834
|
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
835
|
+
Sessions stores MESSAGES; it is not a file store. A message rides in one
|
|
836
|
+
SQLite row until its serialized JSON exceeds the 1.5 MiB row budget; a message
|
|
837
|
+
larger than that is split across continuation rows and reassembled on read.
|
|
838
|
+
Nothing is truncated and no message is too large to store, so there is no size
|
|
839
|
+
error to handle and nothing to configure.
|
|
840
|
+
|
|
841
|
+
Splitting never reclaims database space — the continuation rows live in the
|
|
842
|
+
same Durable Object as the message — and Sessions imposes no upper bound on a
|
|
843
|
+
single message, so one very large write can consume a meaningful share of the
|
|
844
|
+
10 GB an object has. Bounding untrusted input is the application's job. Files
|
|
845
|
+
belong in the Workspace, which spills to R2; put a reference to one in the
|
|
846
|
+
message. This is a storage detail: invisible to the model, and unrelated to
|
|
847
|
+
media eviction.
|
|
848
|
+
|
|
849
|
+
#### Media eviction
|
|
850
|
+
|
|
851
|
+
Media eviction is a context-window technique, not a storage one. Re-sending a
|
|
852
|
+
screenshot the model has already looked at on every later turn is pure cost, so
|
|
853
|
+
once a message has aged past `mediaEviction.keepRecentMessages` (8 by default)
|
|
854
|
+
on the active path, Think takes the media out of the conversation and leaves a
|
|
855
|
+
marker in its place:
|
|
767
856
|
|
|
768
|
-
```ts
|
|
769
|
-
import { R2SkillProvider } from "agents/experimental/memory/session";
|
|
770
|
-
|
|
771
|
-
configureSession(session: Session) {
|
|
772
|
-
return session
|
|
773
|
-
.withContext("skills", {
|
|
774
|
-
provider: new R2SkillProvider(this.env.SKILLS_BUCKET, { prefix: "skills/" })
|
|
775
|
-
})
|
|
776
|
-
.withCachedPrompt();
|
|
777
|
-
}
|
|
778
857
|
```
|
|
858
|
+
[evicted image/png, 812004 bytes; preserved at /attachments/evicted/msg_01H8-0.png]
|
|
859
|
+
```
|
|
860
|
+
|
|
861
|
+
The bytes are written to the Workspace at that path, raw and with their real
|
|
862
|
+
mime type — not as a `data:` URL string. The workspace `read` tool recognises
|
|
863
|
+
`image/*`, so when the agent decides it needs the picture again it reads the
|
|
864
|
+
path out of the marker and the actual image goes back into context. Eviction is
|
|
865
|
+
visible to the model and lossy on purpose.
|
|
866
|
+
|
|
867
|
+
Passes are bounded (`maxRowsPerPass`, 64 by default) and run in the background
|
|
868
|
+
after a turn or a hydration read, rescheduling while a backlog remains. Only
|
|
869
|
+
payloads of at least `minPartBytes` are evicted, and `keepRecentMessages` is
|
|
870
|
+
clamped to the four messages the model replays at full fidelity. Once a row is
|
|
871
|
+
rewritten the Sessions attachment reference is dropped and the blob is reaped,
|
|
872
|
+
so the bytes exist in exactly one place: the Workspace file.
|
|
873
|
+
|
|
874
|
+
`mediaEviction: false` keeps aged media in the conversation, so the model keeps
|
|
875
|
+
seeing it. It does not change where Sessions keeps the bytes.
|
|
876
|
+
|
|
877
|
+
Startup hydration reads a recent window bounded by `hydrationByteBudget`
|
|
878
|
+
(32 MiB by default). The budget charges each row its stored bytes plus the
|
|
879
|
+
attachment bytes it re-inflates, so it bounds isolate memory rather than the
|
|
880
|
+
on-disk footprint.
|
|
779
881
|
|
|
780
882
|
### MCP integration
|
|
781
883
|
|
|
@@ -360,6 +360,7 @@ function chatSdkMessenger(options) {
|
|
|
360
360
|
var ThinkMessengerRuntime = class {
|
|
361
361
|
constructor(definitions, host) {
|
|
362
362
|
this.host = host;
|
|
363
|
+
this.liveReplies = /* @__PURE__ */ new Map();
|
|
363
364
|
this.definitionsByAdapterName = /* @__PURE__ */ new Map();
|
|
364
365
|
this.definitionsById = /* @__PURE__ */ new Map();
|
|
365
366
|
this.definitions = normalizeMessengers(definitions);
|
|
@@ -390,7 +391,7 @@ var ThinkMessengerRuntime = class {
|
|
|
390
391
|
this.chat = chat;
|
|
391
392
|
return chat.webhooks[definition.adapterName](request);
|
|
392
393
|
}
|
|
393
|
-
async handleFiberRecovery(ctx) {
|
|
394
|
+
async handleFiberRecovery(ctx, options) {
|
|
394
395
|
if (ctx.name !== "think:messenger-reply") return false;
|
|
395
396
|
const snapshot = parseMessengerReplySnapshot(ctx.snapshot);
|
|
396
397
|
if (!snapshot) return false;
|
|
@@ -400,6 +401,10 @@ var ThinkMessengerRuntime = class {
|
|
|
400
401
|
const mode = messengerReplyRecoveryMode(snapshot);
|
|
401
402
|
if (mode === "answer") {
|
|
402
403
|
await this.answer(definition, snapshot.event, thread, void 0, snapshot.event, async (nextSnapshot) => {
|
|
404
|
+
if (options?.persistRecoverySnapshot) {
|
|
405
|
+
await options.persistRecoverySnapshot(nextSnapshot);
|
|
406
|
+
return;
|
|
407
|
+
}
|
|
403
408
|
await this.host.resolveFiber(ctx.id, {
|
|
404
409
|
snapshot: nextSnapshot,
|
|
405
410
|
status: nextSnapshot.stage === "completed" ? "completed" : "interrupted"
|
|
@@ -409,10 +414,10 @@ var ThinkMessengerRuntime = class {
|
|
|
409
414
|
}
|
|
410
415
|
if (mode === "apologize") {
|
|
411
416
|
await thread.post(definition.delivery?.interruptedResponseText ?? "Sorry, my reply was interrupted. Please send your message again if you'd like me to retry.");
|
|
412
|
-
await this.host.resolveFiber(ctx.id, { status: "completed" });
|
|
417
|
+
if (!options?.persistRecoverySnapshot) await this.host.resolveFiber(ctx.id, { status: "completed" });
|
|
413
418
|
return true;
|
|
414
419
|
}
|
|
415
|
-
await this.host.resolveFiber(ctx.id, { status: "completed" });
|
|
420
|
+
if (!options?.persistRecoverySnapshot) await this.host.resolveFiber(ctx.id, { status: "completed" });
|
|
416
421
|
return true;
|
|
417
422
|
}
|
|
418
423
|
createChat() {
|
|
@@ -472,38 +477,51 @@ var ThinkMessengerRuntime = class {
|
|
|
472
477
|
});
|
|
473
478
|
return chat.registerSingleton();
|
|
474
479
|
}
|
|
480
|
+
/** Whether this isolate still holds the live closure for one reply. */
|
|
481
|
+
hasLiveReply(nonce) {
|
|
482
|
+
return this.liveReplies.has(nonce);
|
|
483
|
+
}
|
|
484
|
+
/**
|
|
485
|
+
* The durable "accepted" snapshot for one live reply, when its closure is
|
|
486
|
+
* still held. The task definition persists this BEFORE delivery begins:
|
|
487
|
+
* an isolate lost mid-answer recovers through it, and without it replay
|
|
488
|
+
* could neither deliver nor apologize.
|
|
489
|
+
*/
|
|
490
|
+
initialReplySnapshot(nonce) {
|
|
491
|
+
const entry = this.liveReplies.get(nonce);
|
|
492
|
+
if (!entry) return void 0;
|
|
493
|
+
return messengerReplySnapshot("accepted", entry.snapshotEvent, entry.snapshotThread);
|
|
494
|
+
}
|
|
495
|
+
/** Execute one live (same-isolate) reply under the given fiber context. */
|
|
496
|
+
async executeLiveReply(nonce, fiber) {
|
|
497
|
+
const entry = this.liveReplies.get(nonce);
|
|
498
|
+
if (!entry) throw new Error("Messenger reply closure is no longer available in this isolate");
|
|
499
|
+
await this.answer(entry.definition, entry.event, entry.thread, fiber, entry.snapshotEvent);
|
|
500
|
+
}
|
|
475
501
|
async enqueueReply(definition, event, thread) {
|
|
476
502
|
const snapshotEvent = serializableMessengerEvent(event);
|
|
477
503
|
const snapshotThread = thread.toJSON();
|
|
478
|
-
const
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
messageId: event.message?.id,
|
|
486
|
-
provider: event.provider,
|
|
487
|
-
threadId: event.thread.id
|
|
488
|
-
},
|
|
489
|
-
waitForCompletion: true
|
|
504
|
+
const nonce = crypto.randomUUID();
|
|
505
|
+
this.liveReplies.set(nonce, {
|
|
506
|
+
definition,
|
|
507
|
+
event,
|
|
508
|
+
thread,
|
|
509
|
+
snapshotEvent,
|
|
510
|
+
snapshotThread
|
|
490
511
|
});
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
}
|
|
512
|
+
try {
|
|
513
|
+
await this.host._runMessengerReplyTask({
|
|
514
|
+
nonce,
|
|
515
|
+
idempotencyKey: idempotencyKeyForEvent(event),
|
|
516
|
+
metadata: {
|
|
517
|
+
messengerId: event.messengerId,
|
|
518
|
+
messageId: event.message?.id,
|
|
519
|
+
provider: event.provider,
|
|
520
|
+
threadId: event.thread.id
|
|
521
|
+
}
|
|
501
522
|
});
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
if (mode === "apologize") {
|
|
505
|
-
await thread.post(definition.delivery?.interruptedResponseText ?? "Sorry, my reply was interrupted. Please send your message again if you'd like me to retry.").catch(() => void 0);
|
|
506
|
-
await this.host.resolveFiber(result.fiberId, { status: "completed" });
|
|
523
|
+
} finally {
|
|
524
|
+
this.liveReplies.delete(nonce);
|
|
507
525
|
}
|
|
508
526
|
}
|
|
509
527
|
async answer(definition, event, thread, fiber, snapshotEvent = serializableMessengerEvent(event), checkpoint) {
|
|
@@ -753,4 +771,4 @@ function validatePath(path, id) {
|
|
|
753
771
|
//#endregion
|
|
754
772
|
export { parseMessengerReplySnapshot as C, toMessengerUserMessage as D, serializableMessengerEvent as E, messengerReplySnapshot as S, resolveChannelSpeakerLabel as T, TextStreamCallback as _, defaultConversationName as a, messengerReplyFailureMode as b, resolveSelfMention as c, toMessengerMessage as d, toMessengerThread as f, MESSENGER_REPLY_FIBER_NAME as g, INTERRUPTED_MESSENGER_RESPONSE as h, defaultChatSdkEvent as i, toMessengerAttachment as l, ERROR_MESSENGER_RESPONSE as m, ThinkMessengerStateAgent as n, idempotencyKeyForEvent as o, EMPTY_MESSENGER_RESPONSE as p, chatSdkMessenger as r, normalizeMessengers as s, ThinkMessengerRuntime as t, toMessengerAuthor as u, defaultDeliveryTag as v, messengerContextFromEvent as w, messengerReplyRecoveryMode as x, deliverMessengerReply as y };
|
|
755
773
|
|
|
756
|
-
//# sourceMappingURL=chat-sdk-
|
|
774
|
+
//# sourceMappingURL=chat-sdk-B77QwYuj.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"chat-sdk-B77QwYuj.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 /**\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}\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 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(\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 ): 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 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 \"Sorry, my reply was interrupted. Please send your message again if you'd like me to retry.\"\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 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 /** 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 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,MAAM,OAAO,KAAK,IAAI,KAAA;GACrD,OAAO,MAAM,OAAO;EACtB,IACA,KAAA;EACJ,SAAS,MAAM,UACX;GACE,aAAa,MAAM,QAAQ,YAAY,KAAK,gBAAgB;IAC1D,eAAe,WAAW,gBACtB,EAAE,GAAG,WAAW,cAAc,IAC9B,KAAA;IACJ,IAAI,WAAW;IACf,WAAW,WAAW;IACtB,MAAM,WAAW;IACjB,MAAM,WAAW;IACjB,MAAM,WAAW;IACjB,KAAK,WAAW;GAClB,EAAE;GACF,QAAQ,EAAE,GAAG,MAAM,QAAQ,OAAO;GAClC,WAAW,MAAM,QAAQ;GACzB,IAAI,MAAM,QAAQ;GAClB,WAAW,MAAM,QAAQ;GACzB,mBAAmB,MAAM,QAAQ;GACjC,MAAM,MAAM,QAAQ;EACtB,IACA,KAAA;CACN;AACF;AAYA,SAAgB,2BACd,QACA,qBACoB;CACpB,IAAI,CAAC,QACH;CAGF,IAAI,qBAAqB;EACvB,MAAM,QAAQ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
52
|
/**
|
|
53
53
|
* Bridge providers that adapt extension Worker RPC into Session's
|
|
54
|
-
* ContextProvider /
|
|
54
|
+
* ContextProvider / WritableContextProvider interfaces.
|
|
55
55
|
*
|
|
56
56
|
* When an extension declares context blocks in its manifest, Think creates
|
|
57
57
|
* a bridge provider for each block. The bridge delegates `get()`, `load()`,
|
package/dist/extensions/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { a as _assertClassBrand, s as _classPrivateMethodInitSpec, t as ExtensionManager } from "../manager-Cb3DNZgp.js";
|
|
2
2
|
import { WorkerEntrypoint } from "cloudflare:workers";
|
|
3
3
|
//#region src/extensions/host-bridge.ts
|
|
4
4
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/extensions/host-bridge.ts","../../src/extensions/bridge-provider.ts"],"sourcesContent":["/**\n * HostBridgeLoopback — a WorkerEntrypoint that provides controlled workspace\n * access to extension Workers loaded via WorkerLoader.\n *\n * This is a loopback: the extension worker's `env.host` binding points here,\n * and each method call resolves the parent agent via `ctx.exports`, then\n * delegates to the agent's workspace proxy methods (`_hostReadFile`, etc.).\n *\n * Props carry serializable identifiers (agent class name, agent ID, and\n * permissions) so the binding survives across requests and hibernation.\n *\n * Users must re-export this class from their worker entry point:\n *\n * ```typescript\n * export { HostBridgeLoopback } from \"@cloudflare/think/extensions\";\n * ```\n *\n * @experimental The API surface may change before stabilizing.\n */\n\nimport { WorkerEntrypoint } from \"cloudflare:workers\";\nimport type { ExtensionPermissions } from \"./types\";\n\nexport type HostBridgeLoopbackProps = {\n agentClassName: string;\n agentId: string;\n permissions: ExtensionPermissions;\n /** Namespaced context labels this extension declared (for \"own\" write validation). */\n ownContextLabels?: string[];\n};\n\nexport class HostBridgeLoopback extends WorkerEntrypoint<\n Record<string, unknown>,\n HostBridgeLoopbackProps\n> {\n private _permissions = this.ctx.props.permissions;\n\n private _getAgent() {\n const { agentClassName, agentId } = this.ctx.props;\n // @ts-expect-error — experimental: ctx.exports on WorkerEntrypoint\n const ns = this.ctx.exports[agentClassName] as DurableObjectNamespace;\n return ns.get(ns.idFromString(agentId));\n }\n\n // ── Permission checks ──────────────────────────────────────────\n\n #requireWorkspace(level: \"read\" | \"read-write\"): void {\n const ws = this._permissions.workspace ?? \"none\";\n if (ws === \"none\") {\n throw new Error(\"Extension error: no workspace permission declared\");\n }\n if (level === \"read-write\" && ws !== \"read-write\") {\n throw new Error(\n \"Extension error: workspace write permission required, but only read granted\"\n );\n }\n }\n\n #requireContextRead(label: string): void {\n const ctx = this._permissions.context;\n if (!ctx?.read) {\n throw new Error(\"Extension error: no context read permission declared\");\n }\n if (ctx.read !== \"all\" && !ctx.read.includes(label)) {\n throw new Error(\n `Extension error: no read permission for context label \"${label}\"`\n );\n }\n }\n\n #requireContextWrite(label: string): void {\n const ctx = this._permissions.context;\n if (!ctx?.write) {\n throw new Error(\"Extension error: no context write permission declared\");\n }\n if (ctx.write === \"own\") {\n const owned = this.ctx.props.ownContextLabels ?? [];\n if (!owned.includes(label)) {\n throw new Error(\n `Extension error: label \"${label}\" is not owned by this extension`\n );\n }\n } else if (!ctx.write.includes(label)) {\n throw new Error(\n `Extension error: no write permission for context label \"${label}\"`\n );\n }\n }\n\n #requireMessages(): void {\n if (this._permissions.messages !== \"read\") {\n throw new Error(\"Extension error: no messages read permission declared\");\n }\n }\n\n #requireSendMessage(): void {\n if (!this._permissions.session?.sendMessage) {\n throw new Error(\n \"Extension error: no session.sendMessage permission declared\"\n );\n }\n }\n\n #requireSessionMetadata(): void {\n if (!this._permissions.session?.metadata) {\n throw new Error(\n \"Extension error: no session.metadata permission declared\"\n );\n }\n }\n\n // ── Workspace (existing) ───────────────────────────────────────\n\n async readFile(path: string): Promise<string | null> {\n this.#requireWorkspace(\"read\");\n return (\n this._getAgent() as unknown as {\n _hostReadFile(path: string): Promise<string | null>;\n }\n )._hostReadFile(path);\n }\n\n async writeFile(path: string, content: string): Promise<void> {\n this.#requireWorkspace(\"read-write\");\n return (\n this._getAgent() as unknown as {\n _hostWriteFile(path: string, content: string): Promise<void>;\n }\n )._hostWriteFile(path, content);\n }\n\n async deleteFile(path: string): Promise<boolean> {\n this.#requireWorkspace(\"read-write\");\n return (\n this._getAgent() as unknown as {\n _hostDeleteFile(path: string): Promise<boolean>;\n }\n )._hostDeleteFile(path);\n }\n\n async listFiles(\n dir: string\n ): Promise<\n Array<{ name: string; type: string; size: number; path: string }>\n > {\n this.#requireWorkspace(\"read\");\n return (\n this._getAgent() as unknown as {\n _hostListFiles(\n dir: string\n ): Promise<\n Array<{ name: string; type: string; size: number; path: string }>\n >;\n }\n )._hostListFiles(dir);\n }\n\n // ── Context blocks (new) ───────────────────────────────────────\n\n async getContext(label: string): Promise<string | null> {\n this.#requireContextRead(label);\n return (\n this._getAgent() as unknown as {\n _hostGetContext(label: string): Promise<string | null>;\n }\n )._hostGetContext(label);\n }\n\n async setContext(label: string, content: string): Promise<void> {\n this.#requireContextWrite(label);\n return (\n this._getAgent() as unknown as {\n _hostSetContext(label: string, content: string): Promise<void>;\n }\n )._hostSetContext(label, content);\n }\n\n // ── Messages (new) ────────────────────────────────────────────\n\n async getMessages(\n limit?: number\n ): Promise<Array<{ id: string; role: string; content: string }>> {\n this.#requireMessages();\n return (\n this._getAgent() as unknown as {\n _hostGetMessages(\n limit?: number\n ): Promise<Array<{ id: string; role: string; content: string }>>;\n }\n )._hostGetMessages(limit);\n }\n\n async sendMessage(content: string): Promise<void> {\n this.#requireSendMessage();\n return (\n this._getAgent() as unknown as {\n _hostSendMessage(content: string): Promise<void>;\n }\n )._hostSendMessage(content);\n }\n\n // ── Session metadata (new) ────────────────────────────────────\n\n async getSessionInfo(): Promise<{ messageCount: number }> {\n this.#requireSessionMetadata();\n return (\n this._getAgent() as unknown as {\n _hostGetSessionInfo(): Promise<{ messageCount: number }>;\n }\n )._hostGetSessionInfo();\n }\n}\n","/**\n * Bridge providers that adapt extension Worker RPC into Session's\n * ContextProvider / SkillProvider / WritableContextProvider interfaces.\n *\n * When an extension declares context blocks in its manifest, Think creates\n * a bridge provider for each block. The bridge delegates `get()`, `load()`,\n * and `set()` to the extension Worker's entrypoint via RPC.\n *\n * This allows extensions to contribute context blocks to the Session's\n * system prompt without Session knowing about the extension system.\n */\n\ninterface ExtensionContextEntrypoint {\n contextGet(label: string): Promise<string | null>;\n contextLoad?(label: string, key: string): Promise<string | null>;\n contextSet?(\n label: string,\n key: string,\n content: string,\n description?: string\n ): Promise<void>;\n}\n\n/**\n * A readonly context provider backed by an extension Worker.\n * Delegates `get()` to the extension's `contextGet` RPC method.\n */\nexport class ExtensionContextBridge {\n protected _label: string;\n protected _entrypoint: ExtensionContextEntrypoint;\n\n constructor(label: string, entrypoint: ExtensionContextEntrypoint) {\n this._label = label;\n this._entrypoint = entrypoint;\n }\n\n init(_label: string): void {}\n\n async get(): Promise<string | null> {\n return this._entrypoint.contextGet(this._label);\n }\n}\n\n/**\n * A writable context provider backed by an extension Worker.\n * Delegates `get()` and `set()` to the extension's RPC methods.\n */\nexport class ExtensionWritableBridge extends ExtensionContextBridge {\n async set(content: string): Promise<void> {\n await this._entrypoint.contextSet?.(this._label, \"\", content);\n }\n}\n\n/**\n * A skill provider backed by an extension Worker.\n * Delegates `get()`, `load()`, and optionally `set()` to the extension's RPC methods.\n */\nexport class ExtensionSkillBridge extends ExtensionContextBridge {\n async load(key: string): Promise<string | null> {\n return (await this._entrypoint.contextLoad?.(this._label, key)) ?? null;\n }\n\n async set(key: string, content: string, description?: string): Promise<void> {\n await this._entrypoint.contextSet?.(this._label, key, content, description);\n }\n}\n\n/**\n * Create the appropriate bridge provider based on the context block type.\n */\nexport function createBridgeProvider(\n label: string,\n type: \"readonly\" | \"writable\" | \"skill\" | \"searchable\",\n entrypoint: ExtensionContextEntrypoint\n) {\n switch (type) {\n case \"skill\":\n return new ExtensionSkillBridge(label, entrypoint);\n case \"writable\":\n return new ExtensionWritableBridge(label, entrypoint);\n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,QACjC,MAAM,IAAI,MAAM,uDAAuD;AAE3E;AAEA,SAAA,sBAA4B;CAC1B,IAAI,CAAC,KAAK,aAAa,SAAS,aAC9B,MAAM,IAAI,MACR,6DACF;AAEJ;AAEA,SAAA,0BAAgC;CAC9B,IAAI,CAAC,KAAK,aAAa,SAAS,UAC9B,MAAM,IAAI,MACR,0DACF;AAEJ;;;;;;;AClFF,IAAa,yBAAb,MAAoC;CAIlC,YAAY,OAAe,YAAwC;EACjE,KAAK,SAAS;EACd,KAAK,cAAc;CACrB;CAEA,KAAK,QAAsB,CAAC;CAE5B,MAAM,MAA8B;EAClC,OAAO,KAAK,YAAY,WAAW,KAAK,MAAM;CAChD;AACF;;;;;AAMA,IAAa,0BAAb,cAA6C,uBAAuB;CAClE,MAAM,IAAI,SAAgC;EACxC,MAAM,KAAK,YAAY,aAAa,KAAK,QAAQ,IAAI,OAAO;CAC9D;AACF;;;;;AAMA,IAAa,uBAAb,cAA0C,uBAAuB;CAC/D,MAAM,KAAK,KAAqC;EAC9C,OAAQ,MAAM,KAAK,YAAY,cAAc,KAAK,QAAQ,GAAG,KAAM;CACrE;CAEA,MAAM,IAAI,KAAa,SAAiB,aAAqC;EAC3E,MAAM,KAAK,YAAY,aAAa,KAAK,QAAQ,KAAK,SAAS,WAAW;CAC5E;AACF;;;;AAKA,SAAgB,qBACd,OACA,MACA,YACA;CACA,QAAQ,MAAR;EACE,KAAK,SACH,OAAO,IAAI,qBAAqB,OAAO,UAAU;EACnD,KAAK,YACH,OAAO,IAAI,wBAAwB,OAAO,UAAU;EAGtD,SACE,OAAO,IAAI,uBAAuB,OAAO,UAAU;CACvD;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/extensions/host-bridge.ts","../../src/extensions/bridge-provider.ts"],"sourcesContent":["/**\n * HostBridgeLoopback — a WorkerEntrypoint that provides controlled workspace\n * access to extension Workers loaded via WorkerLoader.\n *\n * This is a loopback: the extension worker's `env.host` binding points here,\n * and each method call resolves the parent agent via `ctx.exports`, then\n * delegates to the agent's workspace proxy methods (`_hostReadFile`, etc.).\n *\n * Props carry serializable identifiers (agent class name, agent ID, and\n * permissions) so the binding survives across requests and hibernation.\n *\n * Users must re-export this class from their worker entry point:\n *\n * ```typescript\n * export { HostBridgeLoopback } from \"@cloudflare/think/extensions\";\n * ```\n *\n * @experimental The API surface may change before stabilizing.\n */\n\nimport { WorkerEntrypoint } from \"cloudflare:workers\";\nimport type { ExtensionPermissions } from \"./types\";\n\nexport type HostBridgeLoopbackProps = {\n agentClassName: string;\n agentId: string;\n permissions: ExtensionPermissions;\n /** Namespaced context labels this extension declared (for \"own\" write validation). */\n ownContextLabels?: string[];\n};\n\nexport class HostBridgeLoopback extends WorkerEntrypoint<\n Record<string, unknown>,\n HostBridgeLoopbackProps\n> {\n private _permissions = this.ctx.props.permissions;\n\n private _getAgent() {\n const { agentClassName, agentId } = this.ctx.props;\n // @ts-expect-error — experimental: ctx.exports on WorkerEntrypoint\n const ns = this.ctx.exports[agentClassName] as DurableObjectNamespace;\n return ns.get(ns.idFromString(agentId));\n }\n\n // ── Permission checks ──────────────────────────────────────────\n\n #requireWorkspace(level: \"read\" | \"read-write\"): void {\n const ws = this._permissions.workspace ?? \"none\";\n if (ws === \"none\") {\n throw new Error(\"Extension error: no workspace permission declared\");\n }\n if (level === \"read-write\" && ws !== \"read-write\") {\n throw new Error(\n \"Extension error: workspace write permission required, but only read granted\"\n );\n }\n }\n\n #requireContextRead(label: string): void {\n const ctx = this._permissions.context;\n if (!ctx?.read) {\n throw new Error(\"Extension error: no context read permission declared\");\n }\n if (ctx.read !== \"all\" && !ctx.read.includes(label)) {\n throw new Error(\n `Extension error: no read permission for context label \"${label}\"`\n );\n }\n }\n\n #requireContextWrite(label: string): void {\n const ctx = this._permissions.context;\n if (!ctx?.write) {\n throw new Error(\"Extension error: no context write permission declared\");\n }\n if (ctx.write === \"own\") {\n const owned = this.ctx.props.ownContextLabels ?? [];\n if (!owned.includes(label)) {\n throw new Error(\n `Extension error: label \"${label}\" is not owned by this extension`\n );\n }\n } else if (!ctx.write.includes(label)) {\n throw new Error(\n `Extension error: no write permission for context label \"${label}\"`\n );\n }\n }\n\n #requireMessages(): void {\n if (this._permissions.messages !== \"read\") {\n throw new Error(\"Extension error: no messages read permission declared\");\n }\n }\n\n #requireSendMessage(): void {\n if (!this._permissions.session?.sendMessage) {\n throw new Error(\n \"Extension error: no session.sendMessage permission declared\"\n );\n }\n }\n\n #requireSessionMetadata(): void {\n if (!this._permissions.session?.metadata) {\n throw new Error(\n \"Extension error: no session.metadata permission declared\"\n );\n }\n }\n\n // ── Workspace (existing) ───────────────────────────────────────\n\n async readFile(path: string): Promise<string | null> {\n this.#requireWorkspace(\"read\");\n return (\n this._getAgent() as unknown as {\n _hostReadFile(path: string): Promise<string | null>;\n }\n )._hostReadFile(path);\n }\n\n async writeFile(path: string, content: string): Promise<void> {\n this.#requireWorkspace(\"read-write\");\n return (\n this._getAgent() as unknown as {\n _hostWriteFile(path: string, content: string): Promise<void>;\n }\n )._hostWriteFile(path, content);\n }\n\n async deleteFile(path: string): Promise<boolean> {\n this.#requireWorkspace(\"read-write\");\n return (\n this._getAgent() as unknown as {\n _hostDeleteFile(path: string): Promise<boolean>;\n }\n )._hostDeleteFile(path);\n }\n\n async listFiles(\n dir: string\n ): Promise<\n Array<{ name: string; type: string; size: number; path: string }>\n > {\n this.#requireWorkspace(\"read\");\n return (\n this._getAgent() as unknown as {\n _hostListFiles(\n dir: string\n ): Promise<\n Array<{ name: string; type: string; size: number; path: string }>\n >;\n }\n )._hostListFiles(dir);\n }\n\n // ── Context blocks (new) ───────────────────────────────────────\n\n async getContext(label: string): Promise<string | null> {\n this.#requireContextRead(label);\n return (\n this._getAgent() as unknown as {\n _hostGetContext(label: string): Promise<string | null>;\n }\n )._hostGetContext(label);\n }\n\n async setContext(label: string, content: string): Promise<void> {\n this.#requireContextWrite(label);\n return (\n this._getAgent() as unknown as {\n _hostSetContext(label: string, content: string): Promise<void>;\n }\n )._hostSetContext(label, content);\n }\n\n // ── Messages (new) ────────────────────────────────────────────\n\n async getMessages(\n limit?: number\n ): Promise<Array<{ id: string; role: string; content: string }>> {\n this.#requireMessages();\n return (\n this._getAgent() as unknown as {\n _hostGetMessages(\n limit?: number\n ): Promise<Array<{ id: string; role: string; content: string }>>;\n }\n )._hostGetMessages(limit);\n }\n\n async sendMessage(content: string): Promise<void> {\n this.#requireSendMessage();\n return (\n this._getAgent() as unknown as {\n _hostSendMessage(content: string): Promise<void>;\n }\n )._hostSendMessage(content);\n }\n\n // ── Session metadata (new) ────────────────────────────────────\n\n async getSessionInfo(): Promise<{ messageCount: number }> {\n this.#requireSessionMetadata();\n return (\n this._getAgent() as unknown as {\n _hostGetSessionInfo(): Promise<{ messageCount: number }>;\n }\n )._hostGetSessionInfo();\n }\n}\n","/**\n * Bridge providers that adapt extension Worker RPC into Session's\n * ContextProvider / WritableContextProvider interfaces.\n *\n * When an extension declares context blocks in its manifest, Think creates\n * a bridge provider for each block. The bridge delegates `get()`, `load()`,\n * and `set()` to the extension Worker's entrypoint via RPC.\n *\n * This allows extensions to contribute context blocks to the Session's\n * system prompt without Session knowing about the extension system.\n */\n\ninterface ExtensionContextEntrypoint {\n contextGet(label: string): Promise<string | null>;\n contextLoad?(label: string, key: string): Promise<string | null>;\n contextSet?(\n label: string,\n key: string,\n content: string,\n description?: string\n ): Promise<void>;\n}\n\n/**\n * A readonly context provider backed by an extension Worker.\n * Delegates `get()` to the extension's `contextGet` RPC method.\n */\nexport class ExtensionContextBridge {\n protected _label: string;\n protected _entrypoint: ExtensionContextEntrypoint;\n\n constructor(label: string, entrypoint: ExtensionContextEntrypoint) {\n this._label = label;\n this._entrypoint = entrypoint;\n }\n\n init(_label: string): void {}\n\n async get(): Promise<string | null> {\n return this._entrypoint.contextGet(this._label);\n }\n}\n\n/**\n * A writable context provider backed by an extension Worker.\n * Delegates `get()` and `set()` to the extension's RPC methods.\n */\nexport class ExtensionWritableBridge extends ExtensionContextBridge {\n async set(content: string): Promise<void> {\n await this._entrypoint.contextSet?.(this._label, \"\", content);\n }\n}\n\n/**\n * A skill provider backed by an extension Worker.\n * Delegates `get()`, `load()`, and optionally `set()` to the extension's RPC methods.\n */\nexport class ExtensionSkillBridge extends ExtensionContextBridge {\n async load(key: string): Promise<string | null> {\n return (await this._entrypoint.contextLoad?.(this._label, key)) ?? null;\n }\n\n async set(key: string, content: string, description?: string): Promise<void> {\n await this._entrypoint.contextSet?.(this._label, key, content, description);\n }\n}\n\n/**\n * Create the appropriate bridge provider based on the context block type.\n */\nexport function createBridgeProvider(\n label: string,\n type: \"readonly\" | \"writable\" | \"skill\" | \"searchable\",\n entrypoint: ExtensionContextEntrypoint\n) {\n switch (type) {\n case \"skill\":\n return new ExtensionSkillBridge(label, entrypoint);\n case \"writable\":\n return new ExtensionWritableBridge(label, entrypoint);\n case \"readonly\":\n case \"searchable\":\n default:\n return new ExtensionContextBridge(label, entrypoint);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA+BA,IAAa,qBAAb,cAAwC,iBAGtC;;;;EACA,KAAQ,eAAe,KAAK,IAAI,MAAM;;CAEtC,YAAoB;EAClB,MAAM,EAAE,gBAAgB,YAAY,KAAK,IAAI;EAE7C,MAAM,KAAK,KAAK,IAAI,QAAQ;EAC5B,OAAO,GAAG,IAAI,GAAG,aAAa,OAAO,CAAC;CACxC;CAuEA,MAAM,SAAS,MAAsC;EACnD,kBAAA,2BAAA,MAAA,iBAAA,CAAA,CAAA,KAAA,MAAuB,MAAM;EAC7B,OACE,KAAK,UAAU,CAAC,CAGhB,cAAc,IAAI;CACtB;CAEA,MAAM,UAAU,MAAc,SAAgC;EAC5D,kBAAA,2BAAA,MAAA,iBAAA,CAAA,CAAA,KAAA,MAAuB,YAAY;EACnC,OACE,KAAK,UAAU,CAAC,CAGhB,eAAe,MAAM,OAAO;CAChC;CAEA,MAAM,WAAW,MAAgC;EAC/C,kBAAA,2BAAA,MAAA,iBA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