charness 4.0.1 → 4.1.1
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 +37 -0
- package/DEVELOPMENT.md +3 -2
- package/SETUP.md +34 -8
- 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 +61 -5
- package/dist/adapters/claudeJsonStreamAdapter.d.ts.map +1 -1
- package/dist/adapters/claudeJsonStreamAdapter.js +147 -18
- 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 +430 -297
- package/dist/bot.js.map +1 -1
- package/dist/connectors/jira/answerSink.d.ts +8 -0
- package/dist/connectors/jira/answerSink.d.ts.map +1 -1
- package/dist/connectors/jira/answerSink.js +15 -0
- package/dist/connectors/jira/answerSink.js.map +1 -1
- package/dist/connectors/jira/config.d.ts +16 -0
- package/dist/connectors/jira/config.d.ts.map +1 -1
- package/dist/connectors/jira/config.js +21 -2
- package/dist/connectors/jira/config.js.map +1 -1
- package/dist/connectors/jira/connector.d.ts +10 -3
- package/dist/connectors/jira/connector.d.ts.map +1 -1
- package/dist/connectors/jira/connector.js +21 -3
- package/dist/connectors/jira/connector.js.map +1 -1
- package/dist/connectors/jira/inbound.d.ts +200 -18
- package/dist/connectors/jira/inbound.d.ts.map +1 -1
- package/dist/connectors/jira/inbound.js +814 -43
- package/dist/connectors/jira/inbound.js.map +1 -1
- package/dist/connectors/jira/prompt.d.ts +46 -0
- package/dist/connectors/jira/prompt.d.ts.map +1 -1
- package/dist/connectors/jira/prompt.js +123 -15
- package/dist/connectors/jira/prompt.js.map +1 -1
- package/dist/connectors/jira/trigger.d.ts +27 -4
- package/dist/connectors/jira/trigger.d.ts.map +1 -1
- package/dist/connectors/jira/trigger.js +35 -1
- package/dist/connectors/jira/trigger.js.map +1 -1
- package/dist/connectors/jira/triggerLog.d.ts +60 -5
- package/dist/connectors/jira/triggerLog.d.ts.map +1 -1
- package/dist/connectors/jira/triggerLog.js +116 -7
- package/dist/connectors/jira/triggerLog.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 +29 -2
- package/dist/connectors/telegram/commands/runners.d.ts.map +1 -1
- package/dist/connectors/telegram/commands/runners.js +84 -45
- 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 +50 -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 +17 -0
- package/dist/connectors/telegram/telegramFailureRetry.d.ts.map +1 -0
- package/dist/connectors/telegram/telegramFailureRetry.js +29 -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/i18n/de.d.ts.map +1 -1
- package/dist/i18n/de.js +4 -0
- package/dist/i18n/de.js.map +1 -1
- package/dist/i18n/en.d.ts.map +1 -1
- package/dist/i18n/en.js +4 -0
- package/dist/i18n/en.js.map +1 -1
- package/dist/i18n/es.d.ts.map +1 -1
- package/dist/i18n/es.js +4 -0
- package/dist/i18n/es.js.map +1 -1
- package/dist/i18n/fr.d.ts.map +1 -1
- package/dist/i18n/fr.js +4 -0
- package/dist/i18n/fr.js.map +1 -1
- package/dist/i18n/hi.d.ts.map +1 -1
- package/dist/i18n/hi.js +4 -0
- package/dist/i18n/hi.js.map +1 -1
- package/dist/i18n/ja.d.ts.map +1 -1
- package/dist/i18n/ja.js +4 -0
- package/dist/i18n/ja.js.map +1 -1
- package/dist/i18n/ka.d.ts.map +1 -1
- package/dist/i18n/ka.js +4 -0
- package/dist/i18n/ka.js.map +1 -1
- package/dist/i18n/pt.d.ts.map +1 -1
- package/dist/i18n/pt.js +4 -0
- package/dist/i18n/pt.js.map +1 -1
- package/dist/i18n/ru.d.ts.map +1 -1
- package/dist/i18n/ru.js +4 -0
- package/dist/i18n/ru.js.map +1 -1
- package/dist/i18n/uk.d.ts.map +1 -1
- package/dist/i18n/uk.js +4 -0
- package/dist/i18n/uk.js.map +1 -1
- package/dist/i18n/uz.d.ts.map +1 -1
- package/dist/i18n/uz.js +4 -0
- package/dist/i18n/uz.js.map +1 -1
- package/dist/i18n/zh.d.ts.map +1 -1
- package/dist/i18n/zh.js +4 -0
- package/dist/i18n/zh.js.map +1 -1
- package/dist/i18n.d.ts.map +1 -1
- package/dist/i18n.js +2 -1
- package/dist/i18n.js.map +1 -1
- 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/requests/requestHeader.d.ts.map +1 -1
- package/dist/requests/requestHeader.js +1 -0
- package/dist/requests/requestHeader.js.map +1 -1
- package/dist/requests/types.d.ts +4 -1
- package/dist/requests/types.d.ts.map +1 -1
- package/dist/requests/wakeUpEngine.d.ts +31 -1
- package/dist/requests/wakeUpEngine.d.ts.map +1 -1
- package/dist/requests/wakeUpEngine.js +94 -2
- package/dist/requests/wakeUpEngine.js.map +1 -1
- package/dist/requests/wakeUpRules.d.ts +7 -0
- package/dist/requests/wakeUpRules.d.ts.map +1 -1
- package/dist/requests/wakeUpRules.js +14 -0
- package/dist/requests/wakeUpRules.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/scheduler/engine.d.ts +17 -4
- package/dist/scheduler/engine.d.ts.map +1 -1
- package/dist/scheduler/engine.js +55 -10
- package/dist/scheduler/engine.js.map +1 -1
- package/dist/scheduler/mcpBoot.d.ts +6 -2
- package/dist/scheduler/mcpBoot.d.ts.map +1 -1
- package/dist/scheduler/mcpBoot.js +7 -1
- package/dist/scheduler/mcpBoot.js.map +1 -1
- package/dist/scheduler/mcpSurface.d.ts.map +1 -1
- package/dist/scheduler/mcpSurface.js +18 -9
- package/dist/scheduler/mcpSurface.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/sendErrorClassifier.d.ts +6 -0
- package/dist/sendErrorClassifier.d.ts.map +1 -1
- package/dist/sendErrorClassifier.js +9 -0
- package/dist/sendErrorClassifier.js.map +1 -1
- package/dist/startupPromptBuffer.d.ts +8 -8
- package/dist/startupPromptBuffer.d.ts.map +1 -1
- package/dist/startupPromptBuffer.js +7 -5
- package/dist/startupPromptBuffer.js.map +1 -1
- package/dist/testTimings.d.ts +6 -3
- package/dist/testTimings.d.ts.map +1 -1
- package/dist/testTimings.js +7 -2
- package/dist/testTimings.js.map +1 -1
- package/dist/threadRouting.d.ts +23 -0
- package/dist/threadRouting.d.ts.map +1 -1
- package/dist/threadRouting.js +28 -0
- package/dist/threadRouting.js.map +1 -1
- package/dist/trackers/taskAgentSlots.d.ts +42 -3
- package/dist/trackers/taskAgentSlots.d.ts.map +1 -1
- package/dist/trackers/taskAgentSlots.js +31 -11
- package/dist/trackers/taskAgentSlots.js.map +1 -1
- package/dist/types.d.ts +16 -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/fileSendPlan.d.ts +30 -8
- package/dist/utils/fileSendPlan.d.ts.map +1 -1
- package/dist/utils/fileSendPlan.js +37 -12
- package/dist/utils/fileSendPlan.js.map +1 -1
- package/dist/utils/fileSendService.d.ts +1 -1
- package/dist/utils/fileSendService.d.ts.map +1 -1
- package/dist/utils/fileSendService.js +9 -1
- package/dist/utils/fileSendService.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/imageDimensions.d.ts +32 -0
- package/dist/utils/imageDimensions.d.ts.map +1 -0
- package/dist/utils/imageDimensions.js +181 -0
- package/dist/utils/imageDimensions.js.map +1 -0
- package/dist/utils/jsonStreamHost.d.ts +35 -9
- package/dist/utils/jsonStreamHost.d.ts.map +1 -1
- package/dist/utils/jsonStreamHost.js +59 -16
- package/dist/utils/jsonStreamHost.js.map +1 -1
- package/dist/utils/lostWork.d.ts +8 -2
- package/dist/utils/lostWork.d.ts.map +1 -1
- package/dist/utils/lostWork.js +9 -5
- package/dist/utils/lostWork.js.map +1 -1
- 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/promptDelivery.d.ts +11 -2
- package/dist/utils/promptDelivery.d.ts.map +1 -1
- package/dist/utils/promptDelivery.js +3 -3
- package/dist/utils/promptDelivery.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
|
|
@@ -2760,6 +2730,21 @@ async function authoriseContext(ctx) {
|
|
|
2760
2730
|
noteGroupTitle(ctx, key);
|
|
2761
2731
|
return key;
|
|
2762
2732
|
}
|
|
2733
|
+
/**
|
|
2734
|
+
* @description The gate of a tap on a pairing line's «jobs at once» row (`/runners`): the line is sent to the admin who asked for it in a
|
|
2735
|
+
* PRIVATE message, so the tap comes from their own chat with the bot — which the DM surface does not serve unless it is the owner's
|
|
2736
|
+
* (`authoriseContext` refuses it). A group admin tapping in a chat that is theirs gets that chat's key (`getOwnPrivateChatKey`); every
|
|
2737
|
+
* other tap — the group, the owner's DM — takes the usual admin gate. The key, or `null` when refused.
|
|
2738
|
+
*/
|
|
2739
|
+
async function authorisePairingTap(ctx) {
|
|
2740
|
+
if (ctx.chat?.type === 'private' && !checkIsDmChat(ctx)) {
|
|
2741
|
+
const key = (0, threadRouting_1.getOwnPrivateChatKey)({ chatType: ctx.chat.type, chatId: ctx.chat.id, userId: ctx.from?.id, adminIds: await adminCache.getAdminIds() });
|
|
2742
|
+
if (key === null)
|
|
2743
|
+
console.warn(`[security] ignored update from chat ${ctx.chat.id} user ${ctx.from?.id ?? '?'} (not a group admin in their own private chat)`);
|
|
2744
|
+
return key;
|
|
2745
|
+
}
|
|
2746
|
+
return authoriseContext(ctx);
|
|
2747
|
+
}
|
|
2763
2748
|
/**
|
|
2764
2749
|
* Refresh the group-title cache from an accepted update — supergroups always carry `chat.title`. Feeds the thread-context
|
|
2765
2750
|
* preamble (S2). Cheap, idempotent, and the one place every accepted update funnels through. A private chat (DM key) has
|
|
@@ -3337,7 +3322,9 @@ async function unpinThreadQuestion(key) {
|
|
|
3337
3322
|
*/
|
|
3338
3323
|
function buildSendExtra(key, extra) {
|
|
3339
3324
|
const base = extra;
|
|
3340
|
-
|
|
3325
|
+
// The main thread of ANY private chat — the owner's DM and an admin's own chat alike — has no topic to name: Telegram answers a
|
|
3326
|
+
// `message_thread_id` there with «message thread not found».
|
|
3327
|
+
if (checkIsGeneral(key) || (0, threadRouting_1.checkIsPrivateChatMainKey)(key))
|
|
3341
3328
|
return { ...base };
|
|
3342
3329
|
// Audit S20 / #36: spread `base` BEFORE `message_thread_id` so a
|
|
3343
3330
|
// caller passing `message_thread_id: undefined` in `extra` can't
|
|
@@ -3346,8 +3333,16 @@ function buildSendExtra(key, extra) {
|
|
|
3346
3333
|
return { ...base, message_thread_id: (0, sessionKeyCodec_1.getTelegramThreadId)(key) };
|
|
3347
3334
|
}
|
|
3348
3335
|
async function replyToThread(key, text, extra = {}, options = {}) {
|
|
3336
|
+
const outcome = await replyToThreadDetailed(key, text, extra, options);
|
|
3337
|
+
return outcome.kind === 'sent' ? outcome.messageId : null;
|
|
3338
|
+
}
|
|
3339
|
+
/**
|
|
3340
|
+
* @description {@link replyToThread} telling a send whose outcome is unknown from one that failed, and a failure worth another
|
|
3341
|
+
* try later from a refusal for good — see {@link ThreadSendOutcome}.
|
|
3342
|
+
*/
|
|
3343
|
+
async function replyToThreadDetailed(key, text, extra = {}, options = {}) {
|
|
3349
3344
|
if (!checkIsTelegramPrimitiveKey(key, 'replyToThread'))
|
|
3350
|
-
return
|
|
3345
|
+
return { kind: 'failed', isRetryable: false };
|
|
3351
3346
|
const sendOnce = (sendExtra, sentText = text) => {
|
|
3352
3347
|
const send = () => bot.telegram.sendMessage((0, sessionKeyCodec_1.getTelegramChatId)(key), sentText, sendExtra);
|
|
3353
3348
|
return options.unpaced ? (0, rateLimiter_1.sendUnpaced)(key, send, options.signal) : (0, rateLimiter_1.enqueueSend)(key, send, options.signal);
|
|
@@ -3358,7 +3353,12 @@ async function replyToThread(key, text, extra = {}, options = {}) {
|
|
|
3358
3353
|
await state.pushMessageId(key, messageId);
|
|
3359
3354
|
if ((0, bindPicker_1.checkIsBindPickerExtra)(extra))
|
|
3360
3355
|
openBindMessages.remember((0, sessionKey_1.keyToString)(key), messageId, Date.now());
|
|
3361
|
-
return messageId;
|
|
3356
|
+
return { kind: 'sent', messageId };
|
|
3357
|
+
};
|
|
3358
|
+
// A send the Bot API did not answer in time may have landed: it is reported, never sent again (no plain retry either).
|
|
3359
|
+
const reportUnknown = () => {
|
|
3360
|
+
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`);
|
|
3361
|
+
return { kind: 'unknown' };
|
|
3362
3362
|
};
|
|
3363
3363
|
// 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
3364
|
const releaseSecret = options.isSecret ? (0, outputTrace_1.markOutboundTextsSecret)([text, options.plainFallbackText]) : null;
|
|
@@ -3367,7 +3367,9 @@ async function replyToThread(key, text, extra = {}, options = {}) {
|
|
|
3367
3367
|
}
|
|
3368
3368
|
catch (e) {
|
|
3369
3369
|
if (options.signal?.aborted && (0, utils_1.checkIsAbortError)(e))
|
|
3370
|
-
return
|
|
3370
|
+
return { kind: 'failed', isRetryable: false };
|
|
3371
|
+
if ((0, rateLimiter_1.checkIsSendOutcomeUnknownError)(e))
|
|
3372
|
+
return reportUnknown();
|
|
3371
3373
|
// Markdown parse failure fallback. Several `t(...)` templates interpolate
|
|
3372
3374
|
// user-controlled content (subdir names, branch names, error strings)
|
|
3373
3375
|
// into Markdown body — a backtick or stray `*` inside the content
|
|
@@ -3386,8 +3388,10 @@ async function replyToThread(key, text, extra = {}, options = {}) {
|
|
|
3386
3388
|
return await trackSent(await sendOnce(buildSendExtra(key, plainExtra), options.plainFallbackText ?? text));
|
|
3387
3389
|
}
|
|
3388
3390
|
catch (e2) {
|
|
3391
|
+
if ((0, rateLimiter_1.checkIsSendOutcomeUnknownError)(e2))
|
|
3392
|
+
return reportUnknown();
|
|
3389
3393
|
await handleSendError(key, e2);
|
|
3390
|
-
return
|
|
3394
|
+
return (0, telegramFailureRetry_1.getFailedSendOutcome)(e2);
|
|
3391
3395
|
}
|
|
3392
3396
|
}
|
|
3393
3397
|
// A double-429 (rate-limited even after withRateLimitRetry's single
|
|
@@ -3396,7 +3400,7 @@ async function replyToThread(key, text, extra = {}, options = {}) {
|
|
|
3396
3400
|
// re-arm a bounded redelivery (its late re-send was the OUT-OF-ORDER cause
|
|
3397
3401
|
// the user reported) — the rare 429 is just logged via handleSendError.
|
|
3398
3402
|
await handleSendError(key, e);
|
|
3399
|
-
return
|
|
3403
|
+
return (0, telegramFailureRetry_1.getFailedSendOutcome)(e);
|
|
3400
3404
|
}
|
|
3401
3405
|
finally {
|
|
3402
3406
|
releaseSecret?.();
|
|
@@ -3405,9 +3409,10 @@ async function replyToThread(key, text, extra = {}, options = {}) {
|
|
|
3405
3409
|
/**
|
|
3406
3410
|
* @description Edit an existing assistant message in the thread.
|
|
3407
3411
|
*
|
|
3408
|
-
* Returns `true` on success
|
|
3409
|
-
*
|
|
3410
|
-
*
|
|
3412
|
+
* Returns `true` on success — or when the outcome is unknown, see
|
|
3413
|
+
* {@link editThreadMessageDetailed} — and `false` if the edit failed for any
|
|
3414
|
+
* other reason — caller decides whether to fall back to a new `replyToThread`.
|
|
3415
|
+
* We don't track edits as new ids (the original was already tracked).
|
|
3411
3416
|
*
|
|
3412
3417
|
* `plainFallbackText`: the text for the retry without `parse_mode` when Telegram cannot parse the Markdown one — the
|
|
3413
3418
|
* same text when absent, which shows a Markdown render's escape marks as they are; a caller that has a real plain
|
|
@@ -3418,9 +3423,17 @@ async function editThreadMessage(key, messageId, text, extra = {}, plainFallback
|
|
|
3418
3423
|
}
|
|
3419
3424
|
/**
|
|
3420
3425
|
* @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.
|
|
3426
|
+
* other failure — see {@link ThreadMessageEdit}. The failure is logged either way, as before. An edit whose outcome is unknown
|
|
3427
|
+
* counts as made ({@link getCallerEditResult}): a caller answers a failed edit by posting the content anew, which could show it twice.
|
|
3422
3428
|
*/
|
|
3423
3429
|
async function editThreadMessageDetailed(key, messageId, text, extra = {}, plainFallbackText = text) {
|
|
3430
|
+
return (0, sendOutcome_1.getCallerEditResult)(await editThreadMessageWithOutcome(key, messageId, text, extra, plainFallbackText));
|
|
3431
|
+
}
|
|
3432
|
+
/**
|
|
3433
|
+
* @description {@link editThreadMessageDetailed}, plus `unknown`: the Bot API did not answer within the send queue's deadline, the
|
|
3434
|
+
* edit may or may not be applied. The output flush reads it through `sendOutputChunks`, which counts it as made.
|
|
3435
|
+
*/
|
|
3436
|
+
async function editThreadMessageWithOutcome(key, messageId, text, extra = {}, plainFallbackText = text) {
|
|
3424
3437
|
if (!checkIsTelegramPrimitiveKey(key, 'editThreadMessage'))
|
|
3425
3438
|
return 'failed';
|
|
3426
3439
|
const editOnce = (editText, editExtra) => (0, rateLimiter_1.enqueueSend)(key, () => bot.telegram.editMessageText((0, sessionKeyCodec_1.getTelegramChatId)(key), messageId, undefined, editText, editExtra));
|
|
@@ -3429,6 +3442,8 @@ async function editThreadMessageDetailed(key, messageId, text, extra = {}, plain
|
|
|
3429
3442
|
return 'edited';
|
|
3430
3443
|
}
|
|
3431
3444
|
catch (e) {
|
|
3445
|
+
if ((0, rateLimiter_1.checkIsSendOutcomeUnknownError)(e))
|
|
3446
|
+
return reportUnknownEdit(key, messageId);
|
|
3432
3447
|
const desc = (0, sendErrorClassifier_1.checkIsApiError)(e) ? (0, sendErrorClassifier_1.getErrorDescription)(e) : '';
|
|
3433
3448
|
if (/message is not modified/i.test(desc))
|
|
3434
3449
|
return 'edited'; // benign
|
|
@@ -3449,6 +3464,8 @@ async function editThreadMessageDetailed(key, messageId, text, extra = {}, plain
|
|
|
3449
3464
|
return 'edited';
|
|
3450
3465
|
}
|
|
3451
3466
|
catch (e2) {
|
|
3467
|
+
if ((0, rateLimiter_1.checkIsSendOutcomeUnknownError)(e2))
|
|
3468
|
+
return reportUnknownEdit(key, messageId);
|
|
3452
3469
|
const desc2 = (0, sendErrorClassifier_1.checkIsApiError)(e2) ? (0, sendErrorClassifier_1.getErrorDescription)(e2) : '';
|
|
3453
3470
|
if (/message is not modified/i.test(desc2))
|
|
3454
3471
|
return 'edited';
|
|
@@ -3460,6 +3477,10 @@ async function editThreadMessageDetailed(key, messageId, text, extra = {}, plain
|
|
|
3460
3477
|
return (0, telegramError_1.checkIsMessageNotFoundError)(e) ? 'gone' : 'failed';
|
|
3461
3478
|
}
|
|
3462
3479
|
}
|
|
3480
|
+
function reportUnknownEdit(key, messageId) {
|
|
3481
|
+
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`);
|
|
3482
|
+
return 'unknown';
|
|
3483
|
+
}
|
|
3463
3484
|
/**
|
|
3464
3485
|
* @description Replace the inline keyboard of a message of the thread (`null` removes it) through the paced send queue.
|
|
3465
3486
|
* Returns `true` when the keyboard is as asked — a no-change edit («message is not modified») counts — and `false`
|
|
@@ -3605,7 +3626,7 @@ function startTypingLoader(key) {
|
|
|
3605
3626
|
console.warn(`[typing] ${(0, sessionKey_1.keyToString)(key)} force-stop: kept alive by leaked output-queue state — ` +
|
|
3606
3627
|
`isOutputStreaming=${checkIsOutputStreaming(key)} isAdapterBusy=${checkIsAdapterBusy(key)} ` +
|
|
3607
3628
|
`pendingOutput=${q !== undefined && (0, outputFlushPlan_1.checkHasPendingOutput)(q)} ` +
|
|
3608
|
-
`
|
|
3629
|
+
`isDraining=${q?.isDraining === true} debounceTimer=${q?.debounceTimer !== null && q?.debounceTimer !== undefined}`);
|
|
3609
3630
|
if (q?.debounceTimer) {
|
|
3610
3631
|
clearTimeout(q.debounceTimer);
|
|
3611
3632
|
q.debounceTimer = null;
|
|
@@ -3632,7 +3653,7 @@ function checkIsTypingLoopStuck(key) {
|
|
|
3632
3653
|
isCompacting: checkIsThreadCompacting(key),
|
|
3633
3654
|
isTransportStreaming: getOutboundFor(key).checkIsDelivering(key),
|
|
3634
3655
|
hasPendingOutput: q !== undefined && (0, outputFlushPlan_1.checkHasPendingOutput)(q),
|
|
3635
|
-
isProcessing: q?.
|
|
3656
|
+
isProcessing: q?.isDraining === true,
|
|
3636
3657
|
hasDebounceTimer: q?.debounceTimer != null,
|
|
3637
3658
|
});
|
|
3638
3659
|
}
|
|
@@ -3759,102 +3780,80 @@ function queueOutput(key, output, isContinuation = false, isFinal = false, isCom
|
|
|
3759
3780
|
// S3: scale the in-cooldown debounce to the live remaining cooldown.
|
|
3760
3781
|
remainingCooldownMs: (0, rateLimiter_1.getRateLimitRemainingMs)((0, sessionKeyCodec_1.getTelegramChatId)(key)),
|
|
3761
3782
|
});
|
|
3762
|
-
|
|
3763
|
-
|
|
3764
|
-
|
|
3765
|
-
|
|
3766
|
-
// pending frame will be picked up by the re-trigger timer it arms).
|
|
3767
|
-
void processOutputQueue(key);
|
|
3783
|
+
const newestSeq = (0, outputFlushPlan_1.getNewestPendingSeq)(q);
|
|
3784
|
+
// Final frame: send everything now. The send loop runs once per topic, so a call while it sends only moves its target on.
|
|
3785
|
+
if (timing === 'now') {
|
|
3786
|
+
(0, groupOutputBacklog_1.drainGroupOutput)(q, newestSeq, getGroupOutputDrainDeps(key, q));
|
|
3768
3787
|
return;
|
|
3769
3788
|
}
|
|
3789
|
+
// An earlier segment, sealed by a boundary, has nothing more to wait for: its turn is over. The newest one still grows and
|
|
3790
|
+
// waits out the debounce.
|
|
3791
|
+
if (q.pendingSegments.length > 1)
|
|
3792
|
+
(0, groupOutputBacklog_1.drainGroupOutput)(q, newestSeq - 1, getGroupOutputDrainDeps(key, q));
|
|
3770
3793
|
q.debounceTimer = setTimeout(() => {
|
|
3771
3794
|
q.debounceTimer = null;
|
|
3772
|
-
|
|
3795
|
+
flushGroupOutput(key, q);
|
|
3773
3796
|
}, timing);
|
|
3774
3797
|
}
|
|
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
|
-
}
|
|
3798
|
+
/** @description Send everything the topic's backlog holds — the debounce flush and its retry. */
|
|
3799
|
+
function flushGroupOutput(key, q) {
|
|
3800
|
+
(0, groupOutputBacklog_1.drainGroupOutput)(q, (0, outputFlushPlan_1.getNewestPendingSeq)(q), getGroupOutputDrainDeps(key, q));
|
|
3812
3801
|
}
|
|
3813
3802
|
/**
|
|
3814
|
-
* @description
|
|
3815
|
-
*
|
|
3816
|
-
|
|
3817
|
-
|
|
3818
|
-
|
|
3819
|
-
|
|
3820
|
-
|
|
3821
|
-
|
|
3822
|
-
|
|
3823
|
-
|
|
3824
|
-
|
|
3825
|
-
|
|
3826
|
-
|
|
3827
|
-
|
|
3828
|
-
|
|
3829
|
-
|
|
3830
|
-
|
|
3831
|
-
|
|
3803
|
+
* @description What the send loop of a topic's backlog does through the bot: the send itself, the retry a leftover that failed
|
|
3804
|
+
* 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.
|
|
3805
|
+
*/
|
|
3806
|
+
function getGroupOutputDrainDeps(key, q) {
|
|
3807
|
+
return {
|
|
3808
|
+
sendSegment: (segment) => sendOutputImmediate(key, segment.output, segment.isContinuation, segment.startsNewMessage),
|
|
3809
|
+
onStalled: () => {
|
|
3810
|
+
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`);
|
|
3811
|
+
armOutputRetry(key, q);
|
|
3812
|
+
},
|
|
3813
|
+
onDropped: (segment, unsentRemainder, reason) => {
|
|
3814
|
+
const remainderSize = `${unsentRemainder.length} chars`;
|
|
3815
|
+
if (reason === 'refused')
|
|
3816
|
+
console.warn(`[send] ${(0, sessionKey_1.keyToString)(key)} output remainder (${remainderSize}) was refused by Telegram for good and was dropped`);
|
|
3817
|
+
else
|
|
3818
|
+
console.warn(`[send] ${(0, sessionKey_1.keyToString)(key)} output remainder (${remainderSize}) failed on its final attempt at a stop and was dropped`);
|
|
3819
|
+
// Text that took the new-message mark and is dropped leaves the mark with the thread again.
|
|
3820
|
+
if (segment.startsNewMessage)
|
|
3821
|
+
markNeedsNewMessage(key);
|
|
3822
|
+
},
|
|
3823
|
+
onSendError: (error) => console.error(`[send] ${(0, sessionKey_1.keyToString)(key)} output send failed; it is not sent again:`, error.message),
|
|
3824
|
+
};
|
|
3825
|
+
}
|
|
3826
|
+
/**
|
|
3827
|
+
* @description Arm the timer that sends again what a failure for now (a 429, the network) put back at the head of the backlog.
|
|
3828
|
+
* Several segments go at once; one waits out the debounce, stretched while the chat is in a 429 cooldown.
|
|
3829
|
+
*/
|
|
3830
|
+
function armOutputRetry(key, q) {
|
|
3831
|
+
// Audit S13 / #30: the re-trigger `setTimeout` used to be a bare
|
|
3832
|
+
// call whose handle was never stored. A `queueOutput` call between
|
|
3833
|
+
// here and the timer firing would `clearTimeout(null)` and
|
|
3834
|
+
// schedule a duplicate timer, leaving one orphan callback alive.
|
|
3835
|
+
// Routing through `queueOutput`-equivalent code keeps `q.debounceTimer`
|
|
3836
|
+
// authoritative.
|
|
3837
|
+
if (q.debounceTimer)
|
|
3838
|
+
clearTimeout(q.debounceTimer);
|
|
3839
|
+
q.debounceTimer = setTimeout(() => {
|
|
3840
|
+
q.debounceTimer = null;
|
|
3841
|
+
flushGroupOutput(key, q);
|
|
3842
|
+
}, q.pendingSegments.length > 1 ? 0 : getOutputDelay((0, sessionKeyCodec_1.getTelegramChatId)(key)));
|
|
3843
|
+
}
|
|
3844
|
+
/**
|
|
3845
|
+
* @description Group-path `finalizeInFlight`: land everything the topic's backlog holds — and the send under way — before the
|
|
3846
|
+
* caller posts what must come after it: a tool call's status frame, a question, an answer of `answer_request`, the messages of
|
|
3847
|
+
* `send_messages_to_user` (`landStreamedOutputOfThread`). Those go straight to the topic and would otherwise overtake the
|
|
3848
|
+
* text the agent streamed before them, which still waits out the debounce. Resolves once that text has settled
|
|
3849
|
+
* ({@link landGroupOutput}); a 429 leftover goes back to the head and the wait goes on until its retry lands it. A stop gives
|
|
3850
|
+
* the backlog its final attempt separately (`clearThreadQueues`).
|
|
3832
3851
|
*/
|
|
3833
3852
|
async function finalizeGroupOutput(key) {
|
|
3834
3853
|
const q = outputQueues.get((0, sessionKey_1.keyToString)(key));
|
|
3835
3854
|
if (!q)
|
|
3836
3855
|
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
|
-
}
|
|
3856
|
+
await (0, groupOutputBacklog_1.landGroupOutput)(q, getGroupOutputDrainDeps(key, q));
|
|
3858
3857
|
}
|
|
3859
3858
|
/**
|
|
3860
3859
|
* @description Render `output` as the agent's permanent message in a thread.
|
|
@@ -3878,7 +3877,8 @@ async function finalizeGroupOutput(key) {
|
|
|
3878
3877
|
* On Markdown rejection by Telegram we fall back to plain text (`parse_mode`
|
|
3879
3878
|
* unset) — the message lands either way. If the in-place edit fails (message
|
|
3880
3879
|
* deleted / API hiccup) we send every chunk fresh so the full combined text
|
|
3881
|
-
* still reaches the user
|
|
3880
|
+
* still reaches the user ({@link sendOutputChunks}, which also keeps a call of
|
|
3881
|
+
* unknown outcome from being made twice).
|
|
3882
3882
|
*/
|
|
3883
3883
|
async function sendOutputImmediate(key, output, isContinuation = false, startsNewMessage = false) {
|
|
3884
3884
|
// The typing loader is stopped upstream in `handleAgentOutput` (the shared
|
|
@@ -3901,51 +3901,39 @@ async function sendOutputImmediate(key, output, isContinuation = false, startsNe
|
|
|
3901
3901
|
const chunks = shouldEditFirstChunk
|
|
3902
3902
|
? planChunks
|
|
3903
3903
|
: (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
|
-
}
|
|
3904
|
+
// An edit whose outcome is unknown counts as made, and a chunk whose outcome is unknown as sent: sent (again) they could show
|
|
3905
|
+
// twice. A chunk that FAILED stops the run; the rest is the remainder the backlog puts back, or drops when Telegram refused it
|
|
3906
|
+
// for good. The cursor is the thread's own message state.
|
|
3907
|
+
const result = await (0, sendOutcome_1.sendOutputChunks)(chunks, shouldEditFirstChunk, msgState, {
|
|
3908
|
+
editLastMessage: (messageId, chunk) => editThreadMessageWithOutcome(key, messageId, (0, renderAgentHtml_1.renderAgentHtml)(chunk), { parse_mode: 'HTML' }, chunk),
|
|
3909
|
+
sendChunk: (chunk) => replyChunkDetailed(key, (0, renderAgentHtml_1.renderAgentHtml)(chunk), chunk),
|
|
3910
|
+
});
|
|
3931
3911
|
// S3: output just landed below any pending question — bring the question back
|
|
3932
3912
|
// to the bottom (debounced; no-op when no question is pending).
|
|
3933
3913
|
onThreadActivityWhileQuestionPending(key);
|
|
3934
|
-
return
|
|
3914
|
+
return result;
|
|
3935
3915
|
}
|
|
3936
3916
|
/**
|
|
3937
3917
|
* @description Send a chunk as HTML first; if Telegram rejects the entities,
|
|
3938
3918
|
* fall back to plain text so the message reaches the user either way.
|
|
3939
3919
|
*/
|
|
3940
3920
|
async function replyChunkWithFallback(key, renderedHtml, plainFallback, replyMarkup) {
|
|
3921
|
+
const outcome = await replyChunkDetailed(key, renderedHtml, plainFallback, replyMarkup);
|
|
3922
|
+
return outcome.kind === 'sent' ? outcome.messageId : null;
|
|
3923
|
+
}
|
|
3924
|
+
/**
|
|
3925
|
+
* @description {@link replyChunkWithFallback} telling an unknown outcome from a failure: a chunk whose send got no answer in time
|
|
3926
|
+
* is NOT sent again as plain text — it may already be in the topic.
|
|
3927
|
+
*/
|
|
3928
|
+
async function replyChunkDetailed(key, renderedHtml, plainFallback, replyMarkup) {
|
|
3941
3929
|
if (!checkIsTelegramPrimitiveKey(key, 'replyChunkWithFallback'))
|
|
3942
|
-
return
|
|
3930
|
+
return { kind: 'failed', isRetryable: false };
|
|
3943
3931
|
const markupExtra = replyMarkup ? { reply_markup: replyMarkup } : {};
|
|
3944
3932
|
// 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
|
|
3933
|
+
const outcome = await replyToThreadDetailed(key, renderedHtml, { parse_mode: 'HTML', ...markupExtra }, { plainFallbackText: plainFallback });
|
|
3934
|
+
if (outcome.kind !== 'failed')
|
|
3935
|
+
return outcome;
|
|
3936
|
+
return replyToThreadDetailed(key, plainFallback, markupExtra);
|
|
3949
3937
|
}
|
|
3950
3938
|
const callSendMessageDraft = bot.telegram.callApi.bind(bot.telegram);
|
|
3951
3939
|
/**
|
|
@@ -4073,11 +4061,10 @@ const shutdownOutputFlushMaxMs = rateLimiter_1.shutdownDrainMaxMs + 1000;
|
|
|
4073
4061
|
* already-emitted answer chunks died in the send pipeline with the
|
|
4074
4062
|
* process and were never re-sent). Two buffers drain, in order:
|
|
4075
4063
|
*
|
|
4076
|
-
* [A] per-thread COALESCE state — the group
|
|
4077
|
-
*
|
|
4078
|
-
* transport's active drafts (enumerated via `
|
|
4079
|
-
*
|
|
4080
|
-
* `finalizeInFlight`;
|
|
4064
|
+
* [A] per-thread COALESCE state — the group backlogs (enumerated here from
|
|
4065
|
+
* {@link outputQueues}; each gets its final attempt, as at a stop) and the
|
|
4066
|
+
* DM transport's active drafts (enumerated via `listUnfinalizedKeys`), each
|
|
4067
|
+
* finalized to a permanent message;
|
|
4081
4068
|
* [B] the per-thread send FIFOs already parked on the global pacer — drained
|
|
4082
4069
|
* by `drainPendingSends` after `enterShutdownDrain()` flips the pacer to
|
|
4083
4070
|
* immediate release (at 1 send/2s a 5-message backlog alone outlives any
|
|
@@ -4099,42 +4086,32 @@ async function finalizePendingOutputOnShutdown() {
|
|
|
4099
4086
|
let flushedCount = 0;
|
|
4100
4087
|
const flushWork = (async () => {
|
|
4101
4088
|
(0, rateLimiter_1.enterShutdownDrain)();
|
|
4102
|
-
// [A]
|
|
4103
|
-
//
|
|
4104
|
-
|
|
4089
|
+
// [A] every group backlog with text queued or being sent — the group topics', and the DM topics' on an adapter without
|
|
4090
|
+
// a draft (they coalesce there too) — gets its final attempt; the connectors land their own unfinalized content (the
|
|
4091
|
+
// DM drafts). Deduped by serialised key for the count.
|
|
4092
|
+
const flushedKeys = new Set();
|
|
4093
|
+
const landings = [];
|
|
4105
4094
|
for (const [keyStr, q] of outputQueues) {
|
|
4106
|
-
if (!(0, outputFlushPlan_1.checkHasPendingOutput)(q))
|
|
4095
|
+
if (!(0, outputFlushPlan_1.checkHasPendingOutput)(q) && !q.isDraining)
|
|
4107
4096
|
continue;
|
|
4097
|
+
let key;
|
|
4108
4098
|
try {
|
|
4109
|
-
|
|
4099
|
+
key = (0, sessionKey_1.keyFromString)(keyStr);
|
|
4110
4100
|
}
|
|
4111
4101
|
catch {
|
|
4112
|
-
|
|
4102
|
+
continue; // malformed key — nothing to flush for it
|
|
4113
4103
|
}
|
|
4104
|
+
flushedKeys.add(keyStr);
|
|
4105
|
+
landings.push((0, groupOutputBacklog_1.startFinalGroupOutputAttempt)(q, getGroupOutputDrainDeps(key, q)));
|
|
4114
4106
|
}
|
|
4115
4107
|
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 */
|
|
4108
|
+
for (const key of outbound.listUnfinalizedKeys()) {
|
|
4109
|
+
flushedKeys.add((0, sessionKey_1.keyToString)(key));
|
|
4110
|
+
landings.push(outbound.finalize(key));
|
|
4135
4111
|
}
|
|
4136
4112
|
}
|
|
4137
|
-
|
|
4113
|
+
flushedCount = flushedKeys.size;
|
|
4114
|
+
await Promise.allSettled(landings);
|
|
4138
4115
|
// [B] wait for the released FIFOs to empty, bounded by what is left of the
|
|
4139
4116
|
// shared drain budget.
|
|
4140
4117
|
return (0, rateLimiter_1.drainPendingSends)(Math.max(drainDeadlineMs - Date.now(), 0));
|
|
@@ -4994,17 +4971,19 @@ async function replayBufferedPrompts(key) {
|
|
|
4994
4971
|
// like the API-error retry's nudge, hears whether it reached the session).
|
|
4995
4972
|
await startupPromptBuffer.replayPrompts((0, sessionKey_1.keyToString)(key), {
|
|
4996
4973
|
isSessionActive,
|
|
4997
|
-
forward: async (prompt) => { await forwardPromptToAgent(key, adapter, prompt); },
|
|
4974
|
+
forward: async (prompt, isPersonInput) => { await forwardPromptToAgent(key, adapter, prompt, undefined, { isPersonInput }); },
|
|
4998
4975
|
});
|
|
4999
4976
|
if (!isSessionActive)
|
|
5000
4977
|
return;
|
|
5001
4978
|
// R23: prompts held during a usage-limit wait that ended with the previous
|
|
5002
|
-
// session go to this one — on their own when nothing above carried them.
|
|
4979
|
+
// session go to this one — on their own when nothing above carried them. They
|
|
4980
|
+
// are what people asked for meanwhile: a write that fails is told in the topic
|
|
4981
|
+
// like a person's own message, never only logged.
|
|
5003
4982
|
const heldText = limitHeldPrompts.releaseAll(key);
|
|
5004
4983
|
if (heldText === null)
|
|
5005
4984
|
return;
|
|
5006
4985
|
try {
|
|
5007
|
-
await forwardPromptToAgent(key, adapter, heldText);
|
|
4986
|
+
await forwardPromptToAgent(key, adapter, heldText, undefined, { isPersonInput: true });
|
|
5008
4987
|
}
|
|
5009
4988
|
catch (err) {
|
|
5010
4989
|
console.error('[replayBufferedPrompts] forwarding the held prompts failed:', err);
|
|
@@ -5053,7 +5032,11 @@ async function forwardPromptToAgent(key, adapter, text, sentAtMs, options = {})
|
|
|
5053
5032
|
checkIsWindowOpen: () => startupPromptBuffer.checkIsStarting((0, sessionKey_1.keyToString)(key)),
|
|
5054
5033
|
checkIsSessionActive: () => adapter.checkIsActive(key) && !(isTechnicalPrompt && (adapter.checkIsBusy?.(key) ?? false)),
|
|
5055
5034
|
buffer: async () => {
|
|
5056
|
-
|
|
5035
|
+
// A bot-made prompt (a wake-up) that waits here counts only once its replay reached the agent, as at any other buffer.
|
|
5036
|
+
const buffered = createBufferedOutcome();
|
|
5037
|
+
await deliverPromptOrBuffer(key, `${options.requestHeader ?? ''}${getPromptWithThreadMessageContext(key, text, options.messageContext)}`, true, buffered.settle, { isPersonInput: options.isPersonInput });
|
|
5038
|
+
if (options.isPersonInput !== true)
|
|
5039
|
+
await buffered.assertReplayed();
|
|
5057
5040
|
},
|
|
5058
5041
|
wake: () => wakeSleepingSessionForPrompt(key),
|
|
5059
5042
|
forward: async () => {
|
|
@@ -5108,8 +5091,10 @@ async function forwardPromptToLiveAgent(key, adapter, text, sentAtMs, options =
|
|
|
5108
5091
|
// The request header (S7) leads the per-message body, like the message context and
|
|
5109
5092
|
// unlike the once-per-change thread preamble: it names THIS message's request.
|
|
5110
5093
|
const messageBody = options.requestHeader ? `${options.requestHeader}${quotedBody}` : quotedBody;
|
|
5111
|
-
// A loss the agent was not told about yet (`utils/lostWork.ts`) rides the first real prompt, once, ahead of it
|
|
5112
|
-
|
|
5094
|
+
// A loss the agent was not told about yet (`utils/lostWork.ts`) rides the first real prompt, once, ahead of it — a
|
|
5095
|
+
// request's reminder included: the wake of a tracker request whose process a restart left behind is how its agent hears.
|
|
5096
|
+
const isLostWorkNoteCarried = (isReplayable || options.isRequestReminder === true) && adapter.name !== 'terminal';
|
|
5097
|
+
const lostWorkRecord = isLostWorkNoteCarried ? state.getLostWork(key) : undefined;
|
|
5113
5098
|
const body = lostWorkRecord ? `${(0, lostWork_1.buildLostWorkNote)(lostWorkRecord, (0, i18n_1.getLocaleEndonym)((0, i18n_1.getActiveLang)()))}\n\n${messageBody}` : messageBody;
|
|
5114
5099
|
// Cache the (reply-folded) prompt so a wedged OpenCode session can be recovered
|
|
5115
5100
|
// by restarting fresh and replaying it — replaying WITH the quote is correct.
|
|
@@ -5174,10 +5159,10 @@ async function forwardPromptToLiveAgent(key, adapter, text, sentAtMs, options =
|
|
|
5174
5159
|
if (adapter.detachRunningSubagents && !isTechnicalPrompt) {
|
|
5175
5160
|
await adapter.detachRunningSubagents(key);
|
|
5176
5161
|
}
|
|
5177
|
-
|
|
5178
|
-
//
|
|
5179
|
-
|
|
5180
|
-
|
|
5162
|
+
// A backend that can tell whether the prompt reached the agent (the json-stream host's stdin write) is asked to: a
|
|
5163
|
+
// write that failed rejects this forward, so its caller — a tracker post, a wake-up — knows the prompt never arrived
|
|
5164
|
+
// and retries, instead of believing it delivered. The input is handed over synchronously either way; only its outcome is awaited.
|
|
5165
|
+
const written = adapter.sendInputAndWait ? adapter.sendInputAndWait(key, promptText) : (adapter.sendInput(key, promptText), Promise.resolve());
|
|
5181
5166
|
// S2 busy-onset arm: start the Claude liveness loop the moment the prompt is
|
|
5182
5167
|
// forwarded — driven by `checkIsBusy`, not by waiting for an opportunistic
|
|
5183
5168
|
// scrape emit that may never come during a long quiet think. The arming grace
|
|
@@ -5186,6 +5171,26 @@ async function forwardPromptToLiveAgent(key, adapter, text, sentAtMs, options =
|
|
|
5186
5171
|
// choke point (user text, voice, scheduled run, api-retry continue, buffered
|
|
5187
5172
|
// replay), so every path that makes Claude busy now raises the working frame.
|
|
5188
5173
|
startClaudeLiveness(key, 'busyOnset');
|
|
5174
|
+
// Told only once the prompt carrying the note reached a live session: a forward that failed keeps it for the next.
|
|
5175
|
+
const noteToldIfDelivered = () => {
|
|
5176
|
+
if (lostWorkRecord && adapter.checkIsActive(key))
|
|
5177
|
+
void state.clearLostWork(key);
|
|
5178
|
+
};
|
|
5179
|
+
// A person's own message never holds the topic's update queue on its write — a CLI that stops reading its input would
|
|
5180
|
+
// keep `/esc` and every tap behind it for minutes —: they are told when it failed. Every other prompt (a tracker's post,
|
|
5181
|
+
// a wake-up, a scheduled run, a retry's nudge, the todo reminder) awaits it: one that never arrived is retried.
|
|
5182
|
+
if (options.isPersonInput === true) {
|
|
5183
|
+
void written.then(noteToldIfDelivered, (error) => reportUndeliveredTopicPrompt(key, error));
|
|
5184
|
+
return;
|
|
5185
|
+
}
|
|
5186
|
+
await written;
|
|
5187
|
+
noteToldIfDelivered();
|
|
5188
|
+
}
|
|
5189
|
+
/** @description A topic's prompt whose write into the agent failed (the forward did not wait for it): one line says so. */
|
|
5190
|
+
function reportUndeliveredTopicPrompt(key, error) {
|
|
5191
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
5192
|
+
console.warn(`[forward] ${(0, sessionKey_1.keyToString)(key)}: the prompt did not reach the agent: ${message}`);
|
|
5193
|
+
void withThreadLocale(key, () => replyToThread(key, (0, i18n_1.t)('agent.prompt_not_delivered', { error: message }))).catch(() => { });
|
|
5189
5194
|
}
|
|
5190
5195
|
/**
|
|
5191
5196
|
* @description Return the prompt text with the thread-context preamble glued
|
|
@@ -5362,6 +5367,7 @@ const botCore = {
|
|
|
5362
5367
|
command,
|
|
5363
5368
|
getState: () => state,
|
|
5364
5369
|
replyToThread,
|
|
5370
|
+
replyToThreadDetailed,
|
|
5365
5371
|
editThreadMessage,
|
|
5366
5372
|
editThreadMessageDetailed,
|
|
5367
5373
|
editThreadKeyboard,
|
|
@@ -6941,6 +6947,7 @@ const { registerRunnersCommands, registerRunnersCallbacks, handleRunnersAddressT
|
|
|
6941
6947
|
// What this instance has told about where the runners' links come from: once per new concern, pinned in General.
|
|
6942
6948
|
linkNoticesPath: path.join((0, state_1.resolveDataDir)(), 'runner-link-notices.json'),
|
|
6943
6949
|
cacheDir: runnersCacheDir,
|
|
6950
|
+
authorisePairingTap,
|
|
6944
6951
|
getGeneralKey: () => getOperatorGeneralKey(),
|
|
6945
6952
|
pinMessage: (key, messageId) => pinMessageQuiet(key, messageId, { disableNotification: false }),
|
|
6946
6953
|
sweepExpiredCodes: async (nowMs) => { await (0, hubPairing_1.sweepExpiredPairings)(runnersHub, nowMs); },
|
|
@@ -8444,7 +8451,7 @@ command('schedule', async (ctx, key, parsed) => {
|
|
|
8444
8451
|
await replyToThread(key, result.message);
|
|
8445
8452
|
const isStarting = startupPromptBuffer.checkIsStarting((0, sessionKey_1.keyToString)(key));
|
|
8446
8453
|
const opening = await openTopicRequest(key, wrappedPrompt, { source: 'schedule', requesterId: (0, topicRequest_1.getTopicRequesterId)(ctx.from) });
|
|
8447
|
-
const delivery = await deliverPromptOrBuffer(key, `${opening.header}${wrappedPrompt}`, isStarting);
|
|
8454
|
+
const delivery = await deliverPromptOrBuffer(key, `${opening.header}${wrappedPrompt}`, isStarting, undefined, { isPersonInput: true });
|
|
8448
8455
|
await settleTopicRequestAfterDelivery(key, opening, delivery);
|
|
8449
8456
|
});
|
|
8450
8457
|
const reminderWizards = new Map();
|
|
@@ -8751,7 +8758,7 @@ bot.on((0, filters_1.message)('text'), async (ctx) => {
|
|
|
8751
8758
|
}
|
|
8752
8759
|
}
|
|
8753
8760
|
// `/runners` → «Enter another address»: this General message is the address runners dial. A slash command wins over the wait.
|
|
8754
|
-
if (await handleRunnersAddressText(key, text))
|
|
8761
|
+
if (ctx.from !== undefined && (await handleRunnersAddressText(key, text, ctx.from)))
|
|
8755
8762
|
return;
|
|
8756
8763
|
// Session is mid-startup → buffer the prompt and replay it once the agent is
|
|
8757
8764
|
// ready, instead of dropping it into the "no agent running" guidance below.
|
|
@@ -9268,13 +9275,13 @@ async function downloadIncomingFile(ctx, key, meta, onError) {
|
|
|
9268
9275
|
*/
|
|
9269
9276
|
const promptDeliveryDeps = {
|
|
9270
9277
|
startupBuffer: startupPromptBuffer,
|
|
9271
|
-
forwardPrompt: (key, text) => forwardPromptToAgent(key, (0, createAdapter_1.getThreadAdapter)(key), text),
|
|
9278
|
+
forwardPrompt: (key, text, options) => forwardPromptToAgent(key, (0, createAdapter_1.getThreadAdapter)(key), text, undefined, { isPersonInput: options.isPersonInput }),
|
|
9272
9279
|
announceQueued: async (key) => {
|
|
9273
9280
|
await replyToThread(key, (0, i18n_1.t)('agent.queued_starting', { label: (0, createAdapter_1.getThreadAdapter)(key).label }));
|
|
9274
9281
|
},
|
|
9275
9282
|
};
|
|
9276
|
-
function deliverPromptOrBuffer(key, promptText, isStarting, onBufferedSettled) {
|
|
9277
|
-
return (0, promptDelivery_1.deliverPromptOrBuffer)(promptDeliveryDeps, key, promptText, isStarting, onBufferedSettled);
|
|
9283
|
+
function deliverPromptOrBuffer(key, promptText, isStarting, onBufferedSettled, options = {}) {
|
|
9284
|
+
return (0, promptDelivery_1.deliverPromptOrBuffer)(promptDeliveryDeps, key, promptText, isStarting, onBufferedSettled, options);
|
|
9278
9285
|
}
|
|
9279
9286
|
/**
|
|
9280
9287
|
* @description Per-(thread, media_group) album batcher. Telegram delivers an
|
|
@@ -9307,12 +9314,13 @@ const albumCollector = (0, mediaGroupCollector_1.createMediaGroupCollector)({
|
|
|
9307
9314
|
try {
|
|
9308
9315
|
const opening = await openTopicRequest(key, promptText, { source: 'album', requesterId: orderedItems[0].requesterId }, messageContext);
|
|
9309
9316
|
const quotedPrompt = getPromptWithThreadMessageContext(key, promptText, messageContext);
|
|
9310
|
-
const delivery = await deliverPromptOrBuffer(key, `${opening.header}${quotedPrompt}`, isStarting);
|
|
9317
|
+
const delivery = await deliverPromptOrBuffer(key, `${opening.header}${quotedPrompt}`, isStarting, undefined, { isPersonInput: true });
|
|
9311
9318
|
await settleTopicRequestAfterDelivery(key, opening, delivery);
|
|
9312
9319
|
}
|
|
9313
9320
|
catch (err) {
|
|
9321
|
+
// The files were downloaded already (each item before the flush): what failed is the album's prompt.
|
|
9314
9322
|
console.error('[Bot] album flush failed:', err);
|
|
9315
|
-
await replyToThread(key, (0, i18n_1.t)('
|
|
9323
|
+
await replyToThread(key, (0, i18n_1.t)('agent.prompt_not_delivered', { error: err instanceof Error ? err.message : String(err) })).catch(() => { });
|
|
9316
9324
|
}
|
|
9317
9325
|
});
|
|
9318
9326
|
},
|
|
@@ -9392,7 +9400,7 @@ async function handleIncomingFile(ctx, key, isFromTalker) {
|
|
|
9392
9400
|
const messageContext = getMessageContext(key, ctx.message);
|
|
9393
9401
|
const opening = await openTopicRequest(key, promptText, { source: 'file', requesterId: (0, topicRequest_1.getTopicRequesterId)(ctx.from) }, messageContext);
|
|
9394
9402
|
const quotedPrompt = getPromptWithThreadMessageContext(key, promptText, messageContext);
|
|
9395
|
-
const delivery = await deliverPromptOrBuffer(key, `${opening.header}${quotedPrompt}`, isStarting);
|
|
9403
|
+
const delivery = await deliverPromptOrBuffer(key, `${opening.header}${quotedPrompt}`, isStarting, undefined, { isPersonInput: true });
|
|
9396
9404
|
await settleTopicRequestAfterDelivery(key, opening, delivery);
|
|
9397
9405
|
}
|
|
9398
9406
|
bot.on(
|
|
@@ -10111,7 +10119,7 @@ async function bufferPromptDuringStartup(key, text, intake, messageContext) {
|
|
|
10111
10119
|
notePersonActivity(key);
|
|
10112
10120
|
const opening = await openTopicRequest(key, text, intake, messageContext);
|
|
10113
10121
|
const quotedText = getPromptWithThreadMessageContext(key, text, messageContext);
|
|
10114
|
-
await deliverPromptOrBuffer(key, `${opening.header}${quotedText}`, true);
|
|
10122
|
+
await deliverPromptOrBuffer(key, `${opening.header}${quotedText}`, true, undefined, { isPersonInput: true });
|
|
10115
10123
|
trackTopicRequestTurn(key, opening);
|
|
10116
10124
|
}
|
|
10117
10125
|
/**
|
|
@@ -10194,10 +10202,10 @@ async function deliverActivePrompt(key, adapter, text, intake, sentAtMs, message
|
|
|
10194
10202
|
checkIsWindowOpen: () => startupPromptBuffer.checkIsStarting((0, sessionKey_1.keyToString)(key)),
|
|
10195
10203
|
checkIsSessionActive: () => adapter.checkIsActive(key),
|
|
10196
10204
|
buffer: async () => {
|
|
10197
|
-
await deliverPromptOrBuffer(key, `${opening.header}${getPromptWithThreadMessageContext(key, text, messageContext)}`, true);
|
|
10205
|
+
await deliverPromptOrBuffer(key, `${opening.header}${getPromptWithThreadMessageContext(key, text, messageContext)}`, true, undefined, { isPersonInput: true });
|
|
10198
10206
|
},
|
|
10199
10207
|
wake: () => wakeSleepingSessionForPrompt(key),
|
|
10200
|
-
forward: () => forwardPromptToAgent(key, (0, createAdapter_1.getThreadAdapter)(key), text, sentAtMs, { messageContext, requestHeader: opening.header }),
|
|
10208
|
+
forward: () => forwardPromptToAgent(key, (0, createAdapter_1.getThreadAdapter)(key), text, sentAtMs, { messageContext, requestHeader: opening.header, isPersonInput: true }),
|
|
10201
10209
|
reportNoSession: async (isAlreadyTold) => {
|
|
10202
10210
|
if (!isAlreadyTold)
|
|
10203
10211
|
await replyToThread(key, (0, i18n_1.t)('agent.no_session'));
|
|
@@ -10264,7 +10272,7 @@ async function cancelPendingQuestionAndForward(key, adapter, text, sentAtMs, mes
|
|
|
10264
10272
|
if (!didLabelQuestionMessage) {
|
|
10265
10273
|
await replyToThread(key, (0, i18n_1.t)('agent.question_cancelled_for_prompt'));
|
|
10266
10274
|
}
|
|
10267
|
-
return forwardPromptToAgent(key, adapter, text, sentAtMs, { messageContext, requestHeader });
|
|
10275
|
+
return forwardPromptToAgent(key, adapter, text, sentAtMs, { messageContext, requestHeader, isPersonInput: true });
|
|
10268
10276
|
}
|
|
10269
10277
|
/**
|
|
10270
10278
|
* @description Record one answer for the CURRENTLY shown OpenCode question and
|
|
@@ -10447,8 +10455,10 @@ function deliverAgentOutput(key, output, meta) {
|
|
|
10447
10455
|
// a thinking-text edit queued ~50 ms before could still hit Telegram
|
|
10448
10456
|
// and briefly overwrite the visible status with stale text after the
|
|
10449
10457
|
// real output already landed. Clearing `pendingText` here is safe even
|
|
10450
|
-
// mid-flush: the loop re-checks `pendingText` after every send.
|
|
10451
|
-
|
|
10458
|
+
// mid-flush: the loop re-checks `pendingText` after every send. A status frame that
|
|
10459
|
+
// is still waiting for its ordering `finalize` (`handleAgentStatus`) is older than
|
|
10460
|
+
// this output too.
|
|
10461
|
+
supersedeStatusFrames(key);
|
|
10452
10462
|
const msgState = getThreadMessageState(key);
|
|
10453
10463
|
const hadStatusMessage = msgState.statusMessageId !== null;
|
|
10454
10464
|
if (hadStatusMessage) {
|
|
@@ -10562,9 +10572,21 @@ async function handleAgentStatus(key, status) {
|
|
|
10562
10572
|
// resumes the stale status is removed and the next status re-posts below again.
|
|
10563
10573
|
// Group mode now drains any coalesced-but-unsent output here too (S2), so the
|
|
10564
10574
|
// status likewise lands below content rather than above a still-buffered chunk;
|
|
10565
|
-
// a fully-delivered turn is a no-op.
|
|
10566
|
-
|
|
10575
|
+
// a fully-delivered turn is a no-op. The wait is capped like that of every post
|
|
10576
|
+
// after the streamed text: a landing that never ends must not keep the tool's
|
|
10577
|
+
// frame off the topic for ever.
|
|
10578
|
+
//
|
|
10579
|
+
// That drain waits for the buffered content's paced Bot API sends, and the agent's next text can
|
|
10580
|
+
// arrive meanwhile. Parked after the wait, this frame would still be created — below the text
|
|
10581
|
+
// that outran it (`sendStatusFrame` reads the frame generation only after the wait) — a «🔧 tool»
|
|
10582
|
+
// line left under the finished turn, which the next tool status then edits instead of posting its
|
|
10583
|
+
// own message. So a frame that something newer superseded meanwhile (`supersedeStatusFrames`) is
|
|
10584
|
+
// dropped — and so is one whose coalescer a teardown replaced during the wait.
|
|
10567
10585
|
const c = getStatusCoalesceState(key);
|
|
10586
|
+
const supersedeCountAtArrival = c.supersedeCount;
|
|
10587
|
+
await (0, streamedOutputLanding_1.landStreamedOutputWithinLimit)(() => getOutboundFor(key).finalize(key), (0, sessionKey_1.keyToString)(key));
|
|
10588
|
+
if (statusCoalescers.get((0, sessionKey_1.keyToString)(key)) !== c || c.supersedeCount !== supersedeCountAtArrival)
|
|
10589
|
+
return;
|
|
10568
10590
|
c.pendingText = status;
|
|
10569
10591
|
// Don't start a flush while one is already running OR while a deferred
|
|
10570
10592
|
// retry is armed for a 429 cooldown — in both cases the newest
|
|
@@ -10999,7 +11021,7 @@ function runClaudeLivenessTick(key) {
|
|
|
10999
11021
|
})) {
|
|
11000
11022
|
state.statusIdleSuppressed = true;
|
|
11001
11023
|
stopClaudeLiveness(key);
|
|
11002
|
-
|
|
11024
|
+
supersedeStatusFrames(key);
|
|
11003
11025
|
void deleteStatusMessage(key).catch(() => { });
|
|
11004
11026
|
return;
|
|
11005
11027
|
}
|
|
@@ -11342,7 +11364,7 @@ function handleAgentQuestion(key, questionData) {
|
|
|
11342
11364
|
// liveness loop first so it can't recreate a frame under the question prompt
|
|
11343
11365
|
// (Claude-only; a no-op for OpenCode threads, which never arm it).
|
|
11344
11366
|
stopClaudeLiveness(key);
|
|
11345
|
-
|
|
11367
|
+
supersedeStatusFrames(key);
|
|
11346
11368
|
deleteStatusMessage(key).catch(() => { });
|
|
11347
11369
|
// The question UI takes over — remove any live thinking frame so it doesn't
|
|
11348
11370
|
// sit above the prompt (it would otherwise persist past the answer).
|
|
@@ -11353,9 +11375,10 @@ function handleAgentQuestion(key, questionData) {
|
|
|
11353
11375
|
// the live draft so its already-accumulated text lands as a permanent message
|
|
11354
11376
|
// above the prompt, not dropped; the finalize IS the persistence — no parallel
|
|
11355
11377
|
// 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
|
-
|
|
11378
|
+
// lands above the prompt rather than behind it, S2). Started HERE, so the text is
|
|
11379
|
+
// taken before anything else moves; the question is posted once it has landed (or
|
|
11380
|
+
// after `streamedOutputLandingLimitMs`). A fully-delivered turn is a no-op for both.
|
|
11381
|
+
const streamedOutputLanding = (0, streamedOutputLanding_1.landStreamedOutputWithinLimit)(() => landStreamedOutputOfThread(key), (0, sessionKey_1.keyToString)(key));
|
|
11359
11382
|
// The question UI replaces the "working" cue — stop the typing loader.
|
|
11360
11383
|
getOutboundFor(key).setActivity(key, 'idle');
|
|
11361
11384
|
// Audit S13 / #31: register the pending question BEFORE the async
|
|
@@ -11376,7 +11399,10 @@ function handleAgentQuestion(key, questionData) {
|
|
|
11376
11399
|
answers: new Array(questionData.questions.length).fill(null),
|
|
11377
11400
|
currentIndex: 0,
|
|
11378
11401
|
});
|
|
11379
|
-
void runQuestionLifecycleOp(key, () =>
|
|
11402
|
+
void runQuestionLifecycleOp(key, async () => {
|
|
11403
|
+
await streamedOutputLanding;
|
|
11404
|
+
await postPendingQuestionAt(key);
|
|
11405
|
+
});
|
|
11380
11406
|
}
|
|
11381
11407
|
/**
|
|
11382
11408
|
* @description Render + send ONE OpenCode question (the one at the pending
|
|
@@ -11439,11 +11465,13 @@ async function postPendingQuestionAt(key) {
|
|
|
11439
11465
|
? (0, questionKeyboards_1.buildQuestionOptionsKeyboard)(question, (optionIndex) => `qa_${qIdx}_${optionIndex}`)
|
|
11440
11466
|
: undefined;
|
|
11441
11467
|
try {
|
|
11442
|
-
let
|
|
11443
|
-
|
|
11444
|
-
|
|
11445
|
-
|
|
11468
|
+
let outcome = await replyToThreadDetailed(key, (0, openCodeQuestionFlow_1.buildQuestionBodyLines)(question, escapeMarkdown).join('\n'), (0, questionKeyboards_1.buildKeyboardExtra)(keyboard, { parse_mode: 'Markdown' }));
|
|
11469
|
+
// Markdown rejected — retry plain. Only a post that FAILED: one whose outcome is unknown may already be in the topic, and a
|
|
11470
|
+
// second copy of the question would be posted under it (its id stays unknown; its buttons still answer it).
|
|
11471
|
+
if (outcome.kind === 'failed') {
|
|
11472
|
+
outcome = await replyToThreadDetailed(key, (0, openCodeQuestionFlow_1.buildQuestionBodyLinesPlain)(question).join('\n'), (0, questionKeyboards_1.buildKeyboardExtra)(keyboard));
|
|
11446
11473
|
}
|
|
11474
|
+
const messageId = outcome.kind === 'sent' ? outcome.messageId : null;
|
|
11447
11475
|
if (messageId !== null) {
|
|
11448
11476
|
// Patch the messageId on the existing entry (it may already have been
|
|
11449
11477
|
// cleared/advanced by an answer callback firing in between). Route
|
|
@@ -11495,9 +11523,10 @@ function handleQuestionGone(key) {
|
|
|
11495
11523
|
function handleAgentClosed(key) {
|
|
11496
11524
|
// What the process held that died with it (its own background work), taken before the cleanup below.
|
|
11497
11525
|
const lostWork = takeLostWorkOf(key);
|
|
11498
|
-
// Session is gone —
|
|
11499
|
-
//
|
|
11500
|
-
//
|
|
11526
|
+
// Session is gone — the not-yet-sent output gets its ONE final attempt (a 429
|
|
11527
|
+
// drops what it keeps, nothing is retried after the stop), so the agent's last
|
|
11528
|
+
// words may still land just after the "session ended" notice; the pending status
|
|
11529
|
+
// frame is dropped.
|
|
11501
11530
|
clearThreadQueues(key);
|
|
11502
11531
|
// Session gone — stop the liveness loop so it can't recreate a frame after
|
|
11503
11532
|
// the close (it would otherwise outlive the session via its self-re-arm).
|
|
@@ -11569,10 +11598,16 @@ async function noteLostWork(key, lostWork, reason) {
|
|
|
11569
11598
|
reason,
|
|
11570
11599
|
isLimitWaitArmed,
|
|
11571
11600
|
msSinceLastAutoResume: lastAutoResumeAt === undefined ? null : now - lastAutoResumeAt,
|
|
11572
|
-
// A tracker issue's agent answers only through a request: a bare note would have nowhere to answer.
|
|
11601
|
+
// A tracker issue's agent answers only through a request: a bare note would have nowhere to answer — its open request is woken instead.
|
|
11573
11602
|
isRequestRequired: !(0, sessionKeyCodec_1.checkIsTelegramKey)(key),
|
|
11603
|
+
hasOpenRequest: (topicRequestLedger?.listOpenRequestsOf(key).length ?? 0) > 0,
|
|
11574
11604
|
});
|
|
11575
|
-
|
|
11605
|
+
let planText = plan.isAutoResume ? 'resuming it with a note' : 'the note rides the next prompt';
|
|
11606
|
+
if (plan.isRequestWake)
|
|
11607
|
+
planText = 'its open request is woken, and the note rides that wake';
|
|
11608
|
+
console.log(`[lost-work] ${kStr}: the process ended (${reason}) with the agent's own work pending (${record.backgroundTasks.length} background task(s), ${record.scheduledJobCount} scheduled job(s)${record.hasUnreadTaskResult ? ', an unread task result' : ''}${record.wasTurnInFlight ? ', a cut-off turn' : ''}); ${planText}`);
|
|
11609
|
+
if (plan.isRequestWake)
|
|
11610
|
+
scheduleTrackerRestartWake(key, `its process ended (${reason}) with its own work pending`);
|
|
11576
11611
|
let linePlan = plan;
|
|
11577
11612
|
if (plan.isAutoResume) {
|
|
11578
11613
|
await state.setLostWorkResumedAt(key, now);
|
|
@@ -11583,6 +11618,43 @@ async function noteLostWork(key, lostWork, reason) {
|
|
|
11583
11618
|
if ((0, sessionKeyCodec_1.checkIsTelegramKey)(key))
|
|
11584
11619
|
replyToThread(key, (0, lostWork_1.formatLostWorkTopicLine)(record, linePlan, pendingWorkHoldHours, i18n_1.t)).catch(() => { });
|
|
11585
11620
|
}
|
|
11621
|
+
/**
|
|
11622
|
+
* @description Wake the open requests of a tracker conversation whose process is gone — `restarted`, staggered by the
|
|
11623
|
+
* wake-up engine — instead of leaving them to the 90-minute backstop. A Telegram topic resumes through its own
|
|
11624
|
+
* lost-work path and is never woken here. The lost-work cooldown guards it as well: a conversation woken
|
|
11625
|
+
* automatically within it is left to the backstop, so a crash loop is no wake loop.
|
|
11626
|
+
*/
|
|
11627
|
+
function scheduleTrackerRestartWake(key, why) {
|
|
11628
|
+
if ((0, sessionKeyCodec_1.checkIsTelegramKey)(key) || !requestWakeUpEngine)
|
|
11629
|
+
return;
|
|
11630
|
+
const lastAutoResumeAt = state.getLostWorkResumedAt(key);
|
|
11631
|
+
if (lastAutoResumeAt !== undefined && Date.now() - lastAutoResumeAt < lostWork_1.lostWorkResumeCooldownMs) {
|
|
11632
|
+
console.log(`[requests] ${(0, sessionKey_1.keyToString)(key)}: ${why}; it was woken automatically less than ${lostWork_1.lostWorkResumeCooldownMs / 60_000} min ago, so the backstop takes it`);
|
|
11633
|
+
return;
|
|
11634
|
+
}
|
|
11635
|
+
if (requestWakeUpEngine.scheduleRestartWake(key))
|
|
11636
|
+
console.log(`[requests] ${(0, sessionKey_1.keyToString)(key)}: ${why}; its open request is woken shortly`);
|
|
11637
|
+
}
|
|
11638
|
+
/**
|
|
11639
|
+
* @description The boot's pass over the open requests of tracker conversations: one whose process did not come back
|
|
11640
|
+
* with the boot (not adopted — the conversation sleeps) and that waits for nothing of its own — no post retry, no
|
|
11641
|
+
* progress follow-up, no armed usage-limit wait, not given up — is woken `restarted` ({@link scheduleTrackerRestartWake}).
|
|
11642
|
+
* A process that died with its own work pending is in it too: its lost-work note rides the same wake.
|
|
11643
|
+
*/
|
|
11644
|
+
function scheduleRestartWakesAtBoot(requestLedger) {
|
|
11645
|
+
const keys = new Map();
|
|
11646
|
+
for (const { key, request } of requestLedger.listOpenRequests()) {
|
|
11647
|
+
if ((0, sessionKeyCodec_1.checkIsTelegramKey)(key) || keys.has((0, sessionKey_1.keyToString)(key)))
|
|
11648
|
+
continue;
|
|
11649
|
+
if ((0, wakeUpRules_1.checkIsWakingStopped)(request) || request.nextPostRetryAt !== undefined || request.nextWakeAt !== undefined)
|
|
11650
|
+
continue;
|
|
11651
|
+
if ((0, createAdapter_1.getThreadAdapter)(key).checkIsActive(key) || getArmedApiRetry(key)?.kind === 'usageLimit')
|
|
11652
|
+
continue;
|
|
11653
|
+
keys.set((0, sessionKey_1.keyToString)(key), key);
|
|
11654
|
+
}
|
|
11655
|
+
for (const key of keys.values())
|
|
11656
|
+
scheduleTrackerRestartWake(key, 'its session did not come back with the boot while a request was open');
|
|
11657
|
+
}
|
|
11586
11658
|
/**
|
|
11587
11659
|
* @description Resume the conversation with the lost-work note as its prompt; `false` when the post failed — the note
|
|
11588
11660
|
* then stays for the next prompt.
|
|
@@ -11604,14 +11676,35 @@ function createLostWorkPostDeps() {
|
|
|
11604
11676
|
return {
|
|
11605
11677
|
...createSessionPostDeps(),
|
|
11606
11678
|
forwardPrompt: async (conversationKey, text) => {
|
|
11607
|
-
|
|
11679
|
+
const buffered = createBufferedOutcome();
|
|
11680
|
+
const delivery = await deliverPromptOrBuffer((0, sessionKey_1.keyFromString)(conversationKey), text, startupPromptBuffer.checkIsStarting(conversationKey), buffered.settle);
|
|
11681
|
+
if (delivery === 'buffered')
|
|
11682
|
+
await buffered.assertReplayed();
|
|
11683
|
+
},
|
|
11684
|
+
};
|
|
11685
|
+
}
|
|
11686
|
+
/**
|
|
11687
|
+
* @description How a prompt that waited in the startup buffer ended, for a post that must know it reached the session:
|
|
11688
|
+
* `settle` is the buffer's callback, `assertReplayed` resolves once it was replayed into the session and rejects when it
|
|
11689
|
+
* was dropped — the start failed, or its write did not reach the agent.
|
|
11690
|
+
*/
|
|
11691
|
+
function createBufferedOutcome() {
|
|
11692
|
+
let settle = () => { };
|
|
11693
|
+
const outcome = new Promise((resolve) => {
|
|
11694
|
+
settle = resolve;
|
|
11695
|
+
});
|
|
11696
|
+
return {
|
|
11697
|
+
settle: (result) => settle(result),
|
|
11698
|
+
assertReplayed: async () => {
|
|
11699
|
+
if ((await outcome) !== 'replayed')
|
|
11700
|
+
throw new Error('the prompt waited for the session to start and never reached the agent');
|
|
11608
11701
|
},
|
|
11609
11702
|
};
|
|
11610
11703
|
}
|
|
11611
11704
|
function handleAgentError(key, error) {
|
|
11612
11705
|
console.error(`[Bot] adapter error ${(0, sessionKey_1.keyToString)(key)}:`, error.message);
|
|
11613
11706
|
stopClaudeLiveness(key);
|
|
11614
|
-
|
|
11707
|
+
supersedeStatusFrames(key);
|
|
11615
11708
|
deleteStatusMessage(key).catch(() => { });
|
|
11616
11709
|
clearThinkingMessage(key);
|
|
11617
11710
|
clearSubagentStatus(key);
|
|
@@ -11656,8 +11749,8 @@ function handleAgentStarted(key) {
|
|
|
11656
11749
|
/**
|
|
11657
11750
|
* @description The Telegram frames a process that is GONE leaves behind — shared
|
|
11658
11751
|
* by an explicit stop ({@link handleAgentStopped}) and the idle stop
|
|
11659
|
-
* ({@link handleAgentSuspended}).
|
|
11660
|
-
*
|
|
11752
|
+
* ({@link handleAgentSuspended}). Give the thread's queued-but-unsent output its ONE
|
|
11753
|
+
* final attempt ({@link clearThreadQueues}: never retried after the stop); stop the liveness loop and
|
|
11661
11754
|
* remove its frame (a gone process is idle, a lingering "working…" indicator would
|
|
11662
11755
|
* be a stuck spinner — the timer first, so it cannot recreate the frame right after
|
|
11663
11756
|
* the delete); the "thinking …" frame and the sub-agent status for the same reason;
|
|
@@ -12603,7 +12696,8 @@ const sendFilesToThread = (0, fileSendService_1.createSendFilesToThread)({
|
|
|
12603
12696
|
? { ok: true, target: key, workDir: decision.workDir }
|
|
12604
12697
|
: { ok: false, error: decision.message };
|
|
12605
12698
|
},
|
|
12606
|
-
|
|
12699
|
+
// An upload may take long by its size and bounds its wait for Telegram's answer itself (`fileSendGateway.ts`).
|
|
12700
|
+
executeDelivery: (key, delivery, signal) => (0, rateLimiter_1.enqueueSend)(key, delivery, signal, { hasOperationDeadline: false }),
|
|
12607
12701
|
gateway: (0, fileSendGateway_1.createTelegramFileSendGateway)({
|
|
12608
12702
|
sendPhoto: (key, input, caption, signal) => bot.telegram.callApi('sendPhoto', {
|
|
12609
12703
|
chat_id: (0, sessionKeyCodec_1.getTelegramChatId)(key),
|
|
@@ -12637,6 +12731,17 @@ const sendFilesToThread = (0, fileSendService_1.createSendFilesToThread)({
|
|
|
12637
12731
|
}),
|
|
12638
12732
|
recordMessageIds: (key, messageIds) => state.pushMessageIds(key, messageIds),
|
|
12639
12733
|
});
|
|
12734
|
+
/**
|
|
12735
|
+
* @description Land what the agent streamed before a call it just made — the text its backend still batches (or has written and
|
|
12736
|
+
* the bot has not read yet) and the output the topic still debounces or is sending — so what the call posts lands BELOW it.
|
|
12737
|
+
* The sender of `answer_request` and `send_messages_to_user` and the question path run it first.
|
|
12738
|
+
*/
|
|
12739
|
+
async function landStreamedOutputOfThread(key) {
|
|
12740
|
+
// 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
|
|
12741
|
+
// before that queue is landed.
|
|
12742
|
+
(0, createAdapter_1.getThreadAdapter)(key).flushPendingOutput?.(key);
|
|
12743
|
+
await getOutboundFor(key).finalize(key);
|
|
12744
|
+
}
|
|
12640
12745
|
/**
|
|
12641
12746
|
* Discrete-message sender behind `send_messages_to_user`. Each message is sent as
|
|
12642
12747
|
* its OWN permanent message through `replyChunkWithFallback` (HTML-first with a
|
|
@@ -12654,13 +12759,19 @@ const sendMessagesToThread = (0, messageSendService_1.createSendMessagesToThread
|
|
|
12654
12759
|
return { ok: false, error: `invalid threadKey "${threadKeyStr}"` };
|
|
12655
12760
|
}
|
|
12656
12761
|
},
|
|
12657
|
-
sendChunk: (key, chunk) =>
|
|
12762
|
+
sendChunk: async (key, chunk) => {
|
|
12763
|
+
const outcome = await replyChunkDetailed(key, (0, renderAgentHtml_1.renderAgentHtml)(chunk), chunk);
|
|
12764
|
+
if (outcome.kind === 'unknown')
|
|
12765
|
+
throw new messageSendService_1.MessageDeliveryUnknownError();
|
|
12766
|
+
return outcome.kind === 'sent' ? outcome.messageId : null;
|
|
12767
|
+
},
|
|
12658
12768
|
// Reuse the SAME secure file-send pipeline as `send_file_to_user` for an
|
|
12659
12769
|
// attachment item — no second pipeline, no duplicated path-safety.
|
|
12660
12770
|
sendFiles: sendFilesToThread,
|
|
12661
12771
|
splitMessage: messageSplit_1.splitMessage,
|
|
12662
12772
|
maxMessageLength: messageSplit_1.MAX_MESSAGE_LEN,
|
|
12663
12773
|
measureRendered: (chunk) => (0, renderAgentHtml_1.renderAgentHtml)(chunk).length,
|
|
12774
|
+
landStreamedOutput: landStreamedOutputOfThread,
|
|
12664
12775
|
});
|
|
12665
12776
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
12666
12777
|
// Requests — answer sinks and the wake-up engine's view of a session
|
|
@@ -12824,8 +12935,12 @@ function createSessionPostDeps() {
|
|
|
12824
12935
|
// A scheduled run in a topic with requests on is a request (S7); a tracker's
|
|
12825
12936
|
// post arrives with its request already open and its header in the text.
|
|
12826
12937
|
const opening = await openTopicRequest(key, text, { source: 'scheduledRun', requesterId: topicRequest_1.scheduledRunRequester });
|
|
12827
|
-
const
|
|
12938
|
+
const buffered = createBufferedOutcome();
|
|
12939
|
+
const delivery = await deliverPromptOrBuffer(key, `${opening.header}${text}`, startupPromptBuffer.checkIsStarting(conversationKey), buffered.settle);
|
|
12828
12940
|
await settleTopicRequestAfterDelivery(key, opening, delivery);
|
|
12941
|
+
// A prompt that waited for the session's start counts only once it reached it: a replay whose write failed is a failed post.
|
|
12942
|
+
if (delivery === 'buffered')
|
|
12943
|
+
await buffered.assertReplayed();
|
|
12829
12944
|
},
|
|
12830
12945
|
now: () => Date.now(),
|
|
12831
12946
|
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
@@ -13211,6 +13326,15 @@ function createJiraSessionDeps(requestLedger, slots, adapterName) {
|
|
|
13211
13326
|
if (!posted.isHeld)
|
|
13212
13327
|
await requestWakeUpEngine?.trackForwardedTurn(key, requestId, { isRequestPrompt: true });
|
|
13213
13328
|
},
|
|
13329
|
+
// An issue update (a comment for an open hand-over request) opens no request: the turn it starts is that request's.
|
|
13330
|
+
postUpdate: async (key, prompt, getTargetRequestId) => {
|
|
13331
|
+
notePersonActivity(key);
|
|
13332
|
+
const posted = await (0, postToSession_1.postToSession)(sessionPostDeps, (0, sessionKey_1.keyToString)(key), prompt, adapterName);
|
|
13333
|
+
if (!posted.ok)
|
|
13334
|
+
throw new Error(posted.reason === 'forward-failed' ? posted.error : `session ${posted.reason}`);
|
|
13335
|
+
if (!posted.isHeld)
|
|
13336
|
+
await requestWakeUpEngine?.trackForwardedTurn(key, getTargetRequestId());
|
|
13337
|
+
},
|
|
13214
13338
|
};
|
|
13215
13339
|
}
|
|
13216
13340
|
async function startBot() {
|
|
@@ -13319,6 +13443,11 @@ async function startBot() {
|
|
|
13319
13443
|
return result.ok ? (result.alertRef ?? null) : null;
|
|
13320
13444
|
},
|
|
13321
13445
|
backstopMs: (0, wakeUpRules_1.getRequestBackstopMs)(process.env.REQUEST_BACKSTOP_MINUTES),
|
|
13446
|
+
restartWakeStaggerMs: ENV.testTimings.requestRestartWakeStaggerMs,
|
|
13447
|
+
// The stamp of the lost-work cooldown: a conversation woken after a restart is not woken so again within it.
|
|
13448
|
+
noteRestartWakeDelivered: (key) => {
|
|
13449
|
+
void state.setLostWorkResumedAt(key, Date.now());
|
|
13450
|
+
},
|
|
13322
13451
|
pollIntervalMs: ENV.testTimings.requestTurnPollMs,
|
|
13323
13452
|
sweepIntervalMs: ENV.testTimings.requestSweepIntervalMs,
|
|
13324
13453
|
firstPostRetryDelayMs: ENV.testTimings.requestFirstPostRetryDelayMs,
|
|
@@ -13608,6 +13737,8 @@ async function startBot() {
|
|
|
13608
13737
|
markSessionsRestored();
|
|
13609
13738
|
// From here the engine can tell a live turn from a dead session.
|
|
13610
13739
|
requestWakeUpEngine?.start();
|
|
13740
|
+
// A tracker conversation whose process did not survive the downtime resumes its open request now, not at the backstop.
|
|
13741
|
+
scheduleRestartWakesAtBoot(requestLedger);
|
|
13611
13742
|
todoReminderEngine?.start();
|
|
13612
13743
|
jiraConnector?.start(createJiraSessionDeps(requestLedger, slots, jiraConnector.adapterName));
|
|
13613
13744
|
},
|
|
@@ -13632,9 +13763,11 @@ async function startBot() {
|
|
|
13632
13763
|
// and the CLI never retries a failed MCP server. Fire-and-forget.
|
|
13633
13764
|
healSchedulerMcpForActiveSessions();
|
|
13634
13765
|
},
|
|
13635
|
-
// Boot catch-up replay: arm every persisted job,
|
|
13766
|
+
// Boot catch-up replay: arm every persisted job, START one catch-up per
|
|
13636
13767
|
// missed run. Independent of the MCP server (delivery does not need it).
|
|
13637
|
-
|
|
13768
|
+
// It never waits for a delivery — one waits for its agent, which may wait for
|
|
13769
|
+
// an answer that only polling (started after this phase) can bring.
|
|
13770
|
+
rearmSchedules: () => schedulerEngine.rearmAll(),
|
|
13638
13771
|
});
|
|
13639
13772
|
// 5a. Refresh pinned banners for every binding. Threads that have a
|
|
13640
13773
|
// stored `pinnedStatusMessageId` get their banner edited in place;
|