polygram 0.23.2 → 0.24.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 +9 -0
- package/lib/config-override.js +33 -0
- package/lib/db.js +19 -0
- package/lib/error/net.js +6 -1
- package/lib/ops/heartbeat.js +19 -4
- package/lib/process/channels-tool-dispatcher.js +67 -0
- package/lib/sdk/build-options.js +7 -1
- package/lib/sdk/callbacks.js +26 -1
- package/lib/telegram/api.js +30 -6
- package/lib/telegram/deliver-strategy.js +52 -0
- package/lib/telegram/display-hint.js +24 -7
- package/lib/telegram/live-preview.js +403 -0
- package/lib/telegram/process-agent-reply.js +90 -14
- package/lib/telegram/rich-capability-latch.js +95 -0
- package/lib/telegram/rich-dispatch.js +134 -0
- package/lib/telegram/rich-edit.js +30 -6
- package/lib/telegram/rich-send.js +237 -0
- package/lib/telegram/rich.js +132 -21
- package/lib/telegram/streamer.js +43 -2
- package/package.json +2 -2
- package/polygram.js +349 -24
package/polygram.js
CHANGED
|
@@ -111,11 +111,15 @@ const { sweepInbox } = require('./lib/db/inbox');
|
|
|
111
111
|
const { parseBotArg, parseDbArg, filterConfigToBot, activeBotConfig } = require('./lib/config-scope');
|
|
112
112
|
const { createStore: createPairingsStore, parseTtl: parsePairingTtl } = require('./lib/db/pairings');
|
|
113
113
|
const { transcribe: transcribeVoice, isVoiceAttachment } = require('./lib/telegram/voice');
|
|
114
|
-
const { createStreamer } = require('./lib/telegram/streamer');
|
|
114
|
+
const { createStreamer, DEFAULT_THROTTLE_MS } = require('./lib/telegram/streamer');
|
|
115
|
+
const {
|
|
116
|
+
createStreamerRegistry, createDeliverTextFactory, createTurnSettler,
|
|
117
|
+
resolveStreamPreviewEnabled,
|
|
118
|
+
} = require('./lib/telegram/live-preview');
|
|
115
119
|
const { chunkMarkdownText } = require('./lib/telegram/chunk');
|
|
116
120
|
const {
|
|
117
121
|
toTelegramRichBlocks, resolveRichTextEnabled, isRichCapabilityError, isRichContentError,
|
|
118
|
-
stripMediaMarkdown,
|
|
122
|
+
isRichCapabilityErrorExplicit, isRichMessageFieldRejection, stripMediaMarkdown,
|
|
119
123
|
} = require('./lib/telegram/rich');
|
|
120
124
|
const {
|
|
121
125
|
createRichMediaResolver,
|
|
@@ -126,6 +130,15 @@ const {
|
|
|
126
130
|
OTHER_MEDIA_UPLOAD_CEILING,
|
|
127
131
|
} = require('./lib/telegram/rich-media');
|
|
128
132
|
const { createRichEditor } = require('./lib/telegram/rich-edit');
|
|
133
|
+
const { createRichCapabilityLatch } = require('./lib/telegram/rich-capability-latch');
|
|
134
|
+
|
|
135
|
+
// What a reply consisting only of media the delivering path cannot render
|
|
136
|
+
// degrades to. Silence would leave the user with nothing and the agent
|
|
137
|
+
// believing it answered.
|
|
138
|
+
const MEDIA_ONLY_FALLBACK_TEXT = '(media unavailable)';
|
|
139
|
+
const { createRichSender } = require('./lib/telegram/rich-send');
|
|
140
|
+
const { createRichDeliveryFactory } = require('./lib/telegram/rich-dispatch');
|
|
141
|
+
const { composeDeliverTextFactories } = require('./lib/telegram/deliver-strategy');
|
|
129
142
|
const { buildPolygramDisplayHint } = require('./lib/telegram/display-hint');
|
|
130
143
|
const { redactBotToken, stripUrlCredentials } = require('./lib/error/net');
|
|
131
144
|
// F#23: shared agent-reply helper. parseResponse + sanitizer + chunked
|
|
@@ -214,6 +227,15 @@ let mediaBuffer = null; // media-group coalescing buffer, created in createBot;
|
|
|
214
227
|
// specific turn (not the session). The old per-session Maps were a bug
|
|
215
228
|
// for concurrent pendings — the second send() would overwrite the first's
|
|
216
229
|
// streamer reference before the first turn finished.
|
|
230
|
+
//
|
|
231
|
+
// The registry below is the OTHER direction: the CLI reply path runs in the
|
|
232
|
+
// channels dispatcher, a different call stack that has only a sessionKey, and
|
|
233
|
+
// it must find the turn's live preview to consume it instead of sending a
|
|
234
|
+
// second bubble underneath. It also answers "how many previews are live in this
|
|
235
|
+
// chat right now" for the per-chat edit throttle. Entries live for the span of
|
|
236
|
+
// one dispatched turn (registered just before dispatch, released in the
|
|
237
|
+
// handler's finally).
|
|
238
|
+
const streamerRegistry = createStreamerRegistry();
|
|
217
239
|
|
|
218
240
|
// Allowlist of env var names passed through to spawned Claude processes.
|
|
219
241
|
// Anything not listed here is dropped to prevent leaked secrets/ssh agents
|
|
@@ -333,12 +355,47 @@ function logEvent(kind, detail) {
|
|
|
333
355
|
dbWrite(() => db.logEvent(kind, detail), `log ${kind}`);
|
|
334
356
|
}
|
|
335
357
|
|
|
358
|
+
// The chunked deliverer, wrapped so the live-preview coverage set learns
|
|
359
|
+
// whether a reply actually landed.
|
|
360
|
+
//
|
|
361
|
+
// A reply the preview strategy passed through counts as delivered only once it
|
|
362
|
+
// lands. Recording it at hand-off would let a FAILED reply make a later draft
|
|
363
|
+
// look redundant, and the draft — the only copy the user would ever get — would
|
|
364
|
+
// be deleted at turn end.
|
|
365
|
+
async function deliverRepliesTracked(opts) {
|
|
366
|
+
const sessionKey = opts?.meta?.sessionKey;
|
|
367
|
+
try {
|
|
368
|
+
const res = await deliverReplies(opts);
|
|
369
|
+
streamerRegistry.settlePending(sessionKey, (res?.failed?.length || 0) === 0);
|
|
370
|
+
return res;
|
|
371
|
+
} catch (err) {
|
|
372
|
+
streamerRegistry.settlePending(sessionKey, false);
|
|
373
|
+
throw err;
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
// A streamed bubble's `messages` row is written by the INITIAL send — the first
|
|
378
|
+
// ~30 characters — and no later edit revisits it, so the transcript would keep
|
|
379
|
+
// a torso of every streamed answer. Call this whenever a bubble is finalized.
|
|
380
|
+
function persistBubbleText(chatId, msgId, text) {
|
|
381
|
+
if (msgId == null || typeof text !== 'string' || text.length === 0) return;
|
|
382
|
+
dbWrite(
|
|
383
|
+
() => db.updateOutboundText({ chat_id: chatId, msg_id: msgId, text }),
|
|
384
|
+
'update streamed bubble text',
|
|
385
|
+
);
|
|
386
|
+
}
|
|
387
|
+
|
|
336
388
|
// One bot runs per process, so rich-message capability can be represented
|
|
337
389
|
// by one process-wide boolean rather than a per-connection map. Set once by
|
|
338
390
|
// isRichCapabilityError (endpoint missing/404) and never cleared for the
|
|
339
391
|
// process lifetime — retrying a permanently-missing endpoint on every
|
|
340
392
|
// future send is wasteful. Transient errors must not set the latch.
|
|
341
393
|
let richKnownUnsupported = false;
|
|
394
|
+
// Separate verdict for the newer sendRichMessage verb. A server can implement
|
|
395
|
+
// editMessageText{rich_message} and not this one, answering it with a bare
|
|
396
|
+
// 404 — a single shared flag would let the reply tool's probe permanently
|
|
397
|
+
// disable the streamer's working rich edits.
|
|
398
|
+
let richSendKnownUnsupported = false;
|
|
342
399
|
|
|
343
400
|
// Extracted to lib/telegram/rich-edit.js so the capability/content/
|
|
344
401
|
// transient error-classification + fallback wiring is directly unit-
|
|
@@ -349,6 +406,10 @@ let richKnownUnsupported = false;
|
|
|
349
406
|
// safe to reference early because it's a stable function that does its
|
|
350
407
|
// own live lookups internally when called.
|
|
351
408
|
let richEditMessageText;
|
|
409
|
+
// Send-side counterpart, used by the reply tool. Same latch and the same
|
|
410
|
+
// classification, but it never throws: its caller holds the only copy of the
|
|
411
|
+
// reply and owns the plain fallback.
|
|
412
|
+
let richSendMessage;
|
|
352
413
|
let richMediaFileIdCache;
|
|
353
414
|
|
|
354
415
|
// 0.15 secret redaction (agent-flagged path): the agent marks a secret it saw
|
|
@@ -772,7 +833,10 @@ let recoverCodexRequest = null;
|
|
|
772
833
|
// heartbeat.start() is called in main() once DATA_DIR is settled; the gate
|
|
773
834
|
// needs no runtime config, so it's constructed here directly.
|
|
774
835
|
const authDisabledGate = createAuthDisabledGate();
|
|
775
|
-
|
|
836
|
+
// Constructed in main(), not here: the heartbeat filename carries BOT_NAME (every
|
|
837
|
+
// bot shares DATA_DIR, which is process.cwd()), and BOT_NAME is only parsed once
|
|
838
|
+
// main() runs.
|
|
839
|
+
let authDisabledHeartbeat = null;
|
|
776
840
|
|
|
777
841
|
// rc.59: once-per-cycle gate for the contextHint. A session is added
|
|
778
842
|
// to this Set when the hint fires, removed when the SDK emits
|
|
@@ -1189,6 +1253,10 @@ async function handleMessage(sessionKey, chatId, msg, bot) {
|
|
|
1189
1253
|
});
|
|
1190
1254
|
|
|
1191
1255
|
const botCfg = config.bot || {};
|
|
1256
|
+
// Whether this chat has live previews at all. Resolved once per turn: it
|
|
1257
|
+
// gates every behavior this feature ADDS, so a chat that never opted in
|
|
1258
|
+
// behaves exactly as it did before the feature existed.
|
|
1259
|
+
const streamPreviewEnabled = resolveStreamPreviewEnabled(config, chatId, threadId);
|
|
1192
1260
|
// 0.7.0: per-chat / per-bot link-preview opt-out (port from OpenClaw).
|
|
1193
1261
|
// chat-level wins over bot-level. Default (both undefined) preserves
|
|
1194
1262
|
// Telegram's native auto-preview behavior.
|
|
@@ -1387,7 +1455,22 @@ async function handleMessage(sessionKey, chatId, msg, bot) {
|
|
|
1387
1455
|
}
|
|
1388
1456
|
},
|
|
1389
1457
|
minChars: botCfg.streamMinChars,
|
|
1390
|
-
|
|
1458
|
+
// Telegram's edit limits are per CHAT, but forum topics share one chat_id
|
|
1459
|
+
// and each live topic's preview edits on its own clock. With live previews
|
|
1460
|
+
// on, scale the interval by however many are live in this chat right now,
|
|
1461
|
+
// so N busy topics cost the chat the same edit budget as one — a 429 sleep
|
|
1462
|
+
// here would stall the turn against the tool-ack timeout. Evaluated per
|
|
1463
|
+
// edit because topics start and finish mid-turn.
|
|
1464
|
+
//
|
|
1465
|
+
// Without the feature the value is passed through untouched: scaling is a
|
|
1466
|
+
// behavior change, and a chat that never opted in must edit exactly as it
|
|
1467
|
+
// did before this branch.
|
|
1468
|
+
throttleMs: streamPreviewEnabled
|
|
1469
|
+
? () => {
|
|
1470
|
+
const base = botCfg.streamThrottleMs != null ? botCfg.streamThrottleMs : DEFAULT_THROTTLE_MS;
|
|
1471
|
+
return base * Math.max(1, streamerRegistry.liveCount(chatId));
|
|
1472
|
+
}
|
|
1473
|
+
: botCfg.streamThrottleMs,
|
|
1391
1474
|
// rc.44: preserve intermediate bubbles by default. These are
|
|
1392
1475
|
// regular text segments the model emits across an agentic
|
|
1393
1476
|
// multi-step turn ("Let me check..." → tool runs → "Found it.
|
|
@@ -1406,6 +1489,55 @@ async function handleMessage(sessionKey, chatId, msg, bot) {
|
|
|
1406
1489
|
});
|
|
1407
1490
|
// streamer is registered with this turn via pm.send's context (below)
|
|
1408
1491
|
|
|
1492
|
+
// Reply bodies this turn has already put on screen. The turn-end
|
|
1493
|
+
// reconciliation reads it to tell an orphaned draft (deliver it) from one
|
|
1494
|
+
// whose content a reply already carried (delete it, don't say it twice).
|
|
1495
|
+
const deliveredTexts = [];
|
|
1496
|
+
// Assigned when the turn is actually dispatched (see below) — the early
|
|
1497
|
+
// returns above it never register, so this stays a no-op for them.
|
|
1498
|
+
let releaseStreamerRegistration = () => {};
|
|
1499
|
+
|
|
1500
|
+
// The single answer to "the turn is over; what happens to the half-written
|
|
1501
|
+
// bubble?", shared by every turn-completion exit so no exit can invent its
|
|
1502
|
+
// own. `reason: 'no-reply'` marks the one case where the agent explicitly
|
|
1503
|
+
// chose silence and a draft must NOT be delivered.
|
|
1504
|
+
//
|
|
1505
|
+
// Gated on the feature: for a chat without live previews there is no `stream`
|
|
1506
|
+
// tool, so nothing can be holding a draft that the pre-branch code wouldn't
|
|
1507
|
+
// have handled — and running the new rule there would change settled
|
|
1508
|
+
// behavior for chats that never asked for the feature.
|
|
1509
|
+
const finishStreamer = createTurnSettler({
|
|
1510
|
+
streamer,
|
|
1511
|
+
deliveredTexts,
|
|
1512
|
+
enabled: streamPreviewEnabled,
|
|
1513
|
+
persistBubbleText,
|
|
1514
|
+
logEvent,
|
|
1515
|
+
chatId,
|
|
1516
|
+
detail: {
|
|
1517
|
+
chat_id: chatId, thread_id: threadId, msg_id: msg.message_id, bot: BOT_NAME,
|
|
1518
|
+
},
|
|
1519
|
+
// An orphaned draft too long for one bubble takes the same escape the
|
|
1520
|
+
// consume rule does: deliver the whole thing as chunks rather than leave
|
|
1521
|
+
// the user with a truncation.
|
|
1522
|
+
redeliver: async (text) => {
|
|
1523
|
+
const chunks = chunkMarkdownText(
|
|
1524
|
+
resolveRichTextEnabled(config, chatId, threadId) ? stripMediaMarkdown(text) : text,
|
|
1525
|
+
TG_CHUNK_BUDGET,
|
|
1526
|
+
);
|
|
1527
|
+
const r = await deliverReplies({
|
|
1528
|
+
bot,
|
|
1529
|
+
send: (b, method, params, m) => tg(b, method, params, m),
|
|
1530
|
+
chatId,
|
|
1531
|
+
threadId,
|
|
1532
|
+
chunks,
|
|
1533
|
+
replyToMessageId: msg.message_id,
|
|
1534
|
+
meta: outMetaBase,
|
|
1535
|
+
logger: { error: (m) => console.error(`[${label}] ${m}`) },
|
|
1536
|
+
});
|
|
1537
|
+
return r.failed.length === 0;
|
|
1538
|
+
},
|
|
1539
|
+
});
|
|
1540
|
+
|
|
1409
1541
|
// 0.7.2: clean up bubbles superseded by forceNewMessage() — the
|
|
1410
1542
|
// intermediate text segments that fired across a tool-heavy turn.
|
|
1411
1543
|
// Pre-0.7.2 (since 0.7.0 multi-bubble landed) those bubbles were
|
|
@@ -1741,27 +1873,55 @@ async function handleMessage(sessionKey, chatId, msg, bot) {
|
|
|
1741
1873
|
// (that would block every autosteer).
|
|
1742
1874
|
// Pass streamer + reactor as per-turn context; pm's callbacks
|
|
1743
1875
|
// pick them off entry.pendingQueue[0].context.
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1876
|
+
//
|
|
1877
|
+
// Registered HERE and not at creation: the early returns above (autosteer
|
|
1878
|
+
// fold, codex duplicate/ambiguous) abandon their streamer without ever
|
|
1879
|
+
// dispatching, and registering those would let a later turn's reply find
|
|
1880
|
+
// a preview that was never going to exist. Only for chats that have live
|
|
1881
|
+
// previews — an entry for a chat without them would still be counted by
|
|
1882
|
+
// the per-chat throttle scaling.
|
|
1883
|
+
//
|
|
1884
|
+
// dispatchedTurnId is filled by the engine's onTurnId callback below,
|
|
1885
|
+
// before any tool call for this turn can reach us; it lets a reply be
|
|
1886
|
+
// checked against the turn it actually names.
|
|
1887
|
+
let dispatchedTurnId = null;
|
|
1888
|
+
if (streamPreviewEnabled) {
|
|
1889
|
+
releaseStreamerRegistration = streamerRegistry.register(sessionKey, {
|
|
1890
|
+
streamer, chatId, deliveredTexts,
|
|
1891
|
+
getTurnId: () => dispatchedTurnId,
|
|
1892
|
+
});
|
|
1893
|
+
}
|
|
1894
|
+
try {
|
|
1895
|
+
await new Promise((dispatched) => {
|
|
1896
|
+
sendPromise = sendToProcess(sessionKey, prompt, {
|
|
1897
|
+
// 0.13 D1 (S8): the typing controller rides the per-turn context so
|
|
1898
|
+
// the question lifecycle (callbacks.js onQuestionAsked/-Resumed) can
|
|
1899
|
+
// pause it while the bot waits on the USER and resume on the answer.
|
|
1900
|
+
streamer, reactor, typing: stopTyping, sourceMsgId: msg.message_id,
|
|
1901
|
+
codexDispatchReservationId: codexDispatch?.reservationId,
|
|
1902
|
+
codexDispatchGenerationId: codexDispatch?.generationId,
|
|
1903
|
+
// 0.7.4 (item B): fire THINKING when Claude actually starts
|
|
1904
|
+
// emitting — not the moment we wrote stdin.
|
|
1905
|
+
onFirstStream: () => reactor.setState('THINKING'),
|
|
1906
|
+
onTurnId: (id) => { dispatchedTurnId = id; },
|
|
1907
|
+
}, { onDispatched: dispatched })
|
|
1908
|
+
.catch((e) => ({ __sendError: e }))
|
|
1909
|
+
.finally(dispatched);
|
|
1910
|
+
});
|
|
1911
|
+
} catch (err) {
|
|
1912
|
+
// A throw between registering and the turn's own try/finally would
|
|
1913
|
+
// strand a 'live' entry, inflating liveCount for every other topic in
|
|
1914
|
+
// the chat for the life of the process.
|
|
1915
|
+
releaseStreamerRegistration();
|
|
1916
|
+
throw err;
|
|
1917
|
+
}
|
|
1759
1918
|
}
|
|
1760
1919
|
} finally {
|
|
1761
1920
|
releaseIntent();
|
|
1762
1921
|
}
|
|
1763
1922
|
if (codexDispatchDecision === 'duplicate') {
|
|
1764
1923
|
stopTyping();
|
|
1924
|
+
await finishStreamer();
|
|
1765
1925
|
reactor.stop();
|
|
1766
1926
|
const terminalDuplicateStatus = (
|
|
1767
1927
|
codexDispatch?.state === 'settled'
|
|
@@ -1783,6 +1943,7 @@ async function handleMessage(sessionKey, chatId, msg, bot) {
|
|
|
1783
1943
|
}
|
|
1784
1944
|
if (['ambiguous', 'unavailable'].includes(codexDispatchDecision)) {
|
|
1785
1945
|
stopTyping();
|
|
1946
|
+
await finishStreamer();
|
|
1786
1947
|
await reactor.clear().catch(() => {});
|
|
1787
1948
|
reactor.stop();
|
|
1788
1949
|
const sendCodexDispatchNotice = (notice) => tg(bot, 'sendMessage', {
|
|
@@ -1802,6 +1963,10 @@ async function handleMessage(sessionKey, chatId, msg, bot) {
|
|
|
1802
1963
|
}
|
|
1803
1964
|
if (steered.autosteered) {
|
|
1804
1965
|
stopTyping();
|
|
1966
|
+
// This turn's streamer was built before the steer decision and never
|
|
1967
|
+
// dispatched, so there is normally nothing to settle — but the exit runs
|
|
1968
|
+
// the same rule as every other, so it can't be the one that strands a bubble.
|
|
1969
|
+
await finishStreamer();
|
|
1805
1970
|
// setState('AUTOSTEERED') is terminal — bypasses throttle,
|
|
1806
1971
|
// serializes after any in-flight QUEUED apply via applyChain.
|
|
1807
1972
|
await reactor.setState('AUTOSTEERED');
|
|
@@ -2008,10 +2173,24 @@ async function handleMessage(sessionKey, chatId, msg, bot) {
|
|
|
2008
2173
|
// NO_REPLY is an explicit "stay silent" signal from the agent —
|
|
2009
2174
|
// those still markReplied silently.
|
|
2010
2175
|
if (result.text === 'NO_REPLY') {
|
|
2176
|
+
// Explicit silence. A half-written draft is not consent to speak, so the
|
|
2177
|
+
// preview is deleted rather than delivered — the one case where an
|
|
2178
|
+
// undelivered draft is thrown away on purpose.
|
|
2179
|
+
await finishStreamer('no-reply');
|
|
2011
2180
|
await finalizeResultDelivery();
|
|
2012
2181
|
return;
|
|
2013
2182
|
}
|
|
2014
2183
|
if (!result.text) {
|
|
2184
|
+
// Covers BOTH exits below (tool-only completion and the empty-response
|
|
2185
|
+
// fallback): the turn produced no text to deliver, so whatever the
|
|
2186
|
+
// preview holds is the only thing written this turn.
|
|
2187
|
+
const settled = await finishStreamer();
|
|
2188
|
+
// If the preview HELD an answer and we just delivered it, the turn was
|
|
2189
|
+
// not empty — apologizing for silence underneath the answer the user is
|
|
2190
|
+
// reading is worse than saying nothing.
|
|
2191
|
+
const previewAnswered = settled.action === 'finalized'
|
|
2192
|
+
|| settled.action === 'redelivered'
|
|
2193
|
+
|| settled.action === 'finalize-failed';
|
|
2015
2194
|
// 0.8.0-rc.7: tool-only completion is NOT an error. Under SDK
|
|
2016
2195
|
// pm, a turn that ends after running tools (no closing text
|
|
2017
2196
|
// block) leaves result.text empty even though the bot DID
|
|
@@ -2022,6 +2201,19 @@ async function handleMessage(sessionKey, chatId, msg, bot) {
|
|
|
2022
2201
|
// the emoji visually) and silently mark replied.
|
|
2023
2202
|
const toolOnlyTurn = (result.metrics?.numToolUses ?? 0) > 0
|
|
2024
2203
|
&& (result.metrics?.numAssistantMessages ?? 0) > 0;
|
|
2204
|
+
if (previewAnswered) {
|
|
2205
|
+
// The preview held an answer and reconciliation just delivered it. The
|
|
2206
|
+
// turn produced no `result.text` only because the agent wrote into the
|
|
2207
|
+
// preview instead of replying — the user has their answer.
|
|
2208
|
+
logEvent('stream-orphan-answered-turn', {
|
|
2209
|
+
chat_id: chatId, msg_id: msg.message_id, bot: BOT_NAME,
|
|
2210
|
+
action: settled.action,
|
|
2211
|
+
});
|
|
2212
|
+
await reactor.clear().catch(() => {});
|
|
2213
|
+
clearAutosteeredReactions(sessionKey).catch(() => {});
|
|
2214
|
+
await finalizeResultDelivery();
|
|
2215
|
+
return;
|
|
2216
|
+
}
|
|
2025
2217
|
if (toolOnlyTurn) {
|
|
2026
2218
|
await reactor.clear().catch(() => {});
|
|
2027
2219
|
clearAutosteeredReactions(sessionKey).catch(() => {});
|
|
@@ -2078,6 +2270,10 @@ async function handleMessage(sessionKey, chatId, msg, bot) {
|
|
|
2078
2270
|
// parseResponse/finalize/deliver block; still clear reactor + mark
|
|
2079
2271
|
// replied so the reactive UI elements close cleanly.
|
|
2080
2272
|
if (result.alreadyDelivered) {
|
|
2273
|
+
// The CLI path delivered its replies incrementally during the turn. If a
|
|
2274
|
+
// preview is still live here the turn ended on a stream call (or after
|
|
2275
|
+
// its last reply), so settle it against what the replies actually said.
|
|
2276
|
+
await finishStreamer();
|
|
2081
2277
|
logEvent('channels-turn-resolved', {
|
|
2082
2278
|
chat_id: chatId,
|
|
2083
2279
|
msg_id: msg.message_id,
|
|
@@ -2214,6 +2410,7 @@ async function handleMessage(sessionKey, chatId, msg, bot) {
|
|
|
2214
2410
|
if (fin.finalEditOk) {
|
|
2215
2411
|
// Preview was successfully edited to the final text.
|
|
2216
2412
|
// No follow-up messages needed.
|
|
2413
|
+
persistBubbleText(chatId, fin.msgId, fin.finalText ?? parsed.text);
|
|
2217
2414
|
await mediaContext.flushPartialDeliveryWarning(outMetaBase);
|
|
2218
2415
|
await sendInlineStickers();
|
|
2219
2416
|
await sendInlineReactions();
|
|
@@ -2345,6 +2542,10 @@ async function handleMessage(sessionKey, chatId, msg, bot) {
|
|
|
2345
2542
|
mediaContext.recordTextFailures(deliveryResult.failed.length);
|
|
2346
2543
|
}
|
|
2347
2544
|
|
|
2545
|
+
// A turn whose final output was a solo sticker/reaction skips the
|
|
2546
|
+
// finalize block above entirely, so a preview streamed earlier in the turn
|
|
2547
|
+
// would still be live here.
|
|
2548
|
+
await finishStreamer();
|
|
2348
2549
|
await mediaContext.flushPartialDeliveryWarning(outMetaBase);
|
|
2349
2550
|
await sendInlineStickers();
|
|
2350
2551
|
await sendInlineReactions();
|
|
@@ -2400,8 +2601,38 @@ async function handleMessage(sessionKey, chatId, msg, bot) {
|
|
|
2400
2601
|
// fresh bubble with the full answer below.
|
|
2401
2602
|
const abortedByUser = isSessionRecentlyAborted(sessionKey);
|
|
2402
2603
|
const quietFinalize = abortedByUser || isShuttingDown;
|
|
2604
|
+
// A turn that already delivered replies and THEN failed must not restate
|
|
2605
|
+
// them: finalize(null) publishes whatever the draft holds, which on a CLI
|
|
2606
|
+
// turn is usually the answer a reply already sent. That is precisely the
|
|
2607
|
+
// duplicate the shared rule exists to prevent, so when this turn delivered
|
|
2608
|
+
// anything, the error paths settle through it instead (spec §3.3's "every
|
|
2609
|
+
// exit" beats §3.2.3's literal wording). With nothing delivered, the old
|
|
2610
|
+
// direct finalize is still exactly right — it is what carries the error
|
|
2611
|
+
// suffix onto the partial bubble.
|
|
2612
|
+
const settleErrorExit = async (errorSuffix) => {
|
|
2613
|
+
if (deliveredTexts.length > 0) {
|
|
2614
|
+
await finishStreamer().catch(() => {});
|
|
2615
|
+
if (errorSuffix) {
|
|
2616
|
+
await tg(bot, 'sendMessage', {
|
|
2617
|
+
chat_id: chatId,
|
|
2618
|
+
text: `⚠️ ${errorSuffix}`,
|
|
2619
|
+
...(threadId && { message_thread_id: threadId }),
|
|
2620
|
+
}, { ...outMetaBase, source: 'turn-error-suffix' }).catch(() => {});
|
|
2621
|
+
}
|
|
2622
|
+
return;
|
|
2623
|
+
}
|
|
2624
|
+
// null, not '': finalize falls back to the drafted body. Passing ''
|
|
2625
|
+
// REPLACED whatever had streamed with an empty bubble — the user watched
|
|
2626
|
+
// a partial answer appear and then get wiped by the very failure that
|
|
2627
|
+
// was supposed to leave it standing.
|
|
2628
|
+
const fin = await streamer.finalize(null, errorSuffix ? { errorSuffix } : {})
|
|
2629
|
+
.catch(() => null);
|
|
2630
|
+
// The bubble now shows the drafted body; bring its transcript row along,
|
|
2631
|
+
// or the row keeps the ~30-character stub the initial send wrote.
|
|
2632
|
+
if (fin?.finalEditOk) persistBubbleText(chatId, fin.msgId, fin.finalText);
|
|
2633
|
+
};
|
|
2403
2634
|
if (quietFinalize) {
|
|
2404
|
-
await
|
|
2635
|
+
await settleErrorExit(null);
|
|
2405
2636
|
if (abortedByUser) {
|
|
2406
2637
|
// 0.8.0-rc.13: clear the in-flight emoji on abort so the user
|
|
2407
2638
|
// sees a clean message after their /stop ack — pre-rc.13 the
|
|
@@ -2423,7 +2654,9 @@ async function handleMessage(sessionKey, chatId, msg, bot) {
|
|
|
2423
2654
|
// code, not text). TURN_TIMEOUT (went quiet) / TURN_MAX_EXCEEDED (hit hard
|
|
2424
2655
|
// cap) → TIMEOUT reactor; anything else → ERROR.
|
|
2425
2656
|
const { errorSuffix, reactorState } = classifyTurnEndError(err);
|
|
2426
|
-
|
|
2657
|
+
// null keeps the drafted body so the suffix APPENDS to what the user was
|
|
2658
|
+
// reading instead of replacing it with a bare "⚠️ …".
|
|
2659
|
+
await settleErrorExit(errorSuffix);
|
|
2427
2660
|
reactor.setState(reactorState);
|
|
2428
2661
|
}
|
|
2429
2662
|
if (deliverySettlementError) throw deliverySettlementError;
|
|
@@ -2431,6 +2664,11 @@ async function handleMessage(sessionKey, chatId, msg, bot) {
|
|
|
2431
2664
|
} finally {
|
|
2432
2665
|
stopTyping();
|
|
2433
2666
|
reactor.stop();
|
|
2667
|
+
// The preview is settled by now on every path (a turn-completion exit or
|
|
2668
|
+
// the catch's finalize); drop the registry entry so a later turn on this
|
|
2669
|
+
// session can't find this turn's dead streamer. Removes only OUR entry —
|
|
2670
|
+
// a newer turn that already took the slot keeps it.
|
|
2671
|
+
releaseStreamerRegistration();
|
|
2434
2672
|
// rc.38: defensive clear-on-exit for ✍ reactions. Pre-rc.38 only
|
|
2435
2673
|
// the success path (line ~2622), the abort path (line ~2858), and
|
|
2436
2674
|
// the tool-only-completion path (line ~2681) cleared
|
|
@@ -2982,6 +3220,18 @@ async function main() {
|
|
|
2982
3220
|
}
|
|
2983
3221
|
tg = createSender(db, console, config);
|
|
2984
3222
|
richMediaFileIdCache = createMediaFileIdCache();
|
|
3223
|
+
// ONE latch decision for both rich paths. They set the same flag, so a
|
|
3224
|
+
// counter owned by either would let that path latch on its first bare
|
|
3225
|
+
// 404 while the other still believed two were required.
|
|
3226
|
+
// One strike counter, one verdict per verb.
|
|
3227
|
+
const richCapabilityLatch = createRichCapabilityLatch({
|
|
3228
|
+
isExplicit: isRichCapabilityErrorExplicit,
|
|
3229
|
+
isFieldRejection: isRichMessageFieldRejection,
|
|
3230
|
+
setUnsupported: (verb) => {
|
|
3231
|
+
if (verb === 'send') richSendKnownUnsupported = true;
|
|
3232
|
+
else richKnownUnsupported = true;
|
|
3233
|
+
},
|
|
3234
|
+
});
|
|
2985
3235
|
richEditMessageText = createRichEditor({
|
|
2986
3236
|
tg,
|
|
2987
3237
|
botName: BOT_NAME,
|
|
@@ -2994,6 +3244,25 @@ async function main() {
|
|
|
2994
3244
|
getApiRoot: () => config.bot?.apiRoot || null,
|
|
2995
3245
|
stripUrlCreds: stripUrlCredentials,
|
|
2996
3246
|
sanitizeFallbackText: stripMediaMarkdown,
|
|
3247
|
+
capabilityLatch: richCapabilityLatch,
|
|
3248
|
+
});
|
|
3249
|
+
richSendMessage = createRichSender({
|
|
3250
|
+
tg,
|
|
3251
|
+
botName: BOT_NAME,
|
|
3252
|
+
logEvent,
|
|
3253
|
+
redactBotToken,
|
|
3254
|
+
isRichCapabilityError,
|
|
3255
|
+
isRichCapabilityErrorExplicit,
|
|
3256
|
+
isRichContentError,
|
|
3257
|
+
getRichKnownUnsupported: () => richSendKnownUnsupported,
|
|
3258
|
+
setRichKnownUnsupported: () => { richSendKnownUnsupported = true; },
|
|
3259
|
+
getApiRoot: () => config.bot?.apiRoot || null,
|
|
3260
|
+
stripUrlCreds: stripUrlCredentials,
|
|
3261
|
+
// api.js leaves sendRichMessage untracked so a failed attempt can't
|
|
3262
|
+
// leave a row the plain fallback then duplicates; the sender persists
|
|
3263
|
+
// its own row, on success only.
|
|
3264
|
+
insertSentRow: (row) => db.insertMessage(row),
|
|
3265
|
+
capabilityLatch: richCapabilityLatch,
|
|
2997
3266
|
});
|
|
2998
3267
|
pairings = createPairingsStore(db.raw);
|
|
2999
3268
|
approvals = createApprovalsStore(db.raw);
|
|
@@ -3114,10 +3383,11 @@ async function main() {
|
|
|
3114
3383
|
setInterval(() => runAuthCheck('interval'), 30 * 60_000).unref?.();
|
|
3115
3384
|
|
|
3116
3385
|
// AUTH_DISABLED Netdata-visibility heartbeat (docs/AUTH_DISABLED_HANDLING_SPEC.md,
|
|
3117
|
-
// Layer 3.3) — writes <DATA_DIR>/heartbeat
|
|
3386
|
+
// Layer 3.3) — writes <DATA_DIR>/heartbeat-<botName>.json every 60s with the
|
|
3118
3387
|
// authDisabledGate's occurrence counter. File-only (no HTTP server in this
|
|
3119
3388
|
// repo to hang a /healthz route on); wiring the file into an actual Netdata
|
|
3120
3389
|
// alert is a separate VPS-side ops change, out of scope here.
|
|
3390
|
+
authDisabledHeartbeat = createHeartbeat({ dataDir: DATA_DIR, botName: BOT_NAME, authDisabledGate });
|
|
3121
3391
|
authDisabledHeartbeat.start();
|
|
3122
3392
|
|
|
3123
3393
|
// 0.8.0 Phase 1 step 11 + rc.50: defensive uncaughtException +
|
|
@@ -3316,6 +3586,38 @@ async function main() {
|
|
|
3316
3586
|
console.warn(`[polygram] WARNING: ${binCheck.reason}`);
|
|
3317
3587
|
}
|
|
3318
3588
|
}
|
|
3589
|
+
// The reply-tool text-delivery chain. Two independent decisions about the
|
|
3590
|
+
// same reply, in the order that makes them independent:
|
|
3591
|
+
//
|
|
3592
|
+
// 1. The live preview. Only it knows whether a bubble is already on screen
|
|
3593
|
+
// holding this answer, so it gets first refusal — when it consumes, the
|
|
3594
|
+
// reply IS that bubble (the streamer's own toRichPayload renders rich
|
|
3595
|
+
// there, so consuming loses nothing).
|
|
3596
|
+
// 2. Rich delivery. Everything the preview did not consume — an interim
|
|
3597
|
+
// status, a late reply, a body too long for one bubble, a chat with no
|
|
3598
|
+
// preview at all — flows here, and then to the chunked path.
|
|
3599
|
+
//
|
|
3600
|
+
// Neither feature may switch the other off, which a single strategy slot
|
|
3601
|
+
// could not express.
|
|
3602
|
+
const makeDeliverText = composeDeliverTextFactories([
|
|
3603
|
+
createDeliverTextFactory({
|
|
3604
|
+
registry: streamerRegistry,
|
|
3605
|
+
logEvent,
|
|
3606
|
+
persistBubbleText,
|
|
3607
|
+
logger: console,
|
|
3608
|
+
botName: BOT_NAME,
|
|
3609
|
+
}),
|
|
3610
|
+
// Injected rather than imported by the dispatcher: rich-media.js requires
|
|
3611
|
+
// the dispatcher module, so the reverse direction would be a require cycle.
|
|
3612
|
+
createRichDeliveryFactory({
|
|
3613
|
+
bot,
|
|
3614
|
+
sendRich: (args) => richSendMessage(args),
|
|
3615
|
+
isRichTextEnabled: (chatId, threadId) => resolveRichTextEnabled(config, chatId, threadId),
|
|
3616
|
+
getRichKnownUnsupported: () => richSendKnownUnsupported,
|
|
3617
|
+
redactError: redactBotToken,
|
|
3618
|
+
}),
|
|
3619
|
+
]);
|
|
3620
|
+
|
|
3319
3621
|
// 0.11.0: channels backend wiring. Used when a chat opts in via
|
|
3320
3622
|
// `pm: 'channels'` config. Falls back to SDK gracefully if the pinned
|
|
3321
3623
|
// claude binary isn't present (see factory.js — channelsClaudeBin
|
|
@@ -3324,7 +3626,8 @@ async function main() {
|
|
|
3324
3626
|
bot,
|
|
3325
3627
|
send: tg,
|
|
3326
3628
|
chunkText: chunkMarkdownText,
|
|
3327
|
-
deliverReplies,
|
|
3629
|
+
deliverReplies: deliverRepliesTracked,
|
|
3630
|
+
makeDeliverText,
|
|
3328
3631
|
// Review F#1: required so [sticker:NAME] / [react:EMOJI] / canned-string
|
|
3329
3632
|
// (`No response requested.`) protections fire on channels replies too.
|
|
3330
3633
|
parseResponse,
|
|
@@ -3333,6 +3636,19 @@ async function main() {
|
|
|
3333
3636
|
// inbound on the CLI-channels reply path (handleMessage short-circuits at
|
|
3334
3637
|
// `alreadyDelivered` before its own redact block, so it must fire here).
|
|
3335
3638
|
redactInbound,
|
|
3639
|
+
redactError: redactBotToken,
|
|
3640
|
+
// Chat-level text hygiene for the chunked path. Deliberately independent
|
|
3641
|
+
// of the rich strategy below: a rich-enabled chat must never render a
|
|
3642
|
+
// local path, including when that strategy cannot be built or fails.
|
|
3643
|
+
// A reply that is nothing BUT unrenderable media degrades to a line
|
|
3644
|
+
// saying so rather than to silence.
|
|
3645
|
+
projectFallbackText: (text, { chatId, threadId }) => {
|
|
3646
|
+
if (!resolveRichTextEnabled(config, chatId, threadId)) return text;
|
|
3647
|
+
const stripped = stripMediaMarkdown(text);
|
|
3648
|
+
if (stripped.trim()) return stripped;
|
|
3649
|
+
logEvent('deliver-media-only-degraded', { chat_id: chatId, thread_id: threadId, bot: BOT_NAME });
|
|
3650
|
+
return MEDIA_ONLY_FALLBACK_TEXT;
|
|
3651
|
+
},
|
|
3336
3652
|
logEvent,
|
|
3337
3653
|
logger: console,
|
|
3338
3654
|
});
|
|
@@ -3348,6 +3664,12 @@ async function main() {
|
|
|
3348
3664
|
botName: BOT_NAME,
|
|
3349
3665
|
// channels backend
|
|
3350
3666
|
toolDispatcher: channelsToolDispatcher,
|
|
3667
|
+
// Which optional bridge tools this dispatcher can honor. Resolved per spawn
|
|
3668
|
+
// so `stream` (the live-preview tool + its prompt section) rolls out per
|
|
3669
|
+
// chat/topic; off by default.
|
|
3670
|
+
toolDispatcherCapabilities: (chatId, threadId) => ({
|
|
3671
|
+
stream: resolveStreamPreviewEnabled(config, chatId, threadId),
|
|
3672
|
+
}),
|
|
3351
3673
|
channelsClaudeBin,
|
|
3352
3674
|
// orchestra identity — polygram's names so behavior is byte-identical to the
|
|
3353
3675
|
// copied engine. bridge/tmux/hook/attachment prefixes, product/surface prose,
|
|
@@ -3363,6 +3685,9 @@ async function main() {
|
|
|
3363
3685
|
// CliProcess. Without it, cli chats lose the Telegram table/markdown display rules.
|
|
3364
3686
|
// A resolver (not a static string) so each cli-backed chat gets its own richText
|
|
3365
3687
|
// state — orchestra's factory calls this per spawn with the spawning chat/topic.
|
|
3688
|
+
// No inline-media guidance: replies here are delivered by the reply tool, which
|
|
3689
|
+
// renders rich text on media-stripped input, so an image would reach the user as
|
|
3690
|
+
// its caption and nothing else.
|
|
3366
3691
|
displayHint: (chatId, threadId) => buildPolygramDisplayHint(resolveRichTextEnabled(config, chatId, threadId)),
|
|
3367
3692
|
// Backend-default outbound cap fallback (per-spawn buildSpawnContext override
|
|
3368
3693
|
// normally supersedes this; kept so any context-less spawn still gets the backend
|
|
@@ -3703,7 +4028,7 @@ async function main() {
|
|
|
3703
4028
|
// 4. Remaining shutdown: approvals sweeper, IPC, resolve hook waiters,
|
|
3704
4029
|
// kill pm subprocesses, close DB.
|
|
3705
4030
|
if (approvalSweepTimer) clearInterval(approvalSweepTimer);
|
|
3706
|
-
authDisabledHeartbeat
|
|
4031
|
+
authDisabledHeartbeat?.stop(); // null if we shut down before main() armed it
|
|
3707
4032
|
if (ipcCloser) ipcCloser.close().catch(() => {});
|
|
3708
4033
|
try { fs.unlinkSync(ipcServer.secretPathFor(BOT_NAME)); } catch {}
|
|
3709
4034
|
// Reject every parked canUseTool waiter so the SDK doesn't
|