@agents24/telegram 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,628 @@
1
+ // src/contracts.ts
2
+ var TELEGRAM_PROTOCOL = "agents24.telegram.v1";
3
+ var TEXT_TTL_MS = 24 * 60 * 60 * 1e3;
4
+ var PAIRING_TTL_MS = 10 * 60 * 1e3;
5
+ var ACTION_TTL_MS = 15 * 60 * 1e3;
6
+ var HOST_LEASE_MS = 45e3;
7
+ var MAX_TELEGRAM_BUTTONS = 40;
8
+ var TelegramError = class extends Error {
9
+ constructor(code, status = 400) {
10
+ super(code);
11
+ this.code = code;
12
+ this.status = status;
13
+ }
14
+ code;
15
+ status;
16
+ };
17
+ function emptyGatewayState() {
18
+ return { version: TELEGRAM_PROTOCOL, installations: {}, pairings: {}, bindings: {}, inbox: {}, deliveries: {}, actions: {}, updates: {}, rates: {}, nextDeliveryOrder: 1 };
19
+ }
20
+ function emptyHostState() {
21
+ return { version: TELEGRAM_PROTOCOL, bindings: {}, accepted: {} };
22
+ }
23
+
24
+ // src/host.ts
25
+ import WebSocket from "ws";
26
+ import { Agents24SDKError } from "@agents24/node";
27
+ import { setTimeout as sleep } from "timers/promises";
28
+
29
+ // src/host-http.ts
30
+ function telegramGatewayUrl(value) {
31
+ const url = new URL(value);
32
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)) || url.username || url.password || url.search || url.hash || url.pathname !== "/") throw new TelegramError("INVALID_GATEWAY_URL");
33
+ return url;
34
+ }
35
+ function createTelegramGatewayClient(options) {
36
+ const base = telegramGatewayUrl(options.gatewayUrl), fetcher = options.fetch ?? fetch;
37
+ return async (path, body) => {
38
+ const response = await fetcher(new URL(path, base), {
39
+ method: body === void 0 ? "GET" : "POST",
40
+ headers: { authorization: `Bearer ${options.credential}`, "x-agents24-telegram-protocol": TELEGRAM_PROTOCOL, "content-type": "application/json" },
41
+ body: body === void 0 ? void 0 : JSON.stringify(body),
42
+ signal: AbortSignal.timeout(3e4),
43
+ redirect: "error"
44
+ });
45
+ if (!response.ok) {
46
+ let code = "GATEWAY_REQUEST_FAILED";
47
+ try {
48
+ const data = await response.json();
49
+ if (typeof data.code === "string" && /^[A-Z_]{1,80}$/.test(data.code)) code = data.code;
50
+ } catch {
51
+ }
52
+ throw new TelegramError(code, response.status);
53
+ }
54
+ return await response.json();
55
+ };
56
+ }
57
+ async function enrollTelegramInstallation(gatewayUrl, fetcher = fetch) {
58
+ const url = telegramGatewayUrl(gatewayUrl);
59
+ const response = await fetcher(new URL("/telegram/installations", url), { method: "POST", redirect: "error", signal: AbortSignal.timeout(3e4) });
60
+ if (!response.ok) throw new TelegramError("ENROLLMENT_FAILED", response.status);
61
+ const result = await response.json();
62
+ if (result.protocol !== TELEGRAM_PROTOCOL || !/^[a-f0-9]{64}$/.test(result.credential) || !/^[a-f0-9]{32}$/.test(result.installationId)) throw new TelegramError("PROTOCOL_MISMATCH", 409);
63
+ return result;
64
+ }
65
+
66
+ // src/portable.ts
67
+ function randomToken(bytes = 24) {
68
+ const value = crypto.getRandomValues(new Uint8Array(bytes));
69
+ return Array.from(value, (n) => n.toString(16).padStart(2, "0")).join("");
70
+ }
71
+ async function digest(text) {
72
+ return Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text))), (n) => n.toString(16).padStart(2, "0")).join("");
73
+ }
74
+
75
+ // src/host.ts
76
+ function initialBinding(conversationId, observation) {
77
+ return {
78
+ conversationId,
79
+ baseline: Math.max(0, ...observation.messages.filter((m) => m.completed).map((m) => m.sequence)),
80
+ initialRuns: observation.activeRunId ? [observation.activeRunId] : [],
81
+ delivered: {},
82
+ cursor: 0,
83
+ actions: {},
84
+ prompts: {},
85
+ selections: {},
86
+ custom: {},
87
+ interrupts: {}
88
+ };
89
+ }
90
+ function createTelegramHost(options) {
91
+ const request = createTelegramGatewayClient(options), now = options.now ?? Date.now, app = options.applicationName ?? "your app";
92
+ let tail = Promise.resolve();
93
+ const checkpoint = (fn) => options.store.transaction((s) => {
94
+ if (s.version !== TELEGRAM_PROTOCOL) throw new TelegramError("PROTOCOL_MISMATCH", 409);
95
+ return fn(s);
96
+ });
97
+ const report = (code, bindingId) => {
98
+ try {
99
+ options.onStatus?.({ code, bindingId });
100
+ } catch {
101
+ }
102
+ };
103
+ const output = (b, sourceId, text, buttons, replyRef) => {
104
+ if (text.length > 6e4) {
105
+ text = text.slice(0, 6e4).replace(/[\uD800-\uDBFF]$/, "") + `
106
+
107
+ Continue in ${app} to read the full response.`;
108
+ }
109
+ return request("/telegram/outbound", { bindingId: b.id, generation: b.generation, sourceId, text, buttons, replyRef });
110
+ };
111
+ async function beginPairing(conversationId) {
112
+ return request("/telegram/pairings", { conversationId });
113
+ }
114
+ async function confirmPairing(pairingId, replace = false) {
115
+ const status = await request("/telegram/status");
116
+ const pair = status.pairings.find((p) => p.id === pairingId);
117
+ if (!pair) throw new TelegramError("PAIRING_UNAVAILABLE", 404);
118
+ if (pair.status !== "active") {
119
+ const conversation = await options.driver.resolve(pair.conversationId);
120
+ const observation = conversation ? await options.driver.read(conversation, Number.MAX_SAFE_INTEGER) : { messages: [], activeRunId: null, cancellable: false, interrupts: [] };
121
+ await checkpoint((s) => {
122
+ s.bindings[pairingId] ??= initialBinding(pair.conversationId, observation);
123
+ });
124
+ }
125
+ const result = await request(`/telegram/pairings/${pairingId}/confirm`, { replace });
126
+ await checkpoint((s) => {
127
+ const local = s.bindings[result.binding.id];
128
+ if (!local) throw new TelegramError("LOCAL_BINDING_MISSING", 409);
129
+ local.generation = result.binding.generation;
130
+ });
131
+ return result;
132
+ }
133
+ async function consume(binding, event, local) {
134
+ local = await checkpoint((s) => s.bindings[binding.id]);
135
+ if (await checkpoint((s) => !!s.accepted[event.id])) {
136
+ await request("/telegram/host/ack", { eventId: event.id });
137
+ return;
138
+ }
139
+ if (event.generation !== binding.generation || event.expiresAt <= now()) return;
140
+ if (event.kind === "text") {
141
+ const conversation = await options.driver.resolve(binding.conversationId);
142
+ const hash = await digest(`${binding.id}:${binding.generation}:${event.id}`);
143
+ const submissionId = `${hash.slice(0, 8)}-${hash.slice(8, 12)}-5${hash.slice(13, 16)}-a${hash.slice(17, 20)}-${hash.slice(20, 32)}`;
144
+ await options.driver.submit(conversation, binding.conversationId, event.text, submissionId, event.expiresAt);
145
+ } else {
146
+ const ref = event.actionRef, saved = local.actions[ref];
147
+ if (!saved || saved.expiresAt <= now()) {
148
+ await output(binding, `stale:${event.id}`, `This action is no longer available. Use the current question or run controls in ${app}.`);
149
+ } else if (saved.choice) {
150
+ const interrupt = local.interrupts[`${saved.action.runId}:${saved.action.interruptId}`];
151
+ if (!interrupt) throw new TelegramError("INTERRUPT_UNAVAILABLE", 409);
152
+ if (saved.choice.submit) {
153
+ const answers = interrupt.questions.map((q) => {
154
+ const key = `${interrupt.runId}:${interrupt.interruptId}:${q.id}`, selected = local.selections[key] ?? [], custom = local.custom[key];
155
+ if (!selected.length && !custom || !q.multiple && (selected.length > 1 || !!selected.length && !!custom)) throw new TelegramError("ANSWER_EVERY_QUESTION", 422);
156
+ return { question_id: q.id, selected_option_ids: selected, ...custom ? { custom_text: custom } : {} };
157
+ });
158
+ const conversation = await options.driver.resolve(binding.conversationId);
159
+ if (!conversation) throw new TelegramError("CONVERSATION_UNAVAILABLE", 409);
160
+ await options.driver.control(conversation, { ...saved.action, answers }, `telegram:${binding.id}:${event.id}`);
161
+ } else if (saved.choice.freeText && !event.text) {
162
+ await output(binding, `other:${event.id}`, "Reply to this message with your answer, then press Submit answers on the question.", void 0, ref);
163
+ } else {
164
+ const question = interrupt.questions.find((q) => q.id === saved.choice.questionId);
165
+ if (!question) throw new TelegramError("QUESTION_UNAVAILABLE", 409);
166
+ const key = `${interrupt.runId}:${interrupt.interruptId}:${question.id}`;
167
+ await checkpoint((s) => {
168
+ const current = s.bindings[binding.id];
169
+ if (s.accepted[event.id]) return;
170
+ if (saved.choice.freeText) {
171
+ if (!event.text?.trim() || event.text.length > 2e3) throw new TelegramError("INVALID_ANSWER", 422);
172
+ current.custom[key] = event.text.trim();
173
+ if (!question.multiple) current.selections[key] = [];
174
+ } else {
175
+ const optionId = saved.choice.optionId;
176
+ if (!question.options.some((o) => o.id === optionId)) throw new TelegramError("OPTION_UNAVAILABLE", 409);
177
+ const chosen = current.selections[key] ?? [];
178
+ current.selections[key] = question.multiple ? chosen.includes(optionId) ? chosen.filter((v) => v !== optionId) : [...chosen, optionId] : [optionId];
179
+ if (!question.multiple) delete current.custom[key];
180
+ }
181
+ s.accepted[event.id] = now();
182
+ });
183
+ await output(binding, `selection:${event.id}`, "Answer selected. Press Submit answers when every question is answered.");
184
+ }
185
+ } else {
186
+ const conversation = await options.driver.resolve(binding.conversationId);
187
+ if (!conversation) throw new TelegramError("CONVERSATION_UNAVAILABLE", 409);
188
+ await options.driver.control(conversation, saved.action, `telegram:${binding.id}:${event.id}`);
189
+ if (saved.action.action === "stop") await output(binding, `stop:${event.id}`, `Stop requested for that run. Continue in ${app} before resuming queued work.`);
190
+ }
191
+ }
192
+ await checkpoint((s) => {
193
+ s.accepted[event.id] = now();
194
+ });
195
+ await request("/telegram/host/ack", { eventId: event.id });
196
+ }
197
+ async function reconcile(binding) {
198
+ const local = await checkpoint((s) => s.bindings[binding.id]);
199
+ if (!local || local.generation !== binding.generation) {
200
+ report("LOCAL_BINDING_MISSING", binding.id);
201
+ return;
202
+ }
203
+ const conversation = await options.driver.resolve(binding.conversationId);
204
+ if (!conversation) return;
205
+ const observation = await options.driver.read(conversation, local.watermark ?? local.baseline, local.threadCursor, local.initialRuns);
206
+ for (const message of observation.messages) {
207
+ if (!message.completed || !message.text.trim() || local.delivered[message.id] || message.sequence <= local.baseline && !local.initialRuns.includes(message.runId ?? "")) continue;
208
+ await output(binding, `message:${message.id}`, message.text);
209
+ await checkpoint((s) => {
210
+ s.bindings[binding.id].delivered[message.id] = true;
211
+ });
212
+ }
213
+ const valid = new Set(observation.interrupts.map((i) => `${i.runId}:${i.interruptId}`));
214
+ const invalid = Object.entries(local.actions).filter(([, a]) => a.action.action === "stop" ? a.action.runId !== observation.activeRunId : !valid.has(`${a.action.runId}:${a.action.interruptId}`)).map(([ref]) => ref);
215
+ if (invalid.length) {
216
+ await request("/telegram/actions/invalidate", { bindingId: binding.id, generation: binding.generation, actionRefs: invalid });
217
+ await checkpoint((s) => {
218
+ for (const ref of invalid) delete s.bindings[binding.id].actions[ref];
219
+ });
220
+ }
221
+ async function action(action2, choice) {
222
+ return checkpoint((s) => {
223
+ const current = s.bindings[binding.id], identity = JSON.stringify([action2, choice]);
224
+ const existing = Object.entries(current.actions).find(([, a]) => JSON.stringify([a.action, a.choice]) === identity && a.expiresAt > now() + 6e4);
225
+ if (existing) return existing[0];
226
+ const ref = randomToken(16);
227
+ current.actions[ref] = { action: action2, choice, expiresAt: now() + ACTION_TTL_MS };
228
+ return ref;
229
+ });
230
+ }
231
+ if (observation.activeRunId && observation.cancellable) {
232
+ const ref = await action({ action: "stop", runId: observation.activeRunId });
233
+ await output(binding, `run:${observation.activeRunId}:${ref}`, `${app} is working on this conversation.`, [{ label: "Stop", actionRef: ref, kind: "stop" }]);
234
+ }
235
+ for (const interrupt of observation.interrupts) {
236
+ const key = `${interrupt.runId}:${interrupt.interruptId}`, fingerprint = await digest(JSON.stringify(interrupt));
237
+ if (local.prompts[key] === fingerprint && Object.values(local.actions).some((a) => a.action.interruptId === interrupt.interruptId && a.expiresAt > now() + 6e4)) continue;
238
+ const buttons = [];
239
+ let text = interrupt.message;
240
+ if (interrupt.unsupported) text += `
241
+ Continue in ${app} to complete this interaction.`;
242
+ else {
243
+ for (const verb of interrupt.actions) buttons.push({
244
+ label: verb === "approve" ? "Approve" : "Reject",
245
+ actionRef: await action({ action: verb, runId: interrupt.runId, interruptId: interrupt.interruptId }),
246
+ kind: "answer"
247
+ });
248
+ for (const [index, question] of interrupt.questions.entries()) {
249
+ text += `
250
+
251
+ ${index + 1}. ${question.text}${question.multiple ? " (choose any that apply)" : ""}`;
252
+ const base = { action: "respond", runId: interrupt.runId, interruptId: interrupt.interruptId };
253
+ for (const option of question.options) buttons.push({
254
+ label: `${index + 1}: ${option.label}`.slice(0, 100).replace(/[\uD800-\uDBFF]$/, ""),
255
+ actionRef: await action(base, { questionId: question.id, optionId: option.id }),
256
+ kind: "answer"
257
+ });
258
+ if (question.allowText) buttons.push({ label: `${index + 1}: Other`, actionRef: await action(base, { questionId: question.id, freeText: true }), kind: "answer" });
259
+ }
260
+ if (interrupt.questions.length) buttons.push({ label: "Submit answers", actionRef: await action({ action: "respond", runId: interrupt.runId, interruptId: interrupt.interruptId }, { submit: true }), kind: "answer" });
261
+ }
262
+ await checkpoint((s) => {
263
+ s.bindings[binding.id].interrupts[`${interrupt.runId}:${interrupt.interruptId}`] = interrupt;
264
+ });
265
+ const identity = await digest(JSON.stringify([fingerprint, buttons]));
266
+ await output(binding, `interrupt:${identity}`, text, buttons);
267
+ await checkpoint((s) => {
268
+ s.bindings[binding.id].prompts[key] = fingerprint;
269
+ });
270
+ }
271
+ await checkpoint((s) => {
272
+ const current = s.bindings[binding.id];
273
+ current.cursor = observation.cursor ?? current.cursor;
274
+ current.runId = observation.runId;
275
+ current.threadCursor = observation.threadCursor ?? current.threadCursor;
276
+ current.watermark = Math.max(current.watermark ?? current.baseline, ...observation.messages.filter((m) => m.completed).map((m) => m.sequence));
277
+ current.initialRuns = current.initialRuns.filter((id) => id === observation.activeRunId || !observation.messages.some((m) => m.runId === id && (m.terminal || m.completed)));
278
+ for (const [id, timestamp] of Object.entries(s.accepted)) if (timestamp < now() - 30 * 24 * 60 * 6e4) delete s.accepted[id];
279
+ });
280
+ }
281
+ async function poll() {
282
+ let healthy = true;
283
+ const data = await request("/telegram/host/poll", {});
284
+ if (data.protocol !== TELEGRAM_PROTOCOL) throw new TelegramError("PROTOCOL_MISMATCH", 409);
285
+ for (const binding of data.bindings) {
286
+ const local = await checkpoint((s) => s.bindings[binding.id]);
287
+ if (!local || local.generation !== binding.generation) {
288
+ healthy = false;
289
+ report("LOCAL_BINDING_MISSING", binding.id);
290
+ continue;
291
+ }
292
+ for (const event of data.events.filter((e) => e.bindingId === binding.id)) {
293
+ try {
294
+ await consume(binding, event, local);
295
+ } catch (error) {
296
+ const status = error instanceof TelegramError || error instanceof Agents24SDKError ? error.status : void 0;
297
+ if (status && [400, 403, 404, 409, 422].includes(status)) {
298
+ const code = error instanceof TelegramError ? error.code : "RUNTIME_ACTION_UNAVAILABLE";
299
+ await output(binding, `failure:${event.id}`, `${app} could not accept this action (${code}). Continue in ${app}.`);
300
+ await checkpoint((s) => {
301
+ s.accepted[event.id] = now();
302
+ });
303
+ await request("/telegram/host/ack", { eventId: event.id });
304
+ } else {
305
+ healthy = false;
306
+ report("HOST_ADMISSION_FAILED", binding.id);
307
+ break;
308
+ }
309
+ }
310
+ }
311
+ try {
312
+ await reconcile(binding);
313
+ } catch {
314
+ healthy = false;
315
+ report("OBSERVATION_UNAVAILABLE", binding.id);
316
+ }
317
+ }
318
+ if (healthy) report("CONNECTED");
319
+ }
320
+ function tick() {
321
+ const work = tail.then(poll);
322
+ tail = work.then(() => {
323
+ }, () => {
324
+ });
325
+ return work;
326
+ }
327
+ async function run(signal) {
328
+ let socket, connectingAt = 0, wake;
329
+ const base = telegramGatewayUrl(options.gatewayUrl);
330
+ base.protocol = base.protocol === "https:" ? "wss:" : "ws:";
331
+ base.pathname = "/telegram/host/ws";
332
+ try {
333
+ while (!signal.aborted) {
334
+ if ((!socket || socket.readyState === WebSocket.CLOSED) && Date.now() - connectingAt > 5e3) {
335
+ connectingAt = Date.now();
336
+ socket = new WebSocket(base, { headers: { authorization: `Bearer ${options.credential}`, "x-agents24-telegram-protocol": TELEGRAM_PROTOCOL }, handshakeTimeout: 1e4 });
337
+ socket.on("error", () => report("RECONNECTING"));
338
+ socket.on("message", () => wake?.());
339
+ }
340
+ try {
341
+ await tick();
342
+ } catch {
343
+ report("RECONNECTING");
344
+ }
345
+ try {
346
+ await Promise.race([sleep(1500, void 0, { signal }), new Promise((resolve) => {
347
+ wake = resolve;
348
+ })]);
349
+ } finally {
350
+ wake = void 0;
351
+ }
352
+ }
353
+ } catch (error) {
354
+ if (!signal.aborted) throw error;
355
+ } finally {
356
+ socket?.terminate();
357
+ }
358
+ }
359
+ return {
360
+ tick,
361
+ run,
362
+ beginPairing,
363
+ confirmPairing,
364
+ status: () => request("/telegram/status"),
365
+ disconnect: (bindingId) => request(`/telegram/bindings/${bindingId}/revoke`, {}),
366
+ resolveDelivery: (deliveryId, action) => request("/telegram/deliveries/resolve", { deliveryId, action })
367
+ };
368
+ }
369
+
370
+ // src/sdk-driver.ts
371
+ function scope(c) {
372
+ return {
373
+ externalUserId: c.externalUserId,
374
+ externalSessionId: c.externalSessionId,
375
+ integrationId: c.integrationId,
376
+ chatScope: c.chatScope,
377
+ runtimeTarget: c.runtimeTarget ?? "published"
378
+ };
379
+ }
380
+ function projectTelegramInterrupt(raw, runId) {
381
+ const id = String(raw.interrupt_id ?? "");
382
+ const actions = (Array.isArray(raw.allowed_actions) ? raw.allowed_actions : []).filter((a) => a === "approve" || a === "reject");
383
+ const questions = (Array.isArray(raw.presentation?.questions) ? raw.presentation.questions : []).map((q) => ({
384
+ id: String(q.id ?? ""),
385
+ text: String(q.question ?? ""),
386
+ multiple: q.multi_select === true,
387
+ allowText: true,
388
+ options: (Array.isArray(q.options) ? q.options : []).map((o) => ({ id: String(o.id ?? ""), label: String(o.label ?? "") }))
389
+ }));
390
+ return {
391
+ runId,
392
+ interruptId: id,
393
+ message: String(raw.message ?? raw.title ?? "Your response is needed."),
394
+ actions: [...new Set(actions)],
395
+ questions,
396
+ unsupported: raw.schema_version !== "agents24.hitl.interrupt.v2" || !id || !["approval", "user_input"].includes(raw.kind) || questions.length > 0 && !raw.allowed_actions?.includes("respond") || !actions.length && !questions.length || actions.length + questions.reduce((n, q) => n + q.options.length + 1, 1) > MAX_TELEGRAM_BUTTONS || String(raw.message ?? "").length + questions.reduce((n, q) => n + q.text.length, 0) > 8e3 || questions.some((q) => !q.id || !q.text || q.options.some((o) => !o.id || !o.label))
397
+ };
398
+ }
399
+ function createAgents24TelegramDriver(options) {
400
+ return {
401
+ resolve: options.resolve,
402
+ async submit(conversation, conversationId, text, submissionId, expiresAt) {
403
+ if (options.admitMessage) return options.admitMessage(conversation, conversationId, text, submissionId, expiresAt);
404
+ if (!conversation) throw new TelegramError("CONVERSATION_UNAVAILABLE", 409);
405
+ await options.client.embed.submitAgentThreadMessage(conversation.agentId, conversation.threadId, {
406
+ ...scope(conversation),
407
+ input: text,
408
+ mode: "queue",
409
+ clientSubmissionId: submissionId,
410
+ executionLimits: { deadline_at: new Date(expiresAt).toISOString() }
411
+ }, { idempotencyKey: submissionId });
412
+ },
413
+ async read(conversation, afterSequence, threadCursor, includeRunIds = []) {
414
+ const scoped = scope(conversation), embed = options.client.embed;
415
+ let nextCursor = threadCursor, snapshotRequired = false;
416
+ await embed.subscribeAgentThreadEventsMulti({
417
+ ...scoped,
418
+ agentIds: conversation.agentIds ?? [conversation.agentId],
419
+ threadId: conversation.threadId,
420
+ cursor: threadCursor,
421
+ leaseSeconds: options.observationLeaseSeconds ?? 1,
422
+ signal: AbortSignal.timeout(1e4),
423
+ onControl: (control) => {
424
+ if (control.type === "ready" && control.cursor !== void 0) nextCursor = Math.max(nextCursor ?? 0, control.cursor);
425
+ }
426
+ }, (event) => {
427
+ if (event.event === "thread.deleted") throw new TelegramError("CONVERSATION_DELETED", 404);
428
+ if (event.event === "snapshot_required") {
429
+ snapshotRequired = true;
430
+ nextCursor = event.cursor;
431
+ } else nextCursor = Math.max(nextCursor ?? 0, event.cursor);
432
+ });
433
+ const detail = await embed.getConversationThread(conversation.threadId, { ...scoped, agentIds: conversation.agentIds ?? [conversation.agentId] });
434
+ const observation = {
435
+ messages: [],
436
+ activeRunId: detail.active_run?.run_id ?? null,
437
+ cancellable: detail.active_run?.is_cancellable === true,
438
+ interrupts: [],
439
+ threadCursor: nextCursor
440
+ };
441
+ const outstanding = new Set(includeRunIds);
442
+ let before;
443
+ for (let page = 0; ; page++) {
444
+ if (page >= 100) throw new TelegramError("RECONCILIATION_LIMIT", 409);
445
+ const result = await embed.listAgentThreadMessages(conversation.agentId, conversation.threadId, { ...scoped, before, limit: 100 });
446
+ for (const message of result.items) {
447
+ if (message.role === "assistant" && message.run_id) outstanding.delete(message.run_id);
448
+ observation.messages.push({
449
+ id: message.id,
450
+ sequence: message.sequence,
451
+ runId: message.run_id,
452
+ text: message.text,
453
+ terminal: message.role === "assistant" && ["completed", "failed", "cancelled"].includes(message.status),
454
+ completed: message.role === "assistant" && message.status === "completed" && !!message.response_completion
455
+ });
456
+ }
457
+ const baselineFound = afterSequence !== Number.MAX_SAFE_INTEGER || observation.messages.some((m) => m.completed);
458
+ if (!result.paging.has_more || !result.items.length || !snapshotRequired && !outstanding.size && baselineFound && result.items.some((m) => m.sequence <= afterSequence)) break;
459
+ const next = result.paging.next_before_turn_index;
460
+ if (next == null || next === before) throw new TelegramError("INVALID_HISTORY_CURSOR", 409);
461
+ before = next;
462
+ }
463
+ observation.messages.sort((a, b) => a.sequence - b.sequence);
464
+ const runId = observation.activeRunId;
465
+ if (runId) {
466
+ const resolved = await embed.resolveConversationRun(runId, {
467
+ agent_ids: conversation.agentIds ?? [conversation.agentId],
468
+ external_user_id: conversation.externalUserId,
469
+ external_session_id: conversation.externalSessionId,
470
+ integration_id: conversation.integrationId,
471
+ chat_scope: conversation.chatScope,
472
+ runtime_target: conversation.runtimeTarget ?? "published"
473
+ });
474
+ await embed.attachAgentRun(resolved.agent_id, runId, {
475
+ external_user_id: conversation.externalUserId,
476
+ external_session_id: conversation.externalSessionId,
477
+ integration_id: conversation.integrationId,
478
+ chat_scope: conversation.chatScope,
479
+ runtime_target: conversation.runtimeTarget ?? "published"
480
+ }, (event) => {
481
+ observation.cursor = Math.max(observation.cursor ?? 0, event.seq);
482
+ observation.runId = runId;
483
+ const payload = event.payload;
484
+ if (event.event === "run.snapshot" || event.event === "run.paused") {
485
+ observation.interrupts = (payload.interrupts ?? []).map((r) => projectTelegramInterrupt(r, runId));
486
+ } else if (event.event === "hitl.requested") {
487
+ const raw = payload.response_block?.hitl ?? payload.hitl;
488
+ if (raw) observation.interrupts.push(projectTelegramInterrupt(raw, runId));
489
+ }
490
+ }, { leaseSeconds: options.observationLeaseSeconds ?? 1, signal: AbortSignal.timeout(1e4) });
491
+ }
492
+ return observation;
493
+ },
494
+ async control(conversation, action, idempotencyKey) {
495
+ const scoped = scope(conversation), embed = options.client.embed;
496
+ const resolved = await embed.resolveConversationRun(action.runId, {
497
+ agent_ids: conversation.agentIds ?? [conversation.agentId],
498
+ external_user_id: conversation.externalUserId,
499
+ external_session_id: conversation.externalSessionId,
500
+ integration_id: conversation.integrationId,
501
+ chat_scope: conversation.chatScope,
502
+ runtime_target: conversation.runtimeTarget ?? "published"
503
+ });
504
+ if (action.action === "stop") {
505
+ await options.beforeStop?.(conversation.externalSessionId ?? conversation.threadId, action.runId);
506
+ await embed.cancelAgentRun(resolved.agent_id, action.runId, scoped, { idempotencyKey });
507
+ } else {
508
+ if (!action.interruptId) throw new TelegramError("INTERRUPT_UNAVAILABLE", 409);
509
+ await embed.resumeAgentRun(resolved.agent_id, action.runId, {
510
+ external_user_id: conversation.externalUserId,
511
+ external_session_id: conversation.externalSessionId,
512
+ integration_id: conversation.integrationId,
513
+ chat_scope: conversation.chatScope,
514
+ runtime_target: conversation.runtimeTarget ?? "published",
515
+ schema_version: "agents24.hitl.resume.v2",
516
+ interrupt_id: action.interruptId,
517
+ action: action.action,
518
+ answers: action.answers
519
+ }, { idempotencyKey });
520
+ }
521
+ }
522
+ };
523
+ }
524
+
525
+ // src/file-store.ts
526
+ import { open, readFile, rename, mkdir, unlink } from "fs/promises";
527
+ import { dirname, isAbsolute } from "path";
528
+ import { randomUUID } from "crypto";
529
+ async function createTelegramFileStore(path, initial) {
530
+ if (!isAbsolute(path)) throw new Error("Telegram state requires an absolute private path");
531
+ await mkdir(dirname(path), { recursive: true, mode: 448 });
532
+ const lockPath = `${path}.lock`;
533
+ let lock;
534
+ try {
535
+ lock = await open(lockPath, "wx", 384);
536
+ } catch (error) {
537
+ if (error.code !== "EEXIST") throw error;
538
+ let pid;
539
+ try {
540
+ pid = Number(await readFile(lockPath, "utf8"));
541
+ } catch {
542
+ throw new Error("Telegram state lock is invalid");
543
+ }
544
+ if (!Number.isSafeInteger(pid) || pid < 1) throw new Error("Telegram state lock is invalid");
545
+ try {
546
+ process.kill(pid, 0);
547
+ throw new Error("Telegram state already has an active writer");
548
+ } catch (failure) {
549
+ if (failure.code !== "ESRCH") throw failure;
550
+ }
551
+ await unlink(lockPath);
552
+ lock = await open(lockPath, "wx", 384);
553
+ }
554
+ await lock.writeFile(String(process.pid));
555
+ await lock.sync();
556
+ let state = structuredClone(initial), tail = Promise.resolve(), closed = false;
557
+ try {
558
+ state = JSON.parse(await readFile(path, "utf8"));
559
+ } catch (error) {
560
+ if (error.code !== "ENOENT") {
561
+ await lock.close();
562
+ await unlink(lockPath);
563
+ throw new Error("Telegram state could not be read");
564
+ }
565
+ }
566
+ let serialized = JSON.stringify(state);
567
+ return {
568
+ transaction(change) {
569
+ const next = tail.then(async () => {
570
+ if (closed) throw new Error("Telegram state is closed");
571
+ const candidate = structuredClone(state), result = change(candidate), temporary = `${path}.${randomUUID()}.tmp`;
572
+ if (result && typeof result.then === "function") throw new Error("Telegram transactions must be synchronous");
573
+ const encoded = JSON.stringify(candidate);
574
+ if (encoded === serialized) return structuredClone(result);
575
+ const file = await open(temporary, "wx", 384);
576
+ try {
577
+ await file.writeFile(encoded);
578
+ await file.sync();
579
+ await file.close();
580
+ await rename(temporary, path);
581
+ const parent = await open(dirname(path), "r");
582
+ try {
583
+ await parent.sync();
584
+ } finally {
585
+ await parent.close();
586
+ }
587
+ } catch (error) {
588
+ await file.close().catch(() => {
589
+ });
590
+ await unlink(temporary).catch(() => {
591
+ });
592
+ throw error;
593
+ }
594
+ state = candidate;
595
+ serialized = encoded;
596
+ return structuredClone(result);
597
+ });
598
+ tail = next.then(() => {
599
+ }, () => {
600
+ });
601
+ return next;
602
+ },
603
+ async close() {
604
+ await tail;
605
+ closed = true;
606
+ await lock.close();
607
+ await unlink(lockPath);
608
+ }
609
+ };
610
+ }
611
+ export {
612
+ ACTION_TTL_MS,
613
+ HOST_LEASE_MS,
614
+ MAX_TELEGRAM_BUTTONS,
615
+ PAIRING_TTL_MS,
616
+ TELEGRAM_PROTOCOL,
617
+ TEXT_TTL_MS,
618
+ TelegramError,
619
+ createAgents24TelegramDriver,
620
+ createTelegramFileStore,
621
+ createTelegramGatewayClient,
622
+ createTelegramHost,
623
+ emptyGatewayState,
624
+ emptyHostState,
625
+ enrollTelegramInstallation,
626
+ projectTelegramInterrupt
627
+ };
628
+ //# sourceMappingURL=index.js.map