polygram 0.30.0 → 0.32.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.
@@ -59,6 +59,18 @@ const DEFAULT_CODEX_AVAILABILITY = Object.freeze({
59
59
  const MAX_CONFIG_VALUE_LENGTH = 4096;
60
60
  const assertedReceiptByAvailability = new WeakMap();
61
61
 
62
+ function processMatchesRuntime(proc, runtime, backend) {
63
+ if (!proc || proc.closed) return false;
64
+ const processRuntime = (
65
+ proc.runtime === 'codex'
66
+ || proc.backend === 'codex'
67
+ ) ? 'codex' : 'claude';
68
+ if (processRuntime !== runtime) return false;
69
+ return runtime === 'codex'
70
+ ? backend === 'codex'
71
+ : proc.backend === backend;
72
+ }
73
+
62
74
  class RuntimeConfigError extends Error {
63
75
  constructor(message, {
64
76
  code,
@@ -343,17 +355,16 @@ function resolveRuntimeConfig({
343
355
  }
344
356
 
345
357
  /**
346
- * Resolve only the operator-selected Codex inputs needed to run the matching
347
- * preflight. This does not make Codex available and carries no receipt.
358
+ * Resolve the prospective Codex inputs for one chat/topic without consulting
359
+ * its currently selected runtime. This supports preflight before an atomic
360
+ * runtime switch; it does not make Codex available and carries no receipt.
348
361
  */
349
- function resolveCodexRuntimeRequest({
362
+ function resolveCodexRuntimeCandidate({
350
363
  config = {},
351
364
  chatId = null,
352
365
  threadId = null,
353
- defaultPm = 'sdk',
354
366
  } = {}) {
355
- const pmChoice = resolvePmChoice(config, chatId, threadId, defaultPm);
356
- if (!chatId || pmChoice.value !== 'codex') return null;
367
+ if (!chatId) return null;
357
368
 
358
369
  const scopes = configScopes(config, chatId, threadId);
359
370
  const modelChoice = resolveScopedValue(
@@ -368,7 +379,6 @@ function resolveCodexRuntimeRequest({
368
379
  );
369
380
  const cwdChoice = resolveScopedValue(scopes.codexSpawn, 'cwd', null);
370
381
  const sources = Object.freeze({
371
- pm: pmChoice.source,
372
382
  model: modelChoice.source,
373
383
  effort: effortChoice.source,
374
384
  cwd: cwdChoice.source,
@@ -398,6 +408,33 @@ function resolveCodexRuntimeRequest({
398
408
  });
399
409
  }
400
410
 
411
+ /**
412
+ * Resolve only the operator-selected Codex inputs needed to run the matching
413
+ * preflight. This does not make Codex available and carries no receipt.
414
+ */
415
+ function resolveCodexRuntimeRequest({
416
+ config = {},
417
+ chatId = null,
418
+ threadId = null,
419
+ defaultPm = 'sdk',
420
+ } = {}) {
421
+ const pmChoice = resolvePmChoice(config, chatId, threadId, defaultPm);
422
+ if (!chatId || pmChoice.value !== 'codex') return null;
423
+
424
+ const candidate = resolveCodexRuntimeCandidate({
425
+ config,
426
+ chatId,
427
+ threadId,
428
+ });
429
+ return Object.freeze({
430
+ ...candidate,
431
+ sources: Object.freeze({
432
+ pm: pmChoice.source,
433
+ ...candidate.sources,
434
+ }),
435
+ });
436
+ }
437
+
401
438
  function configScopes(config, chatId, threadId) {
402
439
  const hasChat = Boolean(chatId);
403
440
  const chat = hasChat ? config?.chats?.[chatId] : null;
@@ -598,7 +635,9 @@ function stableRuntimeConfigIdentity(fields) {
598
635
 
599
636
  module.exports = {
600
637
  createCodexRuntimeAvailability,
638
+ processMatchesRuntime,
601
639
  RuntimeConfigError,
640
+ resolveCodexRuntimeCandidate,
602
641
  resolveCodexRuntimeRequest,
603
642
  resolveRuntimeConfig,
604
643
  resolveRuntimeDescriptor,
@@ -65,6 +65,7 @@ function createSdkCallbacks({
65
65
  // — visuals for cycles with NO pending turn (wakeups, fireUserMessage
66
66
  // self-checks, injected messages picked up as their own cycle). Optional.
67
67
  sessionFeedback = null,
68
+ deliveryBarrier = null,
68
69
  logger = console,
69
70
  } = {}) {
70
71
  // 0.13 P4: the rc.9 extraTurnTracker (tmux NEW-TURN typing/✍ bridge) was
@@ -158,6 +159,7 @@ function createSdkCallbacks({
158
159
  text: '⏹ Background work ended (session restarted).',
159
160
  }, { source: 'bg-work-status', botName }).catch(() => {});
160
161
  }
162
+ deliveryBarrier?.retireSession?.(sessionKey);
161
163
  },
162
164
 
163
165
  onStreamChunk: (sessionKey, partial, entry) => {
@@ -30,6 +30,7 @@ const {
30
30
  const { isSafeToRetry, redactBotToken } = require('../error/net');
31
31
  const { coerceFileParams, localFileBytes, FILE_FIELD_BY_METHOD } = require('./input-file');
32
32
  const { resolveFileCaps, resolveMaxFileOverride } = require('../attachments');
33
+ const { getSessionKey } = require('../session-key');
33
34
 
34
35
  // Topic deletion race: a user can delete a forum topic while a turn is in
35
36
  // flight, turning a valid `message_thread_id` into a 404. Telegram's error
@@ -435,8 +436,75 @@ async function send({ bot, method, params, db = null, meta = {}, logger = consol
435
436
  return res;
436
437
  }
437
438
 
438
- function createSender(db, logger = console, config = null) {
439
- return (bot, method, params, meta) => send({ bot, method, params, db, meta, logger, config });
439
+ const OPERATIONAL_UI_METHODS = new Set([
440
+ 'sendChatAction',
441
+ 'setMessageReaction',
442
+ ]);
443
+ const REPLY_BEARING_METHODS = new Set([
444
+ 'deleteMessage',
445
+ 'editMessageCaption',
446
+ 'editMessageMedia',
447
+ 'editMessageReplyMarkup',
448
+ 'editMessageText',
449
+ 'sendAnimation',
450
+ 'sendAudio',
451
+ 'sendDocument',
452
+ 'sendMessage',
453
+ 'sendPhoto',
454
+ 'sendRichMessage',
455
+ 'sendSticker',
456
+ 'sendVideo',
457
+ 'sendVoice',
458
+ ]);
459
+
460
+ function defaultDeliveryClass(method) {
461
+ if (OPERATIONAL_UI_METHODS.has(method)) return 'operational-ui';
462
+ if (REPLY_BEARING_METHODS.has(method)) return 'reply-bearing';
463
+ return null;
464
+ }
465
+
466
+ function deliverySessionKey(params, meta, config) {
467
+ if (meta.sessionKey != null) return meta.sessionKey;
468
+ if (params.chat_id == null) return null;
469
+ const chatId = String(params.chat_id);
470
+ const threadId = params.message_thread_id == null
471
+ ? null
472
+ : String(params.message_thread_id);
473
+ return getSessionKey(chatId, threadId, config?.chats?.[chatId]);
474
+ }
475
+
476
+ function deliverySourceMsgId(params, meta) {
477
+ const value = meta.sourceMsgId ?? params.reply_parameters?.message_id ?? null;
478
+ if (value == null) return null;
479
+ const numeric = Number(value);
480
+ return Number.isSafeInteger(numeric) ? numeric : null;
481
+ }
482
+
483
+ function createSender(db, logger = console, config = null, deliveryBarrier = null) {
484
+ return (bot, method, params, meta = {}) => {
485
+ const operation = () => send({
486
+ bot,
487
+ method,
488
+ params,
489
+ db,
490
+ meta,
491
+ logger,
492
+ config,
493
+ });
494
+ if (!deliveryBarrier) return operation();
495
+ return deliveryBarrier.run({
496
+ sessionKey: deliverySessionKey(params, meta, config),
497
+ sourceMsgId: deliverySourceMsgId(params, meta),
498
+ deliveryClass: meta.deliveryClass ?? defaultDeliveryClass(method),
499
+ }, operation);
500
+ };
440
501
  }
441
502
 
442
- module.exports = { send, createSender, nextPendingId };
503
+ module.exports = {
504
+ send,
505
+ createSender,
506
+ nextPendingId,
507
+ defaultDeliveryClass,
508
+ deliverySessionKey,
509
+ deliverySourceMsgId,
510
+ };
@@ -0,0 +1,117 @@
1
+ 'use strict';
2
+
3
+ const DELIVERY_CLASSES = new Set(['reply-bearing', 'operational-ui']);
4
+
5
+ function deliveryBarrierError() {
6
+ const error = new Error('reply-bearing Telegram delivery is fenced');
7
+ error.code = 'DELIVERY_FENCED';
8
+ return error;
9
+ }
10
+
11
+ function createDeliveryBarrier() {
12
+ let fenced = false;
13
+ const outputSourcesBySession = new Map();
14
+ const uncorrelatedOutput = new Set();
15
+ const pending = new Set();
16
+ const pendingBySession = new Map();
17
+ const forgetWhenIdle = new Set();
18
+
19
+ function forget(sessionKey) {
20
+ outputSourcesBySession.delete(sessionKey);
21
+ uncorrelatedOutput.delete(sessionKey);
22
+ forgetWhenIdle.delete(sessionKey);
23
+ }
24
+
25
+ function inspect(sessionKey, sourceMsgId = null) {
26
+ const outputSources = outputSourcesBySession.get(sessionKey);
27
+ return {
28
+ outputAttempted: uncorrelatedOutput.has(sessionKey)
29
+ || (
30
+ sourceMsgId == null
31
+ ? (outputSources?.size ?? 0) > 0
32
+ : outputSources?.has(sourceMsgId) === true
33
+ ),
34
+ pending: pendingBySession.get(sessionKey)?.size ?? 0,
35
+ fenced,
36
+ };
37
+ }
38
+
39
+ function run({
40
+ sessionKey = null,
41
+ sourceMsgId = null,
42
+ deliveryClass,
43
+ } = {}, operation) {
44
+ if (!DELIVERY_CLASSES.has(deliveryClass)) {
45
+ return Promise.reject(new TypeError('Telegram delivery class is invalid'));
46
+ }
47
+ if (typeof operation !== 'function') {
48
+ return Promise.reject(new TypeError('Telegram delivery operation is required'));
49
+ }
50
+ if (deliveryClass === 'operational-ui') {
51
+ return Promise.resolve().then(operation);
52
+ }
53
+ if (fenced) return Promise.reject(deliveryBarrierError());
54
+
55
+ if (sessionKey != null) {
56
+ forgetWhenIdle.delete(sessionKey);
57
+ if (sourceMsgId == null) uncorrelatedOutput.add(sessionKey);
58
+ else {
59
+ let outputSources = outputSourcesBySession.get(sessionKey);
60
+ if (!outputSources) {
61
+ outputSources = new Set();
62
+ outputSourcesBySession.set(sessionKey, outputSources);
63
+ }
64
+ outputSources.add(sourceMsgId);
65
+ }
66
+ }
67
+ const operationPromise = Promise.resolve().then(operation);
68
+ pending.add(operationPromise);
69
+ if (sessionKey != null) {
70
+ let sessionPending = pendingBySession.get(sessionKey);
71
+ if (!sessionPending) {
72
+ sessionPending = new Set();
73
+ pendingBySession.set(sessionKey, sessionPending);
74
+ }
75
+ sessionPending.add(operationPromise);
76
+ }
77
+ operationPromise.finally(() => {
78
+ pending.delete(operationPromise);
79
+ if (sessionKey == null) return;
80
+ const sessionPending = pendingBySession.get(sessionKey);
81
+ sessionPending?.delete(operationPromise);
82
+ if (sessionPending?.size === 0) {
83
+ pendingBySession.delete(sessionKey);
84
+ if (forgetWhenIdle.has(sessionKey)) forget(sessionKey);
85
+ }
86
+ }).catch(() => {});
87
+ return operationPromise;
88
+ }
89
+
90
+ async function fenceAndDrain() {
91
+ fenced = true;
92
+ while (pending.size > 0) {
93
+ await Promise.allSettled([...pending]);
94
+ }
95
+ return {
96
+ pending: 0,
97
+ };
98
+ }
99
+
100
+ function retireSession(sessionKey) {
101
+ if ((pendingBySession.get(sessionKey)?.size ?? 0) > 0) {
102
+ forgetWhenIdle.add(sessionKey);
103
+ return;
104
+ }
105
+ forget(sessionKey);
106
+ }
107
+
108
+ return {
109
+ run,
110
+ inspect,
111
+ fenceAndDrain,
112
+ retireSession,
113
+ isFenced: () => fenced,
114
+ };
115
+ }
116
+
117
+ module.exports = { createDeliveryBarrier };
@@ -83,7 +83,8 @@
83
83
  * @param {?string|number} [opts.sessionKey] — for event payloads
84
84
  * @param {object} [opts.logger] — { log, error }
85
85
  * @returns {Promise<{ deliverResult: ?object, stickersSent: number, reactionsApplied: number,
86
- * reactionsDropped: number, sanitizerReplaced: boolean, secretsRedacted: number,
86
+ * reactionsDropped: number, auxiliaryFailures: number, deliveryAmbiguous: boolean,
87
+ * sanitizerReplaced: boolean, secretsRedacted: number,
87
88
  * emptiedByStrategy?: boolean }>} — `emptiedByStrategy` marks a reply whose text
88
89
  * projected away entirely, so nothing was delivered and the caller must decide
89
90
  * what to tell the agent.
@@ -116,6 +117,8 @@ async function processAndDeliverAgentText({
116
117
  stickersSent: 0,
117
118
  reactionsApplied: 0,
118
119
  reactionsDropped: 0,
120
+ auxiliaryFailures: 0,
121
+ deliveryAmbiguous: false,
119
122
  sanitizerReplaced: false,
120
123
  secretsRedacted: 0,
121
124
  };
@@ -259,6 +262,8 @@ async function processAndDeliverAgentText({
259
262
  });
260
263
  summary.stickersSent += 1;
261
264
  } catch (err) {
265
+ summary.auxiliaryFailures += 1;
266
+ summary.deliveryAmbiguous = true;
262
267
  logger.error?.(`[${source}] sendSticker(${parsed.stickerLabel}) failed: ${err.message}`);
263
268
  }
264
269
  }
@@ -278,6 +283,8 @@ async function processAndDeliverAgentText({
278
283
  });
279
284
  summary.stickersSent += 1;
280
285
  } catch (err) {
286
+ summary.auxiliaryFailures += 1;
287
+ summary.deliveryAmbiguous = true;
281
288
  logger.error?.(`[${source}] inline sendSticker(${s.name}) failed: ${err.message}`);
282
289
  }
283
290
  }
@@ -312,9 +319,18 @@ async function processAndDeliverAgentText({
312
319
  chat_id: chatId,
313
320
  message_id: replyToMessageId,
314
321
  reaction: [{ type: 'emoji', emoji }],
315
- }, { ...meta, source: `${source}-reaction`, reaction: emoji });
322
+ }, {
323
+ ...meta,
324
+ sessionKey,
325
+ sourceMsgId: meta.sourceMsgId ?? replyToMessageId,
326
+ deliveryClass: 'reply-bearing',
327
+ source: `${source}-reaction`,
328
+ reaction: emoji,
329
+ });
316
330
  summary.reactionsApplied += 1;
317
331
  } catch (err) {
332
+ summary.auxiliaryFailures += 1;
333
+ summary.deliveryAmbiguous = true;
318
334
  logger.error?.(`[${source}] setMessageReaction(${emoji}) failed: ${err.message}`);
319
335
  }
320
336
  if (allReactions.length > 1) {
@@ -115,7 +115,7 @@ function defaultMakeInputFile(source, bytes = null) {
115
115
  * and the SAME tree, flattened, was accepted. The two differ in exactly one
116
116
  * respect, which is what makes it evidence about styling.
117
117
  * @param {() => void} [deps.onStylingAccepted] — a styled payload landed
118
- * @returns {(args: {bot, chatId: string, threadId: (string|null), messageId: number, blocks: Array, sourceText: string, phase?: string, mediaContext?: object, hadReplyAnchor?: boolean}) => Promise<{result: *, wentRich: boolean, bubbleRemoved?: boolean}>}
118
+ * @returns {(args: {bot, chatId: string, threadId: (string|null), messageId: number, blocks: Array, sourceText: string, phase?: string, mediaContext?: object, hadReplyAnchor?: boolean, meta?: object}) => Promise<{result: *, wentRich: boolean, bubbleRemoved?: boolean}>}
119
119
  */
120
120
  function createRichEditor({
121
121
  tg,
@@ -169,11 +169,12 @@ function createRichEditor({
169
169
  phase = 'preview',
170
170
  mediaContext = null,
171
171
  hadReplyAnchor = false,
172
+ meta = {},
172
173
  }) {
173
174
  if (getRichKnownUnsupported()) {
174
175
  const res = await tg(bot, 'editMessageText', {
175
176
  chat_id: chatId, message_id: messageId, text: sanitizeFallbackText(sourceText),
176
- }, { source: 'bot-reply-stream-edit-rich-fallback', botName });
177
+ }, { ...meta, source: 'bot-reply-stream-edit-rich-fallback', botName });
177
178
  return { result: res, wentRich: false };
178
179
  }
179
180
 
@@ -190,7 +191,12 @@ function createRichEditor({
190
191
  mediaContext?.preflightMedia,
191
192
  ),
192
193
  },
193
- }, { source: 'bot-reply-stream-edit-rich', botName, richSourceText: sourceText });
194
+ }, {
195
+ ...meta,
196
+ source: 'bot-reply-stream-edit-rich',
197
+ botName,
198
+ richSourceText: sourceText,
199
+ });
194
200
  latch.recordHealthyOutcome();
195
201
  if (blocksAreStyled(blocks)) {
196
202
  try { onStylingAccepted(); } catch { /* a verdict must not cost a delivered edit */ }
@@ -280,7 +286,12 @@ function createRichEditor({
280
286
  mediaContext?.preflightMedia,
281
287
  ),
282
288
  },
283
- }, { source: 'bot-reply-stream-edit-rich-unstyled', botName, richSourceText: sourceText });
289
+ }, {
290
+ ...meta,
291
+ source: 'bot-reply-stream-edit-rich-unstyled',
292
+ botName,
293
+ richSourceText: sourceText,
294
+ });
284
295
  if (!limitRefusal) {
285
296
  try { onStylingRejected(); } catch { /* the edit landed either way */ }
286
297
  }
@@ -324,7 +335,7 @@ function createRichEditor({
324
335
  // single owner of discard/redelivery.
325
336
  const fallbackRes = await tg(bot, 'editMessageText', {
326
337
  chat_id: chatId, message_id: messageId, text: fallbackText,
327
- }, { source: 'bot-reply-stream-edit-rich-fallback', botName });
338
+ }, { ...meta, source: 'bot-reply-stream-edit-rich-fallback', botName });
328
339
 
329
340
  if (canRescue) {
330
341
  await rescueBestEffort({
@@ -630,6 +630,8 @@ function createMediaDeliveryContext({
630
630
  threadId = null,
631
631
  replyToMessageId = null,
632
632
  botName = null,
633
+ sessionKey = null,
634
+ sourceMsgId = null,
633
635
  logEvent = null,
634
636
  setDeliveryError = () => {},
635
637
  logger = console,
@@ -665,7 +667,13 @@ function createMediaDeliveryContext({
665
667
  await tg(bot, 'deleteMessage', {
666
668
  chat_id: chatId,
667
669
  message_id: messageId,
668
- }, { ...meta, source: 'bot-reply-rich-media-placeholder-delete', botName });
670
+ }, {
671
+ sessionKey,
672
+ sourceMsgId,
673
+ ...meta,
674
+ source: 'bot-reply-rich-media-placeholder-delete',
675
+ botName,
676
+ });
669
677
  return true;
670
678
  } catch (err) {
671
679
  recordFailure('deletion');
@@ -713,6 +721,8 @@ function createMediaDeliveryContext({
713
721
  }
714
722
  try {
715
723
  const result = await tg(bot, rescue.method, params, {
724
+ sessionKey,
725
+ sourceMsgId,
716
726
  ...meta,
717
727
  source: 'bot-reply-rich-media-rescue',
718
728
  botName,
@@ -788,7 +798,13 @@ function createMediaDeliveryContext({
788
798
  chat_id: chatId,
789
799
  text: `⚠️ ${parts.join(' and ')} failed. The reply may be ${risks.join(' or ')} — please retry.`,
790
800
  ...(threadId != null && { message_thread_id: threadId }),
791
- }, { ...meta, source: 'partial-delivery-warning', botName });
801
+ }, {
802
+ sessionKey,
803
+ sourceMsgId,
804
+ ...meta,
805
+ source: 'partial-delivery-warning',
806
+ botName,
807
+ });
792
808
  } catch (err) {
793
809
  logger.warn?.('[rich-media] partial-delivery warning failed');
794
810
  }
@@ -0,0 +1,24 @@
1
+ -- One-shot ownership for a CLI turn interrupted by a deliberate restart.
2
+ --
3
+ -- generation_id is a non-identity reference token. It lets a restart intent
4
+ -- prove that the authoritative provider-session row was not replaced between
5
+ -- shutdown and boot without copying provider session identity into the intent.
6
+
7
+ ALTER TABLE agent_runtime_sessions ADD COLUMN generation_id TEXT;
8
+
9
+ UPDATE agent_runtime_sessions
10
+ SET generation_id = lower(hex(randomblob(16)))
11
+ WHERE generation_id IS NULL;
12
+
13
+ CREATE UNIQUE INDEX idx_agent_runtime_sessions_generation_id
14
+ ON agent_runtime_sessions(generation_id);
15
+
16
+ CREATE TABLE clean_restart_resume_intents (
17
+ bot_name TEXT NOT NULL,
18
+ session_key TEXT NOT NULL,
19
+ session_generation_id TEXT NOT NULL,
20
+ source_message_id INTEGER NOT NULL,
21
+ shutdown_at INTEGER NOT NULL,
22
+ policy_version INTEGER NOT NULL,
23
+ PRIMARY KEY(bot_name, session_key)
24
+ );
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "polygram",
3
- "version": "0.30.0",
3
+ "version": "0.32.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.10.5",
66
+ "@shumkov/orchestra": "0.10.6",
67
67
  "better-sqlite3": "^12.9.0",
68
68
  "grammy": "^1.42.0",
69
69
  "markdown-it": "^14.1.1",