polygram 0.26.0 → 0.27.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/lib/ipc/handlers.js +35 -0
- package/lib/ops/tmux-preflight.js +56 -0
- package/lib/queue-utils.js +35 -1
- package/lib/telegram/display-hint.js +1 -0
- package/package.json +2 -2
- package/polygram.js +51 -11
|
@@ -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.27.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",
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// The op set the IPC server registers.
|
|
2
|
+
//
|
|
3
|
+
// Assembled here rather than inline at the call site so tests exercise the SAME
|
|
4
|
+
// object production serves. A test that builds its own handler map proves the
|
|
5
|
+
// transport works and nothing about which ops a running daemon actually answers
|
|
6
|
+
// — it would keep passing after an op was dropped.
|
|
7
|
+
|
|
8
|
+
'use strict';
|
|
9
|
+
|
|
10
|
+
const { buildBusySnapshot } = require('../queue-utils');
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* @param {object} opts
|
|
14
|
+
* @param {string} opts.botName
|
|
15
|
+
* @param {() => Map<string, number>} opts.getInFlightHandlers — read late, not
|
|
16
|
+
* captured: the dispatcher's map is assigned during boot and replaced on
|
|
17
|
+
* reload, so a value bound at wiring time can go stale.
|
|
18
|
+
* @param {(req) => any} opts.handleSendOverIpc
|
|
19
|
+
*/
|
|
20
|
+
function createIpcHandlers({ botName, getInFlightHandlers, handleSendOverIpc } = {}) {
|
|
21
|
+
return {
|
|
22
|
+
ping: async () => ({ pong: true, bot: botName }),
|
|
23
|
+
|
|
24
|
+
// Deploy pre-flight: what would restarting this daemon interrupt right now?
|
|
25
|
+
// Counts and session keys only — enough to decide, nothing quotable.
|
|
26
|
+
busy: async () => buildBusySnapshot({
|
|
27
|
+
inFlightHandlers: typeof getInFlightHandlers === 'function' ? getInFlightHandlers() : null,
|
|
28
|
+
botName,
|
|
29
|
+
}),
|
|
30
|
+
|
|
31
|
+
send: (req) => handleSendOverIpc(req),
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
module.exports = { createIpcHandlers };
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// Boot preflight for the tmux backend.
|
|
2
|
+
//
|
|
3
|
+
// With ORCHESTRA_TMUX_REQUIRE_SERVER=1 the daemon passes tmux `-N` and must
|
|
4
|
+
// never create the server itself — that server would be a child of this process,
|
|
5
|
+
// so under systemd it lands in this unit's cgroup and a restart reaps every
|
|
6
|
+
// Claude session with it. The cost of that guarantee is that an absent or
|
|
7
|
+
// unreachable server is unrecoverable here: every tmux-backed turn will fail.
|
|
8
|
+
//
|
|
9
|
+
// Booting anyway is the worst available outcome. systemd reports the unit
|
|
10
|
+
// `active`, the bot answers nothing, and the failure is invisible until someone
|
|
11
|
+
// notices the silence. Fail loudly instead, before the DB is opened or any
|
|
12
|
+
// Telegram traffic is accepted.
|
|
13
|
+
//
|
|
14
|
+
// Kept out of the boot sequence so the decision is testable without a daemon.
|
|
15
|
+
|
|
16
|
+
'use strict';
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* @param {object} opts
|
|
20
|
+
* @param {object} [opts.sweep] result of sweepTmuxOrphans, when it returned
|
|
21
|
+
* @param {Error} [opts.error] the error it threw instead, if it threw
|
|
22
|
+
* @param {boolean} opts.requireExistingServer
|
|
23
|
+
* @returns {{ fatal: boolean, reason?: string }}
|
|
24
|
+
*/
|
|
25
|
+
function classifyOrphanSweep({ sweep, error, requireExistingServer } = {}) {
|
|
26
|
+
// Free to create the server on demand, so an empty or absent host is normal.
|
|
27
|
+
if (!requireExistingServer) return { fatal: false };
|
|
28
|
+
|
|
29
|
+
if (error) {
|
|
30
|
+
return { fatal: true, reason: error.message || String(error) };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
if (!sweep) {
|
|
34
|
+
return { fatal: true, reason: 'orphan sweep returned no result' };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// Explicitly `false`, not merely falsy. An orchestra predating the strict
|
|
38
|
+
// sweep leaves this undefined, and it cannot tell "no sessions" from "could
|
|
39
|
+
// not ask" — treating that as healthy silently restores the fail-open this
|
|
40
|
+
// check exists to close, which is exactly what a dependency downgrade would
|
|
41
|
+
// do.
|
|
42
|
+
if (sweep.listFailed === false) return { fatal: false };
|
|
43
|
+
|
|
44
|
+
if (sweep.listFailed === true) {
|
|
45
|
+
return { fatal: true, reason: sweep.listError || 'tmux server unreachable' };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
return {
|
|
49
|
+
fatal: true,
|
|
50
|
+
reason: 'installed @shumkov/orchestra cannot report tmux reachability '
|
|
51
|
+
+ '(no listFailed in the sweep result) — upgrade it, or unset '
|
|
52
|
+
+ 'ORCHESTRA_TMUX_REQUIRE_SERVER',
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
module.exports = { classifyOrphanSweep };
|
package/lib/queue-utils.js
CHANGED
|
@@ -24,4 +24,38 @@ function drainQueuesForChat(queues, chatId) {
|
|
|
24
24
|
return dropped;
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
-
|
|
27
|
+
// Total handler count across every session. `inFlightHandlers` is the
|
|
28
|
+
// dispatcher's Map<sessionKey, count>; it is null before the dispatcher is
|
|
29
|
+
// wired and can be read again while the daemon tears itself down, so a missing
|
|
30
|
+
// map counts as zero rather than throwing.
|
|
31
|
+
function countInFlight(inFlightHandlers) {
|
|
32
|
+
if (!inFlightHandlers) return 0;
|
|
33
|
+
let total = 0;
|
|
34
|
+
for (const n of inFlightHandlers.values()) total += n || 0;
|
|
35
|
+
return total;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Point-in-time view of what the daemon is working on, for the IPC `busy` op.
|
|
39
|
+
//
|
|
40
|
+
// A deploy needs to know whether a restart would interrupt anyone. The only
|
|
41
|
+
// exact answer is the dispatcher's in-flight map: a chat's tmux session exists
|
|
42
|
+
// for the whole LRU lifetime of that chat, so counting live sessions reports
|
|
43
|
+
// "busy" almost always and tells an operator nothing.
|
|
44
|
+
//
|
|
45
|
+
// Sessions at zero are omitted — they have finished, and listing them would
|
|
46
|
+
// make every deploy look unsafe.
|
|
47
|
+
function buildBusySnapshot({ inFlightHandlers, botName } = {}) {
|
|
48
|
+
const sessions = [];
|
|
49
|
+
if (inFlightHandlers) {
|
|
50
|
+
for (const [sessionKey, n] of inFlightHandlers.entries()) {
|
|
51
|
+
if (n > 0) sessions.push({ session_key: sessionKey, in_flight: n });
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return {
|
|
55
|
+
bot: botName ?? null,
|
|
56
|
+
in_flight: countInFlight(inFlightHandlers),
|
|
57
|
+
sessions,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
module.exports = { drainQueuesForChat, countInFlight, buildBusySnapshot };
|
|
@@ -85,6 +85,7 @@ const richSection = (inlineMedia) => [
|
|
|
85
85
|
'**Use the real construct instead of faking it with bold text and emoji.** In plain-mode chats you had to fake structure with **bold** pseudo-headers, emoji bullets (✅ ❓ 🕓, •, etc.), and plain-text separator lines, because headings and checkboxes rendered as flattened text there. That workaround is unnecessary here and looks worse than the real thing. When you catch yourself about to write a bold pseudo-heading or an emoji-bulleted list, use the actual construct instead:',
|
|
86
86
|
'',
|
|
87
87
|
'- A named group of items (e.g. "ready to apply" / "needs your input" / "deferred") → a real heading (`## Ready to apply`), not `**Ready to apply:**`.',
|
|
88
|
+
'- A numbered sequence (steps, ranked facts, top-N) → a real ordered list (`1.` at line start, continuation lines indented under their item), not bold pseudo-items like `**1. First thing.**` on their own paragraphs. A real list renders with native numbering and hanging indentation; the bold fake renders as flat paragraphs that merely start with a digit.',
|
|
88
89
|
'- A list of items each with a yes/no/pending state (approve this? confirm that?) → a real task list (`- [ ] item`), not `• item` with an emoji glued on.',
|
|
89
90
|
'- A comparison or key/value summary → a real markdown table.',
|
|
90
91
|
'- A quoted aside, caveat, or callout you want visually set apart → a real blockquote (`> like this`), not a bold prefix.',
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "polygram",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.27.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": {
|
|
@@ -63,7 +63,7 @@
|
|
|
63
63
|
"dependencies": {
|
|
64
64
|
"@anthropic-ai/claude-agent-sdk": "0.2.123",
|
|
65
65
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
66
|
-
"@shumkov/orchestra": "0.
|
|
66
|
+
"@shumkov/orchestra": "0.9.0",
|
|
67
67
|
"better-sqlite3": "^12.9.0",
|
|
68
68
|
"grammy": "^1.42.0",
|
|
69
69
|
"markdown-it": "^14.1.1",
|
package/polygram.js
CHANGED
|
@@ -29,6 +29,9 @@ const {
|
|
|
29
29
|
resolveSessionForSpawn,
|
|
30
30
|
} = require('./lib/db/sessions');
|
|
31
31
|
const { buildPrompt, resolvePromptBackend } = require('./lib/prompt');
|
|
32
|
+
const { countInFlight } = require('./lib/queue-utils');
|
|
33
|
+
const { createIpcHandlers } = require('./lib/ipc/handlers');
|
|
34
|
+
const { classifyOrphanSweep } = require('./lib/ops/tmux-preflight');
|
|
32
35
|
const { filterAttachments, resolveFileCaps, resolveMaxFileOverride, MAX_TOTAL_BYTES } = require('./lib/attachments');
|
|
33
36
|
// 0.9.0: SDK ProcessManager is the only pm. CLI pm
|
|
34
37
|
// (lib/process-manager.js) deleted in commit 6.
|
|
@@ -3165,6 +3168,12 @@ async function main() {
|
|
|
3165
3168
|
}
|
|
3166
3169
|
const sessionLauncher = process.env.ORCHESTRA_SESSION_LAUNCHER;
|
|
3167
3170
|
const requireExistingServer = process.env.ORCHESTRA_TMUX_REQUIRE_SERVER === '1';
|
|
3171
|
+
// Run against a dedicated tmux server (`tmux -L <name>`) instead of the shared
|
|
3172
|
+
// default socket. Unset keeps today's behaviour. Env rather than config
|
|
3173
|
+
// because the value has to match the tmux service unit that owns that server,
|
|
3174
|
+
// and both are declared in the same systemd file; it is also per-app, while
|
|
3175
|
+
// config here is per-bot and the two bots share one server.
|
|
3176
|
+
const tmuxSocketName = process.env.ORCHESTRA_TMUX_SOCKET || null;
|
|
3168
3177
|
console.log(`[polygram] session containment configured: ${sessionLauncher ? 'yes' : 'no'}`);
|
|
3169
3178
|
|
|
3170
3179
|
// rc.50: claim our PID file BEFORE binding the bot token. If a
|
|
@@ -3183,24 +3192,47 @@ async function main() {
|
|
|
3183
3192
|
// outlive their parent process — without this, the new daemon's
|
|
3184
3193
|
// TmuxProcess.start() hits EEXIST on session spawn for any chat
|
|
3185
3194
|
// routed to pm:'tmux'. See lib/tmux/orphan-sweep.js for rationale.
|
|
3195
|
+
let sweepResult = null;
|
|
3196
|
+
let sweepError = null;
|
|
3186
3197
|
try {
|
|
3187
3198
|
// Sweep must look for polygram's session prefix — orchestra's default runner
|
|
3188
3199
|
// filters 'orchestra-<bot>-', which would never match our 'polygram-<bot>-'
|
|
3189
3200
|
// sessions (dead safety net + EEXIST on cli respawn of a leaked session).
|
|
3190
|
-
|
|
3201
|
+
sweepResult = await sweepTmuxOrphans({
|
|
3191
3202
|
botName: BOT_NAME,
|
|
3192
3203
|
runner: createTmuxRunner({
|
|
3193
3204
|
logger: console,
|
|
3194
3205
|
sessionPrefix: 'polygram',
|
|
3195
3206
|
requireExistingServer,
|
|
3207
|
+
socketName: tmuxSocketName,
|
|
3196
3208
|
}),
|
|
3209
|
+
socketName: tmuxSocketName,
|
|
3197
3210
|
logger: console,
|
|
3198
3211
|
});
|
|
3199
|
-
if (
|
|
3200
|
-
console.log(`[orphan-sweep] killed ${
|
|
3212
|
+
if (sweepResult.swept.length > 0) {
|
|
3213
|
+
console.log(`[orphan-sweep] killed ${sweepResult.swept.length} stale tmux session(s)`);
|
|
3201
3214
|
}
|
|
3202
3215
|
} catch (err) {
|
|
3203
|
-
|
|
3216
|
+
sweepError = err;
|
|
3217
|
+
console.warn?.(`[orphan-sweep] failed: ${err.message}`);
|
|
3218
|
+
}
|
|
3219
|
+
// When we are forbidden from creating the tmux server, an unreachable one is
|
|
3220
|
+
// terminal: every tmux-backed turn would fail while systemd still reported
|
|
3221
|
+
// this unit healthy. Decide before the DB is opened or any inbound is polled.
|
|
3222
|
+
{
|
|
3223
|
+
const verdict = classifyOrphanSweep({
|
|
3224
|
+
sweep: sweepResult,
|
|
3225
|
+
error: sweepError,
|
|
3226
|
+
requireExistingServer,
|
|
3227
|
+
});
|
|
3228
|
+
if (verdict.fatal) {
|
|
3229
|
+
console.error(
|
|
3230
|
+
`[fatal] tmux server required but unusable (${verdict.reason}). `
|
|
3231
|
+
+ `Start the tmux service${tmuxSocketName ? ` (socket '${tmuxSocketName}')` : ''} before this bot.`,
|
|
3232
|
+
);
|
|
3233
|
+
process.exit(2);
|
|
3234
|
+
return;
|
|
3235
|
+
}
|
|
3204
3236
|
}
|
|
3205
3237
|
|
|
3206
3238
|
try {
|
|
@@ -3588,6 +3620,7 @@ async function main() {
|
|
|
3588
3620
|
logger: console,
|
|
3589
3621
|
sessionPrefix: 'polygram',
|
|
3590
3622
|
requireExistingServer,
|
|
3623
|
+
socketName: tmuxSocketName,
|
|
3591
3624
|
});
|
|
3592
3625
|
// Verify the pinned claude CLI binary is present. The tmux
|
|
3593
3626
|
// backend spawns this exact binary by absolute path (see
|
|
@@ -3991,6 +4024,12 @@ async function main() {
|
|
|
3991
4024
|
const shutdown = async () => {
|
|
3992
4025
|
if (isShuttingDown) return;
|
|
3993
4026
|
const shutdownObservation = cgroupOomObserver.sample();
|
|
4027
|
+
// Sample in-flight work at SIGNAL time, alongside the OOM observation and
|
|
4028
|
+
// before anything below can change it. The drain's own `in_flight` is
|
|
4029
|
+
// measured after the wait, and after a lost bridge has already rejected
|
|
4030
|
+
// every pending handler — so it reads 0 whether the daemon was busy or
|
|
4031
|
+
// idle, and cannot answer "how much work did this restart cost?".
|
|
4032
|
+
const inFlightAtSignal = countInFlight(inFlightHandlers);
|
|
3994
4033
|
isShuttingDown = true;
|
|
3995
4034
|
console.log('\nShutting down...');
|
|
3996
4035
|
// 1. Stop accepting new inbound first so nothing new queues behind the drain.
|
|
@@ -4074,8 +4113,7 @@ async function main() {
|
|
|
4074
4113
|
await new Promise((r) => setTimeout(r, 100));
|
|
4075
4114
|
}
|
|
4076
4115
|
const drainElapsed = Date.now() - drainStart;
|
|
4077
|
-
|
|
4078
|
-
for (const n of inFlightHandlers.values()) remaining += n;
|
|
4116
|
+
const remaining = countInFlight(inFlightHandlers);
|
|
4079
4117
|
|
|
4080
4118
|
// 3. A handled signal is normally deliberate, but a Linux supervisor can
|
|
4081
4119
|
// also stop the service after an OOM-killed child. Persist crash-like
|
|
@@ -4092,13 +4130,14 @@ async function main() {
|
|
|
4092
4130
|
logEvent('shutdown-drain', {
|
|
4093
4131
|
bot: BOT_NAME,
|
|
4094
4132
|
in_flight: remaining,
|
|
4133
|
+
in_flight_at_signal: inFlightAtSignal,
|
|
4095
4134
|
replay_marked: res.replayMarked,
|
|
4096
4135
|
elapsed_ms: drainElapsed,
|
|
4097
4136
|
clean: res.clean,
|
|
4098
4137
|
shutdown_reason: res.shutdownReason,
|
|
4099
4138
|
...(res.oomKillDelta != null ? { oom_kill_delta: res.oomKillDelta } : {}),
|
|
4100
4139
|
});
|
|
4101
|
-
console.log(`[shutdown] ${res.clean ? 'clean' : 'crash-like'} shutdown recorded (${res.shutdownReason}); drained ${drainElapsed}ms, ${remaining} in-flight, ${res.replayMarked} marked replay-pending`);
|
|
4140
|
+
console.log(`[shutdown] ${res.clean ? 'clean' : 'crash-like'} shutdown recorded (${res.shutdownReason}); ${inFlightAtSignal} in-flight at signal, drained ${drainElapsed}ms, ${remaining} still in-flight, ${res.replayMarked} marked replay-pending`);
|
|
4102
4141
|
} catch (err) {
|
|
4103
4142
|
console.error(`[shutdown] persistence failed: ${err.message}`);
|
|
4104
4143
|
}
|
|
@@ -4150,10 +4189,11 @@ async function main() {
|
|
|
4150
4189
|
ipcCloser = await ipcServer.start({
|
|
4151
4190
|
path: ipcServer.socketPathFor(BOT_NAME),
|
|
4152
4191
|
secret: ipcSecret,
|
|
4153
|
-
handlers: {
|
|
4154
|
-
|
|
4155
|
-
|
|
4156
|
-
|
|
4192
|
+
handlers: createIpcHandlers({
|
|
4193
|
+
botName: BOT_NAME,
|
|
4194
|
+
getInFlightHandlers: () => inFlightHandlers,
|
|
4195
|
+
handleSendOverIpc: (req) => handleSendOverIpc(req),
|
|
4196
|
+
}),
|
|
4157
4197
|
logger: console,
|
|
4158
4198
|
});
|
|
4159
4199
|
} catch (err) {
|