polygram 0.31.0 → 0.33.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +5 -0
- package/config.example.json +2 -0
- package/lib/db.js +233 -9
- package/lib/handlers/dispatcher.js +84 -13
- package/lib/ops/clean-resume.js +358 -0
- package/lib/ops/clean-shutdown.js +84 -0
- package/lib/ops/shutdown-disposition.js +13 -4
- package/lib/process/channels-tool-dispatcher.js +12 -3
- package/lib/sdk/callbacks.js +2 -0
- package/lib/telegram/api.js +71 -3
- package/lib/telegram/composing-marker.js +53 -0
- package/lib/telegram/delivery-barrier.js +117 -0
- package/lib/telegram/process-agent-reply.js +18 -2
- package/lib/telegram/rich-edit.js +16 -5
- package/lib/telegram/rich-media.js +18 -2
- package/lib/telegram/rich.js +36 -0
- package/lib/telegram/streamer.js +327 -26
- package/migrations/018-clean-restart-resume.sql +24 -0
- package/package.json +2 -2
- package/polygram.js +406 -43
package/lib/telegram/streamer.js
CHANGED
|
@@ -45,6 +45,73 @@ const DEFAULT_THROTTLE_MS = 1000;
|
|
|
45
45
|
// (`streamThrottleMs: 50`) without rejecting the config outright.
|
|
46
46
|
const THROTTLE_FLOOR_MS = 250;
|
|
47
47
|
|
|
48
|
+
/**
|
|
49
|
+
* The part of a snapshot the reader has already seen as COMPLETE: everything
|
|
50
|
+
* up to and including the last blank line. What follows it is the block still
|
|
51
|
+
* being written, which the model may revise freely.
|
|
52
|
+
*
|
|
53
|
+
* A blank line stands in for a real block boundary on purpose. It mirrors what
|
|
54
|
+
* the rich renderer already does — partial mode holds back the last top-level
|
|
55
|
+
* block, so the completed-blocks prefix IS what reached the screen — without
|
|
56
|
+
* a lexer call on the hot path, and it works identically on the plain path
|
|
57
|
+
* where rich rendering is not involved at all. It also fails OPEN: text with
|
|
58
|
+
* no blank line anywhere yields an empty prefix and pins nothing, matching
|
|
59
|
+
* rich's own rule that a single in-progress block renders as-is.
|
|
60
|
+
*/
|
|
61
|
+
// Everything the reader has seen settle, in a PLAIN bubble: the complete
|
|
62
|
+
// lines of what was rendered. The plain path shows the whole text, so there
|
|
63
|
+
// is no held-back block to exempt — but the line being typed is not settled,
|
|
64
|
+
// and a model rewriting the sentence it is mid-way through is ordinary
|
|
65
|
+
// partial-mode behaviour rather than losing anything.
|
|
66
|
+
function completeLines(shown) {
|
|
67
|
+
const i = shown.lastIndexOf('\n');
|
|
68
|
+
return i === -1 ? '' : shown.slice(0, i + 1);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Lazy so the streamer keeps loading for callers (and tests) that never touch
|
|
72
|
+
// the rich path, and so requiring rich.js stays out of the module's own load.
|
|
73
|
+
let _partialVisibleExtent = null;
|
|
74
|
+
function defaultRichVisibleExtent(markdown) {
|
|
75
|
+
if (!_partialVisibleExtent) {
|
|
76
|
+
({ partialVisibleExtent: _partialVisibleExtent } = require('./rich'));
|
|
77
|
+
}
|
|
78
|
+
return _partialVisibleExtent(markdown);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// A task-list marker at the head of a list item, and only there. `[x]` inside
|
|
82
|
+
// a sentence is prose — rewriting it IS losing text, and must still be caught.
|
|
83
|
+
const TASK_MARKER_RE = /^([ \t]*(?:[-*+]|\d+[.)])[ \t]+)\[[ xX]\]/gm;
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Flatten checkbox STATE so ticking an item reads as the same text.
|
|
87
|
+
*
|
|
88
|
+
* Polygram's own display hint tells the agent to "send an updated list with
|
|
89
|
+
* items checked off as you complete them" — a deliberate mutation of a line
|
|
90
|
+
* the reader has already seen. Comparing snapshots verbatim would refuse it
|
|
91
|
+
* and freeze the preview for the rest of the turn on the exact feature the
|
|
92
|
+
* prompt asks for. A tick loses nothing: the item is still there, in place,
|
|
93
|
+
* saying the same thing about a different state.
|
|
94
|
+
*
|
|
95
|
+
* Length-preserving on purpose ('[x]' and '[ ]' are both three characters),
|
|
96
|
+
* so a prefix stays a prefix and the comparison needs no index arithmetic.
|
|
97
|
+
*/
|
|
98
|
+
function normalizeTaskMarkers(text) {
|
|
99
|
+
return text.replace(TASK_MARKER_RE, '$1[ ]');
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* The form both sides of the guard comparison are read in.
|
|
104
|
+
*
|
|
105
|
+
* CRLF is folded first, and not for tidiness: a boundary located by newline
|
|
106
|
+
* never matches `\r\n`, so a CRLF document would find none at all and
|
|
107
|
+
* silently switch the guard off — the one failure mode a guard must not have.
|
|
108
|
+
* Trailing whitespace goes too: a snapshot that loses a blank line off its end
|
|
109
|
+
* has lost nothing anyone was reading.
|
|
110
|
+
*/
|
|
111
|
+
function canonicalizeForGuard(text) {
|
|
112
|
+
return normalizeTaskMarkers(text.replace(/\r\n/g, '\n')).replace(/\s+$/, '');
|
|
113
|
+
}
|
|
114
|
+
|
|
48
115
|
function createStreamer({
|
|
49
116
|
// async (payload) -> { message_id, _hadReplyAnchor?, wentRich? }
|
|
50
117
|
//
|
|
@@ -120,6 +187,33 @@ function createStreamer({
|
|
|
120
187
|
// OPENS rich never had a plain shape to change, so it does not fire —
|
|
121
188
|
// the metric stays a count of visible flips.
|
|
122
189
|
onRichUpgrade = () => {},
|
|
190
|
+
// Fires once per refused snapshot — one that lost text the reader had
|
|
191
|
+
// already seen. Receives { prevLen, newLen }; the caller owns the chat and
|
|
192
|
+
// turn identifiers, which this module has no business knowing, and a turn
|
|
193
|
+
// that keeps offending is a count over the rows it writes.
|
|
194
|
+
onNonCumulativeSnapshot = () => {},
|
|
195
|
+
// Optional "still writing" tail for partial renders.
|
|
196
|
+
//
|
|
197
|
+
// toComposingMarker() -> { block, plainSuffix } | null
|
|
198
|
+
//
|
|
199
|
+
// Called per partial render, so a caller whose rendering capabilities shift
|
|
200
|
+
// mid-turn (typed nodes refused, say) answers with the shape that fits NOW —
|
|
201
|
+
// the same reason toRichPayload is a callback rather than a value. null
|
|
202
|
+
// keeps every bubble exactly as it was before this existed.
|
|
203
|
+
//
|
|
204
|
+
// Deliberately NOT applied to: the initial send (sendMessage and
|
|
205
|
+
// sendRichMessage are the only streamer verbs that write a transcript row —
|
|
206
|
+
// skipping them is what keeps the marker out of storage without threading a
|
|
207
|
+
// do-not-persist signal through the send path), finalize, or a seal. Those
|
|
208
|
+
// render a bubble that is DONE, and a finished bubble must not claim
|
|
209
|
+
// otherwise.
|
|
210
|
+
toComposingMarker = null,
|
|
211
|
+
// (markdown) -> number of leading source characters a PARTIAL rich render
|
|
212
|
+
// displays. Injected for the same reason toRichPayload is: the streamer
|
|
213
|
+
// does not own the renderer. Defaults to lib/telegram/rich's answer, which
|
|
214
|
+
// is the renderer every polygram caller actually uses; a caller with no
|
|
215
|
+
// rich path never reaches it.
|
|
216
|
+
richVisibleExtent = defaultRichVisibleExtent,
|
|
123
217
|
} = {}) {
|
|
124
218
|
// throttleMs may be a number OR a function evaluated per edit. Telegram's
|
|
125
219
|
// rate limits are per CHAT, but a streamer is per turn — several forum topics
|
|
@@ -139,6 +233,18 @@ function createStreamer({
|
|
|
139
233
|
let hadReplyAnchor = false;
|
|
140
234
|
let currentText = ''; // what's on screen right now (truncated to maxLen) — plain-path only
|
|
141
235
|
let currentRichJson = null; // JSON.stringify of the last-sent rich blocks, or null when not in rich mode
|
|
236
|
+
// Whether the bubble is currently showing the composing marker. Tracked
|
|
237
|
+
// beside the content state rather than inside it: currentText and
|
|
238
|
+
// currentRichJson answer "is the content on screen current?", and folding a
|
|
239
|
+
// presentation suffix into them would re-edit unchanged bubbles. It is a
|
|
240
|
+
// second reason to edit, never a change of what the answer says.
|
|
241
|
+
let currentMarkerShown = false;
|
|
242
|
+
// The source behind what the reader can currently see, recorded by whichever
|
|
243
|
+
// render put it there. The append-only guard pins exactly this: a rich frame
|
|
244
|
+
// contributes the source of the blocks it displayed (the held-back tail was
|
|
245
|
+
// never shown), a plain frame the complete lines it displayed. Empty means
|
|
246
|
+
// nothing has been rendered yet, and nothing may be pinned.
|
|
247
|
+
let pinnedSource = '';
|
|
142
248
|
let latestText = ''; // latest we've been told about
|
|
143
249
|
let lastEditTs = 0;
|
|
144
250
|
let pendingEdit = null; // timer id
|
|
@@ -173,11 +279,11 @@ function createStreamer({
|
|
|
173
279
|
// is coming. Finalize doesn't truncate: overflow is handled by
|
|
174
280
|
// signalling the caller to discard-and-redeliver via chunkMarkdownText,
|
|
175
281
|
// which preserves all content without any byte-cut.
|
|
176
|
-
function truncateForLive(s) {
|
|
177
|
-
if (s.length <=
|
|
282
|
+
function truncateForLive(s, limit = maxLen) {
|
|
283
|
+
if (s.length <= limit) return s;
|
|
178
284
|
// Back off one unit if the cut would split a surrogate pair (emoji /
|
|
179
285
|
// astral chars) — a lone high surrogate renders as � in the live bubble.
|
|
180
|
-
let cut =
|
|
286
|
+
let cut = limit - 3;
|
|
181
287
|
const cc = s.charCodeAt(cut - 1);
|
|
182
288
|
if (cc >= 0xD800 && cc <= 0xDBFF) cut -= 1;
|
|
183
289
|
return s.slice(0, cut) + '...';
|
|
@@ -200,6 +306,33 @@ function createStreamer({
|
|
|
200
306
|
async function onChunk(text) {
|
|
201
307
|
if (state === 'finalized') return;
|
|
202
308
|
text = applyTransform(text);
|
|
309
|
+
|
|
310
|
+
// Snapshots must only ever grow. Backends that build the text by
|
|
311
|
+
// appending satisfy this by construction; a model driving the snapshot
|
|
312
|
+
// itself can send a longer one that dropped earlier sections, and
|
|
313
|
+
// rendering it wipes text the reader is part-way through. Refuse it:
|
|
314
|
+
// leave the bubble on the last good snapshot and let the turn's reply
|
|
315
|
+
// deliver the truth, which is what it does anyway.
|
|
316
|
+
//
|
|
317
|
+
// The pin is what the RENDERER put on screen, recorded when it did — not
|
|
318
|
+
// a boundary re-derived from the accepted text afterwards. Only the
|
|
319
|
+
// renderer knows where its own blocks begin, and a snapshot can be
|
|
320
|
+
// accepted while its edit is still throttled, so "last accepted" and
|
|
321
|
+
// "on screen" are not the same text. Empty until something has actually
|
|
322
|
+
// been rendered, which is what keeps a turn that has not opened a bubble
|
|
323
|
+
// from pinning a greeting nobody saw.
|
|
324
|
+
const pinned = canonicalizeForGuard(pinnedSource);
|
|
325
|
+
if (pinned && !canonicalizeForGuard(text).startsWith(pinned)) {
|
|
326
|
+
try {
|
|
327
|
+
onNonCumulativeSnapshot({
|
|
328
|
+
prevLen: latestText.length,
|
|
329
|
+
newLen: text.length,
|
|
330
|
+
});
|
|
331
|
+
} catch (err) {
|
|
332
|
+
logger.error?.(`[stream] onNonCumulativeSnapshot threw: ${err.message}`);
|
|
333
|
+
}
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
203
336
|
latestText = text;
|
|
204
337
|
|
|
205
338
|
// idle: not yet sent the initial message. Only fire the initial send
|
|
@@ -257,10 +390,22 @@ function createStreamer({
|
|
|
257
390
|
if (res?.wentRich === false) {
|
|
258
391
|
currentText = plainText;
|
|
259
392
|
currentRichJson = null;
|
|
393
|
+
notePinned(shownPlainSource(plainText, text), false);
|
|
260
394
|
} else {
|
|
261
395
|
currentRichJson = JSON.stringify(openRich.blocks);
|
|
396
|
+
notePinned(text, true);
|
|
262
397
|
}
|
|
398
|
+
} else {
|
|
399
|
+
notePinned(shownPlainSource(plainText, text), false);
|
|
263
400
|
}
|
|
401
|
+
// The open carries no marker, and flush only ever runs off a LATER
|
|
402
|
+
// snapshot — so a turn that emits one snapshot and then goes quiet,
|
|
403
|
+
// the sharpest form of "is it still writing or did it die?", would
|
|
404
|
+
// never show one. Schedule the frame that adds it. Content is
|
|
405
|
+
// unchanged, so for a caller with no marker this flush finds nothing
|
|
406
|
+
// to do and issues no edit; gated anyway, since scheduling a timer at
|
|
407
|
+
// all is a change those callers did not ask for.
|
|
408
|
+
if (msgId != null && toComposingMarker) scheduleEdit();
|
|
264
409
|
} catch (err) {
|
|
265
410
|
if (generation !== bubbleGeneration) return;
|
|
266
411
|
logger.error(`[stream] initial send failed: ${err.message}`);
|
|
@@ -311,6 +456,62 @@ function createStreamer({
|
|
|
311
456
|
return payload && payload.usedRich ? payload : null;
|
|
312
457
|
}
|
|
313
458
|
|
|
459
|
+
// The marker for THIS partial render, or null when there is none to show or
|
|
460
|
+
// no room for it. `contentLen` is measured on the content alone and the
|
|
461
|
+
// marker has to fit beside it: a bubble gives up the marker before it gives
|
|
462
|
+
// up a character of the answer.
|
|
463
|
+
// Record what a frame just put on screen, so the guard pins that and only
|
|
464
|
+
// that. `shownSource` is the source the frame rendered; `wasRich` picks
|
|
465
|
+
// which part of it the reader actually saw.
|
|
466
|
+
// The source prefix a plain frame actually displayed. An untruncated frame
|
|
467
|
+
// showed all of it; a truncated one showed everything before the "..." the
|
|
468
|
+
// truncation appended, and pinning past that would pin characters the
|
|
469
|
+
// reader could not see.
|
|
470
|
+
function shownPlainSource(rendered, source) {
|
|
471
|
+
return rendered === source ? source : rendered.slice(0, -3);
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
function notePinned(shownSource, wasRich) {
|
|
475
|
+
// partialVisibleExtent answers from the renderer's own token/block stream,
|
|
476
|
+
// so the pin cannot disagree with what was drawn. Absent (a caller with no
|
|
477
|
+
// rich path at all), a rich frame is impossible anyway.
|
|
478
|
+
const visible = wasRich
|
|
479
|
+
? shownSource.slice(0, richVisibleExtent ? richVisibleExtent(shownSource) : 0)
|
|
480
|
+
: shownSource;
|
|
481
|
+
// Settled, not merely visible. A rich frame with nothing held back — one
|
|
482
|
+
// block, which the renderer draws rather than showing an empty bubble —
|
|
483
|
+
// puts the block being WRITTEN on screen, and the reader is watching it
|
|
484
|
+
// resize. Its finished lines have settled; the line in progress has not,
|
|
485
|
+
// exactly as on the plain path.
|
|
486
|
+
pinnedSource = completeLines(visible);
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
// The marker this render would carry, before any question of whether it
|
|
490
|
+
// fits. `blocks` is the planned content (null on the plain path): the
|
|
491
|
+
// builder needs it because a marker that is styled while the content is not
|
|
492
|
+
// would make polygram's own decoration the thing rich-edit.js's styling
|
|
493
|
+
// verdicts are recorded about.
|
|
494
|
+
function buildComposingMarker(blocks) {
|
|
495
|
+
if (!toComposingMarker) return null;
|
|
496
|
+
let marker;
|
|
497
|
+
try {
|
|
498
|
+
marker = toComposingMarker({ blocks });
|
|
499
|
+
} catch (err) {
|
|
500
|
+
logger.error?.(`[stream] toComposingMarker threw, rendering without it: ${err.message}`);
|
|
501
|
+
return null;
|
|
502
|
+
}
|
|
503
|
+
if (!marker || !marker.block || typeof marker.plainSuffix !== 'string') return null;
|
|
504
|
+
return marker;
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
// Whether `marker` fits beside content of `contentLen` under `cap`. One
|
|
508
|
+
// budget for both shapes: the rich block's rendered weight is the same line
|
|
509
|
+
// of text the plain suffix carries, and a single measurement keeps the two
|
|
510
|
+
// paths from disagreeing about whether there is room.
|
|
511
|
+
function markerFits(marker, contentLen, cap) {
|
|
512
|
+
return marker != null && contentLen + marker.plainSuffix.length <= cap;
|
|
513
|
+
}
|
|
514
|
+
|
|
314
515
|
async function flush() {
|
|
315
516
|
pendingEdit = null;
|
|
316
517
|
if (state !== 'live' || msgId == null) return;
|
|
@@ -347,26 +548,48 @@ function createStreamer({
|
|
|
347
548
|
const richPayload = resolveRichPayload(sourceText, { partial: true });
|
|
348
549
|
if (richPayload) {
|
|
349
550
|
const json = JSON.stringify(richPayload.blocks);
|
|
350
|
-
|
|
551
|
+
const built = buildComposingMarker(richPayload.blocks);
|
|
552
|
+
const marker = markerFits(built, sourceText.length, richMaxLen) ? built : null;
|
|
553
|
+
// Appearing or disappearing is itself a change worth an edit — the
|
|
554
|
+
// content-only comparison would otherwise leave the bubble mismatched.
|
|
555
|
+
if (json === currentRichJson && !!marker === currentMarkerShown) return;
|
|
351
556
|
const wasRich = currentRichJson !== null;
|
|
352
557
|
lastEditTs = clock();
|
|
558
|
+
// Committed BEFORE the await, unlike the content state beside it. This
|
|
559
|
+
// flag's job is to tell a later seal that a marker may be on screen, and
|
|
560
|
+
// a detach landing during this await would otherwise snapshot "no
|
|
561
|
+
// marker" for a bubble about to display one — with nothing left that
|
|
562
|
+
// will ever edit it again. Wrong-in-the-true-direction costs one
|
|
563
|
+
// redundant strip edit; wrong the other way is permanent — which is
|
|
564
|
+
// also why this only ever SETS: a removal is believed once Telegram
|
|
565
|
+
// confirms it, never before.
|
|
566
|
+
if (marker) currentMarkerShown = true;
|
|
353
567
|
try {
|
|
354
568
|
// Keep the source beside its blocks so a content-error fallback
|
|
355
|
-
// can render the same Markdown through the plain-text path.
|
|
569
|
+
// can render the same Markdown through the plain-text path. The
|
|
570
|
+
// marker is not in it: a fallback delivers the answer, not the
|
|
571
|
+
// decoration.
|
|
356
572
|
const editResult = await edit(editMsgId, {
|
|
357
|
-
rich: true,
|
|
573
|
+
rich: true,
|
|
574
|
+
blocks: marker ? [...richPayload.blocks, marker.block] : richPayload.blocks,
|
|
575
|
+
sourceText,
|
|
358
576
|
phase: 'preview', hadReplyAnchor,
|
|
359
577
|
});
|
|
360
578
|
if (generation !== bubbleGeneration || msgId !== editMsgId) return;
|
|
361
579
|
// A rich editor can resolve successfully after sending the same
|
|
362
580
|
// source as plain fallback. Track what actually landed.
|
|
363
581
|
const wentRich = editResult == null || editResult.wentRich !== false;
|
|
582
|
+
currentMarkerShown = !!marker; // confirmed: this frame is on screen
|
|
364
583
|
if (wentRich) {
|
|
365
584
|
currentRichJson = json;
|
|
585
|
+
notePinned(sourceText, true);
|
|
366
586
|
if (!wasRich) onRichUpgrade();
|
|
367
587
|
} else {
|
|
588
|
+
// The fallback rendered sourceText, which never carries the marker.
|
|
368
589
|
currentText = sourceText;
|
|
369
590
|
currentRichJson = null;
|
|
591
|
+
currentMarkerShown = false;
|
|
592
|
+
notePinned(sourceText, false);
|
|
370
593
|
}
|
|
371
594
|
} catch (err) {
|
|
372
595
|
logger.error(`[stream] rich edit failed: ${err.message}`);
|
|
@@ -374,14 +597,30 @@ function createStreamer({
|
|
|
374
597
|
return;
|
|
375
598
|
}
|
|
376
599
|
|
|
377
|
-
const
|
|
378
|
-
|
|
600
|
+
const built = buildComposingMarker(null);
|
|
601
|
+
let next = truncateForLive(sourceText);
|
|
602
|
+
let marker = markerFits(built, next.length, maxLen) ? built : null;
|
|
603
|
+
if (built && !marker && sourceText.length > maxLen) {
|
|
604
|
+
// The bubble is already eliding — the text on screen is a view of the
|
|
605
|
+
// answer, not the answer, and finalize delivers the whole thing. Moving
|
|
606
|
+
// the cut back far enough to keep the marker costs nothing anyone would
|
|
607
|
+
// otherwise have read, and a reply long enough to be truncated is the
|
|
608
|
+
// one that streams longest and most needs to say it is still going.
|
|
609
|
+
// Content that fits WITHOUT truncation is never cut to make room: there
|
|
610
|
+
// the marker gives way instead.
|
|
611
|
+
next = truncateForLive(sourceText, maxLen - built.plainSuffix.length);
|
|
612
|
+
marker = built;
|
|
613
|
+
}
|
|
614
|
+
if (currentRichJson === null && next === currentText && !!marker === currentMarkerShown) return;
|
|
379
615
|
lastEditTs = clock();
|
|
616
|
+
if (marker) currentMarkerShown = true; // before the await — see the rich branch
|
|
380
617
|
try {
|
|
381
|
-
await edit(editMsgId, next);
|
|
618
|
+
await edit(editMsgId, marker ? next + marker.plainSuffix : next);
|
|
382
619
|
if (generation !== bubbleGeneration || msgId !== editMsgId) return;
|
|
383
620
|
currentText = next;
|
|
384
621
|
currentRichJson = null;
|
|
622
|
+
currentMarkerShown = !!marker;
|
|
623
|
+
notePinned(shownPlainSource(next, sourceText), false);
|
|
385
624
|
} catch (err) {
|
|
386
625
|
// Non-fatal — maybe 429 or transient. Log and keep going; next
|
|
387
626
|
// chunk will retry. The HTML→plain fallback in lib/telegram.js
|
|
@@ -445,23 +684,75 @@ function createStreamer({
|
|
|
445
684
|
if (snapshot.flushPromise) {
|
|
446
685
|
await awaitDetached(snapshot.flushPromise, 'detached bubble flush');
|
|
447
686
|
}
|
|
448
|
-
if (targetMsgId == null
|
|
687
|
+
if (targetMsgId == null) return;
|
|
688
|
+
|
|
689
|
+
// This bubble is finished — the stream has moved to a new one and nothing
|
|
690
|
+
// will edit this again. A composing marker on it is now a lie, so it is a
|
|
691
|
+
// reason to seal in its own right, alongside media that never resolved.
|
|
692
|
+
const stripMarker = snapshot.markerShown === true;
|
|
693
|
+
|
|
694
|
+
const payload = (toRichPayload && snapshot.sourceText.length <= richMaxLen)
|
|
695
|
+
? toRichPayload(snapshot.sourceText, { partial: false })
|
|
696
|
+
: null;
|
|
697
|
+
|
|
698
|
+
if (payload?.usedRich) {
|
|
699
|
+
const hasRescue = Array.isArray(payload.rescueEntries) && payload.rescueEntries.length > 0;
|
|
700
|
+
if (!hasRescue && !stripMarker) return;
|
|
701
|
+
const json = JSON.stringify(payload.blocks);
|
|
702
|
+
// Identical blocks still need the edit when a marker block is riding on
|
|
703
|
+
// top of them — that extra block is exactly what has to go.
|
|
704
|
+
if (json === snapshot.currentRichJson && !stripMarker) return;
|
|
449
705
|
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
706
|
+
await editWithRetry(targetMsgId, {
|
|
707
|
+
rich: true,
|
|
708
|
+
blocks: payload.blocks,
|
|
709
|
+
sourceText: snapshot.sourceText,
|
|
710
|
+
phase: 'seal',
|
|
711
|
+
hadReplyAnchor: targetHadReplyAnchor,
|
|
712
|
+
});
|
|
453
713
|
return;
|
|
454
714
|
}
|
|
455
|
-
|
|
456
|
-
if (
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
715
|
+
|
|
716
|
+
if (!stripMarker) return;
|
|
717
|
+
|
|
718
|
+
// A RICH bubble whose final render declined rich still has to lose its
|
|
719
|
+
// marker, and it must not lose its document doing so: toRichPayload can
|
|
720
|
+
// render rich while partial and decline at partial:false (rich.js demotes
|
|
721
|
+
// a media-only document whose media never resolved, gated on !partial so
|
|
722
|
+
// it cannot fire during the live ticks). The blocks already on screen are
|
|
723
|
+
// recorded — re-send exactly those, which differ from what is displayed
|
|
724
|
+
// only by the marker that was appended after them.
|
|
725
|
+
if (snapshot.currentRichJson !== null) {
|
|
726
|
+
await editWithRetry(targetMsgId, {
|
|
727
|
+
rich: true,
|
|
728
|
+
blocks: JSON.parse(snapshot.currentRichJson),
|
|
729
|
+
sourceText: snapshot.sourceText,
|
|
730
|
+
phase: 'seal',
|
|
731
|
+
hadReplyAnchor: targetHadReplyAnchor,
|
|
732
|
+
});
|
|
733
|
+
return;
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
// A plain bubble: the content alone is the same text it already shows,
|
|
737
|
+
// minus the marker. truncateForLive keeps the plain path's existing cap
|
|
738
|
+
// contract rather than inventing a second one here.
|
|
739
|
+
await editWithRetry(targetMsgId, truncateForLive(snapshot.sourceText));
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
// A seal is the LAST edit a detached bubble will ever get — appendSealJob
|
|
743
|
+
// logs a failure and moves on, and no turn-end pass revisits it. A transient
|
|
744
|
+
// failure would therefore strand whatever the seal was removing, forever, so
|
|
745
|
+
// it is worth exactly one more attempt.
|
|
746
|
+
// Silent on the first failure by design: appendSealJob reports the one that
|
|
747
|
+
// sticks, and it reports the error CLASS rather than the message because a
|
|
748
|
+
// seal error can name a media path. A retry line carrying err.message would
|
|
749
|
+
// put that path in the log this module works to keep it out of.
|
|
750
|
+
async function editWithRetry(targetMsgId, payload) {
|
|
751
|
+
try {
|
|
752
|
+
await edit(targetMsgId, payload);
|
|
753
|
+
} catch {
|
|
754
|
+
await edit(targetMsgId, payload);
|
|
755
|
+
}
|
|
465
756
|
}
|
|
466
757
|
|
|
467
758
|
// 0.7.0: explicitly drain any pending edit. Useful when the caller
|
|
@@ -499,6 +790,7 @@ function createStreamer({
|
|
|
499
790
|
msgId,
|
|
500
791
|
hadReplyAnchor,
|
|
501
792
|
currentRichJson,
|
|
793
|
+
markerShown: currentMarkerShown,
|
|
502
794
|
initialSendPromise,
|
|
503
795
|
flushPromise,
|
|
504
796
|
};
|
|
@@ -514,6 +806,8 @@ function createStreamer({
|
|
|
514
806
|
hadReplyAnchor = false;
|
|
515
807
|
currentText = '';
|
|
516
808
|
currentRichJson = null; // new bubble starts plain — see toRichPayload doc
|
|
809
|
+
currentMarkerShown = false;
|
|
810
|
+
pinnedSource = ''; // a new bubble has shown the reader nothing yet
|
|
517
811
|
latestText = '';
|
|
518
812
|
state = 'idle';
|
|
519
813
|
lastEditTs = 0;
|
|
@@ -629,7 +923,10 @@ function createStreamer({
|
|
|
629
923
|
};
|
|
630
924
|
}
|
|
631
925
|
const json = JSON.stringify(richPayload.blocks);
|
|
632
|
-
|
|
926
|
+
// A bubble showing the composing marker is NOT already correct, however
|
|
927
|
+
// right its content is — skipping the edit here would leave the finished
|
|
928
|
+
// answer claiming to still be written, permanently.
|
|
929
|
+
if (json === currentRichJson && !currentMarkerShown) {
|
|
633
930
|
return { streamed: true, msgId, finalText: body, finalEditOk: true, overflow: false };
|
|
634
931
|
}
|
|
635
932
|
const wasRich = currentRichJson !== null;
|
|
@@ -640,6 +937,7 @@ function createStreamer({
|
|
|
640
937
|
});
|
|
641
938
|
// A fallback still delivered the final content, but as plain text.
|
|
642
939
|
const wentRich = editResult == null || editResult.wentRich !== false;
|
|
940
|
+
currentMarkerShown = false; // whichever shape landed, it was the final render
|
|
643
941
|
if (wentRich) {
|
|
644
942
|
currentRichJson = json;
|
|
645
943
|
if (!wasRich) onRichUpgrade();
|
|
@@ -677,14 +975,16 @@ function createStreamer({
|
|
|
677
975
|
// without redelivering. If it fails (e.g. parse error after our
|
|
678
976
|
// wrapper exhausts its retry, or a 5xx), caller should discard
|
|
679
977
|
// and redeliver — the bubble's content is unreliable.
|
|
680
|
-
|
|
681
|
-
|
|
978
|
+
// Already correct — no edit needed. A marker on screen means it is not:
|
|
979
|
+
// the content matches, the bubble still says it is being written.
|
|
980
|
+
if (currentRichJson === null && body === currentText && !currentMarkerShown) {
|
|
682
981
|
return { streamed: true, msgId, finalText: body, finalEditOk: true, overflow: false };
|
|
683
982
|
}
|
|
684
983
|
try {
|
|
685
984
|
await edit(msgId, body);
|
|
686
985
|
currentText = body;
|
|
687
986
|
currentRichJson = null;
|
|
987
|
+
currentMarkerShown = false;
|
|
688
988
|
return { streamed: true, msgId, finalText: body, finalEditOk: true, overflow: false };
|
|
689
989
|
} catch (err) {
|
|
690
990
|
logger.error(`[stream] final edit failed: ${err.message}`);
|
|
@@ -722,6 +1022,7 @@ function createStreamer({
|
|
|
722
1022
|
|
|
723
1023
|
module.exports = {
|
|
724
1024
|
createStreamer,
|
|
1025
|
+
completeLines,
|
|
725
1026
|
DEFAULT_MIN_CHARS,
|
|
726
1027
|
DEFAULT_THROTTLE_MS,
|
|
727
1028
|
};
|
|
@@ -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.
|
|
3
|
+
"version": "0.33.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.
|
|
66
|
+
"@shumkov/orchestra": "0.10.7",
|
|
67
67
|
"better-sqlite3": "^12.9.0",
|
|
68
68
|
"grammy": "^1.42.0",
|
|
69
69
|
"markdown-it": "^14.1.1",
|