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