@segmentstream/agent 0.72.5 → 0.73.1

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 (101) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/dist/_chunks/{build-metadata-BBfrovia.mjs → build-metadata-B-1ohlK8.mjs} +1 -1
  3. package/dist/_chunks/chat-archive-BCPLSZeK.mjs +585 -0
  4. package/dist/_chunks/chat-archive-DK7uCgff.mjs +1337 -0
  5. package/dist/_chunks/{principal-Cw1NtCkj.mjs → principal-Zf42Yf4r.mjs} +1 -1
  6. package/dist/extension/config.d.ts +8 -0
  7. package/dist/extension/config.mjs +12 -0
  8. package/dist/extension/connections/ontology.mjs +1 -1
  9. package/dist/extension/hooks/authorization.mjs +1 -1
  10. package/dist/extension/hooks/chat-context.mjs +1 -1
  11. package/dist/extension/hooks/chat-recorder.mjs +1 -1
  12. package/dist/extension/instructions/persona.mjs +1 -1
  13. package/dist/extension/lib/actor.mjs +1 -1
  14. package/dist/extension/lib/attachment-tools.mjs +1 -1
  15. package/dist/extension/lib/attachments-send.mjs +1 -1
  16. package/dist/extension/lib/attachments.mjs +1 -1
  17. package/dist/extension/lib/build-metadata.mjs +1 -1
  18. package/dist/extension/lib/chat-address.mjs +1 -1
  19. package/dist/extension/lib/chat-archive.d.ts +50 -0
  20. package/dist/extension/lib/chat-archive.mjs +1 -188
  21. package/dist/extension/lib/chat-context.d.ts +10 -2
  22. package/dist/extension/lib/chat-context.mjs +48 -9
  23. package/dist/extension/lib/chat-messages.mjs +13 -1
  24. package/dist/extension/lib/chat-recorder.d.ts +2 -0
  25. package/dist/extension/lib/chat-recorder.mjs +105 -4
  26. package/dist/extension/lib/chat-store.d.ts +212 -0
  27. package/dist/extension/lib/chat-store.mjs +103 -0
  28. package/dist/extension/lib/confirmations.mjs +1 -1
  29. package/dist/extension/lib/email/attachments-send.mjs +1 -1
  30. package/dist/extension/lib/email/channel.mjs +2 -2
  31. package/dist/extension/lib/group-routing/routing-context.mjs +21 -11
  32. package/dist/extension/lib/guest-usage.mjs +1 -1
  33. package/dist/extension/lib/inbound-media/files.mjs +1 -1
  34. package/dist/extension/lib/inbound-media/index.mjs +1 -1
  35. package/dist/extension/lib/model-service-alert.mjs +14 -1
  36. package/dist/extension/lib/ontology-connection.mjs +1 -1
  37. package/dist/extension/lib/ontology-file-call.mjs +1 -1
  38. package/dist/extension/lib/ontology-tools.mjs +1 -1
  39. package/dist/extension/lib/review/hold.mjs +1 -1
  40. package/dist/extension/lib/review/judge.mjs +1 -1
  41. package/dist/extension/lib/review/reply.mjs +2 -2
  42. package/dist/extension/lib/review/revision-channel.mjs +1 -1
  43. package/dist/extension/lib/role-skill.mjs +1 -1
  44. package/dist/extension/lib/runtime-envelope.mjs +1 -1
  45. package/dist/extension/lib/sent-files.mjs +1 -1
  46. package/dist/extension/lib/slack/adapter.mjs +2 -2
  47. package/dist/extension/lib/slack/attachments-send.mjs +1 -1
  48. package/dist/extension/lib/slack/callbacks.mjs +1 -1
  49. package/dist/extension/lib/stored-files.mjs +1 -1
  50. package/dist/extension/lib/telegram/adapter.mjs +4 -4
  51. package/dist/extension/lib/telegram/attachment-description.mjs +1 -1
  52. package/dist/extension/lib/telegram/attachments-send.mjs +5 -3
  53. package/dist/extension/lib/telegram/callbacks.mjs +1 -1
  54. package/dist/extension/lib/telegram/chat-archive.d.ts +32 -3
  55. package/dist/extension/lib/telegram/chat-archive.mjs +1 -703
  56. package/dist/extension/lib/telegram/confirmations.mjs +2 -2
  57. package/dist/extension/lib/telegram/customer-text.mjs +1 -1
  58. package/dist/extension/lib/telegram/delivery-diagnostics.mjs +1 -1
  59. package/dist/extension/lib/telegram/files.mjs +1 -1
  60. package/dist/extension/lib/telegram/format.d.ts +6 -0
  61. package/dist/extension/lib/telegram/format.mjs +29 -1
  62. package/dist/extension/lib/telegram/health.mjs +1 -1
  63. package/dist/extension/lib/telegram/held-approvals.mjs +1 -1
  64. package/dist/extension/lib/telegram/inbound-request.d.ts +2 -1
  65. package/dist/extension/lib/telegram/inbound-request.mjs +1 -1
  66. package/dist/extension/lib/telegram/inbound.mjs +2 -2
  67. package/dist/extension/lib/telegram/lifecycle.mjs +2 -2
  68. package/dist/extension/lib/telegram/principal.mjs +1 -1
  69. package/dist/extension/lib/telegram/session-recovery.mjs +1 -1
  70. package/dist/extension/lib/telegram/silent.mjs +1 -1
  71. package/dist/extension/lib/telegram/store-capture.d.ts +37 -0
  72. package/dist/extension/lib/telegram/store-capture.mjs +7 -0
  73. package/dist/extension/lib/telegram/structured.mjs +1 -1
  74. package/dist/extension/lib/telegram/turn-errors.mjs +2 -2
  75. package/dist/extension/lib/traces.d.ts +21 -0
  76. package/dist/extension/lib/traces.mjs +16 -0
  77. package/dist/extension/lib/web/auth.mjs +1 -1
  78. package/dist/extension/lib/web/channel.mjs +1 -1
  79. package/dist/extension/lib/whatsapp/adapter.mjs +2 -2
  80. package/dist/extension/lib/whatsapp/attachments-send.mjs +2 -2
  81. package/dist/extension/lib/whatsapp/callbacks.mjs +1 -1
  82. package/dist/extension/lib/whatsapp/files.mjs +1 -1
  83. package/dist/extension/lib/whatsapp/sent.mjs +1 -1
  84. package/dist/extension/lib/workspace-action.mjs +1 -1
  85. package/dist/extension/lib/workspace-channel/attachments-send.mjs +1 -1
  86. package/dist/extension/lib/workspace-channel/channel.mjs +2 -2
  87. package/dist/extension/lib/workspace-chat-archive.d.ts +41 -0
  88. package/dist/extension/lib/workspace-chat-archive.mjs +7 -0
  89. package/dist/extension/lib/workspace-source.mjs +1 -1
  90. package/dist/extension/model.mjs +1 -1
  91. package/dist/extension/tools/attachments_discard.mjs +1 -1
  92. package/dist/extension/tools/attachments_list.mjs +1 -1
  93. package/dist/extension/tools/attachments_promote.mjs +1 -1
  94. package/dist/extension/tools/attachments_read.mjs +1 -1
  95. package/dist/extension/tools/attachments_send.mjs +1 -1
  96. package/dist/extension/tools/attachments_stage.mjs +1 -1
  97. package/dist/extension/tools/attachments_table.mjs +1 -1
  98. package/dist/extension/tools/handoff.mjs +1 -1
  99. package/dist/extension/tools/questions_ask.mjs +1 -1
  100. package/dist/extension/tools/workspace_source.mjs +1 -1
  101. package/package.json +6 -2
@@ -4,706 +4,4 @@ import { createRequire as __eveCreateRequire } from "node:module";
4
4
  const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
- import { parseArchivedMessage } from "./archive-message.mjs";
8
- import { currentChannel, currentKey } from "../channel-scope.mjs";
9
- import { n as contentText, t as CONTENT_CAPS } from "../../../_chunks/content-cDtVnr8Y.mjs";
10
- import { chatEvent, sessionFailureEventId } from "../chat-archive.mjs";
11
- import { currentConfirmationPrompt } from "../group-routing/messages.mjs";
12
- import { messageMetadata } from "./message-metadata.mjs";
13
- import { c as currentInboundRequest, ht as currentThreadId, xt as reportTelegramError } from "../../../_chunks/principal-Cw1NtCkj.mjs";
14
- import { reportMembership } from "./membership.mjs";
15
- import { currentDeliveryScope } from "./delivery-diagnostics.mjs";
16
- import { contentShape, messageContent } from "./content.mjs";
17
- import { createHash, randomUUID } from "node:crypto";
18
- const captures = new WeakMap();
19
- const record = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
20
- const id = (value) => typeof value === "number" || typeof value === "string" ? String(value) : null;
21
- const REVISION_CLAIM_TTL_MS = 12e4;
22
- function attachmentRefs(message) {
23
- const files = message.attachments.map((file) => ({
24
- id: file.fileId,
25
- kind: file.kind,
26
- ...file.fileName === void 0 ? {} : { filename: file.fileName },
27
- ...file.mediaType === void 0 ? {} : { contentType: file.mediaType },
28
- ...file.size === void 0 ? {} : { size: file.size },
29
- ...file.fileUniqueId === void 0 ? {} : { uniqueId: file.fileUniqueId }
30
- }));
31
- for (const kind of [
32
- "voice",
33
- "audio",
34
- "video",
35
- "video_note",
36
- "sticker",
37
- "animation"
38
- ]) {
39
- const file = record(message.raw[kind]);
40
- const fileId = id(file.file_id);
41
- if (fileId !== null) files.push({
42
- id: fileId,
43
- kind,
44
- ...id(file.file_unique_id) ? { uniqueId: id(file.file_unique_id) } : {},
45
- ...typeof file.file_size === "number" ? { size: file.file_size } : {},
46
- ...typeof file.mime_type === "string" ? { contentType: file.mime_type } : {},
47
- ...typeof file.file_name === "string" ? { filename: file.file_name } : {}
48
- });
49
- }
50
- return files;
51
- }
52
- function attachmentIdentity(files) {
53
- return JSON.stringify(files.map((file) => [file.kind, file.uniqueId ?? file.id]));
54
- }
55
- function eventRouting(event) {
56
- try {
57
- return record(record(JSON.parse(event.argsSummary ?? "{}")).routing);
58
- } catch {
59
- return {};
60
- }
61
- }
62
- async function participants(message, identities, resolved) {
63
- if (message.chat.type !== "private" || message.from === void 0 || message.from.isBot) return [];
64
- try {
65
- const lookup = await identities.lookup({
66
- provider: "telegram",
67
- externalId: message.from.id
68
- });
69
- resolved(lookup);
70
- return lookup.status === "paired" ? [lookup.member.id] : [];
71
- } catch (error) {
72
- console.error("[segmentstream] chat participant lookup failed", { error });
73
- return [];
74
- }
75
- }
76
- async function captureTelegramWebhook(input) {
77
- let raw;
78
- try {
79
- raw = await input.request.clone().json();
80
- } catch {
81
- return input.next();
82
- }
83
- const update = record(raw);
84
- const callback = record(update.callback_query);
85
- const data = callback.data;
86
- if (typeof data === "string" && (data.startsWith("eve_auth:") || data.startsWith("eve:"))) {
87
- if (typeof callback.id === "string" && input.answerCallback !== void 0) {
88
- const locale = record(callback.from).language_code;
89
- try {
90
- await input.answerCallback(callback.id, typeof locale === "string" ? locale : void 0);
91
- } catch (error) {
92
- reportTelegramError("unsupported_callback_ack_failed", error, { callbackQueryId: callback.id });
93
- }
94
- }
95
- return new Response("ok");
96
- }
97
- if (input.chats !== void 0 && (update.my_chat_member !== void 0 || update.chat_member !== void 0)) {
98
- const task = reportMembership({
99
- update,
100
- chats: input.chats,
101
- identities: input.identities
102
- });
103
- currentInboundRequest()?.waitUntil?.(task);
104
- await task;
105
- return input.next();
106
- }
107
- const edited = update.edited_message ?? update.edited_channel_post;
108
- const messagePayload = edited ?? update.channel_post ?? update.message;
109
- const message = parseArchivedMessage(messagePayload);
110
- if (message === void 0) return input.next();
111
- const content = messageContent(message.raw);
112
- const structured = input.structured?.(message.raw);
113
- const time = edited === void 0 ? message.raw.date : message.raw.edit_date ?? message.raw.date;
114
- const sentAt = typeof time === "number" ? time * 1e3 : Date.now();
115
- const senderChat = record(message.raw.sender_chat);
116
- const attachments = attachmentRefs(message);
117
- let lookup;
118
- const event = chatEvent({
119
- eventId: currentKey("telegram", [
120
- "telegram",
121
- message.chat.id,
122
- message.messageId,
123
- edited === void 0 ? "message" : `edit:${id(update.update_id) ?? id(message.raw.edit_date)}`
124
- ].join(":")),
125
- provider: currentChannel("telegram"),
126
- chatId: message.chat.id,
127
- chatType: message.chat.type === "supergroup" ? "group" : message.chat.type,
128
- threadId: message.messageThreadId === void 0 ? null : String(message.messageThreadId),
129
- kind: "inbound",
130
- text: content.text || null,
131
- argsSummary: JSON.stringify({
132
- ...contentShape(message.raw, content),
133
- routing: {
134
- ...messageMetadata(message),
135
- ...attachments.length === 0 ? {} : { originalText: content.text }
136
- }
137
- }),
138
- messageId: message.messageId,
139
- replyToMessageId: message.replyToMessage?.messageId ?? null,
140
- senderId: id(senderChat.id) ?? message.from?.id ?? null,
141
- senderName: typeof senderChat.title === "string" ? senderChat.title : message.from?.username ?? message.from?.firstName ?? null,
142
- senderIsBot: message.from?.isBot ?? false,
143
- participantIds: await participants(message, input.identities, (result) => {
144
- lookup = result;
145
- }),
146
- attachments,
147
- at: new Date(sentAt).toISOString()
148
- });
149
- let persisted;
150
- const capture = {
151
- event,
152
- message,
153
- archive: input.archive,
154
- persist: () => {
155
- persisted ??= input.archive.append(capture.event).then(() => void 0);
156
- return persisted;
157
- },
158
- ...lookup === void 0 ? {} : { lookup }
159
- };
160
- const revisionId = edited === void 0 ? void 0 : `${currentKey("telegram", `telegram:${message.chat.id}:${message.messageId}`)}:routing:${createHash("sha256").update(JSON.stringify({
161
- at: event.at,
162
- content,
163
- ...structured === void 0 ? {} : { structured },
164
- ...event.attachments.length === 0 ? {} : { attachments: attachmentIdentity(event.attachments) }
165
- })).digest("hex")}`;
166
- const dispatchKey = currentKey("telegram", `telegram:${message.chat.id}:${message.messageId}`) + (structured === void 0 ? "" : `:structured:${revisionId ?? "initial"}`);
167
- const revisionEvents = [];
168
- let revisionClaim;
169
- const finishRevision = async (status) => {
170
- if (revisionClaim === void 0) return;
171
- await input.archive.append({
172
- ...revisionClaim,
173
- eventId: status === "completed" ? `${revisionId}:completed` : `${revisionClaim.eventId}:failed`,
174
- at: new Date(Date.now()).toISOString(),
175
- status,
176
- reason: status === "completed" ? "routing_completed" : "routing_failed"
177
- });
178
- };
179
- const inbound = currentInboundRequest();
180
- if (inbound !== void 0) captures.set(inbound, capture);
181
- const automated = message.from === void 0 || message.from.isBot || message.chat.type === "channel";
182
- if (automated || edited !== void 0 || message.raw.left_chat_member || message.raw.new_chat_members || message.raw.migrate_to_chat_id || message.raw.migrate_from_chat_id) await capture.persist();
183
- const messageHistory = automated ? [] : (await input.archive.context({
184
- provider: currentChannel("telegram"),
185
- chatId: message.chat.id,
186
- messageId: message.messageId,
187
- includeDecisions: true,
188
- limit: 100,
189
- ...lookup?.status === "paired" ? { participantId: lookup.member.id } : {}
190
- })).events;
191
- const routing = messageHistory.filter((earlier) => earlier.kind === "decision" && earlier.senderId === event.senderId);
192
- const dispatchHistory = structured === void 0 ? routing : routing.filter((earlier) => earlier.eventId.startsWith(`${dispatchKey}:`));
193
- const previousClaim = dispatchHistory.find((earlier) => earlier.reason === "turn_claimed");
194
- const admitted = dispatchHistory.some((earlier) => earlier.reason === "turn_admitted");
195
- const released = previousClaim !== void 0 && dispatchHistory.some((earlier) => earlier.eventId === `${previousClaim.eventId}:released`);
196
- const dispatched = dispatchHistory.some((earlier) => earlier.reason === "turn_dispatch_started");
197
- const reserved = previousClaim !== void 0 && !released && Date.now() - Date.parse(previousClaim.at) < 6e5;
198
- const result = dispatchHistory.find((earlier) => earlier.reason === "structured_action_completed" && earlier.status === "completed");
199
- let structuredContext;
200
- if (structured !== void 0 && result?.argsSummary && lookup === void 0 && message.from !== void 0 && !message.from.isBot) {
201
- lookup = await input.identities.lookup({
202
- provider: "telegram",
203
- externalId: message.from.id
204
- });
205
- capture.lookup = lookup;
206
- }
207
- if (structured !== void 0 && lookup?.status === "paired" && result?.argsSummary) try {
208
- const value = record(JSON.parse(result.argsSummary));
209
- if (typeof value.memberId === "string" && value.memberId === lookup.member.id && typeof value.context === "string" && value.context.trim() && value.context.length <= 16384) structuredContext = {
210
- text: value.context,
211
- memberId: value.memberId
212
- };
213
- } catch {}
214
- const continuationDispatched = dispatchHistory.some((earlier) => earlier.reason === "structured_context_dispatch_started");
215
- const continuationPending = dispatched && structuredContext !== void 0 && !admitted && !continuationDispatched;
216
- const alreadyHandled = (admitted || dispatched || reserved) && !continuationPending;
217
- const rememberRevision = (events) => {
218
- if (revisionId !== void 0) revisionEvents.push(...events.filter((item) => item.eventId === revisionId || item.eventId.startsWith(`${revisionId}:`)));
219
- };
220
- const historyEvents = [...messageHistory];
221
- rememberRevision(historyEvents);
222
- const previousRevision = (earlier) => earlier.kind === "inbound" && earlier.messageId === message.messageId && earlier.senderId === event.senderId && earlier.eventId !== event.eventId && !(edited !== void 0 && earlier.eventId.includes(":edit:") && earlier.at === event.at && (eventRouting(earlier).originalText ?? earlier.text) === content.text && attachmentIdentity(earlier.attachments) === attachmentIdentity(event.attachments));
223
- const previous = messageHistory.find(previousRevision);
224
- const unchangedAttachments = previous !== void 0 && attachmentIdentity(previous.attachments) === attachmentIdentity(event.attachments);
225
- const previousRouting = previous === void 0 ? {} : eventRouting(previous);
226
- const originalEvent = previous === void 0 ? void 0 : historyEvents.find((item) => item.eventId === previous.eventId.split(":content:")[0]);
227
- if (inbound !== void 0) {
228
- inbound.previousText = typeof previousRouting.originalText === "string" ? previousRouting.originalText : originalEvent?.text ?? previous?.text ?? void 0;
229
- inbound.attachmentsChanged = previous === void 0 ? event.attachments.length > 0 : !unchangedAttachments;
230
- if (unchangedAttachments && event.attachments.length > 0) {
231
- const decoded = Array.isArray(previousRouting.decoded) ? previousRouting.decoded : [];
232
- const media = typeof previousRouting.media === "string" ? previousRouting.media : void 0;
233
- await capture.persist();
234
- const metadata = record(JSON.parse(capture.event.argsSummary ?? "{}"));
235
- capture.event = {
236
- ...capture.event,
237
- argsSummary: JSON.stringify({
238
- ...metadata,
239
- routing: {
240
- ...record(metadata.routing),
241
- membership: previousRouting.membership
242
- }
243
- })
244
- };
245
- inbound.previousContent = {
246
- decoded,
247
- ...media === void 0 ? {} : { media }
248
- };
249
- const transcripts = decoded.flatMap((item) => [
250
- "voice",
251
- "audio",
252
- "video_note"
253
- ].includes(item.attachment_kind) && item.processed && typeof item.content === "string" ? [item.content] : []);
254
- await recordInboundContent({
255
- text: [content.text, ...transcripts].filter(Boolean).join("\n\n"),
256
- decoded,
257
- ...media === void 0 ? {} : { media },
258
- ...Array.isArray(previousRouting.files) ? { files: previousRouting.files } : {}
259
- });
260
- }
261
- }
262
- if (automated || edited !== void 0) {
263
- if (message.chat.type === "group" || message.chat.type === "supergroup") await input.chats?.seen({
264
- chatId: message.chat.id,
265
- title: message.chat.title ?? ""
266
- });
267
- capture.decision = "silent";
268
- capture.reason = automated ? "automated_or_channel_message" : alreadyHandled ? "message_already_handled" : "message_edit";
269
- if (alreadyHandled) capture.note = "This message already started a turn; edits and retries do not repeat its task.";
270
- }
271
- if (alreadyHandled) {
272
- capture.decision = "silent";
273
- capture.reason = "message_already_handled";
274
- }
275
- let accepted = false;
276
- if (inbound !== void 0) {
277
- inbound.structuredContext = continuationPending ? structuredContext : void 0;
278
- inbound.edited = edited !== void 0 && !continuationPending;
279
- if (revisionId !== void 0 && !continuationPending) inbound.claimRevision = async () => {
280
- if (revisionEvents.some((item) => item.eventId === `${revisionId}:completed`)) return false;
281
- const claims = revisionEvents.filter((item) => item.reason === "routing_claimed");
282
- const latest = claims[0];
283
- if (latest !== void 0 && !revisionEvents.some((item) => item.eventId === `${latest.eventId}:failed`) && Date.now() - Date.parse(latest.at) < 12e4) return false;
284
- const attempt = claims.length === 0 ? void 0 : Math.max(...claims.map((item) => Number(item.eventId.slice(revisionId.length).replace(":retry:", "")))) + 1;
285
- const claim = {
286
- ...capture.event,
287
- eventId: attempt === void 0 ? revisionId : `${revisionId}:retry:${attempt}`,
288
- at: new Date(Date.now()).toISOString(),
289
- kind: "decision",
290
- decision: "silent",
291
- reason: "routing_claimed",
292
- status: "requested",
293
- text: null,
294
- attachments: []
295
- };
296
- const inserted = await input.archive.append(claim);
297
- if (inserted !== false) revisionClaim = claim;
298
- return inserted !== false;
299
- };
300
- const nextClaim = previousClaim === void 0 ? void 0 : createHash("sha256").update(previousClaim.eventId).digest("hex");
301
- const claimId = continuationPending && previousClaim !== void 0 ? previousClaim.eventId : previousClaim === void 0 ? `${dispatchKey}:turn` : `${dispatchKey}:turn:${nextClaim}`;
302
- let claimed = continuationPending;
303
- let dispatchStarted = continuationPending;
304
- const claimEvent = (reason, status, suffix = "") => ({
305
- ...capture.event,
306
- eventId: `${claimId}${suffix}`,
307
- kind: "decision",
308
- decision: "reply",
309
- reason,
310
- status,
311
- at: new Date().toISOString(),
312
- text: null,
313
- attachments: []
314
- });
315
- inbound.claimTurn = async () => {
316
- if (alreadyHandled) return false;
317
- claimed = await input.archive.append(claimEvent("turn_claimed", "requested")) !== false;
318
- return claimed;
319
- };
320
- inbound.beginDispatch = async () => {
321
- dispatchStarted = await input.archive.append({
322
- ...claimEvent("turn_dispatch_started", "requested"),
323
- eventId: `${dispatchKey}:dispatch`
324
- }) === true;
325
- return dispatchStarted;
326
- };
327
- inbound.recordStructuredContext = async (context, memberId) => {
328
- if (await input.archive.append({
329
- ...claimEvent("structured_action_completed", "completed"),
330
- eventId: `${dispatchKey}:result`,
331
- argsSummary: JSON.stringify({
332
- context,
333
- memberId
334
- })
335
- }) !== true) throw new Error("The archive did not acknowledge the structured continuation.");
336
- inbound.structuredContext = {
337
- text: context,
338
- memberId
339
- };
340
- };
341
- inbound.beginStructuredContinuation = async () => {
342
- const inserted = await input.archive.append({
343
- ...claimEvent("structured_context_dispatch_started", "requested"),
344
- eventId: `${dispatchKey}:context-dispatch`
345
- });
346
- dispatchStarted ||= inserted === true;
347
- return inserted === true;
348
- };
349
- inbound.finishClaim = async (delivered) => {
350
- if ((accepted || dispatchStarted) && !delivered) return;
351
- accepted ||= delivered;
352
- if (claimed) {
353
- await input.archive.append(claimEvent(delivered ? "turn_admitted" : "turn_released", delivered ? "completed" : "failed", delivered ? ":admitted" : ":released"));
354
- claimed = false;
355
- }
356
- };
357
- }
358
- let response;
359
- try {
360
- const routeEdit = edited !== void 0 && !automated && !alreadyHandled;
361
- if (routeEdit) capture.reason = void 0;
362
- response = await input.next(routeEdit ? new Request(input.request, { body: JSON.stringify({
363
- ...update,
364
- edited_message: void 0,
365
- message: messagePayload
366
- }) }) : alreadyHandled ? new Request(input.request, { body: JSON.stringify({ update_id: update.update_id }) }) : void 0);
367
- } catch (error) {
368
- if (!accepted) try {
369
- await inbound?.releaseLifecycleDispatch?.();
370
- } catch (cleanupError) {
371
- console.error("[segmentstream] inventory dispatch cleanup failed", {
372
- cleanupError,
373
- cause: error
374
- });
375
- }
376
- try {
377
- await capture.persist();
378
- await inbound?.finishClaim?.(false);
379
- await input.archive.append({
380
- ...capture.event,
381
- eventId: `${event.eventId}:decision`,
382
- kind: "decision",
383
- text: null,
384
- decision: "silent",
385
- reason: "inbound_handler_failed",
386
- attachments: []
387
- });
388
- await finishRevision("failed");
389
- } catch (storageError) {
390
- console.error("[segmentstream] recording inbound failure failed", {
391
- storageError,
392
- cause: error
393
- });
394
- }
395
- throw error;
396
- }
397
- let dispatchCleanupError;
398
- let cleanupFailed = false;
399
- if (!accepted) try {
400
- await inbound?.releaseLifecycleDispatch?.();
401
- } catch (error) {
402
- dispatchCleanupError = error;
403
- cleanupFailed = true;
404
- reportTelegramError("inventory_dispatch_cleanup_failed", error);
405
- }
406
- await capture.persist();
407
- await inbound?.finishClaim?.(false);
408
- await input.archive.append({
409
- ...capture.event,
410
- eventId: `${event.eventId}:decision`,
411
- kind: "decision",
412
- argsSummary: JSON.stringify({
413
- ...capture.diagnostics === void 0 ? {} : { decision: capture.diagnostics },
414
- ...capture.router === void 0 ? {} : { router: capture.router },
415
- ...capture.shadow === void 0 ? {} : { shadow: capture.shadow },
416
- routing: { membership: capture.lookup === void 0 ? "unknown" : capture.lookup.status === "paired" || capture.lookup.status === "existing" || capture.lookup.status === "created" ? "linked" : "unlinked" }
417
- }),
418
- text: capture.note ?? (edited !== void 0 ? "Message edit recorded as context; no agent turn started." : null),
419
- decision: capture.decision ?? "silent",
420
- reason: capture.reason ?? (message.raw.left_chat_member ? "member_departure" : message.raw.new_chat_members ? "member_arrival" : message.raw.migrate_to_chat_id || message.raw.migrate_from_chat_id ? "chat_migration" : "unpaired_refused_or_empty_message"),
421
- attachments: []
422
- });
423
- await finishRevision(capture.reason === "inbound_message_failed" || capture.reason === "decision_model_failed" || capture.reason === "decision_model_timeout" ? "failed" : "completed");
424
- if (cleanupFailed) throw dispatchCleanupError;
425
- return response;
426
- }
427
- function recordGateDecision(reason, decision = "silent") {
428
- const inbound = currentInboundRequest();
429
- const capture = inbound === void 0 ? void 0 : captures.get(inbound);
430
- if (capture !== void 0) {
431
- capture.reason = reason;
432
- capture.decision = decision;
433
- capture.note = void 0;
434
- }
435
- }
436
- function recordRouteDecision(route, addressed, policy, audit) {
437
- const inbound = currentInboundRequest();
438
- const capture = inbound === void 0 ? void 0 : captures.get(inbound);
439
- if (capture !== void 0) {
440
- capture.decision = route === "reply" ? "reply" : "silent";
441
- if (audit?.uncertain === true) capture.reason = audit.reason;
442
- capture.reason ??= audit?.reason ?? (typeof addressed === "string" ? addressed : addressed ? "addressed_message" : policy === "mention" ? "mention_policy" : `decision_model_${route}`);
443
- capture.note = audit?.note.slice(0, 500);
444
- capture.routeReason = audit?.reason;
445
- capture.diagnostics = audit?.diagnostics;
446
- capture.router = audit?.router;
447
- capture.shadow = audit?.shadow;
448
- }
449
- }
450
- function captureRouteDecider(decide) {
451
- return async (question) => {
452
- try {
453
- return await decide(question);
454
- } catch (error) {
455
- const inbound = currentInboundRequest();
456
- const capture = inbound === void 0 ? void 0 : captures.get(inbound);
457
- if (capture !== void 0) capture.reason = error instanceof Error && error.name === "TimeoutError" ? "decision_model_timeout" : "decision_model_failed";
458
- throw error;
459
- }
460
- };
461
- }
462
- async function recordInboundContent(content) {
463
- const inbound = currentInboundRequest();
464
- const capture = inbound === void 0 ? void 0 : captures.get(inbound);
465
- if (capture?.archive === void 0) return;
466
- await capture.persist();
467
- const metadata = record(JSON.parse(capture.event.argsSummary ?? "{}"));
468
- const membership = capture.lookup === void 0 ? record(metadata.routing).membership : capture.lookup.status === "paired" || capture.lookup.status === "existing" || capture.lookup.status === "created" ? "linked" : "unlinked";
469
- const author = content.author ?? record(metadata.routing).author;
470
- const files = content.files ?? record(metadata.routing).files;
471
- if (content.text === capture.event.text && content.media === record(metadata.routing).media && membership === record(metadata.routing).membership && author === record(metadata.routing).author && JSON.stringify(files) === JSON.stringify(record(metadata.routing).files) && JSON.stringify(content.decoded) === JSON.stringify(record(metadata.routing).decoded)) return;
472
- const contentHash = createHash("sha256").update(JSON.stringify({
473
- ...content,
474
- membership
475
- })).digest("hex").slice(0, 16);
476
- const event = {
477
- ...capture.event,
478
- eventId: `${capture.event.eventId}:content:${contentHash}`,
479
- text: content.text,
480
- argsSummary: JSON.stringify({
481
- ...metadata,
482
- routing: {
483
- ...record(metadata.routing),
484
- membership,
485
- ...typeof author === "string" ? { author: author.slice(0, 500) } : {},
486
- ...Array.isArray(files) && files.length > 0 ? { files: files.slice(0, 10) } : {},
487
- media: content.media?.slice(0, 8e3),
488
- decoded: content.decoded
489
- }
490
- })
491
- };
492
- await capture.archive.append(event);
493
- capture.event = event;
494
- }
495
- async function outboundAudience(chatId, identities) {
496
- const inbound = currentInboundRequest();
497
- const capture = inbound === void 0 ? void 0 : captures.get(inbound);
498
- let participantIds = capture?.event.participantIds ?? [];
499
- const chatType = capture?.event.chatType ?? (chatId.startsWith("-") ? "group" : "private");
500
- if (chatType === "private" && participantIds.length === 0 && capture === void 0) try {
501
- const lookup = await identities().lookup({
502
- provider: "telegram",
503
- externalId: chatId
504
- });
505
- if (lookup.status === "paired") participantIds = [lookup.member.id];
506
- } catch (error) {
507
- console.error("[segmentstream] outbound participant lookup failed", { error });
508
- }
509
- return {
510
- capture,
511
- chatType,
512
- participantIds
513
- };
514
- }
515
- async function recordSessionFailure(input) {
516
- const { failure } = input;
517
- const sessionId = failure.sessionId === "" ? null : failure.sessionId;
518
- try {
519
- const errorText = contentText(failure.message, CONTENT_CAPS.error);
520
- if (input.chatId === null) {
521
- console.error("[segmentstream] agent log dropped unaddressed failure", {
522
- sessionId,
523
- eventType: "session.failed",
524
- code: failure.code,
525
- message: errorText
526
- });
527
- return;
528
- }
529
- const { chatType, participantIds } = await outboundAudience(input.chatId, input.identities);
530
- await input.archive.append(chatEvent({
531
- eventId: sessionId === null ? `eve:session.failed:${randomUUID()}` : sessionFailureEventId(sessionId),
532
- provider: currentChannel("telegram"),
533
- chatId: input.chatId,
534
- chatType,
535
- threadId: input.threadId,
536
- participantIds,
537
- sessionId,
538
- kind: "decision",
539
- decision: "silent",
540
- reason: "session.failed",
541
- status: "failed",
542
- errorText
543
- }));
544
- } catch (error) {
545
- console.error("[segmentstream] recording session failure failed", {
546
- sessionId,
547
- error
548
- });
549
- }
550
- }
551
- function captureTelegramFetch(fetchImpl, archive, identities) {
552
- return async (input, init) => {
553
- const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
554
- const edit = /\/(?:editMessageText|editMessageCaption)$/u.test(url);
555
- if (!url.endsWith("/sendMessage") && !edit || typeof init?.body !== "string") return fetchImpl(input, init);
556
- const body = record(JSON.parse(init.body));
557
- const chatId = id(body.chat_id);
558
- if (chatId === null) return fetchImpl(input, init);
559
- const { capture, chatType, participantIds } = await outboundAudience(chatId, identities);
560
- const delivery = currentDeliveryScope();
561
- const own = delivery?.chatId === chatId && delivery.sessionId !== null;
562
- const event = chatEvent({
563
- eventId: `telegram:${edit ? "edit" : "send"}:${randomUUID()}`,
564
- provider: currentChannel("telegram"),
565
- chatId,
566
- chatType,
567
- kind: "outbound",
568
- text: typeof body.text === "string" ? body.text : typeof body.caption === "string" ? body.caption : null,
569
- reason: edit ? "telegram_message_edit" : null,
570
- messageId: edit ? id(body.message_id) : null,
571
- senderIsBot: true,
572
- senderId: "agent",
573
- senderName: "agent",
574
- argsSummary: JSON.stringify({
575
- telegram: {
576
- ...Array.isArray(body.entities) ? { entities: body.entities } : {},
577
- ...Array.isArray(body.caption_entities) ? { caption_entities: body.caption_entities } : {},
578
- ...typeof body.parse_mode === "string" ? { parse_mode: body.parse_mode } : {}
579
- },
580
- routing: {
581
- ...capture?.routeReason !== void 0 && [
582
- "mention",
583
- "command",
584
- "reply-to-bot",
585
- "thread-with-agent",
586
- "pending-question"
587
- ].includes(capture.routeReason) ? { invitation: capture.routeReason } : {},
588
- ...currentConfirmationPrompt() === void 0 ? {} : { confirmation: currentConfirmationPrompt() },
589
- ...capture?.event.chatId === chatId && capture.event.senderId !== null ? { inReplyTo: {
590
- id: capture.event.senderId,
591
- author: capture.event.senderName ?? capture.event.senderId,
592
- ...capture.message.from?.username === void 0 ? {} : { username: capture.message.from.username }
593
- } } : {},
594
- ...currentConfirmationPrompt()?.requester === void 0 ? {} : { inReplyTo: currentConfirmationPrompt()?.requester }
595
- }
596
- }),
597
- participantIds,
598
- threadId: id(body.message_thread_id) ?? currentThreadId() ?? null,
599
- replyToMessageId: id(body.reply_to_message_id) ?? id(record(body.reply_parameters).message_id),
600
- ...own ? {
601
- sessionId: delivery.sessionId,
602
- turnId: delivery.turnId
603
- } : {},
604
- status: "requested"
605
- });
606
- await archive.append(event);
607
- let response;
608
- try {
609
- response = await fetchImpl(input, init);
610
- } catch (error) {
611
- try {
612
- await archive.append({
613
- ...event,
614
- eventId: `${event.eventId}:result`,
615
- status: "unknown"
616
- });
617
- } catch (storageError) {
618
- console.error("[segmentstream] recording uncertain delivery failed", {
619
- storageError,
620
- cause: error
621
- });
622
- }
623
- throw error;
624
- }
625
- const result = record(await response.clone().json().catch(() => null));
626
- const messageId = id(record(result.result).message_id);
627
- const acknowledged = edit || messageId !== null && /^[1-9]\d*$/u.test(messageId);
628
- await archive.append({
629
- ...event,
630
- eventId: `${event.eventId}:result`,
631
- status: response.ok && result.ok === true && acknowledged ? "completed" : result.ok === false ? "failed" : "unknown",
632
- messageId: messageId ?? event.messageId
633
- });
634
- return response;
635
- };
636
- }
637
- function chatIdentities(identities) {
638
- return {
639
- ...identities,
640
- resolve: async (account) => {
641
- const resolved = await identities.resolve(account);
642
- const inbound = currentInboundRequest();
643
- const capture = inbound === void 0 ? void 0 : captures.get(inbound);
644
- if (account.provider === "telegram" && capture?.message.from?.id === account.externalId) {
645
- capture.lookup = resolved;
646
- if (capture.event.chatType === "private" && (resolved.status === "existing" || resolved.status === "created")) capture.event = {
647
- ...capture.event,
648
- participantIds: [resolved.member.id]
649
- };
650
- if (capture.event.chatType === "private" && resolved.status === "limited") {
651
- const binding = await identities.lookup(account);
652
- if (binding.status === "paired") capture.event = {
653
- ...capture.event,
654
- participantIds: [binding.member.id]
655
- };
656
- }
657
- await capture.persist();
658
- }
659
- return resolved;
660
- },
661
- lookup: async (account) => {
662
- const inbound = currentInboundRequest();
663
- const capture = inbound === void 0 ? void 0 : captures.get(inbound);
664
- if (account.provider === "telegram" && capture?.message.from?.id === account.externalId) {
665
- const cached = capture.lookup;
666
- if (cached?.status === "paired" || cached?.status === "refused" || cached?.status === "unknown") return cached;
667
- if (cached?.status === "existing" || cached?.status === "created") return {
668
- status: "paired",
669
- member: cached.member
670
- };
671
- if (cached?.status === "pairing_required") return { status: "unknown" };
672
- }
673
- return identities.lookup(account);
674
- }
675
- };
676
- }
677
- function telegramChatCapture(input) {
678
- const processing = new Map();
679
- return async (request, next) => {
680
- if (!input.verify(request)) return next();
681
- try {
682
- const update = record(await request.clone().json().catch(() => null));
683
- const payload = record(update.edited_message ?? update.message);
684
- const chatId = id(record(payload.chat).id);
685
- const messageId = id(payload.message_id);
686
- const key = chatId === null || messageId === null ? void 0 : currentKey("telegram", `${chatId}:${messageId}`);
687
- const previous = key === void 0 ? void 0 : processing.get(key);
688
- const task = (async () => {
689
- await previous?.catch(() => void 0);
690
- return captureTelegramWebhook({
691
- ...input,
692
- request,
693
- identities: input.identities(),
694
- next
695
- });
696
- })();
697
- if (key !== void 0) processing.set(key, task);
698
- try {
699
- return await task;
700
- } finally {
701
- if (key !== void 0 && processing.get(key) === task) processing.delete(key);
702
- }
703
- } catch (error) {
704
- console.error("[segmentstream] chat capture failed", { error });
705
- return new Response("chat storage unavailable", { status: 503 });
706
- }
707
- };
708
- }
709
- export { REVISION_CLAIM_TTL_MS, captureRouteDecider, captureTelegramFetch, captureTelegramWebhook, chatIdentities, recordGateDecision, recordInboundContent, recordRouteDecision, recordSessionFailure, telegramChatCapture };
7
+ export { t as REVISION_CLAIM_TTL_MS, n as attachmentIdentity, r as attachmentRefs, i as captureRouteDecider, a as captureTelegramFetch, o as captureTelegramWebhook, s as chatIdentities, c as currentCapture, l as participants, u as recordGateDecision, d as recordInboundContent, f as recordRouteDecision, p as recordSessionFailure, m as registerCapture, h as telegramChatCapture } from "../../../_chunks/chat-archive-DK7uCgff.mjs";