polygram 0.29.2 → 0.31.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/lib/codex/diagnostics.js +1 -0
- package/lib/codex/runtime-controller.js +81 -20
- package/lib/codex/runtime-profile.js +6 -0
- package/lib/codex/spawn-context.js +13 -4
- package/lib/db/sessions.js +35 -11
- package/lib/handlers/config-callback.js +361 -5
- package/lib/handlers/config-ui.js +74 -16
- package/lib/runtime-config.js +46 -7
- package/lib/telegram/api.js +9 -0
- package/lib/telegram/rich-send.js +56 -2
- package/lib/telegram/streamer.js +51 -6
- package/package.json +2 -2
- package/polygram.js +252 -63
package/lib/telegram/api.js
CHANGED
|
@@ -229,6 +229,15 @@ async function send({ bot, method, params, db = null, meta = {}, logger = consol
|
|
|
229
229
|
// for any URL in the body (they clutter chats and add visual noise).
|
|
230
230
|
// Default (no flag set) preserves Telegram's native preview behavior
|
|
231
231
|
// — matches OpenClaw's account.config.linkPreview opt-out.
|
|
232
|
+
//
|
|
233
|
+
// Rich bubbles have never honored it, from two directions: sendRichMessage
|
|
234
|
+
// is not one of the methods above, and the rich form of editMessageText
|
|
235
|
+
// carries a meta built for the rich renderer that never had the flag in it.
|
|
236
|
+
// So a chat with the opt-out still gets preview cards under any rich reply.
|
|
237
|
+
// A bubble that OPENS rich only starts that gap one frame earlier than one
|
|
238
|
+
// that upgraded into it. Recorded, not fixed — the two paths would need the
|
|
239
|
+
// option threaded through the rich renderers, and no rich verb is known to
|
|
240
|
+
// accept it.
|
|
232
241
|
if (meta.linkPreview === false
|
|
233
242
|
&& (method === 'sendMessage' || method === 'editMessageText')
|
|
234
243
|
&& params.link_preview_options == null) {
|
|
@@ -34,7 +34,7 @@ const {
|
|
|
34
34
|
defaultMakeInputFile,
|
|
35
35
|
MEDIA_SOURCE_CHANGED,
|
|
36
36
|
} = require('./rich-edit');
|
|
37
|
-
const { countMediaBlocks } = require('./rich');
|
|
37
|
+
const { countMediaBlocks, flattenStyledBlocks, blocksAreStyled } = require('./rich');
|
|
38
38
|
|
|
39
39
|
/**
|
|
40
40
|
* @param {object} deps
|
|
@@ -319,4 +319,58 @@ function errText(err) {
|
|
|
319
319
|
return String(err.description || err.message || err);
|
|
320
320
|
}
|
|
321
321
|
|
|
322
|
-
|
|
322
|
+
/**
|
|
323
|
+
* One rich send, with the flatten-and-retry ladder the reply-tool dispatcher
|
|
324
|
+
* runs around this same verb. Callers that open a streamed bubble use it so a
|
|
325
|
+
* styling-refusing server costs the same on an OPEN as on a reply: the
|
|
326
|
+
* structure survives, and the process learns from it.
|
|
327
|
+
*
|
|
328
|
+
* The retry flattens the tree that was REFUSED rather than re-rendering the
|
|
329
|
+
* source, so the two payloads differ in exactly one respect and a
|
|
330
|
+
* refused-then-accepted pair is evidence about styling and nothing else.
|
|
331
|
+
*
|
|
332
|
+
* Only a refusal that did NOT name a limit is that evidence. Flattening
|
|
333
|
+
* removes styling AND shrinks the payload, so a limit refusal is explained by
|
|
334
|
+
* the shrink; counting it would let two oversized replies disable styling for
|
|
335
|
+
* the whole process.
|
|
336
|
+
*
|
|
337
|
+
* @param {object} args
|
|
338
|
+
* @param {(args: object) => Promise<{wentRich: boolean, fallback?: string}>} args.sendRich
|
|
339
|
+
* @param {object} args.request — the sendRich argument object; `blocks` is the
|
|
340
|
+
* only field the retry changes
|
|
341
|
+
* @param {() => void} [args.onStylingRejected]
|
|
342
|
+
* @param {() => void} [args.onStylingAccepted]
|
|
343
|
+
* @param {object} [args.logger]
|
|
344
|
+
*/
|
|
345
|
+
async function sendRichWithStylingRetry({
|
|
346
|
+
sendRich,
|
|
347
|
+
request,
|
|
348
|
+
onStylingRejected = () => {},
|
|
349
|
+
onStylingAccepted = () => {},
|
|
350
|
+
logger = console,
|
|
351
|
+
}) {
|
|
352
|
+
const styled = blocksAreStyled(request.blocks);
|
|
353
|
+
const out = await sendRich(request);
|
|
354
|
+
if (out?.wentRich) {
|
|
355
|
+
// A styled payload the server accepted — the evidence that ends any run
|
|
356
|
+
// of suspicion, so two unrelated content errors far apart cannot add up
|
|
357
|
+
// to a verdict.
|
|
358
|
+
if (styled) recordVerdict(onStylingAccepted, logger);
|
|
359
|
+
return out;
|
|
360
|
+
}
|
|
361
|
+
const contentRefused = out?.fallback === 'content-error' || out?.fallback === 'content-limit';
|
|
362
|
+
if (!styled || !contentRefused) return out;
|
|
363
|
+
|
|
364
|
+
const retried = await sendRich({ ...request, blocks: flattenStyledBlocks(request.blocks) });
|
|
365
|
+
if (retried?.wentRich && out.fallback === 'content-error') {
|
|
366
|
+
recordVerdict(onStylingRejected, logger);
|
|
367
|
+
}
|
|
368
|
+
return retried;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function recordVerdict(fn, logger) {
|
|
372
|
+
try { fn(); }
|
|
373
|
+
catch (err) { logger?.error?.(`[telegram] rich-send styling verdict failed: ${err.message}`); }
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
module.exports = { createRichSender, sendRichWithStylingRetry };
|
package/lib/telegram/streamer.js
CHANGED
|
@@ -10,7 +10,8 @@
|
|
|
10
10
|
* any -> finalize(finalText) -> finalized
|
|
11
11
|
*
|
|
12
12
|
* The streamer never talks to Telegram directly — callers inject
|
|
13
|
-
* `send(
|
|
13
|
+
* `send(payload)`, `edit(msg_id, payload)`, and (optional)
|
|
14
|
+
* `deleteMessage(msg_id)`.
|
|
14
15
|
* That keeps polygram.js in charge of transcript writes, sticker/reaction
|
|
15
16
|
* routing, and error handling; this module is just a cadence machine.
|
|
16
17
|
*
|
|
@@ -45,8 +46,18 @@ const DEFAULT_THROTTLE_MS = 1000;
|
|
|
45
46
|
const THROTTLE_FLOOR_MS = 250;
|
|
46
47
|
|
|
47
48
|
function createStreamer({
|
|
48
|
-
|
|
49
|
-
|
|
49
|
+
// async (payload) -> { message_id, _hadReplyAnchor?, wentRich? }
|
|
50
|
+
//
|
|
51
|
+
// payload is a plain string, or — when the very first qualifying chunk
|
|
52
|
+
// already renders as structure — the rich shape { rich: true, blocks,
|
|
53
|
+
// sourceText, plainText }. (No `phase`, unlike an edit: a send is only
|
|
54
|
+
// ever the open.) A caller that cannot open rich delivers `plainText`
|
|
55
|
+
// instead and reports `wentRich: false`; the streamer then holds PLAIN
|
|
56
|
+
// state so the next flush edits the bubble it actually has. An absent
|
|
57
|
+
// `wentRich` means the payload landed as sent (backward compatible with
|
|
58
|
+
// plain-only callers).
|
|
59
|
+
send,
|
|
60
|
+
edit, // async (msg_id, payload) -> void
|
|
50
61
|
deleteMessage = null, // async (msg_id) -> void [optional]
|
|
51
62
|
minChars = DEFAULT_MIN_CHARS,
|
|
52
63
|
throttleMs = DEFAULT_THROTTLE_MS,
|
|
@@ -105,7 +116,9 @@ function createStreamer({
|
|
|
105
116
|
// messages, so rich edits and finalization must use this limit.
|
|
106
117
|
richMaxLen = 32768,
|
|
107
118
|
// Fires for each successful plain-to-rich transition. Caller wires this
|
|
108
|
-
// to instrumentation for the visible bubble-shape change.
|
|
119
|
+
// to instrumentation for the visible bubble-shape change. A bubble that
|
|
120
|
+
// OPENS rich never had a plain shape to change, so it does not fire —
|
|
121
|
+
// the metric stays a count of visible flips.
|
|
109
122
|
onRichUpgrade = () => {},
|
|
110
123
|
} = {}) {
|
|
111
124
|
// throttleMs may be a number OR a function evaluated per edit. Telegram's
|
|
@@ -196,10 +209,27 @@ function createStreamer({
|
|
|
196
209
|
if (text.length < minChars) return;
|
|
197
210
|
const generation = bubbleGeneration;
|
|
198
211
|
state = 'live';
|
|
199
|
-
|
|
212
|
+
// Open the bubble RICH when the first qualifying chunk already
|
|
213
|
+
// renders as structure. Without this the preview streams plain for
|
|
214
|
+
// the whole turn and converts to the rich document in one jump at
|
|
215
|
+
// finalize; opening rich means every later flush appends completed
|
|
216
|
+
// blocks to a document that was rich from its first frame.
|
|
217
|
+
// The rich payload measures against the rich cap, not the plain
|
|
218
|
+
// live-edit cap — resolveRichPayload owns that check, so an
|
|
219
|
+
// over-cap first chunk falls through to the truncated plain open.
|
|
220
|
+
const openRich = resolveRichPayload(text, { partial: true });
|
|
221
|
+
const plainText = truncateForLive(text);
|
|
222
|
+
currentText = openRich ? '' : plainText;
|
|
200
223
|
let sendPromise;
|
|
201
224
|
try {
|
|
202
|
-
sendPromise = Promise.resolve(send(
|
|
225
|
+
sendPromise = Promise.resolve(send(openRich
|
|
226
|
+
? {
|
|
227
|
+
rich: true, blocks: openRich.blocks, sourceText: text,
|
|
228
|
+
// What the plain path would have sent, so a caller that has to
|
|
229
|
+
// downgrade delivers a bubble under the PLAIN cap.
|
|
230
|
+
plainText,
|
|
231
|
+
}
|
|
232
|
+
: currentText));
|
|
203
233
|
} catch (err) {
|
|
204
234
|
sendPromise = Promise.reject(err);
|
|
205
235
|
}
|
|
@@ -216,12 +246,27 @@ function createStreamer({
|
|
|
216
246
|
state = 'idle';
|
|
217
247
|
msgId = null;
|
|
218
248
|
hadReplyAnchor = false;
|
|
249
|
+
currentRichJson = null;
|
|
250
|
+
} else if (openRich) {
|
|
251
|
+
// The open can resolve after delivering the same source as plain
|
|
252
|
+
// text (capability latch, refused payload). Seed rich state only
|
|
253
|
+
// for what actually landed: claiming rich over a plain bubble
|
|
254
|
+
// would let the next flush skip its edit as a no-op, and claiming
|
|
255
|
+
// plain over a rich one would overwrite the document with a plain
|
|
256
|
+
// edit — a visible downgrade.
|
|
257
|
+
if (res?.wentRich === false) {
|
|
258
|
+
currentText = plainText;
|
|
259
|
+
currentRichJson = null;
|
|
260
|
+
} else {
|
|
261
|
+
currentRichJson = JSON.stringify(openRich.blocks);
|
|
262
|
+
}
|
|
219
263
|
}
|
|
220
264
|
} catch (err) {
|
|
221
265
|
if (generation !== bubbleGeneration) return;
|
|
222
266
|
logger.error(`[stream] initial send failed: ${err.message}`);
|
|
223
267
|
state = 'idle';
|
|
224
268
|
hadReplyAnchor = false;
|
|
269
|
+
currentRichJson = null;
|
|
225
270
|
} finally {
|
|
226
271
|
if (initialSendPromise === sendPromise) initialSendPromise = null;
|
|
227
272
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "polygram",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.31.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.5",
|
|
67
67
|
"better-sqlite3": "^12.9.0",
|
|
68
68
|
"grammy": "^1.42.0",
|
|
69
69
|
"markdown-it": "^14.1.1",
|
package/polygram.js
CHANGED
|
@@ -72,6 +72,11 @@ const {
|
|
|
72
72
|
const {
|
|
73
73
|
buildCodexSpawnContext,
|
|
74
74
|
} = require('./lib/codex/spawn-context');
|
|
75
|
+
const {
|
|
76
|
+
processMatchesRuntime,
|
|
77
|
+
resolveCodexRuntimeCandidate,
|
|
78
|
+
resolveRuntimeDescriptor,
|
|
79
|
+
} = require('./lib/runtime-config');
|
|
75
80
|
const {
|
|
76
81
|
scheduleCodexRetention,
|
|
77
82
|
} = require('./lib/codex/retention-scheduler');
|
|
@@ -146,7 +151,7 @@ const { createRichStylingLatch } = require('./lib/telegram/rich-styling-latch');
|
|
|
146
151
|
// degrades to. Silence would leave the user with nothing and the agent
|
|
147
152
|
// believing it answered.
|
|
148
153
|
const MEDIA_ONLY_FALLBACK_TEXT = '(media unavailable)';
|
|
149
|
-
const { createRichSender } = require('./lib/telegram/rich-send');
|
|
154
|
+
const { createRichSender, sendRichWithStylingRetry } = require('./lib/telegram/rich-send');
|
|
150
155
|
const { createRichDeliveryFactory } = require('./lib/telegram/rich-dispatch');
|
|
151
156
|
const { createRichEditStrategy } = require('./lib/telegram/rich-edit-dispatch');
|
|
152
157
|
const { composeDeliverTextFactories } = require('./lib/telegram/deliver-strategy');
|
|
@@ -411,6 +416,22 @@ let richKnownUnsupported = false;
|
|
|
411
416
|
// the same field rides both requests, so a server that cannot read it on one
|
|
412
417
|
// cannot read it on the other.
|
|
413
418
|
let richSendKnownUnsupported = false;
|
|
419
|
+
// A verdict for the STREAMED OPEN alone, held to a lower evidence bar than
|
|
420
|
+
// either latch above, and never fed back into them.
|
|
421
|
+
//
|
|
422
|
+
// A server that does rich edits but answers sendRichMessage with a bare 404
|
|
423
|
+
// never trips the send latch on this path: two ambiguous 404s in a row are
|
|
424
|
+
// what latch it, and the rich EDIT one flush later reports a healthy outcome
|
|
425
|
+
// that resets the run every time. So without this, every preview for the
|
|
426
|
+
// process lifetime pays a doomed round-trip and files a capability-strike the
|
|
427
|
+
// soak would read as a server going bad.
|
|
428
|
+
//
|
|
429
|
+
// One failure is enough here because the open is the one rich attempt with a
|
|
430
|
+
// guaranteed-working alternative: the bubble opens plain and the next flush
|
|
431
|
+
// renders it rich through the edit verb. The reply tool has no such second
|
|
432
|
+
// chance, which is why it keeps the two-strike rule and why this verdict must
|
|
433
|
+
// not touch it.
|
|
434
|
+
let richStreamOpenUnsupported = false;
|
|
414
435
|
// A THIRD verdict, and deliberately not one of the two above. Those answer
|
|
415
436
|
// "can this server do rich at all", and tripping either costs every heading,
|
|
416
437
|
// table and task list. This one answers "does it accept typed RichText nodes
|
|
@@ -583,58 +604,157 @@ async function clearAutosteeredReactions(sessionKey) {
|
|
|
583
604
|
let buildSdkOptions = null;
|
|
584
605
|
let codexRuntimeController = null;
|
|
585
606
|
|
|
607
|
+
function buildUnavailableCodexRuntimeView({
|
|
608
|
+
runtimeSelection,
|
|
609
|
+
chatId,
|
|
610
|
+
threadId,
|
|
611
|
+
error,
|
|
612
|
+
runtimeView = null,
|
|
613
|
+
}) {
|
|
614
|
+
let candidate = null;
|
|
615
|
+
try {
|
|
616
|
+
candidate = resolveCodexRuntimeCandidate({
|
|
617
|
+
config,
|
|
618
|
+
chatId,
|
|
619
|
+
threadId,
|
|
620
|
+
});
|
|
621
|
+
} catch {
|
|
622
|
+
// The runtime button must remain available even when the saved Codex
|
|
623
|
+
// model, effort, or cwd is incomplete.
|
|
624
|
+
}
|
|
625
|
+
const model = runtimeView?.model ?? candidate?.model ?? null;
|
|
626
|
+
const effort = runtimeView?.effort ?? candidate?.effort ?? null;
|
|
627
|
+
const desiredSettings = (
|
|
628
|
+
typeof model === 'string'
|
|
629
|
+
&& typeof effort === 'string'
|
|
630
|
+
) ? Object.freeze({ model, effort }) : null;
|
|
631
|
+
return Object.freeze({
|
|
632
|
+
...runtimeView,
|
|
633
|
+
runtime: 'codex',
|
|
634
|
+
backend: runtimeSelection.backend,
|
|
635
|
+
configuredPm: runtimeSelection.configuredPm,
|
|
636
|
+
selectionSource: runtimeSelection.source,
|
|
637
|
+
model,
|
|
638
|
+
effort,
|
|
639
|
+
models: runtimeView?.models ?? Object.freeze([]),
|
|
640
|
+
efforts: runtimeView?.efforts ?? Object.freeze([]),
|
|
641
|
+
desiredSettings: runtimeView?.desiredSettings ?? desiredSettings,
|
|
642
|
+
nextTurnSettings: runtimeView?.nextTurnSettings ?? null,
|
|
643
|
+
observedThreadSettings: runtimeView?.observedThreadSettings ?? null,
|
|
644
|
+
activeTurnSettings: runtimeView?.activeTurnSettings ?? null,
|
|
645
|
+
processStatus: 'unavailable',
|
|
646
|
+
unavailableReason:
|
|
647
|
+
error?.code || error?.name || 'CODEX_RUNTIME_UNAVAILABLE',
|
|
648
|
+
});
|
|
649
|
+
}
|
|
650
|
+
|
|
586
651
|
async function resolveSessionRuntimeView({
|
|
587
652
|
sessionKey,
|
|
588
653
|
chatId,
|
|
589
654
|
threadId = null,
|
|
590
655
|
} = {}) {
|
|
591
|
-
|
|
592
|
-
|
|
656
|
+
const runtimeSelection = resolveRuntimeDescriptor({
|
|
657
|
+
config,
|
|
658
|
+
chatId,
|
|
659
|
+
threadId,
|
|
660
|
+
defaultPm: 'sdk',
|
|
661
|
+
logger: console,
|
|
662
|
+
});
|
|
663
|
+
const runtimeMetadata = {
|
|
664
|
+
runtime: runtimeSelection.runtime,
|
|
665
|
+
backend: runtimeSelection.backend,
|
|
666
|
+
configuredPm: runtimeSelection.configuredPm,
|
|
667
|
+
selectionSource: runtimeSelection.source,
|
|
668
|
+
};
|
|
669
|
+
if (runtimeSelection.runtime !== 'codex') {
|
|
670
|
+
return Object.freeze(runtimeMetadata);
|
|
671
|
+
}
|
|
672
|
+
if (!codexRuntimeController) {
|
|
673
|
+
return buildUnavailableCodexRuntimeView({
|
|
674
|
+
runtimeSelection,
|
|
675
|
+
chatId,
|
|
676
|
+
threadId,
|
|
677
|
+
error: { code: 'CODEX_RUNTIME_UNAVAILABLE' },
|
|
678
|
+
});
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
let runtimeView;
|
|
682
|
+
try {
|
|
683
|
+
runtimeView = await codexRuntimeController.resolveRuntimeView({
|
|
593
684
|
sessionKey,
|
|
594
685
|
chatId,
|
|
595
686
|
threadId,
|
|
596
687
|
});
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
const settingsStatus = await pm.getModelSettingsStatus(sessionKey);
|
|
604
|
-
const processStatus = settingsStatus.outcome;
|
|
605
|
-
const unavailableReason = settingsStatus.reason ?? null;
|
|
606
|
-
const copySettings = (settings) => (
|
|
607
|
-
settings
|
|
608
|
-
&& typeof settings.model === 'string'
|
|
609
|
-
&& typeof settings.effort === 'string'
|
|
610
|
-
? Object.freeze({
|
|
611
|
-
model: settings.model,
|
|
612
|
-
effort: settings.effort,
|
|
613
|
-
})
|
|
614
|
-
: null
|
|
615
|
-
);
|
|
616
|
-
return Object.freeze({
|
|
617
|
-
...runtimeView,
|
|
618
|
-
desiredSettings: Object.freeze({
|
|
619
|
-
model: runtimeView.model,
|
|
620
|
-
effort: runtimeView.effort,
|
|
621
|
-
}),
|
|
622
|
-
nextTurnSettings: copySettings(settingsStatus.nextTurn),
|
|
623
|
-
observedThreadSettings: copySettings(settingsStatus.observedThread),
|
|
624
|
-
activeTurnSettings: copySettings(settingsStatus.currentTurn),
|
|
625
|
-
processStatus,
|
|
626
|
-
unavailableReason,
|
|
688
|
+
} catch (error) {
|
|
689
|
+
return buildUnavailableCodexRuntimeView({
|
|
690
|
+
runtimeSelection,
|
|
691
|
+
chatId,
|
|
692
|
+
threadId,
|
|
693
|
+
error,
|
|
627
694
|
});
|
|
628
695
|
}
|
|
629
|
-
if (
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
696
|
+
if (!isCodexRuntimeView(runtimeView)) {
|
|
697
|
+
return buildUnavailableCodexRuntimeView({
|
|
698
|
+
runtimeSelection,
|
|
699
|
+
chatId,
|
|
700
|
+
threadId,
|
|
701
|
+
error: { code: 'CODEX_RUNTIME_VIEW_MISMATCH' },
|
|
702
|
+
runtimeView,
|
|
703
|
+
});
|
|
704
|
+
}
|
|
705
|
+
runtimeView = Object.freeze({
|
|
706
|
+
...runtimeView,
|
|
707
|
+
...runtimeMetadata,
|
|
708
|
+
});
|
|
709
|
+
if (typeof pm?.getModelSettingsStatus !== 'function') {
|
|
710
|
+
return buildUnavailableCodexRuntimeView({
|
|
711
|
+
runtimeSelection,
|
|
712
|
+
chatId,
|
|
713
|
+
threadId,
|
|
714
|
+
error: { code: 'CODEX_RUNTIME_UNAVAILABLE' },
|
|
715
|
+
runtimeView,
|
|
716
|
+
});
|
|
717
|
+
}
|
|
718
|
+
let settingsStatus;
|
|
719
|
+
try {
|
|
720
|
+
settingsStatus = await pm.getModelSettingsStatus(sessionKey);
|
|
721
|
+
} catch (error) {
|
|
722
|
+
return buildUnavailableCodexRuntimeView({
|
|
723
|
+
runtimeSelection,
|
|
724
|
+
chatId,
|
|
725
|
+
threadId,
|
|
726
|
+
error,
|
|
727
|
+
runtimeView,
|
|
728
|
+
});
|
|
633
729
|
}
|
|
634
|
-
|
|
730
|
+
const copySettings = (settings) => (
|
|
731
|
+
settings
|
|
732
|
+
&& typeof settings.model === 'string'
|
|
733
|
+
&& typeof settings.effort === 'string'
|
|
734
|
+
? Object.freeze({
|
|
735
|
+
model: settings.model,
|
|
736
|
+
effort: settings.effort,
|
|
737
|
+
})
|
|
738
|
+
: null
|
|
739
|
+
);
|
|
740
|
+
return Object.freeze({
|
|
741
|
+
...runtimeView,
|
|
742
|
+
desiredSettings: Object.freeze({
|
|
743
|
+
model: runtimeView.model,
|
|
744
|
+
effort: runtimeView.effort,
|
|
745
|
+
}),
|
|
746
|
+
nextTurnSettings: copySettings(settingsStatus.nextTurn),
|
|
747
|
+
observedThreadSettings: copySettings(settingsStatus.observedThread),
|
|
748
|
+
activeTurnSettings: copySettings(settingsStatus.currentTurn),
|
|
749
|
+
processStatus: settingsStatus.outcome,
|
|
750
|
+
unavailableReason: settingsStatus.reason ?? null,
|
|
751
|
+
});
|
|
635
752
|
}
|
|
636
753
|
|
|
637
|
-
async function buildSpawnContext(
|
|
754
|
+
async function buildSpawnContext(
|
|
755
|
+
sessionKey,
|
|
756
|
+
{ mutateSessionOnDrift = true } = {},
|
|
757
|
+
) {
|
|
638
758
|
const chatId = getChatIdFromKey(sessionKey);
|
|
639
759
|
const chatConfig = config.chats[chatId];
|
|
640
760
|
if (!chatConfig) return null;
|
|
@@ -661,6 +781,7 @@ async function buildSpawnContext(sessionKey) {
|
|
|
661
781
|
runtimeController: codexRuntimeController,
|
|
662
782
|
getSessionLabel,
|
|
663
783
|
logEvent,
|
|
784
|
+
mutateSessionOnDrift,
|
|
664
785
|
});
|
|
665
786
|
}
|
|
666
787
|
|
|
@@ -668,24 +789,25 @@ async function buildSpawnContext(sessionKey) {
|
|
|
668
789
|
// under. agent / cwd are spawn-identity — baked into the process at
|
|
669
790
|
// spawn time, never mutable on a live session. Resolve them the
|
|
670
791
|
// same way the backends do (topic override merged over chat-level)
|
|
671
|
-
// and compare to the stored `sessions` row. On
|
|
672
|
-
// resolveSessionForSpawn drops
|
|
673
|
-
// existingSessionId:null
|
|
674
|
-
//
|
|
675
|
-
// pre-per-topic-config rows (e.g. shumorobot's Music topic :3,
|
|
676
|
-
// stored agent=shumabit / cwd=$HOME vs the current
|
|
677
|
-
// music-curation:music-curator / .../Music/rekordbox).
|
|
792
|
+
// and compare to the stored `sessions` row. On a normal cold spawn,
|
|
793
|
+
// resolveSessionForSpawn drops a stale row and returns
|
|
794
|
+
// existingSessionId:null. Runtime-switch preparation can defer that
|
|
795
|
+
// deletion so a rejected replacement cannot erase the dormant session.
|
|
678
796
|
// model/effort are NOT compared — they apply live via setModel /
|
|
679
|
-
// applyFlagSettings with no respawn.
|
|
680
|
-
//
|
|
681
|
-
//
|
|
682
|
-
// preserves context. See lib/db/sessions.js for full reasoning.
|
|
797
|
+
// applyFlagSettings with no respawn. Compatible inline-wrapper backend
|
|
798
|
+
// changes preserve context; the CLI Channels boundary remains
|
|
799
|
+
// invalidating. See lib/db/sessions.js for the compatibility rules.
|
|
683
800
|
//
|
|
684
801
|
// The drift check runs only at COLD spawn (no warm process). A warm
|
|
685
802
|
// process already runs under its spawn-time config; getOrSpawn
|
|
686
803
|
// returns it without using this context, so dropping its row here
|
|
687
804
|
// would be premature — defer to the next cold spawn.
|
|
688
|
-
const
|
|
805
|
+
const liveProcess = pm?.get(sessionKey) ?? null;
|
|
806
|
+
const isColdSpawn = !processMatchesRuntime(
|
|
807
|
+
liveProcess,
|
|
808
|
+
'claude',
|
|
809
|
+
promptBackend,
|
|
810
|
+
);
|
|
689
811
|
let existingSessionId;
|
|
690
812
|
if (isColdSpawn) {
|
|
691
813
|
const topicConfig = getTopicConfig(chatConfig, threadId || null);
|
|
@@ -694,7 +816,12 @@ async function buildSpawnContext(sessionKey) {
|
|
|
694
816
|
cwd: topicConfig.cwd || chatConfig.cwd || null,
|
|
695
817
|
backend: pickBackend({ config, chatId, threadId: threadId || null, pmDefault: 'sdk' }),
|
|
696
818
|
};
|
|
697
|
-
const r = resolveSessionForSpawn(
|
|
819
|
+
const r = resolveSessionForSpawn(
|
|
820
|
+
db,
|
|
821
|
+
sessionKey,
|
|
822
|
+
resolved,
|
|
823
|
+
{ mutateOnDrift: mutateSessionOnDrift },
|
|
824
|
+
);
|
|
698
825
|
existingSessionId = r.existingSessionId;
|
|
699
826
|
if (r.drift) {
|
|
700
827
|
logEvent('session-config-drift', {
|
|
@@ -1411,23 +1538,64 @@ async function handleMessage(sessionKey, chatId, msg, bot) {
|
|
|
1411
1538
|
// becomes rich during streaming.
|
|
1412
1539
|
logEvent('rich-streaming-upgrade', { chat_id: chatId, thread_id: threadId, bot: BOT_NAME });
|
|
1413
1540
|
},
|
|
1414
|
-
send: async (
|
|
1541
|
+
send: async (payload) => {
|
|
1542
|
+
const openRich = payload && typeof payload === 'object' && payload.rich;
|
|
1415
1543
|
const hadReplyAnchor = !firstBubbleSent;
|
|
1544
|
+
// allow_sending_without_reply: long-running turns give the user
|
|
1545
|
+
// plenty of time to delete their original message. Without this
|
|
1546
|
+
// flag, Telegram rejects the reply with MESSAGE_NOT_FOUND and the
|
|
1547
|
+
// whole streamed answer is lost.
|
|
1548
|
+
const replyParams = hadReplyAnchor
|
|
1549
|
+
? { message_id: msg.message_id, allow_sending_without_reply: true }
|
|
1550
|
+
: null;
|
|
1551
|
+
// One bubble per call whichever verb carries it, so the anchor is
|
|
1552
|
+
// spent here rather than once per transport — a rich open that has
|
|
1553
|
+
// to downgrade still quotes the user exactly once.
|
|
1554
|
+
firstBubbleSent = true;
|
|
1555
|
+
if (openRich && !richStreamOpenUnsupported) {
|
|
1556
|
+
// sendRichMessage is the only verb that opens a bubble rich; a
|
|
1557
|
+
// plain send followed by a rich edit would flicker. It never
|
|
1558
|
+
// throws and reports whether rich actually landed, so a refusal
|
|
1559
|
+
// just opens plain here and the next flush retries via the edit
|
|
1560
|
+
// path (which is where the plain→rich upgrade metric belongs).
|
|
1561
|
+
const out = await sendRichWithStylingRetry({
|
|
1562
|
+
sendRich: richSendMessage,
|
|
1563
|
+
request: {
|
|
1564
|
+
bot, chatId, threadId,
|
|
1565
|
+
blocks: payload.blocks,
|
|
1566
|
+
sourceText: payload.sourceText,
|
|
1567
|
+
replyParams,
|
|
1568
|
+
mediaContext,
|
|
1569
|
+
// The soak needs to tell a streamed open from a reply-tool send:
|
|
1570
|
+
// they use one verb, one latch and one renderer, but only one of
|
|
1571
|
+
// them has a working second attempt when it fails.
|
|
1572
|
+
meta: { ...outMetaBase, source: 'bot-reply-stream-open-rich' },
|
|
1573
|
+
},
|
|
1574
|
+
onStylingRejected: () => richStylingLatch?.recordStylingRejection(),
|
|
1575
|
+
onStylingAccepted: () => richStylingLatch?.recordHealthyOutcome(),
|
|
1576
|
+
logger: { error: (m) => console.error(`[${label}] ${m}`) },
|
|
1577
|
+
});
|
|
1578
|
+
if (out?.wentRich) {
|
|
1579
|
+
return { ...out.result, _hadReplyAnchor: hadReplyAnchor, wentRich: true };
|
|
1580
|
+
}
|
|
1581
|
+
if (out?.fallback === 'capability') {
|
|
1582
|
+
// Stop probing. See richStreamOpenUnsupported — the streamer's
|
|
1583
|
+
// rich path continues through the edit verb from the next flush.
|
|
1584
|
+
richStreamOpenUnsupported = true;
|
|
1585
|
+
logEvent('rich-stream-open-unsupported', {
|
|
1586
|
+
chat_id: chatId, thread_id: threadId, bot: BOT_NAME,
|
|
1587
|
+
});
|
|
1588
|
+
}
|
|
1589
|
+
}
|
|
1416
1590
|
const params = {
|
|
1417
|
-
chat_id: chatId,
|
|
1591
|
+
chat_id: chatId,
|
|
1592
|
+
text: sanitizeLiveText(openRich ? payload.plainText : payload),
|
|
1418
1593
|
...(threadId && { message_thread_id: threadId }),
|
|
1419
1594
|
};
|
|
1420
|
-
if (
|
|
1421
|
-
// allow_sending_without_reply: long-running turns give the user
|
|
1422
|
-
// plenty of time to delete their original message. Without this
|
|
1423
|
-
// flag, Telegram rejects the reply with MESSAGE_NOT_FOUND and the
|
|
1424
|
-
// whole streamed answer is lost.
|
|
1425
|
-
params.reply_parameters = { message_id: msg.message_id, allow_sending_without_reply: true };
|
|
1426
|
-
firstBubbleSent = true;
|
|
1427
|
-
}
|
|
1595
|
+
if (replyParams) params.reply_parameters = replyParams;
|
|
1428
1596
|
const res = await tg(bot, 'sendMessage', params, outMetaBase);
|
|
1429
1597
|
return res && typeof res === 'object'
|
|
1430
|
-
? { ...res, _hadReplyAnchor: hadReplyAnchor }
|
|
1598
|
+
? { ...res, _hadReplyAnchor: hadReplyAnchor, wentRich: false }
|
|
1431
1599
|
: res;
|
|
1432
1600
|
},
|
|
1433
1601
|
edit: async (messageId, payload) => {
|
|
@@ -3914,6 +4082,27 @@ async function main() {
|
|
|
3914
4082
|
config, db, dbWrite, pm, intentLock, getSessionKey,
|
|
3915
4083
|
formatConfigInfoText, buildConfigKeyboard, saveConfig,
|
|
3916
4084
|
resolveRuntimeView: resolveSessionRuntimeView,
|
|
4085
|
+
prepareRuntimeSelection: ({
|
|
4086
|
+
sessionKey,
|
|
4087
|
+
chatId,
|
|
4088
|
+
threadId,
|
|
4089
|
+
runtime,
|
|
4090
|
+
}) => {
|
|
4091
|
+
if (runtime !== 'codex' || !codexRuntimeController) {
|
|
4092
|
+
const error = new Error('Codex runtime preflight is unavailable');
|
|
4093
|
+
error.code = 'CODEX_RUNTIME_UNAVAILABLE';
|
|
4094
|
+
throw error;
|
|
4095
|
+
}
|
|
4096
|
+
return codexRuntimeController.resolveCandidateRuntimeView({
|
|
4097
|
+
sessionKey,
|
|
4098
|
+
chatId,
|
|
4099
|
+
threadId,
|
|
4100
|
+
});
|
|
4101
|
+
},
|
|
4102
|
+
discardRuntimeSelection: (sessionKey) => (
|
|
4103
|
+
codexRuntimeController?.discardCandidateRuntime(sessionKey) ?? false
|
|
4104
|
+
),
|
|
4105
|
+
buildSpawnContext,
|
|
3917
4106
|
botName: BOT_NAME, logger: console,
|
|
3918
4107
|
});
|
|
3919
4108
|
handleCodexReconciliationCallback = createHandleCodexReconciliationCallback({
|