polygram 0.31.0 → 0.33.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/.claude-plugin/plugin.json +1 -1
- package/README.md +5 -0
- package/config.example.json +2 -0
- package/lib/db.js +233 -9
- package/lib/handlers/dispatcher.js +84 -13
- package/lib/ops/clean-resume.js +358 -0
- package/lib/ops/clean-shutdown.js +84 -0
- package/lib/ops/shutdown-disposition.js +13 -4
- package/lib/process/channels-tool-dispatcher.js +12 -3
- package/lib/sdk/callbacks.js +2 -0
- package/lib/telegram/api.js +71 -3
- package/lib/telegram/composing-marker.js +53 -0
- package/lib/telegram/delivery-barrier.js +117 -0
- package/lib/telegram/process-agent-reply.js +18 -2
- package/lib/telegram/rich-edit.js +16 -5
- package/lib/telegram/rich-media.js +18 -2
- package/lib/telegram/rich.js +36 -0
- package/lib/telegram/streamer.js +327 -26
- package/migrations/018-clean-restart-resume.sql +24 -0
- package/package.json +2 -2
- package/polygram.js +406 -43
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://anthropic.com/claude-code/plugin.schema.json",
|
|
3
3
|
"name": "polygram",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.33.0",
|
|
5
5
|
"description": "Telegram integration for Claude Code that preserves the OpenClaw per-chat session model. Migration target for OpenClaw users. Multi-bot, multi-chat, per-topic isolation; SQLite transcripts; inline-keyboard approvals. Bundles /polygram:status|logs|pair-code|approvals admin commands plus history (transcript queries) and polygram-send (out-of-turn IPC sends with file-upload validation) skills.",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"telegram",
|
package/README.md
CHANGED
|
@@ -285,6 +285,11 @@ Per-bot flags:
|
|
|
285
285
|
- `replayWindowMs` (default 180000 = 3 min) — boot replay only
|
|
286
286
|
resurrects interrupted turns younger than this. Longer outages drop
|
|
287
287
|
the queue rather than re-dispatching ancient work.
|
|
288
|
+
- `resumeInterruptedCliTurns` (default false) — on a deliberate clean
|
|
289
|
+
restart, strictly resume an interrupted CLI session and send one tracked
|
|
290
|
+
`continue`. Keep this off until the pinned-CLI recovery gate passes for the
|
|
291
|
+
deployed Orchestra version. Crash recovery still re-dispatches the original
|
|
292
|
+
message.
|
|
288
293
|
|
|
289
294
|
See `config.example.json` for the full schema.
|
|
290
295
|
|
package/config.example.json
CHANGED
|
@@ -16,6 +16,8 @@
|
|
|
16
16
|
"attachmentConcurrency": 6,
|
|
17
17
|
"queueWarnThreshold": 20,
|
|
18
18
|
"replayWindowMs": 180000,
|
|
19
|
+
"_comment_resumeInterruptedCliTurns": "Temporary staged-rollout flag. Default false. When true, a deliberate clean restart may strictly resume an interrupted CLI session and send one tracked literal `continue`; crashes still replay the original message. Enable only after the exact pinned-CLI recovery gate passes for the installed Orchestra version.",
|
|
20
|
+
"resumeInterruptedCliTurns": false,
|
|
19
21
|
"_comment_chrome": "Opt-in to Claude Code's Chrome-extension browser-automation integration. Default false. Requires the 'Claude in Chrome' extension installed in the daemon-user's Chrome browser AND a live GUI session (Chrome must be running). See https://code.claude.com/docs/en/chrome. Per-chat override via `config.chats.<id>.chrome`.",
|
|
20
22
|
"chrome": false,
|
|
21
23
|
"_comment_pairedChatDefaults": "When a user sends /pair <CODE> from a private chat that isn't in config.chats yet, polygram auto-creates a chat entry using these defaults (merged over top-level `defaults`). Leave out `cwd` at your peril — without it, auto-onboarded DMs have no working directory and pairing will fail.",
|
package/lib/db.js
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
|
|
7
7
|
const fs = require('fs');
|
|
8
8
|
const path = require('path');
|
|
9
|
+
const crypto = require('crypto');
|
|
9
10
|
const Database = require('better-sqlite3');
|
|
10
11
|
const {
|
|
11
12
|
pruneCodexOperationalData,
|
|
@@ -36,7 +37,7 @@ const {
|
|
|
36
37
|
//
|
|
37
38
|
// 0.15: bumped 13 → 14. Adds migration 014-secret-redactions.sql
|
|
38
39
|
// (secret_redactions audit table + messages.secret_scanned_at).
|
|
39
|
-
const SCHEMA_VERSION =
|
|
40
|
+
const SCHEMA_VERSION = 18;
|
|
40
41
|
|
|
41
42
|
// Sentinel `error` value for outbound rows whose API call may or may not
|
|
42
43
|
// have reached Telegram. markStalePending writes it; hasOutboundReplyTo
|
|
@@ -242,11 +243,11 @@ function wrap(db) {
|
|
|
242
243
|
INSERT INTO agent_runtime_sessions (
|
|
243
244
|
session_key, namespace, provider, provider_session_id,
|
|
244
245
|
app_server_session_id, agent, cwd, model, effort, pm_backend,
|
|
245
|
-
created_ts, last_active_ts
|
|
246
|
+
created_ts, last_active_ts, generation_id
|
|
246
247
|
) VALUES (
|
|
247
248
|
@session_key, @namespace, @provider, @provider_session_id,
|
|
248
249
|
@app_server_session_id, @agent, @cwd, @model, @effort, @pm_backend,
|
|
249
|
-
@ts, @ts
|
|
250
|
+
@ts, @ts, @generation_id
|
|
250
251
|
)
|
|
251
252
|
ON CONFLICT(session_key, namespace) DO UPDATE SET
|
|
252
253
|
provider = excluded.provider,
|
|
@@ -257,7 +258,14 @@ function wrap(db) {
|
|
|
257
258
|
model = excluded.model,
|
|
258
259
|
effort = excluded.effort,
|
|
259
260
|
pm_backend = excluded.pm_backend,
|
|
260
|
-
last_active_ts = excluded.last_active_ts
|
|
261
|
+
last_active_ts = excluded.last_active_ts,
|
|
262
|
+
generation_id = CASE
|
|
263
|
+
WHEN agent_runtime_sessions.provider_session_id = excluded.provider_session_id
|
|
264
|
+
AND agent_runtime_sessions.generation_id IS NOT NULL
|
|
265
|
+
AND agent_runtime_sessions.generation_id != ''
|
|
266
|
+
THEN agent_runtime_sessions.generation_id
|
|
267
|
+
ELSE excluded.generation_id
|
|
268
|
+
END
|
|
261
269
|
`);
|
|
262
270
|
const getProviderSessionStmt = db.prepare(`
|
|
263
271
|
SELECT *
|
|
@@ -308,6 +316,7 @@ function wrap(db) {
|
|
|
308
316
|
model: row.model || null,
|
|
309
317
|
effort: row.effort || null,
|
|
310
318
|
pm_backend: row.pm_backend || null,
|
|
319
|
+
generation_id: crypto.randomUUID(),
|
|
311
320
|
ts: row.ts || Date.now(),
|
|
312
321
|
};
|
|
313
322
|
}
|
|
@@ -530,12 +539,79 @@ function wrap(db) {
|
|
|
530
539
|
UPDATE polling_state SET clean_shutdown_at = NULL
|
|
531
540
|
WHERE bot_name = ?
|
|
532
541
|
`);
|
|
542
|
+
const deleteCleanRestartIntentsStmt = db.prepare(`
|
|
543
|
+
DELETE FROM clean_restart_resume_intents
|
|
544
|
+
WHERE bot_name = ?
|
|
545
|
+
`);
|
|
546
|
+
const insertCleanRestartIntentStmt = db.prepare(`
|
|
547
|
+
INSERT INTO clean_restart_resume_intents (
|
|
548
|
+
bot_name, session_key, session_generation_id,
|
|
549
|
+
source_message_id, shutdown_at, policy_version
|
|
550
|
+
) VALUES (?, ?, ?, ?, ?, ?)
|
|
551
|
+
`);
|
|
533
552
|
|
|
534
|
-
function
|
|
553
|
+
function normalizeResumeIntent(intent) {
|
|
554
|
+
if (!intent || typeof intent.sessionKey !== 'string' || intent.sessionKey.length === 0) {
|
|
555
|
+
throw new TypeError('clean restart intent session key is required');
|
|
556
|
+
}
|
|
557
|
+
if (!Number.isSafeInteger(intent.sourceMessageId) || intent.sourceMessageId <= 0) {
|
|
558
|
+
throw new TypeError('clean restart intent source message ID is invalid');
|
|
559
|
+
}
|
|
560
|
+
if (!Number.isSafeInteger(intent.policyVersion) || intent.policyVersion <= 0) {
|
|
561
|
+
throw new TypeError('clean restart intent policy version is invalid');
|
|
562
|
+
}
|
|
563
|
+
return intent;
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
function recordShutdown({
|
|
567
|
+
botName,
|
|
568
|
+
now = Date.now(),
|
|
569
|
+
since,
|
|
570
|
+
clean,
|
|
571
|
+
resumeIntents = [],
|
|
572
|
+
}) {
|
|
535
573
|
const cutoff = since ?? now - 30 * 60 * 1000;
|
|
536
574
|
const txn = db.transaction(() => {
|
|
537
575
|
const marked = markReplayPendingStmt.run(botName, cutoff);
|
|
538
576
|
if (clean) {
|
|
577
|
+
deleteCleanRestartIntentsStmt.run(botName);
|
|
578
|
+
for (const rawIntent of resumeIntents) {
|
|
579
|
+
const intent = normalizeResumeIntent(rawIntent);
|
|
580
|
+
const source = db.prepare(`
|
|
581
|
+
SELECT id
|
|
582
|
+
FROM messages
|
|
583
|
+
WHERE id = ?
|
|
584
|
+
AND direction = 'in'
|
|
585
|
+
AND bot_name = ?
|
|
586
|
+
AND handler_status != 'resume-attempted'
|
|
587
|
+
`).get(intent.sourceMessageId, botName);
|
|
588
|
+
if (!source) {
|
|
589
|
+
throw new Error(
|
|
590
|
+
`clean restart intent source ${intent.sourceMessageId} is unavailable`,
|
|
591
|
+
);
|
|
592
|
+
}
|
|
593
|
+
const session = getProviderSessionStmt.get(
|
|
594
|
+
intent.sessionKey,
|
|
595
|
+
CLAUDE_CHANNELS_NAMESPACE,
|
|
596
|
+
);
|
|
597
|
+
if (
|
|
598
|
+
!session
|
|
599
|
+
|| typeof session.generation_id !== 'string'
|
|
600
|
+
|| session.generation_id.length === 0
|
|
601
|
+
) {
|
|
602
|
+
throw new Error(
|
|
603
|
+
`clean restart intent session generation is unavailable for ${intent.sessionKey}`,
|
|
604
|
+
);
|
|
605
|
+
}
|
|
606
|
+
insertCleanRestartIntentStmt.run(
|
|
607
|
+
botName,
|
|
608
|
+
intent.sessionKey,
|
|
609
|
+
session.generation_id,
|
|
610
|
+
intent.sourceMessageId,
|
|
611
|
+
now,
|
|
612
|
+
intent.policyVersion,
|
|
613
|
+
);
|
|
614
|
+
}
|
|
539
615
|
db.prepare(`
|
|
540
616
|
INSERT INTO polling_state (bot_name, last_update_id, ts, clean_shutdown_at)
|
|
541
617
|
VALUES (?,
|
|
@@ -545,11 +621,15 @@ function wrap(db) {
|
|
|
545
621
|
ON CONFLICT(bot_name) DO UPDATE SET clean_shutdown_at = excluded.clean_shutdown_at
|
|
546
622
|
`).run(botName, botName, botName, now, now);
|
|
547
623
|
} else {
|
|
624
|
+
deleteCleanRestartIntentsStmt.run(botName);
|
|
548
625
|
clearCleanShutdownMarkerStmt.run(botName);
|
|
549
626
|
}
|
|
550
|
-
return
|
|
627
|
+
return {
|
|
628
|
+
replayMarked: marked.changes,
|
|
629
|
+
intentsRecorded: clean ? resumeIntents.length : 0,
|
|
630
|
+
};
|
|
551
631
|
});
|
|
552
|
-
return
|
|
632
|
+
return txn();
|
|
553
633
|
}
|
|
554
634
|
|
|
555
635
|
function assertCodexGenerationIdentity(generationId, stableHostId, bootSessionId) {
|
|
@@ -4100,8 +4180,19 @@ function wrap(db) {
|
|
|
4100
4180
|
// 005) for a fresh/quiet bot that has no row yet (a row is otherwise created
|
|
4101
4181
|
// only on a non-empty getUpdates batch): COALESCE the existing values, else
|
|
4102
4182
|
// seed (0, now).
|
|
4103
|
-
recordCleanShutdown({
|
|
4104
|
-
|
|
4183
|
+
recordCleanShutdown({
|
|
4184
|
+
botName,
|
|
4185
|
+
now = Date.now(),
|
|
4186
|
+
since,
|
|
4187
|
+
resumeIntents = [],
|
|
4188
|
+
} = {}) {
|
|
4189
|
+
return recordShutdown({
|
|
4190
|
+
botName,
|
|
4191
|
+
now,
|
|
4192
|
+
since,
|
|
4193
|
+
clean: true,
|
|
4194
|
+
resumeIntents,
|
|
4195
|
+
});
|
|
4105
4196
|
},
|
|
4106
4197
|
|
|
4107
4198
|
// A handled stop can still be crash-like when the supervisor is stopping
|
|
@@ -4111,6 +4202,130 @@ function wrap(db) {
|
|
|
4111
4202
|
return recordShutdown({ botName, now, since, clean: false });
|
|
4112
4203
|
},
|
|
4113
4204
|
|
|
4205
|
+
// Atomically consumes one clean-shutdown epoch and claims every matching
|
|
4206
|
+
// continuation intent before any process can spawn or polling can begin.
|
|
4207
|
+
// Unsupported policies and replaced sessions are still tombstoned so a
|
|
4208
|
+
// later boot cannot reinterpret them as original-message crash replay.
|
|
4209
|
+
claimCleanRestartRecovery({
|
|
4210
|
+
botName,
|
|
4211
|
+
now = Date.now(),
|
|
4212
|
+
maxAgeMs,
|
|
4213
|
+
supportedPolicyVersions = [],
|
|
4214
|
+
olderThanMs = 30 * 60 * 1000,
|
|
4215
|
+
} = {}) {
|
|
4216
|
+
const supported = new Set(supportedPolicyVersions);
|
|
4217
|
+
const cutoff = now - olderThanMs;
|
|
4218
|
+
const txn = db.transaction(() => {
|
|
4219
|
+
const stranded = db.prepare(`
|
|
4220
|
+
SELECT id, chat_id, thread_id, msg_id, user, user_id, text,
|
|
4221
|
+
reply_to_id, ts, handler_status, bot_name
|
|
4222
|
+
FROM messages
|
|
4223
|
+
WHERE direction = 'in'
|
|
4224
|
+
AND bot_name = ?
|
|
4225
|
+
AND handler_status = 'resume-attempted'
|
|
4226
|
+
AND ts > ?
|
|
4227
|
+
ORDER BY ts, id
|
|
4228
|
+
`).all(botName, cutoff);
|
|
4229
|
+
|
|
4230
|
+
const markerRow = db.prepare(`
|
|
4231
|
+
SELECT clean_shutdown_at
|
|
4232
|
+
FROM polling_state
|
|
4233
|
+
WHERE bot_name = ?
|
|
4234
|
+
`).get(botName);
|
|
4235
|
+
const markerAt = markerRow?.clean_shutdown_at ?? null;
|
|
4236
|
+
const age = typeof markerAt === 'number' ? now - markerAt : null;
|
|
4237
|
+
const clean = age != null
|
|
4238
|
+
&& age >= 0
|
|
4239
|
+
&& (maxAgeMs == null || age <= maxAgeMs);
|
|
4240
|
+
|
|
4241
|
+
const rows = clean
|
|
4242
|
+
? db.prepare(`
|
|
4243
|
+
SELECT intent.*,
|
|
4244
|
+
source.id AS source_id,
|
|
4245
|
+
source.chat_id,
|
|
4246
|
+
source.thread_id,
|
|
4247
|
+
source.msg_id,
|
|
4248
|
+
source.bot_name AS source_bot_name,
|
|
4249
|
+
source.direction AS source_direction,
|
|
4250
|
+
runtime.generation_id AS current_generation_id,
|
|
4251
|
+
runtime.provider_session_id,
|
|
4252
|
+
runtime.namespace AS provider_namespace,
|
|
4253
|
+
runtime.pm_backend
|
|
4254
|
+
FROM clean_restart_resume_intents AS intent
|
|
4255
|
+
LEFT JOIN messages AS source
|
|
4256
|
+
ON source.id = intent.source_message_id
|
|
4257
|
+
LEFT JOIN agent_runtime_sessions AS runtime
|
|
4258
|
+
ON runtime.session_key = intent.session_key
|
|
4259
|
+
AND runtime.namespace = '${CLAUDE_CHANNELS_NAMESPACE}'
|
|
4260
|
+
WHERE intent.bot_name = ?
|
|
4261
|
+
AND intent.shutdown_at = ?
|
|
4262
|
+
ORDER BY intent.session_key
|
|
4263
|
+
`).all(botName, markerAt)
|
|
4264
|
+
: [];
|
|
4265
|
+
|
|
4266
|
+
deleteCleanRestartIntentsStmt.run(botName);
|
|
4267
|
+
if (markerAt != null) clearCleanShutdownMarkerStmt.run(botName);
|
|
4268
|
+
|
|
4269
|
+
const claims = rows.map((row) => {
|
|
4270
|
+
const sourceMatches = row.source_id != null
|
|
4271
|
+
&& row.source_direction === 'in'
|
|
4272
|
+
&& row.source_bot_name === botName;
|
|
4273
|
+
if (sourceMatches) {
|
|
4274
|
+
db.prepare(`
|
|
4275
|
+
UPDATE messages
|
|
4276
|
+
SET handler_status = 'resume-attempted'
|
|
4277
|
+
WHERE id = ?
|
|
4278
|
+
AND direction = 'in'
|
|
4279
|
+
AND bot_name = ?
|
|
4280
|
+
`).run(row.source_message_id, botName);
|
|
4281
|
+
}
|
|
4282
|
+
|
|
4283
|
+
let reason = null;
|
|
4284
|
+
if (!sourceMatches) {
|
|
4285
|
+
reason = 'source-message-missing';
|
|
4286
|
+
} else if (!supported.has(row.policy_version)) {
|
|
4287
|
+
reason = 'unsupported-policy-version';
|
|
4288
|
+
} else if (
|
|
4289
|
+
typeof row.current_generation_id !== 'string'
|
|
4290
|
+
|| row.current_generation_id.length === 0
|
|
4291
|
+
|| row.current_generation_id !== row.session_generation_id
|
|
4292
|
+
) {
|
|
4293
|
+
reason = 'session-generation-replaced';
|
|
4294
|
+
}
|
|
4295
|
+
|
|
4296
|
+
return {
|
|
4297
|
+
bot_name: row.bot_name,
|
|
4298
|
+
session_key: row.session_key,
|
|
4299
|
+
session_generation_id: row.session_generation_id,
|
|
4300
|
+
source_message_id: row.source_message_id,
|
|
4301
|
+
shutdown_at: row.shutdown_at,
|
|
4302
|
+
policy_version: row.policy_version,
|
|
4303
|
+
provider_namespace: reason == null ? row.provider_namespace : null,
|
|
4304
|
+
provider_session_id: reason == null ? row.provider_session_id : null,
|
|
4305
|
+
pm_backend: reason == null ? row.pm_backend : null,
|
|
4306
|
+
executable: reason == null,
|
|
4307
|
+
reason,
|
|
4308
|
+
};
|
|
4309
|
+
});
|
|
4310
|
+
|
|
4311
|
+
return { clean, markerAt, claims, stranded };
|
|
4312
|
+
});
|
|
4313
|
+
return txn();
|
|
4314
|
+
},
|
|
4315
|
+
|
|
4316
|
+
completeCleanRestartRecovery({ sourceMessageId, status }) {
|
|
4317
|
+
if (!['replied', 'replay-skipped'].includes(status)) {
|
|
4318
|
+
throw new TypeError('clean restart recovery terminal status is invalid');
|
|
4319
|
+
}
|
|
4320
|
+
return db.prepare(`
|
|
4321
|
+
UPDATE messages
|
|
4322
|
+
SET handler_status = ?
|
|
4323
|
+
WHERE id = ?
|
|
4324
|
+
AND direction = 'in'
|
|
4325
|
+
AND handler_status = 'resume-attempted'
|
|
4326
|
+
`).run(status, sourceMessageId);
|
|
4327
|
+
},
|
|
4328
|
+
|
|
4114
4329
|
// 0.14: read AND clear the clean-shutdown marker in one txn. "Clean" iff a
|
|
4115
4330
|
// marker is present, not future-dated (clock skew → crash), and within
|
|
4116
4331
|
// maxAgeMs (derived from the replay window). Clear-on-read so a marker from
|
|
@@ -4296,6 +4511,15 @@ function wrap(db) {
|
|
|
4296
4511
|
return row ? row.id : null;
|
|
4297
4512
|
},
|
|
4298
4513
|
|
|
4514
|
+
getInboundMessageById(messageId) {
|
|
4515
|
+
return db.prepare(`
|
|
4516
|
+
SELECT *
|
|
4517
|
+
FROM messages
|
|
4518
|
+
WHERE id = ?
|
|
4519
|
+
AND direction = 'in'
|
|
4520
|
+
`).get(messageId);
|
|
4521
|
+
},
|
|
4522
|
+
|
|
4299
4523
|
listFailedAttachments({ since = null, limit = 100 } = {}) {
|
|
4300
4524
|
const cutoff = since ?? Date.now() - 24 * 60 * 60 * 1000;
|
|
4301
4525
|
return db.prepare(`
|
|
@@ -76,6 +76,49 @@ function createDispatcher({
|
|
|
76
76
|
} = {}) {
|
|
77
77
|
// Per-session in-flight handler count.
|
|
78
78
|
const inFlightHandlers = new Map();
|
|
79
|
+
const activeHandlers = new Set();
|
|
80
|
+
|
|
81
|
+
function trackTask(task) {
|
|
82
|
+
activeHandlers.add(task);
|
|
83
|
+
task.then(
|
|
84
|
+
() => activeHandlers.delete(task),
|
|
85
|
+
() => activeHandlers.delete(task),
|
|
86
|
+
);
|
|
87
|
+
return task;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function awaitSettlement({ timeoutMs = 30_000 } = {}) {
|
|
91
|
+
const deadline = Date.now() + timeoutMs;
|
|
92
|
+
while (activeHandlers.size > 0) {
|
|
93
|
+
const remainingMs = deadline - Date.now();
|
|
94
|
+
if (remainingMs <= 0) {
|
|
95
|
+
const error = new Error(
|
|
96
|
+
`handler settlement timed out with ${activeHandlers.size} task(s) still active`,
|
|
97
|
+
);
|
|
98
|
+
error.code = 'HANDLER_SETTLEMENT_TIMEOUT';
|
|
99
|
+
throw error;
|
|
100
|
+
}
|
|
101
|
+
let timeout;
|
|
102
|
+
const timedOut = new Promise((_, reject) => {
|
|
103
|
+
timeout = setTimeout(() => {
|
|
104
|
+
const error = new Error(
|
|
105
|
+
`handler settlement timed out with ${activeHandlers.size} task(s) still active`,
|
|
106
|
+
);
|
|
107
|
+
error.code = 'HANDLER_SETTLEMENT_TIMEOUT';
|
|
108
|
+
reject(error);
|
|
109
|
+
}, remainingMs);
|
|
110
|
+
timeout.unref?.();
|
|
111
|
+
});
|
|
112
|
+
try {
|
|
113
|
+
await Promise.race([
|
|
114
|
+
Promise.allSettled([...activeHandlers]),
|
|
115
|
+
timedOut,
|
|
116
|
+
]);
|
|
117
|
+
} finally {
|
|
118
|
+
clearTimeout(timeout);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
79
122
|
|
|
80
123
|
function queueWarnThreshold() {
|
|
81
124
|
const v = Number(config.bot?.queueWarnThreshold);
|
|
@@ -111,7 +154,12 @@ function createDispatcher({
|
|
|
111
154
|
: '🔁 Auto-resuming after timeout — continuing where the previous turn left off.',
|
|
112
155
|
reply_parameters: { message_id: originalMsg.message_id },
|
|
113
156
|
...(threadId && { message_thread_id: threadId }),
|
|
114
|
-
}, {
|
|
157
|
+
}, {
|
|
158
|
+
source: 'auto-resume-indicator',
|
|
159
|
+
botName,
|
|
160
|
+
sessionKey,
|
|
161
|
+
sourceMsgId: originalMsg.message_id,
|
|
162
|
+
}).catch((sendErr) => {
|
|
115
163
|
logger.error?.(`[${sessionKey}] auto-resume indicator send failed: ${sendErr.message}`);
|
|
116
164
|
});
|
|
117
165
|
|
|
@@ -204,7 +252,12 @@ function createDispatcher({
|
|
|
204
252
|
threadId,
|
|
205
253
|
chunks,
|
|
206
254
|
replyToMessageId: originalMsg.message_id,
|
|
207
|
-
meta: {
|
|
255
|
+
meta: {
|
|
256
|
+
source: 'auto-resume-reply',
|
|
257
|
+
botName,
|
|
258
|
+
sessionKey,
|
|
259
|
+
sourceMsgId: originalMsg.message_id,
|
|
260
|
+
},
|
|
208
261
|
logger: { error: (m) => logger.error?.(`[${sessionKey}] auto-resume deliver: ${m}`) },
|
|
209
262
|
});
|
|
210
263
|
|
|
@@ -221,7 +274,7 @@ function createDispatcher({
|
|
|
221
274
|
in_flight: count, threshold: warnAt,
|
|
222
275
|
});
|
|
223
276
|
}
|
|
224
|
-
handleMessage(sessionKey, chatId, msg, bot).catch((err) => {
|
|
277
|
+
const task = handleMessage(sessionKey, chatId, msg, bot).catch(async (err) => {
|
|
225
278
|
const wasAborted = abortGrace.isRecent(sessionKey);
|
|
226
279
|
const isReplay = msg._isReplay === true;
|
|
227
280
|
let oomShutdown = false;
|
|
@@ -349,7 +402,12 @@ function createDispatcher({
|
|
|
349
402
|
chat_id: chatId,
|
|
350
403
|
text: '⚠️ This turn was interrupted and didn\'t complete on retry — please rephrase or simplify, or split into smaller steps.',
|
|
351
404
|
reply_parameters: { message_id: msg.message_id },
|
|
352
|
-
}, {
|
|
405
|
+
}, {
|
|
406
|
+
source: 'error-reply',
|
|
407
|
+
botName,
|
|
408
|
+
sessionKey,
|
|
409
|
+
sourceMsgId: msg.message_id,
|
|
410
|
+
}).catch((replyErr) => {
|
|
353
411
|
logger.error?.(`[${sessionKey}] failed to send replay-failure reply: ${replyErr.message}`);
|
|
354
412
|
});
|
|
355
413
|
}
|
|
@@ -404,11 +462,12 @@ function createDispatcher({
|
|
|
404
462
|
// best-effort timer so a pending retry can't pin the daemon alive
|
|
405
463
|
// (the Telegram long-poll already keeps the loop running).
|
|
406
464
|
const retryMsg = { ...msg, _startupRetried: true };
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
)
|
|
411
|
-
return;
|
|
465
|
+
await new Promise((resolve) => {
|
|
466
|
+
const timer = setTimeout(resolve, startupRetryDelayMs);
|
|
467
|
+
timer.unref?.();
|
|
468
|
+
});
|
|
469
|
+
if (getIsShuttingDown()) return;
|
|
470
|
+
return dispatchHandleMessage(sessionKey, chatId, retryMsg, bot);
|
|
412
471
|
}
|
|
413
472
|
// rc.54: auto-resume on 300s no-activity timeout. The
|
|
414
473
|
// resume turn itself runs through sendToProcess directly
|
|
@@ -427,7 +486,7 @@ function createDispatcher({
|
|
|
427
486
|
chat_id: chatId, session_key: sessionKey, msg_id: msg.message_id,
|
|
428
487
|
original_error: err.message?.slice(0, 200),
|
|
429
488
|
});
|
|
430
|
-
attemptAutoResume(sessionKey, chatId, msg, bot, {
|
|
489
|
+
return attemptAutoResume(sessionKey, chatId, msg, bot, {
|
|
431
490
|
provider,
|
|
432
491
|
providerRecovery,
|
|
433
492
|
})
|
|
@@ -471,10 +530,14 @@ function createDispatcher({
|
|
|
471
530
|
tg(bot, 'sendMessage', {
|
|
472
531
|
chat_id: chatId, text: fallbackText,
|
|
473
532
|
reply_parameters: { message_id: msg.message_id },
|
|
474
|
-
}, {
|
|
533
|
+
}, {
|
|
534
|
+
source: 'error-reply',
|
|
535
|
+
botName,
|
|
536
|
+
sessionKey,
|
|
537
|
+
sourceMsgId: msg.message_id,
|
|
538
|
+
}).catch(() => {});
|
|
475
539
|
}
|
|
476
540
|
});
|
|
477
|
-
return;
|
|
478
541
|
}
|
|
479
542
|
// 0.7.7: errorReplyText may return null (suppress reply
|
|
480
543
|
// signal — INTERRUPTED inside abort grace).
|
|
@@ -486,7 +549,12 @@ function createDispatcher({
|
|
|
486
549
|
chat_id: chatId,
|
|
487
550
|
text: replyText,
|
|
488
551
|
reply_parameters: { message_id: msg.message_id },
|
|
489
|
-
}, {
|
|
552
|
+
}, {
|
|
553
|
+
source: 'error-reply',
|
|
554
|
+
botName,
|
|
555
|
+
sessionKey,
|
|
556
|
+
sourceMsgId: msg.message_id,
|
|
557
|
+
}).catch((replyErr) => {
|
|
490
558
|
logger.error?.(`[${sessionKey}] failed to send error reply: ${replyErr.message}`);
|
|
491
559
|
});
|
|
492
560
|
}
|
|
@@ -496,6 +564,7 @@ function createDispatcher({
|
|
|
496
564
|
if (n <= 0) inFlightHandlers.delete(sessionKey);
|
|
497
565
|
else inFlightHandlers.set(sessionKey, n);
|
|
498
566
|
});
|
|
567
|
+
return trackTask(task);
|
|
499
568
|
}
|
|
500
569
|
|
|
501
570
|
return {
|
|
@@ -504,6 +573,8 @@ function createDispatcher({
|
|
|
504
573
|
errorReplyText,
|
|
505
574
|
queueWarnThreshold,
|
|
506
575
|
inFlightHandlers, // exposed so polygram.js can introspect for shutdown drain
|
|
576
|
+
awaitSettlement,
|
|
577
|
+
trackTask,
|
|
507
578
|
};
|
|
508
579
|
}
|
|
509
580
|
|