@cloudflare/think 0.19.0 → 0.20.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 +21 -1
- package/dist/{chat-sdk-B77QwYuj.js → chat-sdk-BEjKXjCm.js} +333 -67
- package/dist/chat-sdk-BEjKXjCm.js.map +1 -0
- package/dist/{hook-proxy-Dogs9wbj.js → hook-proxy-DY2sBNa0.js} +8 -3
- package/dist/hook-proxy-DY2sBNa0.js.map +1 -0
- package/dist/{index-BLkPlEbF.d.ts → index-DwPAhQRQ.d.ts} +971 -228
- package/dist/messengers/index.d.ts +60 -56
- package/dist/messengers/index.js +2 -2
- package/dist/messengers/telegram.d.ts +11 -4
- package/dist/messengers/telegram.js +3 -1
- package/dist/messengers/telegram.js.map +1 -1
- package/dist/react.d.ts +4 -0
- package/dist/react.js.map +1 -1
- package/dist/think.d.ts +2 -2
- package/dist/think.js +2080 -480
- package/dist/think.js.map +1 -1
- package/dist/workflows.d.ts +1 -1
- package/docs/actions.md +36 -11
- package/docs/channels.md +15 -2
- package/docs/index.md +107 -12
- package/docs/lifecycle-hooks.md +113 -62
- package/docs/messengers.md +93 -1
- package/docs/multi-chat.md +614 -0
- package/docs/programmatic-submissions.md +45 -0
- package/docs/sub-agents.md +61 -20
- package/docs/tools.md +4 -1
- package/docs/workflows.md +5 -0
- package/package.json +7 -7
- package/dist/chat-sdk-B77QwYuj.js.map +0 -1
- package/dist/hook-proxy-Dogs9wbj.js.map +0 -1
|
@@ -1,18 +1,25 @@
|
|
|
1
1
|
import { TextSegmentJoiner } from "agents/chat";
|
|
2
|
-
import { Chat } from "chat";
|
|
2
|
+
import { Chat, Message, ThreadImpl } from "chat";
|
|
3
3
|
import { ChatSdkStateAgent, createChatSdkState, defaultKeyShard } from "agents/chat-sdk";
|
|
4
4
|
import { RpcTarget } from "cloudflare:workers";
|
|
5
5
|
//#region src/messengers/events.ts
|
|
6
|
+
/**
|
|
7
|
+
* The context persisted on a messenger turn's user message. Built from the
|
|
8
|
+
* serializable form of the event, so raw platform payloads and attachment
|
|
9
|
+
* bytes are never stored and a live turn matches its recovered replay.
|
|
10
|
+
*/
|
|
6
11
|
function messengerContextFromEvent(event) {
|
|
12
|
+
const serializable = serializableMessengerEvent(event);
|
|
7
13
|
return {
|
|
8
|
-
action:
|
|
9
|
-
author:
|
|
10
|
-
capabilities:
|
|
11
|
-
kind:
|
|
12
|
-
message:
|
|
13
|
-
messengerId:
|
|
14
|
-
provider:
|
|
15
|
-
|
|
14
|
+
action: serializable.action,
|
|
15
|
+
author: serializable.message?.author ?? serializable.action?.user,
|
|
16
|
+
capabilities: serializable.capabilities,
|
|
17
|
+
kind: serializable.kind,
|
|
18
|
+
message: serializable.message,
|
|
19
|
+
messengerId: serializable.messengerId,
|
|
20
|
+
provider: serializable.provider,
|
|
21
|
+
skipped: serializable.skipped,
|
|
22
|
+
thread: serializable.thread
|
|
16
23
|
};
|
|
17
24
|
}
|
|
18
25
|
function serializableMessengerEvent(event) {
|
|
@@ -28,23 +35,27 @@ function serializableMessengerEvent(event) {
|
|
|
28
35
|
user: event.action.user ? { ...event.action.user } : void 0,
|
|
29
36
|
value: event.action.value
|
|
30
37
|
} : void 0,
|
|
31
|
-
message: event.message ?
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
38
|
+
message: event.message ? serializableMessengerMessage(event.message) : void 0,
|
|
39
|
+
skipped: event.skipped?.map(serializableMessengerMessage)
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
function serializableMessengerMessage(message) {
|
|
43
|
+
return {
|
|
44
|
+
attachments: message.attachments.map((attachment) => ({
|
|
45
|
+
fetchMetadata: attachment.fetchMetadata ? { ...attachment.fetchMetadata } : void 0,
|
|
46
|
+
id: attachment.id,
|
|
47
|
+
mediaType: attachment.mediaType,
|
|
48
|
+
name: attachment.name,
|
|
49
|
+
size: attachment.size,
|
|
50
|
+
text: attachment.text,
|
|
51
|
+
url: attachment.url
|
|
52
|
+
})),
|
|
53
|
+
author: { ...message.author },
|
|
54
|
+
createdAt: message.createdAt,
|
|
55
|
+
id: message.id,
|
|
56
|
+
isMention: message.isMention,
|
|
57
|
+
providerMessageId: message.providerMessageId,
|
|
58
|
+
text: message.text
|
|
48
59
|
};
|
|
49
60
|
}
|
|
50
61
|
function resolveChannelSpeakerLabel(author, channelSpeakerLabel) {
|
|
@@ -83,11 +94,15 @@ function toMessengerUserMessage(event, channelSpeakerLabel) {
|
|
|
83
94
|
};
|
|
84
95
|
}
|
|
85
96
|
if (!message) throw new Error(`Messenger event ${event.kind} does not contain a message`);
|
|
86
|
-
const
|
|
87
|
-
const
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
97
|
+
const messages = [...event.skipped ?? [], message];
|
|
98
|
+
const runs = speakerRuns(messages).map((run) => ({
|
|
99
|
+
author: run[0].author,
|
|
100
|
+
text: run.map((entry) => entry.text.trim()).filter(Boolean).join("\n")
|
|
101
|
+
}));
|
|
102
|
+
const fullText = [runs.filter((run) => runs.length === 1 || run.text).map((run) => {
|
|
103
|
+
const displayName = event.thread.isDirectMessage ? void 0 : resolveChannelSpeakerLabel(run.author, channelSpeakerLabel);
|
|
104
|
+
return displayName ? `${displayName}: ${run.text}` : run.text;
|
|
105
|
+
}).join("\n"), describeAttachments(messages.flatMap((entry) => entry.attachments))].filter(Boolean).join("\n\n");
|
|
91
106
|
return {
|
|
92
107
|
id: `${event.messengerId}:${message.id}`,
|
|
93
108
|
role: "user",
|
|
@@ -98,6 +113,16 @@ function toMessengerUserMessage(event, channelSpeakerLabel) {
|
|
|
98
113
|
metadata: { messenger: messengerContextFromEvent(event) }
|
|
99
114
|
};
|
|
100
115
|
}
|
|
116
|
+
/** Consecutive messages from the same author, in order. */
|
|
117
|
+
function speakerRuns(messages) {
|
|
118
|
+
const runs = [];
|
|
119
|
+
for (const message of messages) {
|
|
120
|
+
const run = runs.at(-1);
|
|
121
|
+
if (run && run[0].author.userId === message.author.userId) run.push(message);
|
|
122
|
+
else runs.push([message]);
|
|
123
|
+
}
|
|
124
|
+
return runs;
|
|
125
|
+
}
|
|
101
126
|
function describeAttachments(attachments) {
|
|
102
127
|
if (attachments.length === 0) return "";
|
|
103
128
|
return ["Attachments:", ...attachments.map((attachment, index) => {
|
|
@@ -124,11 +149,13 @@ var TextStreamCallback = class extends RpcTarget {
|
|
|
124
149
|
this.wakeups = [];
|
|
125
150
|
this.closed = false;
|
|
126
151
|
this.interrupted = false;
|
|
152
|
+
this.recoveredReplyDelivered = false;
|
|
127
153
|
this.text = "";
|
|
128
154
|
this.visibleClosed = false;
|
|
129
155
|
this.visibleLimitReachedValue = false;
|
|
130
156
|
this.visibleStarted = false;
|
|
131
157
|
this.visibleTextValue = "";
|
|
158
|
+
this.emptyText = options.emptyText;
|
|
132
159
|
this.onVisibleStart = options.onVisibleStart;
|
|
133
160
|
this.visibleSoftLimit = options.visibleSoftLimit;
|
|
134
161
|
}
|
|
@@ -148,18 +175,28 @@ var TextStreamCallback = class extends RpcTarget {
|
|
|
148
175
|
if (pushedText) this.wake();
|
|
149
176
|
}
|
|
150
177
|
onDone() {
|
|
151
|
-
this.
|
|
178
|
+
this.complete();
|
|
152
179
|
}
|
|
153
180
|
onError(error) {
|
|
154
181
|
this.fail(new Error(error));
|
|
155
182
|
}
|
|
156
|
-
onInterrupted() {
|
|
183
|
+
onInterrupted(info) {
|
|
157
184
|
this.interrupted = true;
|
|
185
|
+
this.recoveredReplyDelivered = info?.deliversRecoveredReply === true;
|
|
158
186
|
this.close();
|
|
159
187
|
}
|
|
160
188
|
wasInterrupted() {
|
|
161
189
|
return this.interrupted;
|
|
162
190
|
}
|
|
191
|
+
/** Whether the target posts the recovered reply to the thread itself. */
|
|
192
|
+
targetDeliversRecoveredReply() {
|
|
193
|
+
return this.recoveredReplyDelivered;
|
|
194
|
+
}
|
|
195
|
+
/** Ends a completed turn, streaming `emptyText` if it produced no text. */
|
|
196
|
+
complete() {
|
|
197
|
+
if (!this.closed && this.emptyText !== void 0 && !this.hasText()) this.visibleChunks.push(this.emptyText);
|
|
198
|
+
this.close();
|
|
199
|
+
}
|
|
163
200
|
close() {
|
|
164
201
|
this.closed = true;
|
|
165
202
|
this.visibleClosed = true;
|
|
@@ -174,6 +211,19 @@ var TextStreamCallback = class extends RpcTarget {
|
|
|
174
211
|
hasText() {
|
|
175
212
|
return this.text.trim().length > 0;
|
|
176
213
|
}
|
|
214
|
+
/**
|
|
215
|
+
* Resolves `true` once there is visible text to post, or `false` when the
|
|
216
|
+
* stream ends without any, so a caller can avoid posting an empty reply.
|
|
217
|
+
*/
|
|
218
|
+
async hasVisibleOutput() {
|
|
219
|
+
while (true) {
|
|
220
|
+
if (this.visibleChunks.length > 0) return true;
|
|
221
|
+
if (this.error || this.closed || this.visibleClosed) return false;
|
|
222
|
+
await new Promise((resolve) => {
|
|
223
|
+
this.wakeups.push(resolve);
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
}
|
|
177
227
|
remainingText() {
|
|
178
228
|
return this.text.slice(this.visibleTextValue.length);
|
|
179
229
|
}
|
|
@@ -283,6 +333,17 @@ function messengerReplyFailureMode(hasStreamedText, completedModelTurn = false,
|
|
|
283
333
|
if (completedModelTurn) return "error";
|
|
284
334
|
return hasStreamedText ? "apologize" : "error";
|
|
285
335
|
}
|
|
336
|
+
const DEFAULT_TYPING_REFRESH_MS = 4e3;
|
|
337
|
+
/** Longest the reply waits on a typing request an adapter never settles. */
|
|
338
|
+
const TYPING_SETTLE_TIMEOUT_MS = 1e3;
|
|
339
|
+
async function settleTyping(pending) {
|
|
340
|
+
if (!pending) return;
|
|
341
|
+
let timer;
|
|
342
|
+
await Promise.race([pending, new Promise((resolve) => {
|
|
343
|
+
timer = setTimeout(resolve, TYPING_SETTLE_TIMEOUT_MS);
|
|
344
|
+
})]);
|
|
345
|
+
clearTimeout(timer);
|
|
346
|
+
}
|
|
286
347
|
async function deliverMessengerReply(options) {
|
|
287
348
|
const emptyResponseText = options.policy?.emptyResponseText ?? "I couldn't produce a text response. Please try again.";
|
|
288
349
|
const errorResponseText = options.policy?.errorResponseText ?? "Sorry, I couldn't answer that right now. Please try again.";
|
|
@@ -293,12 +354,39 @@ async function deliverMessengerReply(options) {
|
|
|
293
354
|
options.fiber?.stash(snapshot);
|
|
294
355
|
});
|
|
295
356
|
const callback = new TextStreamCallback({
|
|
357
|
+
emptyText: emptyResponseText,
|
|
296
358
|
onVisibleStart: async () => {
|
|
297
359
|
await checkpoint(messengerReplySnapshot("streaming", snapshotEvent, options.snapshotThread));
|
|
298
360
|
},
|
|
299
361
|
visibleSoftLimit: options.policy?.visibleSoftLimit
|
|
300
362
|
});
|
|
301
|
-
|
|
363
|
+
let typingInFlight;
|
|
364
|
+
let typingStopped = false;
|
|
365
|
+
const sendTyping = () => {
|
|
366
|
+
if (typingStopped) return Promise.resolve();
|
|
367
|
+
typingInFlight ??= (async () => {
|
|
368
|
+
try {
|
|
369
|
+
await options.surface.startTyping?.("Thinking...");
|
|
370
|
+
} catch (error) {
|
|
371
|
+
console.warn("[Think] Messenger typing indicator failed", error);
|
|
372
|
+
} finally {
|
|
373
|
+
typingInFlight = void 0;
|
|
374
|
+
}
|
|
375
|
+
})();
|
|
376
|
+
return typingInFlight;
|
|
377
|
+
};
|
|
378
|
+
const typingRefreshMs = options.policy?.typingRefreshMs ?? DEFAULT_TYPING_REFRESH_MS;
|
|
379
|
+
let typingTimer;
|
|
380
|
+
const stopTyping = () => {
|
|
381
|
+
typingStopped = true;
|
|
382
|
+
clearInterval(typingTimer);
|
|
383
|
+
typingTimer = void 0;
|
|
384
|
+
};
|
|
385
|
+
const post = callback.hasVisibleOutput().then(async (visible) => {
|
|
386
|
+
stopTyping();
|
|
387
|
+
await settleTyping(typingInFlight);
|
|
388
|
+
return visible ? options.surface.post(callback.stream()) : void 0;
|
|
389
|
+
}).catch(async (error) => {
|
|
302
390
|
if (options.policy?.isExpectedDeliveryCompletion?.(error, callback)) return;
|
|
303
391
|
const requestId = callback.requestId();
|
|
304
392
|
if (requestId) await Promise.resolve(options.target.cancelChat(requestId, toError(error).message)).catch(() => void 0);
|
|
@@ -306,7 +394,8 @@ async function deliverMessengerReply(options) {
|
|
|
306
394
|
throw error;
|
|
307
395
|
});
|
|
308
396
|
try {
|
|
309
|
-
|
|
397
|
+
if (options.surface.startTyping && typingRefreshMs > 0) typingTimer = setInterval(() => void sendTyping(), typingRefreshMs);
|
|
398
|
+
await settleTyping(sendTyping());
|
|
310
399
|
const userMessage = options.userMessage ?? toMessengerUserMessage(options.event);
|
|
311
400
|
const restoreSurface = options.target.bindActiveDeliverySurface?.(options.surface);
|
|
312
401
|
try {
|
|
@@ -317,15 +406,18 @@ async function deliverMessengerReply(options) {
|
|
|
317
406
|
}
|
|
318
407
|
if (callback.wasInterrupted()) {
|
|
319
408
|
callback.close();
|
|
320
|
-
await post.
|
|
321
|
-
await options.surface.post(interruptedResponseText).catch(() => void 0);
|
|
409
|
+
const streamRejected = await post.then(() => false, () => true);
|
|
322
410
|
await checkpoint(messengerReplySnapshot("completed", snapshotEvent, options.snapshotThread));
|
|
411
|
+
if (callback.targetDeliversRecoveredReply()) {
|
|
412
|
+
for (const chunk of options.policy?.splitText?.(streamRejected ? callback.textSoFar() : callback.remainingText()) ?? []) await options.surface.post(chunk).catch(() => void 0);
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
await options.surface.post(interruptedResponseText).catch(() => void 0);
|
|
323
416
|
return;
|
|
324
417
|
}
|
|
325
418
|
completedModelTurn = true;
|
|
326
|
-
callback.
|
|
419
|
+
callback.complete();
|
|
327
420
|
await post;
|
|
328
|
-
if (!callback.hasText()) await options.surface.post(emptyResponseText);
|
|
329
421
|
for (const chunk of options.policy?.splitText?.(callback.remainingText()) ?? []) await options.surface.post(chunk);
|
|
330
422
|
await checkpoint(messengerReplySnapshot("completed", snapshotEvent, options.snapshotThread));
|
|
331
423
|
} catch (error) {
|
|
@@ -336,13 +428,14 @@ async function deliverMessengerReply(options) {
|
|
|
336
428
|
await checkpoint(messengerReplySnapshot("completed", snapshotEvent, options.snapshotThread));
|
|
337
429
|
return;
|
|
338
430
|
}
|
|
431
|
+
await checkpoint(messengerReplySnapshot("completed", snapshotEvent, options.snapshotThread));
|
|
339
432
|
if (failureMode === "apologize") {
|
|
340
433
|
await options.surface.post(interruptedResponseText).catch(() => void 0);
|
|
341
|
-
await checkpoint(messengerReplySnapshot("completed", snapshotEvent, options.snapshotThread));
|
|
342
434
|
return;
|
|
343
435
|
}
|
|
344
436
|
await options.surface.post({ markdown: errorResponseText }).catch(() => void 0);
|
|
345
|
-
|
|
437
|
+
} finally {
|
|
438
|
+
stopTyping();
|
|
346
439
|
}
|
|
347
440
|
}
|
|
348
441
|
function toError(error) {
|
|
@@ -351,6 +444,43 @@ function toError(error) {
|
|
|
351
444
|
//#endregion
|
|
352
445
|
//#region src/messengers/chat-sdk.ts
|
|
353
446
|
var ThinkMessengerStateAgent = class extends ChatSdkStateAgent {};
|
|
447
|
+
/**
|
|
448
|
+
* Adapters without native streaming would otherwise post `"..."` and edit it,
|
|
449
|
+
* and platforms such as Slack keep that first text as the notification
|
|
450
|
+
* preview. Delivery already shows a typing indicator before the reply starts.
|
|
451
|
+
*/
|
|
452
|
+
const FALLBACK_STREAMING_PLACEHOLDER_TEXT = null;
|
|
453
|
+
/** The posts that deliver a recovered messenger reply, in order. */
|
|
454
|
+
function recoveredReplyPosts(definition, input) {
|
|
455
|
+
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
|
+
const text = input.text?.trim() ? input.text : "";
|
|
457
|
+
if (!text) return input.partialPosted ? [] : [definition.delivery?.emptyResponseText ?? "I couldn't produce a text response. Please try again."];
|
|
458
|
+
return (definition.delivery?.splitText?.(text) ?? [text]).map((chunk) => ({ markdown: chunk }));
|
|
459
|
+
}
|
|
460
|
+
/**
|
|
461
|
+
* How long a message queued behind a running reply stays answerable. The
|
|
462
|
+
* Chat SDK default (90 seconds) drops follow-ups sent early in a long turn,
|
|
463
|
+
* so Think applies this unless `queueEntryTtlMs` is set explicitly.
|
|
464
|
+
*/
|
|
465
|
+
const MESSENGER_QUEUE_ENTRY_TTL_MS = 1800 * 1e3;
|
|
466
|
+
const DEFAULT_MESSENGER_CONCURRENCY = {
|
|
467
|
+
debounceMs: 600,
|
|
468
|
+
queueEntryTtlMs: MESSENGER_QUEUE_ENTRY_TTL_MS,
|
|
469
|
+
strategy: "burst"
|
|
470
|
+
};
|
|
471
|
+
/** The Chat SDK's thread lock TTL (`DEFAULT_LOCK_TTL_MS`). */
|
|
472
|
+
const CHAT_SDK_LOCK_TTL_MS = 3e4;
|
|
473
|
+
/** Fill in Think's queue-entry TTL where the setting leaves it unset. */
|
|
474
|
+
function withMessengerQueueTtl(concurrency) {
|
|
475
|
+
if (typeof concurrency === "string") return {
|
|
476
|
+
queueEntryTtlMs: MESSENGER_QUEUE_ENTRY_TTL_MS,
|
|
477
|
+
strategy: concurrency
|
|
478
|
+
};
|
|
479
|
+
return {
|
|
480
|
+
...concurrency,
|
|
481
|
+
queueEntryTtlMs: concurrency.queueEntryTtlMs ?? 18e5
|
|
482
|
+
};
|
|
483
|
+
}
|
|
354
484
|
function chatSdkMessenger(options) {
|
|
355
485
|
return {
|
|
356
486
|
...options,
|
|
@@ -358,11 +488,12 @@ function chatSdkMessenger(options) {
|
|
|
358
488
|
};
|
|
359
489
|
}
|
|
360
490
|
var ThinkMessengerRuntime = class {
|
|
361
|
-
constructor(definitions, host) {
|
|
491
|
+
constructor(definitions, host, options) {
|
|
362
492
|
this.host = host;
|
|
363
493
|
this.liveReplies = /* @__PURE__ */ new Map();
|
|
364
494
|
this.definitionsByAdapterName = /* @__PURE__ */ new Map();
|
|
365
495
|
this.definitionsById = /* @__PURE__ */ new Map();
|
|
496
|
+
this.concurrency = withMessengerQueueTtl(options?.concurrency ?? DEFAULT_MESSENGER_CONCURRENCY);
|
|
366
497
|
this.definitions = normalizeMessengers(definitions);
|
|
367
498
|
for (const definition of this.definitions) {
|
|
368
499
|
this.definitionsByAdapterName.set(definition.adapterName, definition);
|
|
@@ -397,7 +528,18 @@ var ThinkMessengerRuntime = class {
|
|
|
397
528
|
if (!snapshot) return false;
|
|
398
529
|
const definition = this.definitionsById.get(snapshot.event.messengerId);
|
|
399
530
|
if (!definition) throw new Error(`No messenger definition found for recovered messenger ${snapshot.event.messengerId}`);
|
|
400
|
-
const thread = this.
|
|
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) {
|
|
401
543
|
const mode = messengerReplyRecoveryMode(snapshot);
|
|
402
544
|
if (mode === "answer") {
|
|
403
545
|
await this.answer(definition, snapshot.event, thread, void 0, snapshot.event, async (nextSnapshot) => {
|
|
@@ -420,46 +562,97 @@ var ThinkMessengerRuntime = class {
|
|
|
420
562
|
if (!options?.persistRecoverySnapshot) await this.host.resolveFiber(ctx.id, { status: "completed" });
|
|
421
563
|
return true;
|
|
422
564
|
}
|
|
565
|
+
/**
|
|
566
|
+
* Messages queued behind a reply are drained only by the Chat SDK handler
|
|
567
|
+
* holding the thread lock. When the isolate running that reply dies, the
|
|
568
|
+
* queue is stranded until another message arrives, so recovery drains it:
|
|
569
|
+
* once the dead holder's lock expires, take the lock and hand the queue to
|
|
570
|
+
* the SDK's own drain. A live holder drains the queue itself, which ends
|
|
571
|
+
* the wait.
|
|
572
|
+
*/
|
|
573
|
+
drainQueuedMessagesInBackground(definition, threadId) {
|
|
574
|
+
const drain = () => this.drainQueuedMessages(definition, threadId);
|
|
575
|
+
(this.host.keepAliveWhile?.(drain) ?? drain()).catch((error) => {
|
|
576
|
+
console.error(`[Think] Failed to drain messages queued on ${threadId} after recovery`, error);
|
|
577
|
+
});
|
|
578
|
+
}
|
|
579
|
+
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
|
+
}
|
|
600
|
+
}
|
|
423
601
|
createChat() {
|
|
424
602
|
const chat = new Chat({
|
|
425
603
|
adapters: Object.fromEntries(this.definitions.map((definition) => [definition.adapterName, definition.adapter])),
|
|
426
|
-
concurrency:
|
|
427
|
-
|
|
428
|
-
strategy: "burst"
|
|
429
|
-
},
|
|
604
|
+
concurrency: this.concurrency,
|
|
605
|
+
fallbackStreamingPlaceholderText: FALLBACK_STREAMING_PLACEHOLDER_TEXT,
|
|
430
606
|
state: createChatSdkState({
|
|
431
607
|
agent: ThinkMessengerStateAgent,
|
|
432
608
|
keyShard: (key) => this.shardStateKey(key),
|
|
609
|
+
lockHeartbeat: true,
|
|
433
610
|
parent: this.host,
|
|
434
611
|
shardKey: (threadId) => this.shardThread(threadId)
|
|
435
612
|
}),
|
|
436
613
|
userName: this.definitions[0]?.userName ?? "think"
|
|
437
614
|
});
|
|
438
|
-
chat.onDirectMessage(async (thread, message) => {
|
|
615
|
+
chat.onDirectMessage(async (thread, message, _channel, context) => {
|
|
439
616
|
const definition = this.definitionForThread(thread);
|
|
440
617
|
if (!definition) return;
|
|
441
618
|
if (definition.respondTo.includes("direct-message")) await this.enqueueReply(definition, await this.toEvent(definition, {
|
|
442
619
|
eventKind: "direct-message",
|
|
443
620
|
message,
|
|
621
|
+
skipped: context?.skipped,
|
|
444
622
|
thread
|
|
445
623
|
}), thread);
|
|
446
624
|
});
|
|
447
|
-
chat.onNewMention(async (thread, message) => {
|
|
625
|
+
chat.onNewMention(async (thread, message, context) => {
|
|
448
626
|
const definition = this.definitionForThread(thread);
|
|
449
627
|
if (!definition) return;
|
|
450
628
|
if (definition.subscribeOnMention) await thread.subscribe();
|
|
451
629
|
if (definition.respondTo.includes("mention")) await this.enqueueReply(definition, await this.toEvent(definition, {
|
|
452
630
|
eventKind: "mention",
|
|
453
631
|
message,
|
|
632
|
+
skipped: context?.skipped,
|
|
454
633
|
thread
|
|
455
634
|
}), thread);
|
|
456
635
|
});
|
|
457
|
-
chat.
|
|
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) => {
|
|
458
649
|
const definition = this.definitionForThread(thread);
|
|
459
650
|
if (!definition) return;
|
|
460
|
-
|
|
461
|
-
|
|
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",
|
|
462
654
|
message,
|
|
655
|
+
skipped: context?.skipped,
|
|
463
656
|
thread
|
|
464
657
|
}), thread);
|
|
465
658
|
});
|
|
@@ -551,6 +744,22 @@ var ThinkMessengerRuntime = class {
|
|
|
551
744
|
if (!this.definitionsById.get(channelId) || !threadId) return;
|
|
552
745
|
return (this.chat ?? this.createChat()).thread(threadId);
|
|
553
746
|
}
|
|
747
|
+
/**
|
|
748
|
+
* Post what chat recovery produced for an interrupted messenger turn: the
|
|
749
|
+
* text the thread has not seen yet, or the interrupted apology when
|
|
750
|
+
* recovery gave up. The reply may span several posts; this posts only post
|
|
751
|
+
* number `chunk` (skipped when out of range) and returns how many there
|
|
752
|
+
* are, so the caller can checkpoint between posts.
|
|
753
|
+
*/
|
|
754
|
+
async deliverRecoveredReply(input) {
|
|
755
|
+
const definition = this.definitionsById.get(input.messengerId);
|
|
756
|
+
const surface = await this.resolveDeliverySurface(input.messengerId, input.threadId);
|
|
757
|
+
if (!definition || !surface) throw new Error(`No messenger delivery surface for ${input.messengerId} thread ${input.threadId}`);
|
|
758
|
+
const posts = recoveredReplyPosts(definition, input);
|
|
759
|
+
const post = posts[input.chunk];
|
|
760
|
+
if (post !== void 0) await surface.post(post);
|
|
761
|
+
return { chunks: posts.length };
|
|
762
|
+
}
|
|
554
763
|
async resolveTarget(definition, event) {
|
|
555
764
|
const conversation = definition.conversation ?? "thread";
|
|
556
765
|
const target = typeof conversation === "function" ? await conversation(event) : conversation === "self" ? { target: "self" } : {
|
|
@@ -559,7 +768,12 @@ var ThinkMessengerRuntime = class {
|
|
|
559
768
|
};
|
|
560
769
|
if (target.target === "self") return this.host;
|
|
561
770
|
const agentClass = target.agentClass ?? this.host.constructor;
|
|
562
|
-
|
|
771
|
+
const stub = await this.host.subAgent(agentClass, target.name);
|
|
772
|
+
return {
|
|
773
|
+
cancelChat: (requestId, reason) => stub.cancelChat(requestId, reason),
|
|
774
|
+
chat: (userMessage, callback) => stub.chat(userMessage, callback),
|
|
775
|
+
chatWithMessengerContext: (userMessage, callback, context) => stub.chatWithMessengerContext(userMessage, callback, context)
|
|
776
|
+
};
|
|
563
777
|
}
|
|
564
778
|
definitionForThread(thread) {
|
|
565
779
|
return this.definitionsByAdapterName.get(thread.toJSON().adapterName) ?? this.definitionForThreadId(thread.id) ?? this.definitionForThreadId(thread.channelId);
|
|
@@ -582,11 +796,25 @@ var ThinkMessengerRuntime = class {
|
|
|
582
796
|
}
|
|
583
797
|
return defaultKeyShard(key, (threadId) => this.shardThread(threadId));
|
|
584
798
|
}
|
|
585
|
-
|
|
799
|
+
/**
|
|
800
|
+
* `ThreadImpl.fromJSON` (what `chat.reviver()` calls) builds the thread
|
|
801
|
+
* without the Chat's streaming config, so a recovered reply would fall back to
|
|
802
|
+
* the `"..."` placeholder. Rebuild it from the same fields with that config.
|
|
803
|
+
*/
|
|
804
|
+
reviveThread(definition, value) {
|
|
586
805
|
if (value === void 0) throw new Error("Messenger recovery snapshot is missing chat object data");
|
|
587
|
-
const chat = this.chat
|
|
588
|
-
|
|
589
|
-
return
|
|
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
|
+
});
|
|
590
818
|
}
|
|
591
819
|
async toEvent(definition, input) {
|
|
592
820
|
return await definition.toEvent?.(input) ?? defaultChatSdkEvent(definition, input);
|
|
@@ -643,16 +871,21 @@ function idempotencyEventPart(event) {
|
|
|
643
871
|
return event.kind;
|
|
644
872
|
}
|
|
645
873
|
function defaultChatSdkEvent(definition, input) {
|
|
646
|
-
const
|
|
647
|
-
|
|
874
|
+
const convert = (chatMessage) => {
|
|
875
|
+
const message = toMessengerMessage(chatMessage);
|
|
876
|
+
message.text = resolveSelfMention(message.text, definition.adapter.botUserId, definition.userName);
|
|
877
|
+
return message;
|
|
878
|
+
};
|
|
879
|
+
const skipped = input.skipped?.length ? input.skipped.map(convert) : void 0;
|
|
648
880
|
return {
|
|
649
881
|
capabilities: definition.capabilities ?? {},
|
|
650
882
|
action: input.action && toMessengerAction(input.action),
|
|
651
883
|
kind: input.eventKind,
|
|
652
|
-
message,
|
|
884
|
+
message: input.message && convert(input.message),
|
|
653
885
|
messengerId: definition.id,
|
|
654
886
|
provider: definition.provider,
|
|
655
887
|
raw: input.raw ?? input.message?.raw,
|
|
888
|
+
...skipped && { skipped },
|
|
656
889
|
thread: toMessengerThread(input.thread)
|
|
657
890
|
};
|
|
658
891
|
}
|
|
@@ -675,6 +908,23 @@ function resolveSelfMention(text, botUserId, userName) {
|
|
|
675
908
|
const replacement = `@${userName}`;
|
|
676
909
|
return text.replace(new RegExp(`<@!?${id}>`, "g"), replacement).replace(new RegExp(`@${id}\\b`, "g"), replacement);
|
|
677
910
|
}
|
|
911
|
+
/**
|
|
912
|
+
* Whether a message mentions the bot. The Chat SDK only runs its own mention
|
|
913
|
+
* detection on the message it dispatches, so messages a burst folded into
|
|
914
|
+
* `skipped` carry `isMention` only when their adapter set it. This mirrors the
|
|
915
|
+
* SDK's check (`@userName`, `@botUserId`, `<@botUserId>`) for them.
|
|
916
|
+
*/
|
|
917
|
+
function mentionsBot(definition, message) {
|
|
918
|
+
if (message.isMention) return true;
|
|
919
|
+
const userName = definition.adapter.userName || definition.userName;
|
|
920
|
+
const patterns = [new RegExp(`@${escapeRegExp(userName)}\\b`, "i")];
|
|
921
|
+
const botUserId = definition.adapter.botUserId;
|
|
922
|
+
if (botUserId) {
|
|
923
|
+
const id = escapeRegExp(botUserId);
|
|
924
|
+
patterns.push(new RegExp(`@${id}\\b`, "i"), new RegExp(`<@!?${id}>`, "i"));
|
|
925
|
+
}
|
|
926
|
+
return patterns.some((pattern) => pattern.test(message.text));
|
|
927
|
+
}
|
|
678
928
|
function escapeRegExp(value) {
|
|
679
929
|
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
680
930
|
}
|
|
@@ -719,13 +969,15 @@ function toMessengerAuthor(author) {
|
|
|
719
969
|
}
|
|
720
970
|
function toMessengerAttachment(attachment) {
|
|
721
971
|
const fetchMetadata = attachment.fetchMetadata;
|
|
972
|
+
const inline = attachment.data;
|
|
973
|
+
const data = inline instanceof ArrayBuffer || ArrayBuffer.isView(inline) ? attachmentBytes(inline) : void 0;
|
|
974
|
+
const blob = inline instanceof Blob ? inline : void 0;
|
|
722
975
|
return {
|
|
976
|
+
data,
|
|
723
977
|
fetch: attachment.fetchData ? async () => {
|
|
724
|
-
const
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
return copy instanceof ArrayBuffer ? copy : /* @__PURE__ */ new ArrayBuffer(0);
|
|
728
|
-
} : void 0,
|
|
978
|
+
const fetched = await attachment.fetchData?.();
|
|
979
|
+
return fetched ? attachmentBytes(fetched) : /* @__PURE__ */ new ArrayBuffer(0);
|
|
980
|
+
} : data ? () => Promise.resolve(data) : blob ? () => blob.arrayBuffer() : void 0,
|
|
729
981
|
fetchMetadata: fetchMetadata ? { ...fetchMetadata } : void 0,
|
|
730
982
|
id: identifierFromFetchMetadata(fetchMetadata),
|
|
731
983
|
mediaType: attachment.mimeType,
|
|
@@ -735,6 +987,20 @@ function toMessengerAttachment(attachment) {
|
|
|
735
987
|
url: attachment.url
|
|
736
988
|
};
|
|
737
989
|
}
|
|
990
|
+
/**
|
|
991
|
+
* `chat` adapters resolve `fetchData` to a `Buffer` or, from `chat@4.41`
|
|
992
|
+
* (inside this package's `^4.31.0` range), a plain `ArrayBuffer`. A `Buffer` is
|
|
993
|
+
* a view that may share a pooled or `SharedArrayBuffer` backing store with
|
|
994
|
+
* unrelated bytes, so only its own range is copied out; a view spanning its
|
|
995
|
+
* whole `ArrayBuffer` hands that buffer over as is.
|
|
996
|
+
*/
|
|
997
|
+
function attachmentBytes(data) {
|
|
998
|
+
if (data instanceof ArrayBuffer) return data;
|
|
999
|
+
if (data.buffer instanceof ArrayBuffer && data.byteOffset === 0 && data.byteLength === data.buffer.byteLength) return data.buffer;
|
|
1000
|
+
const copy = new Uint8Array(data.byteLength);
|
|
1001
|
+
copy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
|
|
1002
|
+
return copy.buffer;
|
|
1003
|
+
}
|
|
738
1004
|
const FETCH_METADATA_ID_KEYS = [
|
|
739
1005
|
"id",
|
|
740
1006
|
"fileId",
|
|
@@ -769,6 +1035,6 @@ function validatePath(path, id) {
|
|
|
769
1035
|
if (path.includes("?") || path.includes("#")) throw new Error(`Messenger ${id} path must not include query or hash`);
|
|
770
1036
|
}
|
|
771
1037
|
//#endregion
|
|
772
|
-
export {
|
|
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 };
|
|
773
1039
|
|
|
774
|
-
//# sourceMappingURL=chat-sdk-
|
|
1040
|
+
//# sourceMappingURL=chat-sdk-BEjKXjCm.js.map
|