polygram 0.39.1 → 0.41.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/config.example.json +25 -0
- package/docs/EXTERNAL_JOBS_API.md +66 -0
- package/docs/RECORDED_NOTIFICATIONS_API.md +107 -0
- package/lib/db.js +7 -1
- package/lib/external-jobs/delivery.js +32 -0
- package/lib/external-jobs/notifications.js +270 -0
- package/lib/external-jobs/runtime.js +157 -0
- package/lib/external-jobs/schema.sql +41 -0
- package/lib/external-jobs/service.js +129 -0
- package/lib/external-jobs/store.js +180 -0
- package/lib/handlers/abort.js +21 -0
- package/lib/handlers/dispatcher.js +36 -22
- package/lib/handlers/gate-inbound.js +6 -0
- package/lib/history-preload.js +2 -1
- package/lib/history.js +18 -6
- package/lib/ipc/handlers.js +16 -0
- package/lib/telegram/api.js +18 -4
- package/migrations/022-external-jobs.sql +41 -0
- package/migrations/023-recorded-notifications.sql +44 -0
- package/package.json +3 -1
- package/polygram.js +59 -1
- package/skills/notifications/SKILL.md +22 -0
- package/skills/notifications/scripts/check.js +13 -0
package/lib/history-preload.js
CHANGED
|
@@ -54,7 +54,8 @@ function formatRow(row) {
|
|
|
54
54
|
: (row.user || row.bot_name || 'bot'));
|
|
55
55
|
const prefix = row.reply_to_id ? `[reply→#${row.reply_to_id}] ` : '';
|
|
56
56
|
const text = xmlEscape((row.text || '').replace(/\s+/g, ' ').slice(0, 600));
|
|
57
|
-
|
|
57
|
+
const transport = row.notification ? ` [source:${xmlEscape(row.notification.sourceId)} delivery:${xmlEscape(row.notification.deliveryState)}]` : '';
|
|
58
|
+
return `[${ts}] ${who}${transport}: ${prefix}${text}`;
|
|
58
59
|
}
|
|
59
60
|
|
|
60
61
|
/**
|
package/lib/history.js
CHANGED
|
@@ -56,6 +56,16 @@ function fts5Escape(query) {
|
|
|
56
56
|
.join(' ');
|
|
57
57
|
}
|
|
58
58
|
|
|
59
|
+
function withNotificationStatus(db, rows) {
|
|
60
|
+
// Archived databases predate the optional notification transport.
|
|
61
|
+
if (!db.raw.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='recorded_notifications'").get()) return rows;
|
|
62
|
+
const statement = db.raw.prepare('SELECT n.id,n.source_id,n.event_id,n.delivery_state,n.delivery_error,n.processed_request_id,j.state execution_state,j.report_state FROM recorded_notifications n LEFT JOIN external_jobs j ON j.bot_name=n.bot_name AND j.session_key=n.session_key AND j.request_id=n.processed_request_id WHERE n.message_id=?');
|
|
63
|
+
return rows.map((row) => {
|
|
64
|
+
const notification = statement.get(row.id);
|
|
65
|
+
return notification ? { ...row, notification: { id: notification.id, sourceId: notification.source_id, eventId: notification.event_id, deliveryState: notification.delivery_state, deliveryError: notification.delivery_error, requestId: notification.processed_request_id, executionState: notification.execution_state, reportState: notification.report_state } } : row;
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
|
|
59
69
|
function recent(db, { chatId, threadId = null, scopeThread = false, limit = 20, since = null, includeOutbound = true, allowedChatIds = null } = {}) {
|
|
60
70
|
const clamped = clampLimit(limit);
|
|
61
71
|
let sql = 'SELECT * FROM messages WHERE chat_id = ?';
|
|
@@ -72,7 +82,7 @@ function recent(db, { chatId, threadId = null, scopeThread = false, limit = 20,
|
|
|
72
82
|
if (sinceMs) { sql += ' AND ts >= ?'; params.push(Date.now() - sinceMs); }
|
|
73
83
|
const scoped = withChatScope(sql, params, allowedChatIds);
|
|
74
84
|
scoped.sql += ' ORDER BY ts DESC LIMIT ?';
|
|
75
|
-
return db.raw.prepare(scoped.sql).all(...scoped.params, clamped).reverse();
|
|
85
|
+
return withNotificationStatus(db, db.raw.prepare(scoped.sql).all(...scoped.params, clamped).reverse());
|
|
76
86
|
}
|
|
77
87
|
|
|
78
88
|
function around(db, { chatId, msgId, before = 5, after = 5, allowedChatIds = null } = {}) {
|
|
@@ -84,7 +94,7 @@ function around(db, { chatId, msgId, before = 5, after = 5, allowedChatIds = nul
|
|
|
84
94
|
const a = Math.min(Math.max(0, Number(after) || 0), HARD_LIMIT);
|
|
85
95
|
const beforeRows = db.raw.prepare('SELECT * FROM messages WHERE chat_id = ? AND ts < ? ORDER BY ts DESC LIMIT ?').all(chat, anchor.ts, b).reverse();
|
|
86
96
|
const afterRows = db.raw.prepare('SELECT * FROM messages WHERE chat_id = ? AND ts > ? ORDER BY ts ASC LIMIT ?').all(chat, anchor.ts, a);
|
|
87
|
-
return [...beforeRows, anchor, ...afterRows];
|
|
97
|
+
return withNotificationStatus(db, [...beforeRows, anchor, ...afterRows]);
|
|
88
98
|
}
|
|
89
99
|
|
|
90
100
|
function search(db, { query, chatId = null, threadId = null, user = null, days = null, limit = 20, allowedChatIds = null } = {}) {
|
|
@@ -103,7 +113,7 @@ function search(db, { query, chatId = null, threadId = null, user = null, days =
|
|
|
103
113
|
if (days) { sql += ' AND m.ts >= ?'; params.push(Date.now() - days * 86_400_000); }
|
|
104
114
|
const scoped = withChatScope(sql, params, allowedChatIds, 'm.chat_id');
|
|
105
115
|
scoped.sql += ' ORDER BY m.ts DESC LIMIT ?';
|
|
106
|
-
return db.raw.prepare(scoped.sql).all(...scoped.params, clamped);
|
|
116
|
+
return withNotificationStatus(db, db.raw.prepare(scoped.sql).all(...scoped.params, clamped));
|
|
107
117
|
}
|
|
108
118
|
|
|
109
119
|
function byUser(db, { user, chatId = null, threadId = null, days = 7, limit = 50, allowedChatIds = null } = {}) {
|
|
@@ -115,7 +125,7 @@ function byUser(db, { user, chatId = null, threadId = null, days = 7, limit = 50
|
|
|
115
125
|
if (days) { sql += ' AND ts >= ?'; params.push(Date.now() - days * 86_400_000); }
|
|
116
126
|
const scoped = withChatScope(sql, params, allowedChatIds);
|
|
117
127
|
scoped.sql += ' ORDER BY ts DESC LIMIT ?';
|
|
118
|
-
return db.raw.prepare(scoped.sql).all(...scoped.params, clamped);
|
|
128
|
+
return withNotificationStatus(db, db.raw.prepare(scoped.sql).all(...scoped.params, clamped));
|
|
119
129
|
}
|
|
120
130
|
|
|
121
131
|
function getMsg(db, { msgId, chatId = null, allowedChatIds = null } = {}) {
|
|
@@ -124,7 +134,8 @@ function getMsg(db, { msgId, chatId = null, allowedChatIds = null } = {}) {
|
|
|
124
134
|
if (chatId) { sql += ' AND chat_id = ?'; params.push(String(chatId)); }
|
|
125
135
|
const scoped = withChatScope(sql, params, allowedChatIds);
|
|
126
136
|
scoped.sql += ' ORDER BY id DESC LIMIT 1';
|
|
127
|
-
|
|
137
|
+
const row = db.raw.prepare(scoped.sql).get(...scoped.params);
|
|
138
|
+
return row ? withNotificationStatus(db, [row])[0] : null;
|
|
128
139
|
}
|
|
129
140
|
|
|
130
141
|
function stats(db, { chatId = null, threadId = null, days = 7, allowedChatIds = null } = {}) {
|
|
@@ -143,8 +154,9 @@ function formatPretty(rows) {
|
|
|
143
154
|
const d = new Date(r.ts);
|
|
144
155
|
const hhmm = `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
|
|
145
156
|
const who = r.direction === 'out' ? `[bot:${r.bot_name || '?'}]` : (r.user || '?');
|
|
157
|
+
const transport = r.notification ? ` [source:${r.notification.sourceId} delivery:${r.notification.deliveryState}]` : '';
|
|
146
158
|
const text = (r.text || '').replace(/\s+/g, ' ').slice(0, 200);
|
|
147
|
-
return `[${hhmm}] ${who}: ${text} (msg ${r.msg_id})`;
|
|
159
|
+
return `[${hhmm}] ${who}${transport}: ${text} (msg ${r.msg_id})`;
|
|
148
160
|
}).join('\n');
|
|
149
161
|
}
|
|
150
162
|
|
package/lib/ipc/handlers.js
CHANGED
|
@@ -33,8 +33,24 @@ function createIpcHandlers({
|
|
|
33
33
|
requestDeployRestart,
|
|
34
34
|
requestForegroundCanaryTarget,
|
|
35
35
|
inspectCleanRestartQualification,
|
|
36
|
+
externalJobs = null,
|
|
37
|
+
notifications = null,
|
|
36
38
|
} = {}) {
|
|
39
|
+
const requireJobs = () => {
|
|
40
|
+
if (!externalJobs) throw new Error('External jobs are not enabled');
|
|
41
|
+
return externalJobs;
|
|
42
|
+
};
|
|
43
|
+
const requireNotifications = () => { if (!notifications) throw new Error('Recorded notifications are disabled'); return notifications; };
|
|
44
|
+
const requestData = ({ op, id, secret, ...request }) => request;
|
|
37
45
|
return {
|
|
46
|
+
notify: (req) => requireNotifications().notify(requestData(req)),
|
|
47
|
+
notification_get: (req) => requireNotifications().get(requestData(req)),
|
|
48
|
+
notification_status: (req) => requireNotifications().scopedStatus(req.scope),
|
|
49
|
+
notification_wake: (req) => { const { scope, ...input } = requestData(req); return requireNotifications().schedule(scope, input); },
|
|
50
|
+
external_jobs_info: () => externalJobs?.info() ?? { protocolVersion: 1, enabled: false, supportedBackends: ['cli'] },
|
|
51
|
+
external_job_submit: (req) => requireJobs().submit(requestData(req)),
|
|
52
|
+
external_job_get: (req) => requireJobs().get(requestData(req)),
|
|
53
|
+
external_jobs_status: (req) => requireJobs().status(requestData(req)),
|
|
38
54
|
ping: async () => ({ pong: true, bot: botName }),
|
|
39
55
|
|
|
40
56
|
identity: async () => ({ bot: botName, ...daemonIdentity }),
|
package/lib/telegram/api.js
CHANGED
|
@@ -250,8 +250,15 @@ async function send({ bot, method, params, db = null, meta = {}, logger = consol
|
|
|
250
250
|
// restart would re-dispatch already-answered messages.
|
|
251
251
|
const replyToId = params.reply_parameters?.message_id ?? null;
|
|
252
252
|
|
|
253
|
-
let rowId = null;
|
|
254
|
-
if (
|
|
253
|
+
let rowId = meta.recordedRowId ?? null;
|
|
254
|
+
if (meta.requireRecording && (!db || !tracksMessage || !chatId)) throw new Error('Recorded outbound requires history storage');
|
|
255
|
+
if (rowId != null) {
|
|
256
|
+
const row = db.raw.prepare('SELECT * FROM messages WHERE id=?').get(rowId);
|
|
257
|
+
if (!row || row.direction !== 'out' || row.status !== 'pending' || row.chat_id !== chatId
|
|
258
|
+
|| String(row.thread_id ?? '') !== String(threadId ?? '') || row.text !== text
|
|
259
|
+
|| row.bot_name !== meta.botName || row.source !== meta.source) throw new Error('Recorded outbound does not match destination or content');
|
|
260
|
+
}
|
|
261
|
+
if (rowId == null && db && tracksMessage && chatId) {
|
|
255
262
|
const pendingId = nextPendingId();
|
|
256
263
|
try {
|
|
257
264
|
const result = db.insertOutboundPending({
|
|
@@ -268,6 +275,7 @@ async function send({ bot, method, params, db = null, meta = {}, logger = consol
|
|
|
268
275
|
});
|
|
269
276
|
rowId = result?.lastInsertRowid ?? null;
|
|
270
277
|
} catch (err) {
|
|
278
|
+
if (meta.requireRecording) throw err;
|
|
271
279
|
logger.error(`[telegram] insertOutboundPending failed: ${err.message}`);
|
|
272
280
|
}
|
|
273
281
|
}
|
|
@@ -391,7 +399,7 @@ async function send({ bot, method, params, db = null, meta = {}, logger = consol
|
|
|
391
399
|
try {
|
|
392
400
|
return await withPreConnectRetry(p);
|
|
393
401
|
} catch (err) {
|
|
394
|
-
if (!isThreadNotFound(err) || p.message_thread_id == null) throw err;
|
|
402
|
+
if (meta.strictDestination === true || !isThreadNotFound(err) || p.message_thread_id == null) throw err;
|
|
395
403
|
const retryParams = { ...p };
|
|
396
404
|
delete retryParams.message_thread_id;
|
|
397
405
|
logger.error?.(`[telegram] ${method}: thread gone, retrying without thread_id`);
|
|
@@ -409,7 +417,12 @@ async function send({ bot, method, params, db = null, meta = {}, logger = consol
|
|
|
409
417
|
};
|
|
410
418
|
|
|
411
419
|
try {
|
|
412
|
-
|
|
420
|
+
// Durable callers record each attempt and decide retry safety themselves.
|
|
421
|
+
res = meta.durableDelivery === true ? await rawAttempt(params) : await withThreadFallback(params);
|
|
422
|
+
if (meta.requireRecording && (!Number.isSafeInteger(res?.message_id) || res.message_id <= 0
|
|
423
|
+
|| String(res.chat?.id ?? '') !== chatId || String(res.message_thread_id ?? '') !== String(threadId ?? ''))) {
|
|
424
|
+
throw new Error('Telegram receipt does not prove the configured destination');
|
|
425
|
+
}
|
|
413
426
|
} catch (err) {
|
|
414
427
|
if (rowId != null && db) {
|
|
415
428
|
// 0.6.14: redact bot tokens before persisting err.message —
|
|
@@ -438,6 +451,7 @@ async function send({ bot, method, params, db = null, meta = {}, logger = consol
|
|
|
438
451
|
ts: (res?.date ? res.date * 1000 : Date.now()),
|
|
439
452
|
});
|
|
440
453
|
} catch (err) {
|
|
454
|
+
if (meta.requireRecording) throw err;
|
|
441
455
|
logger.error(`[telegram] markOutboundSent: ${err.message}`);
|
|
442
456
|
}
|
|
443
457
|
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
CREATE TABLE IF NOT EXISTS external_jobs (
|
|
2
|
+
id INTEGER PRIMARY KEY,
|
|
3
|
+
bot_name TEXT NOT NULL,
|
|
4
|
+
route_id TEXT NOT NULL,
|
|
5
|
+
request_id TEXT NOT NULL,
|
|
6
|
+
content_hash TEXT NOT NULL,
|
|
7
|
+
task TEXT NOT NULL,
|
|
8
|
+
payload TEXT NOT NULL,
|
|
9
|
+
target TEXT NOT NULL,
|
|
10
|
+
session_key TEXT NOT NULL,
|
|
11
|
+
state TEXT NOT NULL DEFAULT 'queued',
|
|
12
|
+
report_state TEXT NOT NULL DEFAULT 'none',
|
|
13
|
+
turn_id TEXT,
|
|
14
|
+
report_receipt TEXT,
|
|
15
|
+
error TEXT,
|
|
16
|
+
inactive INTEGER NOT NULL DEFAULT 0,
|
|
17
|
+
created_at INTEGER NOT NULL,
|
|
18
|
+
updated_at INTEGER NOT NULL,
|
|
19
|
+
UNIQUE(bot_name, route_id, request_id)
|
|
20
|
+
);
|
|
21
|
+
CREATE INDEX IF NOT EXISTS external_jobs_queue ON external_jobs(bot_name, state, id);
|
|
22
|
+
CREATE INDEX IF NOT EXISTS external_jobs_session ON external_jobs(bot_name, session_key, inactive, state);
|
|
23
|
+
CREATE TABLE IF NOT EXISTS external_job_controls (
|
|
24
|
+
bot_name TEXT NOT NULL,
|
|
25
|
+
session_key TEXT NOT NULL,
|
|
26
|
+
paused INTEGER NOT NULL DEFAULT 0,
|
|
27
|
+
updated_at INTEGER NOT NULL,
|
|
28
|
+
PRIMARY KEY(bot_name, session_key)
|
|
29
|
+
);
|
|
30
|
+
CREATE TABLE IF NOT EXISTS external_job_report_parts (
|
|
31
|
+
id INTEGER PRIMARY KEY,
|
|
32
|
+
job_id INTEGER NOT NULL REFERENCES external_jobs(id),
|
|
33
|
+
part_index INTEGER NOT NULL,
|
|
34
|
+
text TEXT NOT NULL,
|
|
35
|
+
state TEXT NOT NULL DEFAULT 'pending',
|
|
36
|
+
receipt TEXT,
|
|
37
|
+
error TEXT,
|
|
38
|
+
retry_at INTEGER NOT NULL DEFAULT 0,
|
|
39
|
+
UNIQUE(job_id, part_index)
|
|
40
|
+
);
|
|
41
|
+
CREATE INDEX IF NOT EXISTS external_job_report_pending ON external_job_report_parts(state, retry_at, job_id);
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
CREATE TABLE recorded_notifications (
|
|
2
|
+
id INTEGER PRIMARY KEY,
|
|
3
|
+
bot_name TEXT NOT NULL,
|
|
4
|
+
source_id TEXT NOT NULL,
|
|
5
|
+
event_id TEXT NOT NULL,
|
|
6
|
+
content_hash TEXT NOT NULL,
|
|
7
|
+
message_id INTEGER NOT NULL UNIQUE REFERENCES messages(id),
|
|
8
|
+
data TEXT NOT NULL,
|
|
9
|
+
target TEXT NOT NULL,
|
|
10
|
+
session_key TEXT NOT NULL,
|
|
11
|
+
eligible INTEGER NOT NULL,
|
|
12
|
+
delivery_state TEXT NOT NULL DEFAULT 'pending',
|
|
13
|
+
delivery_error TEXT,
|
|
14
|
+
retry_at INTEGER NOT NULL DEFAULT 0,
|
|
15
|
+
processed_request_id TEXT,
|
|
16
|
+
created_at INTEGER NOT NULL,
|
|
17
|
+
UNIQUE(bot_name, source_id, event_id)
|
|
18
|
+
);
|
|
19
|
+
CREATE INDEX recorded_notifications_unread ON recorded_notifications(bot_name, session_key, eligible, id);
|
|
20
|
+
CREATE TABLE notification_consumers (
|
|
21
|
+
bot_name TEXT NOT NULL,
|
|
22
|
+
consumer_id TEXT NOT NULL,
|
|
23
|
+
generation TEXT NOT NULL,
|
|
24
|
+
session_key TEXT NOT NULL,
|
|
25
|
+
target TEXT NOT NULL,
|
|
26
|
+
processed_id INTEGER NOT NULL,
|
|
27
|
+
active_batch TEXT,
|
|
28
|
+
last_request_id TEXT,
|
|
29
|
+
error TEXT,
|
|
30
|
+
PRIMARY KEY(bot_name, consumer_id, generation),
|
|
31
|
+
UNIQUE(bot_name, session_key, generation)
|
|
32
|
+
);
|
|
33
|
+
CREATE TABLE notification_wakes (
|
|
34
|
+
bot_name TEXT NOT NULL,
|
|
35
|
+
consumer_id TEXT NOT NULL,
|
|
36
|
+
generation TEXT NOT NULL,
|
|
37
|
+
wake_key TEXT NOT NULL,
|
|
38
|
+
revision INTEGER NOT NULL,
|
|
39
|
+
due_at INTEGER,
|
|
40
|
+
context TEXT NOT NULL,
|
|
41
|
+
notification_ids TEXT NOT NULL,
|
|
42
|
+
PRIMARY KEY(bot_name, consumer_id, generation, wake_key),
|
|
43
|
+
FOREIGN KEY(bot_name, consumer_id, generation) REFERENCES notification_consumers(bot_name, consumer_id, generation)
|
|
44
|
+
);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "polygram",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.41.0",
|
|
4
4
|
"description": "Telegram daemon for Claude Code that preserves the OpenClaw per-chat session model. Migration path for OpenClaw users moving to Claude Code.",
|
|
5
5
|
"main": "lib/ipc/client.js",
|
|
6
6
|
"bin": {
|
|
@@ -24,6 +24,8 @@
|
|
|
24
24
|
"commands/",
|
|
25
25
|
".claude-plugin/",
|
|
26
26
|
"ops/polygram.plist.example",
|
|
27
|
+
"docs/EXTERNAL_JOBS_API.md",
|
|
28
|
+
"docs/RECORDED_NOTIFICATIONS_API.md",
|
|
27
29
|
"ops/README.md",
|
|
28
30
|
"docs/2026-08-16-003-codex-protected-hook-artifact-runbook.md",
|
|
29
31
|
"config.example.json"
|
package/polygram.js
CHANGED
|
@@ -31,6 +31,9 @@ const {
|
|
|
31
31
|
const { buildPrompt, resolvePromptBackend } = require('./lib/prompt');
|
|
32
32
|
const { countInFlight } = require('./lib/queue-utils');
|
|
33
33
|
const { createIpcHandlers } = require('./lib/ipc/handlers');
|
|
34
|
+
const { createExternalJobService } = require('./lib/external-jobs/service');
|
|
35
|
+
const { prepareReport, createReportDelivery } = require('./lib/external-jobs/delivery');
|
|
36
|
+
const { createExternalJobRuntime, createExternalJobTargetResolver, createAutomationCommandHandler, isAutomationOperator, isAutomationDestination, pauseAutomationSession } = require('./lib/external-jobs/runtime');
|
|
34
37
|
const {
|
|
35
38
|
buildQualificationEvent,
|
|
36
39
|
} = require('./lib/ops/clean-restart-qualification');
|
|
@@ -143,6 +146,7 @@ const {
|
|
|
143
146
|
approvalCardText,
|
|
144
147
|
} = require('./lib/approvals/ui');
|
|
145
148
|
const { buildHistoryBlock } = require('./lib/history-preload');
|
|
149
|
+
const { createNotificationService } = require('./lib/external-jobs/notifications');
|
|
146
150
|
const { formatContextReply, maybeContextFullHint } = require('./lib/context-format');
|
|
147
151
|
// appendDisplayHint moved with buildSdkOptions extraction (commit 18) —
|
|
148
152
|
// only consumer of that import is now lib/sdk/build-options.js itself.
|
|
@@ -612,7 +616,7 @@ function formatPrompt(msg, sessionCtx, attachments = [], { sessionKey = null } =
|
|
|
612
616
|
sessionCtx,
|
|
613
617
|
attachments,
|
|
614
618
|
replyTo: resolveReplyTo(msg),
|
|
615
|
-
polygramHistory,
|
|
619
|
+
polygramHistory: polygramHistory + (notificationService?.context(sessionKey, msg.reply_to_message?.message_id) || '') + (notificationService?.instructions(sessionKey) || ''),
|
|
616
620
|
backend: resolvePromptBackend({ config, chatId, threadId }),
|
|
617
621
|
// Only advertise stickers this bot actually has — empty for a bot with no
|
|
618
622
|
// sticker set, so its prompt never mentions stickers.
|
|
@@ -1088,6 +1092,9 @@ function isSessionRecentlyAborted(sessionKey) { return abortGrace.isRecent(sessi
|
|
|
1088
1092
|
const autoResumeTracker = createAutoResumeTracker();
|
|
1089
1093
|
const contextHintShown = new Set();
|
|
1090
1094
|
let dispatchHandleMessage = null;
|
|
1095
|
+
let dispatchExternalEvent = null;
|
|
1096
|
+
let externalJobService = null;
|
|
1097
|
+
let notificationService = null;
|
|
1091
1098
|
let attemptAutoResume = null;
|
|
1092
1099
|
let errorReplyText = null;
|
|
1093
1100
|
let queueWarnThreshold = null;
|
|
@@ -3343,6 +3350,19 @@ function createBot(token) {
|
|
|
3343
3350
|
pairings: { hasLivePairing: (args) => !!pairings?.hasLivePairing(args) },
|
|
3344
3351
|
isAbortRequest,
|
|
3345
3352
|
handleAbortIfRequested: (...a) => handleAbortIfRequested(...a),
|
|
3353
|
+
handleAutomationCommand: createAutomationCommandHandler({
|
|
3354
|
+
getSessionKey, intentLock,
|
|
3355
|
+
config,
|
|
3356
|
+
getService: () => externalJobService,
|
|
3357
|
+
getNotificationStatus: (sessionKey) => notificationService?.statusForSession(sessionKey) || [],
|
|
3358
|
+
reply: async (msg, chatId, text) => {
|
|
3359
|
+
await tg(bot, 'sendMessage', {
|
|
3360
|
+
chat_id: chatId, message_thread_id: msg.message_thread_id,
|
|
3361
|
+
text, reply_parameters: { message_id: msg.message_id },
|
|
3362
|
+
}, { source: 'automation-command', botName: BOT_NAME });
|
|
3363
|
+
db.setInboundHandlerStatus({ chat_id: chatId, msg_id: msg.message_id, status: 'replied' });
|
|
3364
|
+
},
|
|
3365
|
+
}),
|
|
3346
3366
|
getRewindHandler: () => rewindHandler,
|
|
3347
3367
|
isRewindCommand,
|
|
3348
3368
|
resolveRuntime: ({ chatId, threadId }) => resolvePromptBackend({
|
|
@@ -4490,6 +4510,11 @@ async function main() {
|
|
|
4490
4510
|
pm, bot, tg, logEvent, isAbortRequest,
|
|
4491
4511
|
markSessionAborted, clearAutosteeredReactions, getSessionKey,
|
|
4492
4512
|
retireQuestionSession: (sessionKey) => questionHandlers?.retireSession(sessionKey),
|
|
4513
|
+
pauseAutomation: ({ msg, chatId, threadId, sessionKey }) => {
|
|
4514
|
+
if (externalJobService && isAutomationDestination({ config, getSessionKey }, chatId, threadId) && isAutomationOperator(config, msg)) {
|
|
4515
|
+
return pauseAutomationSession({ service: externalJobService, intentLock, sessionKey, paused: true });
|
|
4516
|
+
}
|
|
4517
|
+
},
|
|
4493
4518
|
botName: BOT_NAME, logger: console,
|
|
4494
4519
|
});
|
|
4495
4520
|
autosteer = createAutosteerHandlers({
|
|
@@ -4506,6 +4531,7 @@ async function main() {
|
|
|
4506
4531
|
});
|
|
4507
4532
|
({
|
|
4508
4533
|
dispatchHandleMessage,
|
|
4534
|
+
dispatchExternalEvent,
|
|
4509
4535
|
attemptAutoResume,
|
|
4510
4536
|
errorReplyText,
|
|
4511
4537
|
queueWarnThreshold,
|
|
@@ -4537,6 +4563,32 @@ async function main() {
|
|
|
4537
4563
|
authDisabledGate,
|
|
4538
4564
|
logger: console,
|
|
4539
4565
|
}));
|
|
4566
|
+
const resolveExternalTarget = createExternalJobTargetResolver({
|
|
4567
|
+
config, getSessionKey,
|
|
4568
|
+
resolveBackend: ({ chatId, threadId }) => resolvePromptBackend({ config, chatId, threadId }),
|
|
4569
|
+
});
|
|
4570
|
+
const externalRuntime = createExternalJobRuntime({
|
|
4571
|
+
config, pm, intentLock, getSessionKey,
|
|
4572
|
+
resolveBackend: ({ chatId, threadId }) => resolvePromptBackend({ config, chatId, threadId }),
|
|
4573
|
+
isPaused: (sessionKey) => externalJobService.isPaused(sessionKey),
|
|
4574
|
+
isShuttingDown: () => isShuttingDown,
|
|
4575
|
+
needsAuth: () => needsNativeClaudeAuth(config.bot, 'cli'),
|
|
4576
|
+
checkAuth: checkClaudeAuthHealth,
|
|
4577
|
+
awaitSessionRecovery: (sessionKey) => cleanReplaySessionCoordinator.wait(sessionKey, null),
|
|
4578
|
+
getOrSpawnForChat, sendToProcess,
|
|
4579
|
+
});
|
|
4580
|
+
externalJobService = createExternalJobService({
|
|
4581
|
+
config, db, botName: BOT_NAME, resolveTarget: resolveExternalTarget,
|
|
4582
|
+
dispatch: (job, hooks) => dispatchExternalEvent({
|
|
4583
|
+
...job.target, eventId: job.requestId,
|
|
4584
|
+
}, () => externalRuntime.dispatch({ ...job, task: job.task + (notificationService?.instructions(job.target.sessionKey) || '') }, hooks)),
|
|
4585
|
+
checkInactive: externalRuntime.checkInactive,
|
|
4586
|
+
prepareReport,
|
|
4587
|
+
deliverPart: createReportDelivery({ bot, tg, botName: BOT_NAME }),
|
|
4588
|
+
});
|
|
4589
|
+
notificationService = createNotificationService({
|
|
4590
|
+
config, db, botName: BOT_NAME, jobs: externalJobService, resolveTarget: resolveExternalTarget, bot, tg,
|
|
4591
|
+
});
|
|
4540
4592
|
// 0.12.0 post-turn edit re-delivery: constructed AFTER dispatchHandleMessage is assigned (above).
|
|
4541
4593
|
// Claude keeps its same-message fold behavior. Codex defers edits to the
|
|
4542
4594
|
// exact live generation's idle boundary and then re-dispatches them as
|
|
@@ -4650,6 +4702,8 @@ async function main() {
|
|
|
4650
4702
|
// idle, and cannot answer "how much work did this restart cost?".
|
|
4651
4703
|
const inFlightAtSignal = countInFlight(inFlightHandlers);
|
|
4652
4704
|
isShuttingDown = true;
|
|
4705
|
+
notificationService?.stop();
|
|
4706
|
+
externalJobService?.stop();
|
|
4653
4707
|
console.log(`\nShutting down (${trigger})...`);
|
|
4654
4708
|
// 1. Stop accepting new inbound first so nothing new queues behind the drain.
|
|
4655
4709
|
stopPolling();
|
|
@@ -4973,6 +5027,8 @@ async function main() {
|
|
|
4973
5027
|
path: ipcServer.socketPathFor(BOT_NAME),
|
|
4974
5028
|
secret: ipcSecret,
|
|
4975
5029
|
handlers: createIpcHandlers({
|
|
5030
|
+
externalJobs: externalJobService,
|
|
5031
|
+
notifications: notificationService,
|
|
4976
5032
|
botName: BOT_NAME,
|
|
4977
5033
|
daemonIdentity,
|
|
4978
5034
|
getInFlightHandlers: () => inFlightHandlers,
|
|
@@ -5626,6 +5682,8 @@ async function main() {
|
|
|
5626
5682
|
console.error(`[compact-orphan-handler] failed: ${err.message}`);
|
|
5627
5683
|
}
|
|
5628
5684
|
|
|
5685
|
+
externalJobService.start();
|
|
5686
|
+
notificationService.start();
|
|
5629
5687
|
logEvent('polygram-admission-open', lifecycleDetail({
|
|
5630
5688
|
bot: BOT_NAME,
|
|
5631
5689
|
}, invocationId, daemonIdentity));
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: notifications
|
|
3
|
+
description: Inspect this conversation's unread external notifications and persist, replace or cancel a timed follow-up check.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
Use the own-conversation command and scope supplied by Polygram in the current turn.
|
|
7
|
+
The daemon chooses the destination; the tool cannot target another topic. Its scope
|
|
8
|
+
expires when the daemon restarts, so use the current turn's command.
|
|
9
|
+
|
|
10
|
+
`status` returns the processing cursor, unread count, active job execution/report
|
|
11
|
+
states, pause state and schedules. `schedule` accepts one JSON argument with key,
|
|
12
|
+
future dueAt (epoch milliseconds), context and notificationIds. A stable key replaces
|
|
13
|
+
an older schedule with a new revision. `cancel` accepts a key and durably cancels it.
|
|
14
|
+
Only a successful persisted result proves a check was scheduled. Paused automation
|
|
15
|
+
retains overdue work and performs one check after resume. Unknown execution is held
|
|
16
|
+
for human reconciliation; it is never permission to repeat the turn.
|
|
17
|
+
|
|
18
|
+
Read fresh source evidence to establish recovery. Missing history, an unavailable
|
|
19
|
+
host or disabled check cannot establish health. Default unresolved recheck interval
|
|
20
|
+
is 30 minutes; choose a later time when appropriate. Report meaningful changes or
|
|
21
|
+
questions, without repeating an unchanged report. Notifications and scheduled checks
|
|
22
|
+
do not authorize repairs.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
const { call, readSecret, socketPathFor } = require('../../../lib/ipc/client');
|
|
4
|
+
async function main() {
|
|
5
|
+
const [botName, scope, command, json] = process.argv.slice(2);
|
|
6
|
+
if (!botName || !scope || !['status', 'schedule', 'cancel'].includes(command)) throw new Error('Usage: check.js bot scope status | schedule <JSON> | cancel <JSON>');
|
|
7
|
+
const input = command === 'status' ? {} : JSON.parse(json);
|
|
8
|
+
if (command === 'cancel') input.dueAt = null;
|
|
9
|
+
const result = await call({ path: socketPathFor(botName), secret: readSecret(botName), op: command === 'status' ? 'notification_status' : 'notification_wake', payload: { ...input, scope } });
|
|
10
|
+
if (!result.ok) throw new Error(result.error || 'Notification operation failed');
|
|
11
|
+
console.log(JSON.stringify(result));
|
|
12
|
+
}
|
|
13
|
+
main().catch((error) => { console.error(error.message); process.exitCode = 1; });
|