charness 4.0.0 → 4.1.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/CHANGELOG.md +18 -0
- package/DEVELOPMENT.md +2 -1
- package/agent-plugin/skills/charness-delegate-claude/SKILL.md +2 -0
- package/agent-plugin/skills/charness-orchestration/SKILL.md +5 -0
- package/dist/adapters/claudeCliAdapter.d.ts.map +1 -1
- package/dist/adapters/claudeCliAdapter.js +3 -2
- package/dist/adapters/claudeCliAdapter.js.map +1 -1
- package/dist/adapters/claudeJsonStreamAdapter.d.ts +1 -0
- package/dist/adapters/claudeJsonStreamAdapter.d.ts.map +1 -1
- package/dist/adapters/claudeJsonStreamAdapter.js +19 -4
- package/dist/adapters/claudeJsonStreamAdapter.js.map +1 -1
- package/dist/adapters/openCodeAdapter.d.ts +1 -0
- package/dist/adapters/openCodeAdapter.d.ts.map +1 -1
- package/dist/adapters/openCodeAdapter.js +11 -0
- package/dist/adapters/openCodeAdapter.js.map +1 -1
- package/dist/bot.d.ts.map +1 -1
- package/dist/bot.js +268 -268
- package/dist/bot.js.map +1 -1
- package/dist/connectors/telegram/answerSink.d.ts +12 -0
- package/dist/connectors/telegram/answerSink.d.ts.map +1 -1
- package/dist/connectors/telegram/answerSink.js +23 -0
- package/dist/connectors/telegram/answerSink.js.map +1 -1
- package/dist/connectors/telegram/botApiConnection.d.ts +2 -1
- package/dist/connectors/telegram/botApiConnection.d.ts.map +1 -1
- package/dist/connectors/telegram/botApiConnection.js +19 -1
- package/dist/connectors/telegram/botApiConnection.js.map +1 -1
- package/dist/connectors/telegram/commands/botCore.d.ts +13 -5
- package/dist/connectors/telegram/commands/botCore.d.ts.map +1 -1
- package/dist/connectors/telegram/commands/runners.d.ts +1 -1
- package/dist/connectors/telegram/commands/runners.d.ts.map +1 -1
- package/dist/connectors/telegram/commands/runners.js +9 -5
- package/dist/connectors/telegram/commands/runners.js.map +1 -1
- package/dist/connectors/telegram/outbound.d.ts +1 -1
- package/dist/connectors/telegram/outbound.d.ts.map +1 -1
- package/dist/connectors/telegram/outbound.js +3 -1
- package/dist/connectors/telegram/outbound.js.map +1 -1
- package/dist/connectors/telegram/outputBacklogGlue.d.ts +1 -1
- package/dist/connectors/telegram/outputBacklogGlue.js +1 -1
- package/dist/connectors/telegram/outputFlushPlan.d.ts +23 -8
- package/dist/connectors/telegram/outputFlushPlan.d.ts.map +1 -1
- package/dist/connectors/telegram/outputFlushPlan.js +22 -13
- package/dist/connectors/telegram/outputFlushPlan.js.map +1 -1
- package/dist/connectors/telegram/pinnedNoticeSlot.d.ts +31 -0
- package/dist/connectors/telegram/pinnedNoticeSlot.d.ts.map +1 -0
- package/dist/connectors/telegram/pinnedNoticeSlot.js +43 -0
- package/dist/connectors/telegram/pinnedNoticeSlot.js.map +1 -0
- package/dist/connectors/telegram/sendOutcome.d.ts +48 -0
- package/dist/connectors/telegram/sendOutcome.d.ts.map +1 -0
- package/dist/connectors/telegram/sendOutcome.js +49 -0
- package/dist/connectors/telegram/sendOutcome.js.map +1 -0
- package/dist/connectors/telegram/telegramFailureRetry.d.ts +9 -0
- package/dist/connectors/telegram/telegramFailureRetry.d.ts.map +1 -0
- package/dist/connectors/telegram/telegramFailureRetry.js +21 -0
- package/dist/connectors/telegram/telegramFailureRetry.js.map +1 -0
- package/dist/connectors/telegram/unpinMessages.d.ts +1 -1
- package/dist/connectors/telegram/unpinMessages.d.ts.map +1 -1
- package/dist/connectors/telegram/unpinMessages.js +3 -18
- package/dist/connectors/telegram/unpinMessages.js.map +1 -1
- package/dist/hooks/claudeSkillsRestoreHook.d.ts +105 -0
- package/dist/hooks/claudeSkillsRestoreHook.d.ts.map +1 -0
- package/dist/hooks/claudeSkillsRestoreHook.js +276 -0
- package/dist/hooks/claudeSkillsRestoreHook.js.map +1 -0
- package/dist/platform/outbound.d.ts +4 -1
- package/dist/platform/outbound.d.ts.map +1 -1
- package/dist/platform/outbound.js.map +1 -1
- package/dist/rateLimiter.d.ts +33 -1
- package/dist/rateLimiter.d.ts.map +1 -1
- package/dist/rateLimiter.js +91 -5
- package/dist/rateLimiter.js.map +1 -1
- package/dist/runnerUtility/pueueDaemon.d.ts +7 -13
- package/dist/runnerUtility/pueueDaemon.d.ts.map +1 -1
- package/dist/runnerUtility/pueueDaemon.js +8 -27
- package/dist/runnerUtility/pueueDaemon.js.map +1 -1
- package/dist/selfUpdate/selfCheck.d.ts.map +1 -1
- package/dist/selfUpdate/selfCheck.js +1 -1
- package/dist/selfUpdate/selfCheck.js.map +1 -1
- package/dist/testTimings.d.ts +4 -2
- package/dist/testTimings.d.ts.map +1 -1
- package/dist/testTimings.js +4 -1
- package/dist/testTimings.js.map +1 -1
- package/dist/types.d.ts +9 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/utils/agentPlugin.d.ts +7 -0
- package/dist/utils/agentPlugin.d.ts.map +1 -1
- package/dist/utils/agentPlugin.js +12 -0
- package/dist/utils/agentPlugin.js.map +1 -1
- package/dist/utils/claudeCompactHook.d.ts +73 -10
- package/dist/utils/claudeCompactHook.d.ts.map +1 -1
- package/dist/utils/claudeCompactHook.js +96 -17
- package/dist/utils/claudeCompactHook.js.map +1 -1
- package/dist/utils/claudeProfiles.d.ts +8 -0
- package/dist/utils/claudeProfiles.d.ts.map +1 -1
- package/dist/utils/claudeProfiles.js +12 -2
- package/dist/utils/claudeProfiles.js.map +1 -1
- package/dist/utils/claudeTranscriptEpoch.d.ts +15 -0
- package/dist/utils/claudeTranscriptEpoch.d.ts.map +1 -0
- package/dist/utils/claudeTranscriptEpoch.js +120 -0
- package/dist/utils/claudeTranscriptEpoch.js.map +1 -0
- package/dist/utils/clearStatusCoalescer.d.ts +24 -0
- package/dist/utils/clearStatusCoalescer.d.ts.map +1 -0
- package/dist/utils/clearStatusCoalescer.js +25 -0
- package/dist/utils/clearStatusCoalescer.js.map +1 -0
- package/dist/utils/compactOnIdle.d.ts +91 -34
- package/dist/utils/compactOnIdle.d.ts.map +1 -1
- package/dist/utils/compactOnIdle.js +149 -31
- package/dist/utils/compactOnIdle.js.map +1 -1
- package/dist/utils/groupOutputBacklog.d.ts +90 -0
- package/dist/utils/groupOutputBacklog.d.ts.map +1 -0
- package/dist/utils/groupOutputBacklog.js +134 -0
- package/dist/utils/groupOutputBacklog.js.map +1 -0
- package/dist/utils/messageSendService.d.ts +26 -3
- package/dist/utils/messageSendService.d.ts.map +1 -1
- package/dist/utils/messageSendService.js +35 -3
- package/dist/utils/messageSendService.js.map +1 -1
- package/dist/utils/openCodeCompactPlugin.d.ts +33 -0
- package/dist/utils/openCodeCompactPlugin.d.ts.map +1 -1
- package/dist/utils/openCodeCompactPlugin.js +192 -1
- package/dist/utils/openCodeCompactPlugin.js.map +1 -1
- package/dist/utils/skillsRestore.d.ts +235 -0
- package/dist/utils/skillsRestore.d.ts.map +1 -0
- package/dist/utils/skillsRestore.js +515 -0
- package/dist/utils/skillsRestore.js.map +1 -0
- package/dist/utils/statusFlushDecision.js +1 -1
- package/dist/utils/streamedCompactionSummary.d.ts +4 -4
- package/dist/utils/streamedCompactionSummary.js +5 -5
- package/dist/utils/streamedCompactionSummary.js.map +1 -1
- package/dist/utils/streamedOutputLanding.d.ts +14 -0
- package/dist/utils/streamedOutputLanding.d.ts.map +1 -0
- package/dist/utils/streamedOutputLanding.js +45 -0
- package/dist/utils/streamedOutputLanding.js.map +1 -0
- package/dist/utils/typingLoopBackstop.d.ts +8 -7
- package/dist/utils/typingLoopBackstop.d.ts.map +1 -1
- package/dist/utils/typingLoopBackstop.js +6 -5
- package/dist/utils/typingLoopBackstop.js.map +1 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/dist/utils/clearThreadOutputQueues.d.ts +0 -44
- package/dist/utils/clearThreadOutputQueues.d.ts.map +0 -1
- package/dist/utils/clearThreadOutputQueues.js +0 -39
- package/dist/utils/clearThreadOutputQueues.js.map +0 -1
- package/dist/utils/groupFinalizePlan.d.ts +0 -36
- package/dist/utils/groupFinalizePlan.d.ts.map +0 -1
- package/dist/utils/groupFinalizePlan.js +0 -31
- package/dist/utils/groupFinalizePlan.js.map +0 -1
package/dist/bot.js
CHANGED
|
@@ -141,6 +141,9 @@ const messageSplit_1 = require("./connectors/telegram/messageSplit");
|
|
|
141
141
|
const foldedMessage_1 = require("./connectors/telegram/foldedMessage");
|
|
142
142
|
const unpinMessages_1 = require("./connectors/telegram/unpinMessages");
|
|
143
143
|
const outputFlushPlan_1 = require("./connectors/telegram/outputFlushPlan");
|
|
144
|
+
const sendOutcome_1 = require("./connectors/telegram/sendOutcome");
|
|
145
|
+
const telegramFailureRetry_1 = require("./connectors/telegram/telegramFailureRetry");
|
|
146
|
+
const pinnedNoticeSlot_1 = require("./connectors/telegram/pinnedNoticeSlot");
|
|
144
147
|
const outputBacklogGlue_1 = require("./connectors/telegram/outputBacklogGlue");
|
|
145
148
|
const typingActive_1 = require("./utils/typingActive");
|
|
146
149
|
const typingLoopBackstop_1 = require("./utils/typingLoopBackstop");
|
|
@@ -151,8 +154,9 @@ const outputTrace_1 = require("./outputTrace");
|
|
|
151
154
|
const linkPreviewSuppression_1 = require("./utils/linkPreviewSuppression");
|
|
152
155
|
const rotatingLogFile_1 = require("./utils/rotatingLogFile");
|
|
153
156
|
const consoleFileTap_1 = require("./utils/consoleFileTap");
|
|
154
|
-
const
|
|
155
|
-
const
|
|
157
|
+
const clearStatusCoalescer_1 = require("./utils/clearStatusCoalescer");
|
|
158
|
+
const groupOutputBacklog_1 = require("./utils/groupOutputBacklog");
|
|
159
|
+
const streamedOutputLanding_1 = require("./utils/streamedOutputLanding");
|
|
156
160
|
const persistAdapterSessionIds_1 = require("./utils/persistAdapterSessionIds");
|
|
157
161
|
const ensureSessionPlan_1 = require("./utils/ensureSessionPlan");
|
|
158
162
|
const backendUnavailableError_1 = require("./adapters/backendUnavailableError");
|
|
@@ -410,6 +414,8 @@ if (testTimingsBootLine !== null)
|
|
|
410
414
|
console.log(testTimingsBootLine);
|
|
411
415
|
if (ENV.testTimings.telegramSendIntervalMs !== undefined)
|
|
412
416
|
(0, rateLimiter_1.configureGlobalSendInterval)(ENV.testTimings.telegramSendIntervalMs);
|
|
417
|
+
if (ENV.testTimings.telegramSendOperationDeadlineMs !== undefined)
|
|
418
|
+
(0, rateLimiter_1.configureSendOperationDeadline)(ENV.testTimings.telegramSendOperationDeadlineMs);
|
|
413
419
|
if (ENV.testTimings.backgroundHoldMaxMs !== undefined)
|
|
414
420
|
(0, createAdapter_1.registerPendingWorkHoldMs)(ENV.testTimings.backgroundHoldMaxMs);
|
|
415
421
|
if (ENV.testTimings.scheduleMinFireIntervalMs !== undefined)
|
|
@@ -1220,14 +1226,6 @@ const pendingQuestions = new Map();
|
|
|
1220
1226
|
* and Claude's live re-scrape, so it needs no persistence of its own.
|
|
1221
1227
|
*/
|
|
1222
1228
|
const questionPinnedMessageId = new Map();
|
|
1223
|
-
/**
|
|
1224
|
-
* @description Placeholder stored in a pinned-notice map ({@link
|
|
1225
|
-
* authNoticePinnedMessageId}, {@link limitResumeNoticePinnedMessageId}) between
|
|
1226
|
-
* reserving the one-notice slot and the pin landing, so a burst of events can't
|
|
1227
|
-
* race two notices out. A real Telegram message id is always positive, so `-1` can
|
|
1228
|
-
* never collide with one.
|
|
1229
|
-
*/
|
|
1230
|
-
const pinnedNoticePendingSentinel = -1;
|
|
1231
1229
|
/**
|
|
1232
1230
|
* @description Per-thread id of the PINNED "logged-out" notice (in-memory). Its
|
|
1233
1231
|
* presence is ALSO the one-notice-per-logout-episode guard: while set, a repeat
|
|
@@ -2192,33 +2190,26 @@ async function handleNoResponseWithLocale(key) {
|
|
|
2192
2190
|
* (a pin pierces the muted topic → a Telegram notification), backend-aware
|
|
2193
2191
|
* (Claude → re-`/login`; OpenCode → restart the server). No timer, no persisted
|
|
2194
2192
|
* retry record — a wait never recovers auth. Deduped to exactly one notice per
|
|
2195
|
-
* logout episode via {@link authNoticePinnedMessageId}
|
|
2196
|
-
*
|
|
2197
|
-
*
|
|
2193
|
+
* logout episode via {@link authNoticePinnedMessageId} ({@link surfacePinnedNotice}:
|
|
2194
|
+
* the slot is reserved BEFORE the post so a burst of `apiError` frames can't race
|
|
2195
|
+
* two notices out, and a post of unknown outcome is never repeated). The pin is removed on recovery — the first
|
|
2198
2196
|
* real output after re-login ({@link clearAuthNotice}, wired in
|
|
2199
2197
|
* {@link handleAgentOutput}) — and at the session-end / teardown sites (NOT the
|
|
2200
2198
|
* user-takeover {@link cancelApiRetry} sites; see its NOTE).
|
|
2201
2199
|
*/
|
|
2202
2200
|
async function surfaceLoggedOutNotice(key) {
|
|
2203
|
-
const k = (0, sessionKey_1.keyToString)(key);
|
|
2204
|
-
if (authNoticePinnedMessageId.has(k))
|
|
2205
|
-
return; // already surfaced this episode
|
|
2206
|
-
authNoticePinnedMessageId.set(k, pinnedNoticePendingSentinel);
|
|
2207
2201
|
const messageKey = (0, createAdapter_1.getThreadAdapterNameRaw)(key) === adapterNames_1.openCodeAdapterName ? 'apiRetry.loggedOutOpenCode' : 'apiRetry.loggedOutClaude';
|
|
2208
|
-
|
|
2209
|
-
|
|
2210
|
-
|
|
2211
|
-
|
|
2212
|
-
|
|
2213
|
-
|
|
2214
|
-
|
|
2215
|
-
|
|
2216
|
-
|
|
2217
|
-
|
|
2218
|
-
|
|
2219
|
-
authNoticePinnedMessageId.set(k, id);
|
|
2220
|
-
// First pin of the episode notifies (disableNotification: false).
|
|
2221
|
-
await pinMessageQuiet(key, id, { disableNotification: false });
|
|
2202
|
+
await (0, pinnedNoticeSlot_1.surfacePinnedNotice)(authNoticePinnedMessageId, (0, sessionKey_1.keyToString)(key), getPinnedNoticePorts(key, (0, i18n_1.t)(messageKey)));
|
|
2203
|
+
}
|
|
2204
|
+
/** @description The post and the notifying pin of a pinned notice of `key`'s topic ({@link surfacePinnedNotice}). */
|
|
2205
|
+
function getPinnedNoticePorts(key, text) {
|
|
2206
|
+
return {
|
|
2207
|
+
send: () => replyToThreadDetailed(key, text),
|
|
2208
|
+
// The pin of the episode's one notice notifies (disableNotification: false).
|
|
2209
|
+
pin: async (messageId) => {
|
|
2210
|
+
await pinMessageQuiet(key, messageId, { disableNotification: false });
|
|
2211
|
+
},
|
|
2212
|
+
};
|
|
2222
2213
|
}
|
|
2223
2214
|
/**
|
|
2224
2215
|
* @description Retire a thread's pinned logged-out notice: unpin it (if a real
|
|
@@ -2228,40 +2219,21 @@ async function surfaceLoggedOutNotice(key) {
|
|
|
2228
2219
|
* {@link cancelApiRetry} — see its NOTE). No-op when none is active.
|
|
2229
2220
|
*/
|
|
2230
2221
|
function clearAuthNotice(key) {
|
|
2231
|
-
const
|
|
2232
|
-
|
|
2233
|
-
if (pinnedId === undefined)
|
|
2234
|
-
return;
|
|
2235
|
-
authNoticePinnedMessageId.delete(k);
|
|
2236
|
-
if (pinnedId !== pinnedNoticePendingSentinel)
|
|
2222
|
+
const pinnedId = (0, pinnedNoticeSlot_1.releasePinnedNoticeSlot)(authNoticePinnedMessageId, (0, sessionKey_1.keyToString)(key));
|
|
2223
|
+
if (pinnedId !== null)
|
|
2237
2224
|
void unpinMessageQuiet(key, pinnedId);
|
|
2238
2225
|
}
|
|
2239
2226
|
/**
|
|
2240
2227
|
* @description Announce that a usage/session-limit window reset and work is moving
|
|
2241
2228
|
* again, as ONE PINNED, NOTIFYING message. A limit wait runs for up to an hour per
|
|
2242
2229
|
* attempt in a topic the operator keeps muted, so a plain line would go unseen —
|
|
2243
|
-
* the pin is what fires the Telegram notification.
|
|
2244
|
-
* {@link
|
|
2245
|
-
*
|
|
2246
|
-
*
|
|
2230
|
+
* the pin is what fires the Telegram notification. Posted through
|
|
2231
|
+
* {@link surfacePinnedNotice}, as {@link surfaceLoggedOutNotice} is: one notice per
|
|
2232
|
+
* episode, never repeated after a post of unknown outcome, and never pinned after a
|
|
2233
|
+
* concurrent teardown dropped its slot mid-send.
|
|
2247
2234
|
*/
|
|
2248
2235
|
async function surfaceLimitResumedNotice(key) {
|
|
2249
|
-
|
|
2250
|
-
if (limitResumeNoticePinnedMessageId.has(k))
|
|
2251
|
-
return; // already pinned this episode
|
|
2252
|
-
limitResumeNoticePinnedMessageId.set(k, pinnedNoticePendingSentinel);
|
|
2253
|
-
const id = await replyToThread(key, (0, i18n_1.t)('apiRetry.limitResetResuming'));
|
|
2254
|
-
if (id === null) {
|
|
2255
|
-
// Send failed — release the reservation so a later fire can retry surfacing.
|
|
2256
|
-
if (limitResumeNoticePinnedMessageId.get(k) === pinnedNoticePendingSentinel) {
|
|
2257
|
-
limitResumeNoticePinnedMessageId.delete(k);
|
|
2258
|
-
}
|
|
2259
|
-
return;
|
|
2260
|
-
}
|
|
2261
|
-
if (!limitResumeNoticePinnedMessageId.has(k))
|
|
2262
|
-
return;
|
|
2263
|
-
limitResumeNoticePinnedMessageId.set(k, id);
|
|
2264
|
-
await pinMessageQuiet(key, id, { disableNotification: false });
|
|
2236
|
+
await (0, pinnedNoticeSlot_1.surfacePinnedNotice)(limitResumeNoticePinnedMessageId, (0, sessionKey_1.keyToString)(key), getPinnedNoticePorts(key, (0, i18n_1.t)('apiRetry.limitResetResuming')));
|
|
2265
2237
|
}
|
|
2266
2238
|
/**
|
|
2267
2239
|
* @description Retire a thread's pinned limit-resumed notice: unpin it (if a real
|
|
@@ -2272,12 +2244,8 @@ async function surfaceLimitResumedNotice(key) {
|
|
|
2272
2244
|
* none is active.
|
|
2273
2245
|
*/
|
|
2274
2246
|
function clearLimitResumeNotice(key) {
|
|
2275
|
-
const
|
|
2276
|
-
|
|
2277
|
-
if (pinnedId === undefined)
|
|
2278
|
-
return;
|
|
2279
|
-
limitResumeNoticePinnedMessageId.delete(k);
|
|
2280
|
-
if (pinnedId !== pinnedNoticePendingSentinel)
|
|
2247
|
+
const pinnedId = (0, pinnedNoticeSlot_1.releasePinnedNoticeSlot)(limitResumeNoticePinnedMessageId, (0, sessionKey_1.keyToString)(key));
|
|
2248
|
+
if (pinnedId !== null)
|
|
2281
2249
|
void unpinMessageQuiet(key, pinnedId);
|
|
2282
2250
|
}
|
|
2283
2251
|
/**
|
|
@@ -2493,7 +2461,7 @@ function getOutputQueueState(key) {
|
|
|
2493
2461
|
const k = (0, sessionKey_1.keyToString)(key);
|
|
2494
2462
|
let s = outputQueues.get(k);
|
|
2495
2463
|
if (!s) {
|
|
2496
|
-
s =
|
|
2464
|
+
s = (0, groupOutputBacklog_1.createGroupOutputBacklog)();
|
|
2497
2465
|
outputQueues.set(k, s);
|
|
2498
2466
|
}
|
|
2499
2467
|
return s;
|
|
@@ -2514,17 +2482,27 @@ function checkIsOutputStreaming(key) {
|
|
|
2514
2482
|
const q = outputQueues.get((0, sessionKey_1.keyToString)(key));
|
|
2515
2483
|
if (!q)
|
|
2516
2484
|
return false;
|
|
2517
|
-
return (0, outputFlushPlan_1.checkHasPendingOutput)(q) || q.
|
|
2485
|
+
return (0, outputFlushPlan_1.checkHasPendingOutput)(q) || q.isDraining || q.debounceTimer !== null;
|
|
2518
2486
|
}
|
|
2519
2487
|
function getStatusCoalesceState(key) {
|
|
2520
2488
|
const k = (0, sessionKey_1.keyToString)(key);
|
|
2521
2489
|
let s = statusCoalescers.get(k);
|
|
2522
2490
|
if (!s) {
|
|
2523
|
-
s = { pendingText: null, inFlight: false, lastSentText: null, deferRetryTimer: null };
|
|
2491
|
+
s = { pendingText: null, inFlight: false, lastSentText: null, deferRetryTimer: null, supersedeCount: 0 };
|
|
2524
2492
|
statusCoalescers.set(k, s);
|
|
2525
2493
|
}
|
|
2526
2494
|
return s;
|
|
2527
2495
|
}
|
|
2496
|
+
/**
|
|
2497
|
+
* @description The status frames that exist so far are stale (real output, a question UI, an error, the forced idle
|
|
2498
|
+
* removal came): drop the parked text, and tell every status still waiting for its ordering `finalize` in
|
|
2499
|
+
* `handleAgentStatus` not to be created afterwards. A status that arrives after this call is newer and shows.
|
|
2500
|
+
*/
|
|
2501
|
+
function supersedeStatusFrames(key) {
|
|
2502
|
+
const coalescer = getStatusCoalesceState(key);
|
|
2503
|
+
coalescer.pendingText = null;
|
|
2504
|
+
coalescer.supersedeCount += 1;
|
|
2505
|
+
}
|
|
2528
2506
|
function getThinkingCoalesceState(key) {
|
|
2529
2507
|
const k = (0, sessionKey_1.keyToString)(key);
|
|
2530
2508
|
let s = thinkingCoalescers.get(k);
|
|
@@ -2561,31 +2539,23 @@ function clearThinkingMessage(key) {
|
|
|
2561
2539
|
deleteThreadMessage(key, id).catch(() => { });
|
|
2562
2540
|
}
|
|
2563
2541
|
/**
|
|
2564
|
-
* @description
|
|
2565
|
-
*
|
|
2566
|
-
*
|
|
2567
|
-
*
|
|
2568
|
-
* clearing a thread that never queued anything is a no-op. The pure clear
|
|
2569
|
-
* logic lives in `utils/clearThreadOutputQueues` for unit testing.
|
|
2542
|
+
* @description A stop's handling of a thread's not-yet-sent output: the agent's text gets ONE final attempt (never dropped up
|
|
2543
|
+
* front — S2), the pending status frame is dropped so no stale frame appears after the stop. Looks the existing state up with
|
|
2544
|
+
* `.get()` — no lazy creation, since a thread that never queued anything has nothing to land. The pure parts live in
|
|
2545
|
+
* `utils/groupOutputBacklog.ts` and `utils/clearStatusCoalescer.ts` for unit testing.
|
|
2570
2546
|
*/
|
|
2571
2547
|
function clearThreadQueues(key) {
|
|
2572
2548
|
const k = (0, sessionKey_1.keyToString)(key);
|
|
2573
|
-
// A teardown
|
|
2574
|
-
//
|
|
2575
|
-
//
|
|
2576
|
-
//
|
|
2577
|
-
//
|
|
2578
|
-
// all route through here. CRITICAL ORDER: finalize BEFORE
|
|
2579
|
-
// `clearThreadOutputQueues`, because the group finalize drains
|
|
2580
|
-
// the pending segments and the clear would otherwise drop them first (S2). Both
|
|
2581
|
-
// transports capture + reset their in-flight state SYNCHRONOUSLY before any
|
|
2582
|
-
// await, so the clear below can't race the drain. Fire-and-forget.
|
|
2583
|
-
void getOutboundFor(key).finalize(key);
|
|
2549
|
+
// A teardown never discards the agent's last words (S2). This is the convergence point for `/quit` release, session
|
|
2550
|
+
// `closed`/`stopped`, `/unbind`, and topic-delete — all route through here. The group backlog (also the one of a DM topic
|
|
2551
|
+
// on an adapter without a draft) gives everything queued so far ONE final attempt, in order after the send under way; a
|
|
2552
|
+
// 429 then drops what it keeps, logged, and nothing is retried after the stop. The DM transport turns its live draft into
|
|
2553
|
+
// a permanent message. Fire-and-forget.
|
|
2584
2554
|
const queue = outputQueues.get(k);
|
|
2585
|
-
|
|
2586
|
-
|
|
2587
|
-
|
|
2588
|
-
(0,
|
|
2555
|
+
if (queue)
|
|
2556
|
+
void (0, groupOutputBacklog_1.startFinalGroupOutputAttempt)(queue, getGroupOutputDrainDeps(key, queue));
|
|
2557
|
+
void getOutboundFor(key).finalize(key);
|
|
2558
|
+
(0, clearStatusCoalescer_1.clearStatusCoalescer)(statusCoalescers.get(k));
|
|
2589
2559
|
// A new session starts with empty context — forget the last-sent outputs so
|
|
2590
2560
|
// the identical-output backstop can't suppress a legitimate repeat across a
|
|
2591
2561
|
// session boundary (the same convergence point that clears the other
|
|
@@ -3346,8 +3316,16 @@ function buildSendExtra(key, extra) {
|
|
|
3346
3316
|
return { ...base, message_thread_id: (0, sessionKeyCodec_1.getTelegramThreadId)(key) };
|
|
3347
3317
|
}
|
|
3348
3318
|
async function replyToThread(key, text, extra = {}, options = {}) {
|
|
3319
|
+
const outcome = await replyToThreadDetailed(key, text, extra, options);
|
|
3320
|
+
return outcome.kind === 'sent' ? outcome.messageId : null;
|
|
3321
|
+
}
|
|
3322
|
+
/**
|
|
3323
|
+
* @description {@link replyToThread} telling a send whose outcome is unknown from one that failed, and a failure worth another
|
|
3324
|
+
* try later from a refusal for good — see {@link ThreadSendOutcome}.
|
|
3325
|
+
*/
|
|
3326
|
+
async function replyToThreadDetailed(key, text, extra = {}, options = {}) {
|
|
3349
3327
|
if (!checkIsTelegramPrimitiveKey(key, 'replyToThread'))
|
|
3350
|
-
return
|
|
3328
|
+
return { kind: 'failed', isRetryable: false };
|
|
3351
3329
|
const sendOnce = (sendExtra, sentText = text) => {
|
|
3352
3330
|
const send = () => bot.telegram.sendMessage((0, sessionKeyCodec_1.getTelegramChatId)(key), sentText, sendExtra);
|
|
3353
3331
|
return options.unpaced ? (0, rateLimiter_1.sendUnpaced)(key, send, options.signal) : (0, rateLimiter_1.enqueueSend)(key, send, options.signal);
|
|
@@ -3358,7 +3336,12 @@ async function replyToThread(key, text, extra = {}, options = {}) {
|
|
|
3358
3336
|
await state.pushMessageId(key, messageId);
|
|
3359
3337
|
if ((0, bindPicker_1.checkIsBindPickerExtra)(extra))
|
|
3360
3338
|
openBindMessages.remember((0, sessionKey_1.keyToString)(key), messageId, Date.now());
|
|
3361
|
-
return messageId;
|
|
3339
|
+
return { kind: 'sent', messageId };
|
|
3340
|
+
};
|
|
3341
|
+
// A send the Bot API did not answer in time may have landed: it is reported, never sent again (no plain retry either).
|
|
3342
|
+
const reportUnknown = () => {
|
|
3343
|
+
console.warn(`[send] ${(0, sessionKey_1.keyToString)(key)} a message got no answer from the Bot API in time; it may or may not be in the topic, and is not sent again`);
|
|
3344
|
+
return { kind: 'unknown' };
|
|
3362
3345
|
};
|
|
3363
3346
|
// The plain twin goes out in place of `text` when Telegram refuses the markup: it is as much a secret, and the trace must not quote it.
|
|
3364
3347
|
const releaseSecret = options.isSecret ? (0, outputTrace_1.markOutboundTextsSecret)([text, options.plainFallbackText]) : null;
|
|
@@ -3367,7 +3350,9 @@ async function replyToThread(key, text, extra = {}, options = {}) {
|
|
|
3367
3350
|
}
|
|
3368
3351
|
catch (e) {
|
|
3369
3352
|
if (options.signal?.aborted && (0, utils_1.checkIsAbortError)(e))
|
|
3370
|
-
return
|
|
3353
|
+
return { kind: 'failed', isRetryable: false };
|
|
3354
|
+
if ((0, rateLimiter_1.checkIsSendOutcomeUnknownError)(e))
|
|
3355
|
+
return reportUnknown();
|
|
3371
3356
|
// Markdown parse failure fallback. Several `t(...)` templates interpolate
|
|
3372
3357
|
// user-controlled content (subdir names, branch names, error strings)
|
|
3373
3358
|
// into Markdown body — a backtick or stray `*` inside the content
|
|
@@ -3386,8 +3371,10 @@ async function replyToThread(key, text, extra = {}, options = {}) {
|
|
|
3386
3371
|
return await trackSent(await sendOnce(buildSendExtra(key, plainExtra), options.plainFallbackText ?? text));
|
|
3387
3372
|
}
|
|
3388
3373
|
catch (e2) {
|
|
3374
|
+
if ((0, rateLimiter_1.checkIsSendOutcomeUnknownError)(e2))
|
|
3375
|
+
return reportUnknown();
|
|
3389
3376
|
await handleSendError(key, e2);
|
|
3390
|
-
return
|
|
3377
|
+
return { kind: 'failed', isRetryable: (0, telegramFailureRetry_1.checkIsTelegramFailureRetryable)(e2) };
|
|
3391
3378
|
}
|
|
3392
3379
|
}
|
|
3393
3380
|
// A double-429 (rate-limited even after withRateLimitRetry's single
|
|
@@ -3396,7 +3383,7 @@ async function replyToThread(key, text, extra = {}, options = {}) {
|
|
|
3396
3383
|
// re-arm a bounded redelivery (its late re-send was the OUT-OF-ORDER cause
|
|
3397
3384
|
// the user reported) — the rare 429 is just logged via handleSendError.
|
|
3398
3385
|
await handleSendError(key, e);
|
|
3399
|
-
return
|
|
3386
|
+
return { kind: 'failed', isRetryable: (0, telegramFailureRetry_1.checkIsTelegramFailureRetryable)(e) };
|
|
3400
3387
|
}
|
|
3401
3388
|
finally {
|
|
3402
3389
|
releaseSecret?.();
|
|
@@ -3405,9 +3392,10 @@ async function replyToThread(key, text, extra = {}, options = {}) {
|
|
|
3405
3392
|
/**
|
|
3406
3393
|
* @description Edit an existing assistant message in the thread.
|
|
3407
3394
|
*
|
|
3408
|
-
* Returns `true` on success
|
|
3409
|
-
*
|
|
3410
|
-
*
|
|
3395
|
+
* Returns `true` on success — or when the outcome is unknown, see
|
|
3396
|
+
* {@link editThreadMessageDetailed} — and `false` if the edit failed for any
|
|
3397
|
+
* other reason — caller decides whether to fall back to a new `replyToThread`.
|
|
3398
|
+
* We don't track edits as new ids (the original was already tracked).
|
|
3411
3399
|
*
|
|
3412
3400
|
* `plainFallbackText`: the text for the retry without `parse_mode` when Telegram cannot parse the Markdown one — the
|
|
3413
3401
|
* same text when absent, which shows a Markdown render's escape marks as they are; a caller that has a real plain
|
|
@@ -3418,9 +3406,17 @@ async function editThreadMessage(key, messageId, text, extra = {}, plainFallback
|
|
|
3418
3406
|
}
|
|
3419
3407
|
/**
|
|
3420
3408
|
* @description {@link editThreadMessage} telling a message that is not there (deleted by hand: «message to edit not found») from any
|
|
3421
|
-
* other failure — see {@link ThreadMessageEdit}. The failure is logged either way, as before.
|
|
3409
|
+
* other failure — see {@link ThreadMessageEdit}. The failure is logged either way, as before. An edit whose outcome is unknown
|
|
3410
|
+
* counts as made ({@link getCallerEditResult}): a caller answers a failed edit by posting the content anew, which could show it twice.
|
|
3422
3411
|
*/
|
|
3423
3412
|
async function editThreadMessageDetailed(key, messageId, text, extra = {}, plainFallbackText = text) {
|
|
3413
|
+
return (0, sendOutcome_1.getCallerEditResult)(await editThreadMessageWithOutcome(key, messageId, text, extra, plainFallbackText));
|
|
3414
|
+
}
|
|
3415
|
+
/**
|
|
3416
|
+
* @description {@link editThreadMessageDetailed}, plus `unknown`: the Bot API did not answer within the send queue's deadline, the
|
|
3417
|
+
* edit may or may not be applied. The output flush reads it through `sendOutputChunks`, which counts it as made.
|
|
3418
|
+
*/
|
|
3419
|
+
async function editThreadMessageWithOutcome(key, messageId, text, extra = {}, plainFallbackText = text) {
|
|
3424
3420
|
if (!checkIsTelegramPrimitiveKey(key, 'editThreadMessage'))
|
|
3425
3421
|
return 'failed';
|
|
3426
3422
|
const editOnce = (editText, editExtra) => (0, rateLimiter_1.enqueueSend)(key, () => bot.telegram.editMessageText((0, sessionKeyCodec_1.getTelegramChatId)(key), messageId, undefined, editText, editExtra));
|
|
@@ -3429,6 +3425,8 @@ async function editThreadMessageDetailed(key, messageId, text, extra = {}, plain
|
|
|
3429
3425
|
return 'edited';
|
|
3430
3426
|
}
|
|
3431
3427
|
catch (e) {
|
|
3428
|
+
if ((0, rateLimiter_1.checkIsSendOutcomeUnknownError)(e))
|
|
3429
|
+
return reportUnknownEdit(key, messageId);
|
|
3432
3430
|
const desc = (0, sendErrorClassifier_1.checkIsApiError)(e) ? (0, sendErrorClassifier_1.getErrorDescription)(e) : '';
|
|
3433
3431
|
if (/message is not modified/i.test(desc))
|
|
3434
3432
|
return 'edited'; // benign
|
|
@@ -3449,6 +3447,8 @@ async function editThreadMessageDetailed(key, messageId, text, extra = {}, plain
|
|
|
3449
3447
|
return 'edited';
|
|
3450
3448
|
}
|
|
3451
3449
|
catch (e2) {
|
|
3450
|
+
if ((0, rateLimiter_1.checkIsSendOutcomeUnknownError)(e2))
|
|
3451
|
+
return reportUnknownEdit(key, messageId);
|
|
3452
3452
|
const desc2 = (0, sendErrorClassifier_1.checkIsApiError)(e2) ? (0, sendErrorClassifier_1.getErrorDescription)(e2) : '';
|
|
3453
3453
|
if (/message is not modified/i.test(desc2))
|
|
3454
3454
|
return 'edited';
|
|
@@ -3460,6 +3460,10 @@ async function editThreadMessageDetailed(key, messageId, text, extra = {}, plain
|
|
|
3460
3460
|
return (0, telegramError_1.checkIsMessageNotFoundError)(e) ? 'gone' : 'failed';
|
|
3461
3461
|
}
|
|
3462
3462
|
}
|
|
3463
|
+
function reportUnknownEdit(key, messageId) {
|
|
3464
|
+
console.warn(`[edit] ${(0, sessionKey_1.keyToString)(key)}#${messageId} got no answer from the Bot API in time; it may or may not be applied`);
|
|
3465
|
+
return 'unknown';
|
|
3466
|
+
}
|
|
3463
3467
|
/**
|
|
3464
3468
|
* @description Replace the inline keyboard of a message of the thread (`null` removes it) through the paced send queue.
|
|
3465
3469
|
* Returns `true` when the keyboard is as asked — a no-change edit («message is not modified») counts — and `false`
|
|
@@ -3605,7 +3609,7 @@ function startTypingLoader(key) {
|
|
|
3605
3609
|
console.warn(`[typing] ${(0, sessionKey_1.keyToString)(key)} force-stop: kept alive by leaked output-queue state — ` +
|
|
3606
3610
|
`isOutputStreaming=${checkIsOutputStreaming(key)} isAdapterBusy=${checkIsAdapterBusy(key)} ` +
|
|
3607
3611
|
`pendingOutput=${q !== undefined && (0, outputFlushPlan_1.checkHasPendingOutput)(q)} ` +
|
|
3608
|
-
`
|
|
3612
|
+
`isDraining=${q?.isDraining === true} debounceTimer=${q?.debounceTimer !== null && q?.debounceTimer !== undefined}`);
|
|
3609
3613
|
if (q?.debounceTimer) {
|
|
3610
3614
|
clearTimeout(q.debounceTimer);
|
|
3611
3615
|
q.debounceTimer = null;
|
|
@@ -3632,7 +3636,7 @@ function checkIsTypingLoopStuck(key) {
|
|
|
3632
3636
|
isCompacting: checkIsThreadCompacting(key),
|
|
3633
3637
|
isTransportStreaming: getOutboundFor(key).checkIsDelivering(key),
|
|
3634
3638
|
hasPendingOutput: q !== undefined && (0, outputFlushPlan_1.checkHasPendingOutput)(q),
|
|
3635
|
-
isProcessing: q?.
|
|
3639
|
+
isProcessing: q?.isDraining === true,
|
|
3636
3640
|
hasDebounceTimer: q?.debounceTimer != null,
|
|
3637
3641
|
});
|
|
3638
3642
|
}
|
|
@@ -3759,102 +3763,80 @@ function queueOutput(key, output, isContinuation = false, isFinal = false, isCom
|
|
|
3759
3763
|
// S3: scale the in-cooldown debounce to the live remaining cooldown.
|
|
3760
3764
|
remainingCooldownMs: (0, rateLimiter_1.getRateLimitRemainingMs)((0, sessionKeyCodec_1.getTelegramChatId)(key)),
|
|
3761
3765
|
});
|
|
3762
|
-
|
|
3763
|
-
|
|
3764
|
-
|
|
3765
|
-
|
|
3766
|
-
// pending frame will be picked up by the re-trigger timer it arms).
|
|
3767
|
-
void processOutputQueue(key);
|
|
3766
|
+
const newestSeq = (0, outputFlushPlan_1.getNewestPendingSeq)(q);
|
|
3767
|
+
// Final frame: send everything now. The send loop runs once per topic, so a call while it sends only moves its target on.
|
|
3768
|
+
if (timing === 'now') {
|
|
3769
|
+
(0, groupOutputBacklog_1.drainGroupOutput)(q, newestSeq, getGroupOutputDrainDeps(key, q));
|
|
3768
3770
|
return;
|
|
3769
3771
|
}
|
|
3772
|
+
// An earlier segment, sealed by a boundary, has nothing more to wait for: its turn is over. The newest one still grows and
|
|
3773
|
+
// waits out the debounce.
|
|
3774
|
+
if (q.pendingSegments.length > 1)
|
|
3775
|
+
(0, groupOutputBacklog_1.drainGroupOutput)(q, newestSeq - 1, getGroupOutputDrainDeps(key, q));
|
|
3770
3776
|
q.debounceTimer = setTimeout(() => {
|
|
3771
3777
|
q.debounceTimer = null;
|
|
3772
|
-
|
|
3778
|
+
flushGroupOutput(key, q);
|
|
3773
3779
|
}, timing);
|
|
3774
3780
|
}
|
|
3775
|
-
|
|
3776
|
-
|
|
3777
|
-
|
|
3778
|
-
return;
|
|
3779
|
-
q.isProcessing = true;
|
|
3780
|
-
try {
|
|
3781
|
-
const flush = (0, outputFlushPlan_1.takePendingOutput)(q);
|
|
3782
|
-
if (!flush)
|
|
3783
|
-
return;
|
|
3784
|
-
const { unsentRemainder } = await sendOutputImmediate(key, flush.output, flush.isContinuation, flush.startsNewMessage);
|
|
3785
|
-
// No silent drop: a chunk dropped on a 429 after the retry-after wait comes
|
|
3786
|
-
// back as `unsentRemainder`. Put it BACK at the FRONT of the buffer (it is
|
|
3787
|
-
// older than anything that arrived during the await) so the re-trigger flush
|
|
3788
|
-
// below retries it — never lost. Landed chunks are excluded by
|
|
3789
|
-
// `getUnsentRemainder`, so this never re-sends what already reached Telegram.
|
|
3790
|
-
// The remainder restarts a fresh message (its predecessors landed / edited in
|
|
3791
|
-
// place already), so it is NOT a continuation.
|
|
3792
|
-
if (unsentRemainder)
|
|
3793
|
-
(0, outputFlushPlan_1.requeueUnsentRemainder)(q, unsentRemainder);
|
|
3794
|
-
}
|
|
3795
|
-
finally {
|
|
3796
|
-
q.isProcessing = false;
|
|
3797
|
-
if ((0, outputFlushPlan_1.checkHasPendingOutput)(q)) {
|
|
3798
|
-
// Audit S13 / #30: the re-trigger `setTimeout` used to be a bare
|
|
3799
|
-
// call whose handle was never stored. A `queueOutput` call between
|
|
3800
|
-
// here and the timer firing would `clearTimeout(null)` and
|
|
3801
|
-
// schedule a duplicate timer, leaving one orphan callback alive.
|
|
3802
|
-
// Routing through `queueOutput`-equivalent code keeps `q.debounceTimer`
|
|
3803
|
-
// authoritative.
|
|
3804
|
-
if (q.debounceTimer)
|
|
3805
|
-
clearTimeout(q.debounceTimer);
|
|
3806
|
-
q.debounceTimer = setTimeout(() => {
|
|
3807
|
-
q.debounceTimer = null;
|
|
3808
|
-
processOutputQueue(key);
|
|
3809
|
-
}, q.pendingSegments.length > 1 ? 0 : getOutputDelay((0, sessionKeyCodec_1.getTelegramChatId)(key)));
|
|
3810
|
-
}
|
|
3811
|
-
}
|
|
3781
|
+
/** @description Send everything the topic's backlog holds — the debounce flush and its retry. */
|
|
3782
|
+
function flushGroupOutput(key, q) {
|
|
3783
|
+
(0, groupOutputBacklog_1.drainGroupOutput)(q, (0, outputFlushPlan_1.getNewestPendingSeq)(q), getGroupOutputDrainDeps(key, q));
|
|
3812
3784
|
}
|
|
3813
3785
|
/**
|
|
3814
|
-
* @description
|
|
3815
|
-
*
|
|
3816
|
-
|
|
3817
|
-
|
|
3818
|
-
|
|
3819
|
-
|
|
3820
|
-
|
|
3821
|
-
|
|
3822
|
-
|
|
3823
|
-
|
|
3824
|
-
|
|
3825
|
-
|
|
3826
|
-
|
|
3827
|
-
|
|
3828
|
-
|
|
3829
|
-
|
|
3830
|
-
|
|
3831
|
-
|
|
3786
|
+
* @description What the send loop of a topic's backlog does through the bot: the send itself, the retry a leftover that failed
|
|
3787
|
+
* for now needs (a 429, the network), and the log of what was dropped (refused for good, or failed at a stop) or a send threw.
|
|
3788
|
+
*/
|
|
3789
|
+
function getGroupOutputDrainDeps(key, q) {
|
|
3790
|
+
return {
|
|
3791
|
+
sendSegment: (segment) => sendOutputImmediate(key, segment.output, segment.isContinuation, segment.startsNewMessage),
|
|
3792
|
+
onStalled: () => {
|
|
3793
|
+
console.warn(`[send] ${(0, sessionKey_1.keyToString)(key)} output remainder failed for now (a 429 or the network) and was put back at the head for a retry`);
|
|
3794
|
+
armOutputRetry(key, q);
|
|
3795
|
+
},
|
|
3796
|
+
onDropped: (segment, unsentRemainder, reason) => {
|
|
3797
|
+
const remainderSize = `${unsentRemainder.length} chars`;
|
|
3798
|
+
if (reason === 'refused')
|
|
3799
|
+
console.warn(`[send] ${(0, sessionKey_1.keyToString)(key)} output remainder (${remainderSize}) was refused by Telegram for good and was dropped`);
|
|
3800
|
+
else
|
|
3801
|
+
console.warn(`[send] ${(0, sessionKey_1.keyToString)(key)} output remainder (${remainderSize}) failed on its final attempt at a stop and was dropped`);
|
|
3802
|
+
// Text that took the new-message mark and is dropped leaves the mark with the thread again.
|
|
3803
|
+
if (segment.startsNewMessage)
|
|
3804
|
+
markNeedsNewMessage(key);
|
|
3805
|
+
},
|
|
3806
|
+
onSendError: (error) => console.error(`[send] ${(0, sessionKey_1.keyToString)(key)} output send failed; it is not sent again:`, error.message),
|
|
3807
|
+
};
|
|
3808
|
+
}
|
|
3809
|
+
/**
|
|
3810
|
+
* @description Arm the timer that sends again what a failure for now (a 429, the network) put back at the head of the backlog.
|
|
3811
|
+
* Several segments go at once; one waits out the debounce, stretched while the chat is in a 429 cooldown.
|
|
3812
|
+
*/
|
|
3813
|
+
function armOutputRetry(key, q) {
|
|
3814
|
+
// Audit S13 / #30: the re-trigger `setTimeout` used to be a bare
|
|
3815
|
+
// call whose handle was never stored. A `queueOutput` call between
|
|
3816
|
+
// here and the timer firing would `clearTimeout(null)` and
|
|
3817
|
+
// schedule a duplicate timer, leaving one orphan callback alive.
|
|
3818
|
+
// Routing through `queueOutput`-equivalent code keeps `q.debounceTimer`
|
|
3819
|
+
// authoritative.
|
|
3820
|
+
if (q.debounceTimer)
|
|
3821
|
+
clearTimeout(q.debounceTimer);
|
|
3822
|
+
q.debounceTimer = setTimeout(() => {
|
|
3823
|
+
q.debounceTimer = null;
|
|
3824
|
+
flushGroupOutput(key, q);
|
|
3825
|
+
}, q.pendingSegments.length > 1 ? 0 : getOutputDelay((0, sessionKeyCodec_1.getTelegramChatId)(key)));
|
|
3826
|
+
}
|
|
3827
|
+
/**
|
|
3828
|
+
* @description Group-path `finalizeInFlight`: land everything the topic's backlog holds — and the send under way — before the
|
|
3829
|
+
* caller posts what must come after it: a tool call's status frame, a question, an answer of `answer_request`, the messages of
|
|
3830
|
+
* `send_messages_to_user` (`landStreamedOutputOfThread`). Those go straight to the topic and would otherwise overtake the
|
|
3831
|
+
* text the agent streamed before them, which still waits out the debounce. Resolves once that text has settled
|
|
3832
|
+
* ({@link landGroupOutput}); a 429 leftover goes back to the head and the wait goes on until its retry lands it. A stop gives
|
|
3833
|
+
* the backlog its final attempt separately (`clearThreadQueues`).
|
|
3832
3834
|
*/
|
|
3833
3835
|
async function finalizeGroupOutput(key) {
|
|
3834
3836
|
const q = outputQueues.get((0, sessionKey_1.keyToString)(key));
|
|
3835
3837
|
if (!q)
|
|
3836
3838
|
return;
|
|
3837
|
-
|
|
3838
|
-
if (plan.action === 'noop')
|
|
3839
|
-
return; // fully delivered → no-op, no dupe.
|
|
3840
|
-
// Snapshot is captured by the plan; empty the buffer SYNCHRONOUSLY before the
|
|
3841
|
-
// await so the immediately-following clear / a concurrent flush can't re-send it.
|
|
3842
|
-
q.pendingSegments = [];
|
|
3843
|
-
if (q.debounceTimer) {
|
|
3844
|
-
clearTimeout(q.debounceTimer);
|
|
3845
|
-
q.debounceTimer = null;
|
|
3846
|
-
}
|
|
3847
|
-
for (const segment of plan.segments) {
|
|
3848
|
-
const { unsentRemainder } = await sendOutputImmediate(key, segment.output, segment.isContinuation, segment.startsNewMessage);
|
|
3849
|
-
// A remainder that still 429'd at teardown is dropped (the buffer is being
|
|
3850
|
-
// torn down anyway — unchanged from the pre-S2 discard), and so is everything behind it. Do NOT re-queue: the
|
|
3851
|
-
// queue is about to be cleared, and re-queuing would race that clear. At 1/2s
|
|
3852
|
-
// global pacing a 429 here is essentially impossible.
|
|
3853
|
-
if (unsentRemainder) {
|
|
3854
|
-
console.warn(`[send] ${(0, sessionKey_1.keyToString)(key)} finalize remainder 429'd and was dropped at teardown`);
|
|
3855
|
-
return;
|
|
3856
|
-
}
|
|
3857
|
-
}
|
|
3839
|
+
await (0, groupOutputBacklog_1.landGroupOutput)(q, getGroupOutputDrainDeps(key, q));
|
|
3858
3840
|
}
|
|
3859
3841
|
/**
|
|
3860
3842
|
* @description Render `output` as the agent's permanent message in a thread.
|
|
@@ -3878,7 +3860,8 @@ async function finalizeGroupOutput(key) {
|
|
|
3878
3860
|
* On Markdown rejection by Telegram we fall back to plain text (`parse_mode`
|
|
3879
3861
|
* unset) — the message lands either way. If the in-place edit fails (message
|
|
3880
3862
|
* deleted / API hiccup) we send every chunk fresh so the full combined text
|
|
3881
|
-
* still reaches the user
|
|
3863
|
+
* still reaches the user ({@link sendOutputChunks}, which also keeps a call of
|
|
3864
|
+
* unknown outcome from being made twice).
|
|
3882
3865
|
*/
|
|
3883
3866
|
async function sendOutputImmediate(key, output, isContinuation = false, startsNewMessage = false) {
|
|
3884
3867
|
// The typing loader is stopped upstream in `handleAgentOutput` (the shared
|
|
@@ -3901,51 +3884,39 @@ async function sendOutputImmediate(key, output, isContinuation = false, startsNe
|
|
|
3901
3884
|
const chunks = shouldEditFirstChunk
|
|
3902
3885
|
? planChunks
|
|
3903
3886
|
: (0, outputBacklogGlue_1.glueBacklogFrames)(planChunks, messageSplit_1.MAX_MESSAGE_LEN, (chunk) => (0, renderAgentHtml_1.renderAgentHtml)(chunk).length);
|
|
3904
|
-
|
|
3905
|
-
|
|
3906
|
-
|
|
3907
|
-
|
|
3908
|
-
|
|
3909
|
-
|
|
3910
|
-
|
|
3911
|
-
}
|
|
3912
|
-
// Edit failed (message deleted / API hiccup): fall through and send every
|
|
3913
|
-
// chunk fresh — the full combined text still reaches the user.
|
|
3914
|
-
}
|
|
3915
|
-
// No silent drop: track how many chunks actually landed, counting from the
|
|
3916
|
-
// FRONT. `startIndex` already covers a successful in-place edit of chunks[0];
|
|
3917
|
-
// when that edit failed it is 0 and every chunk re-sends fresh below. A
|
|
3918
|
-
// `replyChunkWithFallback` that returns null means the chunk was dropped on a
|
|
3919
|
-
// 429 after the retry-after wait — STOP the run (the cooldown would drop the
|
|
3920
|
-
// rest of this synchronous flush too) and report the un-sent remainder so the
|
|
3921
|
-
// caller re-enqueues it for the next flush.
|
|
3922
|
-
let sentCount = startIndex;
|
|
3923
|
-
for (let i = startIndex; i < chunks.length; i++) {
|
|
3924
|
-
const id = await replyChunkWithFallback(key, (0, renderAgentHtml_1.renderAgentHtml)(chunks[i]), chunks[i]);
|
|
3925
|
-
if (!id)
|
|
3926
|
-
break;
|
|
3927
|
-
msgState.lastMessageId = id;
|
|
3928
|
-
msgState.lastMessageText = chunks[i];
|
|
3929
|
-
sentCount = i + 1;
|
|
3930
|
-
}
|
|
3887
|
+
// An edit whose outcome is unknown counts as made, and a chunk whose outcome is unknown as sent: sent (again) they could show
|
|
3888
|
+
// twice. A chunk that FAILED stops the run; the rest is the remainder the backlog puts back, or drops when Telegram refused it
|
|
3889
|
+
// for good. The cursor is the thread's own message state.
|
|
3890
|
+
const result = await (0, sendOutcome_1.sendOutputChunks)(chunks, shouldEditFirstChunk, msgState, {
|
|
3891
|
+
editLastMessage: (messageId, chunk) => editThreadMessageWithOutcome(key, messageId, (0, renderAgentHtml_1.renderAgentHtml)(chunk), { parse_mode: 'HTML' }, chunk),
|
|
3892
|
+
sendChunk: (chunk) => replyChunkDetailed(key, (0, renderAgentHtml_1.renderAgentHtml)(chunk), chunk),
|
|
3893
|
+
});
|
|
3931
3894
|
// S3: output just landed below any pending question — bring the question back
|
|
3932
3895
|
// to the bottom (debounced; no-op when no question is pending).
|
|
3933
3896
|
onThreadActivityWhileQuestionPending(key);
|
|
3934
|
-
return
|
|
3897
|
+
return result;
|
|
3935
3898
|
}
|
|
3936
3899
|
/**
|
|
3937
3900
|
* @description Send a chunk as HTML first; if Telegram rejects the entities,
|
|
3938
3901
|
* fall back to plain text so the message reaches the user either way.
|
|
3939
3902
|
*/
|
|
3940
3903
|
async function replyChunkWithFallback(key, renderedHtml, plainFallback, replyMarkup) {
|
|
3904
|
+
const outcome = await replyChunkDetailed(key, renderedHtml, plainFallback, replyMarkup);
|
|
3905
|
+
return outcome.kind === 'sent' ? outcome.messageId : null;
|
|
3906
|
+
}
|
|
3907
|
+
/**
|
|
3908
|
+
* @description {@link replyChunkWithFallback} telling an unknown outcome from a failure: a chunk whose send got no answer in time
|
|
3909
|
+
* is NOT sent again as plain text — it may already be in the topic.
|
|
3910
|
+
*/
|
|
3911
|
+
async function replyChunkDetailed(key, renderedHtml, plainFallback, replyMarkup) {
|
|
3941
3912
|
if (!checkIsTelegramPrimitiveKey(key, 'replyChunkWithFallback'))
|
|
3942
|
-
return
|
|
3913
|
+
return { kind: 'failed', isRetryable: false };
|
|
3943
3914
|
const markupExtra = replyMarkup ? { reply_markup: replyMarkup } : {};
|
|
3944
3915
|
// Telegram refusing the markup is answered INSIDE replyToThread, with the plain twin — without it the retry would show the tags.
|
|
3945
|
-
const
|
|
3946
|
-
if (
|
|
3947
|
-
return
|
|
3948
|
-
return
|
|
3916
|
+
const outcome = await replyToThreadDetailed(key, renderedHtml, { parse_mode: 'HTML', ...markupExtra }, { plainFallbackText: plainFallback });
|
|
3917
|
+
if (outcome.kind !== 'failed')
|
|
3918
|
+
return outcome;
|
|
3919
|
+
return replyToThreadDetailed(key, plainFallback, markupExtra);
|
|
3949
3920
|
}
|
|
3950
3921
|
const callSendMessageDraft = bot.telegram.callApi.bind(bot.telegram);
|
|
3951
3922
|
/**
|
|
@@ -4073,11 +4044,10 @@ const shutdownOutputFlushMaxMs = rateLimiter_1.shutdownDrainMaxMs + 1000;
|
|
|
4073
4044
|
* already-emitted answer chunks died in the send pipeline with the
|
|
4074
4045
|
* process and were never re-sent). Two buffers drain, in order:
|
|
4075
4046
|
*
|
|
4076
|
-
* [A] per-thread COALESCE state — the group
|
|
4077
|
-
*
|
|
4078
|
-
* transport's active drafts (enumerated via `
|
|
4079
|
-
*
|
|
4080
|
-
* `finalizeInFlight`;
|
|
4047
|
+
* [A] per-thread COALESCE state — the group backlogs (enumerated here from
|
|
4048
|
+
* {@link outputQueues}; each gets its final attempt, as at a stop) and the
|
|
4049
|
+
* DM transport's active drafts (enumerated via `listUnfinalizedKeys`), each
|
|
4050
|
+
* finalized to a permanent message;
|
|
4081
4051
|
* [B] the per-thread send FIFOs already parked on the global pacer — drained
|
|
4082
4052
|
* by `drainPendingSends` after `enterShutdownDrain()` flips the pacer to
|
|
4083
4053
|
* immediate release (at 1 send/2s a 5-message backlog alone outlives any
|
|
@@ -4099,42 +4069,32 @@ async function finalizePendingOutputOnShutdown() {
|
|
|
4099
4069
|
let flushedCount = 0;
|
|
4100
4070
|
const flushWork = (async () => {
|
|
4101
4071
|
(0, rateLimiter_1.enterShutdownDrain)();
|
|
4102
|
-
// [A]
|
|
4103
|
-
//
|
|
4104
|
-
|
|
4072
|
+
// [A] every group backlog with text queued or being sent — the group topics', and the DM topics' on an adapter without
|
|
4073
|
+
// a draft (they coalesce there too) — gets its final attempt; the connectors land their own unfinalized content (the
|
|
4074
|
+
// DM drafts). Deduped by serialised key for the count.
|
|
4075
|
+
const flushedKeys = new Set();
|
|
4076
|
+
const landings = [];
|
|
4105
4077
|
for (const [keyStr, q] of outputQueues) {
|
|
4106
|
-
if (!(0, outputFlushPlan_1.checkHasPendingOutput)(q))
|
|
4078
|
+
if (!(0, outputFlushPlan_1.checkHasPendingOutput)(q) && !q.isDraining)
|
|
4107
4079
|
continue;
|
|
4080
|
+
let key;
|
|
4108
4081
|
try {
|
|
4109
|
-
|
|
4082
|
+
key = (0, sessionKey_1.keyFromString)(keyStr);
|
|
4110
4083
|
}
|
|
4111
4084
|
catch {
|
|
4112
|
-
|
|
4085
|
+
continue; // malformed key — nothing to flush for it
|
|
4113
4086
|
}
|
|
4087
|
+
flushedKeys.add(keyStr);
|
|
4088
|
+
landings.push((0, groupOutputBacklog_1.startFinalGroupOutputAttempt)(q, getGroupOutputDrainDeps(key, q)));
|
|
4114
4089
|
}
|
|
4115
4090
|
for (const outbound of connectorOutbounds.values()) {
|
|
4116
|
-
for (const key of outbound.listUnfinalizedKeys())
|
|
4117
|
-
|
|
4118
|
-
|
|
4119
|
-
flushedCount = pendingKeys.size;
|
|
4120
|
-
await Promise.allSettled([...pendingKeys.values()].map((key) => getOutboundFor(key).finalize(key)));
|
|
4121
|
-
// A DM-surface thread on a non-draft adapter (e.g. terminal) coalesces via
|
|
4122
|
-
// the group `queueOutput` path, but its transport finalize handled only the
|
|
4123
|
-
// draft — drain any such leftover buffer directly. Group keys were already
|
|
4124
|
-
// drained above (their finalize empties the pending segments synchronously), so
|
|
4125
|
-
// this is a no-op for them.
|
|
4126
|
-
const leftoverDrains = [];
|
|
4127
|
-
for (const [keyStr, q] of outputQueues) {
|
|
4128
|
-
if (!(0, outputFlushPlan_1.checkHasPendingOutput)(q))
|
|
4129
|
-
continue;
|
|
4130
|
-
try {
|
|
4131
|
-
leftoverDrains.push(finalizeGroupOutput((0, sessionKey_1.keyFromString)(keyStr)));
|
|
4132
|
-
}
|
|
4133
|
-
catch {
|
|
4134
|
-
/* malformed key */
|
|
4091
|
+
for (const key of outbound.listUnfinalizedKeys()) {
|
|
4092
|
+
flushedKeys.add((0, sessionKey_1.keyToString)(key));
|
|
4093
|
+
landings.push(outbound.finalize(key));
|
|
4135
4094
|
}
|
|
4136
4095
|
}
|
|
4137
|
-
|
|
4096
|
+
flushedCount = flushedKeys.size;
|
|
4097
|
+
await Promise.allSettled(landings);
|
|
4138
4098
|
// [B] wait for the released FIFOs to empty, bounded by what is left of the
|
|
4139
4099
|
// shared drain budget.
|
|
4140
4100
|
return (0, rateLimiter_1.drainPendingSends)(Math.max(drainDeadlineMs - Date.now(), 0));
|
|
@@ -5362,6 +5322,7 @@ const botCore = {
|
|
|
5362
5322
|
command,
|
|
5363
5323
|
getState: () => state,
|
|
5364
5324
|
replyToThread,
|
|
5325
|
+
replyToThreadDetailed,
|
|
5365
5326
|
editThreadMessage,
|
|
5366
5327
|
editThreadMessageDetailed,
|
|
5367
5328
|
editThreadKeyboard,
|
|
@@ -10447,8 +10408,10 @@ function deliverAgentOutput(key, output, meta) {
|
|
|
10447
10408
|
// a thinking-text edit queued ~50 ms before could still hit Telegram
|
|
10448
10409
|
// and briefly overwrite the visible status with stale text after the
|
|
10449
10410
|
// real output already landed. Clearing `pendingText` here is safe even
|
|
10450
|
-
// mid-flush: the loop re-checks `pendingText` after every send.
|
|
10451
|
-
|
|
10411
|
+
// mid-flush: the loop re-checks `pendingText` after every send. A status frame that
|
|
10412
|
+
// is still waiting for its ordering `finalize` (`handleAgentStatus`) is older than
|
|
10413
|
+
// this output too.
|
|
10414
|
+
supersedeStatusFrames(key);
|
|
10452
10415
|
const msgState = getThreadMessageState(key);
|
|
10453
10416
|
const hadStatusMessage = msgState.statusMessageId !== null;
|
|
10454
10417
|
if (hadStatusMessage) {
|
|
@@ -10562,9 +10525,21 @@ async function handleAgentStatus(key, status) {
|
|
|
10562
10525
|
// resumes the stale status is removed and the next status re-posts below again.
|
|
10563
10526
|
// Group mode now drains any coalesced-but-unsent output here too (S2), so the
|
|
10564
10527
|
// status likewise lands below content rather than above a still-buffered chunk;
|
|
10565
|
-
// a fully-delivered turn is a no-op.
|
|
10566
|
-
|
|
10528
|
+
// a fully-delivered turn is a no-op. The wait is capped like that of every post
|
|
10529
|
+
// after the streamed text: a landing that never ends must not keep the tool's
|
|
10530
|
+
// frame off the topic for ever.
|
|
10531
|
+
//
|
|
10532
|
+
// That drain waits for the buffered content's paced Bot API sends, and the agent's next text can
|
|
10533
|
+
// arrive meanwhile. Parked after the wait, this frame would still be created — below the text
|
|
10534
|
+
// that outran it (`sendStatusFrame` reads the frame generation only after the wait) — a «🔧 tool»
|
|
10535
|
+
// line left under the finished turn, which the next tool status then edits instead of posting its
|
|
10536
|
+
// own message. So a frame that something newer superseded meanwhile (`supersedeStatusFrames`) is
|
|
10537
|
+
// dropped — and so is one whose coalescer a teardown replaced during the wait.
|
|
10567
10538
|
const c = getStatusCoalesceState(key);
|
|
10539
|
+
const supersedeCountAtArrival = c.supersedeCount;
|
|
10540
|
+
await (0, streamedOutputLanding_1.landStreamedOutputWithinLimit)(() => getOutboundFor(key).finalize(key), (0, sessionKey_1.keyToString)(key));
|
|
10541
|
+
if (statusCoalescers.get((0, sessionKey_1.keyToString)(key)) !== c || c.supersedeCount !== supersedeCountAtArrival)
|
|
10542
|
+
return;
|
|
10568
10543
|
c.pendingText = status;
|
|
10569
10544
|
// Don't start a flush while one is already running OR while a deferred
|
|
10570
10545
|
// retry is armed for a 429 cooldown — in both cases the newest
|
|
@@ -10999,7 +10974,7 @@ function runClaudeLivenessTick(key) {
|
|
|
10999
10974
|
})) {
|
|
11000
10975
|
state.statusIdleSuppressed = true;
|
|
11001
10976
|
stopClaudeLiveness(key);
|
|
11002
|
-
|
|
10977
|
+
supersedeStatusFrames(key);
|
|
11003
10978
|
void deleteStatusMessage(key).catch(() => { });
|
|
11004
10979
|
return;
|
|
11005
10980
|
}
|
|
@@ -11342,7 +11317,7 @@ function handleAgentQuestion(key, questionData) {
|
|
|
11342
11317
|
// liveness loop first so it can't recreate a frame under the question prompt
|
|
11343
11318
|
// (Claude-only; a no-op for OpenCode threads, which never arm it).
|
|
11344
11319
|
stopClaudeLiveness(key);
|
|
11345
|
-
|
|
11320
|
+
supersedeStatusFrames(key);
|
|
11346
11321
|
deleteStatusMessage(key).catch(() => { });
|
|
11347
11322
|
// The question UI takes over — remove any live thinking frame so it doesn't
|
|
11348
11323
|
// sit above the prompt (it would otherwise persist past the answer).
|
|
@@ -11353,9 +11328,10 @@ function handleAgentQuestion(key, questionData) {
|
|
|
11353
11328
|
// the live draft so its already-accumulated text lands as a permanent message
|
|
11354
11329
|
// above the prompt, not dropped; the finalize IS the persistence — no parallel
|
|
11355
11330
|
// queueOutput in DM. Group: drain any coalesced-but-unsent output so the answer
|
|
11356
|
-
// lands above the prompt rather than behind it, S2).
|
|
11357
|
-
//
|
|
11358
|
-
|
|
11331
|
+
// lands above the prompt rather than behind it, S2). Started HERE, so the text is
|
|
11332
|
+
// taken before anything else moves; the question is posted once it has landed (or
|
|
11333
|
+
// after `streamedOutputLandingLimitMs`). A fully-delivered turn is a no-op for both.
|
|
11334
|
+
const streamedOutputLanding = (0, streamedOutputLanding_1.landStreamedOutputWithinLimit)(() => landStreamedOutputOfThread(key), (0, sessionKey_1.keyToString)(key));
|
|
11359
11335
|
// The question UI replaces the "working" cue — stop the typing loader.
|
|
11360
11336
|
getOutboundFor(key).setActivity(key, 'idle');
|
|
11361
11337
|
// Audit S13 / #31: register the pending question BEFORE the async
|
|
@@ -11376,7 +11352,10 @@ function handleAgentQuestion(key, questionData) {
|
|
|
11376
11352
|
answers: new Array(questionData.questions.length).fill(null),
|
|
11377
11353
|
currentIndex: 0,
|
|
11378
11354
|
});
|
|
11379
|
-
void runQuestionLifecycleOp(key, () =>
|
|
11355
|
+
void runQuestionLifecycleOp(key, async () => {
|
|
11356
|
+
await streamedOutputLanding;
|
|
11357
|
+
await postPendingQuestionAt(key);
|
|
11358
|
+
});
|
|
11380
11359
|
}
|
|
11381
11360
|
/**
|
|
11382
11361
|
* @description Render + send ONE OpenCode question (the one at the pending
|
|
@@ -11439,11 +11418,13 @@ async function postPendingQuestionAt(key) {
|
|
|
11439
11418
|
? (0, questionKeyboards_1.buildQuestionOptionsKeyboard)(question, (optionIndex) => `qa_${qIdx}_${optionIndex}`)
|
|
11440
11419
|
: undefined;
|
|
11441
11420
|
try {
|
|
11442
|
-
let
|
|
11443
|
-
|
|
11444
|
-
|
|
11445
|
-
|
|
11421
|
+
let outcome = await replyToThreadDetailed(key, (0, openCodeQuestionFlow_1.buildQuestionBodyLines)(question, escapeMarkdown).join('\n'), (0, questionKeyboards_1.buildKeyboardExtra)(keyboard, { parse_mode: 'Markdown' }));
|
|
11422
|
+
// Markdown rejected — retry plain. Only a post that FAILED: one whose outcome is unknown may already be in the topic, and a
|
|
11423
|
+
// second copy of the question would be posted under it (its id stays unknown; its buttons still answer it).
|
|
11424
|
+
if (outcome.kind === 'failed') {
|
|
11425
|
+
outcome = await replyToThreadDetailed(key, (0, openCodeQuestionFlow_1.buildQuestionBodyLinesPlain)(question).join('\n'), (0, questionKeyboards_1.buildKeyboardExtra)(keyboard));
|
|
11446
11426
|
}
|
|
11427
|
+
const messageId = outcome.kind === 'sent' ? outcome.messageId : null;
|
|
11447
11428
|
if (messageId !== null) {
|
|
11448
11429
|
// Patch the messageId on the existing entry (it may already have been
|
|
11449
11430
|
// cleared/advanced by an answer callback firing in between). Route
|
|
@@ -11495,9 +11476,10 @@ function handleQuestionGone(key) {
|
|
|
11495
11476
|
function handleAgentClosed(key) {
|
|
11496
11477
|
// What the process held that died with it (its own background work), taken before the cleanup below.
|
|
11497
11478
|
const lostWork = takeLostWorkOf(key);
|
|
11498
|
-
// Session is gone —
|
|
11499
|
-
//
|
|
11500
|
-
//
|
|
11479
|
+
// Session is gone — the not-yet-sent output gets its ONE final attempt (a 429
|
|
11480
|
+
// drops what it keeps, nothing is retried after the stop), so the agent's last
|
|
11481
|
+
// words may still land just after the "session ended" notice; the pending status
|
|
11482
|
+
// frame is dropped.
|
|
11501
11483
|
clearThreadQueues(key);
|
|
11502
11484
|
// Session gone — stop the liveness loop so it can't recreate a frame after
|
|
11503
11485
|
// the close (it would otherwise outlive the session via its self-re-arm).
|
|
@@ -11611,7 +11593,7 @@ function createLostWorkPostDeps() {
|
|
|
11611
11593
|
function handleAgentError(key, error) {
|
|
11612
11594
|
console.error(`[Bot] adapter error ${(0, sessionKey_1.keyToString)(key)}:`, error.message);
|
|
11613
11595
|
stopClaudeLiveness(key);
|
|
11614
|
-
|
|
11596
|
+
supersedeStatusFrames(key);
|
|
11615
11597
|
deleteStatusMessage(key).catch(() => { });
|
|
11616
11598
|
clearThinkingMessage(key);
|
|
11617
11599
|
clearSubagentStatus(key);
|
|
@@ -11656,8 +11638,8 @@ function handleAgentStarted(key) {
|
|
|
11656
11638
|
/**
|
|
11657
11639
|
* @description The Telegram frames a process that is GONE leaves behind — shared
|
|
11658
11640
|
* by an explicit stop ({@link handleAgentStopped}) and the idle stop
|
|
11659
|
-
* ({@link handleAgentSuspended}).
|
|
11660
|
-
*
|
|
11641
|
+
* ({@link handleAgentSuspended}). Give the thread's queued-but-unsent output its ONE
|
|
11642
|
+
* final attempt ({@link clearThreadQueues}: never retried after the stop); stop the liveness loop and
|
|
11661
11643
|
* remove its frame (a gone process is idle, a lingering "working…" indicator would
|
|
11662
11644
|
* be a stuck spinner — the timer first, so it cannot recreate the frame right after
|
|
11663
11645
|
* the delete); the "thinking …" frame and the sub-agent status for the same reason;
|
|
@@ -12603,7 +12585,8 @@ const sendFilesToThread = (0, fileSendService_1.createSendFilesToThread)({
|
|
|
12603
12585
|
? { ok: true, target: key, workDir: decision.workDir }
|
|
12604
12586
|
: { ok: false, error: decision.message };
|
|
12605
12587
|
},
|
|
12606
|
-
|
|
12588
|
+
// An upload may take long by its size and bounds its wait for Telegram's answer itself (`fileSendGateway.ts`).
|
|
12589
|
+
executeDelivery: (key, delivery, signal) => (0, rateLimiter_1.enqueueSend)(key, delivery, signal, { hasOperationDeadline: false }),
|
|
12607
12590
|
gateway: (0, fileSendGateway_1.createTelegramFileSendGateway)({
|
|
12608
12591
|
sendPhoto: (key, input, caption, signal) => bot.telegram.callApi('sendPhoto', {
|
|
12609
12592
|
chat_id: (0, sessionKeyCodec_1.getTelegramChatId)(key),
|
|
@@ -12637,6 +12620,17 @@ const sendFilesToThread = (0, fileSendService_1.createSendFilesToThread)({
|
|
|
12637
12620
|
}),
|
|
12638
12621
|
recordMessageIds: (key, messageIds) => state.pushMessageIds(key, messageIds),
|
|
12639
12622
|
});
|
|
12623
|
+
/**
|
|
12624
|
+
* @description Land what the agent streamed before a call it just made — the text its backend still batches (or has written and
|
|
12625
|
+
* the bot has not read yet) and the output the topic still debounces or is sending — so what the call posts lands BELOW it.
|
|
12626
|
+
* The sender of `answer_request` and `send_messages_to_user` and the question path run it first.
|
|
12627
|
+
*/
|
|
12628
|
+
async function landStreamedOutputOfThread(key) {
|
|
12629
|
+
// The text may still sit in the adapter's own batch window (or unread in its output log): it has to reach the output queue
|
|
12630
|
+
// before that queue is landed.
|
|
12631
|
+
(0, createAdapter_1.getThreadAdapter)(key).flushPendingOutput?.(key);
|
|
12632
|
+
await getOutboundFor(key).finalize(key);
|
|
12633
|
+
}
|
|
12640
12634
|
/**
|
|
12641
12635
|
* Discrete-message sender behind `send_messages_to_user`. Each message is sent as
|
|
12642
12636
|
* its OWN permanent message through `replyChunkWithFallback` (HTML-first with a
|
|
@@ -12654,13 +12648,19 @@ const sendMessagesToThread = (0, messageSendService_1.createSendMessagesToThread
|
|
|
12654
12648
|
return { ok: false, error: `invalid threadKey "${threadKeyStr}"` };
|
|
12655
12649
|
}
|
|
12656
12650
|
},
|
|
12657
|
-
sendChunk: (key, chunk) =>
|
|
12651
|
+
sendChunk: async (key, chunk) => {
|
|
12652
|
+
const outcome = await replyChunkDetailed(key, (0, renderAgentHtml_1.renderAgentHtml)(chunk), chunk);
|
|
12653
|
+
if (outcome.kind === 'unknown')
|
|
12654
|
+
throw new messageSendService_1.MessageDeliveryUnknownError();
|
|
12655
|
+
return outcome.kind === 'sent' ? outcome.messageId : null;
|
|
12656
|
+
},
|
|
12658
12657
|
// Reuse the SAME secure file-send pipeline as `send_file_to_user` for an
|
|
12659
12658
|
// attachment item — no second pipeline, no duplicated path-safety.
|
|
12660
12659
|
sendFiles: sendFilesToThread,
|
|
12661
12660
|
splitMessage: messageSplit_1.splitMessage,
|
|
12662
12661
|
maxMessageLength: messageSplit_1.MAX_MESSAGE_LEN,
|
|
12663
12662
|
measureRendered: (chunk) => (0, renderAgentHtml_1.renderAgentHtml)(chunk).length,
|
|
12663
|
+
landStreamedOutput: landStreamedOutputOfThread,
|
|
12664
12664
|
});
|
|
12665
12665
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
12666
12666
|
// Requests — answer sinks and the wake-up engine's view of a session
|