@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
@@ -0,0 +1,1337 @@
1
+ import { fileURLToPath as __eveFileURLToPath } from "node:url";
2
+ import { dirname as __eveDirname } from "node:path";
3
+ import { createRequire as __eveCreateRequire } from "node:module";
4
+ const __filename = __eveFileURLToPath(import.meta.url);
5
+ __eveDirname(__filename);
6
+ __eveCreateRequire(import.meta.url);
7
+ import { parseArchivedMessage } from "../extension/lib/telegram/archive-message.mjs";
8
+ import { currentChannel, currentKey } from "../extension/lib/channel-scope.mjs";
9
+ import { n as contentText, t as CONTENT_CAPS } from "./content-cDtVnr8Y.mjs";
10
+ import { S as storedFiles, a as chatEvent, b as reasonCode, d as sessionFailureEventId, f as storeOf, g as cutText, h as boundedMeta, v as messageInput, x as sendFingerprint, y as metaOf } from "./chat-archive-BCPLSZeK.mjs";
11
+ import { ChatStoreError } from "../extension/lib/chat-store.mjs";
12
+ import { c as currentInboundRequest, ht as currentThreadId, xt as reportTelegramError } from "./principal-Zf42Yf4r.mjs";
13
+ import { currentConfirmationPrompt } from "../extension/lib/group-routing/messages.mjs";
14
+ import { messageMetadata } from "../extension/lib/telegram/message-metadata.mjs";
15
+ import { reportMembership } from "../extension/lib/telegram/membership.mjs";
16
+ import { currentDeliveryScope } from "../extension/lib/telegram/delivery-diagnostics.mjs";
17
+ import { contentShape, messageContent } from "../extension/lib/telegram/content.mjs";
18
+ import { createHash, randomUUID } from "node:crypto";
19
+ const CLAIM_MS = 6e5;
20
+ const META_ATTEMPTS = 8;
21
+ const MESSAGE = "message";
22
+ function object(value) {
23
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
24
+ }
25
+ function fencesOf(meta) {
26
+ return object(object(meta).fences);
27
+ }
28
+ function withFence(meta, key, fence) {
29
+ const fences = Object.entries(fencesOf(meta)).filter(([name]) => name !== key);
30
+ return {
31
+ ...object(meta),
32
+ fences: Object.fromEntries([...fences, [key, fence]].slice(-20))
33
+ };
34
+ }
35
+ function age(at) {
36
+ const time = at === null || at === void 0 ? NaN : Date.parse(at);
37
+ return Number.isNaN(time) ? Number.POSITIVE_INFINITY : Date.now() - time;
38
+ }
39
+ async function readMessage(store, target) {
40
+ return (await store.read({
41
+ channel: target.channel,
42
+ chatId: target.chatId,
43
+ messageId: target.messageId,
44
+ limit: 1
45
+ })).messages[0];
46
+ }
47
+ function alike(first, second) {
48
+ const canonical = (value) => JSON.stringify(value ?? null, (_key, item) => item !== null && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) : item);
49
+ return canonical(first) === canonical(second);
50
+ }
51
+ async function readLive(store, target) {
52
+ const message = await readMessage(store, target);
53
+ return message?.deletedAt === null ? message : void 0;
54
+ }
55
+ async function writeMeta(store, target, next, known) {
56
+ let state = known ?? await readLive(store, target);
57
+ for (let attempt = 0; attempt < META_ATTEMPTS && state !== void 0; attempt += 1) {
58
+ const write = next(state);
59
+ if (write === void 0) return;
60
+ const meta = boundedMeta(write.meta);
61
+ const { text, files } = write;
62
+ if (alike(meta, state.meta) && (text === void 0 || text === state.text) && (files === void 0 || state.files !== void 0 && alike(files, state.files))) return;
63
+ const expected = state.meta ?? null;
64
+ const { applied } = await store.change(write.edit !== void 0 ? {
65
+ ...target,
66
+ change: "edit",
67
+ text: text ?? state.text ?? "",
68
+ ...write.edit.at === void 0 ? {} : { at: write.edit.at },
69
+ meta,
70
+ expected,
71
+ ...files === void 0 ? {} : { files }
72
+ } : text === void 0 && files === void 0 ? {
73
+ ...target,
74
+ change: "meta",
75
+ meta,
76
+ expected
77
+ } : {
78
+ ...target,
79
+ change: "content",
80
+ meta,
81
+ expected,
82
+ ...text === void 0 ? {} : { text },
83
+ ...files === void 0 ? {} : { files }
84
+ });
85
+ if (applied) {
86
+ const held = files ?? state.files;
87
+ return {
88
+ text: text ?? state.text,
89
+ meta,
90
+ ...held === void 0 ? {} : { files: held }
91
+ };
92
+ }
93
+ state = await readLive(store, target);
94
+ }
95
+ if (state === void 0) return;
96
+ throw new ChatStoreError("meta_contended", void 0, void 0, "A message's routing state kept changing under its writer.");
97
+ }
98
+ function changeMeta(store, target, next, known) {
99
+ return writeMeta(store, target, (current) => {
100
+ const meta = next(current);
101
+ return meta === void 0 ? void 0 : { meta };
102
+ }, known);
103
+ }
104
+ function attachmentsOf(meta) {
105
+ return Array.isArray(meta.attachments) ? meta.attachments : [];
106
+ }
107
+ const SPOKEN = new Set([
108
+ "voice",
109
+ "audio",
110
+ "video_note"
111
+ ]);
112
+ function transcriptsOf(decoded) {
113
+ return (decoded ?? []).flatMap((item) => SPOKEN.has(item.attachment_kind) && item.processed && typeof item.content === "string" && item.content.trim() !== "" ? [item.content] : []);
114
+ }
115
+ function withoutTranscripts(decoded) {
116
+ return decoded.map((item) => {
117
+ if (!SPOKEN.has(item.attachment_kind) || item.content === void 0) return item;
118
+ return Object.fromEntries(Object.entries(item).filter(([key]) => key !== "content"));
119
+ });
120
+ }
121
+ function transcriptIn(text, caption) {
122
+ if (text === null || typeof caption !== "string") return;
123
+ const transcript = caption === "" ? text : text.startsWith(`${caption}\n\n`) ? text.slice(caption.length + 2) : "";
124
+ return transcript.trim() === "" ? void 0 : transcript;
125
+ }
126
+ function revisionDigest(input) {
127
+ return createHash("sha256").update(JSON.stringify({
128
+ at: input.at,
129
+ content: input.content,
130
+ ...input.structured === void 0 ? {} : { structured: input.structured },
131
+ ...input.attachments.length === 0 ? {} : { attachments: attachmentIdentity(input.attachments) }
132
+ })).digest("hex");
133
+ }
134
+ function baselineOf(message) {
135
+ const meta = object(message.meta);
136
+ const caption = object(meta.routing).originalText;
137
+ return {
138
+ text: typeof caption === "string" ? caption : message.text,
139
+ routing: object(meta.routing),
140
+ attachments: Array.isArray(meta.attachments) ? meta.attachments : []
141
+ };
142
+ }
143
+ function membershipOf(lookup) {
144
+ return lookup === void 0 ? void 0 : lookup.status === "paired" || lookup.status === "existing" || lookup.status === "created" ? "linked" : "unlinked";
145
+ }
146
+ function memberOf(lookup) {
147
+ return lookup !== void 0 && (lookup.status === "paired" || lookup.status === "existing" || lookup.status === "created") ? lookup.member.id : void 0;
148
+ }
149
+ async function captureInStore(input) {
150
+ const { store, message, update, structured, content } = input;
151
+ const edited = input.edited !== void 0;
152
+ const event = input.event;
153
+ const target = {
154
+ channel: event.provider,
155
+ chatId: event.chatId,
156
+ messageId: event.messageId ?? ""
157
+ };
158
+ const digest = revisionDigest({
159
+ at: event.at,
160
+ content,
161
+ structured,
162
+ attachments: event.attachments
163
+ });
164
+ const fenceKey = structured === void 0 || !edited ? MESSAGE : digest;
165
+ const rowFence = fenceKey === MESSAGE;
166
+ const held = await readMessage(store, target);
167
+ let known = held;
168
+ const heldMeta = object(held?.meta);
169
+ const heldRevision = object(heldMeta.held);
170
+ const sameRevision = held !== void 0 && heldRevision.digest === digest && heldRevision.edit === true;
171
+ const baseline = held === void 0 ? void 0 : sameRevision ? heldMeta.previous === void 0 ? void 0 : heldMeta.previous : baselineOf(held);
172
+ let persisted;
173
+ let superseded = false;
174
+ const capture = {
175
+ event,
176
+ message,
177
+ archive: input.archive,
178
+ ...input.lookup === void 0 ? {} : { lookup: input.lookup },
179
+ persist: () => {
180
+ persisted ??= persist();
181
+ return persisted;
182
+ },
183
+ keepContent: (kept) => keepContent(kept)
184
+ };
185
+ async function persist() {
186
+ const own = object(metaOf(capture.event));
187
+ const sender = Object.fromEntries(Object.entries(object(object(held?.meta).routing)).filter(([key]) => ["membership", "author"].includes(key)));
188
+ const meta = {
189
+ ...own,
190
+ routing: {
191
+ ...sender,
192
+ ...object(own.routing)
193
+ },
194
+ held: {
195
+ digest,
196
+ at: event.at,
197
+ ...edited ? { edit: true } : {}
198
+ },
199
+ ...baseline === void 0 ? {} : { previous: baseline }
200
+ };
201
+ const userId = memberOf(capture.lookup);
202
+ if (held === void 0) {
203
+ const input = messageInput({
204
+ ...capture.event,
205
+ ...userId === void 0 ? {} : { userId }
206
+ });
207
+ const bounded = boundedMeta(meta);
208
+ known = (await store.record({
209
+ ...input,
210
+ meta: bounded
211
+ })).first ? {
212
+ text: input.text ?? null,
213
+ meta: bounded,
214
+ files: input.files ?? []
215
+ } : void 0;
216
+ return;
217
+ }
218
+ if (!edited) return;
219
+ const caption = (capture.event.text ?? "").slice(0, 1e5);
220
+ if (held.deletedAt !== null || newerThanEdit(heldMeta) || editedAfter(held)) {
221
+ superseded = true;
222
+ return;
223
+ }
224
+ const written = await writeMeta(store, target, (current) => {
225
+ const kept = object(current.meta);
226
+ if (newerThanEdit(kept) || editedAfter(current)) {
227
+ superseded = true;
228
+ return;
229
+ }
230
+ const sameFiles = attachmentIdentity(attachmentsOf(kept)) === attachmentIdentity(event.attachments);
231
+ const transcript = sameFiles ? transcriptIn(current.text, object(kept.routing).originalText) : void 0;
232
+ return {
233
+ meta: object(kept.held).digest === digest ? kept : {
234
+ ...meta,
235
+ ...kept.fences === void 0 ? {} : { fences: kept.fences }
236
+ },
237
+ text: cutText([caption, transcript ?? ""].filter((part) => part.trim() !== "").join("\n\n"), 1e5),
238
+ ...sameFiles ? {} : { files: [] },
239
+ edit: { at: event.at }
240
+ };
241
+ }, known);
242
+ if (superseded) return;
243
+ if (written === void 0) {
244
+ const current = await readMessage(store, target);
245
+ superseded = current === void 0 || current.deletedAt !== null || object(object(current.meta).held).digest !== digest;
246
+ known = current;
247
+ return;
248
+ }
249
+ known = written;
250
+ }
251
+ function editedAfter(current) {
252
+ return typeof current.editedAt === "string" && Date.parse(current.editedAt) > Date.parse(event.at);
253
+ }
254
+ function newerThanEdit(kept) {
255
+ const revision = object(kept.held);
256
+ return revision.edit === true && typeof revision.at === "string" && Date.parse(revision.at) > Date.parse(event.at);
257
+ }
258
+ async function keepContent(kept) {
259
+ await capture.persist();
260
+ const membership = membershipOf(capture.lookup);
261
+ const transcripts = transcriptsOf(kept.decoded);
262
+ const files = storedFiles(kept.files ?? []);
263
+ known = await writeMeta(store, target, (current) => {
264
+ const meta = object(current.meta);
265
+ if (object(meta.held).digest !== digest) return;
266
+ const routing = object(meta.routing);
267
+ const routed = kept.files ?? routing.files;
268
+ const author = kept.author ?? routing.author;
269
+ const caption = routing.originalText;
270
+ const text = typeof caption === "string" && transcripts.length > 0 ? cutText([caption, ...transcripts].filter((part) => part.trim() !== "").join("\n\n"), 1e5) : void 0;
271
+ const rest = Object.fromEntries(Object.entries(routing).filter(([key]) => key !== "retainedText"));
272
+ const retained = kept.text !== "" && kept.text !== caption && kept.text !== (text ?? current.text ?? "") ? { retainedText: kept.text } : {};
273
+ return {
274
+ meta: {
275
+ ...meta,
276
+ routing: {
277
+ ...rest,
278
+ ...membership === void 0 ? {} : { membership },
279
+ ...typeof author === "string" ? { author: author.slice(0, 500) } : {},
280
+ ...Array.isArray(routed) && routed.length > 0 ? { files: routed.slice(0, 10) } : {},
281
+ ...kept.media === void 0 ? {} : { media: kept.media.slice(0, 8e3) },
282
+ ...kept.decoded === void 0 ? {} : { decoded: withoutTranscripts(kept.decoded) },
283
+ ...retained
284
+ }
285
+ },
286
+ ...text === void 0 ? {} : { text },
287
+ ...files.length === 0 ? {} : { files }
288
+ };
289
+ }, known) ?? known;
290
+ }
291
+ const inbound = currentInboundRequest();
292
+ if (inbound !== void 0) registerCapture(inbound, capture);
293
+ const automated = message.from === void 0 || message.from.isBot || message.chat.type === "channel";
294
+ const raw = message.raw;
295
+ if (automated || edited || raw.left_chat_member || raw.new_chat_members || raw.migrate_to_chat_id || raw.migrate_from_chat_id) await capture.persist();
296
+ if (superseded) {
297
+ capture.decision = "silent";
298
+ capture.reason = "message_edit_superseded";
299
+ return input.next(new Request(input.request, { body: JSON.stringify({ update_id: update.update_id }) }));
300
+ }
301
+ const fence = () => fencesOf(held?.meta)[fenceKey] ?? {};
302
+ const dispatched = rowFence ? held?.disposition === "turn" : fence().dispatched === true;
303
+ const admitted = fence().admitted === true || rowFence && dispatched && (structured === void 0 || held?.sessionId != null);
304
+ const reserved = rowFence ? held?.disposition === "claimed" && age(held.dispositionAt) < CLAIM_MS : fence().claim !== void 0 && !dispatched && age(fence().claim?.at) < CLAIM_MS;
305
+ const result = fence().result;
306
+ let lookup = capture.lookup;
307
+ let structuredContext;
308
+ if (structured !== void 0 && result !== void 0 && lookup === void 0 && message.from !== void 0 && !message.from.isBot) {
309
+ lookup = await input.identities.lookup({
310
+ provider: "telegram",
311
+ externalId: message.from.id
312
+ });
313
+ capture.lookup = lookup;
314
+ }
315
+ if (structured !== void 0 && lookup?.status === "paired" && result !== void 0 && result.memberId === lookup.member.id && typeof result.context === "string" && result.context.trim() !== "" && result.context.length <= 16384) structuredContext = {
316
+ text: result.context,
317
+ memberId: result.memberId
318
+ };
319
+ const continuationPending = dispatched && structuredContext !== void 0 && !admitted && fence().continuation !== true;
320
+ const alreadyHandled = (admitted || dispatched || reserved) && !continuationPending;
321
+ if (inbound !== void 0) {
322
+ const previousRouting = baseline?.routing ?? {};
323
+ inbound.previousText = typeof previousRouting.originalText === "string" ? previousRouting.originalText : baseline?.text ?? void 0;
324
+ const unchangedAttachments = baseline !== void 0 && attachmentIdentity(baseline.attachments) === attachmentIdentity(event.attachments);
325
+ inbound.attachmentsChanged = baseline === void 0 ? event.attachments.length > 0 : !unchangedAttachments;
326
+ if (unchangedAttachments && event.attachments.length > 0) {
327
+ const transcript = transcriptIn(held?.text ?? null, object(heldMeta.routing).originalText);
328
+ const decoded = (Array.isArray(previousRouting.decoded) ? previousRouting.decoded : []).map((item) => SPOKEN.has(item.attachment_kind) && item.processed && item.content === void 0 && transcript !== void 0 ? {
329
+ ...item,
330
+ content: transcript
331
+ } : item);
332
+ const media = typeof previousRouting.media === "string" ? previousRouting.media : void 0;
333
+ inbound.previousContent = {
334
+ decoded,
335
+ ...media === void 0 ? {} : { media }
336
+ };
337
+ await keepContent({
338
+ text: content.text,
339
+ decoded,
340
+ ...media === void 0 ? {} : { media },
341
+ ...Array.isArray(previousRouting.files) ? { files: previousRouting.files } : {}
342
+ });
343
+ }
344
+ }
345
+ if (automated || edited) {
346
+ if (message.chat.type === "group" || message.chat.type === "supergroup") await input.chats?.seen({
347
+ chatId: message.chat.id,
348
+ title: message.chat.title ?? ""
349
+ });
350
+ capture.decision = "silent";
351
+ capture.reason = automated ? "automated_or_channel_message" : alreadyHandled ? "message_already_handled" : "message_edit";
352
+ }
353
+ if (alreadyHandled) {
354
+ capture.decision = "silent";
355
+ capture.reason = "message_already_handled";
356
+ }
357
+ let accepted = false;
358
+ let routingClaimed = false;
359
+ const mutate = async (next) => {
360
+ const changed = await changeMeta(store, target, next, known);
361
+ if (changed !== void 0) known = changed;
362
+ return changed !== void 0;
363
+ };
364
+ const setFence = (next) => mutate((current) => {
365
+ const changed = next(fencesOf(current.meta)[fenceKey] ?? {});
366
+ return changed === void 0 ? void 0 : withFence(current.meta, fenceKey, changed);
367
+ });
368
+ if (inbound !== void 0) {
369
+ inbound.structuredContext = continuationPending ? structuredContext : void 0;
370
+ inbound.edited = edited && !continuationPending;
371
+ if (edited && !continuationPending) inbound.claimRevision = async () => {
372
+ await capture.persist();
373
+ routingClaimed = await mutate((current) => {
374
+ const routing = (fencesOf(current.meta)[digest] ?? {}).routing;
375
+ if (routing?.state === "completed" || routing?.state === "claimed" && age(routing.at) < 12e4) return;
376
+ return withFence(current.meta, digest, {
377
+ ...fencesOf(current.meta)[digest],
378
+ routing: {
379
+ state: "claimed",
380
+ at: new Date(Date.now()).toISOString(),
381
+ attempt: (routing?.attempt ?? 0) + 1
382
+ }
383
+ });
384
+ });
385
+ return routingClaimed;
386
+ };
387
+ let claimed = continuationPending;
388
+ let dispatchStarted = continuationPending;
389
+ inbound.claimTurn = async () => {
390
+ if (alreadyHandled) return false;
391
+ await capture.persist();
392
+ if (rowFence) claimed = (await store.change({
393
+ ...target,
394
+ change: "disposition",
395
+ disposition: "claimed"
396
+ })).applied;
397
+ else claimed = await setFence((current) => current.dispatched === true || current.claim !== void 0 && age(current.claim.at) < CLAIM_MS ? void 0 : {
398
+ ...current,
399
+ claim: { at: new Date(Date.now()).toISOString() }
400
+ });
401
+ return claimed;
402
+ };
403
+ inbound.beginDispatch = async () => {
404
+ dispatchStarted = rowFence ? (await store.change({
405
+ ...target,
406
+ change: "disposition",
407
+ disposition: "turn"
408
+ })).applied : await setFence((current) => current.dispatched === true ? void 0 : {
409
+ ...current,
410
+ dispatched: true
411
+ });
412
+ return dispatchStarted;
413
+ };
414
+ inbound.recordStructuredContext = async (context, memberId) => {
415
+ if (!await setFence((current) => current.result === void 0 ? {
416
+ ...current,
417
+ result: {
418
+ context,
419
+ memberId
420
+ }
421
+ } : void 0)) throw new Error("The chat store did not acknowledge the structured continuation.");
422
+ inbound.structuredContext = {
423
+ text: context,
424
+ memberId
425
+ };
426
+ };
427
+ inbound.beginStructuredContinuation = async () => {
428
+ const started = await setFence((current) => current.continuation === true ? void 0 : {
429
+ ...current,
430
+ continuation: true
431
+ });
432
+ dispatchStarted ||= started;
433
+ return started;
434
+ };
435
+ inbound.finishClaim = async (delivered, sessionId) => {
436
+ if ((accepted || dispatchStarted) && !delivered) return;
437
+ accepted ||= delivered;
438
+ if (!claimed) return;
439
+ claimed = false;
440
+ if (!delivered) {
441
+ if (rowFence) await store.change({
442
+ ...target,
443
+ change: "release"
444
+ });
445
+ else await setFence((current) => Object.fromEntries(Object.entries(current).filter(([key]) => key !== "claim")));
446
+ return;
447
+ }
448
+ const reason = reasonCode(capture.routeReason ?? capture.reason);
449
+ if (rowFence) await store.change({
450
+ ...target,
451
+ change: "disposition",
452
+ disposition: "turn",
453
+ ...reason === void 0 ? {} : { reason },
454
+ ...sessionId === void 0 ? {} : { sessionId }
455
+ });
456
+ if (!rowFence || sessionId === void 0) await setFence((current) => current.admitted === true ? void 0 : {
457
+ ...current,
458
+ admitted: true
459
+ });
460
+ };
461
+ }
462
+ const finishRouting = async (state) => {
463
+ if (!routingClaimed) return;
464
+ await mutate((current) => {
465
+ const fence = fencesOf(current.meta)[digest] ?? {};
466
+ return fence.routing === void 0 || fence.routing.state !== "claimed" ? void 0 : withFence(current.meta, digest, {
467
+ ...fence,
468
+ routing: {
469
+ ...fence.routing,
470
+ state
471
+ }
472
+ });
473
+ });
474
+ };
475
+ const skip = async (reason) => {
476
+ if (accepted || target.messageId === "") return;
477
+ await store.change({
478
+ ...target,
479
+ change: "disposition",
480
+ disposition: "skipped",
481
+ reason: reasonCode(reason) ?? "silent"
482
+ });
483
+ };
484
+ let response;
485
+ try {
486
+ const routeEdit = edited && !automated && !alreadyHandled;
487
+ if (routeEdit) capture.reason = void 0;
488
+ response = await input.next(routeEdit ? new Request(input.request, { body: JSON.stringify({
489
+ ...update,
490
+ edited_message: void 0,
491
+ message: input.messagePayload
492
+ }) }) : alreadyHandled ? new Request(input.request, { body: JSON.stringify({ update_id: update.update_id }) }) : void 0);
493
+ } catch (error) {
494
+ if (!accepted) try {
495
+ await inbound?.releaseLifecycleDispatch?.();
496
+ } catch (cleanupError) {
497
+ console.error("[segmentstream] inventory dispatch cleanup failed", {
498
+ cleanupError,
499
+ cause: error
500
+ });
501
+ }
502
+ try {
503
+ await capture.persist();
504
+ await inbound?.finishClaim?.(false);
505
+ await skip("inbound_handler_failed");
506
+ await finishRouting("failed");
507
+ } catch (storageError) {
508
+ console.error("[segmentstream] recording inbound failure failed", {
509
+ storageError,
510
+ cause: error
511
+ });
512
+ }
513
+ throw error;
514
+ }
515
+ let dispatchCleanupError;
516
+ let cleanupFailed = false;
517
+ if (!accepted) try {
518
+ await inbound?.releaseLifecycleDispatch?.();
519
+ } catch (error) {
520
+ dispatchCleanupError = error;
521
+ cleanupFailed = true;
522
+ reportTelegramError("inventory_dispatch_cleanup_failed", error);
523
+ }
524
+ await capture.persist();
525
+ await inbound?.finishClaim?.(false);
526
+ const reason = capture.reason ?? (raw.left_chat_member ? "member_departure" : raw.new_chat_members ? "member_arrival" : raw.migrate_to_chat_id || raw.migrate_from_chat_id ? "chat_migration" : "unpaired_refused_or_empty_message");
527
+ if (capture.router !== void 0 || capture.shadow !== void 0) console.info("[segmentstream] telegram.routing", {
528
+ chatId: event.chatId,
529
+ messageId: event.messageId,
530
+ reason,
531
+ ...capture.diagnostics === void 0 ? {} : { decision: capture.diagnostics },
532
+ ...capture.router === void 0 ? {} : { router: capture.router },
533
+ ...capture.shadow === void 0 ? {} : { shadow: capture.shadow }
534
+ });
535
+ await skip(reason);
536
+ await finishRouting(capture.reason === "inbound_message_failed" || capture.reason === "decision_model_failed" || capture.reason === "decision_model_timeout" ? "failed" : "completed");
537
+ if (cleanupFailed) throw dispatchCleanupError;
538
+ return response;
539
+ }
540
+ async function storeSend(input) {
541
+ const { store, event } = input;
542
+ if (input.edit) {
543
+ const response = await input.send();
544
+ const result = object(await response.clone().json().catch(() => null));
545
+ if (event.messageId !== null && response.ok && result.ok === true) {
546
+ const target = {
547
+ channel: event.provider,
548
+ chatId: event.chatId,
549
+ messageId: event.messageId
550
+ };
551
+ const meta = metaOf(event);
552
+ const text = (event.text ?? "").slice(0, 1e5);
553
+ await (meta === void 0 ? store.change({
554
+ ...target,
555
+ change: "edit",
556
+ text
557
+ }) : writeMeta(store, target, (current) => ({
558
+ meta: {
559
+ ...object(current.meta),
560
+ ...meta
561
+ },
562
+ text,
563
+ edit: {}
564
+ })));
565
+ }
566
+ return response;
567
+ }
568
+ const operation = `telegram:send:${randomUUID()}`;
569
+ await store.record({
570
+ ...messageInput(event),
571
+ messageId: void 0,
572
+ status: "pending",
573
+ operation,
574
+ fingerprint: sendFingerprint({
575
+ operation,
576
+ ...event
577
+ })
578
+ });
579
+ const receipt = async (status, providerMessageId) => {
580
+ await store.change({
581
+ change: "sent",
582
+ channel: event.provider,
583
+ chatId: event.chatId,
584
+ operation,
585
+ status,
586
+ ...providerMessageId === void 0 ? {} : { providerMessageId }
587
+ });
588
+ };
589
+ let response;
590
+ try {
591
+ response = await input.send();
592
+ } catch (error) {
593
+ try {
594
+ await receipt("uncertain");
595
+ } catch (storageError) {
596
+ console.error("[segmentstream] recording uncertain delivery failed", {
597
+ storageError,
598
+ cause: error
599
+ });
600
+ }
601
+ throw error;
602
+ }
603
+ const result = object(await response.clone().json().catch(() => null));
604
+ const messageId = object(result.result).message_id;
605
+ const sent = (typeof messageId === "number" || typeof messageId === "string") && /^[1-9]\d*$/u.test(String(messageId));
606
+ await receipt(response.ok && result.ok === true && sent ? "sent" : result.ok === false ? "failed" : "uncertain", sent ? String(messageId) : void 0);
607
+ return response;
608
+ }
609
+ const captures = new WeakMap();
610
+ function registerCapture(inbound, capture) {
611
+ captures.set(inbound, capture);
612
+ }
613
+ function currentCapture() {
614
+ const inbound = currentInboundRequest();
615
+ return inbound === void 0 ? void 0 : captures.get(inbound);
616
+ }
617
+ const record = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
618
+ const id = (value) => typeof value === "number" || typeof value === "string" ? String(value) : null;
619
+ const REVISION_CLAIM_TTL_MS = 12e4;
620
+ function attachmentRefs(message) {
621
+ const files = message.attachments.map((file) => ({
622
+ id: file.fileId,
623
+ kind: file.kind,
624
+ ...file.fileName === void 0 ? {} : { filename: file.fileName },
625
+ ...file.mediaType === void 0 ? {} : { contentType: file.mediaType },
626
+ ...file.size === void 0 ? {} : { size: file.size },
627
+ ...file.fileUniqueId === void 0 ? {} : { uniqueId: file.fileUniqueId }
628
+ }));
629
+ for (const kind of [
630
+ "voice",
631
+ "audio",
632
+ "video",
633
+ "video_note",
634
+ "sticker",
635
+ "animation"
636
+ ]) {
637
+ const file = record(message.raw[kind]);
638
+ const fileId = id(file.file_id);
639
+ if (fileId !== null) files.push({
640
+ id: fileId,
641
+ kind,
642
+ ...id(file.file_unique_id) ? { uniqueId: id(file.file_unique_id) } : {},
643
+ ...typeof file.file_size === "number" ? { size: file.file_size } : {},
644
+ ...typeof file.mime_type === "string" ? { contentType: file.mime_type } : {},
645
+ ...typeof file.file_name === "string" ? { filename: file.file_name } : {}
646
+ });
647
+ }
648
+ return files;
649
+ }
650
+ function attachmentIdentity(files) {
651
+ return JSON.stringify(files.map((file) => [file.kind, file.uniqueId ?? file.id]));
652
+ }
653
+ function eventRouting(event) {
654
+ try {
655
+ return record(record(JSON.parse(event.argsSummary ?? "{}")).routing);
656
+ } catch {
657
+ return {};
658
+ }
659
+ }
660
+ async function participants(message, identities, resolved) {
661
+ if (message.chat.type !== "private" || message.from === void 0 || message.from.isBot) return [];
662
+ try {
663
+ const lookup = await identities.lookup({
664
+ provider: "telegram",
665
+ externalId: message.from.id
666
+ });
667
+ resolved(lookup);
668
+ return lookup.status === "paired" ? [lookup.member.id] : [];
669
+ } catch (error) {
670
+ console.error("[segmentstream] chat participant lookup failed", { error });
671
+ return [];
672
+ }
673
+ }
674
+ async function captureTelegramWebhook(input) {
675
+ let raw;
676
+ try {
677
+ raw = await input.request.clone().json();
678
+ } catch {
679
+ return input.next();
680
+ }
681
+ const update = record(raw);
682
+ const callback = record(update.callback_query);
683
+ const data = callback.data;
684
+ if (typeof data === "string" && (data.startsWith("eve_auth:") || data.startsWith("eve:"))) {
685
+ if (typeof callback.id === "string" && input.answerCallback !== void 0) {
686
+ const locale = record(callback.from).language_code;
687
+ try {
688
+ await input.answerCallback(callback.id, typeof locale === "string" ? locale : void 0);
689
+ } catch (error) {
690
+ reportTelegramError("unsupported_callback_ack_failed", error, { callbackQueryId: callback.id });
691
+ }
692
+ }
693
+ return new Response("ok");
694
+ }
695
+ if (input.chats !== void 0 && (update.my_chat_member !== void 0 || update.chat_member !== void 0)) {
696
+ const task = reportMembership({
697
+ update,
698
+ chats: input.chats,
699
+ identities: input.identities
700
+ });
701
+ currentInboundRequest()?.waitUntil?.(task);
702
+ await task;
703
+ return input.next();
704
+ }
705
+ const edited = update.edited_message ?? update.edited_channel_post;
706
+ const messagePayload = edited ?? update.channel_post ?? update.message;
707
+ const message = parseArchivedMessage(messagePayload);
708
+ if (message === void 0) return input.next();
709
+ const content = messageContent(message.raw);
710
+ const structured = input.structured?.(message.raw);
711
+ const time = edited === void 0 ? message.raw.date : message.raw.edit_date ?? message.raw.date;
712
+ const sentAt = typeof time === "number" ? time * 1e3 : Date.now();
713
+ const senderChat = record(message.raw.sender_chat);
714
+ const attachments = attachmentRefs(message);
715
+ let lookup;
716
+ const event = chatEvent({
717
+ eventId: currentKey("telegram", [
718
+ "telegram",
719
+ message.chat.id,
720
+ message.messageId,
721
+ edited === void 0 ? "message" : `edit:${id(update.update_id) ?? id(message.raw.edit_date)}`
722
+ ].join(":")),
723
+ provider: currentChannel("telegram"),
724
+ chatId: message.chat.id,
725
+ chatType: message.chat.type === "supergroup" ? "group" : message.chat.type,
726
+ threadId: message.messageThreadId === void 0 ? null : String(message.messageThreadId),
727
+ kind: "inbound",
728
+ text: content.text || null,
729
+ argsSummary: JSON.stringify({
730
+ ...contentShape(message.raw, content),
731
+ routing: {
732
+ ...messageMetadata(message),
733
+ ...attachments.length === 0 ? {} : { originalText: content.text }
734
+ }
735
+ }),
736
+ messageId: message.messageId,
737
+ replyToMessageId: message.replyToMessage?.messageId ?? null,
738
+ senderId: id(senderChat.id) ?? message.from?.id ?? null,
739
+ senderName: typeof senderChat.title === "string" ? senderChat.title : message.from?.username ?? message.from?.firstName ?? null,
740
+ senderIsBot: message.from?.isBot ?? false,
741
+ participantIds: await participants(message, input.identities, (result) => {
742
+ lookup = result;
743
+ }),
744
+ attachments,
745
+ at: new Date(sentAt).toISOString()
746
+ });
747
+ const store = await storeOf(input.archive);
748
+ if (store !== void 0) return captureInStore({
749
+ ...input,
750
+ store,
751
+ update,
752
+ edited,
753
+ messagePayload,
754
+ message,
755
+ content,
756
+ structured,
757
+ event,
758
+ lookup
759
+ });
760
+ let persisted;
761
+ const capture = {
762
+ event,
763
+ message,
764
+ archive: input.archive,
765
+ persist: () => {
766
+ persisted ??= input.archive.append(capture.event).then(() => void 0);
767
+ return persisted;
768
+ },
769
+ ...lookup === void 0 ? {} : { lookup }
770
+ };
771
+ const revisionId = edited === void 0 ? void 0 : `${currentKey("telegram", `telegram:${message.chat.id}:${message.messageId}`)}:routing:${createHash("sha256").update(JSON.stringify({
772
+ at: event.at,
773
+ content,
774
+ ...structured === void 0 ? {} : { structured },
775
+ ...event.attachments.length === 0 ? {} : { attachments: attachmentIdentity(event.attachments) }
776
+ })).digest("hex")}`;
777
+ const dispatchKey = currentKey("telegram", `telegram:${message.chat.id}:${message.messageId}`) + (structured === void 0 ? "" : `:structured:${revisionId ?? "initial"}`);
778
+ const revisionEvents = [];
779
+ let revisionClaim;
780
+ const finishRevision = async (status) => {
781
+ if (revisionClaim === void 0) return;
782
+ await input.archive.append({
783
+ ...revisionClaim,
784
+ eventId: status === "completed" ? `${revisionId}:completed` : `${revisionClaim.eventId}:failed`,
785
+ at: new Date(Date.now()).toISOString(),
786
+ status,
787
+ reason: status === "completed" ? "routing_completed" : "routing_failed"
788
+ });
789
+ };
790
+ const inbound = currentInboundRequest();
791
+ if (inbound !== void 0) captures.set(inbound, capture);
792
+ const automated = message.from === void 0 || message.from.isBot || message.chat.type === "channel";
793
+ 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();
794
+ const messageHistory = automated ? [] : (await input.archive.context({
795
+ provider: currentChannel("telegram"),
796
+ chatId: message.chat.id,
797
+ messageId: message.messageId,
798
+ includeDecisions: true,
799
+ limit: 100,
800
+ ...lookup?.status === "paired" ? { participantId: lookup.member.id } : {}
801
+ })).events;
802
+ const routing = messageHistory.filter((earlier) => earlier.kind === "decision" && earlier.senderId === event.senderId);
803
+ const dispatchHistory = structured === void 0 ? routing : routing.filter((earlier) => earlier.eventId.startsWith(`${dispatchKey}:`));
804
+ const previousClaim = dispatchHistory.find((earlier) => earlier.reason === "turn_claimed");
805
+ const admitted = dispatchHistory.some((earlier) => earlier.reason === "turn_admitted");
806
+ const released = previousClaim !== void 0 && dispatchHistory.some((earlier) => earlier.eventId === `${previousClaim.eventId}:released`);
807
+ const dispatched = dispatchHistory.some((earlier) => earlier.reason === "turn_dispatch_started");
808
+ const reserved = previousClaim !== void 0 && !released && Date.now() - Date.parse(previousClaim.at) < 6e5;
809
+ const result = dispatchHistory.find((earlier) => earlier.reason === "structured_action_completed" && earlier.status === "completed");
810
+ let structuredContext;
811
+ if (structured !== void 0 && result?.argsSummary && lookup === void 0 && message.from !== void 0 && !message.from.isBot) {
812
+ lookup = await input.identities.lookup({
813
+ provider: "telegram",
814
+ externalId: message.from.id
815
+ });
816
+ capture.lookup = lookup;
817
+ }
818
+ if (structured !== void 0 && lookup?.status === "paired" && result?.argsSummary) try {
819
+ const value = record(JSON.parse(result.argsSummary));
820
+ if (typeof value.memberId === "string" && value.memberId === lookup.member.id && typeof value.context === "string" && value.context.trim() && value.context.length <= 16384) structuredContext = {
821
+ text: value.context,
822
+ memberId: value.memberId
823
+ };
824
+ } catch {}
825
+ const continuationDispatched = dispatchHistory.some((earlier) => earlier.reason === "structured_context_dispatch_started");
826
+ const continuationPending = dispatched && structuredContext !== void 0 && !admitted && !continuationDispatched;
827
+ const alreadyHandled = (admitted || dispatched || reserved) && !continuationPending;
828
+ const rememberRevision = (events) => {
829
+ if (revisionId !== void 0) revisionEvents.push(...events.filter((item) => item.eventId === revisionId || item.eventId.startsWith(`${revisionId}:`)));
830
+ };
831
+ const historyEvents = [...messageHistory];
832
+ rememberRevision(historyEvents);
833
+ 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));
834
+ const previous = messageHistory.find(previousRevision);
835
+ const unchangedAttachments = previous !== void 0 && attachmentIdentity(previous.attachments) === attachmentIdentity(event.attachments);
836
+ const previousRouting = previous === void 0 ? {} : eventRouting(previous);
837
+ const originalEvent = previous === void 0 ? void 0 : historyEvents.find((item) => item.eventId === previous.eventId.split(":content:")[0]);
838
+ if (inbound !== void 0) {
839
+ inbound.previousText = typeof previousRouting.originalText === "string" ? previousRouting.originalText : originalEvent?.text ?? previous?.text ?? void 0;
840
+ inbound.attachmentsChanged = previous === void 0 ? event.attachments.length > 0 : !unchangedAttachments;
841
+ if (unchangedAttachments && event.attachments.length > 0) {
842
+ const decoded = Array.isArray(previousRouting.decoded) ? previousRouting.decoded : [];
843
+ const media = typeof previousRouting.media === "string" ? previousRouting.media : void 0;
844
+ await capture.persist();
845
+ const metadata = record(JSON.parse(capture.event.argsSummary ?? "{}"));
846
+ capture.event = {
847
+ ...capture.event,
848
+ argsSummary: JSON.stringify({
849
+ ...metadata,
850
+ routing: {
851
+ ...record(metadata.routing),
852
+ membership: previousRouting.membership
853
+ }
854
+ })
855
+ };
856
+ inbound.previousContent = {
857
+ decoded,
858
+ ...media === void 0 ? {} : { media }
859
+ };
860
+ const transcripts = decoded.flatMap((item) => [
861
+ "voice",
862
+ "audio",
863
+ "video_note"
864
+ ].includes(item.attachment_kind) && item.processed && typeof item.content === "string" ? [item.content] : []);
865
+ await recordInboundContent({
866
+ text: [content.text, ...transcripts].filter(Boolean).join("\n\n"),
867
+ decoded,
868
+ ...media === void 0 ? {} : { media },
869
+ ...Array.isArray(previousRouting.files) ? { files: previousRouting.files } : {}
870
+ });
871
+ }
872
+ }
873
+ if (automated || edited !== void 0) {
874
+ if (message.chat.type === "group" || message.chat.type === "supergroup") await input.chats?.seen({
875
+ chatId: message.chat.id,
876
+ title: message.chat.title ?? ""
877
+ });
878
+ capture.decision = "silent";
879
+ capture.reason = automated ? "automated_or_channel_message" : alreadyHandled ? "message_already_handled" : "message_edit";
880
+ if (alreadyHandled) capture.note = "This message already started a turn; edits and retries do not repeat its task.";
881
+ }
882
+ if (alreadyHandled) {
883
+ capture.decision = "silent";
884
+ capture.reason = "message_already_handled";
885
+ }
886
+ let accepted = false;
887
+ if (inbound !== void 0) {
888
+ inbound.structuredContext = continuationPending ? structuredContext : void 0;
889
+ inbound.edited = edited !== void 0 && !continuationPending;
890
+ if (revisionId !== void 0 && !continuationPending) inbound.claimRevision = async () => {
891
+ if (revisionEvents.some((item) => item.eventId === `${revisionId}:completed`)) return false;
892
+ const claims = revisionEvents.filter((item) => item.reason === "routing_claimed");
893
+ const latest = claims[0];
894
+ if (latest !== void 0 && !revisionEvents.some((item) => item.eventId === `${latest.eventId}:failed`) && Date.now() - Date.parse(latest.at) < 12e4) return false;
895
+ const attempt = claims.length === 0 ? void 0 : Math.max(...claims.map((item) => Number(item.eventId.slice(revisionId.length).replace(":retry:", "")))) + 1;
896
+ const claim = {
897
+ ...capture.event,
898
+ eventId: attempt === void 0 ? revisionId : `${revisionId}:retry:${attempt}`,
899
+ at: new Date(Date.now()).toISOString(),
900
+ kind: "decision",
901
+ decision: "silent",
902
+ reason: "routing_claimed",
903
+ status: "requested",
904
+ text: null,
905
+ attachments: []
906
+ };
907
+ const inserted = await input.archive.append(claim);
908
+ if (inserted !== false) revisionClaim = claim;
909
+ return inserted !== false;
910
+ };
911
+ const nextClaim = previousClaim === void 0 ? void 0 : createHash("sha256").update(previousClaim.eventId).digest("hex");
912
+ const claimId = continuationPending && previousClaim !== void 0 ? previousClaim.eventId : previousClaim === void 0 ? `${dispatchKey}:turn` : `${dispatchKey}:turn:${nextClaim}`;
913
+ let claimed = continuationPending;
914
+ let dispatchStarted = continuationPending;
915
+ const claimEvent = (reason, status, suffix = "") => ({
916
+ ...capture.event,
917
+ eventId: `${claimId}${suffix}`,
918
+ kind: "decision",
919
+ decision: "reply",
920
+ reason,
921
+ status,
922
+ at: new Date().toISOString(),
923
+ text: null,
924
+ attachments: []
925
+ });
926
+ inbound.claimTurn = async () => {
927
+ if (alreadyHandled) return false;
928
+ claimed = await input.archive.append(claimEvent("turn_claimed", "requested")) !== false;
929
+ return claimed;
930
+ };
931
+ inbound.beginDispatch = async () => {
932
+ dispatchStarted = await input.archive.append({
933
+ ...claimEvent("turn_dispatch_started", "requested"),
934
+ eventId: `${dispatchKey}:dispatch`
935
+ }) === true;
936
+ return dispatchStarted;
937
+ };
938
+ inbound.recordStructuredContext = async (context, memberId) => {
939
+ if (await input.archive.append({
940
+ ...claimEvent("structured_action_completed", "completed"),
941
+ eventId: `${dispatchKey}:result`,
942
+ argsSummary: JSON.stringify({
943
+ context,
944
+ memberId
945
+ })
946
+ }) !== true) throw new Error("The archive did not acknowledge the structured continuation.");
947
+ inbound.structuredContext = {
948
+ text: context,
949
+ memberId
950
+ };
951
+ };
952
+ inbound.beginStructuredContinuation = async () => {
953
+ const inserted = await input.archive.append({
954
+ ...claimEvent("structured_context_dispatch_started", "requested"),
955
+ eventId: `${dispatchKey}:context-dispatch`
956
+ });
957
+ dispatchStarted ||= inserted === true;
958
+ return inserted === true;
959
+ };
960
+ inbound.finishClaim = async (delivered) => {
961
+ if ((accepted || dispatchStarted) && !delivered) return;
962
+ accepted ||= delivered;
963
+ if (claimed) {
964
+ await input.archive.append(claimEvent(delivered ? "turn_admitted" : "turn_released", delivered ? "completed" : "failed", delivered ? ":admitted" : ":released"));
965
+ claimed = false;
966
+ }
967
+ };
968
+ }
969
+ let response;
970
+ try {
971
+ const routeEdit = edited !== void 0 && !automated && !alreadyHandled;
972
+ if (routeEdit) capture.reason = void 0;
973
+ response = await input.next(routeEdit ? new Request(input.request, { body: JSON.stringify({
974
+ ...update,
975
+ edited_message: void 0,
976
+ message: messagePayload
977
+ }) }) : alreadyHandled ? new Request(input.request, { body: JSON.stringify({ update_id: update.update_id }) }) : void 0);
978
+ } catch (error) {
979
+ if (!accepted) try {
980
+ await inbound?.releaseLifecycleDispatch?.();
981
+ } catch (cleanupError) {
982
+ console.error("[segmentstream] inventory dispatch cleanup failed", {
983
+ cleanupError,
984
+ cause: error
985
+ });
986
+ }
987
+ try {
988
+ await capture.persist();
989
+ await inbound?.finishClaim?.(false);
990
+ await input.archive.append({
991
+ ...capture.event,
992
+ eventId: `${event.eventId}:decision`,
993
+ kind: "decision",
994
+ text: null,
995
+ decision: "silent",
996
+ reason: "inbound_handler_failed",
997
+ attachments: []
998
+ });
999
+ await finishRevision("failed");
1000
+ } catch (storageError) {
1001
+ console.error("[segmentstream] recording inbound failure failed", {
1002
+ storageError,
1003
+ cause: error
1004
+ });
1005
+ }
1006
+ throw error;
1007
+ }
1008
+ let dispatchCleanupError;
1009
+ let cleanupFailed = false;
1010
+ if (!accepted) try {
1011
+ await inbound?.releaseLifecycleDispatch?.();
1012
+ } catch (error) {
1013
+ dispatchCleanupError = error;
1014
+ cleanupFailed = true;
1015
+ reportTelegramError("inventory_dispatch_cleanup_failed", error);
1016
+ }
1017
+ await capture.persist();
1018
+ await inbound?.finishClaim?.(false);
1019
+ await input.archive.append({
1020
+ ...capture.event,
1021
+ eventId: `${event.eventId}:decision`,
1022
+ kind: "decision",
1023
+ argsSummary: JSON.stringify({
1024
+ ...capture.diagnostics === void 0 ? {} : { decision: capture.diagnostics },
1025
+ ...capture.router === void 0 ? {} : { router: capture.router },
1026
+ ...capture.shadow === void 0 ? {} : { shadow: capture.shadow },
1027
+ routing: { membership: capture.lookup === void 0 ? "unknown" : capture.lookup.status === "paired" || capture.lookup.status === "existing" || capture.lookup.status === "created" ? "linked" : "unlinked" }
1028
+ }),
1029
+ text: capture.note ?? (edited !== void 0 ? "Message edit recorded as context; no agent turn started." : null),
1030
+ decision: capture.decision ?? "silent",
1031
+ 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"),
1032
+ attachments: []
1033
+ });
1034
+ await finishRevision(capture.reason === "inbound_message_failed" || capture.reason === "decision_model_failed" || capture.reason === "decision_model_timeout" ? "failed" : "completed");
1035
+ if (cleanupFailed) throw dispatchCleanupError;
1036
+ return response;
1037
+ }
1038
+ function recordGateDecision(reason, decision = "silent") {
1039
+ const inbound = currentInboundRequest();
1040
+ const capture = inbound === void 0 ? void 0 : captures.get(inbound);
1041
+ if (capture !== void 0) {
1042
+ capture.reason = reason;
1043
+ capture.decision = decision;
1044
+ capture.note = void 0;
1045
+ }
1046
+ }
1047
+ function recordRouteDecision(route, addressed, policy, audit) {
1048
+ const inbound = currentInboundRequest();
1049
+ const capture = inbound === void 0 ? void 0 : captures.get(inbound);
1050
+ if (capture !== void 0) {
1051
+ capture.decision = route === "reply" ? "reply" : "silent";
1052
+ if (audit?.uncertain === true) capture.reason = audit.reason;
1053
+ capture.reason ??= audit?.reason ?? (typeof addressed === "string" ? addressed : addressed ? "addressed_message" : policy === "mention" ? "mention_policy" : `decision_model_${route}`);
1054
+ capture.note = audit?.note.slice(0, 500);
1055
+ capture.routeReason = audit?.reason;
1056
+ capture.diagnostics = audit?.diagnostics;
1057
+ capture.router = audit?.router;
1058
+ capture.shadow = audit?.shadow;
1059
+ }
1060
+ }
1061
+ function captureRouteDecider(decide) {
1062
+ return async (question) => {
1063
+ try {
1064
+ return await decide(question);
1065
+ } catch (error) {
1066
+ const inbound = currentInboundRequest();
1067
+ const capture = inbound === void 0 ? void 0 : captures.get(inbound);
1068
+ if (capture !== void 0) capture.reason = error instanceof Error && error.name === "TimeoutError" ? "decision_model_timeout" : "decision_model_failed";
1069
+ throw error;
1070
+ }
1071
+ };
1072
+ }
1073
+ async function recordInboundContent(content) {
1074
+ const inbound = currentInboundRequest();
1075
+ const capture = inbound === void 0 ? void 0 : captures.get(inbound);
1076
+ if (capture?.keepContent !== void 0) return capture.keepContent(content);
1077
+ if (capture?.archive === void 0) return;
1078
+ await capture.persist();
1079
+ const metadata = record(JSON.parse(capture.event.argsSummary ?? "{}"));
1080
+ const membership = capture.lookup === void 0 ? record(metadata.routing).membership : capture.lookup.status === "paired" || capture.lookup.status === "existing" || capture.lookup.status === "created" ? "linked" : "unlinked";
1081
+ const author = content.author ?? record(metadata.routing).author;
1082
+ const files = content.files ?? record(metadata.routing).files;
1083
+ 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;
1084
+ const contentHash = createHash("sha256").update(JSON.stringify({
1085
+ ...content,
1086
+ membership
1087
+ })).digest("hex").slice(0, 16);
1088
+ const event = {
1089
+ ...capture.event,
1090
+ eventId: `${capture.event.eventId}:content:${contentHash}`,
1091
+ text: content.text,
1092
+ argsSummary: JSON.stringify({
1093
+ ...metadata,
1094
+ routing: {
1095
+ ...record(metadata.routing),
1096
+ membership,
1097
+ ...typeof author === "string" ? { author: author.slice(0, 500) } : {},
1098
+ ...Array.isArray(files) && files.length > 0 ? { files: files.slice(0, 10) } : {},
1099
+ media: content.media?.slice(0, 8e3),
1100
+ decoded: content.decoded
1101
+ }
1102
+ })
1103
+ };
1104
+ await capture.archive.append(event);
1105
+ capture.event = event;
1106
+ }
1107
+ async function outboundAudience(chatId, identities) {
1108
+ const inbound = currentInboundRequest();
1109
+ const capture = inbound === void 0 ? void 0 : captures.get(inbound);
1110
+ let participantIds = capture?.event.participantIds ?? [];
1111
+ const chatType = capture?.event.chatType ?? (chatId.startsWith("-") ? "group" : "private");
1112
+ if (chatType === "private" && participantIds.length === 0 && capture === void 0) try {
1113
+ const lookup = await identities().lookup({
1114
+ provider: "telegram",
1115
+ externalId: chatId
1116
+ });
1117
+ if (lookup.status === "paired") participantIds = [lookup.member.id];
1118
+ } catch (error) {
1119
+ console.error("[segmentstream] outbound participant lookup failed", { error });
1120
+ }
1121
+ return {
1122
+ capture,
1123
+ chatType,
1124
+ participantIds
1125
+ };
1126
+ }
1127
+ async function recordSessionFailure(input) {
1128
+ const { failure } = input;
1129
+ const sessionId = failure.sessionId === "" ? null : failure.sessionId;
1130
+ try {
1131
+ const errorText = contentText(failure.message, CONTENT_CAPS.error);
1132
+ if (input.chatId === null) {
1133
+ console.error("[segmentstream] agent log dropped unaddressed failure", {
1134
+ sessionId,
1135
+ eventType: "session.failed",
1136
+ code: failure.code,
1137
+ message: errorText
1138
+ });
1139
+ return;
1140
+ }
1141
+ if (await storeOf(input.archive) !== void 0) {
1142
+ console.error("[segmentstream] agent session failed", {
1143
+ sessionId,
1144
+ eventType: "session.failed",
1145
+ code: failure.code,
1146
+ message: errorText
1147
+ });
1148
+ return;
1149
+ }
1150
+ const { chatType, participantIds } = await outboundAudience(input.chatId, input.identities);
1151
+ await input.archive.append(chatEvent({
1152
+ eventId: sessionId === null ? `eve:session.failed:${randomUUID()}` : sessionFailureEventId(sessionId),
1153
+ provider: currentChannel("telegram"),
1154
+ chatId: input.chatId,
1155
+ chatType,
1156
+ threadId: input.threadId,
1157
+ participantIds,
1158
+ sessionId,
1159
+ kind: "decision",
1160
+ decision: "silent",
1161
+ reason: "session.failed",
1162
+ status: "failed",
1163
+ errorText
1164
+ }));
1165
+ } catch (error) {
1166
+ console.error("[segmentstream] recording session failure failed", {
1167
+ sessionId,
1168
+ error
1169
+ });
1170
+ }
1171
+ }
1172
+ function captureTelegramFetch(fetchImpl, archive, identities) {
1173
+ return async (input, init) => {
1174
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
1175
+ const edit = /\/(?:editMessageText|editMessageCaption)$/u.test(url);
1176
+ if (!url.endsWith("/sendMessage") && !edit || typeof init?.body !== "string") return fetchImpl(input, init);
1177
+ const body = record(JSON.parse(init.body));
1178
+ const chatId = id(body.chat_id);
1179
+ if (chatId === null) return fetchImpl(input, init);
1180
+ const { capture, chatType, participantIds } = await outboundAudience(chatId, identities);
1181
+ const delivery = currentDeliveryScope();
1182
+ const own = delivery?.chatId === chatId && delivery.sessionId !== null;
1183
+ const store = await storeOf(archive);
1184
+ const event = chatEvent({
1185
+ eventId: `telegram:${edit ? "edit" : "send"}:${randomUUID()}`,
1186
+ provider: currentChannel("telegram"),
1187
+ chatId,
1188
+ chatType,
1189
+ kind: "outbound",
1190
+ text: typeof body.text === "string" ? body.text : typeof body.caption === "string" ? body.caption : null,
1191
+ reason: edit ? "telegram_message_edit" : null,
1192
+ messageId: edit ? id(body.message_id) : null,
1193
+ senderIsBot: true,
1194
+ senderId: "agent",
1195
+ senderName: "agent",
1196
+ argsSummary: JSON.stringify({
1197
+ telegram: {
1198
+ ...Array.isArray(body.entities) ? { entities: body.entities } : {},
1199
+ ...Array.isArray(body.caption_entities) ? { caption_entities: body.caption_entities } : {},
1200
+ ...typeof body.parse_mode === "string" ? { parse_mode: body.parse_mode } : {}
1201
+ },
1202
+ routing: {
1203
+ ...capture?.routeReason !== void 0 && [
1204
+ "mention",
1205
+ "command",
1206
+ "reply-to-bot",
1207
+ "thread-with-agent",
1208
+ "pending-question"
1209
+ ].includes(capture.routeReason) ? { invitation: capture.routeReason } : {},
1210
+ ...currentConfirmationPrompt() === void 0 ? {} : { confirmation: currentConfirmationPrompt() },
1211
+ ...capture?.event.chatId === chatId && capture.event.senderId !== null ? { inReplyTo: {
1212
+ id: capture.event.senderId,
1213
+ author: capture.event.senderName ?? capture.event.senderId,
1214
+ ...capture.message.from?.username === void 0 ? {} : { username: capture.message.from.username }
1215
+ } } : {},
1216
+ ...currentConfirmationPrompt()?.requester === void 0 ? {} : { inReplyTo: currentConfirmationPrompt()?.requester }
1217
+ }
1218
+ }),
1219
+ participantIds,
1220
+ threadId: id(body.message_thread_id) ?? currentThreadId() ?? null,
1221
+ replyToMessageId: id(body.reply_to_message_id) ?? id(record(body.reply_parameters).message_id),
1222
+ ...own ? {
1223
+ sessionId: delivery.sessionId,
1224
+ turnId: delivery.turnId
1225
+ } : {},
1226
+ status: "requested"
1227
+ });
1228
+ if (store !== void 0) return storeSend({
1229
+ store,
1230
+ event,
1231
+ edit,
1232
+ send: () => fetchImpl(input, init)
1233
+ });
1234
+ await archive.append(event);
1235
+ let response;
1236
+ try {
1237
+ response = await fetchImpl(input, init);
1238
+ } catch (error) {
1239
+ try {
1240
+ await archive.append({
1241
+ ...event,
1242
+ eventId: `${event.eventId}:result`,
1243
+ status: "unknown"
1244
+ });
1245
+ } catch (storageError) {
1246
+ console.error("[segmentstream] recording uncertain delivery failed", {
1247
+ storageError,
1248
+ cause: error
1249
+ });
1250
+ }
1251
+ throw error;
1252
+ }
1253
+ const result = record(await response.clone().json().catch(() => null));
1254
+ const messageId = id(record(result.result).message_id);
1255
+ const acknowledged = edit || messageId !== null && /^[1-9]\d*$/u.test(messageId);
1256
+ await archive.append({
1257
+ ...event,
1258
+ eventId: `${event.eventId}:result`,
1259
+ status: response.ok && result.ok === true && acknowledged ? "completed" : result.ok === false ? "failed" : "unknown",
1260
+ messageId: messageId ?? event.messageId
1261
+ });
1262
+ return response;
1263
+ };
1264
+ }
1265
+ function chatIdentities(identities) {
1266
+ return {
1267
+ ...identities,
1268
+ resolve: async (account) => {
1269
+ const resolved = await identities.resolve(account);
1270
+ const inbound = currentInboundRequest();
1271
+ const capture = inbound === void 0 ? void 0 : captures.get(inbound);
1272
+ if (account.provider === "telegram" && capture?.message.from?.id === account.externalId) {
1273
+ capture.lookup = resolved;
1274
+ if (capture.event.chatType === "private" && (resolved.status === "existing" || resolved.status === "created")) capture.event = {
1275
+ ...capture.event,
1276
+ participantIds: [resolved.member.id]
1277
+ };
1278
+ if (capture.event.chatType === "private" && resolved.status === "limited") {
1279
+ const binding = await identities.lookup(account);
1280
+ if (binding.status === "paired") capture.event = {
1281
+ ...capture.event,
1282
+ participantIds: [binding.member.id]
1283
+ };
1284
+ }
1285
+ await capture.persist();
1286
+ }
1287
+ return resolved;
1288
+ },
1289
+ lookup: async (account) => {
1290
+ const inbound = currentInboundRequest();
1291
+ const capture = inbound === void 0 ? void 0 : captures.get(inbound);
1292
+ if (account.provider === "telegram" && capture?.message.from?.id === account.externalId) {
1293
+ const cached = capture.lookup;
1294
+ if (cached?.status === "paired" || cached?.status === "refused" || cached?.status === "unknown") return cached;
1295
+ if (cached?.status === "existing" || cached?.status === "created") return {
1296
+ status: "paired",
1297
+ member: cached.member
1298
+ };
1299
+ if (cached?.status === "pairing_required") return { status: "unknown" };
1300
+ }
1301
+ return identities.lookup(account);
1302
+ }
1303
+ };
1304
+ }
1305
+ function telegramChatCapture(input) {
1306
+ const processing = new Map();
1307
+ return async (request, next) => {
1308
+ if (!input.verify(request)) return next();
1309
+ try {
1310
+ const update = record(await request.clone().json().catch(() => null));
1311
+ const payload = record(update.edited_message ?? update.message);
1312
+ const chatId = id(record(payload.chat).id);
1313
+ const messageId = id(payload.message_id);
1314
+ const key = chatId === null || messageId === null ? void 0 : currentKey("telegram", `${chatId}:${messageId}`);
1315
+ const previous = key === void 0 ? void 0 : processing.get(key);
1316
+ const task = (async () => {
1317
+ await previous?.catch(() => void 0);
1318
+ return captureTelegramWebhook({
1319
+ ...input,
1320
+ request,
1321
+ identities: input.identities(),
1322
+ next
1323
+ });
1324
+ })();
1325
+ if (key !== void 0) processing.set(key, task);
1326
+ try {
1327
+ return await task;
1328
+ } finally {
1329
+ if (key !== void 0 && processing.get(key) === task) processing.delete(key);
1330
+ }
1331
+ } catch (error) {
1332
+ console.error("[segmentstream] chat capture failed", { error });
1333
+ return new Response("chat storage unavailable", { status: 503 });
1334
+ }
1335
+ };
1336
+ }
1337
+ export { storeSend as _, captureTelegramFetch as a, currentCapture as c, recordInboundContent as d, recordRouteDecision as f, captureInStore as g, telegramChatCapture as h, captureRouteDecider as i, participants as l, registerCapture as m, attachmentIdentity as n, captureTelegramWebhook as o, recordSessionFailure as p, attachmentRefs as r, chatIdentities as s, REVISION_CLAIM_TTL_MS as t, recordGateDecision as u };