@agentpro/scroll-telegram 0.0.0-stage → 2.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -2
- package/bin/scroll-telegram.js +114 -0
- package/package.json +28 -4
- package/src/index.js +4 -0
- package/src/telegram-admin-ui.js +157 -0
- package/src/telegram-api.js +180 -0
- package/src/telegram-daemon.js +643 -0
package/README.md
CHANGED
|
@@ -1,3 +1,19 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @agentpro/scroll-telegram
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Zero-dependency Telegram multi-bot fleet adapter for `@agentpro/scroll`.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- Long-polling Telegram Bot API client (`createTelegramApi`) with retry backoff, photo download, and file uploads.
|
|
8
|
+
- Multi-bot fleet daemon (`createTelegramFleetDaemon`) sharing a persistent Codex App-Server client, AuthStore, Cron Scheduler, WorkerPool, GroupGrantStore, and LongTaskRunner.
|
|
9
|
+
- DM-locked inline `/admin` UI (`createTelegramAdminUi`) backed by `@agentpro/scroll/chat`'s transport-agnostic `AdminController`.
|
|
10
|
+
- Inline HITL tool approval buttons (`Approve` / `Deny`) bound to single-use per-call tokens.
|
|
11
|
+
- Dynamic `plugins: [...]` loader for private extensions and optional voice hooks.
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npm install @agentpro/scroll @agentpro/scroll-telegram
|
|
17
|
+
scroll-telegram doctor --config ./config.json
|
|
18
|
+
scroll-telegram start --config ./config.json
|
|
19
|
+
```
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// CLI entrypoint for `@agentpro/scroll-telegram`.
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import {
|
|
6
|
+
findCodexBinary,
|
|
7
|
+
checkAgent,
|
|
8
|
+
openKnowledge,
|
|
9
|
+
createCodexAppServerClient,
|
|
10
|
+
} from '@agentpro/scroll';
|
|
11
|
+
import { createTelegramFleetDaemon } from '../src/telegram-daemon.js';
|
|
12
|
+
|
|
13
|
+
function parseArgs(argv) {
|
|
14
|
+
const out = { _: [] };
|
|
15
|
+
for (let i = 0; i < argv.length; i++) {
|
|
16
|
+
const a = argv[i];
|
|
17
|
+
if (a.startsWith('--')) {
|
|
18
|
+
const k = a.slice(2);
|
|
19
|
+
const next = argv[i + 1];
|
|
20
|
+
if (!next || next.startsWith('--')) out[k] = true;
|
|
21
|
+
else { out[k] = next; i++; }
|
|
22
|
+
} else {
|
|
23
|
+
out._.push(a);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return out;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function loadConfig(configPath) {
|
|
30
|
+
const abs = path.resolve(configPath || path.join(process.env.HOME || '.', '.scroll-telegram', 'config.json'));
|
|
31
|
+
if (!fs.existsSync(abs)) {
|
|
32
|
+
throw new Error(`Config file not found: ${abs}`);
|
|
33
|
+
}
|
|
34
|
+
const parsed = JSON.parse(fs.readFileSync(abs, 'utf8'));
|
|
35
|
+
return { abs, config: { baseDir: path.dirname(abs), ...parsed } };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function main() {
|
|
39
|
+
const args = parseArgs(process.argv.slice(2));
|
|
40
|
+
const cmd = args._[0] || 'help';
|
|
41
|
+
|
|
42
|
+
if (cmd === 'start') {
|
|
43
|
+
const { config } = loadConfig(args.config);
|
|
44
|
+
const daemon = await createTelegramFleetDaemon(config);
|
|
45
|
+
const onSig = async (sig) => {
|
|
46
|
+
console.log(`[scroll-telegram] received ${sig}, shutting down cleanly...`);
|
|
47
|
+
await daemon.stop();
|
|
48
|
+
process.exit(0);
|
|
49
|
+
};
|
|
50
|
+
process.on('SIGTERM', () => onSig('SIGTERM'));
|
|
51
|
+
process.on('SIGINT', () => onSig('SIGINT'));
|
|
52
|
+
await daemon.start();
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
if (cmd === 'doctor') {
|
|
57
|
+
const { abs, config } = loadConfig(args.config);
|
|
58
|
+
const report = {
|
|
59
|
+
configPath: abs,
|
|
60
|
+
stateDir: path.resolve(config.stateDir || path.dirname(abs)),
|
|
61
|
+
codexBinary: findCodexBinary({
|
|
62
|
+
command: config.codexAppServer?.command || null,
|
|
63
|
+
searchPaths: config.codexAppServer?.searchPaths || [],
|
|
64
|
+
}),
|
|
65
|
+
bots: [],
|
|
66
|
+
};
|
|
67
|
+
for (const b of config.bots || []) {
|
|
68
|
+
const check = checkAgent(b.agentName || b.id, path.resolve(b.deploymentDir));
|
|
69
|
+
const kb = openKnowledge({ cwd: path.resolve(b.deploymentDir) });
|
|
70
|
+
report.bots.push({
|
|
71
|
+
id: b.id,
|
|
72
|
+
enabled: b.enabled !== false,
|
|
73
|
+
agentName: b.agentName || b.id,
|
|
74
|
+
level: check.level,
|
|
75
|
+
errors: check.errors,
|
|
76
|
+
knowledgeChunks: kb.active ? kb.chunks.length : 0,
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
console.log(JSON.stringify(report, null, 2));
|
|
80
|
+
if (report.bots.some((b) => b.enabled && b.errors.length > 0)) process.exitCode = 1;
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
if (cmd === 'login-chatgpt') {
|
|
85
|
+
const { config } = loadConfig(args.config);
|
|
86
|
+
const client = createCodexAppServerClient({
|
|
87
|
+
command: config.codexAppServer?.command || null,
|
|
88
|
+
searchPaths: config.codexAppServer?.searchPaths || [],
|
|
89
|
+
});
|
|
90
|
+
try {
|
|
91
|
+
const acct = await client.readAccount();
|
|
92
|
+
if (acct?.account && !args.force) {
|
|
93
|
+
console.log(JSON.stringify({ status: 'already_signed_in', account: acct.account }, null, 2));
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
const login = await client.startLogin({ type: 'chatgpt' });
|
|
97
|
+
console.log(JSON.stringify({ status: 'login_started', ...login }, null, 2));
|
|
98
|
+
} finally {
|
|
99
|
+
await client.close();
|
|
100
|
+
}
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
console.log(`scroll-telegram -- SCROLL 2.5 Multi-Bot Telegram Fleet Daemon
|
|
105
|
+
Usage:
|
|
106
|
+
scroll-telegram start --config <path/to/config.json>
|
|
107
|
+
scroll-telegram doctor --config <path/to/config.json>
|
|
108
|
+
scroll-telegram login-chatgpt --config <path/to/config.json> [--force]`);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
main().catch((err) => {
|
|
112
|
+
console.error('[scroll-telegram] fatal:', err?.message || err);
|
|
113
|
+
process.exit(1);
|
|
114
|
+
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,30 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agentpro/scroll-telegram",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "2.5.0",
|
|
4
|
+
"description": "Zero-dependency Telegram multi-bot fleet adapter for @agentpro/scroll (polling, inline /admin UI, HITL approval buttons, multimodal vision, cron delivery, and plugin hooks).",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "src/index.js",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./src/index.js",
|
|
9
|
+
"./api": "./src/telegram-api.js",
|
|
10
|
+
"./admin-ui": "./src/telegram-admin-ui.js",
|
|
11
|
+
"./daemon": "./src/telegram-daemon.js",
|
|
12
|
+
"./package.json": "./package.json"
|
|
13
|
+
},
|
|
14
|
+
"bin": {
|
|
15
|
+
"scroll-telegram": "bin/scroll-telegram.js"
|
|
16
|
+
},
|
|
17
|
+
"engines": {
|
|
18
|
+
"node": ">=20"
|
|
19
|
+
},
|
|
20
|
+
"files": [
|
|
21
|
+
"bin",
|
|
22
|
+
"src",
|
|
23
|
+
"README.md"
|
|
24
|
+
],
|
|
25
|
+
"dependencies": {},
|
|
26
|
+
"peerDependencies": {
|
|
27
|
+
"@agentpro/scroll": "^2.5.0"
|
|
28
|
+
},
|
|
29
|
+
"license": "MIT"
|
|
30
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
// Telegram Inline Keyboard Admin UI wrapping @agentpro/scroll/chat's pure JSON AdminController.
|
|
2
|
+
import { ADMIN_CALLBACK_NAMESPACE } from '@agentpro/scroll/chat';
|
|
3
|
+
|
|
4
|
+
export function createTelegramAdminUi({
|
|
5
|
+
controller,
|
|
6
|
+
namespace = ADMIN_CALLBACK_NAMESPACE,
|
|
7
|
+
} = {}) {
|
|
8
|
+
if (!controller) throw new Error('createTelegramAdminUi: controller is required');
|
|
9
|
+
|
|
10
|
+
const btn = (text, ...parts) => ({
|
|
11
|
+
text,
|
|
12
|
+
callback_data: [namespace, ...parts].join(':'),
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
function renderView({ page = 'home', botId = null, notice = null } = {}) {
|
|
16
|
+
const status = controller.getStatus();
|
|
17
|
+
const lines = [];
|
|
18
|
+
const buttons = [];
|
|
19
|
+
|
|
20
|
+
if (page === 'bot' && botId) {
|
|
21
|
+
const b = status.bots.find((x) => x.id === botId);
|
|
22
|
+
if (b) {
|
|
23
|
+
lines.push(`Admin - Bot ${b.id} (${b.username ? '@' + b.username : b.agentName})`);
|
|
24
|
+
lines.push(`- State: ${b.paused ? 'Paused' : 'Running'}`);
|
|
25
|
+
lines.push(`- Provider/Model: ${b.provider} - ${b.model || 'auto'}`);
|
|
26
|
+
lines.push(`- Group policy: ${b.groupPolicy}`);
|
|
27
|
+
lines.push(`- Knowledge chunks: ${b.knowledgeChunks}`);
|
|
28
|
+
lines.push(`- Turns: ${b.turnsProcessed} (errors: ${b.errors})`);
|
|
29
|
+
buttons.push([
|
|
30
|
+
btn(b.paused ? 'Resume bot' : 'Pause bot', 'bpause', b.id),
|
|
31
|
+
btn('Reload SOUL/KB', 'reload', b.id),
|
|
32
|
+
]);
|
|
33
|
+
buttons.push([
|
|
34
|
+
btn(`Group: mention${b.groupPolicy === 'mention' ? ' *' : ''}`, 'gpol', b.id, 'mention'),
|
|
35
|
+
btn(`Group: all${b.groupPolicy === 'all' ? ' *' : ''}`, 'gpol', b.id, 'all'),
|
|
36
|
+
btn(`Group: off${b.groupPolicy === 'off' ? ' *' : ''}`, 'gpol', b.id, 'off'),
|
|
37
|
+
]);
|
|
38
|
+
buttons.push([btn('Back', 'home')]);
|
|
39
|
+
}
|
|
40
|
+
} else if (page === 'crons') {
|
|
41
|
+
lines.push(`Admin - Cron Jobs (${status.cronCount})`);
|
|
42
|
+
const jobs = status.cronCount ? controller.listCrons({ id: null, isDm: true, isGroup: false }).jobs : [];
|
|
43
|
+
if (!jobs.length) lines.push('(no scheduled jobs)');
|
|
44
|
+
for (const j of jobs.slice(0, 8)) {
|
|
45
|
+
lines.push(`- [${j.enabled ? 'ON' : 'OFF'}] ${j.id}: ${j.name} (${j.cron || j.at || `${j.everyMs}ms`})`);
|
|
46
|
+
buttons.push([
|
|
47
|
+
btn(`${j.enabled ? 'Disable' : 'Enable'} ${j.id}`, 'ctog', j.id),
|
|
48
|
+
btn(`Run ${j.id}`, 'crun', j.id),
|
|
49
|
+
btn(`Delete ${j.id}`, 'cdel', j.id),
|
|
50
|
+
]);
|
|
51
|
+
}
|
|
52
|
+
buttons.push([btn('Back', 'home')]);
|
|
53
|
+
} else if (page === 'grants') {
|
|
54
|
+
lines.push(`Admin - Active Group Grants (${status.activeGrants.length})`);
|
|
55
|
+
if (!status.activeGrants.length) lines.push('(no active group grants)');
|
|
56
|
+
for (const g of status.activeGrants.slice(0, 8)) {
|
|
57
|
+
lines.push(`- Room ${g.roomId}: ${g.allowedTools.join(', ')} (${g.remainingMinutes}m left)`);
|
|
58
|
+
buttons.push([btn(`Revoke ${g.roomId}`, 'grev', g.roomId)]);
|
|
59
|
+
}
|
|
60
|
+
buttons.push([btn('Back', 'home')]);
|
|
61
|
+
} else if (page === 'tasks') {
|
|
62
|
+
lines.push(`Admin - Long Tasks (${status.longTasks.length})`);
|
|
63
|
+
if (!status.longTasks.length) lines.push('(no recent long tasks)');
|
|
64
|
+
for (const t of status.longTasks.slice(0, 8)) {
|
|
65
|
+
lines.push(`- [${t.status}] ${t.id}: ${t.title} (${t.step}/${t.maxSteps})`);
|
|
66
|
+
if (t.status === 'running' || t.status === 'queued') {
|
|
67
|
+
buttons.push([btn(`Cancel ${t.id}`, 'tcancel', t.id)]);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
buttons.push([btn('Back', 'home')]);
|
|
71
|
+
} else {
|
|
72
|
+
lines.push(`SCROLL Fleet Admin (uptime ${status.uptimeSec}s)`);
|
|
73
|
+
lines.push(`- Global: ${status.globalPaused ? 'PAUSED' : 'ACTIVE'}`);
|
|
74
|
+
lines.push(`- Bots: ${status.bots.length} | Crons: ${status.cronCount} | Grants: ${status.activeGrants.length}`);
|
|
75
|
+
for (const b of status.bots) {
|
|
76
|
+
lines.push(`- ${b.id}: ${b.paused ? 'paused' : 'active'} (${b.provider}/${b.model || 'auto'}) · ${b.turnsProcessed} turns`);
|
|
77
|
+
buttons.push([btn(`Manage ${b.id}`, 'bot', b.id)]);
|
|
78
|
+
}
|
|
79
|
+
buttons.push([
|
|
80
|
+
btn(status.globalPaused ? 'Resume Fleet' : 'Pause Fleet', 'gkill'),
|
|
81
|
+
btn('Memory Consolidate', 'mcons'),
|
|
82
|
+
]);
|
|
83
|
+
buttons.push([
|
|
84
|
+
btn('Grants', 'grants'),
|
|
85
|
+
btn('Tasks', 'tasks'),
|
|
86
|
+
btn('Refresh', 'home'),
|
|
87
|
+
]);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
if (notice) lines.push('', `Note: ${notice}`);
|
|
91
|
+
return { text: lines.join('\n'), buttons };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
async function handleCallback(actor, data) {
|
|
95
|
+
if (!String(data || '').startsWith(`${namespace}:`)) return null;
|
|
96
|
+
if (!controller.isOwner(actor)) {
|
|
97
|
+
return { forbidden: true, toast: 'Owner DM required.' };
|
|
98
|
+
}
|
|
99
|
+
const parts = String(data).slice(namespace.length + 1).split(':');
|
|
100
|
+
const [cmd, a1, a2] = parts;
|
|
101
|
+
try {
|
|
102
|
+
if (cmd === 'home') return { toast: 'Refreshed', view: renderView({ page: 'home' }) };
|
|
103
|
+
if (cmd === 'bot') return { toast: a1, view: renderView({ page: 'bot', botId: a1 }) };
|
|
104
|
+
if (cmd === 'grants') return { toast: 'Grants', view: renderView({ page: 'grants' }) };
|
|
105
|
+
if (cmd === 'tasks') return { toast: 'Tasks', view: renderView({ page: 'tasks' }) };
|
|
106
|
+
if (cmd === 'gkill') {
|
|
107
|
+
const r = await controller.executeAction(actor, 'global_pause');
|
|
108
|
+
return { toast: r.data.globalPaused ? 'Paused' : 'Resumed', view: renderView({ page: 'home' }) };
|
|
109
|
+
}
|
|
110
|
+
if (cmd === 'bpause') {
|
|
111
|
+
const r = await controller.executeAction(actor, 'bot_pause', { botId: a1 });
|
|
112
|
+
return { toast: r.data.paused ? 'Paused' : 'Resumed', view: renderView({ page: 'bot', botId: a1 }) };
|
|
113
|
+
}
|
|
114
|
+
if (cmd === 'gpol') {
|
|
115
|
+
await controller.executeAction(actor, 'bot_policy', { botId: a1, policy: a2 });
|
|
116
|
+
return { toast: `Policy: ${a2}`, view: renderView({ page: 'bot', botId: a1 }) };
|
|
117
|
+
}
|
|
118
|
+
if (cmd === 'reload') {
|
|
119
|
+
await controller.executeAction(actor, 'bot_reload', { botId: a1 });
|
|
120
|
+
return { toast: 'Reloaded', view: renderView({ page: 'bot', botId: a1, notice: 'Agent reloaded.' }) };
|
|
121
|
+
}
|
|
122
|
+
if (cmd === 'mcons') {
|
|
123
|
+
const r = await controller.executeAction(actor, 'memory_consolidate');
|
|
124
|
+
return { toast: `Consolidated ${r.data.totalSubjects}`, view: renderView({ page: 'home', notice: `Consolidated ${r.data.totalSubjects} subject(s).` }) };
|
|
125
|
+
}
|
|
126
|
+
if (cmd === 'grev') {
|
|
127
|
+
await controller.executeAction(actor, 'grant_revoke', { roomId: a1 });
|
|
128
|
+
return { toast: 'Revoked', view: renderView({ page: 'grants', notice: `Revoked ${a1}.` }) };
|
|
129
|
+
}
|
|
130
|
+
if (cmd === 'tcancel') {
|
|
131
|
+
await controller.executeAction(actor, 'task_cancel', { taskId: a1 });
|
|
132
|
+
return { toast: 'Cancelled', view: renderView({ page: 'tasks', notice: `Cancelled ${a1}.` }) };
|
|
133
|
+
}
|
|
134
|
+
if (cmd === 'ctog') {
|
|
135
|
+
await controller.executeAction(actor, 'cron_toggle', { jobId: a1 });
|
|
136
|
+
return { toast: 'Toggled', view: renderView({ page: 'home' }) };
|
|
137
|
+
}
|
|
138
|
+
if (cmd === 'cdel') {
|
|
139
|
+
await controller.executeAction(actor, 'cron_delete', { jobId: a1 });
|
|
140
|
+
return { toast: 'Deleted', view: renderView({ page: 'home' }) };
|
|
141
|
+
}
|
|
142
|
+
if (cmd === 'crun') {
|
|
143
|
+
await controller.executeAction(actor, 'cron_run', { jobId: a1 });
|
|
144
|
+
return { toast: 'Triggered', view: renderView({ page: 'home', notice: `Triggered ${a1}.` }) };
|
|
145
|
+
}
|
|
146
|
+
return { toast: 'Unknown command', view: renderView({ page: 'home' }) };
|
|
147
|
+
} catch (err) {
|
|
148
|
+
return { toast: String(err?.message || err).slice(0, 120), view: renderView({ page: 'home', notice: String(err?.message || err) }) };
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
return {
|
|
153
|
+
namespace,
|
|
154
|
+
renderView,
|
|
155
|
+
handleCallback,
|
|
156
|
+
};
|
|
157
|
+
}
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
// Zero-dependency Telegram Bot API client (Node >= 20 built-in fetch).
|
|
2
|
+
// Supports custom apiBaseUrl for local mock-server E2E testing or reverse proxies.
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
|
|
6
|
+
export function createTelegramApi({
|
|
7
|
+
token,
|
|
8
|
+
apiBaseUrl = 'https://api.telegram.org',
|
|
9
|
+
fetchImpl = globalThis.fetch,
|
|
10
|
+
timeoutMs = 45_000,
|
|
11
|
+
} = {}) {
|
|
12
|
+
if (!token) throw new Error('createTelegramApi: token is required');
|
|
13
|
+
const base = String(apiBaseUrl).replace(/\/+$/, '');
|
|
14
|
+
|
|
15
|
+
async function call(method, payload = null, { signal = null, timeoutMs: reqTimeout = timeoutMs } = {}) {
|
|
16
|
+
const url = `${base}/bot${token}/${method}`;
|
|
17
|
+
const ctrl = new AbortController();
|
|
18
|
+
const timer = setTimeout(() => ctrl.abort(), reqTimeout);
|
|
19
|
+
if (typeof timer.unref === 'function') timer.unref();
|
|
20
|
+
const onExternalAbort = () => ctrl.abort();
|
|
21
|
+
if (signal) {
|
|
22
|
+
if (signal.aborted) ctrl.abort();
|
|
23
|
+
else signal.addEventListener('abort', onExternalAbort, { once: true });
|
|
24
|
+
}
|
|
25
|
+
try {
|
|
26
|
+
const opts = {
|
|
27
|
+
method: payload ? 'POST' : 'GET',
|
|
28
|
+
signal: ctrl.signal,
|
|
29
|
+
};
|
|
30
|
+
if (payload) {
|
|
31
|
+
opts.headers = { 'Content-Type': 'application/json' };
|
|
32
|
+
opts.body = JSON.stringify(payload);
|
|
33
|
+
}
|
|
34
|
+
const res = await fetchImpl(url, opts);
|
|
35
|
+
const raw = await res.text();
|
|
36
|
+
let json;
|
|
37
|
+
try { json = JSON.parse(raw); } catch { json = { ok: false, description: raw.slice(0, 300) }; }
|
|
38
|
+
if (!res.ok || json.ok === false) {
|
|
39
|
+
const err = new Error(json.description || `telegram_${method}_http_${res.status}`);
|
|
40
|
+
err.status = res.status;
|
|
41
|
+
err.error_code = json.error_code || res.status;
|
|
42
|
+
err.description = json.description || '';
|
|
43
|
+
if (json.parameters?.retry_after) err.retryAfterMs = Number(json.parameters.retry_after) * 1000;
|
|
44
|
+
throw err;
|
|
45
|
+
}
|
|
46
|
+
return json.result;
|
|
47
|
+
} finally {
|
|
48
|
+
clearTimeout(timer);
|
|
49
|
+
if (signal) signal.removeEventListener('abort', onExternalAbort);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function toInlineKeyboard(buttons) {
|
|
54
|
+
if (!Array.isArray(buttons) || !buttons.length) return undefined;
|
|
55
|
+
return { inline_keyboard: buttons };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
return {
|
|
59
|
+
call,
|
|
60
|
+
getMe: (opts) => call('getMe', null, opts),
|
|
61
|
+
getUpdates: ({ offset, timeout = 25, limit = 50, allowedUpdates = ['message', 'edited_message', 'callback_query'] } = {}, opts) =>
|
|
62
|
+
call('getUpdates', {
|
|
63
|
+
...(offset != null ? { offset } : {}),
|
|
64
|
+
timeout,
|
|
65
|
+
limit,
|
|
66
|
+
allowed_updates: allowedUpdates,
|
|
67
|
+
}, { timeoutMs: Math.max(timeoutMs, (timeout + 15) * 1000), ...(opts || {}) }),
|
|
68
|
+
sendMessage: ({ chatId, text, replyToMessageId = null, buttons = null, parseMode = null, disableNotification = false } = {}) =>
|
|
69
|
+
call('sendMessage', {
|
|
70
|
+
chat_id: chatId,
|
|
71
|
+
text: String(text || ''),
|
|
72
|
+
...(replyToMessageId ? { reply_parameters: { message_id: Number(replyToMessageId), allow_sending_without_reply: true } } : {}),
|
|
73
|
+
...(buttons ? { reply_markup: toInlineKeyboard(buttons) } : {}),
|
|
74
|
+
...(parseMode ? { parse_mode: parseMode } : {}),
|
|
75
|
+
...(disableNotification ? { disable_notification: true } : {}),
|
|
76
|
+
}),
|
|
77
|
+
editMessageText: async ({ chatId, messageId, text, buttons = null, parseMode = null } = {}) => {
|
|
78
|
+
try {
|
|
79
|
+
return await call('editMessageText', {
|
|
80
|
+
chat_id: chatId,
|
|
81
|
+
message_id: Number(messageId),
|
|
82
|
+
text: String(text || ''),
|
|
83
|
+
...(buttons ? { reply_markup: toInlineKeyboard(buttons) } : {}),
|
|
84
|
+
...(parseMode ? { parse_mode: parseMode } : {}),
|
|
85
|
+
});
|
|
86
|
+
} catch (err) {
|
|
87
|
+
if (err?.error_code === 400 && String(err.description || '').includes('message is not modified')) {
|
|
88
|
+
return { unchanged: true };
|
|
89
|
+
}
|
|
90
|
+
throw err;
|
|
91
|
+
}
|
|
92
|
+
},
|
|
93
|
+
sendChatAction: ({ chatId, action = 'typing' } = {}) =>
|
|
94
|
+
call('sendChatAction', { chat_id: chatId, action }).catch(() => null),
|
|
95
|
+
setMessageReaction: ({ chatId, messageId, emoji, isBig = false } = {}) =>
|
|
96
|
+
call('setMessageReaction', {
|
|
97
|
+
chat_id: chatId,
|
|
98
|
+
message_id: Number(messageId),
|
|
99
|
+
reaction: emoji ? [{ type: 'emoji', emoji }] : [],
|
|
100
|
+
is_big: Boolean(isBig),
|
|
101
|
+
}).catch(() => null),
|
|
102
|
+
answerCallbackQuery: ({ callbackQueryId, text = null, showAlert = false } = {}) =>
|
|
103
|
+
call('answerCallbackQuery', {
|
|
104
|
+
callback_query_id: String(callbackQueryId),
|
|
105
|
+
...(text ? { text: String(text).slice(0, 180) } : {}),
|
|
106
|
+
show_alert: Boolean(showAlert),
|
|
107
|
+
}).catch(() => null),
|
|
108
|
+
getFile: (fileId) => call('getFile', { file_id: String(fileId) }),
|
|
109
|
+
async downloadFile(filePath) {
|
|
110
|
+
const url = `${base}/file/bot${token}/${String(filePath).replace(/^\/+/, '')}`;
|
|
111
|
+
const res = await fetchImpl(url);
|
|
112
|
+
if (!res.ok) throw new Error(`telegram_download_failed:${res.status}`);
|
|
113
|
+
return Buffer.from(await res.arrayBuffer());
|
|
114
|
+
},
|
|
115
|
+
sendPhoto: ({ chatId, photo, caption = null, replyToMessageId = null } = {}) =>
|
|
116
|
+
call('sendPhoto', {
|
|
117
|
+
chat_id: chatId,
|
|
118
|
+
photo,
|
|
119
|
+
...(caption ? { caption } : {}),
|
|
120
|
+
...(replyToMessageId ? { reply_parameters: { message_id: Number(replyToMessageId), allow_sending_without_reply: true } } : {}),
|
|
121
|
+
}),
|
|
122
|
+
sendDocument: ({ chatId, document, caption = null, replyToMessageId = null } = {}) =>
|
|
123
|
+
call('sendDocument', {
|
|
124
|
+
chat_id: chatId,
|
|
125
|
+
document,
|
|
126
|
+
...(caption ? { caption } : {}),
|
|
127
|
+
...(replyToMessageId ? { reply_parameters: { message_id: Number(replyToMessageId), allow_sending_without_reply: true } } : {}),
|
|
128
|
+
}),
|
|
129
|
+
async sendLocalFile({ chatId, filePath, kind = 'document', caption = null, replyToMessageId = null, allowedRoots = null } = {}) {
|
|
130
|
+
const abs = path.resolve(String(filePath || ''));
|
|
131
|
+
if (!fs.existsSync(abs)) throw new Error(`local_file_not_found:${abs}`);
|
|
132
|
+
const real = fs.realpathSync.native ? fs.realpathSync.native(abs) : fs.realpathSync(abs);
|
|
133
|
+
// Fail-closed: if caller supplies an allowedRoots array (even empty `[]`!), require explicit containment!
|
|
134
|
+
if (Array.isArray(allowedRoots)) {
|
|
135
|
+
const permitted = allowedRoots.length > 0 && allowedRoots.some((root) => {
|
|
136
|
+
if (!root) return false;
|
|
137
|
+
const rr = fs.existsSync(root)
|
|
138
|
+
? (fs.realpathSync.native ? fs.realpathSync.native(root) : fs.realpathSync(root))
|
|
139
|
+
: path.resolve(root);
|
|
140
|
+
return real === rr || real.startsWith(rr + path.sep);
|
|
141
|
+
});
|
|
142
|
+
if (!permitted) throw new Error(`local_file_outside_allowed_roots:${path.basename(abs)}`);
|
|
143
|
+
}
|
|
144
|
+
// Block symlink swap via O_NOFOLLOW + post-open dev/ino verification against realpath
|
|
145
|
+
const fd = fs.openSync(real, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));
|
|
146
|
+
let buf;
|
|
147
|
+
try {
|
|
148
|
+
const st = fs.fstatSync(fd);
|
|
149
|
+
if (!st.isFile()) throw new Error(`local_path_not_a_file:${path.basename(real)}`);
|
|
150
|
+
const postReal = fs.realpathSync.native ? fs.realpathSync.native(abs) : fs.realpathSync(abs);
|
|
151
|
+
const postSt = fs.statSync(postReal);
|
|
152
|
+
if (postReal !== real || postSt.dev !== st.dev || postSt.ino !== st.ino) {
|
|
153
|
+
throw new Error(`local_file_symlink_race:${path.basename(abs)}`);
|
|
154
|
+
}
|
|
155
|
+
buf = fs.readFileSync(fd);
|
|
156
|
+
} finally {
|
|
157
|
+
fs.closeSync(fd);
|
|
158
|
+
}
|
|
159
|
+
const isPhoto = kind === 'photo' || /\.(?:png|jpe?g|webp|gif)$/i.test(real);
|
|
160
|
+
const method = isPhoto ? 'sendPhoto' : 'sendDocument';
|
|
161
|
+
const field = isPhoto ? 'photo' : 'document';
|
|
162
|
+
const form = new FormData();
|
|
163
|
+
form.append('chat_id', String(chatId));
|
|
164
|
+
form.append(field, new Blob([buf]), path.basename(real));
|
|
165
|
+
if (caption) form.append('caption', String(caption).slice(0, 1024));
|
|
166
|
+
if (replyToMessageId) {
|
|
167
|
+
form.append('reply_parameters', JSON.stringify({ message_id: Number(replyToMessageId), allow_sending_without_reply: true }));
|
|
168
|
+
}
|
|
169
|
+
const res = await fetchImpl(`${base}/bot${token}/${method}`, { method: 'POST', body: form });
|
|
170
|
+
const raw = await res.text();
|
|
171
|
+
let json;
|
|
172
|
+
try { json = JSON.parse(raw); } catch { json = { ok: false, description: raw.slice(0, 300) }; }
|
|
173
|
+
if (!res.ok || json.ok === false) {
|
|
174
|
+
throw new Error(json.description || `telegram_${method}_http_${res.status}`);
|
|
175
|
+
}
|
|
176
|
+
return json.result;
|
|
177
|
+
},
|
|
178
|
+
setMyCommands: (commands) => call('setMyCommands', { commands }),
|
|
179
|
+
};
|
|
180
|
+
}
|
|
@@ -0,0 +1,643 @@
|
|
|
1
|
+
// SCROLL 2.5 -- Standalone Multi-Bot Telegram Fleet Daemon (`@agentpro/scroll-telegram`).
|
|
2
|
+
// Consumes ONLY `@agentpro/scroll` and `@agentpro/scroll/chat` (zero parent relative imports).
|
|
3
|
+
// Private extensions (e.g., custom tools, Voice hooks, custom slash commands) load cleanly
|
|
4
|
+
// through the `plugins: [...]` contract.
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import crypto from 'node:crypto';
|
|
8
|
+
import { pathToFileURL } from 'node:url';
|
|
9
|
+
import {
|
|
10
|
+
createAuthStore,
|
|
11
|
+
createWorkerPool,
|
|
12
|
+
createScheduler,
|
|
13
|
+
createCodexAppServerClient,
|
|
14
|
+
pickProvider,
|
|
15
|
+
} from '@agentpro/scroll';
|
|
16
|
+
import {
|
|
17
|
+
createScrollChatRuntime,
|
|
18
|
+
createMessageDebouncer,
|
|
19
|
+
createGroupGrantStore,
|
|
20
|
+
matchesOwnerDelegationPhrase,
|
|
21
|
+
createLongTaskRunner,
|
|
22
|
+
createAdminController,
|
|
23
|
+
ADMIN_CALLBACK_NAMESPACE,
|
|
24
|
+
} from '@agentpro/scroll/chat';
|
|
25
|
+
import { createTelegramApi } from './telegram-api.js';
|
|
26
|
+
import { createTelegramAdminUi } from './telegram-admin-ui.js';
|
|
27
|
+
|
|
28
|
+
const HITL_NAMESPACE = 'scroll-hitl';
|
|
29
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, Math.max(0, ms)));
|
|
30
|
+
|
|
31
|
+
function loadDotEnvFile(envFile) {
|
|
32
|
+
if (!envFile || !fs.existsSync(envFile)) return 0;
|
|
33
|
+
let loaded = 0;
|
|
34
|
+
const raw = fs.readFileSync(envFile, 'utf8');
|
|
35
|
+
for (const line of raw.split('\n')) {
|
|
36
|
+
const trimmed = line.trim();
|
|
37
|
+
if (!trimmed || trimmed.startsWith('#')) continue;
|
|
38
|
+
const eq = trimmed.indexOf('=');
|
|
39
|
+
if (eq <= 0) continue;
|
|
40
|
+
const key = trimmed.slice(0, eq).trim();
|
|
41
|
+
let val = trimmed.slice(eq + 1).trim();
|
|
42
|
+
if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
|
|
43
|
+
val = val.slice(1, -1);
|
|
44
|
+
}
|
|
45
|
+
if (key && process.env[key] === undefined) {
|
|
46
|
+
process.env[key] = val;
|
|
47
|
+
loaded++;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return loaded;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function readOffset(file) {
|
|
54
|
+
try {
|
|
55
|
+
if (!fs.existsSync(file)) return null;
|
|
56
|
+
const j = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
57
|
+
return Number.isSafeInteger(j.offset) ? j.offset : null;
|
|
58
|
+
} catch {
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function writeOffset(file, offset) {
|
|
64
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
65
|
+
const tmp = `${file}.tmp.${process.pid}`;
|
|
66
|
+
fs.writeFileSync(tmp, JSON.stringify({ offset, updatedAt: new Date().toISOString() }) + '\n', { mode: 0o600 });
|
|
67
|
+
fs.renameSync(tmp, file);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function senderDisplayName(from) {
|
|
71
|
+
if (!from) return 'Member';
|
|
72
|
+
const full = [from.first_name, from.last_name].filter(Boolean).join(' ').trim();
|
|
73
|
+
return full || (from.username ? `@${from.username}` : `User ${from.id}`);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function matchesTrigger({ bot, msg, text }) {
|
|
77
|
+
const isGroup = msg.chat && (msg.chat.type === 'group' || msg.chat.type === 'supergroup');
|
|
78
|
+
if (!isGroup) return { trigger: true, reason: 'dm' };
|
|
79
|
+
const slashMatch = /^\/([a-z0-9_]+)(?:@([A-Za-z0-9_]+))?\b/i.exec(String(text || '').trim());
|
|
80
|
+
if (slashMatch) {
|
|
81
|
+
const targetBot = slashMatch[2];
|
|
82
|
+
if (!targetBot || (bot.username && targetBot.toLowerCase() === bot.username.toLowerCase())) {
|
|
83
|
+
return { trigger: true, reason: 'slash_command' };
|
|
84
|
+
}
|
|
85
|
+
return { trigger: false, reason: 'other_bot_command' };
|
|
86
|
+
}
|
|
87
|
+
const policy = bot.groupPolicy || 'mention';
|
|
88
|
+
if (policy === 'off') return { trigger: false, reason: 'group_off' };
|
|
89
|
+
if (policy === 'all') return { trigger: true, reason: 'group_all' };
|
|
90
|
+
if (msg.reply_to_message?.from && bot.botUserId && String(msg.reply_to_message.from.id) === String(bot.botUserId)) {
|
|
91
|
+
return { trigger: true, reason: 'reply_to_bot' };
|
|
92
|
+
}
|
|
93
|
+
const lowered = String(text || '').toLowerCase();
|
|
94
|
+
if (bot.username && lowered.includes(`@${bot.username.toLowerCase()}`)) {
|
|
95
|
+
return { trigger: true, reason: 'at_mention' };
|
|
96
|
+
}
|
|
97
|
+
for (const pat of bot.mentionRegexes || []) {
|
|
98
|
+
if (pat.test(text || '')) return { trigger: true, reason: 'pattern_mention' };
|
|
99
|
+
}
|
|
100
|
+
return { trigger: false, reason: 'no_mention' };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async function resolvePlugins(pluginSpecs = [], baseDir = process.cwd()) {
|
|
104
|
+
const resolved = [];
|
|
105
|
+
for (const spec of pluginSpecs || []) {
|
|
106
|
+
if (typeof spec === 'function') {
|
|
107
|
+
resolved.push(spec);
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
if (spec && typeof spec === 'object' && typeof spec.setup === 'function') {
|
|
111
|
+
resolved.push(spec.setup);
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
if (typeof spec === 'string' && spec.trim()) {
|
|
115
|
+
const target = spec.startsWith('file://')
|
|
116
|
+
? spec
|
|
117
|
+
: (spec.startsWith('.') || path.isAbsolute(spec) ? pathToFileURL(path.resolve(baseDir, spec)).href : spec);
|
|
118
|
+
const mod = await import(target);
|
|
119
|
+
const fn = mod.default || mod.setup || mod.registerPlugin;
|
|
120
|
+
if (typeof fn === 'function') resolved.push(fn);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return resolved;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export async function createTelegramFleetDaemon(config = {}, {
|
|
127
|
+
logger = console,
|
|
128
|
+
fetchImpl = globalThis.fetch,
|
|
129
|
+
providerFactory = null,
|
|
130
|
+
plugins = [],
|
|
131
|
+
} = {}) {
|
|
132
|
+
if (config.envFile) loadDotEnvFile(path.resolve(config.envFile));
|
|
133
|
+
const stateDir = path.resolve(config.stateDir || path.join(process.cwd(), '.scroll-telegram'));
|
|
134
|
+
fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 });
|
|
135
|
+
|
|
136
|
+
const ownerIds = (config.ownerIds || []).map(String);
|
|
137
|
+
const authStore = createAuthStore({ filePath: path.join(stateDir, 'auth.json') });
|
|
138
|
+
const workerPool = createWorkerPool({ maxConcurrent: Number(config.maxWorkers || 3) });
|
|
139
|
+
|
|
140
|
+
let sharedCodexClient = null;
|
|
141
|
+
const needsCodex = (config.bots || []).some((b) => (b.provider || 'codex-app-server') === 'codex-app-server');
|
|
142
|
+
if (needsCodex && !providerFactory) {
|
|
143
|
+
const codexCfg = config.codexAppServer || {};
|
|
144
|
+
sharedCodexClient = createCodexAppServerClient({
|
|
145
|
+
command: codexCfg.command || null,
|
|
146
|
+
args: codexCfg.args || null,
|
|
147
|
+
searchPaths: codexCfg.searchPaths || [],
|
|
148
|
+
defaultModel: codexCfg.defaultModel || null,
|
|
149
|
+
timeoutMs: Number(codexCfg.timeoutMs || 120_000),
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const bots = new Map();
|
|
154
|
+
const pendingHitl = new Map();
|
|
155
|
+
const startedAt = Date.now();
|
|
156
|
+
let stopped = false;
|
|
157
|
+
|
|
158
|
+
const scheduler = createScheduler({
|
|
159
|
+
filePath: path.join(stateDir, 'cron.json'),
|
|
160
|
+
defaultTz: config.defaultTz || 'UTC',
|
|
161
|
+
tickIntervalMs: Number(config.cronTickIntervalMs || 15_000),
|
|
162
|
+
onTrigger: async (job) => deliverScheduledJob(job),
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
const groupGrants = createGroupGrantStore({
|
|
166
|
+
filePath: path.join(stateDir, 'group-grants.json'),
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
const longTasks = createLongTaskRunner({
|
|
170
|
+
stateDir,
|
|
171
|
+
workerPool,
|
|
172
|
+
channel: 'telegram',
|
|
173
|
+
onProgress: async (task, stepSummary) => {
|
|
174
|
+
const bot = bots.get(task.botId);
|
|
175
|
+
if (!bot || task.isGroup) return;
|
|
176
|
+
await bot.api.sendMessage({
|
|
177
|
+
chatId: task.chatId,
|
|
178
|
+
text: `[${task.title} - Step ${task.step}/${task.maxSteps}]\n${stepSummary.slice(0, 420)}`,
|
|
179
|
+
}).catch(() => {});
|
|
180
|
+
},
|
|
181
|
+
onComplete: async (task) => {
|
|
182
|
+
const bot = bots.get(task.botId);
|
|
183
|
+
if (!bot) return;
|
|
184
|
+
const ownerDm = bot.ownerIds?.[0] || ownerIds?.[0] || null;
|
|
185
|
+
if (task.status === 'failed' || task.status === 'blocked') {
|
|
186
|
+
const target = task.isGroup && ownerDm ? ownerDm : task.chatId;
|
|
187
|
+
await bot.api.sendMessage({
|
|
188
|
+
chatId: target,
|
|
189
|
+
text: `[Long Task ${task.status}: ${task.title}]\nStep ${task.step}/${task.maxSteps}: ${String(task.error || 'stopped').slice(0, 900)}`,
|
|
190
|
+
}).catch(() => {});
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
const body = task.finalReport || `Completed "${task.title}" after ${task.step} step(s).`;
|
|
194
|
+
await bot.api.sendMessage({ chatId: task.chatId, text: body.slice(0, 4000) }).catch(() => {});
|
|
195
|
+
},
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
const adminController = createAdminController({
|
|
199
|
+
bots,
|
|
200
|
+
authStore,
|
|
201
|
+
scheduler,
|
|
202
|
+
groupGrants,
|
|
203
|
+
longTasks,
|
|
204
|
+
runCronNowFn: async (jobId) => {
|
|
205
|
+
const job = scheduler.getJob(jobId);
|
|
206
|
+
if (!job) return { ok: false, reason: 'job_not_found' };
|
|
207
|
+
await deliverScheduledJob(job);
|
|
208
|
+
return { ok: true, jobId };
|
|
209
|
+
},
|
|
210
|
+
ownerIds,
|
|
211
|
+
startedAt,
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
const adminUi = createTelegramAdminUi({ controller: adminController });
|
|
215
|
+
const loadedPlugins = await resolvePlugins([...(config.plugins || []), ...(plugins || [])], config.baseDir || process.cwd());
|
|
216
|
+
const pluginHooks = [];
|
|
217
|
+
|
|
218
|
+
async function requestHitlApproval(bot, req) {
|
|
219
|
+
const ownerChatId = bot.ownerIds?.[0] || ownerIds[0];
|
|
220
|
+
if (!ownerChatId) return { approved: false, reason: 'no_owner_chat_configured' };
|
|
221
|
+
const tokenId = crypto.randomBytes(6).toString('hex');
|
|
222
|
+
const preview = JSON.stringify(req.args || {}).slice(0, 220);
|
|
223
|
+
await bot.api.sendMessage({
|
|
224
|
+
chatId: ownerChatId,
|
|
225
|
+
text: `Approval required (${bot.id})\n- Tool: ${req.tool} (${req.tier})\n- Args: ${preview}`,
|
|
226
|
+
buttons: [[
|
|
227
|
+
{ text: 'Approve', callback_data: `${HITL_NAMESPACE}:ok:${tokenId}` },
|
|
228
|
+
{ text: 'Deny', callback_data: `${HITL_NAMESPACE}:no:${tokenId}` },
|
|
229
|
+
]],
|
|
230
|
+
});
|
|
231
|
+
return new Promise((resolve) => {
|
|
232
|
+
const timer = setTimeout(() => {
|
|
233
|
+
pendingHitl.delete(tokenId);
|
|
234
|
+
resolve({ approved: false, reason: 'approval_timeout' });
|
|
235
|
+
}, Number(config.hitlTimeoutMs || 120_000));
|
|
236
|
+
if (typeof timer.unref === 'function') timer.unref();
|
|
237
|
+
pendingHitl.set(tokenId, {
|
|
238
|
+
resolve: (approved, approver) => {
|
|
239
|
+
clearTimeout(timer);
|
|
240
|
+
pendingHitl.delete(tokenId);
|
|
241
|
+
resolve({ approved, approver });
|
|
242
|
+
},
|
|
243
|
+
ownerIds: new Set(bot.ownerIds?.length ? bot.ownerIds : ownerIds),
|
|
244
|
+
});
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
async function deliverScheduledJob(job) {
|
|
249
|
+
const bot = bots.get(job.agentName) || [...bots.values()][0];
|
|
250
|
+
if (!bot || bot.paused || adminController.globalPaused) return { skipped: true };
|
|
251
|
+
const targetChatId = job.targetChatId || bot.ownerIds?.[0] || ownerIds[0];
|
|
252
|
+
if (!targetChatId) return { skipped: true, reason: 'no_target_chat' };
|
|
253
|
+
const turn = await bot.runtime.sendTurn({
|
|
254
|
+
conversationId: String(targetChatId),
|
|
255
|
+
text: job.prompt || job.name,
|
|
256
|
+
channel: 'telegram',
|
|
257
|
+
model: bot.model,
|
|
258
|
+
effort: bot.effort,
|
|
259
|
+
});
|
|
260
|
+
const bubbles = Array.isArray(turn.bubbles) && turn.bubbles.length ? turn.bubbles : [turn.text];
|
|
261
|
+
for (const b of bubbles.filter(Boolean)) {
|
|
262
|
+
await bot.api.sendMessage({ chatId: targetChatId, text: b });
|
|
263
|
+
}
|
|
264
|
+
return { ok: true, bubbles: bubbles.length };
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
async function extractAttachments(bot, msg) {
|
|
268
|
+
const out = [];
|
|
269
|
+
if (Array.isArray(msg.photo) && msg.photo.length) {
|
|
270
|
+
const largest = msg.photo[msg.photo.length - 1];
|
|
271
|
+
try {
|
|
272
|
+
const info = await bot.api.getFile(largest.file_id);
|
|
273
|
+
if (info?.file_path) {
|
|
274
|
+
const buf = await bot.api.downloadFile(info.file_path);
|
|
275
|
+
out.push({
|
|
276
|
+
type: 'image',
|
|
277
|
+
base64: buf.toString('base64'),
|
|
278
|
+
mimeType: 'image/jpeg',
|
|
279
|
+
caption: msg.caption || null,
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
} catch (err) {
|
|
283
|
+
logger.warn?.(`[scroll-telegram:${bot.id}] photo download failed:`, err?.message || err);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
if (msg.voice?.file_id) {
|
|
287
|
+
out.push({ type: 'voice', fileId: msg.voice.file_id, mimeType: msg.voice.mime_type || 'audio/ogg' });
|
|
288
|
+
}
|
|
289
|
+
if (msg.document?.file_id) {
|
|
290
|
+
out.push({ type: 'document', fileId: msg.document.file_id, name: msg.document.file_name || 'file', mimeType: msg.document.mime_type || null });
|
|
291
|
+
}
|
|
292
|
+
return out;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
async function handleIncomingMessage(bot, msg) {
|
|
296
|
+
if (!msg || !msg.chat) return;
|
|
297
|
+
if (msg.from?.is_bot) return;
|
|
298
|
+
const chatId = String(msg.chat.id);
|
|
299
|
+
const isGroup = msg.chat.type === 'group' || msg.chat.type === 'supergroup';
|
|
300
|
+
const senderId = msg.from ? String(msg.from.id) : null;
|
|
301
|
+
const senderName = senderDisplayName(msg.from);
|
|
302
|
+
const rawText = String(msg.text || msg.caption || '').trim();
|
|
303
|
+
const attachments = await extractAttachments(bot, msg);
|
|
304
|
+
if (!rawText && !attachments.length) return;
|
|
305
|
+
|
|
306
|
+
// Allow plugins to observe every message (e.g. rolling group buffer)
|
|
307
|
+
for (const h of pluginHooks) {
|
|
308
|
+
if (typeof h.onRawMessage === 'function') {
|
|
309
|
+
try { await h.onRawMessage({ bot, msg, chatId, isGroup, senderId, senderName, text: rawText }); } catch { /* isolate */ }
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
const trig = matchesTrigger({ bot, msg, text: rawText });
|
|
314
|
+
if (!trig.trigger) return;
|
|
315
|
+
|
|
316
|
+
const actor = { id: senderId, senderId, isDm: !isGroup, isGroup };
|
|
317
|
+
|
|
318
|
+
// Built-in slash commands
|
|
319
|
+
if (/^\/admin(?:@[A-Za-z0-9_]+)?\b/i.test(rawText)) {
|
|
320
|
+
if (!adminController.isOwner(actor)) {
|
|
321
|
+
await bot.api.sendMessage({ chatId, text: 'Admin console is available to the verified owner in DM only.', replyToMessageId: msg.message_id });
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
const view = adminUi.renderView({ page: 'home' });
|
|
325
|
+
await bot.api.sendMessage({ chatId, text: view.text, buttons: view.buttons });
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
if (/^\/clear(?:@[A-Za-z0-9_]+)?\b/i.test(rawText)) {
|
|
329
|
+
await bot.runtime.clearSession(chatId);
|
|
330
|
+
await bot.api.sendMessage({ chatId, text: 'Session history cleared.', replyToMessageId: msg.message_id });
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
333
|
+
if (/^\/grant(?:@[A-Za-z0-9_]+)?\b/i.test(rawText) && isGroup) {
|
|
334
|
+
if (!senderId || !bot.ownerSet.has(senderId)) {
|
|
335
|
+
await bot.api.sendMessage({ chatId, text: 'Only the verified owner may grant group tool permissions.', replyToMessageId: msg.message_id });
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
const minsMatch = rawText.match(/\b(\d{1,3})\b/);
|
|
339
|
+
const g = groupGrants.grant({ roomId: chatId, isGroup: true, grantedBy: senderId, ttlMinutes: minsMatch ? Number(minsMatch[1]) : 60 });
|
|
340
|
+
await bot.api.sendMessage({ chatId, text: `Granted group tools (${g.allowedTools.join(', ')}) for ${g.ttlMinutes} min.`, replyToMessageId: msg.message_id });
|
|
341
|
+
return;
|
|
342
|
+
}
|
|
343
|
+
if (/^\/revoke(?:@[A-Za-z0-9_]+)?\b/i.test(rawText) && isGroup) {
|
|
344
|
+
if (!senderId || !bot.ownerSet.has(senderId)) return;
|
|
345
|
+
groupGrants.revoke(chatId);
|
|
346
|
+
await bot.api.sendMessage({ chatId, text: 'Revoked group tool grant.', replyToMessageId: msg.message_id });
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// Plugin slash commands
|
|
351
|
+
for (const h of pluginHooks) {
|
|
352
|
+
if (typeof h.onCommand === 'function') {
|
|
353
|
+
const handled = await h.onCommand({ bot, msg, chatId, isGroup, senderId, senderName, text: rawText, actor });
|
|
354
|
+
if (handled) return;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
if (bot.paused || adminController.globalPaused) return;
|
|
359
|
+
|
|
360
|
+
// Owner natural-language delegation in groups
|
|
361
|
+
if (isGroup && senderId && bot.ownerSet.has(senderId) && matchesOwnerDelegationPhrase(rawText, bot.delegationPatterns)) {
|
|
362
|
+
groupGrants.grant({ roomId: chatId, isGroup: true, grantedBy: senderId, ttlMinutes: 60, note: rawText.slice(0, 120) });
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
const burstKey = `${bot.id}:${chatId}:${senderId || 'anon'}`;
|
|
366
|
+
await bot.debouncer.push(burstKey, {
|
|
367
|
+
chatId,
|
|
368
|
+
isGroup,
|
|
369
|
+
chatTitle: msg.chat.title || null,
|
|
370
|
+
sender: { id: senderId, channelId: senderId ? `tg:${senderId}` : null, name: senderName },
|
|
371
|
+
text: rawText,
|
|
372
|
+
attachments,
|
|
373
|
+
messageId: msg.message_id,
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
async function processBurst(bot, item) {
|
|
378
|
+
if (bot.paused || adminController.globalPaused) return;
|
|
379
|
+
const { chatId, isGroup, chatTitle, sender, text, attachments, messageId, messageIds } = item;
|
|
380
|
+
await bot.api.sendChatAction({ chatId, action: 'typing' });
|
|
381
|
+
const activeGrant = isGroup ? groupGrants.getActiveGrant(chatId) : null;
|
|
382
|
+
try {
|
|
383
|
+
const turn = await bot.runtime.sendTurn({
|
|
384
|
+
conversationId: chatId,
|
|
385
|
+
text,
|
|
386
|
+
sender,
|
|
387
|
+
isGroup,
|
|
388
|
+
channel: 'telegram',
|
|
389
|
+
chatTitle,
|
|
390
|
+
messageId,
|
|
391
|
+
messageIds,
|
|
392
|
+
attachments,
|
|
393
|
+
model: bot.model,
|
|
394
|
+
effort: bot.effort,
|
|
395
|
+
delegatedTools: activeGrant ? activeGrant.allowedTools : null,
|
|
396
|
+
});
|
|
397
|
+
bot.stats.turns++;
|
|
398
|
+
if (turn.streamHeld) {
|
|
399
|
+
logger.warn?.(`[scroll-telegram:${bot.id}] grounding held unverified reply for chat ${chatId}`);
|
|
400
|
+
}
|
|
401
|
+
const bubbles = Array.isArray(turn.bubbles) && turn.bubbles.length ? turn.bubbles : [turn.text];
|
|
402
|
+
for (let i = 0; i < bubbles.length; i++) {
|
|
403
|
+
const chunk = String(bubbles[i] || '').trim();
|
|
404
|
+
if (!chunk) continue;
|
|
405
|
+
if (i > 0) await sleep(Math.round(350 * bot.delayScale));
|
|
406
|
+
await bot.api.sendMessage({
|
|
407
|
+
chatId,
|
|
408
|
+
text: chunk.slice(0, 4096),
|
|
409
|
+
replyToMessageId: i === 0 && isGroup ? messageId : null,
|
|
410
|
+
});
|
|
411
|
+
}
|
|
412
|
+
} catch (err) {
|
|
413
|
+
bot.stats.errors++;
|
|
414
|
+
logger.error?.(`[scroll-telegram:${bot.id}] turn error:`, err?.message || err);
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
async function handleCallbackQuery(bot, cq) {
|
|
419
|
+
if (!cq) return;
|
|
420
|
+
const data = String(cq.data || '');
|
|
421
|
+
const fromId = cq.from ? String(cq.from.id) : null;
|
|
422
|
+
const chatId = cq.message?.chat ? String(cq.message.chat.id) : null;
|
|
423
|
+
const isGroup = cq.message?.chat && (cq.message.chat.type === 'group' || cq.message.chat.type === 'supergroup');
|
|
424
|
+
const actor = { id: fromId, senderId: fromId, isDm: !isGroup, isGroup: Boolean(isGroup) };
|
|
425
|
+
|
|
426
|
+
if (data.startsWith(`${HITL_NAMESPACE}:`)) {
|
|
427
|
+
const [, decision, tokenId] = data.split(':');
|
|
428
|
+
const entry = pendingHitl.get(tokenId);
|
|
429
|
+
if (!entry) {
|
|
430
|
+
await bot.api.answerCallbackQuery({ callbackQueryId: cq.id, text: 'Approval request expired.' });
|
|
431
|
+
return;
|
|
432
|
+
}
|
|
433
|
+
if (!fromId || !entry.ownerIds.has(fromId) || isGroup) {
|
|
434
|
+
await bot.api.answerCallbackQuery({ callbackQueryId: cq.id, text: 'Owner DM required.', showAlert: true });
|
|
435
|
+
return;
|
|
436
|
+
}
|
|
437
|
+
const approved = decision === 'ok';
|
|
438
|
+
entry.resolve(approved, `tg:${fromId}`);
|
|
439
|
+
await bot.api.answerCallbackQuery({ callbackQueryId: cq.id, text: approved ? 'Approved' : 'Denied' });
|
|
440
|
+
if (chatId && cq.message?.message_id) {
|
|
441
|
+
await bot.api.editMessageText({
|
|
442
|
+
chatId,
|
|
443
|
+
messageId: cq.message.message_id,
|
|
444
|
+
text: `${cq.message.text || 'Approval'}\n\nDecision: ${approved ? 'APPROVED' : 'DENIED'}`,
|
|
445
|
+
}).catch(() => {});
|
|
446
|
+
}
|
|
447
|
+
return;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
if (data.startsWith(`${ADMIN_CALLBACK_NAMESPACE}:`)) {
|
|
451
|
+
const res = await adminUi.handleCallback(actor, data);
|
|
452
|
+
if (res?.forbidden) {
|
|
453
|
+
await bot.api.answerCallbackQuery({ callbackQueryId: cq.id, text: res.toast, showAlert: true });
|
|
454
|
+
return;
|
|
455
|
+
}
|
|
456
|
+
await bot.api.answerCallbackQuery({ callbackQueryId: cq.id, text: res?.toast || 'OK' });
|
|
457
|
+
if (res?.view && chatId && cq.message?.message_id) {
|
|
458
|
+
await bot.api.editMessageText({
|
|
459
|
+
chatId,
|
|
460
|
+
messageId: cq.message.message_id,
|
|
461
|
+
text: res.view.text,
|
|
462
|
+
buttons: res.view.buttons,
|
|
463
|
+
}).catch(() => {});
|
|
464
|
+
}
|
|
465
|
+
return;
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
for (const h of pluginHooks) {
|
|
469
|
+
if (typeof h.onCallbackQuery === 'function') {
|
|
470
|
+
const handled = await h.onCallbackQuery({ bot, cq, data, actor, chatId, isGroup });
|
|
471
|
+
if (handled) return;
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
// Initialize bots
|
|
477
|
+
for (const bCfg of config.bots || []) {
|
|
478
|
+
if (bCfg.enabled === false) continue;
|
|
479
|
+
const token = bCfg.token || (bCfg.tokenEnv ? process.env[bCfg.tokenEnv] : null);
|
|
480
|
+
if (!token) throw new Error(`Bot "${bCfg.id}" missing token / tokenEnv`);
|
|
481
|
+
const botOwnerIds = (bCfg.ownerIds || ownerIds).map(String);
|
|
482
|
+
const api = createTelegramApi({ token, apiBaseUrl: bCfg.apiBaseUrl || config.apiBaseUrl || 'https://api.telegram.org', fetchImpl });
|
|
483
|
+
|
|
484
|
+
let provider;
|
|
485
|
+
if (typeof providerFactory === 'function') {
|
|
486
|
+
provider = await providerFactory(bCfg);
|
|
487
|
+
} else if ((bCfg.provider || 'codex-app-server') === 'codex-app-server' && sharedCodexClient) {
|
|
488
|
+
provider = pickProvider('codex-app-server', {
|
|
489
|
+
model: bCfg.model || null,
|
|
490
|
+
effort: bCfg.effort || null,
|
|
491
|
+
client: sharedCodexClient,
|
|
492
|
+
});
|
|
493
|
+
} else {
|
|
494
|
+
provider = pickProvider(bCfg.provider || 'auto', {
|
|
495
|
+
model: bCfg.model || null,
|
|
496
|
+
authStore,
|
|
497
|
+
cwd: path.resolve(bCfg.deploymentDir || process.cwd()),
|
|
498
|
+
});
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
const botObj = {
|
|
502
|
+
id: bCfg.id,
|
|
503
|
+
agentName: bCfg.agentName || bCfg.id,
|
|
504
|
+
username: bCfg.username || null,
|
|
505
|
+
botUserId: null,
|
|
506
|
+
api,
|
|
507
|
+
model: bCfg.model || null,
|
|
508
|
+
effort: bCfg.effort || null,
|
|
509
|
+
groupPolicy: bCfg.groupPolicy || 'mention',
|
|
510
|
+
mentionRegexes: (bCfg.mentionPatterns || []).map((p) => new RegExp(p, 'i')),
|
|
511
|
+
delegationPatterns: (bCfg.delegationPatterns || []).map((p) => new RegExp(p, 'iu')),
|
|
512
|
+
paused: Boolean(bCfg.paused),
|
|
513
|
+
delayScale: Number(bCfg.delayScale ?? 1),
|
|
514
|
+
ownerIds: botOwnerIds,
|
|
515
|
+
ownerSet: new Set(botOwnerIds),
|
|
516
|
+
offsetFile: path.join(stateDir, `offset-${bCfg.id}.json`),
|
|
517
|
+
stats: { turns: 0, errors: 0 },
|
|
518
|
+
runtime: null,
|
|
519
|
+
tools: null,
|
|
520
|
+
debouncer: null,
|
|
521
|
+
pollAbort: null,
|
|
522
|
+
};
|
|
523
|
+
|
|
524
|
+
const runtime = await createScrollChatRuntime({
|
|
525
|
+
agentName: botObj.agentName,
|
|
526
|
+
deploymentDir: path.resolve(bCfg.deploymentDir || process.cwd()),
|
|
527
|
+
stateDir,
|
|
528
|
+
accountId: bCfg.accountId || bCfg.id,
|
|
529
|
+
ownerIds: botOwnerIds,
|
|
530
|
+
provider,
|
|
531
|
+
model: botObj.model,
|
|
532
|
+
effort: botObj.effort,
|
|
533
|
+
authStore,
|
|
534
|
+
scheduler,
|
|
535
|
+
workerPool,
|
|
536
|
+
enableMemory: bCfg.enableMemory !== false,
|
|
537
|
+
memoryChannel: 'telegram',
|
|
538
|
+
enableTools: bCfg.enableTools !== false,
|
|
539
|
+
enableMcp: Boolean(bCfg.enableMcp),
|
|
540
|
+
voiceHooks: bCfg.voiceHooks || null,
|
|
541
|
+
requestApproval: (req) => requestHitlApproval(botObj, req),
|
|
542
|
+
compactAtChars: Number(bCfg.compactAtChars || 48_000),
|
|
543
|
+
keepRecentTurns: Number(bCfg.keepRecentTurns || 12),
|
|
544
|
+
acquireLock: bCfg.acquireLock !== false,
|
|
545
|
+
});
|
|
546
|
+
botObj.runtime = runtime;
|
|
547
|
+
botObj.tools = runtime.tools;
|
|
548
|
+
if (runtime.tools) {
|
|
549
|
+
longTasks.registerTools({ tools: runtime.tools, bot: botObj, ownerIds: botOwnerIds, groupGrants });
|
|
550
|
+
}
|
|
551
|
+
botObj.debouncer = createMessageDebouncer({
|
|
552
|
+
quietMs: Number(bCfg.debounceQuietMs ?? 1200),
|
|
553
|
+
maxWaitMs: Number(bCfg.debounceMaxWaitMs ?? 4500),
|
|
554
|
+
onFlush: (item) => processBurst(botObj, item),
|
|
555
|
+
});
|
|
556
|
+
|
|
557
|
+
bots.set(botObj.id, botObj);
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
// Invoke registered plugins
|
|
561
|
+
for (const pluginFn of loadedPlugins) {
|
|
562
|
+
const hook = await pluginFn({
|
|
563
|
+
config,
|
|
564
|
+
stateDir,
|
|
565
|
+
bots,
|
|
566
|
+
authStore,
|
|
567
|
+
scheduler,
|
|
568
|
+
workerPool,
|
|
569
|
+
groupGrants,
|
|
570
|
+
longTasks,
|
|
571
|
+
adminController,
|
|
572
|
+
logger,
|
|
573
|
+
});
|
|
574
|
+
if (hook && typeof hook === 'object') pluginHooks.push(hook);
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
async function pollBot(bot) {
|
|
578
|
+
let offset = readOffset(bot.offsetFile);
|
|
579
|
+
bot.pollAbort = new AbortController();
|
|
580
|
+
while (!stopped && !bot.pollAbort.signal.aborted) {
|
|
581
|
+
try {
|
|
582
|
+
const updates = await bot.api.getUpdates(
|
|
583
|
+
{ offset: offset != null ? offset : undefined, timeout: Number(config.pollTimeoutSec || 25) },
|
|
584
|
+
{ signal: bot.pollAbort.signal }
|
|
585
|
+
);
|
|
586
|
+
for (const upd of updates || []) {
|
|
587
|
+
offset = upd.update_id + 1;
|
|
588
|
+
writeOffset(bot.offsetFile, offset);
|
|
589
|
+
if (upd.callback_query) {
|
|
590
|
+
handleCallbackQuery(bot, upd.callback_query).catch((e) => logger.error?.('[callback]', e?.message || e));
|
|
591
|
+
} else if (upd.message) {
|
|
592
|
+
handleIncomingMessage(bot, upd.message).catch((e) => logger.error?.('[message]', e?.message || e));
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
} catch (err) {
|
|
596
|
+
if (stopped || bot.pollAbort.signal.aborted) break;
|
|
597
|
+
const waitMs = Number(err?.retryAfterMs || 2500);
|
|
598
|
+
logger.warn?.(`[scroll-telegram:${bot.id}] poll error (retrying in ${waitMs}ms):`, err?.message || err);
|
|
599
|
+
await sleep(waitMs);
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
async function start() {
|
|
605
|
+
stopped = false;
|
|
606
|
+
for (const bot of bots.values()) {
|
|
607
|
+
const me = await bot.api.getMe();
|
|
608
|
+
bot.username = me?.username || bot.username;
|
|
609
|
+
bot.botUserId = me?.id || null;
|
|
610
|
+
logger.info?.(`[scroll-telegram] connected @${bot.username} (${bot.id})`);
|
|
611
|
+
pollBot(bot).catch(() => {});
|
|
612
|
+
}
|
|
613
|
+
scheduler.start();
|
|
614
|
+
return { bots: [...bots.keys()] };
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
async function stop() {
|
|
618
|
+
stopped = true;
|
|
619
|
+
scheduler.stop();
|
|
620
|
+
for (const bot of bots.values()) {
|
|
621
|
+
if (bot.pollAbort) bot.pollAbort.abort();
|
|
622
|
+
bot.debouncer.close();
|
|
623
|
+
await bot.runtime.close().catch(() => {});
|
|
624
|
+
}
|
|
625
|
+
workerPool.close();
|
|
626
|
+
if (sharedCodexClient) await sharedCodexClient.close().catch(() => {});
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
return {
|
|
630
|
+
bots,
|
|
631
|
+
authStore,
|
|
632
|
+
scheduler,
|
|
633
|
+
workerPool,
|
|
634
|
+
groupGrants,
|
|
635
|
+
longTasks,
|
|
636
|
+
adminController,
|
|
637
|
+
adminUi,
|
|
638
|
+
start,
|
|
639
|
+
stop,
|
|
640
|
+
handleIncomingMessage,
|
|
641
|
+
handleCallbackQuery,
|
|
642
|
+
};
|
|
643
|
+
}
|