@cloudflare/think 0.24.0 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +18 -26
  2. package/dist/{chat-sdk-BEjKXjCm.js → chat-sdk-4Nu96eDX.js} +375 -256
  3. package/dist/chat-sdk-4Nu96eDX.js.map +1 -0
  4. package/dist/extensions/index.d.ts +30 -72
  5. package/dist/extensions/index.js +45 -47
  6. package/dist/extensions/index.js.map +1 -1
  7. package/dist/{fetch-DO3uQ9py.js → fetch-BbYxtlff.js} +10 -2
  8. package/dist/fetch-BbYxtlff.js.map +1 -0
  9. package/dist/manager-B3rcb_6p.js +493 -0
  10. package/dist/manager-B3rcb_6p.js.map +1 -0
  11. package/dist/manager-CWGumyKi.d.ts +3391 -0
  12. package/dist/messengers/index.d.ts +54 -66
  13. package/dist/messengers/index.js +2 -2
  14. package/dist/messengers/telegram.d.ts +4 -4
  15. package/dist/messengers/telegram.js +1 -1
  16. package/dist/think.d.ts +2 -2
  17. package/dist/think.js +8493 -10759
  18. package/dist/think.js.map +1 -1
  19. package/dist/tools/extensions.d.ts +1 -1
  20. package/dist/tools/extensions.js +1 -1
  21. package/dist/tools/fetch.js +1 -1
  22. package/dist/workflows.d.ts +5 -2
  23. package/docs/actions.md +12 -0
  24. package/docs/channels.md +10 -4
  25. package/docs/client-tools.md +57 -27
  26. package/docs/context.md +92 -0
  27. package/docs/getting-started.md +2 -2
  28. package/docs/index.md +109 -49
  29. package/docs/lifecycle-hooks.md +10 -21
  30. package/docs/multi-chat.md +5 -5
  31. package/docs/programmatic-submissions.md +28 -10
  32. package/docs/sub-agents.md +45 -51
  33. package/docs/tools.md +31 -3
  34. package/docs/workflows.md +4 -3
  35. package/package.json +13 -8
  36. package/dist/chat-sdk-BEjKXjCm.js.map +0 -1
  37. package/dist/fetch-DO3uQ9py.js.map +0 -1
  38. package/dist/hook-proxy-DY2sBNa0.js +0 -117
  39. package/dist/hook-proxy-DY2sBNa0.js.map +0 -1
  40. package/dist/index-DIQ9oY1t.d.ts +0 -5864
  41. package/dist/manager-CtXhU1fK.d.ts +0 -243
  42. package/dist/manager-sfWIcYJT.js +0 -333
  43. package/dist/manager-sfWIcYJT.js.map +0 -1
@@ -1,7 +1,149 @@
1
+ import { isDurableObjectCodeUpdateReset, isDurableObjectMemoryLimitReset, isPlatformTransientError } from "agents";
2
+ import { registerDeliverySink, sendDelivery } from "agents/internal";
1
3
  import { TextSegmentJoiner } from "agents/chat";
2
4
  import { Chat, Message, ThreadImpl } from "chat";
3
5
  import { ChatSdkStateAgent, createChatSdkState, defaultKeyShard } from "agents/chat-sdk";
6
+ import { NonRetryableError } from "agents/tasks";
4
7
  import { RpcTarget } from "cloudflare:workers";
8
+ //#region src/messengers/reply-task.ts
9
+ /**
10
+ * Messenger replies as deliveries. A webhook's reply is one delivery run:
11
+ * its input is the event and thread, its first attempt answers live, and
12
+ * an attempt after a reset answers again or apologizes, by how far the
13
+ * reply got (the `stage` in its checkpoint).
14
+ *
15
+ * Durable: nothing of its own (the run and its checkpoint belong to Tasks).
16
+ * In memory: the live reply, for as long as the webhook waits on it.
17
+ */
18
+ const MESSENGER_REPLY_SINK = "messenger-reply";
19
+ /** The checkpoint key of how far a reply got. */
20
+ const STAGE = "stage";
21
+ /**
22
+ * The checkpoint key of the reply's event and thread. In the checkpoint,
23
+ * not the run's input: the run is kept once answered (a repeat is a
24
+ * repeat), and its checkpoint, unlike its input, is cleared then, so the
25
+ * message's text is not kept with it.
26
+ */
27
+ const REPLY = "reply";
28
+ /** A reply's own attempt takes as long as its answer: one day at most. */
29
+ const REPLY_ATTEMPT_TIMEOUT_MS = 1440 * 60 * 1e3;
30
+ const isPlatformReset = (error) => isPlatformTransientError(error) || isDurableObjectMemoryLimitReset(error) || isDurableObjectCodeUpdateReset(error);
31
+ /**
32
+ * Post the apology for a reply a reset cut off. A post the platform fails is
33
+ * not sent again (it may have landed): the thread gets `errorText` once
34
+ * instead, so it is not left without a word. A platform reset is thrown on,
35
+ * for the retry. `spent` records that the apology was tried, before the
36
+ * error text is posted: a reset while that is posted does not send the
37
+ * apology a second time.
38
+ *
39
+ * @internal
40
+ */
41
+ async function postApology(thread, apology, errorText, spent) {
42
+ try {
43
+ await thread.post(apology);
44
+ } catch (error) {
45
+ if (isPlatformReset(error)) throw error;
46
+ console.error("[Think] Messenger apology was not posted", error);
47
+ await spent();
48
+ try {
49
+ await thread.post(errorText);
50
+ } catch (failure) {
51
+ if (isPlatformReset(failure)) throw failure;
52
+ console.error("[Think] Messenger failure notice failed", failure);
53
+ }
54
+ }
55
+ }
56
+ /**
57
+ * Answer again or apologize for a reply a reset cut off at `stage`, then
58
+ * answer what queued behind it. A failure `retried` says is tried again
59
+ * (the queue waits for it); any other ends the reply, so it is never
60
+ * answered twice.
61
+ *
62
+ * @internal
63
+ */
64
+ async function recoverMessengerReply(messengers, payload, stage, record, retried = isPlatformReset) {
65
+ try {
66
+ await messengers.recoverReply(payload, stage, record);
67
+ } catch (error) {
68
+ if (retried(error)) throw error;
69
+ messengers.drainAfterRecovery(payload);
70
+ throw new NonRetryableError(error instanceof Error ? error.message : String(error));
71
+ }
72
+ messengers.drainAfterRecovery(payload);
73
+ }
74
+ /**
75
+ * Where reply deliveries go: the first attempt answers live, a later one
76
+ * recovers by the stage the reply reached.
77
+ *
78
+ * @internal
79
+ */
80
+ function messengerReplySink(runtime) {
81
+ return {
82
+ attemptTimeoutMs: REPLY_ATTEMPT_TIMEOUT_MS,
83
+ async deliver(_input, attempt) {
84
+ const messengers = runtime();
85
+ if (!messengers) throw new Error("Messenger runtime is unavailable");
86
+ const record = (stage) => attempt.checkpoint.set(STAGE, stage);
87
+ const live = attempt.local;
88
+ if (live) {
89
+ await live.answer(record);
90
+ return;
91
+ }
92
+ const payload = attempt.checkpoint.get(REPLY);
93
+ if (!payload) return;
94
+ await recoverMessengerReply(messengers, payload, attempt.checkpoint.get(STAGE) ?? "accepted", record);
95
+ },
96
+ onGiveUp(error, _input, progress) {
97
+ console.error("[Think] A messenger reply was given up", error);
98
+ const payload = progress.get(REPLY);
99
+ if (payload) runtime()?.drainAfterRecovery(payload);
100
+ }
101
+ };
102
+ }
103
+ /**
104
+ * Register the sink each reply runs on (`sendMessengerReply`), without the
105
+ * runs think@0.24.0 left.
106
+ *
107
+ * @internal
108
+ */
109
+ function registerMessengerReplySink(tasks, runtime) {
110
+ registerDeliverySink(tasks, MESSENGER_REPLY_SINK, messengerReplySink(runtime));
111
+ }
112
+ /**
113
+ * Accept one reply and answer it here and now. A repeated webhook (same
114
+ * id) joins the reply, or finds it answered.
115
+ *
116
+ * @internal
117
+ */
118
+ function sendMessengerReply(tasks, id, live) {
119
+ return sendDelivery(tasks, MESSENGER_REPLY_SINK, id, {}, void 0, {
120
+ local: live,
121
+ progress: { [REPLY]: live.payload },
122
+ retain: true
123
+ });
124
+ }
125
+ /**
126
+ * The definition think@0.24.0 ran replies on.
127
+ *
128
+ * @internal
129
+ */
130
+ const RELEASED_REPLY_DEFINITION = "__cf_internal_messenger_reply";
131
+ /**
132
+ * A released reply snapshot, as think@0.24.0 kept it.
133
+ *
134
+ * @internal
135
+ */
136
+ function releasedSnapshot(value) {
137
+ if (value === null || typeof value !== "object") return void 0;
138
+ const candidate = value;
139
+ if (candidate.type !== "think:messenger-reply" || candidate.stage !== "accepted" && candidate.stage !== "streaming" && candidate.stage !== "completed" || candidate.event === void 0) return;
140
+ return {
141
+ stage: candidate.stage,
142
+ event: candidate.event,
143
+ thread: candidate.thread
144
+ };
145
+ }
146
+ //#endregion
5
147
  //#region src/messengers/events.ts
6
148
  /**
7
149
  * The context persisted on a messenger turn's user message. Built from the
@@ -137,7 +279,6 @@ function describeAttachments(attachments) {
137
279
  }
138
280
  //#endregion
139
281
  //#region src/messengers/delivery.ts
140
- const MESSENGER_REPLY_FIBER_NAME = "think:messenger-reply";
141
282
  const EMPTY_MESSENGER_RESPONSE = "I couldn't produce a text response. Please try again.";
142
283
  const ERROR_MESSENGER_RESPONSE = "Sorry, I couldn't answer that right now. Please try again.";
143
284
  const INTERRUPTED_MESSENGER_RESPONSE = "Sorry, my reply was interrupted. Please send your message again if you'd like me to retry.";
@@ -294,38 +435,27 @@ function streamChunkFromJson(json) {
294
435
  return null;
295
436
  }
296
437
  }
297
- /** Derive a sensible default tag from a reply stage. */
298
- function defaultDeliveryTag(stage) {
299
- return {
300
- stage,
301
- kind: stage === "completed" ? "final" : "interim",
302
- turnEnded: stage === "completed"
303
- };
304
- }
305
- function messengerReplySnapshot(stage, event, thread, tag) {
306
- return {
307
- event,
308
- stage,
309
- tag: tag ?? defaultDeliveryTag(stage),
310
- thread,
311
- type: MESSENGER_REPLY_FIBER_NAME
312
- };
313
- }
314
- function parseMessengerReplySnapshot(snapshot) {
315
- if (snapshot === null || typeof snapshot !== "object") return null;
316
- const candidate = snapshot;
317
- if (candidate.type !== "think:messenger-reply" || candidate.stage !== "accepted" && candidate.stage !== "streaming" && candidate.stage !== "completed" || candidate.event === void 0) return null;
438
+ /**
439
+ * A messenger event kept as JSON (a reply's delivery input) holds its
440
+ * messages' `createdAt` as strings: give them back as `Date`s.
441
+ *
442
+ * @internal
443
+ */
444
+ function reviveMessengerEvent(event) {
445
+ const revive = (message) => typeof message.createdAt === "string" ? {
446
+ ...message,
447
+ createdAt: new Date(message.createdAt)
448
+ } : message;
318
449
  return {
319
- event: candidate.event,
320
- stage: candidate.stage,
321
- tag: candidate.tag ?? defaultDeliveryTag(candidate.stage),
322
- thread: candidate.thread,
323
- type: MESSENGER_REPLY_FIBER_NAME
450
+ ...event,
451
+ ...event.message && { message: revive(event.message) },
452
+ ...event.skipped && { skipped: event.skipped.map(revive) }
324
453
  };
325
454
  }
326
- function messengerReplyRecoveryMode(snapshot) {
327
- if (snapshot.stage === "accepted") return "answer";
328
- if (snapshot.stage === "streaming") return "apologize";
455
+ /** What a reply cut off at `stage` does on its next attempt. */
456
+ function messengerReplyRecoveryMode(stage) {
457
+ if (stage === "accepted") return "answer";
458
+ if (stage === "streaming") return "apologize";
329
459
  return null;
330
460
  }
331
461
  function messengerReplyFailureMode(hasStreamedText, completedModelTurn = false, expectedDeliveryCompletion = false) {
@@ -350,13 +480,11 @@ async function deliverMessengerReply(options) {
350
480
  const interruptedResponseText = options.policy?.interruptedResponseText ?? "Sorry, my reply was interrupted. Please send your message again if you'd like me to retry.";
351
481
  let completedModelTurn = false;
352
482
  const snapshotEvent = options.snapshotEvent ?? options.event;
353
- const checkpoint = options.checkpoint ?? ((snapshot) => {
354
- options.fiber?.stash(snapshot);
355
- });
483
+ const onStage = options.onStage ?? (() => void 0);
356
484
  const callback = new TextStreamCallback({
357
485
  emptyText: emptyResponseText,
358
486
  onVisibleStart: async () => {
359
- await checkpoint(messengerReplySnapshot("streaming", snapshotEvent, options.snapshotThread));
487
+ await onStage("streaming");
360
488
  },
361
489
  visibleSoftLimit: options.policy?.visibleSoftLimit
362
490
  });
@@ -407,7 +535,7 @@ async function deliverMessengerReply(options) {
407
535
  if (callback.wasInterrupted()) {
408
536
  callback.close();
409
537
  const streamRejected = await post.then(() => false, () => true);
410
- await checkpoint(messengerReplySnapshot("completed", snapshotEvent, options.snapshotThread));
538
+ await onStage("completed");
411
539
  if (callback.targetDeliversRecoveredReply()) {
412
540
  for (const chunk of options.policy?.splitText?.(streamRejected ? callback.textSoFar() : callback.remainingText()) ?? []) await options.surface.post(chunk).catch(() => void 0);
413
541
  return;
@@ -419,16 +547,16 @@ async function deliverMessengerReply(options) {
419
547
  callback.complete();
420
548
  await post;
421
549
  for (const chunk of options.policy?.splitText?.(callback.remainingText()) ?? []) await options.surface.post(chunk);
422
- await checkpoint(messengerReplySnapshot("completed", snapshotEvent, options.snapshotThread));
550
+ await onStage("completed");
423
551
  } catch (error) {
424
552
  callback.fail(error);
425
553
  await post.catch(() => void 0);
426
554
  const failureMode = messengerReplyFailureMode(callback.hasText(), completedModelTurn, options.policy?.isExpectedDeliveryCompletion?.(error, callback));
427
555
  if (failureMode === null) {
428
- await checkpoint(messengerReplySnapshot("completed", snapshotEvent, options.snapshotThread));
556
+ await onStage("completed");
429
557
  return;
430
558
  }
431
- await checkpoint(messengerReplySnapshot("completed", snapshotEvent, options.snapshotThread));
559
+ await onStage("completed");
432
560
  if (failureMode === "apologize") {
433
561
  await options.surface.post(interruptedResponseText).catch(() => void 0);
434
562
  return;
@@ -450,8 +578,9 @@ var ThinkMessengerStateAgent = class extends ChatSdkStateAgent {};
450
578
  * preview. Delivery already shows a typing indicator before the reply starts.
451
579
  */
452
580
  const FALLBACK_STREAMING_PLACEHOLDER_TEXT = null;
453
- /** The posts that deliver a recovered messenger reply, in order. */
581
+ /** The posts that deliver a recovered messenger reply, in order. @internal */
454
582
  function recoveredReplyPosts(definition, input) {
583
+ if (input.notice) return [definition.delivery?.errorResponseText ?? "Sorry, I couldn't answer that right now. Please try again."];
455
584
  if (input.outcome === "interrupted") return [definition.delivery?.interruptedResponseText ?? "Sorry, my reply was interrupted. Please send your message again if you'd like me to retry."];
456
585
  const text = input.text?.trim() ? input.text : "";
457
586
  if (!text) return input.partialPosted ? [] : [definition.delivery?.emptyResponseText ?? "I couldn't produce a text response. Please try again."];
@@ -470,6 +599,35 @@ const DEFAULT_MESSENGER_CONCURRENCY = {
470
599
  };
471
600
  /** The Chat SDK's thread lock TTL (`DEFAULT_LOCK_TTL_MS`). */
472
601
  const CHAT_SDK_LOCK_TTL_MS = 3e4;
602
+ /**
603
+ * Answer the messages queued on `threadId` behind a reply whose isolate
604
+ * died: once the dead holder's lock expires, take the lock and hand the
605
+ * queue to the SDK's own drain. A live holder drains the queue itself,
606
+ * which ends the wait.
607
+ *
608
+ * @internal
609
+ */
610
+ async function drainStrandedQueue(chat, definition, threadId) {
611
+ const internals = chat;
612
+ if (typeof internals.getLockKey !== "function" || typeof internals.drainQueue !== "function") return;
613
+ await chat.initialize();
614
+ const state = chat.getState();
615
+ const lockKey = await internals.getLockKey.call(chat, definition.adapter, threadId);
616
+ const deadline = Date.now() + CHAT_SDK_LOCK_TTL_MS + 5e3;
617
+ while (await state.queueDepth(lockKey) > 0) {
618
+ const lock = await state.acquireLock(lockKey, CHAT_SDK_LOCK_TTL_MS);
619
+ if (lock) {
620
+ try {
621
+ await internals.drainQueue.call(chat, lock, definition.adapter, threadId, lockKey);
622
+ } finally {
623
+ await state.releaseLock(lock);
624
+ }
625
+ return;
626
+ }
627
+ if (Date.now() >= deadline) return;
628
+ await new Promise((resolve) => setTimeout(resolve, 1e3));
629
+ }
630
+ }
473
631
  /** Fill in Think's queue-entry TTL where the setting leaves it unset. */
474
632
  function withMessengerQueueTtl(concurrency) {
475
633
  if (typeof concurrency === "string") return {
@@ -478,7 +636,7 @@ function withMessengerQueueTtl(concurrency) {
478
636
  };
479
637
  return {
480
638
  ...concurrency,
481
- queueEntryTtlMs: concurrency.queueEntryTtlMs ?? 18e5
639
+ queueEntryTtlMs: concurrency.queueEntryTtlMs ?? MESSENGER_QUEUE_ENTRY_TTL_MS
482
640
  };
483
641
  }
484
642
  function chatSdkMessenger(options) {
@@ -490,15 +648,10 @@ function chatSdkMessenger(options) {
490
648
  var ThinkMessengerRuntime = class {
491
649
  constructor(definitions, host, options) {
492
650
  this.host = host;
493
- this.liveReplies = /* @__PURE__ */ new Map();
494
- this.definitionsByAdapterName = /* @__PURE__ */ new Map();
495
651
  this.definitionsById = /* @__PURE__ */ new Map();
496
652
  this.concurrency = withMessengerQueueTtl(options?.concurrency ?? DEFAULT_MESSENGER_CONCURRENCY);
497
653
  this.definitions = normalizeMessengers(definitions);
498
- for (const definition of this.definitions) {
499
- this.definitionsByAdapterName.set(definition.adapterName, definition);
500
- this.definitionsById.set(definition.id, definition);
501
- }
654
+ for (const definition of this.definitions) this.definitionsById.set(definition.id, definition);
502
655
  }
503
656
  get size() {
504
657
  return this.definitions.length;
@@ -522,45 +675,37 @@ var ThinkMessengerRuntime = class {
522
675
  this.chat = chat;
523
676
  return chat.webhooks[definition.adapterName](request);
524
677
  }
525
- async handleFiberRecovery(ctx, options) {
526
- if (ctx.name !== "think:messenger-reply") return false;
527
- const snapshot = parseMessengerReplySnapshot(ctx.snapshot);
528
- if (!snapshot) return false;
529
- const definition = this.definitionsById.get(snapshot.event.messengerId);
530
- if (!definition) throw new Error(`No messenger definition found for recovered messenger ${snapshot.event.messengerId}`);
531
- const thread = this.reviveThread(definition, snapshot.thread);
532
- let handled;
533
- try {
534
- handled = await this.recoverReply(ctx, definition, thread, snapshot, options);
535
- } catch (error) {
536
- if (!options?.retriesAfter?.(error)) this.drainQueuedMessagesInBackground(definition, thread.id);
537
- throw error;
538
- }
539
- this.drainQueuedMessagesInBackground(definition, thread.id);
540
- return handled;
541
- }
542
- async recoverReply(ctx, definition, thread, snapshot, options) {
543
- const mode = messengerReplyRecoveryMode(snapshot);
678
+ /**
679
+ * Answer again, or apologize, for a reply a reset cut off at `stage`.
680
+ *
681
+ * @internal
682
+ */
683
+ async recoverReply(payload, stage, record) {
684
+ const event = reviveMessengerEvent(payload.event);
685
+ const definition = this.definitionsById.get(event.messengerId);
686
+ if (!definition) throw new Error(`No messenger definition found for recovered messenger ${event.messengerId}`);
687
+ const thread = this.reviveThread(definition, payload.thread);
688
+ const mode = messengerReplyRecoveryMode(stage);
544
689
  if (mode === "answer") {
545
- await this.answer(definition, snapshot.event, thread, void 0, snapshot.event, async (nextSnapshot) => {
546
- if (options?.persistRecoverySnapshot) {
547
- await options.persistRecoverySnapshot(nextSnapshot);
548
- return;
549
- }
550
- await this.host.resolveFiber(ctx.id, {
551
- snapshot: nextSnapshot,
552
- status: nextSnapshot.stage === "completed" ? "completed" : "interrupted"
553
- });
554
- });
555
- return true;
690
+ await this.answer(definition, event, thread, record, event);
691
+ return;
556
692
  }
557
693
  if (mode === "apologize") {
558
- await thread.post(definition.delivery?.interruptedResponseText ?? "Sorry, my reply was interrupted. Please send your message again if you'd like me to retry.");
559
- if (!options?.persistRecoverySnapshot) await this.host.resolveFiber(ctx.id, { status: "completed" });
560
- return true;
694
+ await postApology(thread, definition.delivery?.interruptedResponseText ?? "Sorry, my reply was interrupted. Please send your message again if you'd like me to retry.", definition.delivery?.errorResponseText ?? "Sorry, I couldn't answer that right now. Please try again.", () => record("completed"));
695
+ record("completed");
561
696
  }
562
- if (!options?.persistRecoverySnapshot) await this.host.resolveFiber(ctx.id, { status: "completed" });
563
- return true;
697
+ }
698
+ /**
699
+ * After a recovered reply ended or gave up, answer the messages queued
700
+ * behind it.
701
+ *
702
+ * @internal
703
+ */
704
+ drainAfterRecovery(payload) {
705
+ const definition = this.definitionsById.get(payload.event.messengerId);
706
+ if (!definition) return;
707
+ const thread = this.reviveThread(definition, payload.thread);
708
+ this.drainQueuedMessagesInBackground(definition, thread.id);
564
709
  }
565
710
  /**
566
711
  * Messages queued behind a reply are drained only by the Chat SDK handler
@@ -577,155 +722,33 @@ var ThinkMessengerRuntime = class {
577
722
  });
578
723
  }
579
724
  async drainQueuedMessages(definition, threadId) {
580
- const chat = this.chat ??= this.createChat();
581
- const internals = chat;
582
- if (typeof internals.getLockKey !== "function" || typeof internals.drainQueue !== "function") return;
583
- await chat.initialize();
584
- const state = chat.getState();
585
- const lockKey = await internals.getLockKey.call(chat, definition.adapter, threadId);
586
- const deadline = Date.now() + CHAT_SDK_LOCK_TTL_MS + 5e3;
587
- while (await state.queueDepth(lockKey) > 0) {
588
- const lock = await state.acquireLock(lockKey, CHAT_SDK_LOCK_TTL_MS);
589
- if (lock) {
590
- try {
591
- await internals.drainQueue.call(chat, lock, definition.adapter, threadId, lockKey);
592
- } finally {
593
- await state.releaseLock(lock);
594
- }
595
- return;
596
- }
597
- if (Date.now() >= deadline) return;
598
- await new Promise((resolve) => setTimeout(resolve, 1e3));
599
- }
725
+ await drainStrandedQueue(this.chat ??= this.createChat(), definition, threadId);
600
726
  }
601
727
  createChat() {
602
- const chat = new Chat({
603
- adapters: Object.fromEntries(this.definitions.map((definition) => [definition.adapterName, definition.adapter])),
728
+ return createMessengerChat({
729
+ definitions: this.definitions,
604
730
  concurrency: this.concurrency,
605
- fallbackStreamingPlaceholderText: FALLBACK_STREAMING_PLACEHOLDER_TEXT,
606
- state: createChatSdkState({
607
- agent: ThinkMessengerStateAgent,
608
- keyShard: (key) => this.shardStateKey(key),
609
- lockHeartbeat: true,
610
- parent: this.host,
611
- shardKey: (threadId) => this.shardThread(threadId)
612
- }),
613
- userName: this.definitions[0]?.userName ?? "think"
614
- });
615
- chat.onDirectMessage(async (thread, message, _channel, context) => {
616
- const definition = this.definitionForThread(thread);
617
- if (!definition) return;
618
- if (definition.respondTo.includes("direct-message")) await this.enqueueReply(definition, await this.toEvent(definition, {
619
- eventKind: "direct-message",
620
- message,
621
- skipped: context?.skipped,
622
- thread
623
- }), thread);
624
- });
625
- chat.onNewMention(async (thread, message, context) => {
626
- const definition = this.definitionForThread(thread);
627
- if (!definition) return;
628
- if (definition.subscribeOnMention) await thread.subscribe();
629
- if (definition.respondTo.includes("mention")) await this.enqueueReply(definition, await this.toEvent(definition, {
630
- eventKind: "mention",
631
- message,
632
- skipped: context?.skipped,
633
- thread
634
- }), thread);
635
- });
636
- chat.onNewMessage(/[\s\S]*/, async (thread, message, context) => {
637
- const definition = this.definitionForThread(thread);
638
- if (!definition || !definition.respondTo.includes("mention")) return;
639
- if (!context?.skipped.some((skipped) => mentionsBot(definition, skipped))) return;
640
- if (definition.subscribeOnMention) await thread.subscribe();
641
- await this.enqueueReply(definition, await this.toEvent(definition, {
642
- eventKind: "mention",
643
- message,
644
- skipped: context.skipped,
645
- thread
646
- }), thread);
647
- });
648
- chat.onSubscribedMessage(async (thread, message, context) => {
649
- const definition = this.definitionForThread(thread);
650
- if (!definition) return;
651
- const mentioned = message.isMention || (context?.skipped.some((skipped) => mentionsBot(definition, skipped)) ?? false);
652
- if (definition.respondTo.includes("subscribed-thread") || mentioned && definition.respondTo.includes("mention")) await this.enqueueReply(definition, await this.toEvent(definition, {
653
- eventKind: mentioned ? "mention" : "subscribed-message",
654
- message,
655
- skipped: context?.skipped,
656
- thread
657
- }), thread);
731
+ parent: this.host,
732
+ onEvent: (definition, event, thread) => this.enqueueReply(definition, event, thread)
658
733
  });
659
- chat.onAction(async (event) => {
660
- if (!event.thread) return;
661
- const thread = event.thread;
662
- const definition = this.definitionForThread(thread);
663
- if (!definition) return;
664
- if (definition.respondTo.includes("action")) await this.enqueueReply(definition, await this.toEvent(definition, {
665
- action: event,
666
- eventKind: "action",
667
- raw: event.raw,
668
- thread
669
- }), thread);
670
- });
671
- return chat.registerSingleton();
672
- }
673
- /** Whether this isolate still holds the live closure for one reply. */
674
- hasLiveReply(nonce) {
675
- return this.liveReplies.has(nonce);
676
- }
677
- /**
678
- * The durable "accepted" snapshot for one live reply, when its closure is
679
- * still held. The task definition persists this BEFORE delivery begins:
680
- * an isolate lost mid-answer recovers through it, and without it replay
681
- * could neither deliver nor apologize.
682
- */
683
- initialReplySnapshot(nonce) {
684
- const entry = this.liveReplies.get(nonce);
685
- if (!entry) return void 0;
686
- return messengerReplySnapshot("accepted", entry.snapshotEvent, entry.snapshotThread);
687
- }
688
- /** Execute one live (same-isolate) reply under the given fiber context. */
689
- async executeLiveReply(nonce, fiber) {
690
- const entry = this.liveReplies.get(nonce);
691
- if (!entry) throw new Error("Messenger reply closure is no longer available in this isolate");
692
- await this.answer(entry.definition, entry.event, entry.thread, fiber, entry.snapshotEvent);
693
734
  }
694
735
  async enqueueReply(definition, event, thread) {
695
736
  const snapshotEvent = serializableMessengerEvent(event);
696
- const snapshotThread = thread.toJSON();
697
- const nonce = crypto.randomUUID();
698
- this.liveReplies.set(nonce, {
699
- definition,
700
- event,
701
- thread,
702
- snapshotEvent,
703
- snapshotThread
737
+ await this.host._sendMessengerReply(idempotencyKeyForEvent(event), {
738
+ payload: {
739
+ event: snapshotEvent,
740
+ thread: thread.toJSON()
741
+ },
742
+ answer: (record) => this.answer(definition, event, thread, record, snapshotEvent)
704
743
  });
705
- try {
706
- await this.host._runMessengerReplyTask({
707
- nonce,
708
- idempotencyKey: idempotencyKeyForEvent(event),
709
- metadata: {
710
- messengerId: event.messengerId,
711
- messageId: event.message?.id,
712
- provider: event.provider,
713
- threadId: event.thread.id
714
- }
715
- });
716
- } finally {
717
- this.liveReplies.delete(nonce);
718
- }
719
744
  }
720
- async answer(definition, event, thread, fiber, snapshotEvent = serializableMessengerEvent(event), checkpoint) {
745
+ async answer(definition, event, thread, record, snapshotEvent = serializableMessengerEvent(event)) {
721
746
  const target = await this.resolveTarget(definition, event);
722
747
  await deliverMessengerReply({
723
748
  event,
724
- checkpoint,
725
- fiber,
749
+ ...record && { onStage: record },
726
750
  policy: definition.delivery,
727
751
  snapshotEvent,
728
- snapshotThread: thread.toJSON(),
729
752
  surface: thread,
730
753
  target,
731
754
  userMessage: toMessengerUserMessage(event, definition.channelSpeakerLabel)
@@ -742,7 +765,9 @@ var ThinkMessengerRuntime = class {
742
765
  */
743
766
  async resolveDeliverySurface(channelId, threadId) {
744
767
  if (!this.definitionsById.get(channelId) || !threadId) return;
745
- return (this.chat ?? this.createChat()).thread(threadId);
768
+ const chat = this.chat ??= this.createChat();
769
+ await chat.initialize();
770
+ return chat.thread(threadId);
746
771
  }
747
772
  /**
748
773
  * Post what chat recovery produced for an interrupted messenger turn: the
@@ -775,51 +800,123 @@ var ThinkMessengerRuntime = class {
775
800
  chatWithMessengerContext: (userMessage, callback, context) => stub.chatWithMessengerContext(userMessage, callback, context)
776
801
  };
777
802
  }
778
- definitionForThread(thread) {
779
- return this.definitionsByAdapterName.get(thread.toJSON().adapterName) ?? this.definitionForThreadId(thread.id) ?? this.definitionForThreadId(thread.channelId);
780
- }
781
- definitionForThreadId(threadId) {
782
- if (!threadId) return;
783
- if (this.definitions.length === 1) return this.definitions[0];
784
- return this.definitions.find((definition) => threadId === definition.id || threadId.startsWith(`${definition.id}:`) || this.hasUniqueProvider(definition.provider) && (threadId === definition.provider || threadId.startsWith(`${definition.provider}:`)) || threadId === definition.adapterName || threadId.startsWith(`${definition.adapterName}:`));
785
- }
786
- hasUniqueProvider(provider) {
787
- return this.definitions.filter((definition) => definition.provider === provider).length === 1;
788
- }
789
- shardThread(threadId) {
790
- return this.definitionForThreadId(threadId)?.shardKey?.(threadId) || threadId.split(":").slice(0, 2).join(":") || "default";
791
- }
792
- shardStateKey(key) {
793
- for (const definition of this.definitions) {
794
- const shard = definition.keyShard?.(key);
795
- if (shard) return shard;
796
- }
797
- return defaultKeyShard(key, (threadId) => this.shardThread(threadId));
798
- }
799
803
  /**
800
804
  * `ThreadImpl.fromJSON` (what `chat.reviver()` calls) builds the thread
801
805
  * without the Chat's streaming config, so a recovered reply would fall back to
802
806
  * the `"..."` placeholder. Rebuild it from the same fields with that config.
803
807
  */
804
808
  reviveThread(definition, value) {
805
- if (value === void 0) throw new Error("Messenger recovery snapshot is missing chat object data");
806
- const chat = this.chat ??= this.createChat();
807
- const json = JSON.parse(JSON.stringify(value));
808
- return new ThreadImpl({
809
- adapter: definition.adapter,
810
- stateAdapter: chat.getState(),
811
- channelId: json.channelId,
812
- channelVisibility: json.channelVisibility,
813
- currentMessage: json.currentMessage ? Message.fromJSON(json.currentMessage) : void 0,
814
- fallbackStreamingPlaceholderText: FALLBACK_STREAMING_PLACEHOLDER_TEXT,
815
- id: json.id,
816
- isDM: json.isDM
817
- });
818
- }
819
- async toEvent(definition, input) {
820
- return await definition.toEvent?.(input) ?? defaultChatSdkEvent(definition, input);
809
+ return reviveMessengerThread(this.chat ??= this.createChat(), definition, value);
821
810
  }
822
811
  };
812
+ /**
813
+ * The Chat SDK `Chat` a Think's messengers take their webhooks through: its
814
+ * state on Think's state sub-agents (subscriptions, thread locks, queued
815
+ * messages), its concurrency, and the handlers that turn what each
816
+ * messenger answers (`respondTo`) into a {@link MessengerEvent} for
817
+ * `onEvent`. A handler holds the thread's lock until `onEvent` resolves.
818
+ *
819
+ * @internal
820
+ */
821
+ function createMessengerChat(options) {
822
+ const { definitions } = options;
823
+ const lookup = messengerLookup(definitions);
824
+ const chat = new Chat({
825
+ adapters: Object.fromEntries(definitions.map((definition) => [definition.adapterName, definition.adapter])),
826
+ concurrency: options.concurrency,
827
+ fallbackStreamingPlaceholderText: FALLBACK_STREAMING_PLACEHOLDER_TEXT,
828
+ state: createChatSdkState({
829
+ agent: ThinkMessengerStateAgent,
830
+ keyShard: (key) => lookup.shardStateKey(key),
831
+ lockHeartbeat: true,
832
+ parent: options.parent,
833
+ shardKey: (threadId) => lookup.shardThread(threadId)
834
+ }),
835
+ userName: definitions[0]?.userName ?? "think"
836
+ });
837
+ chat.onDirectMessage(async (thread, message, _channel, context) => {
838
+ const definition = lookup.forThread(thread);
839
+ if (!definition) return;
840
+ if (definition.respondTo.includes("direct-message")) await options.onEvent(definition, await messengerEvent(definition, {
841
+ eventKind: "direct-message",
842
+ message,
843
+ skipped: context?.skipped,
844
+ thread
845
+ }), thread);
846
+ });
847
+ chat.onNewMention(async (thread, message, context) => {
848
+ const definition = lookup.forThread(thread);
849
+ if (!definition) return;
850
+ if (definition.subscribeOnMention) await thread.subscribe();
851
+ if (definition.respondTo.includes("mention")) await options.onEvent(definition, await messengerEvent(definition, {
852
+ eventKind: "mention",
853
+ message,
854
+ skipped: context?.skipped,
855
+ thread
856
+ }), thread);
857
+ });
858
+ chat.onNewMessage(/[\s\S]*/, async (thread, message, context) => {
859
+ const definition = lookup.forThread(thread);
860
+ if (!definition || !definition.respondTo.includes("mention")) return;
861
+ if (!context?.skipped.some((skipped) => mentionsBot(definition, skipped))) return;
862
+ if (definition.subscribeOnMention) await thread.subscribe();
863
+ await options.onEvent(definition, await messengerEvent(definition, {
864
+ eventKind: "mention",
865
+ message,
866
+ skipped: context.skipped,
867
+ thread
868
+ }), thread);
869
+ });
870
+ chat.onSubscribedMessage(async (thread, message, context) => {
871
+ const definition = lookup.forThread(thread);
872
+ if (!definition) return;
873
+ const mentioned = message.isMention || (context?.skipped.some((skipped) => mentionsBot(definition, skipped)) ?? false);
874
+ if (definition.respondTo.includes("subscribed-thread") || mentioned && definition.respondTo.includes("mention")) await options.onEvent(definition, await messengerEvent(definition, {
875
+ eventKind: mentioned ? "mention" : "subscribed-message",
876
+ message,
877
+ skipped: context?.skipped,
878
+ thread
879
+ }), thread);
880
+ });
881
+ chat.onAction(async (event) => {
882
+ if (!event.thread) return;
883
+ const thread = event.thread;
884
+ const definition = lookup.forThread(thread);
885
+ if (!definition) return;
886
+ if (definition.respondTo.includes("action")) await options.onEvent(definition, await messengerEvent(definition, {
887
+ action: event,
888
+ eventKind: "action",
889
+ raw: event.raw,
890
+ thread
891
+ }), thread);
892
+ });
893
+ return chat.registerSingleton();
894
+ }
895
+ /** Which messenger a thread or a state key belongs to. */
896
+ function messengerLookup(definitions) {
897
+ const byAdapterName = new Map(definitions.map((definition) => [definition.adapterName, definition]));
898
+ const hasUniqueProvider = (provider) => definitions.filter((definition) => definition.provider === provider).length === 1;
899
+ const forThreadId = (threadId) => {
900
+ if (!threadId) return void 0;
901
+ if (definitions.length === 1) return definitions[0];
902
+ return definitions.find((definition) => threadId === definition.id || threadId.startsWith(`${definition.id}:`) || hasUniqueProvider(definition.provider) && (threadId === definition.provider || threadId.startsWith(`${definition.provider}:`)) || threadId === definition.adapterName || threadId.startsWith(`${definition.adapterName}:`));
903
+ };
904
+ const shardThread = (threadId) => forThreadId(threadId)?.shardKey?.(threadId) || threadId.split(":").slice(0, 2).join(":") || "default";
905
+ return {
906
+ forThread: (thread) => byAdapterName.get(thread.toJSON().adapterName) ?? forThreadId(thread.id) ?? forThreadId(thread.channelId),
907
+ shardThread,
908
+ shardStateKey(key) {
909
+ for (const definition of definitions) {
910
+ const shard = definition.keyShard?.(key);
911
+ if (shard) return shard;
912
+ }
913
+ return defaultKeyShard(key, shardThread);
914
+ }
915
+ };
916
+ }
917
+ async function messengerEvent(definition, input) {
918
+ return await definition.toEvent?.(input) ?? defaultChatSdkEvent(definition, input);
919
+ }
823
920
  function normalizeMessengers(messengers) {
824
921
  const ids = /* @__PURE__ */ new Set();
825
922
  const adapterNames = /* @__PURE__ */ new Set();
@@ -847,6 +944,28 @@ function normalizeMessengers(messengers) {
847
944
  }
848
945
  return normalized;
849
946
  }
947
+ /**
948
+ * `ThreadImpl.fromJSON` (what `chat.reviver()` calls) builds the thread
949
+ * without the Chat's streaming config, so a recovered reply would fall back to
950
+ * the `"..."` placeholder, and `chat.thread(id)` has no current message to
951
+ * stream against. Rebuild a reply's thread from its JSON with that config.
952
+ *
953
+ * @internal
954
+ */
955
+ function reviveMessengerThread(chat, definition, value) {
956
+ if (value === void 0) throw new Error("Messenger recovery snapshot is missing chat object data");
957
+ const json = JSON.parse(JSON.stringify(value));
958
+ return new ThreadImpl({
959
+ adapter: definition.adapter,
960
+ stateAdapter: chat.getState(),
961
+ channelId: json.channelId,
962
+ channelVisibility: json.channelVisibility,
963
+ currentMessage: json.currentMessage ? Message.fromJSON(json.currentMessage) : void 0,
964
+ fallbackStreamingPlaceholderText: FALLBACK_STREAMING_PLACEHOLDER_TEXT,
965
+ id: json.id,
966
+ isDM: json.isDM
967
+ });
968
+ }
850
969
  function defaultConversationName(event) {
851
970
  return `messenger:${event.messengerId}:${stableNamePart(event.thread.id)}`;
852
971
  }
@@ -1035,6 +1154,6 @@ function validatePath(path, id) {
1035
1154
  if (path.includes("?") || path.includes("#")) throw new Error(`Messenger ${id} path must not include query or hash`);
1036
1155
  }
1037
1156
  //#endregion
1038
- export { messengerReplySnapshot as C, serializableMessengerEvent as D, resolveChannelSpeakerLabel as E, toMessengerUserMessage as O, messengerReplyRecoveryMode as S, messengerContextFromEvent as T, MESSENGER_REPLY_FIBER_NAME as _, defaultChatSdkEvent as a, deliverMessengerReply as b, normalizeMessengers as c, toMessengerAuthor as d, toMessengerMessage as f, INTERRUPTED_MESSENGER_RESPONSE as g, ERROR_MESSENGER_RESPONSE as h, chatSdkMessenger as i, resolveSelfMention as l, EMPTY_MESSENGER_RESPONSE as m, ThinkMessengerRuntime as n, defaultConversationName as o, toMessengerThread as p, ThinkMessengerStateAgent as r, idempotencyKeyForEvent as s, DEFAULT_MESSENGER_CONCURRENCY as t, toMessengerAttachment as u, TextStreamCallback as v, parseMessengerReplySnapshot as w, messengerReplyFailureMode as x, defaultDeliveryTag as y };
1157
+ export { toMessengerUserMessage as A, deliverMessengerReply as C, messengerContextFromEvent as D, reviveMessengerEvent as E, sendMessengerReply as F, postApology as M, registerMessengerReplySink as N, resolveChannelSpeakerLabel as O, releasedSnapshot as P, TextStreamCallback as S, messengerReplyRecoveryMode as T, toMessengerThread as _, createMessengerChat as a, ERROR_MESSENGER_RESPONSE as b, drainStrandedQueue as c, recoveredReplyPosts as d, resolveSelfMention as f, toMessengerMessage as g, toMessengerAuthor as h, chatSdkMessenger as i, RELEASED_REPLY_DEFINITION as j, serializableMessengerEvent as k, idempotencyKeyForEvent as l, toMessengerAttachment as m, ThinkMessengerRuntime as n, defaultChatSdkEvent as o, reviveMessengerThread as p, ThinkMessengerStateAgent as r, defaultConversationName as s, DEFAULT_MESSENGER_CONCURRENCY as t, normalizeMessengers as u, withMessengerQueueTtl as v, messengerReplyFailureMode as w, INTERRUPTED_MESSENGER_RESPONSE as x, EMPTY_MESSENGER_RESPONSE as y };
1039
1158
 
1040
- //# sourceMappingURL=chat-sdk-BEjKXjCm.js.map
1159
+ //# sourceMappingURL=chat-sdk-4Nu96eDX.js.map