@cloudflare/think 0.7.2 → 0.8.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 +420 -43
- package/dist/chat-sdk-CJwYlbp9.js +669 -0
- package/dist/chat-sdk-CJwYlbp9.js.map +1 -0
- package/dist/extensions/index.d.ts +2 -2
- package/dist/{hook-proxy-5248W-ea.js → hook-proxy-DHwqL8MV.js} +1 -1
- package/dist/{hook-proxy-5248W-ea.js.map → hook-proxy-DHwqL8MV.js.map} +1 -1
- package/dist/index-CYp8VDIe.d.ts +2202 -0
- package/dist/{index-BsB4GUsL.d.ts → index-DS00xJwR.d.ts} +2 -2
- package/dist/{manager-DCbSiSWT.d.ts → manager-C1zjft70.d.ts} +1 -1
- package/dist/messengers/index.d.ts +110 -0
- package/dist/messengers/index.js +2 -0
- package/dist/messengers/telegram.d.ts +62 -0
- package/dist/messengers/telegram.js +84 -0
- package/dist/messengers/telegram.js.map +1 -0
- package/dist/think.d.ts +73 -1144
- package/dist/think.js +2370 -179
- package/dist/think.js.map +1 -1
- package/dist/tools/extensions.d.ts +1 -1
- package/dist/tools/workspace.d.ts +35 -334
- package/dist/tools/workspace.js +283 -3
- package/dist/tools/workspace.js.map +1 -1
- package/dist/workflows.d.ts +78 -0
- package/dist/workflows.js +119 -0
- package/dist/workflows.js.map +1 -0
- package/dist/workspace-Bri0ANBX.d.ts +342 -0
- package/package.json +24 -7
|
@@ -0,0 +1,669 @@
|
|
|
1
|
+
import { Chat } from "chat";
|
|
2
|
+
import { ChatSdkStateAgent, createChatSdkState, defaultKeyShard } from "agents/chat-sdk";
|
|
3
|
+
import { RpcTarget } from "cloudflare:workers";
|
|
4
|
+
//#region src/messengers/events.ts
|
|
5
|
+
function messengerContextFromEvent(event) {
|
|
6
|
+
return {
|
|
7
|
+
action: event.action,
|
|
8
|
+
author: event.message?.author ?? event.action?.user,
|
|
9
|
+
capabilities: event.capabilities,
|
|
10
|
+
kind: event.kind,
|
|
11
|
+
message: event.message,
|
|
12
|
+
messengerId: event.messengerId,
|
|
13
|
+
provider: event.provider,
|
|
14
|
+
thread: event.thread
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
function serializableMessengerEvent(event) {
|
|
18
|
+
return {
|
|
19
|
+
capabilities: { ...event.capabilities },
|
|
20
|
+
kind: event.kind,
|
|
21
|
+
messengerId: event.messengerId,
|
|
22
|
+
provider: event.provider,
|
|
23
|
+
thread: { ...event.thread },
|
|
24
|
+
action: event.action ? {
|
|
25
|
+
actionId: event.action.actionId,
|
|
26
|
+
messageId: event.action.messageId,
|
|
27
|
+
user: event.action.user ? { ...event.action.user } : void 0,
|
|
28
|
+
value: event.action.value
|
|
29
|
+
} : void 0,
|
|
30
|
+
message: event.message ? {
|
|
31
|
+
attachments: event.message.attachments.map((attachment) => ({
|
|
32
|
+
id: attachment.id,
|
|
33
|
+
mediaType: attachment.mediaType,
|
|
34
|
+
name: attachment.name,
|
|
35
|
+
size: attachment.size,
|
|
36
|
+
text: attachment.text,
|
|
37
|
+
url: attachment.url
|
|
38
|
+
})),
|
|
39
|
+
author: { ...event.message.author },
|
|
40
|
+
createdAt: event.message.createdAt,
|
|
41
|
+
id: event.message.id,
|
|
42
|
+
isMention: event.message.isMention,
|
|
43
|
+
providerMessageId: event.message.providerMessageId,
|
|
44
|
+
text: event.message.text
|
|
45
|
+
} : void 0
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
function toMessengerUserMessage(event) {
|
|
49
|
+
const message = event.message;
|
|
50
|
+
if (event.action) {
|
|
51
|
+
const user = event.action.user;
|
|
52
|
+
const displayName = user?.fullName || user?.userName || user?.userId;
|
|
53
|
+
const details = [
|
|
54
|
+
`Action selected: ${event.action.actionId}`,
|
|
55
|
+
event.action.value ? `Value: ${event.action.value}` : void 0,
|
|
56
|
+
event.action.messageId ? `Source message: ${event.action.messageId}` : void 0
|
|
57
|
+
].filter(Boolean);
|
|
58
|
+
const text = displayName ? `${displayName}: ${details.join("\n")}` : details.join("\n");
|
|
59
|
+
return {
|
|
60
|
+
id: [
|
|
61
|
+
event.messengerId,
|
|
62
|
+
"action",
|
|
63
|
+
event.thread.id,
|
|
64
|
+
event.action.messageId,
|
|
65
|
+
event.action.actionId
|
|
66
|
+
].filter(Boolean).join(":"),
|
|
67
|
+
role: "user",
|
|
68
|
+
parts: [{
|
|
69
|
+
type: "text",
|
|
70
|
+
text
|
|
71
|
+
}],
|
|
72
|
+
metadata: { messenger: messengerContextFromEvent(event) }
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
if (!message) throw new Error(`Messenger event ${event.kind} does not contain a message`);
|
|
76
|
+
const text = message.text.trim();
|
|
77
|
+
const displayName = message.author.fullName || message.author.userName || message.author.userId;
|
|
78
|
+
const content = event.thread.isDirectMessage || !displayName ? text : `${displayName}: ${text}`;
|
|
79
|
+
const attachmentText = describeAttachments(message.attachments);
|
|
80
|
+
const fullText = [content || text, attachmentText].filter(Boolean).join("\n\n");
|
|
81
|
+
return {
|
|
82
|
+
id: `${event.messengerId}:${message.id}`,
|
|
83
|
+
role: "user",
|
|
84
|
+
parts: [{
|
|
85
|
+
type: "text",
|
|
86
|
+
text: fullText
|
|
87
|
+
}],
|
|
88
|
+
metadata: { messenger: messengerContextFromEvent(event) }
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
function describeAttachments(attachments) {
|
|
92
|
+
if (attachments.length === 0) return "";
|
|
93
|
+
return ["Attachments:", ...attachments.map((attachment, index) => {
|
|
94
|
+
const label = attachment.name || attachment.id || `attachment ${index + 1}`;
|
|
95
|
+
const details = [
|
|
96
|
+
attachment.mediaType,
|
|
97
|
+
attachment.size === void 0 ? void 0 : `${attachment.size} bytes`,
|
|
98
|
+
attachment.url
|
|
99
|
+
].filter(Boolean);
|
|
100
|
+
return `- ${label}${details.length ? ` (${details.join(", ")})` : ""}`;
|
|
101
|
+
})].join("\n");
|
|
102
|
+
}
|
|
103
|
+
//#endregion
|
|
104
|
+
//#region src/messengers/delivery.ts
|
|
105
|
+
const MESSENGER_REPLY_FIBER_NAME = "think:messenger-reply";
|
|
106
|
+
const EMPTY_MESSENGER_RESPONSE = "I couldn't produce a text response. Please try again.";
|
|
107
|
+
const ERROR_MESSENGER_RESPONSE = "Sorry, I couldn't answer that right now. Please try again.";
|
|
108
|
+
const INTERRUPTED_MESSENGER_RESPONSE = "Sorry, my reply was interrupted. Please send your message again if you'd like me to retry.";
|
|
109
|
+
var TextStreamCallback = class extends RpcTarget {
|
|
110
|
+
constructor(options = {}) {
|
|
111
|
+
super();
|
|
112
|
+
this.visibleChunks = [];
|
|
113
|
+
this.wakeups = [];
|
|
114
|
+
this.closed = false;
|
|
115
|
+
this.interrupted = false;
|
|
116
|
+
this.text = "";
|
|
117
|
+
this.visibleClosed = false;
|
|
118
|
+
this.visibleLimitReachedValue = false;
|
|
119
|
+
this.visibleStarted = false;
|
|
120
|
+
this.visibleTextValue = "";
|
|
121
|
+
this.onVisibleStart = options.onVisibleStart;
|
|
122
|
+
this.visibleSoftLimit = options.visibleSoftLimit;
|
|
123
|
+
}
|
|
124
|
+
onStart(event) {
|
|
125
|
+
this.chatRequestId = event.requestId;
|
|
126
|
+
}
|
|
127
|
+
onEvent(json) {
|
|
128
|
+
const text = textDeltaFromStreamChunk(json);
|
|
129
|
+
if (!text) return;
|
|
130
|
+
this.text += text;
|
|
131
|
+
this.pushVisibleText(text);
|
|
132
|
+
this.wake();
|
|
133
|
+
}
|
|
134
|
+
onDone() {
|
|
135
|
+
this.close();
|
|
136
|
+
}
|
|
137
|
+
onError(error) {
|
|
138
|
+
this.fail(new Error(error));
|
|
139
|
+
}
|
|
140
|
+
onInterrupted() {
|
|
141
|
+
this.interrupted = true;
|
|
142
|
+
this.close();
|
|
143
|
+
}
|
|
144
|
+
wasInterrupted() {
|
|
145
|
+
return this.interrupted;
|
|
146
|
+
}
|
|
147
|
+
close() {
|
|
148
|
+
this.closed = true;
|
|
149
|
+
this.visibleClosed = true;
|
|
150
|
+
this.wake();
|
|
151
|
+
}
|
|
152
|
+
fail(error) {
|
|
153
|
+
this.error = error instanceof Error ? error : new Error(String(error));
|
|
154
|
+
this.closed = true;
|
|
155
|
+
this.visibleClosed = true;
|
|
156
|
+
this.wake();
|
|
157
|
+
}
|
|
158
|
+
hasText() {
|
|
159
|
+
return this.text.trim().length > 0;
|
|
160
|
+
}
|
|
161
|
+
remainingText() {
|
|
162
|
+
return this.text.slice(this.visibleTextValue.length);
|
|
163
|
+
}
|
|
164
|
+
requestId() {
|
|
165
|
+
return this.chatRequestId;
|
|
166
|
+
}
|
|
167
|
+
textSoFar() {
|
|
168
|
+
return this.text;
|
|
169
|
+
}
|
|
170
|
+
visibleLimitReached() {
|
|
171
|
+
return this.visibleLimitReachedValue;
|
|
172
|
+
}
|
|
173
|
+
visibleText() {
|
|
174
|
+
return this.visibleTextValue;
|
|
175
|
+
}
|
|
176
|
+
async *stream() {
|
|
177
|
+
while (true) {
|
|
178
|
+
const next = this.visibleChunks.shift();
|
|
179
|
+
if (next !== void 0) {
|
|
180
|
+
await this.markVisibleStarted();
|
|
181
|
+
yield next;
|
|
182
|
+
continue;
|
|
183
|
+
}
|
|
184
|
+
if (this.error) throw this.error;
|
|
185
|
+
if (this.closed || this.visibleClosed) return;
|
|
186
|
+
await new Promise((resolve) => {
|
|
187
|
+
this.wakeups.push(resolve);
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
pushVisibleText(text) {
|
|
192
|
+
if (this.visibleClosed) return;
|
|
193
|
+
if (this.visibleSoftLimit === void 0) {
|
|
194
|
+
this.visibleChunks.push(text);
|
|
195
|
+
this.visibleTextValue += text;
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
const remaining = this.visibleSoftLimit - this.visibleTextValue.length;
|
|
199
|
+
if (remaining <= 0) {
|
|
200
|
+
this.visibleClosed = true;
|
|
201
|
+
this.visibleLimitReachedValue = true;
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
const visible = text.slice(0, remaining);
|
|
205
|
+
if (visible) {
|
|
206
|
+
this.visibleChunks.push(visible);
|
|
207
|
+
this.visibleTextValue += visible;
|
|
208
|
+
}
|
|
209
|
+
if (visible.length < text.length || this.visibleTextValue.length >= this.visibleSoftLimit) {
|
|
210
|
+
this.visibleClosed = true;
|
|
211
|
+
this.visibleLimitReachedValue = true;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
wake() {
|
|
215
|
+
for (const wake of this.wakeups.splice(0)) wake();
|
|
216
|
+
}
|
|
217
|
+
async markVisibleStarted() {
|
|
218
|
+
if (this.visibleStarted) return;
|
|
219
|
+
this.visibleStarted = true;
|
|
220
|
+
await this.onVisibleStart?.();
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
function textDeltaFromStreamChunk(json) {
|
|
224
|
+
try {
|
|
225
|
+
const chunk = JSON.parse(json);
|
|
226
|
+
return chunk.type === "text-delta" && typeof chunk.delta === "string" ? chunk.delta : null;
|
|
227
|
+
} catch {
|
|
228
|
+
return null;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
function messengerReplySnapshot(stage, event, thread) {
|
|
232
|
+
return {
|
|
233
|
+
event,
|
|
234
|
+
stage,
|
|
235
|
+
thread,
|
|
236
|
+
type: MESSENGER_REPLY_FIBER_NAME
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
function parseMessengerReplySnapshot(snapshot) {
|
|
240
|
+
if (snapshot === null || typeof snapshot !== "object") return null;
|
|
241
|
+
const candidate = snapshot;
|
|
242
|
+
if (candidate.type !== "think:messenger-reply" || candidate.stage !== "accepted" && candidate.stage !== "streaming" && candidate.stage !== "completed" || candidate.event === void 0) return null;
|
|
243
|
+
return {
|
|
244
|
+
event: candidate.event,
|
|
245
|
+
stage: candidate.stage,
|
|
246
|
+
thread: candidate.thread,
|
|
247
|
+
type: MESSENGER_REPLY_FIBER_NAME
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
function messengerReplyRecoveryMode(snapshot) {
|
|
251
|
+
if (snapshot.stage === "accepted") return "answer";
|
|
252
|
+
if (snapshot.stage === "streaming") return "apologize";
|
|
253
|
+
return null;
|
|
254
|
+
}
|
|
255
|
+
function messengerReplyFailureMode(hasStreamedText, completedModelTurn = false, expectedDeliveryCompletion = false) {
|
|
256
|
+
if (expectedDeliveryCompletion) return null;
|
|
257
|
+
if (completedModelTurn) return "error";
|
|
258
|
+
return hasStreamedText ? "apologize" : "error";
|
|
259
|
+
}
|
|
260
|
+
async function deliverMessengerReply(options) {
|
|
261
|
+
const emptyResponseText = options.policy?.emptyResponseText ?? "I couldn't produce a text response. Please try again.";
|
|
262
|
+
const errorResponseText = options.policy?.errorResponseText ?? "Sorry, I couldn't answer that right now. Please try again.";
|
|
263
|
+
const interruptedResponseText = options.policy?.interruptedResponseText ?? "Sorry, my reply was interrupted. Please send your message again if you'd like me to retry.";
|
|
264
|
+
let completedModelTurn = false;
|
|
265
|
+
const snapshotEvent = options.snapshotEvent ?? options.event;
|
|
266
|
+
const checkpoint = options.checkpoint ?? ((snapshot) => {
|
|
267
|
+
options.fiber?.stash(snapshot);
|
|
268
|
+
});
|
|
269
|
+
const callback = new TextStreamCallback({
|
|
270
|
+
onVisibleStart: async () => {
|
|
271
|
+
await checkpoint(messengerReplySnapshot("streaming", snapshotEvent, options.snapshotThread));
|
|
272
|
+
},
|
|
273
|
+
visibleSoftLimit: options.policy?.visibleSoftLimit
|
|
274
|
+
});
|
|
275
|
+
const post = options.surface.post(callback.stream()).catch(async (error) => {
|
|
276
|
+
if (options.policy?.isExpectedDeliveryCompletion?.(error, callback)) return;
|
|
277
|
+
const requestId = callback.requestId();
|
|
278
|
+
if (requestId) await Promise.resolve(options.target.cancelChat(requestId, toError(error).message)).catch(() => void 0);
|
|
279
|
+
callback.fail(error);
|
|
280
|
+
throw error;
|
|
281
|
+
});
|
|
282
|
+
try {
|
|
283
|
+
await options.surface.startTyping?.("Thinking...");
|
|
284
|
+
const userMessage = options.userMessage ?? toMessengerUserMessage(options.event);
|
|
285
|
+
if (options.target.chatWithMessengerContext) await options.target.chatWithMessengerContext(userMessage, callback, snapshotEvent);
|
|
286
|
+
else await options.target.chat(userMessage, callback);
|
|
287
|
+
if (callback.wasInterrupted()) {
|
|
288
|
+
callback.close();
|
|
289
|
+
await post.catch(() => void 0);
|
|
290
|
+
await options.surface.post(interruptedResponseText).catch(() => void 0);
|
|
291
|
+
await checkpoint(messengerReplySnapshot("completed", snapshotEvent, options.snapshotThread));
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
completedModelTurn = true;
|
|
295
|
+
callback.close();
|
|
296
|
+
await post;
|
|
297
|
+
if (!callback.hasText()) await options.surface.post(emptyResponseText);
|
|
298
|
+
for (const chunk of options.policy?.splitText?.(callback.remainingText()) ?? []) await options.surface.post(chunk);
|
|
299
|
+
await checkpoint(messengerReplySnapshot("completed", snapshotEvent, options.snapshotThread));
|
|
300
|
+
} catch (error) {
|
|
301
|
+
callback.fail(error);
|
|
302
|
+
await post.catch(() => void 0);
|
|
303
|
+
const failureMode = messengerReplyFailureMode(callback.hasText(), completedModelTurn, options.policy?.isExpectedDeliveryCompletion?.(error, callback));
|
|
304
|
+
if (failureMode === null) {
|
|
305
|
+
await checkpoint(messengerReplySnapshot("completed", snapshotEvent, options.snapshotThread));
|
|
306
|
+
return;
|
|
307
|
+
}
|
|
308
|
+
if (failureMode === "apologize") {
|
|
309
|
+
await options.surface.post(interruptedResponseText).catch(() => void 0);
|
|
310
|
+
await checkpoint(messengerReplySnapshot("completed", snapshotEvent, options.snapshotThread));
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
313
|
+
await options.surface.post({ markdown: errorResponseText }).catch(() => void 0);
|
|
314
|
+
await checkpoint(messengerReplySnapshot("completed", snapshotEvent, options.snapshotThread));
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
function toError(error) {
|
|
318
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
319
|
+
}
|
|
320
|
+
//#endregion
|
|
321
|
+
//#region src/messengers/chat-sdk.ts
|
|
322
|
+
var ThinkMessengerStateAgent = class extends ChatSdkStateAgent {};
|
|
323
|
+
function defineMessengers(messengers) {
|
|
324
|
+
return messengers;
|
|
325
|
+
}
|
|
326
|
+
function chatSdkMessenger(options) {
|
|
327
|
+
return {
|
|
328
|
+
...options,
|
|
329
|
+
adapterName: options.adapterName ?? options.provider
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
var ThinkMessengerRuntime = class {
|
|
333
|
+
constructor(definitions, host) {
|
|
334
|
+
this.host = host;
|
|
335
|
+
this.definitionsByAdapterName = /* @__PURE__ */ new Map();
|
|
336
|
+
this.definitionsById = /* @__PURE__ */ new Map();
|
|
337
|
+
this.definitions = normalizeMessengers(definitions);
|
|
338
|
+
for (const definition of this.definitions) {
|
|
339
|
+
this.definitionsByAdapterName.set(definition.adapterName, definition);
|
|
340
|
+
this.definitionsById.set(definition.id, definition);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
get size() {
|
|
344
|
+
return this.definitions.length;
|
|
345
|
+
}
|
|
346
|
+
initialize() {
|
|
347
|
+
if (this.host.parentPath.length > 0) return;
|
|
348
|
+
this.chat = this.createChat();
|
|
349
|
+
}
|
|
350
|
+
async handleRequest(request) {
|
|
351
|
+
if (this.host.parentPath.length > 0) return;
|
|
352
|
+
const url = new URL(request.url);
|
|
353
|
+
const definition = this.definitions.find((candidate) => candidate.path === url.pathname);
|
|
354
|
+
if (!definition) return;
|
|
355
|
+
if (request.method !== "POST") return new Response("Method not allowed", { status: 405 });
|
|
356
|
+
if (definition.verifyWebhook !== false) {
|
|
357
|
+
const verification = await definition.verifyWebhook(request.clone());
|
|
358
|
+
if (verification instanceof Response) return verification;
|
|
359
|
+
if (verification === false) return new Response("Unauthorized", { status: 401 });
|
|
360
|
+
}
|
|
361
|
+
const chat = this.chat ?? this.createChat();
|
|
362
|
+
this.chat = chat;
|
|
363
|
+
return chat.webhooks[definition.adapterName](request);
|
|
364
|
+
}
|
|
365
|
+
async handleFiberRecovery(ctx) {
|
|
366
|
+
if (ctx.name !== "think:messenger-reply") return false;
|
|
367
|
+
const snapshot = parseMessengerReplySnapshot(ctx.snapshot);
|
|
368
|
+
if (!snapshot) return false;
|
|
369
|
+
const definition = this.definitionsById.get(snapshot.event.messengerId);
|
|
370
|
+
if (!definition) throw new Error(`No messenger definition found for recovered messenger ${snapshot.event.messengerId}`);
|
|
371
|
+
const thread = this.reviveChatObject(snapshot.thread);
|
|
372
|
+
const mode = messengerReplyRecoveryMode(snapshot);
|
|
373
|
+
if (mode === "answer") {
|
|
374
|
+
await this.answer(definition, snapshot.event, thread, void 0, snapshot.event, async (nextSnapshot) => {
|
|
375
|
+
await this.host.resolveFiber(ctx.id, {
|
|
376
|
+
snapshot: nextSnapshot,
|
|
377
|
+
status: nextSnapshot.stage === "completed" ? "completed" : "interrupted"
|
|
378
|
+
});
|
|
379
|
+
});
|
|
380
|
+
return true;
|
|
381
|
+
}
|
|
382
|
+
if (mode === "apologize") {
|
|
383
|
+
await thread.post(definition.delivery?.interruptedResponseText ?? "Sorry, my reply was interrupted. Please send your message again if you'd like me to retry.");
|
|
384
|
+
await this.host.resolveFiber(ctx.id, { status: "completed" });
|
|
385
|
+
return true;
|
|
386
|
+
}
|
|
387
|
+
await this.host.resolveFiber(ctx.id, { status: "completed" });
|
|
388
|
+
return true;
|
|
389
|
+
}
|
|
390
|
+
createChat() {
|
|
391
|
+
const chat = new Chat({
|
|
392
|
+
adapters: Object.fromEntries(this.definitions.map((definition) => [definition.adapterName, definition.adapter])),
|
|
393
|
+
concurrency: {
|
|
394
|
+
debounceMs: 600,
|
|
395
|
+
strategy: "burst"
|
|
396
|
+
},
|
|
397
|
+
state: createChatSdkState({
|
|
398
|
+
agent: ThinkMessengerStateAgent,
|
|
399
|
+
keyShard: (key) => this.shardStateKey(key),
|
|
400
|
+
parent: this.host,
|
|
401
|
+
shardKey: (threadId) => this.shardThread(threadId)
|
|
402
|
+
}),
|
|
403
|
+
userName: this.definitions[0]?.userName ?? "think"
|
|
404
|
+
});
|
|
405
|
+
chat.onDirectMessage(async (thread, message) => {
|
|
406
|
+
const definition = this.definitionForThread(thread);
|
|
407
|
+
if (!definition) return;
|
|
408
|
+
if (definition.respondTo.includes("direct-message")) await this.enqueueReply(definition, await this.toEvent(definition, {
|
|
409
|
+
eventKind: "direct-message",
|
|
410
|
+
message,
|
|
411
|
+
thread
|
|
412
|
+
}), thread);
|
|
413
|
+
});
|
|
414
|
+
chat.onNewMention(async (thread, message) => {
|
|
415
|
+
const definition = this.definitionForThread(thread);
|
|
416
|
+
if (!definition) return;
|
|
417
|
+
if (definition.subscribeOnMention) await thread.subscribe();
|
|
418
|
+
if (definition.respondTo.includes("mention")) await this.enqueueReply(definition, await this.toEvent(definition, {
|
|
419
|
+
eventKind: "mention",
|
|
420
|
+
message,
|
|
421
|
+
thread
|
|
422
|
+
}), thread);
|
|
423
|
+
});
|
|
424
|
+
chat.onSubscribedMessage(async (thread, message) => {
|
|
425
|
+
const definition = this.definitionForThread(thread);
|
|
426
|
+
if (!definition) return;
|
|
427
|
+
if (definition.respondTo.includes("subscribed-thread") || message.isMention && definition.respondTo.includes("mention")) await this.enqueueReply(definition, await this.toEvent(definition, {
|
|
428
|
+
eventKind: message.isMention ? "mention" : "subscribed-message",
|
|
429
|
+
message,
|
|
430
|
+
thread
|
|
431
|
+
}), thread);
|
|
432
|
+
});
|
|
433
|
+
chat.onAction(async (event) => {
|
|
434
|
+
if (!event.thread) return;
|
|
435
|
+
const thread = event.thread;
|
|
436
|
+
const definition = this.definitionForThread(thread);
|
|
437
|
+
if (!definition) return;
|
|
438
|
+
if (definition.respondTo.includes("action")) await this.enqueueReply(definition, await this.toEvent(definition, {
|
|
439
|
+
action: event,
|
|
440
|
+
eventKind: "action",
|
|
441
|
+
raw: event.raw,
|
|
442
|
+
thread
|
|
443
|
+
}), thread);
|
|
444
|
+
});
|
|
445
|
+
return chat.registerSingleton();
|
|
446
|
+
}
|
|
447
|
+
async enqueueReply(definition, event, thread) {
|
|
448
|
+
const snapshotEvent = serializableMessengerEvent(event);
|
|
449
|
+
const snapshotThread = thread.toJSON();
|
|
450
|
+
const result = await this.host.startFiber(MESSENGER_REPLY_FIBER_NAME, async (fiber) => {
|
|
451
|
+
fiber.stash(messengerReplySnapshot("accepted", snapshotEvent, snapshotThread));
|
|
452
|
+
await this.answer(definition, event, thread, fiber, snapshotEvent);
|
|
453
|
+
}, {
|
|
454
|
+
idempotencyKey: idempotencyKeyForEvent(event),
|
|
455
|
+
metadata: {
|
|
456
|
+
messengerId: event.messengerId,
|
|
457
|
+
messageId: event.message?.id,
|
|
458
|
+
provider: event.provider,
|
|
459
|
+
threadId: event.thread.id
|
|
460
|
+
},
|
|
461
|
+
waitForCompletion: true
|
|
462
|
+
});
|
|
463
|
+
if (result.accepted || result.status !== "interrupted") return;
|
|
464
|
+
const snapshot = parseMessengerReplySnapshot(result.snapshot);
|
|
465
|
+
if (!snapshot) return;
|
|
466
|
+
const mode = messengerReplyRecoveryMode(snapshot);
|
|
467
|
+
if (mode === "answer") {
|
|
468
|
+
await this.answer(definition, snapshot.event, thread, void 0, snapshot.event, async (nextSnapshot) => {
|
|
469
|
+
await this.host.resolveFiber(result.fiberId, {
|
|
470
|
+
snapshot: nextSnapshot,
|
|
471
|
+
status: nextSnapshot.stage === "completed" ? "completed" : "interrupted"
|
|
472
|
+
});
|
|
473
|
+
});
|
|
474
|
+
return;
|
|
475
|
+
}
|
|
476
|
+
if (mode === "apologize") {
|
|
477
|
+
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);
|
|
478
|
+
await this.host.resolveFiber(result.fiberId, { status: "completed" });
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
async answer(definition, event, thread, fiber, snapshotEvent = serializableMessengerEvent(event), checkpoint) {
|
|
482
|
+
const target = await this.resolveTarget(definition, event);
|
|
483
|
+
await deliverMessengerReply({
|
|
484
|
+
event,
|
|
485
|
+
checkpoint,
|
|
486
|
+
fiber,
|
|
487
|
+
policy: definition.delivery,
|
|
488
|
+
snapshotEvent,
|
|
489
|
+
snapshotThread: thread.toJSON(),
|
|
490
|
+
surface: thread,
|
|
491
|
+
target,
|
|
492
|
+
userMessage: toMessengerUserMessage(event)
|
|
493
|
+
});
|
|
494
|
+
}
|
|
495
|
+
async resolveTarget(definition, event) {
|
|
496
|
+
const conversation = definition.conversation ?? "thread";
|
|
497
|
+
const target = typeof conversation === "function" ? await conversation(event) : conversation === "self" ? { target: "self" } : {
|
|
498
|
+
name: defaultConversationName(event),
|
|
499
|
+
target: "subagent"
|
|
500
|
+
};
|
|
501
|
+
if (target.target === "self") return this.host;
|
|
502
|
+
const agentClass = target.agentClass ?? this.host.constructor;
|
|
503
|
+
return await this.host.subAgent(agentClass, target.name);
|
|
504
|
+
}
|
|
505
|
+
definitionForThread(thread) {
|
|
506
|
+
return this.definitionsByAdapterName.get(thread.toJSON().adapterName) ?? this.definitionForThreadId(thread.id) ?? this.definitionForThreadId(thread.channelId);
|
|
507
|
+
}
|
|
508
|
+
definitionForThreadId(threadId) {
|
|
509
|
+
if (!threadId) return;
|
|
510
|
+
if (this.definitions.length === 1) return this.definitions[0];
|
|
511
|
+
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}:`));
|
|
512
|
+
}
|
|
513
|
+
hasUniqueProvider(provider) {
|
|
514
|
+
return this.definitions.filter((definition) => definition.provider === provider).length === 1;
|
|
515
|
+
}
|
|
516
|
+
shardThread(threadId) {
|
|
517
|
+
return this.definitionForThreadId(threadId)?.shardKey?.(threadId) || threadId.split(":").slice(0, 2).join(":") || "default";
|
|
518
|
+
}
|
|
519
|
+
shardStateKey(key) {
|
|
520
|
+
for (const definition of this.definitions) {
|
|
521
|
+
const shard = definition.keyShard?.(key);
|
|
522
|
+
if (shard) return shard;
|
|
523
|
+
}
|
|
524
|
+
return defaultKeyShard(key, (threadId) => this.shardThread(threadId));
|
|
525
|
+
}
|
|
526
|
+
reviveChatObject(value) {
|
|
527
|
+
if (value === void 0) throw new Error("Messenger recovery snapshot is missing chat object data");
|
|
528
|
+
const chat = this.chat ?? this.createChat();
|
|
529
|
+
this.chat = chat;
|
|
530
|
+
return JSON.parse(JSON.stringify(value), chat.reviver());
|
|
531
|
+
}
|
|
532
|
+
async toEvent(definition, input) {
|
|
533
|
+
return await definition.toEvent?.(input) ?? defaultChatSdkEvent(definition, input);
|
|
534
|
+
}
|
|
535
|
+
};
|
|
536
|
+
function normalizeMessengers(messengers) {
|
|
537
|
+
const ids = /* @__PURE__ */ new Set();
|
|
538
|
+
const adapterNames = /* @__PURE__ */ new Set();
|
|
539
|
+
const paths = /* @__PURE__ */ new Set();
|
|
540
|
+
const normalized = [];
|
|
541
|
+
for (const [id, definition] of Object.entries(messengers)) {
|
|
542
|
+
if (ids.has(id)) throw new Error(`Duplicate messenger id: ${id}`);
|
|
543
|
+
ids.add(id);
|
|
544
|
+
const path = definition.path ?? `/messengers/${id}/webhook`;
|
|
545
|
+
validatePath(path, id);
|
|
546
|
+
if (definition.verifyWebhook === void 0) throw new Error(`Messenger ${id} requires verifyWebhook, or verifyWebhook: false to opt out explicitly`);
|
|
547
|
+
const verifyWebhook = definition.verifyWebhook;
|
|
548
|
+
if (adapterNames.has(definition.adapterName)) throw new Error(`Duplicate messenger adapter name: ${definition.adapterName}`);
|
|
549
|
+
adapterNames.add(definition.adapterName);
|
|
550
|
+
if (paths.has(path)) throw new Error(`Duplicate messenger path: ${path}`);
|
|
551
|
+
paths.add(path);
|
|
552
|
+
normalized.push({
|
|
553
|
+
...definition,
|
|
554
|
+
id,
|
|
555
|
+
path,
|
|
556
|
+
respondTo: definition.respondTo ?? ["direct-message", "mention"],
|
|
557
|
+
subscribeOnMention: definition.subscribeOnMention ?? true,
|
|
558
|
+
verifyWebhook
|
|
559
|
+
});
|
|
560
|
+
}
|
|
561
|
+
return normalized;
|
|
562
|
+
}
|
|
563
|
+
function defaultConversationName(event) {
|
|
564
|
+
return `messenger:${event.messengerId}:${stableNamePart(event.thread.id)}`;
|
|
565
|
+
}
|
|
566
|
+
function idempotencyKeyForEvent(event) {
|
|
567
|
+
return [
|
|
568
|
+
"messenger",
|
|
569
|
+
event.messengerId,
|
|
570
|
+
"message",
|
|
571
|
+
event.thread.id,
|
|
572
|
+
idempotencyEventPart(event)
|
|
573
|
+
].join(":");
|
|
574
|
+
}
|
|
575
|
+
function idempotencyEventPart(event) {
|
|
576
|
+
if (event.message) return event.message.id;
|
|
577
|
+
if (event.action) return [
|
|
578
|
+
"action",
|
|
579
|
+
stableNamePart(event.action.messageId ?? "unknown-message"),
|
|
580
|
+
stableNamePart(event.action.actionId),
|
|
581
|
+
stableNamePart(event.action.user?.userId ?? "unknown-user"),
|
|
582
|
+
stableNamePart(event.action.value ?? "no-value")
|
|
583
|
+
].join(":");
|
|
584
|
+
return event.kind;
|
|
585
|
+
}
|
|
586
|
+
function defaultChatSdkEvent(definition, input) {
|
|
587
|
+
return {
|
|
588
|
+
capabilities: definition.capabilities ?? {},
|
|
589
|
+
action: input.action && toMessengerAction(input.action),
|
|
590
|
+
kind: input.eventKind,
|
|
591
|
+
message: input.message && toMessengerMessage(input.message),
|
|
592
|
+
messengerId: definition.id,
|
|
593
|
+
provider: definition.provider,
|
|
594
|
+
raw: input.raw ?? input.message?.raw,
|
|
595
|
+
thread: toMessengerThread(input.thread)
|
|
596
|
+
};
|
|
597
|
+
}
|
|
598
|
+
function toMessengerAction(action) {
|
|
599
|
+
return {
|
|
600
|
+
actionId: action.actionId,
|
|
601
|
+
messageId: action.messageId,
|
|
602
|
+
raw: action.raw,
|
|
603
|
+
user: toMessengerAuthor(action.user),
|
|
604
|
+
value: action.value
|
|
605
|
+
};
|
|
606
|
+
}
|
|
607
|
+
function toMessengerThread(thread) {
|
|
608
|
+
return {
|
|
609
|
+
channelId: thread.channelId,
|
|
610
|
+
channelName: thread.channel.name ?? void 0,
|
|
611
|
+
id: thread.id,
|
|
612
|
+
isDirectMessage: thread.isDM,
|
|
613
|
+
providerThreadId: thread.id
|
|
614
|
+
};
|
|
615
|
+
}
|
|
616
|
+
function toMessengerMessage(message) {
|
|
617
|
+
return {
|
|
618
|
+
attachments: message.attachments.map(toMessengerAttachment),
|
|
619
|
+
author: toMessengerAuthor(message.author),
|
|
620
|
+
createdAt: message.metadata.dateSent,
|
|
621
|
+
id: message.id,
|
|
622
|
+
isMention: message.isMention,
|
|
623
|
+
providerMessageId: message.id,
|
|
624
|
+
raw: message.raw,
|
|
625
|
+
text: message.text
|
|
626
|
+
};
|
|
627
|
+
}
|
|
628
|
+
function toMessengerAuthor(author) {
|
|
629
|
+
return {
|
|
630
|
+
fullName: author.fullName || void 0,
|
|
631
|
+
isBot: author.isBot,
|
|
632
|
+
isMe: author.isMe,
|
|
633
|
+
userId: author.userId,
|
|
634
|
+
userName: author.userName || void 0
|
|
635
|
+
};
|
|
636
|
+
}
|
|
637
|
+
function toMessengerAttachment(attachment) {
|
|
638
|
+
return {
|
|
639
|
+
fetch: attachment.fetchData ? async () => {
|
|
640
|
+
const data = await attachment.fetchData?.();
|
|
641
|
+
if (!data) return /* @__PURE__ */ new ArrayBuffer(0);
|
|
642
|
+
const copy = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
|
|
643
|
+
return copy instanceof ArrayBuffer ? copy : /* @__PURE__ */ new ArrayBuffer(0);
|
|
644
|
+
} : void 0,
|
|
645
|
+
mediaType: attachment.mimeType,
|
|
646
|
+
name: attachment.name,
|
|
647
|
+
raw: attachment,
|
|
648
|
+
size: attachment.size,
|
|
649
|
+
url: attachment.url
|
|
650
|
+
};
|
|
651
|
+
}
|
|
652
|
+
function stableNamePart(value) {
|
|
653
|
+
const safe = value.replace(/[^a-zA-Z0-9:_-]/g, "_");
|
|
654
|
+
if (safe.length <= 80) return safe;
|
|
655
|
+
return `${safe.slice(0, 48)}_${hashString(value)}`;
|
|
656
|
+
}
|
|
657
|
+
function hashString(value) {
|
|
658
|
+
let hash = 5381;
|
|
659
|
+
for (let index = 0; index < value.length; index += 1) hash = hash * 33 ^ value.charCodeAt(index);
|
|
660
|
+
return (hash >>> 0).toString(36);
|
|
661
|
+
}
|
|
662
|
+
function validatePath(path, id) {
|
|
663
|
+
if (!path.startsWith("/")) throw new Error(`Messenger ${id} path must start with "/"`);
|
|
664
|
+
if (path.includes("?") || path.includes("#")) throw new Error(`Messenger ${id} path must not include query or hash`);
|
|
665
|
+
}
|
|
666
|
+
//#endregion
|
|
667
|
+
export { textDeltaFromStreamChunk as C, toMessengerUserMessage as E, parseMessengerReplySnapshot as S, serializableMessengerEvent as T, TextStreamCallback as _, defaultConversationName as a, messengerReplyRecoveryMode as b, normalizeMessengers 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, defineMessengers as o, EMPTY_MESSENGER_RESPONSE as p, chatSdkMessenger as r, idempotencyKeyForEvent as s, ThinkMessengerRuntime as t, toMessengerAuthor as u, deliverMessengerReply as v, messengerContextFromEvent as w, messengerReplySnapshot as x, messengerReplyFailureMode as y };
|
|
668
|
+
|
|
669
|
+
//# sourceMappingURL=chat-sdk-CJwYlbp9.js.map
|