polygram 0.23.3 → 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/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 +342 -21
|
@@ -0,0 +1,403 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The live-preview bubble's lifecycle, outside handleMessage's closure.
|
|
3
|
+
*
|
|
4
|
+
* A streamer is created per turn inside handleMessage, but three things need to
|
|
5
|
+
* reach it from elsewhere:
|
|
6
|
+
*
|
|
7
|
+
* 1. The CLI reply path. Replies arrive through the channels tool dispatcher,
|
|
8
|
+
* a different call stack entirely, and a reply must CONSUME the live
|
|
9
|
+
* preview rather than send a second bubble under it saying the same thing.
|
|
10
|
+
* 2. Turn-completion exits. A turn can end many ways, and each one has to
|
|
11
|
+
* settle whatever the preview is holding — identically.
|
|
12
|
+
* 3. The edit cadence. Telegram rate-limits per CHAT, but forum topics share
|
|
13
|
+
* one chat_id and each live topic edits at its own 1 Hz.
|
|
14
|
+
*
|
|
15
|
+
* The registry keyed on sessionKey answers all three — polygram's own
|
|
16
|
+
* bookkeeping, not a reach into process-manager internals.
|
|
17
|
+
*
|
|
18
|
+
* The governing rule, stated once: a live preview ALWAYS consumes the next
|
|
19
|
+
* non-interim reply; a new bubble is sent only when no preview is live. Every
|
|
20
|
+
* turn shape in this module follows from it.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
'use strict';
|
|
24
|
+
|
|
25
|
+
const { resolveBoolOverride } = require('../config-override');
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Per-chat opt-in for the CLI `stream` tool. Default OFF: registering the tool
|
|
29
|
+
* changes what the agent is taught to do, so it rolls out per chat rather than
|
|
30
|
+
* fleet-wide.
|
|
31
|
+
*/
|
|
32
|
+
function resolveStreamPreviewEnabled(config, chatId, threadId = null) {
|
|
33
|
+
return resolveBoolOverride(config, 'streamPreview', chatId, threadId);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function createStreamerRegistry() {
|
|
37
|
+
const bySessionKey = new Map(); // sessionKey → { streamer, chatId }
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Register the turn's streamer. Returns a release function that removes the
|
|
41
|
+
* entry ONLY if it is still the one registered here — a later turn on the
|
|
42
|
+
* same session that has already taken over must not be evicted by an earlier
|
|
43
|
+
* turn's cleanup.
|
|
44
|
+
*/
|
|
45
|
+
function register(sessionKey, { streamer, chatId, deliveredTexts = [], getTurnId = null }) {
|
|
46
|
+
if (sessionKey == null || !streamer) return () => {};
|
|
47
|
+
// deliveredTexts is the CALLER's array by reference: the reply path appends
|
|
48
|
+
// to it here, and the turn's own reconciliation reads it from the handler's
|
|
49
|
+
// closure. One list, two readers, no copy to fall out of date.
|
|
50
|
+
const entry = {
|
|
51
|
+
streamer,
|
|
52
|
+
chatId: String(chatId),
|
|
53
|
+
deliveredTexts,
|
|
54
|
+
// Read lazily: the engine publishes the turn id onto the caller's context
|
|
55
|
+
// object during dispatch, which happens after registration.
|
|
56
|
+
getTurnId: typeof getTurnId === 'function' ? getTurnId : () => null,
|
|
57
|
+
// Text handed to the delivery pipeline but not yet confirmed delivered.
|
|
58
|
+
// Promoted into deliveredTexts only once the send succeeds — a failed
|
|
59
|
+
// reply the user never saw must not make a later draft look redundant.
|
|
60
|
+
pendingDelivered: null,
|
|
61
|
+
// Replies are serialized through this: two concurrent calls would
|
|
62
|
+
// otherwise race one preview through flush/finalize/discard.
|
|
63
|
+
chain: Promise.resolve(),
|
|
64
|
+
};
|
|
65
|
+
bySessionKey.set(sessionKey, entry);
|
|
66
|
+
return () => {
|
|
67
|
+
if (bySessionKey.get(sessionKey) === entry) bySessionKey.delete(sessionKey);
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function get(sessionKey) {
|
|
72
|
+
return sessionKey == null ? null : (bySessionKey.get(sessionKey) || null);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** How many previews are currently live (initial send landed) in this chat. */
|
|
76
|
+
function liveCount(chatId) {
|
|
77
|
+
const want = String(chatId);
|
|
78
|
+
let n = 0;
|
|
79
|
+
for (const entry of bySessionKey.values()) {
|
|
80
|
+
if (entry.chatId === want && entry.streamer.state === 'live') n += 1;
|
|
81
|
+
}
|
|
82
|
+
return n;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* A reply's text has been handed to the delivery pipeline but has not landed
|
|
87
|
+
* yet. Held aside until settlePending says whether it did.
|
|
88
|
+
*/
|
|
89
|
+
function notePending(sessionKey, text) {
|
|
90
|
+
const entry = get(sessionKey);
|
|
91
|
+
if (entry) entry.pendingDelivered = typeof text === 'string' ? text : null;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* The pipeline finished. On success the text joins the delivered set; on
|
|
96
|
+
* failure it is dropped, because the user never saw it and a later draft
|
|
97
|
+
* repeating it is the only copy they will get.
|
|
98
|
+
*/
|
|
99
|
+
function settlePending(sessionKey, ok) {
|
|
100
|
+
const entry = get(sessionKey);
|
|
101
|
+
if (!entry) return;
|
|
102
|
+
if (ok && entry.pendingDelivered) entry.deliveredTexts.push(entry.pendingDelivered);
|
|
103
|
+
entry.pendingDelivered = null;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
return {
|
|
107
|
+
register, get, liveCount, notePending, settlePending,
|
|
108
|
+
get size() { return bySessionKey.size; },
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Is the draft's content already in the user's hands?
|
|
114
|
+
*
|
|
115
|
+
* A delivered reply must contain the COMPLETE draft. The containment is
|
|
116
|
+
* deliberately one-directional: `reply("A")` followed by `stream("A and also
|
|
117
|
+
* B")` is NOT covered — the draft holds B, which nobody delivered, and treating
|
|
118
|
+
* the shorter reply as covering it deletes B for good. Only "everything the
|
|
119
|
+
* draft says has already been said" justifies discarding it.
|
|
120
|
+
*/
|
|
121
|
+
function isCoveredByDelivered(latestText, deliveredTexts) {
|
|
122
|
+
const norm = (s) => String(s || '').replace(/\s+/g, ' ').trim();
|
|
123
|
+
const draft = norm(latestText);
|
|
124
|
+
if (!draft) return true; // nothing to lose
|
|
125
|
+
for (const delivered of (deliveredTexts || [])) {
|
|
126
|
+
const d = norm(delivered);
|
|
127
|
+
if (d && d.includes(draft)) return true;
|
|
128
|
+
}
|
|
129
|
+
return false;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Settle a live preview at any turn-completion exit — the shared answer to
|
|
134
|
+
* "the turn is over; what happens to the half-written bubble?"
|
|
135
|
+
*
|
|
136
|
+
* Every exit runs this, so there is one rule instead of one decision per exit:
|
|
137
|
+
*
|
|
138
|
+
* - not live → nothing to settle.
|
|
139
|
+
* - the draft's content was already delivered by a reply → delete it; leaving
|
|
140
|
+
* it would show the answer twice.
|
|
141
|
+
* - reason 'no-reply' → delete it. The agent explicitly chose silence,
|
|
142
|
+
* and a half-written draft is not consent to speak.
|
|
143
|
+
* - otherwise → finalize it in place. The turn ended holding
|
|
144
|
+
* text nobody else delivered (it died mid-compose, or answered via a
|
|
145
|
+
* stream call and never replied) — the user should get what was written,
|
|
146
|
+
* not an empty chat.
|
|
147
|
+
*
|
|
148
|
+
* @param {object|null} streamer
|
|
149
|
+
* @param {string[]} deliveredTexts — reply bodies this turn already delivered
|
|
150
|
+
* @param {object} [opts]
|
|
151
|
+
* @param {?string} [opts.reason] — 'no-reply' honors an explicit silence
|
|
152
|
+
* @param {?Function} [opts.logEvent]
|
|
153
|
+
* @param {object} [opts.detail] — merged into the emitted event
|
|
154
|
+
* @param {?Function} [opts.redeliver] — async (text) → boolean. Used when the
|
|
155
|
+
* draft cannot fit one bubble: same escape hatch the consume rule has, so an
|
|
156
|
+
* over-long orphan is delivered whole instead of surviving as a truncation.
|
|
157
|
+
* @returns {Promise<{action: 'none'|'discarded'|'finalized'|'redelivered'|'finalize-failed', msgId: ?number, text: ?string}>}
|
|
158
|
+
*/
|
|
159
|
+
async function reconcileStreamer(streamer, deliveredTexts = [], {
|
|
160
|
+
reason = null,
|
|
161
|
+
logEvent = null,
|
|
162
|
+
detail = {},
|
|
163
|
+
redeliver = null,
|
|
164
|
+
} = {}) {
|
|
165
|
+
if (!streamer) return { action: 'none', msgId: null, text: null };
|
|
166
|
+
|
|
167
|
+
// Drains the pending throttled edit AND the in-flight initial send, so the
|
|
168
|
+
// state and msgId read below are the real ones.
|
|
169
|
+
try { await streamer.flushDraft(); } catch { /* best effort */ }
|
|
170
|
+
if (streamer.state !== 'live') return { action: 'none', msgId: null, text: null };
|
|
171
|
+
|
|
172
|
+
const latest = streamer.latestText || '';
|
|
173
|
+
const covered = isCoveredByDelivered(latest, deliveredTexts);
|
|
174
|
+
|
|
175
|
+
if (covered || reason === 'no-reply') {
|
|
176
|
+
let discarded = { msgId: streamer.msgId, deleted: false };
|
|
177
|
+
try { discarded = await streamer.discard(); } catch { /* bubble may be gone */ }
|
|
178
|
+
logEvent?.('stream-orphan-discarded', {
|
|
179
|
+
...detail,
|
|
180
|
+
reason: reason || (latest.trim() ? 'covered-by-reply' : 'empty-draft'),
|
|
181
|
+
deleted: discarded.deleted === true,
|
|
182
|
+
});
|
|
183
|
+
return { action: 'discarded', msgId: discarded.msgId ?? null, text: null };
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const fin = await streamer.finalize(latest);
|
|
187
|
+
if (fin.finalEditOk && fin.msgId != null) {
|
|
188
|
+
logEvent?.('stream-orphan-finalized', { ...detail, reason: reason || 'undelivered-draft', len: latest.length });
|
|
189
|
+
return { action: 'finalized', msgId: fin.msgId, text: fin.finalText ?? latest };
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// The draft outgrew one bubble, or the last edit failed. The bubble holds at
|
|
193
|
+
// best a truncation of the answer, so hand the WHOLE text to the chunked path
|
|
194
|
+
// and delete the stump — the same escape the consume rule takes, for the same
|
|
195
|
+
// reason: a preview must never be the only copy of a partial answer.
|
|
196
|
+
if (typeof redeliver === 'function') {
|
|
197
|
+
let sent = false;
|
|
198
|
+
try { sent = await redeliver(fin.finalText ?? latest); } catch { sent = false; }
|
|
199
|
+
if (sent) {
|
|
200
|
+
try { await streamer.discard(); } catch { /* bubble may be gone */ }
|
|
201
|
+
logEvent?.('stream-orphan-redelivered', {
|
|
202
|
+
...detail,
|
|
203
|
+
reason: fin.overflow ? 'overflow' : 'edit-failed',
|
|
204
|
+
len: latest.length,
|
|
205
|
+
});
|
|
206
|
+
return { action: 'redelivered', msgId: null, text: fin.finalText ?? latest };
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// No redelivery path, or it failed. Leave the bubble standing: deleting it
|
|
211
|
+
// would destroy the only copy the user has.
|
|
212
|
+
logEvent?.('stream-orphan-finalize-failed', {
|
|
213
|
+
...detail,
|
|
214
|
+
overflow: fin.overflow === true,
|
|
215
|
+
len: latest.length,
|
|
216
|
+
});
|
|
217
|
+
return { action: 'finalize-failed', msgId: fin.msgId ?? null, text: latest };
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Bind the turn-completion rule to one turn's state.
|
|
222
|
+
*
|
|
223
|
+
* handleMessage calls the returned `settle(reason)` at every exit. Everything
|
|
224
|
+
* the settlement DOES — reconcile, bring the transcript row along, hand an
|
|
225
|
+
* over-long draft to the chunked path — lives here rather than in the handler's
|
|
226
|
+
* closure, so it can be executed in a test instead of only pattern-matched in
|
|
227
|
+
* the source.
|
|
228
|
+
*
|
|
229
|
+
* @param {object} deps
|
|
230
|
+
* @param {?object} deps.streamer
|
|
231
|
+
* @param {string[]} deps.deliveredTexts
|
|
232
|
+
* @param {boolean} [deps.enabled] — false makes settle a no-op, so a chat
|
|
233
|
+
* without live previews behaves exactly as it did before this feature
|
|
234
|
+
* @param {?Function} [deps.persistBubbleText] — (chatId, msgId, text) → void
|
|
235
|
+
* @param {?Function} [deps.redeliver] — async (text) → boolean
|
|
236
|
+
* @param {?Function} [deps.logEvent]
|
|
237
|
+
* @param {string|number} [deps.chatId]
|
|
238
|
+
* @param {object} [deps.detail] — merged into emitted events
|
|
239
|
+
*/
|
|
240
|
+
function createTurnSettler({
|
|
241
|
+
streamer,
|
|
242
|
+
deliveredTexts,
|
|
243
|
+
enabled = true,
|
|
244
|
+
persistBubbleText = null,
|
|
245
|
+
redeliver = null,
|
|
246
|
+
logEvent = null,
|
|
247
|
+
chatId = null,
|
|
248
|
+
detail = {},
|
|
249
|
+
} = {}) {
|
|
250
|
+
return async function settle(reason = null) {
|
|
251
|
+
if (!enabled) return { action: 'none', msgId: null, text: null };
|
|
252
|
+
const res = await reconcileStreamer(streamer, deliveredTexts, {
|
|
253
|
+
reason, logEvent, detail, redeliver,
|
|
254
|
+
});
|
|
255
|
+
// The bubble now holds the final body; its row still holds the ~30
|
|
256
|
+
// characters the initial send wrote.
|
|
257
|
+
if (res.action === 'finalized') persistBubbleText?.(chatId, res.msgId, res.text);
|
|
258
|
+
return res;
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* The reply-side half of the rule: build the `deliverText` strategy factory the
|
|
264
|
+
* channels dispatcher hands to the agent-reply pipeline.
|
|
265
|
+
*
|
|
266
|
+
* `makeDeliverText({sessionKey, chatId, threadId, interim, turnId})` returns
|
|
267
|
+
* either a strategy or null (no live-preview surface for that session → the
|
|
268
|
+
* pipeline delivers normally).
|
|
269
|
+
*
|
|
270
|
+
* @param {object} deps
|
|
271
|
+
* @param {object} deps.registry — createStreamerRegistry() instance
|
|
272
|
+
* @param {Function} [deps.logEvent] — (kind, detail) → void
|
|
273
|
+
* @param {Function} [deps.persistBubbleText] — (chatId, msgId, text) → void
|
|
274
|
+
* @param {object} [deps.logger]
|
|
275
|
+
* @param {?string} [deps.botName] — event payload tag
|
|
276
|
+
*/
|
|
277
|
+
function createDeliverTextFactory({
|
|
278
|
+
registry,
|
|
279
|
+
logEvent = null,
|
|
280
|
+
persistBubbleText = null,
|
|
281
|
+
logger = console,
|
|
282
|
+
botName = null,
|
|
283
|
+
} = {}) {
|
|
284
|
+
return function makeDeliverText({ sessionKey, chatId, interim, turnId } = {}) {
|
|
285
|
+
const entry = registry.get(sessionKey);
|
|
286
|
+
if (!entry) return null; // no live-preview surface for this turn
|
|
287
|
+
const { streamer } = entry;
|
|
288
|
+
|
|
289
|
+
return function deliverText({ text }) {
|
|
290
|
+
// Replies are serialized per session. Two concurrent calls would
|
|
291
|
+
// otherwise race one preview through flushDraft → finalize → discard →
|
|
292
|
+
// forceNewMessage and interleave halfway, consuming the same bubble
|
|
293
|
+
// twice or deleting one the other just finalized.
|
|
294
|
+
const run = entry.chain.then(() => consume({ text }));
|
|
295
|
+
entry.chain = run.then(() => {}, () => {});
|
|
296
|
+
return run;
|
|
297
|
+
};
|
|
298
|
+
|
|
299
|
+
async function consume({ text }) {
|
|
300
|
+
// A reply is bound to the turn it names. A delayed reply from an earlier
|
|
301
|
+
// turn must not finalize the CURRENT turn's preview with stale text; it
|
|
302
|
+
// still gets delivered, just as its own bubble.
|
|
303
|
+
const ownTurnId = entry.getTurnId();
|
|
304
|
+
const turnMismatch = turnId != null && ownTurnId != null && turnId !== ownTurnId;
|
|
305
|
+
|
|
306
|
+
// An interim status is not the turn's answer, so its text must never
|
|
307
|
+
// enter the coverage set: a later draft holding the status AND the answer
|
|
308
|
+
// would look covered and be deleted.
|
|
309
|
+
if (!interim) entry.pendingDelivered = text;
|
|
310
|
+
|
|
311
|
+
// Drains the pending throttled edit AND the in-flight initial send, so
|
|
312
|
+
// the state and msgId read below are the real ones.
|
|
313
|
+
await streamer.flushDraft();
|
|
314
|
+
|
|
315
|
+
// An interim status must not eat the preview the answer is still being
|
|
316
|
+
// written into. It goes out as its own bubble; forceNewMessage then opens
|
|
317
|
+
// the next preview BELOW it, which keeps the visual order truthful.
|
|
318
|
+
if (interim || turnMismatch || streamer.state !== 'live') {
|
|
319
|
+
if (turnMismatch) {
|
|
320
|
+
logEvent?.('stream-preview-turn-mismatch', {
|
|
321
|
+
chat_id: chatId, session_key: sessionKey,
|
|
322
|
+
reply_turn_id: turnId, preview_turn_id: ownTurnId, bot: botName,
|
|
323
|
+
});
|
|
324
|
+
}
|
|
325
|
+
detachCurrentPreview();
|
|
326
|
+
return { handled: false };
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
const fin = await streamer.finalize(text);
|
|
330
|
+
// finalEditOk with no msgId means the bubble is gone (a rich edit removed
|
|
331
|
+
// it). There is nothing to hand back as the reply's message_id, so this
|
|
332
|
+
// is a fallthrough, not a consumption — never answer {ok:true, id:null}.
|
|
333
|
+
if (fin.streamed && fin.finalEditOk && fin.msgId != null) {
|
|
334
|
+
openNextPreview();
|
|
335
|
+
persistBubbleText?.(chatId, fin.msgId, fin.finalText ?? text);
|
|
336
|
+
if (!interim) {
|
|
337
|
+
// The finalize edit IS the delivery, and it succeeded.
|
|
338
|
+
entry.pendingDelivered = null;
|
|
339
|
+
entry.deliveredTexts.push(text);
|
|
340
|
+
}
|
|
341
|
+
logEvent?.('stream-preview-consumed', {
|
|
342
|
+
chat_id: chatId, session_key: sessionKey,
|
|
343
|
+
msg_id: fin.msgId, chars: text.length, bot: botName,
|
|
344
|
+
});
|
|
345
|
+
return { handled: true, sent: [fin.msgId], failed: [] };
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
// The answer outgrew one bubble (the common case past 4,096 characters)
|
|
349
|
+
// or the last edit failed. Delete the preview and let the normal chunked
|
|
350
|
+
// path deliver the whole thing at the bottom of the chat — no content is
|
|
351
|
+
// lost, and no stale half-answer is left standing above it.
|
|
352
|
+
try { await streamer.discard(); }
|
|
353
|
+
catch (err) { logger?.error?.(`[live-preview] discard failed: ${err.message}`); }
|
|
354
|
+
openNextPreview();
|
|
355
|
+
logEvent?.('stream-preview-redelivered', {
|
|
356
|
+
chat_id: chatId, session_key: sessionKey,
|
|
357
|
+
reason: fin.overflow ? 'overflow' : 'edit-failed',
|
|
358
|
+
chars: text.length, bot: botName,
|
|
359
|
+
});
|
|
360
|
+
return { handled: false };
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/**
|
|
364
|
+
* Open a fresh preview slot after WE settled the bubble (finalized it into
|
|
365
|
+
* a reply, or discarded it). Unconditional: we know the settle just
|
|
366
|
+
* happened and that the next snapshot deserves a new bubble below it.
|
|
367
|
+
*/
|
|
368
|
+
function openNextPreview() {
|
|
369
|
+
streamer.forceNewMessage();
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/**
|
|
373
|
+
* Leave the current preview standing and open a fresh slot below it — the
|
|
374
|
+
* interim-status path, where the bubble is substantive content the user
|
|
375
|
+
* should keep reading.
|
|
376
|
+
*
|
|
377
|
+
* A streamer someone ELSE settled is left completely alone. forceNewMessage
|
|
378
|
+
* resets state to 'idle', so calling it on a finalized streamer un-finalizes
|
|
379
|
+
* it, and a chunk arriving afterwards opens a bubble that no turn-completion
|
|
380
|
+
* exit will ever reconcile.
|
|
381
|
+
*
|
|
382
|
+
* The persist covers the bubble being left behind: it keeps whatever it last
|
|
383
|
+
* showed on screen, but its transcript row still holds the first ~30
|
|
384
|
+
* characters from the initial send, and no edit ever revisits that row.
|
|
385
|
+
*/
|
|
386
|
+
function detachCurrentPreview() {
|
|
387
|
+
if (streamer.state === 'finalized') return;
|
|
388
|
+
if (streamer.state === 'live') {
|
|
389
|
+
persistBubbleText?.(chatId, streamer.msgId, streamer.latestText);
|
|
390
|
+
}
|
|
391
|
+
streamer.forceNewMessage();
|
|
392
|
+
}
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
module.exports = {
|
|
397
|
+
createStreamerRegistry,
|
|
398
|
+
createDeliverTextFactory,
|
|
399
|
+
createTurnSettler,
|
|
400
|
+
reconcileStreamer,
|
|
401
|
+
isCoveredByDelivered,
|
|
402
|
+
resolveStreamPreviewEnabled,
|
|
403
|
+
};
|
|
@@ -65,11 +65,28 @@
|
|
|
65
65
|
* @param {Function} opts.sanitizeAssistantReply — text → { text, replaced, original? }
|
|
66
66
|
* @param {Function} opts.chunkMarkdownText — (text, budget) → string[]
|
|
67
67
|
* @param {Function} opts.deliverReplies — async ({ bot, send, chatId, threadId, chunks, replyToMessageId, meta, logger }) → { sent, failed }
|
|
68
|
+
* @param {Function} [opts.deliverText] — optional delivery strategy replacing ONLY the
|
|
69
|
+
* chunk+deliver step. Called as ({ text, chatId, threadId, replyToMessageId, meta }) and
|
|
70
|
+
* returns { handled, text?, sent?, failed?, results? }. `handled: true` makes its result
|
|
71
|
+
* the deliverResult; `handled: false` falls through to chunk+deliver, using `text` as the
|
|
72
|
+
* body when the strategy supplied a replacement. Runs after parse/redact/sanitize and
|
|
73
|
+
* before stickers/reactions, exactly once per reply. Callers that omit it deliver exactly
|
|
74
|
+
* as before.
|
|
75
|
+
* @param {(text: string) => string} [opts.sanitizeFallbackText] — projection applied
|
|
76
|
+
* to the body the chunked path delivers, whatever route led there. Deliberately
|
|
77
|
+
* NOT owned by the delivery strategy: a chat's text hygiene must survive that
|
|
78
|
+
* strategy failing to build, failing to run, or simply declining.
|
|
79
|
+
* @param {(s: string) => string} [opts.redactError] — strips bot tokens from a logged
|
|
80
|
+
* strategy error; network error shapes can embed the request URL
|
|
68
81
|
* @param {number} [opts.chunkBudget=3500]
|
|
69
82
|
* @param {Function} [opts.logEvent] — (kind, detail) → void
|
|
70
83
|
* @param {?string|number} [opts.sessionKey] — for event payloads
|
|
71
84
|
* @param {object} [opts.logger] — { log, error }
|
|
72
|
-
* @returns {Promise<{ deliverResult: ?object, stickersSent: number, reactionsApplied: number,
|
|
85
|
+
* @returns {Promise<{ deliverResult: ?object, stickersSent: number, reactionsApplied: number,
|
|
86
|
+
* reactionsDropped: number, sanitizerReplaced: boolean, secretsRedacted: number,
|
|
87
|
+
* emptiedByStrategy?: boolean }>} — `emptiedByStrategy` marks a reply whose text
|
|
88
|
+
* projected away entirely, so nothing was delivered and the caller must decide
|
|
89
|
+
* what to tell the agent.
|
|
73
90
|
*/
|
|
74
91
|
async function processAndDeliverAgentText({
|
|
75
92
|
text,
|
|
@@ -85,6 +102,9 @@ async function processAndDeliverAgentText({
|
|
|
85
102
|
sanitizeAssistantReply,
|
|
86
103
|
chunkMarkdownText,
|
|
87
104
|
deliverReplies,
|
|
105
|
+
deliverText = null,
|
|
106
|
+
sanitizeFallbackText = null,
|
|
107
|
+
redactError = (s) => s,
|
|
88
108
|
chunkBudget = 3500,
|
|
89
109
|
logEvent = null,
|
|
90
110
|
sessionKey = null,
|
|
@@ -152,20 +172,76 @@ async function processAndDeliverAgentText({
|
|
|
152
172
|
}
|
|
153
173
|
}
|
|
154
174
|
|
|
155
|
-
// 3. Deliver text
|
|
156
|
-
//
|
|
175
|
+
// 3. Deliver text. An injected strategy gets first refusal — it sits HERE,
|
|
176
|
+
// inside the pipeline, so redaction/sanitize run exactly once and the
|
|
177
|
+
// sticker/reaction steps below still fire whichever way delivery went.
|
|
178
|
+
// Declining (or failing) falls through to the chunked path, which is
|
|
179
|
+
// the only delivery guarantee either branch relies on.
|
|
157
180
|
if (parsed.text) {
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
181
|
+
let body = parsed.text;
|
|
182
|
+
if (typeof deliverText === 'function') {
|
|
183
|
+
let strategy = null;
|
|
184
|
+
try {
|
|
185
|
+
strategy = await deliverText({
|
|
186
|
+
text: body,
|
|
187
|
+
chatId,
|
|
188
|
+
threadId,
|
|
189
|
+
replyToMessageId,
|
|
190
|
+
meta: { ...meta, source, botName: meta.botName },
|
|
191
|
+
});
|
|
192
|
+
} catch (err) {
|
|
193
|
+
// A broken strategy must cost structure, never the message.
|
|
194
|
+
logger?.error?.(`[${source}] delivery strategy failed: ${err.message}`);
|
|
195
|
+
logEvent?.('deliver-strategy-error', {
|
|
196
|
+
chat_id: chatId, thread_id: threadId, source, session_key: sessionKey,
|
|
197
|
+
error: redactError(String(err?.message || err)).slice(0, 200),
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
if (strategy?.handled) {
|
|
201
|
+
summary.deliverResult = {
|
|
202
|
+
sent: strategy.sent || [],
|
|
203
|
+
failed: strategy.failed || [],
|
|
204
|
+
results: strategy.results || [],
|
|
205
|
+
};
|
|
206
|
+
} else if (typeof strategy?.text === 'string') {
|
|
207
|
+
body = strategy.text;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
// Applied on every route to the chunked path — strategy declined, threw,
|
|
211
|
+
// was never built, or rewrote the body already (the projection is
|
|
212
|
+
// idempotent). This is the only place that guarantees it.
|
|
213
|
+
if (!summary.deliverResult && typeof sanitizeFallbackText === 'function') {
|
|
214
|
+
try {
|
|
215
|
+
body = sanitizeFallbackText(body) ?? '';
|
|
216
|
+
} catch (err) {
|
|
217
|
+
logger?.error?.(`[${source}] fallback projection failed: ${redactError(err.message)}`);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// Nothing deliverable survived, and sending the empty string would trip
|
|
222
|
+
// the API's empty-text guard. Record it loudly: a caller that reports
|
|
223
|
+
// success here leaves the user with silence and the agent believing it
|
|
224
|
+
// answered.
|
|
225
|
+
if (!summary.deliverResult && !body) {
|
|
226
|
+
summary.emptiedByStrategy = true;
|
|
227
|
+
logEvent?.('deliver-empty-after-strategy', {
|
|
228
|
+
chat_id: chatId, thread_id: threadId, source, session_key: sessionKey,
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
if (!summary.deliverResult && body) {
|
|
233
|
+
const chunks = chunkMarkdownText(body, chunkBudget);
|
|
234
|
+
summary.deliverResult = await deliverReplies({
|
|
235
|
+
bot,
|
|
236
|
+
send: (b, method, params, m) => tg(b, method, params, m),
|
|
237
|
+
chatId,
|
|
238
|
+
threadId,
|
|
239
|
+
chunks,
|
|
240
|
+
replyToMessageId,
|
|
241
|
+
meta: { ...meta, source, botName: meta.botName },
|
|
242
|
+
logger,
|
|
243
|
+
});
|
|
244
|
+
}
|
|
169
245
|
}
|
|
170
246
|
|
|
171
247
|
// 4. Solo sticker (parseResponse path when whole text was just
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared decision for when a rich-message capability error is enough to
|
|
3
|
+
* disable rich for the rest of the process.
|
|
4
|
+
*
|
|
5
|
+
* The latch it guards is process-wide and never cleared, and it disables
|
|
6
|
+
* every rich path at once. That makes the evidence bar worth stating:
|
|
7
|
+
*
|
|
8
|
+
* - An error that NAMES the missing capability can only come from a server
|
|
9
|
+
* that read our payload and cannot serve it. One is conclusive.
|
|
10
|
+
* - A bare 404 is ALSO what a restarting or briefly misrouted bot-api
|
|
11
|
+
* server returns. One buys a strike; two in a row are the verdict.
|
|
12
|
+
*
|
|
13
|
+
* The counter belongs here rather than in either sender because both the
|
|
14
|
+
* send and the edit path draw on it. Owned per-module, one path would latch
|
|
15
|
+
* on its first 404 while the other still believed it was protected — which
|
|
16
|
+
* is exactly the restart blip the rule exists to survive.
|
|
17
|
+
*
|
|
18
|
+
* The VERDICT, unlike the counter, is per verb. A server can implement
|
|
19
|
+
* `editMessageText{rich_message}` and not the newer `sendRichMessage`,
|
|
20
|
+
* answering the latter with a bare 404. One shared verdict would let a probe
|
|
21
|
+
* of the new verb permanently disable rich edits that are working.
|
|
22
|
+
*
|
|
23
|
+
* "Consecutive" means consecutive RICH ATTEMPTS across both paths, not
|
|
24
|
+
* consecutive replies and not consecutive minutes: attempts that never
|
|
25
|
+
* happen (plain prose, over-length, an already-tripped latch) cannot clear
|
|
26
|
+
* a strike, so two 404s far apart in wall-clock time still latch.
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
'use strict';
|
|
30
|
+
|
|
31
|
+
const VERBS = ['send', 'edit'];
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* @param {object} deps
|
|
35
|
+
* @param {(err) => boolean} [deps.isExplicit] — true when the error names the
|
|
36
|
+
* missing capability rather than being a bare 404. Defaults to treating
|
|
37
|
+
* every capability error as conclusive, which is the behavior of a caller
|
|
38
|
+
* that has not opted into the distinction.
|
|
39
|
+
* @param {(err) => boolean} [deps.isFieldRejection] — true when the error names
|
|
40
|
+
* the `rich_message` FIELD rather than a missing method.
|
|
41
|
+
* @param {(verb: 'send'|'edit') => void} deps.setUnsupported
|
|
42
|
+
* @returns {{recordCapabilityError: (err, verb) => boolean, recordHealthyOutcome: () => void}}
|
|
43
|
+
*/
|
|
44
|
+
function createRichCapabilityLatch({
|
|
45
|
+
isExplicit = () => true,
|
|
46
|
+
isFieldRejection = () => true,
|
|
47
|
+
setUnsupported = () => {},
|
|
48
|
+
} = {}) {
|
|
49
|
+
let consecutiveBare404 = 0;
|
|
50
|
+
|
|
51
|
+
const test = (fn, err) => {
|
|
52
|
+
try { return fn(err) === true; }
|
|
53
|
+
catch { return true; }
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
return {
|
|
57
|
+
/**
|
|
58
|
+
* Record a capability error from one verb and decide what it disables.
|
|
59
|
+
* @param {*} err
|
|
60
|
+
* @param {'send'|'edit'} verb — the verb that got this error
|
|
61
|
+
* @returns {boolean} true when this verb was disabled by this error.
|
|
62
|
+
*/
|
|
63
|
+
recordCapabilityError(err, verb = 'send') {
|
|
64
|
+
if (test(isExplicit, err)) {
|
|
65
|
+
consecutiveBare404 = 0;
|
|
66
|
+
// A rejection of the shared field condemns both verbs; a missing
|
|
67
|
+
// method condemns only itself. Getting this backwards lets a probe
|
|
68
|
+
// of the newer verb disable rich edits that are working right now.
|
|
69
|
+
if (test(isFieldRejection, err)) {
|
|
70
|
+
for (const v of VERBS) setUnsupported(v);
|
|
71
|
+
} else {
|
|
72
|
+
setUnsupported(verb);
|
|
73
|
+
}
|
|
74
|
+
return true;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
consecutiveBare404 += 1;
|
|
78
|
+
if (consecutiveBare404 >= 2) {
|
|
79
|
+
consecutiveBare404 = 0;
|
|
80
|
+
// Ambiguous errors never condemn a verb that did not report one.
|
|
81
|
+
setUnsupported(verb);
|
|
82
|
+
return true;
|
|
83
|
+
}
|
|
84
|
+
return false;
|
|
85
|
+
},
|
|
86
|
+
|
|
87
|
+
// Anything that proves the endpoint is present and answering — a
|
|
88
|
+
// successful rich message, or a rejection of this specific payload.
|
|
89
|
+
recordHealthyOutcome() {
|
|
90
|
+
consecutiveBare404 = 0;
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
module.exports = { createRichCapabilityLatch };
|