charness 4.1.0 → 4.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +52 -0
- package/DEVELOPMENT.md +11 -5
- package/{COMMERCIAL-LICENSE.md → LICENSE-COMMERCIAL.md} +1 -1
- package/MIGRATION_3_TO_4.md +1 -1
- package/README.md +4 -1
- package/SETUP.md +37 -9
- package/agent-plugin/skills/charness-delegate-claude/SKILL.md +1 -0
- package/agent-plugin/skills/charness-orchestration/SKILL.md +1 -0
- package/dist/adapters/adapterNames.d.ts +2 -0
- package/dist/adapters/adapterNames.d.ts.map +1 -1
- package/dist/adapters/adapterNames.js +3 -1
- package/dist/adapters/adapterNames.js.map +1 -1
- package/dist/adapters/claudeJsonStreamAdapter.d.ts +74 -5
- package/dist/adapters/claudeJsonStreamAdapter.d.ts.map +1 -1
- package/dist/adapters/claudeJsonStreamAdapter.js +164 -20
- package/dist/adapters/claudeJsonStreamAdapter.js.map +1 -1
- package/dist/adapters/openCodeAdapter.d.ts +31 -2
- package/dist/adapters/openCodeAdapter.d.ts.map +1 -1
- package/dist/adapters/openCodeAdapter.js +84 -8
- package/dist/adapters/openCodeAdapter.js.map +1 -1
- package/dist/adapters/terminalAdapter.d.ts.map +1 -1
- package/dist/adapters/terminalAdapter.js +2 -1
- package/dist/adapters/terminalAdapter.js.map +1 -1
- package/dist/bot.d.ts.map +1 -1
- package/dist/bot.js +769 -118
- package/dist/bot.js.map +1 -1
- package/dist/cli/claudeProfiles.d.ts +3 -0
- package/dist/cli/claudeProfiles.d.ts.map +1 -1
- package/dist/cli/claudeProfiles.js +8 -0
- package/dist/cli/claudeProfiles.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/commands/botCore.d.ts +5 -2
- package/dist/connectors/telegram/commands/botCore.d.ts.map +1 -1
- package/dist/connectors/telegram/commands/claudeAccounts.d.ts +5 -0
- package/dist/connectors/telegram/commands/claudeAccounts.d.ts.map +1 -1
- package/dist/connectors/telegram/commands/claudeAccounts.js +15 -39
- package/dist/connectors/telegram/commands/claudeAccounts.js.map +1 -1
- package/dist/connectors/telegram/commands/compaction.d.ts +6 -0
- package/dist/connectors/telegram/commands/compaction.d.ts.map +1 -1
- package/dist/connectors/telegram/commands/compaction.js +8 -1
- package/dist/connectors/telegram/commands/compaction.js.map +1 -1
- package/dist/connectors/telegram/commands/questionSetAside.d.ts +111 -0
- package/dist/connectors/telegram/commands/questionSetAside.d.ts.map +1 -0
- package/dist/connectors/telegram/commands/questionSetAside.js +637 -0
- package/dist/connectors/telegram/commands/questionSetAside.js.map +1 -0
- package/dist/connectors/telegram/commands/questionWait.d.ts +21 -0
- package/dist/connectors/telegram/commands/questionWait.d.ts.map +1 -0
- package/dist/connectors/telegram/commands/questionWait.js +109 -0
- package/dist/connectors/telegram/commands/questionWait.js.map +1 -0
- package/dist/connectors/telegram/commands/runners.d.ts +28 -1
- package/dist/connectors/telegram/commands/runners.d.ts.map +1 -1
- package/dist/connectors/telegram/commands/runners.js +75 -40
- package/dist/connectors/telegram/commands/runners.js.map +1 -1
- package/dist/connectors/telegram/commands/topicAccess.js +1 -1
- package/dist/connectors/telegram/commands/topicAccess.js.map +1 -1
- package/dist/connectors/telegram/commands/topicCommand.d.ts +0 -2
- package/dist/connectors/telegram/commands/topicCommand.d.ts.map +1 -1
- package/dist/connectors/telegram/commands/topicCommand.js +4 -5
- package/dist/connectors/telegram/commands/topicCommand.js.map +1 -1
- package/dist/connectors/telegram/commands/topicStatus.d.ts +24 -0
- package/dist/connectors/telegram/commands/topicStatus.d.ts.map +1 -0
- package/dist/connectors/telegram/commands/topicStatus.js +148 -0
- package/dist/connectors/telegram/commands/topicStatus.js.map +1 -0
- package/dist/connectors/telegram/firstUpdateBatchNote.d.ts +30 -0
- package/dist/connectors/telegram/firstUpdateBatchNote.d.ts.map +1 -0
- package/dist/connectors/telegram/firstUpdateBatchNote.js +39 -0
- package/dist/connectors/telegram/firstUpdateBatchNote.js.map +1 -0
- package/dist/connectors/telegram/inbound.d.ts +12 -0
- package/dist/connectors/telegram/inbound.d.ts.map +1 -1
- package/dist/connectors/telegram/inbound.js +31 -3
- package/dist/connectors/telegram/inbound.js.map +1 -1
- package/dist/connectors/telegram/sendOutcome.d.ts +3 -1
- package/dist/connectors/telegram/sendOutcome.d.ts.map +1 -1
- package/dist/connectors/telegram/sendOutcome.js.map +1 -1
- package/dist/connectors/telegram/telegramFailureRetry.d.ts +8 -0
- package/dist/connectors/telegram/telegramFailureRetry.d.ts.map +1 -1
- package/dist/connectors/telegram/telegramFailureRetry.js +8 -0
- package/dist/connectors/telegram/telegramFailureRetry.js.map +1 -1
- package/dist/connectors/telegram/topicIndicator.d.ts +86 -0
- package/dist/connectors/telegram/topicIndicator.d.ts.map +1 -0
- package/dist/connectors/telegram/topicIndicator.js +490 -0
- package/dist/connectors/telegram/topicIndicator.js.map +1 -0
- package/dist/connectors/telegram/waitingTopicRenames.d.ts +39 -0
- package/dist/connectors/telegram/waitingTopicRenames.d.ts.map +1 -0
- package/dist/connectors/telegram/waitingTopicRenames.js +48 -0
- package/dist/connectors/telegram/waitingTopicRenames.js.map +1 -0
- package/dist/i18n/de.d.ts.map +1 -1
- package/dist/i18n/de.js +51 -0
- package/dist/i18n/de.js.map +1 -1
- package/dist/i18n/en.d.ts.map +1 -1
- package/dist/i18n/en.js +51 -0
- package/dist/i18n/en.js.map +1 -1
- package/dist/i18n/es.d.ts.map +1 -1
- package/dist/i18n/es.js +51 -0
- package/dist/i18n/es.js.map +1 -1
- package/dist/i18n/fr.d.ts.map +1 -1
- package/dist/i18n/fr.js +51 -0
- package/dist/i18n/fr.js.map +1 -1
- package/dist/i18n/hi.d.ts.map +1 -1
- package/dist/i18n/hi.js +51 -0
- package/dist/i18n/hi.js.map +1 -1
- package/dist/i18n/ja.d.ts.map +1 -1
- package/dist/i18n/ja.js +51 -0
- package/dist/i18n/ja.js.map +1 -1
- package/dist/i18n/ka.d.ts.map +1 -1
- package/dist/i18n/ka.js +51 -0
- package/dist/i18n/ka.js.map +1 -1
- package/dist/i18n/pt.d.ts.map +1 -1
- package/dist/i18n/pt.js +51 -0
- package/dist/i18n/pt.js.map +1 -1
- package/dist/i18n/ru.d.ts.map +1 -1
- package/dist/i18n/ru.js +51 -0
- package/dist/i18n/ru.js.map +1 -1
- package/dist/i18n/uk.d.ts.map +1 -1
- package/dist/i18n/uk.js +51 -0
- package/dist/i18n/uk.js.map +1 -1
- package/dist/i18n/uz.d.ts.map +1 -1
- package/dist/i18n/uz.js +51 -0
- package/dist/i18n/uz.js.map +1 -1
- package/dist/i18n/zh.d.ts.map +1 -1
- package/dist/i18n/zh.js +51 -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/instanceSettings.d.ts +19 -1
- package/dist/instanceSettings.d.ts.map +1 -1
- package/dist/instanceSettings.js +35 -2
- package/dist/instanceSettings.js.map +1 -1
- package/dist/openCodeOpenQuestion.d.ts +12 -4
- package/dist/openCodeOpenQuestion.d.ts.map +1 -1
- package/dist/openCodeOpenQuestion.js +16 -7
- package/dist/openCodeOpenQuestion.js.map +1 -1
- package/dist/openCodeQuestionFlow.d.ts +10 -2
- package/dist/openCodeQuestionFlow.d.ts.map +1 -1
- package/dist/openCodeQuestionFlow.js +27 -5
- package/dist/openCodeQuestionFlow.js.map +1 -1
- package/dist/postToSession.d.ts +9 -0
- package/dist/postToSession.d.ts.map +1 -1
- package/dist/postToSession.js +15 -2
- package/dist/postToSession.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/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/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/state.d.ts +98 -6
- package/dist/state.d.ts.map +1 -1
- package/dist/state.js +149 -7
- package/dist/state.js.map +1 -1
- package/dist/testTimings.d.ts +12 -3
- package/dist/testTimings.d.ts.map +1 -1
- package/dist/testTimings.js +23 -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/todos/registry.d.ts +2 -0
- package/dist/todos/registry.d.ts.map +1 -1
- package/dist/todos/registry.js +3 -1
- package/dist/todos/registry.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 +95 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/utils/claudeCompactHook.d.ts +3 -1
- package/dist/utils/claudeCompactHook.d.ts.map +1 -1
- package/dist/utils/claudeCompactHook.js +3 -1
- package/dist/utils/claudeCompactHook.js.map +1 -1
- package/dist/utils/claudeLimitSwitch.d.ts +1 -1
- package/dist/utils/claudeLimitSwitch.d.ts.map +1 -1
- package/dist/utils/claudeLimitSwitch.js +1 -1
- package/dist/utils/claudeLimitSwitch.js.map +1 -1
- package/dist/utils/claudeProfileSync.d.ts +88 -0
- package/dist/utils/claudeProfileSync.d.ts.map +1 -0
- package/dist/utils/claudeProfileSync.js +198 -0
- package/dist/utils/claudeProfileSync.js.map +1 -0
- package/dist/utils/claudeProfiles.d.ts +101 -6
- package/dist/utils/claudeProfiles.d.ts.map +1 -1
- package/dist/utils/claudeProfiles.js +288 -23
- package/dist/utils/claudeProfiles.js.map +1 -1
- package/dist/utils/claudeUsageRefresher.d.ts +8 -1
- package/dist/utils/claudeUsageRefresher.d.ts.map +1 -1
- package/dist/utils/claudeUsageRefresher.js +11 -1
- package/dist/utils/claudeUsageRefresher.js.map +1 -1
- package/dist/utils/cutButtonLabel.d.ts +7 -0
- package/dist/utils/cutButtonLabel.d.ts.map +1 -0
- package/dist/utils/cutButtonLabel.js +17 -0
- package/dist/utils/cutButtonLabel.js.map +1 -0
- 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/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/limitSwitchPlan.d.ts +44 -0
- package/dist/utils/limitSwitchPlan.d.ts.map +1 -0
- package/dist/utils/limitSwitchPlan.js +54 -0
- package/dist/utils/limitSwitchPlan.js.map +1 -0
- 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/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/questionWaitChoices.d.ts +20 -0
- package/dist/utils/questionWaitChoices.d.ts.map +1 -0
- package/dist/utils/questionWaitChoices.js +31 -0
- package/dist/utils/questionWaitChoices.js.map +1 -0
- package/dist/utils/questionWaitPlan.d.ts +166 -0
- package/dist/utils/questionWaitPlan.d.ts.map +1 -0
- package/dist/utils/questionWaitPlan.js +237 -0
- package/dist/utils/questionWaitPlan.js.map +1 -0
- package/dist/utils/replyQuote.d.ts +10 -0
- package/dist/utils/replyQuote.d.ts.map +1 -1
- package/dist/utils/replyQuote.js +18 -7
- package/dist/utils/replyQuote.js.map +1 -1
- package/dist/utils/talkerAccess.d.ts +2 -2
- package/dist/utils/talkerAccess.d.ts.map +1 -1
- package/dist/utils/talkerAccess.js +5 -4
- package/dist/utils/talkerAccess.js.map +1 -1
- package/dist/utils/telegramError.d.ts +6 -0
- package/dist/utils/telegramError.d.ts.map +1 -1
- package/dist/utils/telegramError.js +12 -0
- package/dist/utils/telegramError.js.map +1 -1
- package/dist/utils/topicAccessScreenPlan.d.ts +1 -1
- package/dist/utils/topicAccessScreenPlan.d.ts.map +1 -1
- package/dist/utils/topicAccessScreenPlan.js +3 -7
- package/dist/utils/topicAccessScreenPlan.js.map +1 -1
- package/dist/utils/topicIndicatorPlan.d.ts +143 -0
- package/dist/utils/topicIndicatorPlan.d.ts.map +1 -0
- package/dist/utils/topicIndicatorPlan.js +202 -0
- package/dist/utils/topicIndicatorPlan.js.map +1 -0
- package/dist/utils/topicIndicatorSources.d.ts +40 -0
- package/dist/utils/topicIndicatorSources.d.ts.map +1 -0
- package/dist/utils/topicIndicatorSources.js +31 -0
- package/dist/utils/topicIndicatorSources.js.map +1 -0
- package/dist/utils/topicStatusPlan.d.ts +90 -0
- package/dist/utils/topicStatusPlan.d.ts.map +1 -0
- package/dist/utils/topicStatusPlan.js +160 -0
- package/dist/utils/topicStatusPlan.js.map +1 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +2 -2
package/dist/bot.js
CHANGED
|
@@ -69,6 +69,13 @@ const openCodeAdapter_1 = require("./adapters/openCodeAdapter");
|
|
|
69
69
|
const terminalAdapter_1 = require("./adapters/terminalAdapter");
|
|
70
70
|
const openCodeQuestionFlow_1 = require("./openCodeQuestionFlow");
|
|
71
71
|
const pendingQuestionRepost_1 = require("./pendingQuestionRepost");
|
|
72
|
+
const questionSetAside_1 = require("./connectors/telegram/commands/questionSetAside");
|
|
73
|
+
const questionWaitPlan_1 = require("./utils/questionWaitPlan");
|
|
74
|
+
const topicIndicatorPlan_1 = require("./utils/topicIndicatorPlan");
|
|
75
|
+
const topicIndicator_1 = require("./connectors/telegram/topicIndicator");
|
|
76
|
+
const firstUpdateBatchNote_1 = require("./connectors/telegram/firstUpdateBatchNote");
|
|
77
|
+
const waitingTopicRenames_1 = require("./connectors/telegram/waitingTopicRenames");
|
|
78
|
+
const topicIndicatorSources_1 = require("./utils/topicIndicatorSources");
|
|
72
79
|
const rateLimiter_1 = require("./rateLimiter");
|
|
73
80
|
const testTimings_1 = require("./testTimings");
|
|
74
81
|
const installManager_1 = require("./installManager");
|
|
@@ -258,6 +265,8 @@ const callbackToast_2 = require("./connectors/telegram/commands/callbackToast");
|
|
|
258
265
|
const compaction_1 = require("./connectors/telegram/commands/compaction");
|
|
259
266
|
const autoContinueLimits_1 = require("./connectors/telegram/commands/autoContinueLimits");
|
|
260
267
|
const botSkills_2 = require("./connectors/telegram/commands/botSkills");
|
|
268
|
+
const questionWait_1 = require("./connectors/telegram/commands/questionWait");
|
|
269
|
+
const topicStatus_1 = require("./connectors/telegram/commands/topicStatus");
|
|
261
270
|
const topicAccess_1 = require("./connectors/telegram/commands/topicAccess");
|
|
262
271
|
const taskAgents_1 = require("./connectors/telegram/commands/taskAgents");
|
|
263
272
|
const runners_1 = require("./connectors/telegram/commands/runners");
|
|
@@ -273,9 +282,11 @@ const claudeAccounts_1 = require("./connectors/telegram/commands/claudeAccounts"
|
|
|
273
282
|
const claudeProfiles_1 = require("./utils/claudeProfiles");
|
|
274
283
|
const claudeUsage_1 = require("./utils/claudeUsage");
|
|
275
284
|
const claudeUsageRefresher_1 = require("./utils/claudeUsageRefresher");
|
|
285
|
+
const claudeProfileSync_1 = require("./utils/claudeProfileSync");
|
|
276
286
|
const openCodeUsage_1 = require("./utils/openCodeUsage");
|
|
277
287
|
const usageRefreshBudget_1 = require("./utils/usageRefreshBudget");
|
|
278
288
|
const claudeLimitSwitch_1 = require("./utils/claudeLimitSwitch");
|
|
289
|
+
const limitSwitchPlan_1 = require("./utils/limitSwitchPlan");
|
|
279
290
|
const anthropicApiKeyCheck_1 = require("./utils/anthropicApiKeyCheck");
|
|
280
291
|
const claudeApiKeyHelper_1 = require("./utils/claudeApiKeyHelper");
|
|
281
292
|
const fallbackSwitchNotice_1 = require("./utils/fallbackSwitchNotice");
|
|
@@ -420,6 +431,7 @@ if (ENV.testTimings.backgroundHoldMaxMs !== undefined)
|
|
|
420
431
|
(0, createAdapter_1.registerPendingWorkHoldMs)(ENV.testTimings.backgroundHoldMaxMs);
|
|
421
432
|
if (ENV.testTimings.scheduleMinFireIntervalMs !== undefined)
|
|
422
433
|
(0, recurrence_1.registerMinFireIntervalMs)(ENV.testTimings.scheduleMinFireIntervalMs);
|
|
434
|
+
(0, postToSession_1.registerPostWaitWindows)({ busyPollMs: ENV.testTimings.postBusyPollMs, waitForIdleMs: ENV.testTimings.postWaitForIdleMs });
|
|
423
435
|
/** The short retry that probes an unconfirmed usage limit (a test instance may shorten it). */
|
|
424
436
|
const limitProbeDelayMs = ENV.testTimings.limitProbeDelayMs ?? apiErrorRetry_1.unconfirmedLimitProbeDelayMs;
|
|
425
437
|
// The instance default effort (`/effort` in General) is `settings.json`'s `defaultEffort`, re-read when the file changes.
|
|
@@ -486,9 +498,12 @@ function checkIsDmKey(key) {
|
|
|
486
498
|
* chat type and identifies the owner. False when the DM surface is inert.
|
|
487
499
|
*/
|
|
488
500
|
function checkIsDmChat(ctx) {
|
|
501
|
+
return checkIsOwnerDm(ctx.chat);
|
|
502
|
+
}
|
|
503
|
+
/** @description Whether `chat` is the owner's private chat on a surface that serves it. */
|
|
504
|
+
function checkIsOwnerDm(chat) {
|
|
489
505
|
if (!checkIsDmSurfaceActive())
|
|
490
506
|
return false;
|
|
491
|
-
const chat = ctx.chat;
|
|
492
507
|
if (!chat || chat.type !== 'private')
|
|
493
508
|
return false;
|
|
494
509
|
return chat.id === getOwnerUserId();
|
|
@@ -549,6 +564,9 @@ process.on('exit', outputTrace_1.flushTraceBufferSyncOnExit);
|
|
|
549
564
|
// connection the server had closed. AFTER the trace wrap, so the trace records both real HTTP attempts, and below the
|
|
550
565
|
// send queue, pacer and 429 retry. Telegraf builds a NEW client per update: see the first `bot.use` below.
|
|
551
566
|
(0, botApiConnection_1.wireBotApiClient)(bot.telegram, telegramApiAgent);
|
|
567
|
+
// The first answered long poll: the updates that waited while the bot was down are in its hands from then on — the boot wave of the topic
|
|
568
|
+
// status marks waits for it and for the dispatcher to be idle, so an owner's rename made during the downtime is learned before the wave writes.
|
|
569
|
+
const firstUpdateBatch = (0, firstUpdateBatchNote_1.installFirstUpdateBatchNote)(bot.telegram);
|
|
552
570
|
// Default every text message/edit to NO link preview: a bare URL in agent
|
|
553
571
|
// output otherwise expanded into a large preview card, one per message, in the
|
|
554
572
|
// muted topic (operator complaint 2026-09-07). Installed OUTSIDE the trace wrap
|
|
@@ -657,10 +675,13 @@ const seenGroupSenders = (0, topicTalkerMemory_1.createSeenSenders)();
|
|
|
657
675
|
* group with the owner id would lock out the group's real admins.
|
|
658
676
|
*/
|
|
659
677
|
async function checkIsAllowedUser(ctx) {
|
|
660
|
-
|
|
678
|
+
return checkIsAllowedSender(checkIsDmChat(ctx), ctx.from?.id);
|
|
679
|
+
}
|
|
680
|
+
/** @description {@link checkIsAllowedUser} for a sender read off a raw update (no `ctx`): `isDmChat` says which surface decides. */
|
|
681
|
+
async function checkIsAllowedSender(isDmChat, userId) {
|
|
661
682
|
if (!userId)
|
|
662
683
|
return false;
|
|
663
|
-
if (
|
|
684
|
+
if (isDmChat) {
|
|
664
685
|
return userId === getOwnerUserId();
|
|
665
686
|
}
|
|
666
687
|
const adminIds = await adminCache.getAdminIds();
|
|
@@ -792,6 +813,17 @@ bot.use(async (ctx, next) => {
|
|
|
792
813
|
}
|
|
793
814
|
return next();
|
|
794
815
|
});
|
|
816
|
+
// The name a topic was created with rides on the root message a client attaches to the owner's plain messages: kept as a candidate for
|
|
817
|
+
// the topic's name while the bot does not know it (it is offered to the owner, never applied by itself).
|
|
818
|
+
bot.use(async (ctx, next) => {
|
|
819
|
+
try {
|
|
820
|
+
await noteTopicNameCandidate(ctx);
|
|
821
|
+
}
|
|
822
|
+
catch (e) {
|
|
823
|
+
console.warn('[topic-name] noting the creation name of a topic failed:', e instanceof Error ? e.message : e);
|
|
824
|
+
}
|
|
825
|
+
return next();
|
|
826
|
+
});
|
|
795
827
|
// Default-deny for talkers on buttons: a person an admin let talk to the agent here may tap only the agent's own question
|
|
796
828
|
// buttons (`checkIsTalkerCallback`). Every other tap is refused with one toast, here, so no handler or module has to know a
|
|
797
829
|
// talker exists — each of them keeps asking the admin gate.
|
|
@@ -1011,7 +1043,7 @@ function getDataDir() {
|
|
|
1011
1043
|
/** The shared todo registry (`todos/`), built on first use: its store lives in `DATA_DIR`, known once the state is. */
|
|
1012
1044
|
let todoRegistry = null;
|
|
1013
1045
|
function getTodoRegistry() {
|
|
1014
|
-
todoRegistry ??= (0, registry_1.createTodoRegistry)({ store: new store_1.TodoStore(getDataDir()), getNowMs: Date.now });
|
|
1046
|
+
todoRegistry ??= (0, registry_1.createTodoRegistry)({ store: new store_1.TodoStore(getDataDir()), getNowMs: Date.now, onItemsChanged: (key) => topicIndicator.requestRefresh(key) });
|
|
1015
1047
|
return todoRegistry;
|
|
1016
1048
|
}
|
|
1017
1049
|
/**
|
|
@@ -1291,29 +1323,51 @@ const identicalOutputGuard = (0, identicalOutputGuard_1.createIdenticalOutputGua
|
|
|
1291
1323
|
*/
|
|
1292
1324
|
function setPendingQuestion(key, value) {
|
|
1293
1325
|
pendingQuestions.set((0, sessionKey_1.keyToString)(key), value);
|
|
1326
|
+
topicIndicator.requestRefresh(key);
|
|
1294
1327
|
state.setPendingQuestion(key, value).catch(e => console.error('[pendingQuestion] persist failed:', e));
|
|
1295
1328
|
}
|
|
1296
1329
|
/**
|
|
1297
|
-
* @description
|
|
1298
|
-
*
|
|
1299
|
-
*
|
|
1330
|
+
* @description The ONE place a thread's pending interactive question is removed: from the in-memory map, the persisted store
|
|
1331
|
+
* and the re-post and set-aside-timer bookkeeping, so memory and disk stay in lockstep. Everything it does is STARTED in the
|
|
1332
|
+
* same tick, in order — the saved-state clear and the pin step queue behind whatever else touches them — so a question the
|
|
1333
|
+
* agent asks right after cannot be wiped by a removal that is still finishing: its own writes queue after this one's.
|
|
1334
|
+
*
|
|
1335
|
+
* `isPinKept`: the bot SET the question aside, so its pin stays — it belongs to the set-aside record now. The map entry that
|
|
1336
|
+
* tracks «the pinned question» is dropped WITHOUT unpinning, so the pin of the question the agent asks next neither retires it
|
|
1337
|
+
* nor counts as a re-pin (which is silent); taken under the pin lock, after any pin of this question still in flight. Otherwise
|
|
1338
|
+
* the pin is released. Resolves once the saved state and the pin step are done.
|
|
1300
1339
|
*/
|
|
1301
|
-
function
|
|
1340
|
+
function dropPendingQuestion(key, options) {
|
|
1302
1341
|
const kStr = (0, sessionKey_1.keyToString)(key);
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1342
|
+
let pinStep;
|
|
1343
|
+
if (options.isPinKept) {
|
|
1344
|
+
pinStep = questionPinLock.withLock(kStr, async () => {
|
|
1345
|
+
questionPinnedMessageId.delete(kStr);
|
|
1346
|
+
});
|
|
1347
|
+
}
|
|
1348
|
+
else {
|
|
1349
|
+
// Post-restart OpenCode: the in-memory pin map was lost on restart but the
|
|
1350
|
+
// question message is still pinned on Telegram (its id lives on the persisted
|
|
1351
|
+
// `pendingQuestions` entry). Seed the map from it so the unpin below finds the
|
|
1352
|
+
// id — deterministic, with no reliance on sync execution order against the
|
|
1353
|
+
// `delete` that follows. The live case is a no-op (the map already holds the
|
|
1354
|
+
// id; `has` is true).
|
|
1355
|
+
const pending = pendingQuestions.get(kStr);
|
|
1356
|
+
if (pending?.messageId != null && !questionPinnedMessageId.has(kStr)) {
|
|
1357
|
+
questionPinnedMessageId.set(kStr, pending.messageId);
|
|
1358
|
+
}
|
|
1359
|
+
pinStep = unpinThreadQuestion(key);
|
|
1312
1360
|
}
|
|
1313
|
-
void unpinThreadQuestion(key);
|
|
1314
1361
|
pendingQuestions.delete(kStr);
|
|
1315
|
-
|
|
1362
|
+
topicIndicator.requestRefresh(key);
|
|
1363
|
+
const savedStateStep = state.clearPendingQuestion(key).catch(e => console.error('[pendingQuestion] clear failed:', e));
|
|
1316
1364
|
clearQuestionRepostState(key);
|
|
1365
|
+
clearQuestionSetAsideTimer(key);
|
|
1366
|
+
return Promise.all([pinStep, savedStateStep]).then(() => undefined);
|
|
1367
|
+
}
|
|
1368
|
+
/** @description Drop a thread's pending question and release its pin ({@link dropPendingQuestion}); not awaited. */
|
|
1369
|
+
function clearPendingQuestion(key) {
|
|
1370
|
+
void dropPendingQuestion(key, { isPinKept: false });
|
|
1317
1371
|
}
|
|
1318
1372
|
const questionRepostStates = new Map();
|
|
1319
1373
|
/**
|
|
@@ -1455,33 +1509,39 @@ const questionClosingNoteKeys = {
|
|
|
1455
1509
|
askedAgain: 'agent.question_asked_again_note',
|
|
1456
1510
|
};
|
|
1457
1511
|
/**
|
|
1458
|
-
* @description
|
|
1459
|
-
*
|
|
1460
|
-
*
|
|
1512
|
+
* @description Put a note under a question's message in the topic WITHOUT deleting it or re-posting it: the header, the question
|
|
1513
|
+
* and its options stay, so what the agent asked can still be read, and `note` says what became of it. Without `keyboard` the
|
|
1514
|
+
* buttons are taken off (a question that ended — every way one ends goes through this, a delete would take the record away);
|
|
1515
|
+
* with `keyboard` they are replaced by it (a question the bot set aside keeps option buttons, which now name its record).
|
|
1516
|
+
* Resolves whether the text edit landed.
|
|
1461
1517
|
*
|
|
1462
1518
|
* Telegram that cannot parse the Markdown render gets the plain one (no escape marks shown), and a question too long for
|
|
1463
|
-
* the note gets a shortened plain one. An edit that
|
|
1464
|
-
*
|
|
1519
|
+
* the note gets a shortened plain one. An edit that fails (the message gone, say) leaves the old text — and with it the buttons
|
|
1520
|
+
* of a question that is NO LONGER the one waiting here, which would answer whatever the agent asks next: they are replaced by
|
|
1521
|
+
* `keyboard`, or taken off when there is none or that edit fails too.
|
|
1465
1522
|
*/
|
|
1466
|
-
async function
|
|
1523
|
+
async function editQuestionMessageWithNote(key, messageId, question, note, keyboard) {
|
|
1467
1524
|
const markdownText = (0, openCodeQuestionFlow_1.buildClosedQuestionText)(question, note, escapeMarkdown);
|
|
1468
1525
|
const plainText = (0, openCodeQuestionFlow_1.buildClosedQuestionPlainText)(question, note, messageSplit_1.MAX_MESSAGE_LEN);
|
|
1469
1526
|
// A question that filled a message when it was asked has no room for the note under it, and Telegram refuses the text:
|
|
1470
1527
|
// the note is the result, so the body gives way (descriptions first) and goes out as plain text, which cutting cannot break.
|
|
1471
1528
|
const isEdited = markdownText.length <= messageSplit_1.MAX_MESSAGE_LEN
|
|
1472
|
-
? await editThreadMessage(key, messageId, markdownText, { parse_mode: 'Markdown' }, plainText)
|
|
1473
|
-
: await editThreadMessage(key, messageId, plainText);
|
|
1474
|
-
if (
|
|
1475
|
-
|
|
1476
|
-
|
|
1529
|
+
? await editThreadMessage(key, messageId, markdownText, (0, questionKeyboards_1.buildKeyboardExtra)(keyboard, { parse_mode: 'Markdown' }), plainText)
|
|
1530
|
+
: await editThreadMessage(key, messageId, plainText, (0, questionKeyboards_1.buildKeyboardExtra)(keyboard));
|
|
1531
|
+
if (isEdited)
|
|
1532
|
+
return true;
|
|
1533
|
+
const isKeyboardReplaced = keyboard !== undefined && await editThreadKeyboard(key, messageId, keyboard, 'questionNote');
|
|
1534
|
+
if (!isKeyboardReplaced)
|
|
1535
|
+
await editThreadKeyboard(key, messageId, null, 'questionNote');
|
|
1536
|
+
return false;
|
|
1477
1537
|
}
|
|
1478
1538
|
/**
|
|
1479
|
-
* {@link
|
|
1539
|
+
* {@link editQuestionMessageWithNote} for a question that ended some way ({@link QuestionEnd}). The note speaks the topic's
|
|
1480
1540
|
* language whatever called it — a boot or a session teardown runs in no request, so no locale is set by one.
|
|
1481
1541
|
*/
|
|
1482
1542
|
async function closeQuestionMessage(key, messageId, question, ending) {
|
|
1483
1543
|
const note = withThreadLocale(key, () => (typeof ending === 'string' ? (0, i18n_1.t)(questionClosingNoteKeys[ending]) : (0, i18n_1.t)('agent.question_answered_note', { answer: ending.answer })));
|
|
1484
|
-
return
|
|
1544
|
+
return editQuestionMessageWithNote(key, messageId, question, note);
|
|
1485
1545
|
}
|
|
1486
1546
|
/**
|
|
1487
1547
|
* @description End a question message the bot holds no record of — a copy a restart left while its re-ask was being sent, an
|
|
@@ -1613,6 +1673,7 @@ function handleApiError(key, cls, options = {}) {
|
|
|
1613
1673
|
if (cls.kind === 'usageLimit' && !state.checkIsAutoContinueOnLimitEnabled(key)) {
|
|
1614
1674
|
const isFirstOffNotice = !autoContinueOffNoticedThreads.has(k);
|
|
1615
1675
|
autoContinueOffNoticedThreads.add(k);
|
|
1676
|
+
topicIndicator.requestRefresh(key);
|
|
1616
1677
|
// Each repeat is offered to the open request: the dedup is per request, so one
|
|
1617
1678
|
// opened after the first notice still hears about the limit (and is stopped).
|
|
1618
1679
|
const wait = { kind: 'autoResumeOff' };
|
|
@@ -1700,6 +1761,7 @@ function armApiRetryTimer(key, arming) {
|
|
|
1700
1761
|
// S3: the notice landed below any pending question — bring it back to the
|
|
1701
1762
|
// bottom (debounced; no-op when no question is pending).
|
|
1702
1763
|
onThreadActivityWhileQuestionPending(key);
|
|
1764
|
+
topicIndicator.requestRefresh(key);
|
|
1703
1765
|
void state
|
|
1704
1766
|
.setApiRetry(key, { kind: arming.kind, attempt: arming.attempt, fireAt: arming.fireAt, ...(arming.isLimitProbe ? { isLimitProbe: true } : {}), ...(arming.resumeOn ? { resumeOn: arming.resumeOn } : {}) })
|
|
1705
1767
|
.catch(e => console.error('[apiRetry] persist failed:', e));
|
|
@@ -1805,7 +1867,13 @@ function holdPromptForLimitResume(key, text, heldText) {
|
|
|
1805
1867
|
* relentlessly.
|
|
1806
1868
|
*/
|
|
1807
1869
|
async function fireApiRetry(key) {
|
|
1808
|
-
|
|
1870
|
+
try {
|
|
1871
|
+
return await withThreadLocale(key, () => (0, apiRetryKick_1.runApiRetryKick)(apiRetryKickDeps, key));
|
|
1872
|
+
}
|
|
1873
|
+
finally {
|
|
1874
|
+
// The wait is no longer armed (the entry stays in memory, its timer is gone): the topic is no longer stuck on it.
|
|
1875
|
+
topicIndicator.requestRefresh(key);
|
|
1876
|
+
}
|
|
1809
1877
|
}
|
|
1810
1878
|
/**
|
|
1811
1879
|
* The ports of the retry kick (`apiRetryKick.ts`): the bot's own retry map and
|
|
@@ -1843,7 +1911,7 @@ const apiRetryKickDeps = {
|
|
|
1843
1911
|
const from = getTopicFallbackPosition(key);
|
|
1844
1912
|
if (from !== null && (0, fallbackChain_1.checkIsSameFallbackAccount)(from, rung))
|
|
1845
1913
|
return false; // already there
|
|
1846
|
-
const outcome = await switchTopicToFallbackEntry(key, from, rung, { isAnnounced: true });
|
|
1914
|
+
const outcome = await switchTopicToFallbackEntry(key, from, rung, { isAnnounced: true, isAutomatic: true });
|
|
1847
1915
|
return outcome.isSwitched;
|
|
1848
1916
|
},
|
|
1849
1917
|
clearSavedRetry: clearSavedApiRetry,
|
|
@@ -1891,7 +1959,7 @@ async function announceUsageLimitOrSwitch(key, cls, episodeId, initialWait, atte
|
|
|
1891
1959
|
}
|
|
1892
1960
|
if (plan.action === 'auto') {
|
|
1893
1961
|
const to = plan.to;
|
|
1894
|
-
const outcome = await switchTopicToFallbackEntry(key, plan.from, to, { isAnnounced: true }).catch((e) => {
|
|
1962
|
+
const outcome = await switchTopicToFallbackEntry(key, plan.from, to, { isAnnounced: true, isAutomatic: true }).catch((e) => {
|
|
1895
1963
|
console.warn(`[fallback] ${(0, sessionKey_1.keyToString)(key)}: the auto-switch to ${formatFallbackEntry(to)} failed:`, e instanceof Error ? e.message : e);
|
|
1896
1964
|
return { isSwitched: false };
|
|
1897
1965
|
});
|
|
@@ -1955,6 +2023,7 @@ async function handleBalanceExhausted(key, cls) {
|
|
|
1955
2023
|
return;
|
|
1956
2024
|
}
|
|
1957
2025
|
balanceExhaustedNoticedThreads.add(k);
|
|
2026
|
+
topicIndicator.requestRefresh(key);
|
|
1958
2027
|
const episodeId = Date.now();
|
|
1959
2028
|
let plan = { action: 'none', from: position, earliest: null };
|
|
1960
2029
|
try {
|
|
@@ -1965,8 +2034,9 @@ async function handleBalanceExhausted(key, cls) {
|
|
|
1965
2034
|
}
|
|
1966
2035
|
if (plan.action === 'auto') {
|
|
1967
2036
|
const to = plan.to;
|
|
1968
|
-
|
|
1969
|
-
|
|
2037
|
+
if ((0, sessionKeyCodec_1.checkIsTelegramKey)(key))
|
|
2038
|
+
await replyToThread(key, notice);
|
|
2039
|
+
const outcome = await switchTopicToFallbackEntry(key, plan.from, to, { isAnnounced: true, isAutomatic: true }).catch((e) => {
|
|
1970
2040
|
console.warn(`[fallback] ${k}: the auto-switch to ${formatFallbackEntry(to)} failed:`, e instanceof Error ? e.message : e);
|
|
1971
2041
|
return { isSwitched: false };
|
|
1972
2042
|
});
|
|
@@ -2093,6 +2163,7 @@ function cancelApiRetry(key) {
|
|
|
2093
2163
|
autoContinueOffNoticedThreads.delete(k);
|
|
2094
2164
|
balanceExhaustedNoticedThreads.delete(k);
|
|
2095
2165
|
fallbackSwitchOffers.delete(k);
|
|
2166
|
+
topicIndicator.requestRefresh(key);
|
|
2096
2167
|
// NOTE: intentionally does NOT touch the logged-out notice. `cancelApiRetry`
|
|
2097
2168
|
// fires on EVERY inbound message (user takeover); clearing the auth notice here
|
|
2098
2169
|
// would drop the one-notice guard so the user's next prompt (into the STILL
|
|
@@ -2200,6 +2271,7 @@ async function handleNoResponseWithLocale(key) {
|
|
|
2200
2271
|
async function surfaceLoggedOutNotice(key) {
|
|
2201
2272
|
const messageKey = (0, createAdapter_1.getThreadAdapterNameRaw)(key) === adapterNames_1.openCodeAdapterName ? 'apiRetry.loggedOutOpenCode' : 'apiRetry.loggedOutClaude';
|
|
2202
2273
|
await (0, pinnedNoticeSlot_1.surfacePinnedNotice)(authNoticePinnedMessageId, (0, sessionKey_1.keyToString)(key), getPinnedNoticePorts(key, (0, i18n_1.t)(messageKey)));
|
|
2274
|
+
topicIndicator.requestRefresh(key);
|
|
2203
2275
|
}
|
|
2204
2276
|
/** @description The post and the notifying pin of a pinned notice of `key`'s topic ({@link surfacePinnedNotice}). */
|
|
2205
2277
|
function getPinnedNoticePorts(key, text) {
|
|
@@ -2222,6 +2294,7 @@ function clearAuthNotice(key) {
|
|
|
2222
2294
|
const pinnedId = (0, pinnedNoticeSlot_1.releasePinnedNoticeSlot)(authNoticePinnedMessageId, (0, sessionKey_1.keyToString)(key));
|
|
2223
2295
|
if (pinnedId !== null)
|
|
2224
2296
|
void unpinMessageQuiet(key, pinnedId);
|
|
2297
|
+
topicIndicator.requestRefresh(key);
|
|
2225
2298
|
}
|
|
2226
2299
|
/**
|
|
2227
2300
|
* @description Announce that a usage/session-limit window reset and work is moving
|
|
@@ -2592,6 +2665,10 @@ function getThreadKey(ctx) {
|
|
|
2592
2665
|
}
|
|
2593
2666
|
: undefined,
|
|
2594
2667
|
};
|
|
2668
|
+
return getThreadKeyForRoute(routeInput);
|
|
2669
|
+
}
|
|
2670
|
+
/** @description The thread key of a route, under the instance's surface settings — for a `ctx` and for a raw update alike. */
|
|
2671
|
+
function getThreadKeyForRoute(routeInput) {
|
|
2595
2672
|
return (0, threadRouting_1.resolveThreadKeyForMode)(routeInput, {
|
|
2596
2673
|
mode: getChatMode(),
|
|
2597
2674
|
ownerUserId: getOwnerUserId(),
|
|
@@ -2730,6 +2807,21 @@ async function authoriseContext(ctx) {
|
|
|
2730
2807
|
noteGroupTitle(ctx, key);
|
|
2731
2808
|
return key;
|
|
2732
2809
|
}
|
|
2810
|
+
/**
|
|
2811
|
+
* @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
|
|
2812
|
+
* 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
|
|
2813
|
+
* (`authoriseContext` refuses it). A group admin tapping in a chat that is theirs gets that chat's key (`getOwnPrivateChatKey`); every
|
|
2814
|
+
* other tap — the group, the owner's DM — takes the usual admin gate. The key, or `null` when refused.
|
|
2815
|
+
*/
|
|
2816
|
+
async function authorisePairingTap(ctx) {
|
|
2817
|
+
if (ctx.chat?.type === 'private' && !checkIsDmChat(ctx)) {
|
|
2818
|
+
const key = (0, threadRouting_1.getOwnPrivateChatKey)({ chatType: ctx.chat.type, chatId: ctx.chat.id, userId: ctx.from?.id, adminIds: await adminCache.getAdminIds() });
|
|
2819
|
+
if (key === null)
|
|
2820
|
+
console.warn(`[security] ignored update from chat ${ctx.chat.id} user ${ctx.from?.id ?? '?'} (not a group admin in their own private chat)`);
|
|
2821
|
+
return key;
|
|
2822
|
+
}
|
|
2823
|
+
return authoriseContext(ctx);
|
|
2824
|
+
}
|
|
2733
2825
|
/**
|
|
2734
2826
|
* Refresh the group-title cache from an accepted update — supergroups always carry `chat.title`. Feeds the thread-context
|
|
2735
2827
|
* preamble (S2). Cheap, idempotent, and the one place every accepted update funnels through. A private chat (DM key) has
|
|
@@ -2823,6 +2915,26 @@ async function noteServedGroupSender(ctx) {
|
|
|
2823
2915
|
if (groupSpeaker.role === 'none' && !isTalkerNow)
|
|
2824
2916
|
recentTopicWriters.noteIgnoredWriter((0, sessionKey_1.keyToString)(groupSpeaker.key), person);
|
|
2825
2917
|
}
|
|
2918
|
+
/**
|
|
2919
|
+
* @description Keep the name a bound topic was created with as the candidate for its name, when an admin writes in it and the bot
|
|
2920
|
+
* knows no name for it yet. The topic may have been renamed since: the candidate is only offered by `/topic_status`, never applied.
|
|
2921
|
+
*/
|
|
2922
|
+
async function noteTopicNameCandidate(ctx) {
|
|
2923
|
+
if (!ctx.message)
|
|
2924
|
+
return;
|
|
2925
|
+
const creationName = (0, inbound_1.getTopicCreationName)(ctx.message);
|
|
2926
|
+
if (creationName === null)
|
|
2927
|
+
return;
|
|
2928
|
+
const key = getThreadKey(ctx);
|
|
2929
|
+
if (!key || checkIsGeneral(key))
|
|
2930
|
+
return;
|
|
2931
|
+
const binding = state.getBinding(key);
|
|
2932
|
+
if (!binding || binding.topicName !== undefined || binding.topicNameCandidate === creationName)
|
|
2933
|
+
return;
|
|
2934
|
+
if (!(await checkIsAllowedUser(ctx)))
|
|
2935
|
+
return;
|
|
2936
|
+
await state.setBindingTopicNaming(key, { topicNameCandidate: creationName });
|
|
2937
|
+
}
|
|
2826
2938
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
2827
2939
|
// Send helpers — replyToThread + auto-track + error routing
|
|
2828
2940
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
@@ -3062,6 +3174,75 @@ function computePinnedStatusText(key) {
|
|
|
3062
3174
|
}
|
|
3063
3175
|
return (0, pinnedStatus_1.formatPinnedStatus)({ binding, agentLabel, model, effort: effortView?.level ?? null, effortNextStart: effortView?.nextStartLevel ?? null, isActive });
|
|
3064
3176
|
}
|
|
3177
|
+
/**
|
|
3178
|
+
* Conversations whose agent went wrong on its own — a crash, an error after the start, a conversation that was lost — until their
|
|
3179
|
+
* next turn begins: the topic's status mark says «stuck» meanwhile. In memory: a restart starts the conversation clean.
|
|
3180
|
+
*/
|
|
3181
|
+
const topicsStuckUntilNextTurn = new Set();
|
|
3182
|
+
/**
|
|
3183
|
+
* @description Whether the agent of `key`'s topic cannot go on by itself: logged out, a usage-limit wait ARMED (a fired one — its entry kept in memory — is the agent going on) or its notice waiting for
|
|
3184
|
+
* the owner (auto-continue off, an API account used up), or a crash / lost conversation not yet followed by a turn.
|
|
3185
|
+
*/
|
|
3186
|
+
function checkIsTopicStuck(key) {
|
|
3187
|
+
const k = (0, sessionKey_1.keyToString)(key);
|
|
3188
|
+
return (authNoticePinnedMessageId.has(k) ||
|
|
3189
|
+
getArmedApiRetry(key)?.kind === 'usageLimit' ||
|
|
3190
|
+
autoContinueOffNoticedThreads.has(k) ||
|
|
3191
|
+
balanceExhaustedNoticedThreads.has(k) ||
|
|
3192
|
+
topicsStuckUntilNextTurn.has(k));
|
|
3193
|
+
}
|
|
3194
|
+
/** The workers the agent of `key`'s topic watches that still run (`checkIsWatchedWorkerRunning`). */
|
|
3195
|
+
function getWatchedWorkerCount(key) {
|
|
3196
|
+
return state.getThreadSchedules(key).filter(topicIndicatorSources_1.checkIsWatchedWorkerRunning).length;
|
|
3197
|
+
}
|
|
3198
|
+
/** The adapter names a topic held that no adapter answers to, told once each. */
|
|
3199
|
+
const unknownTopicAdapterNamesLogged = new Set();
|
|
3200
|
+
/**
|
|
3201
|
+
* @description Read the agent of `key`'s topic once: `null` for a topic with no agent states — a terminal topic, one that never started an
|
|
3202
|
+
* agent. A name no adapter answers to (a stale binding) is a topic with an agent that is not up, said once in the log.
|
|
3203
|
+
*/
|
|
3204
|
+
function readTopicAgent(key) {
|
|
3205
|
+
const adapterName = (0, createAdapter_1.getThreadAdapterNameRaw)(key) ?? state.getAgent(key)?.name;
|
|
3206
|
+
if (adapterName === undefined || adapterName === adapterNames_1.terminalAdapterName)
|
|
3207
|
+
return null;
|
|
3208
|
+
if (!(0, createAdapter_1.getKnownAdapterNames)().includes(adapterName)) {
|
|
3209
|
+
if (!unknownTopicAdapterNamesLogged.has(adapterName)) {
|
|
3210
|
+
unknownTopicAdapterNamesLogged.add(adapterName);
|
|
3211
|
+
console.warn(`[topic-indicator] ${(0, sessionKey_1.keyToString)(key)}: the topic holds the backend "${adapterName}", which no adapter answers to — no agent states for it`);
|
|
3212
|
+
}
|
|
3213
|
+
return { adapterName, isActive: false, isTurnRunning: false };
|
|
3214
|
+
}
|
|
3215
|
+
const adapter = (0, createAdapter_1.getAdapter)(adapterName);
|
|
3216
|
+
const isActive = adapter.checkIsActive(key);
|
|
3217
|
+
return { adapterName, isActive, isTurnRunning: isActive && (adapter.checkIsWorking ? adapter.checkIsWorking(key) : adapter.checkIsBusy?.(key) === true) };
|
|
3218
|
+
}
|
|
3219
|
+
/**
|
|
3220
|
+
* @description The facts the status mark of `key`'s topic name is chosen from (`utils/topicIndicatorPlan.ts`), read live: an open question
|
|
3221
|
+
* (waiting or set aside), a stuck agent, a turn or a watched worker at work, a process that is up and idle (finished) or stopped with the
|
|
3222
|
+
* conversation kept (asleep; for the per-turn backend, whose process stops after every turn, finished). The rules are `getTopicStatusInputs`.
|
|
3223
|
+
*/
|
|
3224
|
+
function getTopicIndicatorInputs(key) {
|
|
3225
|
+
const k = (0, sessionKey_1.keyToString)(key);
|
|
3226
|
+
const agent = readTopicAgent(key);
|
|
3227
|
+
return (0, topicIndicatorSources_1.getTopicStatusInputs)({
|
|
3228
|
+
hasAgent: agent !== null,
|
|
3229
|
+
isActive: agent?.isActive ?? false,
|
|
3230
|
+
isTurnRunning: agent?.isTurnRunning ?? false,
|
|
3231
|
+
isPerTurnBackend: agent?.adapterName === adapterNames_1.claudePerTurnAdapterName,
|
|
3232
|
+
watchedWorkerCount: getWatchedWorkerCount(key),
|
|
3233
|
+
hasOpenQuestion: pendingQuestions.has(k) || (state.getSetAsideQuestions()[k]?.length ?? 0) > 0,
|
|
3234
|
+
isStuck: checkIsTopicStuck(key),
|
|
3235
|
+
hasResumableSession: getResumableSessionId(key) !== null,
|
|
3236
|
+
});
|
|
3237
|
+
}
|
|
3238
|
+
/** The agents at work in `key`'s topic: its own while it works, plus each worker it watches. */
|
|
3239
|
+
function getTopicIndicatorAgentsCount(key) {
|
|
3240
|
+
return (readTopicAgent(key)?.isTurnRunning ? 1 : 0) + getWatchedWorkerCount(key);
|
|
3241
|
+
}
|
|
3242
|
+
/** The tasks the topic's agent published as queued (`todo_update`); `inWork` ones are being done and show as working. */
|
|
3243
|
+
function getTopicIndicatorQueuedCount(key) {
|
|
3244
|
+
return getTodoRegistry().getTopic(key).items.filter((item) => item.status === 'queued').length;
|
|
3245
|
+
}
|
|
3065
3246
|
/**
|
|
3066
3247
|
* @description Send-or-edit the pinned status banner for a thread.
|
|
3067
3248
|
*
|
|
@@ -3081,6 +3262,8 @@ async function updatePinnedStatus(key) {
|
|
|
3081
3262
|
return;
|
|
3082
3263
|
if (!shouldHavePinnedStatus(key))
|
|
3083
3264
|
return;
|
|
3265
|
+
// The banner is refreshed at every start, stop, suspension and close of the topic's agent: the same moments its name's mark changes.
|
|
3266
|
+
topicIndicator.requestRefresh(key);
|
|
3084
3267
|
// Audit S6 / #8: serialise all banner work for a key — without this,
|
|
3085
3268
|
// two near-simultaneous adapter events could both observe a missing
|
|
3086
3269
|
// `pinnedStatusMessageId` and stack duplicate pins. Errors from one
|
|
@@ -3307,7 +3490,9 @@ async function unpinThreadQuestion(key) {
|
|
|
3307
3490
|
*/
|
|
3308
3491
|
function buildSendExtra(key, extra) {
|
|
3309
3492
|
const base = extra;
|
|
3310
|
-
|
|
3493
|
+
// 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
|
|
3494
|
+
// `message_thread_id` there with «message thread not found».
|
|
3495
|
+
if (checkIsGeneral(key) || (0, threadRouting_1.checkIsPrivateChatMainKey)(key))
|
|
3311
3496
|
return { ...base };
|
|
3312
3497
|
// Audit S20 / #36: spread `base` BEFORE `message_thread_id` so a
|
|
3313
3498
|
// caller passing `message_thread_id: undefined` in `extra` can't
|
|
@@ -3374,7 +3559,7 @@ async function replyToThreadDetailed(key, text, extra = {}, options = {}) {
|
|
|
3374
3559
|
if ((0, rateLimiter_1.checkIsSendOutcomeUnknownError)(e2))
|
|
3375
3560
|
return reportUnknown();
|
|
3376
3561
|
await handleSendError(key, e2);
|
|
3377
|
-
return
|
|
3562
|
+
return (0, telegramFailureRetry_1.getFailedSendOutcome)(e2);
|
|
3378
3563
|
}
|
|
3379
3564
|
}
|
|
3380
3565
|
// A double-429 (rate-limited even after withRateLimitRetry's single
|
|
@@ -3383,7 +3568,7 @@ async function replyToThreadDetailed(key, text, extra = {}, options = {}) {
|
|
|
3383
3568
|
// re-arm a bounded redelivery (its late re-send was the OUT-OF-ORDER cause
|
|
3384
3569
|
// the user reported) — the rare 429 is just logged via handleSendError.
|
|
3385
3570
|
await handleSendError(key, e);
|
|
3386
|
-
return
|
|
3571
|
+
return (0, telegramFailureRetry_1.getFailedSendOutcome)(e);
|
|
3387
3572
|
}
|
|
3388
3573
|
finally {
|
|
3389
3574
|
releaseSecret?.();
|
|
@@ -4360,6 +4545,16 @@ async function releaseThreadSession(key) {
|
|
|
4360
4545
|
async function releaseConversationIds(key) {
|
|
4361
4546
|
await state.clearAgentSessionIds(key);
|
|
4362
4547
|
clearThreadCompaction(key);
|
|
4548
|
+
closeSetAsideQuestionsInBackground(key);
|
|
4549
|
+
}
|
|
4550
|
+
/**
|
|
4551
|
+
* @description The conversation ended or was replaced (released for good, another conversation or backend picked): every question
|
|
4552
|
+
* the bot had set aside for it ends as «not answered», its pin released — its buttons would send an answer into a conversation that
|
|
4553
|
+
* is not the one that asked. NOT the idle stop, the sleep or a crash: the conversation is still there, and a late answer wakes it.
|
|
4554
|
+
* Not awaited (the edits go through the send pacer); a failure is logged.
|
|
4555
|
+
*/
|
|
4556
|
+
function closeSetAsideQuestionsInBackground(key) {
|
|
4557
|
+
closeSetAsideQuestions(key).catch((e) => console.error('[questionSetAside] closing the set-aside questions failed:', e));
|
|
4363
4558
|
}
|
|
4364
4559
|
/**
|
|
4365
4560
|
* @description Switch a thread's adapter and clear the previous adapter's
|
|
@@ -4378,7 +4573,7 @@ async function releaseConversationIds(key) {
|
|
|
4378
4573
|
* Resolves the work the stop cut off that the agent's next prompt is told about (`null`: none), so a caller's line to
|
|
4379
4574
|
* the operator is derived from the very record the note lists.
|
|
4380
4575
|
*/
|
|
4381
|
-
async function switchThreadAdapter(key, newName) {
|
|
4576
|
+
async function switchThreadAdapter(key, newName, options = {}) {
|
|
4382
4577
|
const prevName = (0, createAdapter_1.getThreadAdapterNameRaw)(key);
|
|
4383
4578
|
// Another agent or a shell takes the topic over: the open request belonged to
|
|
4384
4579
|
// the old conversation, so it closes silently instead of a later wake-up
|
|
@@ -4387,6 +4582,10 @@ async function switchThreadAdapter(key, newName) {
|
|
|
4387
4582
|
cancelConversationRequest(key);
|
|
4388
4583
|
// Nor does the conversation left behind get its re-asked question answered: its buttons would send the label into the new one.
|
|
4389
4584
|
closeReAskedQuestion(key);
|
|
4585
|
+
// The same for the questions it had set aside — unless the bot moved the conversation itself (an automatic usage-limit
|
|
4586
|
+
// fallback): it parks the conversation and bridges its context, so a late answer goes to the one now running.
|
|
4587
|
+
if (options.isConversationKept !== true)
|
|
4588
|
+
closeSetAsideQuestionsInBackground(key);
|
|
4390
4589
|
}
|
|
4391
4590
|
let switchCutOffWork = null;
|
|
4392
4591
|
if (prevName && prevName !== newName) {
|
|
@@ -4915,6 +5114,7 @@ const autoStopUnsupportedLoggedKeys = new Set();
|
|
|
4915
5114
|
*/
|
|
4916
5115
|
function handleAgentTurnEnded(key) {
|
|
4917
5116
|
noteThreadActivity(key);
|
|
5117
|
+
topicIndicator.requestRefresh(key);
|
|
4918
5118
|
const adapter = (0, createAdapter_1.getThreadAdapter)(key);
|
|
4919
5119
|
if (adapter.name !== adapterNames_1.claudePerTurnAdapterName)
|
|
4920
5120
|
return;
|
|
@@ -4954,17 +5154,19 @@ async function replayBufferedPrompts(key) {
|
|
|
4954
5154
|
// like the API-error retry's nudge, hears whether it reached the session).
|
|
4955
5155
|
await startupPromptBuffer.replayPrompts((0, sessionKey_1.keyToString)(key), {
|
|
4956
5156
|
isSessionActive,
|
|
4957
|
-
forward: async (prompt) => { await forwardPromptToAgent(key, adapter, prompt); },
|
|
5157
|
+
forward: async (prompt, isPersonInput) => { await forwardPromptToAgent(key, adapter, prompt, undefined, { isPersonInput }); },
|
|
4958
5158
|
});
|
|
4959
5159
|
if (!isSessionActive)
|
|
4960
5160
|
return;
|
|
4961
5161
|
// R23: prompts held during a usage-limit wait that ended with the previous
|
|
4962
|
-
// session go to this one — on their own when nothing above carried them.
|
|
5162
|
+
// session go to this one — on their own when nothing above carried them. They
|
|
5163
|
+
// are what people asked for meanwhile: a write that fails is told in the topic
|
|
5164
|
+
// like a person's own message, never only logged.
|
|
4963
5165
|
const heldText = limitHeldPrompts.releaseAll(key);
|
|
4964
5166
|
if (heldText === null)
|
|
4965
5167
|
return;
|
|
4966
5168
|
try {
|
|
4967
|
-
await forwardPromptToAgent(key, adapter, heldText);
|
|
5169
|
+
await forwardPromptToAgent(key, adapter, heldText, undefined, { isPersonInput: true });
|
|
4968
5170
|
}
|
|
4969
5171
|
catch (err) {
|
|
4970
5172
|
console.error('[replayBufferedPrompts] forwarding the held prompts failed:', err);
|
|
@@ -4994,6 +5196,9 @@ async function replayBufferedPrompts(key) {
|
|
|
4994
5196
|
* for an adopt replay can come out as anything but `forwarded`; most callers have no use for the answer.
|
|
4995
5197
|
*/
|
|
4996
5198
|
async function forwardPromptToAgent(key, adapter, text, sentAtMs, options = {}) {
|
|
5199
|
+
// The next turn begins: an agent that went wrong is no longer stuck (`checkIsTopicStuck`), and its name follows.
|
|
5200
|
+
if (topicsStuckUntilNextTurn.delete((0, sessionKey_1.keyToString)(key)))
|
|
5201
|
+
topicIndicator.requestRefresh(key);
|
|
4997
5202
|
// An adopted session replays what its process wrote during the downtime first: a prompt written meanwhile would reset
|
|
4998
5203
|
// the answer and error state those frames still use, and the replayed text would join the new reply's message (the
|
|
4999
5204
|
// «new message» mark would go to the replayed text). Nothing is awaited when no replay is pending: the forward then runs
|
|
@@ -5013,7 +5218,11 @@ async function forwardPromptToAgent(key, adapter, text, sentAtMs, options = {})
|
|
|
5013
5218
|
checkIsWindowOpen: () => startupPromptBuffer.checkIsStarting((0, sessionKey_1.keyToString)(key)),
|
|
5014
5219
|
checkIsSessionActive: () => adapter.checkIsActive(key) && !(isTechnicalPrompt && (adapter.checkIsBusy?.(key) ?? false)),
|
|
5015
5220
|
buffer: async () => {
|
|
5016
|
-
|
|
5221
|
+
// A bot-made prompt (a wake-up) that waits here counts only once its replay reached the agent, as at any other buffer.
|
|
5222
|
+
const buffered = createBufferedOutcome();
|
|
5223
|
+
await deliverPromptOrBuffer(key, `${options.requestHeader ?? ''}${getPromptWithThreadMessageContext(key, text, options.messageContext)}`, true, buffered.settle, { isPersonInput: options.isPersonInput });
|
|
5224
|
+
if (options.isPersonInput !== true)
|
|
5225
|
+
await buffered.assertReplayed();
|
|
5017
5226
|
},
|
|
5018
5227
|
wake: () => wakeSleepingSessionForPrompt(key),
|
|
5019
5228
|
forward: async () => {
|
|
@@ -5068,8 +5277,10 @@ async function forwardPromptToLiveAgent(key, adapter, text, sentAtMs, options =
|
|
|
5068
5277
|
// The request header (S7) leads the per-message body, like the message context and
|
|
5069
5278
|
// unlike the once-per-change thread preamble: it names THIS message's request.
|
|
5070
5279
|
const messageBody = options.requestHeader ? `${options.requestHeader}${quotedBody}` : quotedBody;
|
|
5071
|
-
// A loss the agent was not told about yet (`utils/lostWork.ts`) rides the first real prompt, once, ahead of it
|
|
5072
|
-
|
|
5280
|
+
// A loss the agent was not told about yet (`utils/lostWork.ts`) rides the first real prompt, once, ahead of it — a
|
|
5281
|
+
// request's reminder included: the wake of a tracker request whose process a restart left behind is how its agent hears.
|
|
5282
|
+
const isLostWorkNoteCarried = (isReplayable || options.isRequestReminder === true) && adapter.name !== 'terminal';
|
|
5283
|
+
const lostWorkRecord = isLostWorkNoteCarried ? state.getLostWork(key) : undefined;
|
|
5073
5284
|
const body = lostWorkRecord ? `${(0, lostWork_1.buildLostWorkNote)(lostWorkRecord, (0, i18n_1.getLocaleEndonym)((0, i18n_1.getActiveLang)()))}\n\n${messageBody}` : messageBody;
|
|
5074
5285
|
// Cache the (reply-folded) prompt so a wedged OpenCode session can be recovered
|
|
5075
5286
|
// by restarting fresh and replaying it — replaying WITH the quote is correct.
|
|
@@ -5134,10 +5345,10 @@ async function forwardPromptToLiveAgent(key, adapter, text, sentAtMs, options =
|
|
|
5134
5345
|
if (adapter.detachRunningSubagents && !isTechnicalPrompt) {
|
|
5135
5346
|
await adapter.detachRunningSubagents(key);
|
|
5136
5347
|
}
|
|
5137
|
-
|
|
5138
|
-
//
|
|
5139
|
-
|
|
5140
|
-
|
|
5348
|
+
// A backend that can tell whether the prompt reached the agent (the json-stream host's stdin write) is asked to: a
|
|
5349
|
+
// write that failed rejects this forward, so its caller — a tracker post, a wake-up — knows the prompt never arrived
|
|
5350
|
+
// and retries, instead of believing it delivered. The input is handed over synchronously either way; only its outcome is awaited.
|
|
5351
|
+
const written = adapter.sendInputAndWait ? adapter.sendInputAndWait(key, promptText) : (adapter.sendInput(key, promptText), Promise.resolve());
|
|
5141
5352
|
// S2 busy-onset arm: start the Claude liveness loop the moment the prompt is
|
|
5142
5353
|
// forwarded — driven by `checkIsBusy`, not by waiting for an opportunistic
|
|
5143
5354
|
// scrape emit that may never come during a long quiet think. The arming grace
|
|
@@ -5146,6 +5357,26 @@ async function forwardPromptToLiveAgent(key, adapter, text, sentAtMs, options =
|
|
|
5146
5357
|
// choke point (user text, voice, scheduled run, api-retry continue, buffered
|
|
5147
5358
|
// replay), so every path that makes Claude busy now raises the working frame.
|
|
5148
5359
|
startClaudeLiveness(key, 'busyOnset');
|
|
5360
|
+
// Told only once the prompt carrying the note reached a live session: a forward that failed keeps it for the next.
|
|
5361
|
+
const noteToldIfDelivered = () => {
|
|
5362
|
+
if (lostWorkRecord && adapter.checkIsActive(key))
|
|
5363
|
+
void state.clearLostWork(key);
|
|
5364
|
+
};
|
|
5365
|
+
// A person's own message never holds the topic's update queue on its write — a CLI that stops reading its input would
|
|
5366
|
+
// keep `/esc` and every tap behind it for minutes —: they are told when it failed. Every other prompt (a tracker's post,
|
|
5367
|
+
// a wake-up, a scheduled run, a retry's nudge, the todo reminder) awaits it: one that never arrived is retried.
|
|
5368
|
+
if (options.isPersonInput === true) {
|
|
5369
|
+
void written.then(noteToldIfDelivered, (error) => reportUndeliveredTopicPrompt(key, error));
|
|
5370
|
+
return;
|
|
5371
|
+
}
|
|
5372
|
+
await written;
|
|
5373
|
+
noteToldIfDelivered();
|
|
5374
|
+
}
|
|
5375
|
+
/** @description A topic's prompt whose write into the agent failed (the forward did not wait for it): one line says so. */
|
|
5376
|
+
function reportUndeliveredTopicPrompt(key, error) {
|
|
5377
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
5378
|
+
console.warn(`[forward] ${(0, sessionKey_1.keyToString)(key)}: the prompt did not reach the agent: ${message}`);
|
|
5379
|
+
void withThreadLocale(key, () => replyToThread(key, (0, i18n_1.t)('agent.prompt_not_delivered', { error: message }))).catch(() => { });
|
|
5149
5380
|
}
|
|
5150
5381
|
/**
|
|
5151
5382
|
* @description Return the prompt text with the thread-context preamble glued
|
|
@@ -5343,6 +5574,8 @@ const { checkIsThreadCompacting, noteThreadActivity, noteThreadUserActivity, mar
|
|
|
5343
5574
|
pendingQuestions,
|
|
5344
5575
|
clearPendingQuestion,
|
|
5345
5576
|
closeQuestionMessage,
|
|
5577
|
+
// The module that sets questions aside is built just below (it needs nothing from this one): the idle fire reaches it through this.
|
|
5578
|
+
setQuestionAsideAtIdle: (key) => setPendingQuestionAsideAtIdle(key),
|
|
5346
5579
|
idleWindowMs: (0, compactOnIdle_1.getAgentIdleMs)(process.env.AGENT_IDLE_MINUTES),
|
|
5347
5580
|
checkIsLimitWaitArmed: (key) => getArmedApiRetry(key)?.kind === 'usageLimit',
|
|
5348
5581
|
suspendThreadSession,
|
|
@@ -5358,6 +5591,29 @@ const { checkIsThreadCompacting, noteThreadActivity, noteThreadUserActivity, mar
|
|
|
5358
5591
|
notePersonActivity,
|
|
5359
5592
|
compactSelfReviewFlagDirs: (0, compactSelfReviewFlags_1.getCompactSelfReviewFlagDirs)((0, state_1.resolveDataDir)(), (0, openCodeCompactPlugin_1.resolveOpenCodeGlobalPluginDir)(process.env)),
|
|
5360
5593
|
});
|
|
5594
|
+
/** The instance's question wait, re-read from `settings.json` when the file changes (`null`: not set, the default applies). */
|
|
5595
|
+
const readInstanceQuestionWait = (0, instanceSettings_1.createQuestionWaitSettingsReader)(() => (0, instanceSettings_1.getInstanceSettingsPath)(), (line) => console.error(line));
|
|
5596
|
+
const { armQuestionSetAsideTimer, clearQuestionSetAsideTimer, setPendingQuestionAsideAtIdle, answerQuestionAskedAgain, checkIsSetAsideQuestionMessage, answerLiveTapOnSetAsideQuestion, registerQuestionSetAsideCallbacks, answerSetAsideQuestionByReply, closeSetAsideQuestions, } = (0, questionSetAside_1.createQuestionSetAside)({
|
|
5597
|
+
...botCore,
|
|
5598
|
+
pendingQuestions,
|
|
5599
|
+
getThreadAdapter: createAdapter_1.getThreadAdapter,
|
|
5600
|
+
runQuestionLifecycleOp,
|
|
5601
|
+
setPendingQuestion,
|
|
5602
|
+
clearPendingQuestion,
|
|
5603
|
+
releasePendingQuestionToSetAside: (key) => dropPendingQuestion(key, { isPinKept: true }),
|
|
5604
|
+
editQuestionMessageWithNote,
|
|
5605
|
+
closeQuestionMessage,
|
|
5606
|
+
unpinMessage: unpinMessageQuiet,
|
|
5607
|
+
pinMessageSilently: (key, messageId) => pinMessageQuiet(key, messageId, { disableNotification: true }),
|
|
5608
|
+
sendQuestionMessage,
|
|
5609
|
+
deliverLateAnswer: (key, text) => withThreadLocale(key, () => deliverLateAnswerPrompt(key, text)),
|
|
5610
|
+
markNeedsNewMessage,
|
|
5611
|
+
// The topic's own choice (`/question_wait`), else the instance value `settings.json` holds (`questionWait`), else the default.
|
|
5612
|
+
getQuestionWaitChoice: (key) => (0, questionWaitPlan_1.resolveQuestionWait)(state.getQuestionWaitOverride(key), readInstanceQuestionWait() ?? undefined),
|
|
5613
|
+
shortenedWaitMs: ENV.testTimings.questionSetAsideWaitMs,
|
|
5614
|
+
retryDelayMs: ENV.testTimings.questionSetAsideRetryMs,
|
|
5615
|
+
postQuestionAnew: postAgentQuestion,
|
|
5616
|
+
});
|
|
5361
5617
|
/**
|
|
5362
5618
|
* @description True iff the neutral router owns `name`, i.e. a `/name` message
|
|
5363
5619
|
* is claimed by the routed-command trigger instead of falling through.
|
|
@@ -6074,6 +6330,9 @@ async function unbindThread(key) {
|
|
|
6074
6330
|
// the next /bind resumes them. `removeBinding` only touches bindings/agents/
|
|
6075
6331
|
// messages — schedules are their own collection and survive (S8).
|
|
6076
6332
|
await pauseThreadSchedulesOnUnbind(key).catch((e) => console.warn(`[scheduler] pause-on-unbind failed for ${kStr}:`, e));
|
|
6333
|
+
// The topic leaves the status marks: the owner's own name goes back while the binding still knows it.
|
|
6334
|
+
await topicIndicator.restoreBaseName(key);
|
|
6335
|
+
topicIndicator.forgetTopic(key);
|
|
6077
6336
|
await state.removeBinding(key);
|
|
6078
6337
|
clearInMemoryThreadState(key);
|
|
6079
6338
|
await replyToThread(key, (0, i18n_1.t)('thread.unbound'));
|
|
@@ -6868,6 +7127,57 @@ const { registerBotSkillsCommands, registerBotSkillsCallbacks } = (0, botSkills_
|
|
|
6868
7127
|
checkIsOpenCodeTopic: (key) => ((0, createAdapter_1.getThreadAdapterNameRaw)(key) ?? state.getAgent(key)?.name) === adapterNames_1.openCodeAdapterName,
|
|
6869
7128
|
});
|
|
6870
7129
|
registerBotSkillsCommands();
|
|
7130
|
+
// ── The question wait (`/question_wait`): `connectors/telegram/commands/questionWait.ts`, `utils/questionWaitPlan.ts` ──
|
|
7131
|
+
const { registerQuestionWaitCommands, registerQuestionWaitCallbacks } = (0, questionWait_1.createQuestionWait)({
|
|
7132
|
+
...botCore,
|
|
7133
|
+
readInstanceQuestionWait,
|
|
7134
|
+
getSettingsPath: () => (0, instanceSettings_1.getInstanceSettingsPath)(),
|
|
7135
|
+
// A changed wait applies to the questions that wait now too: their timers are set again, counted from the moment each was asked.
|
|
7136
|
+
noteQuestionWaitChanged: (key) => rearmQuestionSetAsideTimers(key),
|
|
7137
|
+
});
|
|
7138
|
+
registerQuestionWaitCommands();
|
|
7139
|
+
// ── The status mark at the end of a topic's name: `connectors/telegram/topicIndicator.ts`, `utils/topicIndicatorPlan.ts` ──
|
|
7140
|
+
const readInstanceTopicStatus = (0, instanceSettings_1.createTopicStatusSettingsReader)(() => (0, instanceSettings_1.getInstanceSettingsPath)(), (line) => console.error(line));
|
|
7141
|
+
const topicIndicator = (0, topicIndicator_1.createTopicIndicator)({
|
|
7142
|
+
getState: () => state,
|
|
7143
|
+
checkIsMarkableTopic: (key) => (0, sessionKeyCodec_1.checkIsTelegramKey)(key) && !checkIsGeneral(key),
|
|
7144
|
+
checkIsUnbinding: (key) => unbindingKeys.has((0, sessionKey_1.keyToString)(key)),
|
|
7145
|
+
getPrefs: (key) => (0, topicIndicatorPlan_1.resolveTopicStatusPrefs)(readInstanceTopicStatus(), state.getTopicStatusOverride(key)),
|
|
7146
|
+
getStatusInputs: getTopicIndicatorInputs,
|
|
7147
|
+
getAgentsCount: getTopicIndicatorAgentsCount,
|
|
7148
|
+
getQueuedCount: getTopicIndicatorQueuedCount,
|
|
7149
|
+
// The NAME alone: the topic's icon is the owner's and never travels with a rename.
|
|
7150
|
+
sendTopicName: async (key, name) => {
|
|
7151
|
+
await (0, rateLimiter_1.enqueueSend)(key, () => bot.telegram.editForumTopic((0, sessionKeyCodec_1.getTelegramChatId)(key), (0, sessionKeyCodec_1.getTelegramThreadId)(key), { name }));
|
|
7152
|
+
},
|
|
7153
|
+
deleteMessage: async (key, messageId) => {
|
|
7154
|
+
await (0, rateLimiter_1.enqueueSend)(key, () => bot.telegram.deleteMessage((0, sessionKeyCodec_1.getTelegramChatId)(key), messageId));
|
|
7155
|
+
},
|
|
7156
|
+
checkIsBacklogHandled: () => firstUpdateBatch.checkIsBacklogHandled(updateDispatcher.size()),
|
|
7157
|
+
windows: {
|
|
7158
|
+
settleMs: ENV.testTimings.topicIndicatorSettleMs ?? topicIndicatorPlan_1.indicatorSettleMs,
|
|
7159
|
+
minGapMs: ENV.testTimings.topicIndicatorMinRenameGapMs ?? topicIndicatorPlan_1.indicatorMinRenameGapMs,
|
|
7160
|
+
sweepIntervalMs: ENV.testTimings.topicIndicatorSweepMs ?? topicIndicatorPlan_1.indicatorSweepIntervalMs,
|
|
7161
|
+
bootWaveDelayMs: ENV.testTimings.topicIndicatorBootWaveDelayMs ?? topicIndicatorPlan_1.indicatorBootWaveDelayMs,
|
|
7162
|
+
},
|
|
7163
|
+
getNowMs: Date.now,
|
|
7164
|
+
setTimer: (callback, delayMs) => {
|
|
7165
|
+
const timer = setTimeout(callback, delayMs);
|
|
7166
|
+
timer.unref();
|
|
7167
|
+
return { cancel: () => clearTimeout(timer) };
|
|
7168
|
+
},
|
|
7169
|
+
log: (line) => console.warn(line),
|
|
7170
|
+
});
|
|
7171
|
+
// ── `/topic_status`: `connectors/telegram/commands/topicStatus.ts`, `utils/topicStatusPlan.ts` — the switches of those marks ──
|
|
7172
|
+
const { registerTopicStatusCommands, registerTopicStatusCallbacks } = (0, topicStatus_1.createTopicStatus)({
|
|
7173
|
+
...botCore,
|
|
7174
|
+
readInstanceTopicStatus,
|
|
7175
|
+
getSettingsPath: () => (0, instanceSettings_1.getInstanceSettingsPath)(),
|
|
7176
|
+
getHealth: (key) => topicIndicator.getHealth(key),
|
|
7177
|
+
// The change is the owner's own: it skips the settle time and the gap, like the edges of ❓.
|
|
7178
|
+
noteTopicStatusChanged: (key) => (key === null ? topicIndicator.refreshAll({ isOwnerChange: true }) : topicIndicator.requestRefresh(key, { isOwnerChange: true })),
|
|
7179
|
+
});
|
|
7180
|
+
registerTopicStatusCommands();
|
|
6871
7181
|
// ── Who may talk to the agent in a topic (`/access`): `connectors/telegram/commands/topicAccess.ts`, `topicTalkers.ts` ──
|
|
6872
7182
|
const { registerTopicAccessCommands, registerTopicAccessCallbacks } = (0, topicAccess_1.createTopicAccess)({
|
|
6873
7183
|
...botCore,
|
|
@@ -6902,6 +7212,7 @@ const { registerRunnersCommands, registerRunnersCallbacks, handleRunnersAddressT
|
|
|
6902
7212
|
// What this instance has told about where the runners' links come from: once per new concern, pinned in General.
|
|
6903
7213
|
linkNoticesPath: path.join((0, state_1.resolveDataDir)(), 'runner-link-notices.json'),
|
|
6904
7214
|
cacheDir: runnersCacheDir,
|
|
7215
|
+
authorisePairingTap,
|
|
6905
7216
|
getGeneralKey: () => getOperatorGeneralKey(),
|
|
6906
7217
|
pinMessage: (key, messageId) => pinMessageQuiet(key, messageId, { disableNotification: false }),
|
|
6907
7218
|
sweepExpiredCodes: async (nowMs) => { await (0, hubPairing_1.sweepExpiredPairings)(runnersHub, nowMs); },
|
|
@@ -6919,9 +7230,20 @@ const { registerRunnersCommands, registerRunnersCallbacks, handleRunnersAddressT
|
|
|
6919
7230
|
});
|
|
6920
7231
|
registerRunnersCommands();
|
|
6921
7232
|
// ── Claude account profiles (`/account`): `utils/claudeProfiles.ts`, `commands/claudeAccounts.ts` ──
|
|
7233
|
+
/**
|
|
7234
|
+
* @description Put a profile folder's layout right before a process starts under it (`repairClaudeProfileFolderForLaunch`): the entries
|
|
7235
|
+
* Claude Code loads as user-level configuration are links into `~/.claude` again, and whatever an agent on the account planted in their
|
|
7236
|
+
* place is moved aside. Every launch site calls it — the conversation spawns (`resolveThreadClaudeConfigDir`: json-stream, per-turn and
|
|
7237
|
+
* tmux, start, resume and account switch), the `claude auth` probes (`readClaudeAuthStatusUnder`), the sign-in (the layout call of
|
|
7238
|
+
* `/accounts`) and the account a worker is pointed at (`listClaudeProfilesForAgent`, `charness claude-profiles`). Never throws.
|
|
7239
|
+
*/
|
|
7240
|
+
function repairClaudeProfileFolder(configDir) {
|
|
7241
|
+
(0, claudeProfiles_1.repairClaudeProfileFolderForLaunch)({ dataDir: (0, state_1.resolveDataDir)(), configDir });
|
|
7242
|
+
}
|
|
6922
7243
|
/**
|
|
6923
7244
|
* @description The Claude config directory a conversation's NEXT process starts with: its resolved account
|
|
6924
|
-
* profile's directory, `null` for the default profile. Registered as the adapters' reader at boot
|
|
7245
|
+
* profile's directory, `null` for the default profile. Registered as the adapters' reader at boot, and read by
|
|
7246
|
+
* every spawn, so the folder is repaired here ({@link repairClaudeProfileFolder}). A profile
|
|
6925
7247
|
* whose directory vanished (a hand-cleaned `DATA_DIR`) runs on the default rather than failing the spawn.
|
|
6926
7248
|
*/
|
|
6927
7249
|
function resolveThreadClaudeConfigDir(key) {
|
|
@@ -6931,6 +7253,7 @@ function resolveThreadClaudeConfigDir(key) {
|
|
|
6931
7253
|
console.warn(`[account] ${(0, sessionKey_1.keyToString)(key)}: the directory of profile ${name} is missing; its process runs on the default profile`);
|
|
6932
7254
|
return null;
|
|
6933
7255
|
}
|
|
7256
|
+
repairClaudeProfileFolder(dir);
|
|
6934
7257
|
return dir;
|
|
6935
7258
|
}
|
|
6936
7259
|
/**
|
|
@@ -6939,6 +7262,8 @@ function resolveThreadClaudeConfigDir(key) {
|
|
|
6939
7262
|
* the probe fails.
|
|
6940
7263
|
*/
|
|
6941
7264
|
async function readClaudeAuthStatusUnder(configDir) {
|
|
7265
|
+
// The probe loads the folder's settings (an `apiKeyHelper` there is a command): the layout is put right first.
|
|
7266
|
+
repairClaudeProfileFolder(configDir);
|
|
6942
7267
|
const env = (0, claudeProfiles_1.getClaudeAuthCommandEnvironment)(configDir);
|
|
6943
7268
|
try {
|
|
6944
7269
|
const args = [...(0, claudeApiKeyHelper_1.buildClaudeAuthProbeSettingsArgs)(configDir), 'auth', 'status', '--json'];
|
|
@@ -7004,12 +7329,31 @@ const openCodeUsagePoller = (0, openCodeUsage_1.createOpenCodeUsagePoller)({
|
|
|
7004
7329
|
getRecord: (providerId) => state.getOpenCodeProviderUsage(providerId),
|
|
7005
7330
|
saveRecord: (providerId, record) => state.setOpenCodeProviderUsage(providerId, record),
|
|
7006
7331
|
});
|
|
7332
|
+
/**
|
|
7333
|
+
* The registry of Claude profiles kept in step with the disk and the CLI, with no Telegram in the way (`utils/claudeProfileSync.ts`):
|
|
7334
|
+
* a profile folder under `DATA_DIR/claude-profiles/` signed in by hand is adopted, every profile's sign-in status is probed when it
|
|
7335
|
+
* is due. The usage poll below runs it first, so an instance that serves only a tracker sees every account; `/accounts` forces it.
|
|
7336
|
+
* `state` is assigned at boot, so the store reads it at each call.
|
|
7337
|
+
*/
|
|
7338
|
+
const claudeProfileSync = (0, claudeProfileSync_1.createClaudeProfileSync)({
|
|
7339
|
+
store: {
|
|
7340
|
+
getClaudeProfileRecords: () => state.getClaudeProfileRecords(),
|
|
7341
|
+
getClaudeProfileRecord: (name) => state.getClaudeProfileRecord(name),
|
|
7342
|
+
getClaudeProfileInfo: (name) => state.getClaudeProfileInfo(name),
|
|
7343
|
+
upsertClaudeProfileRecord: (name, patch) => state.upsertClaudeProfileRecord(name, patch),
|
|
7344
|
+
},
|
|
7345
|
+
getDataDir: () => (0, state_1.resolveDataDir)(),
|
|
7346
|
+
readStatus: readClaudeAuthStatusUnder,
|
|
7347
|
+
// A folder made by hand may lack the links into `~/.claude` (the transcripts above all): the one idempotent layout call adds them.
|
|
7348
|
+
ensureLayout: (name) => { (0, claudeProfiles_1.createClaudeProfileLayout)({ dataDir: (0, state_1.resolveDataDir)(), name }); },
|
|
7349
|
+
});
|
|
7007
7350
|
/**
|
|
7008
7351
|
* The per-profile usage cache (`utils/claudeUsageRefresher.ts`): every signed-in profile's windows off the
|
|
7009
7352
|
* OAuth usage endpoint on a 10-minute timer, on `/account` open and on a `claude_profiles` call, plus the
|
|
7010
7353
|
* `rate_limit_event` frames the json-stream sessions report. Snapshots live on the profile records.
|
|
7011
7354
|
*/
|
|
7012
7355
|
const claudeUsageRefresher = (0, claudeUsageRefresher_1.createClaudeUsageRefresher)({
|
|
7356
|
+
syncProfiles: () => claudeProfileSync.sync(),
|
|
7013
7357
|
listProfiles: () => [
|
|
7014
7358
|
{
|
|
7015
7359
|
name: claudeProfiles_1.defaultClaudeProfileName, configDir: null,
|
|
@@ -7289,12 +7633,18 @@ function notePersonActivity(key) {
|
|
|
7289
7633
|
* blind delay; an OpenCode model: else the blind delay), the usage snapshots are brought up to date, and the
|
|
7290
7634
|
* chain's AVAILABLE rungs are listed in priority order. Without a configured chain a Claude topic falls back to
|
|
7291
7635
|
* the within-Claude ranking by the soonest weekly reset (`utils/claudeLimitSwitch.ts`) — the behaviour before the chain existed. An
|
|
7292
|
-
* offer is remembered per thread under its episode so only ITS buttons can act on it. `none` for a
|
|
7293
|
-
*
|
|
7636
|
+
* offer is remembered per thread under its episode so only ITS buttons can act on it. `none` for a topic with no account to
|
|
7637
|
+
* switch from, or when no rung can take over.
|
|
7638
|
+
*
|
|
7639
|
+
* A conversation of another platform (a Jira issue) takes the AUTOMATIC move only, and only between Claude accounts: the chain's
|
|
7640
|
+
* Claude rungs when it has any (else the ranking), never an OpenCode rung (a cross-backend hand-over has no surface there). The
|
|
7641
|
+
* offer's buttons and the wait aimed at the rung that resets first (the retry kick moves a topic there only for Telegram) are
|
|
7642
|
+
* Telegram's: with auto-switch OFF, with no account free, or on OpenCode such a conversation waits for the reset as it always did.
|
|
7294
7643
|
*/
|
|
7295
7644
|
async function planFallbackSwitch(key, cls, episodeId) {
|
|
7296
7645
|
const from = getTopicFallbackPosition(key);
|
|
7297
|
-
|
|
7646
|
+
const isTelegram = (0, sessionKeyCodec_1.checkIsTelegramKey)(key);
|
|
7647
|
+
if (from === null || !(0, limitSwitchPlan_1.checkIsLimitSwitchPossible)(isTelegram, from))
|
|
7298
7648
|
return { action: 'none', from, earliest: null };
|
|
7299
7649
|
const k = (0, sessionKey_1.keyToString)(key);
|
|
7300
7650
|
const nowMs = Date.now();
|
|
@@ -7323,29 +7673,23 @@ async function planFallbackSwitch(key, cls, episodeId) {
|
|
|
7323
7673
|
// a stuck usage endpoint must never hold the switch or the wait notice of a topic that just hit its limit.
|
|
7324
7674
|
await (0, usageRefreshBudget_1.refreshUsageWithinBudget)((options) => claudeUsageRefresher.refreshAll(options));
|
|
7325
7675
|
const detection = await detectFallbackOptions();
|
|
7326
|
-
|
|
7327
|
-
|
|
7328
|
-
|
|
7329
|
-
|
|
7330
|
-
|
|
7331
|
-
|
|
7332
|
-
|
|
7676
|
+
const { plan, waitRungs } = (0, limitSwitchPlan_1.decideLimitSwitch)({
|
|
7677
|
+
isTelegram,
|
|
7678
|
+
from,
|
|
7679
|
+
chain: state.getFallbackChain(),
|
|
7680
|
+
detection,
|
|
7681
|
+
isAutoSwitchEnabled: state.checkIsClaudeAutoSwitchOnLimitEnabled(key),
|
|
7682
|
+
nowMs: Date.now(),
|
|
7683
|
+
});
|
|
7333
7684
|
if (plan.action === 'offer')
|
|
7334
7685
|
fallbackSwitchOffers.set(k, { episodeId, from, candidates: plan.candidates });
|
|
7335
7686
|
else
|
|
7336
7687
|
fallbackSwitchOffers.delete(k);
|
|
7337
7688
|
const detail = plan.action === 'auto' ? ` → ${formatFallbackEntry(plan.to)}` : plan.action === 'offer' ? ` [${plan.candidates.map(formatFallbackEntry).join(', ')}]` : '';
|
|
7338
|
-
// Nothing has room: the wait should end on the rung whose limit resets EARLIEST, not necessarily this one.
|
|
7689
|
+
// Nothing has room: the wait should end on the rung whose limit resets EARLIEST, not necessarily this one (a topic's wait only).
|
|
7339
7690
|
let earliest = null;
|
|
7340
|
-
if (
|
|
7341
|
-
const
|
|
7342
|
-
// Without a chain the implicit one is the signed-in SUBSCRIPTIONS: an account billed to API credits never ends a wait by itself.
|
|
7343
|
-
const rungs = explicit.length > 0 ? explicit : from.backend === 'claude'
|
|
7344
|
-
? detection.claudeProfiles
|
|
7345
|
-
.filter((profile) => profile.loggedIn !== false && profile.billing !== 'api')
|
|
7346
|
-
.map((profile) => ({ backend: 'claude', profile: profile.name, model: null }))
|
|
7347
|
-
: [];
|
|
7348
|
-
const found = (0, fallbackChain_1.pickEarliestResetRung)({ chain: rungs, current: from, detection, nowMs: Date.now() });
|
|
7691
|
+
if (waitRungs.length > 0) {
|
|
7692
|
+
const found = (0, fallbackChain_1.pickEarliestResetRung)({ chain: waitRungs, current: from, detection, nowMs: Date.now() });
|
|
7349
7693
|
if (found && !found.isCurrent)
|
|
7350
7694
|
earliest = { entry: found.entry, untilMs: found.untilMs };
|
|
7351
7695
|
}
|
|
@@ -7470,8 +7814,10 @@ async function switchTopicToFallbackEntry(key, from, to, options) {
|
|
|
7470
7814
|
// An OpenCode topic on the server's default model has no rung (`from` is null), yet it is on OpenCode all the same.
|
|
7471
7815
|
const isSameFamily = (from?.backend ?? getTopicBackendFamily(key)) === to.backend;
|
|
7472
7816
|
const runningModel = readRunningModelBeforeMove(key, from, to);
|
|
7817
|
+
// The notice is a topic message: a conversation of another platform (a Jira issue) hears nothing — the log line below says it — and
|
|
7818
|
+
// its work simply continues.
|
|
7473
7819
|
const say = async (notice) => {
|
|
7474
|
-
if (options.isAnnounced)
|
|
7820
|
+
if (options.isAnnounced && (0, sessionKeyCodec_1.checkIsTelegramKey)(key))
|
|
7475
7821
|
await replyToThread(key, notice);
|
|
7476
7822
|
};
|
|
7477
7823
|
const fail = async (error) => {
|
|
@@ -7518,7 +7864,8 @@ async function switchTopicToFallbackEntry(key, from, to, options) {
|
|
|
7518
7864
|
reason: 'limit',
|
|
7519
7865
|
resetsAtText: getFallbackResetTime(from),
|
|
7520
7866
|
});
|
|
7521
|
-
|
|
7867
|
+
// An automatic fallback keeps the conversation (parked, bridged): the questions it had set aside stay open for a late answer.
|
|
7868
|
+
isStoppingBackground = await moveTopicToOtherBackend(key, to.backend, to.backend === 'claude' ? to.profile : null, { isConversationKept: options.isAutomatic === true });
|
|
7522
7869
|
if (to.backend === 'opencode') {
|
|
7523
7870
|
const error = await (0, createAdapter_1.getThreadAdapter)(key).setModel?.(key, (0, fallbackChain_1.buildOpenCodeModelLabel)(to));
|
|
7524
7871
|
if (error)
|
|
@@ -7560,10 +7907,10 @@ async function switchTopicToFallbackEntry(key, from, to, options) {
|
|
|
7560
7907
|
* the adapter being left still runs. Resolves whether the stop took background work with it — the caller tells the
|
|
7561
7908
|
* operator (the agent is told by the next prompt, `switchThreadAdapter`).
|
|
7562
7909
|
*/
|
|
7563
|
-
async function moveTopicToOtherBackend(key, backend, account) {
|
|
7910
|
+
async function moveTopicToOtherBackend(key, backend, account, options = {}) {
|
|
7564
7911
|
if (account !== null)
|
|
7565
7912
|
await state.setClaudeProfileOverride(key, account);
|
|
7566
|
-
return (0, lostWork_1.checkHasLostBackgroundWork)(await switchThreadAdapter(key, backend === 'claude' ? (0, createAdapter_1.resolveClaudeBackendName)(key) : adapterNames_1.openCodeAdapterName));
|
|
7913
|
+
return (0, lostWork_1.checkHasLostBackgroundWork)(await switchThreadAdapter(key, backend === 'claude' ? (0, createAdapter_1.resolveClaudeBackendName)(key) : adapterNames_1.openCodeAdapterName, options));
|
|
7567
7914
|
}
|
|
7568
7915
|
/**
|
|
7569
7916
|
* @description The second half, after a move (across backends or between accounts): start or resume the topic's
|
|
@@ -7790,6 +8137,9 @@ async function takeFallbackSwitchOffer(key, episodeId, index) {
|
|
|
7790
8137
|
* dropped by its own client after 300 s).
|
|
7791
8138
|
*/
|
|
7792
8139
|
async function listClaudeProfilesForAgent(query) {
|
|
8140
|
+
// The agent launches its worker under whichever folder the answer names, so every folder is put right before it is named.
|
|
8141
|
+
for (const view of getClaudeProfileUsageViews())
|
|
8142
|
+
repairClaudeProfileFolder(view.configDir);
|
|
7793
8143
|
const stoppedApiProfile = (0, claudeApiAgentStop_1.getApiProfileStoppedByAgent)(getClaudeProfileUsageViews(), query, Date.now());
|
|
7794
8144
|
await Promise.all([
|
|
7795
8145
|
(0, claudeUsageRefresher_1.refreshClaudeUsageForLaunch)(claudeUsageRefresher, { currentProfile: query.currentProfile, isStoppedByLimit: query.isStoppedByLimit, maxAgeMs: claudeUsageRefresher_1.claudeUsageOnDemandMaxAgeMs }),
|
|
@@ -7835,6 +8185,7 @@ const { registerClaudeAccountCommands, registerClaudeAccountCallbacks, checkIsAw
|
|
|
7835
8185
|
getDataDir: state_1.resolveDataDir,
|
|
7836
8186
|
getInstanceTimezone: getCurrentTimezone,
|
|
7837
8187
|
refreshClaudeUsage: (options) => claudeUsageRefresher.refreshAll(options),
|
|
8188
|
+
syncClaudeProfiles: (options) => claudeProfileSync.sync(options),
|
|
7838
8189
|
readClaudeAuthStatus: readClaudeAuthStatusUnder,
|
|
7839
8190
|
startClaudeProfileLogin: (key, profile) => startClaudeAuthLogin(key, profile),
|
|
7840
8191
|
applyClaudeProfile: applyClaudePickToThread,
|
|
@@ -8000,6 +8351,7 @@ async function resumeSessionByIndex(key, idx, onExpired) {
|
|
|
8000
8351
|
// for the conversation it replaces would send its label into the picked one.
|
|
8001
8352
|
cancelConversationRequest(key);
|
|
8002
8353
|
closeReAskedQuestion(key);
|
|
8354
|
+
closeSetAsideQuestionsInBackground(key);
|
|
8003
8355
|
// Persist the PICKED id — without this the next restart re-attaches to
|
|
8004
8356
|
// whatever id the last fresh start wrote, silently dropping the user's
|
|
8005
8357
|
// pick (live incident 2026-06-10).
|
|
@@ -8405,7 +8757,7 @@ command('schedule', async (ctx, key, parsed) => {
|
|
|
8405
8757
|
await replyToThread(key, result.message);
|
|
8406
8758
|
const isStarting = startupPromptBuffer.checkIsStarting((0, sessionKey_1.keyToString)(key));
|
|
8407
8759
|
const opening = await openTopicRequest(key, wrappedPrompt, { source: 'schedule', requesterId: (0, topicRequest_1.getTopicRequesterId)(ctx.from) });
|
|
8408
|
-
const delivery = await deliverPromptOrBuffer(key, `${opening.header}${wrappedPrompt}`, isStarting);
|
|
8760
|
+
const delivery = await deliverPromptOrBuffer(key, `${opening.header}${wrappedPrompt}`, isStarting, undefined, { isPersonInput: true });
|
|
8409
8761
|
await settleTopicRequestAfterDelivery(key, opening, delivery);
|
|
8410
8762
|
});
|
|
8411
8763
|
const reminderWizards = new Map();
|
|
@@ -8495,7 +8847,7 @@ const botCommands = new Set([
|
|
|
8495
8847
|
'start', 'claude', 'opencode', 'oc', 'terminal', 'agent', 'sessions', 'resume', 'cancel', 'model', 'connect',
|
|
8496
8848
|
'disconnect', 'stop', 'stopall', 'stop-all', 'quit-all', 'status', 'c', 'y', 'n', 'enter', 'up', 'down', 'tab', 'esc', 'escape', 'interrupt', 'output', 'clear_messages',
|
|
8497
8849
|
'bind', 'topic', 'unbind', 'where', 'ls', 'list', 'new', 'whoami', 'version', 'help', 'language', 'lang',
|
|
8498
|
-
'doctor', 'mcp', 'rename_session', 'compact', 'compact_on_idle', 'compact_summary', 'compact_self_review', 'bot_skills', 'task_agents', 'runners', 'auto_continue_limits', 'limits', 'limits_autoswitch', 'trace', 'timestamps', 'timezone', 'schedule', 'reminders', 'todo', 'thinking', 'tool_results',
|
|
8850
|
+
'doctor', 'mcp', 'rename_session', 'compact', 'compact_on_idle', 'compact_summary', 'compact_self_review', 'bot_skills', 'question_wait', 'topic_status', 'task_agents', 'runners', 'auto_continue_limits', 'limits', 'limits_autoswitch', 'trace', 'timestamps', 'timezone', 'schedule', 'reminders', 'todo', 'thinking', 'tool_results',
|
|
8499
8851
|
'subagent', 'claude_mode', 'effort', 'verbosity', 'quit', 'q', 'quitall', 'pair', 'account', 'accounts', 'fallback', 'stt', 'voice', 'speech', 'update', 'access',
|
|
8500
8852
|
]);
|
|
8501
8853
|
/**
|
|
@@ -8552,12 +8904,12 @@ async function handleTalkerText(ctx, key) {
|
|
|
8552
8904
|
return;
|
|
8553
8905
|
}
|
|
8554
8906
|
if (adapter.checkIsActive(key)) {
|
|
8555
|
-
await deliverActivePrompt(key, adapter, text, intake, sentAtMs, messageContext);
|
|
8907
|
+
await deliverActivePrompt(key, adapter, text, intake, sentAtMs, messageContext, { replyToMessageId: (0, inbound_1.getTelegramReplyTargetId)(ctx.message) });
|
|
8556
8908
|
return;
|
|
8557
8909
|
}
|
|
8558
8910
|
// A sleeping conversation is resumed by the message itself, as for anybody (L-D4).
|
|
8559
8911
|
if (await resumeSleepingSessionForPrompt(key)) {
|
|
8560
|
-
await deliverActivePrompt(key, (0, createAdapter_1.getThreadAdapter)(key), text, intake, sentAtMs, messageContext);
|
|
8912
|
+
await deliverActivePrompt(key, (0, createAdapter_1.getThreadAdapter)(key), text, intake, sentAtMs, messageContext, { replyToMessageId: (0, inbound_1.getTelegramReplyTargetId)(ctx.message) });
|
|
8561
8913
|
return;
|
|
8562
8914
|
}
|
|
8563
8915
|
await replyToThread(key, (0, i18n_1.t)('access.noAgentForTalkerNotice'));
|
|
@@ -8577,6 +8929,10 @@ bot.on((0, filters_1.message)('text'), async (ctx) => {
|
|
|
8577
8929
|
if (!speaker)
|
|
8578
8930
|
return;
|
|
8579
8931
|
const { key } = speaker;
|
|
8932
|
+
// A REPLY to a question the bot set aside is its late answer — from the operator and from a topic member alike. It is not a prompt:
|
|
8933
|
+
// it cancels no question that waits now, and reaches the agent as the late-answer message.
|
|
8934
|
+
if (await answerSetAsideQuestionByReply(ctx.from, key, { message_id: ctx.message.message_id, text: ctx.message.text, replyToMessageId: (0, inbound_1.getTelegramReplyTargetId)(ctx.message), isForwarded: (0, inbound_1.checkIsTelegramForward)(ctx.message) }, speaker.role))
|
|
8935
|
+
return;
|
|
8580
8936
|
if (speaker.role === 'talker') {
|
|
8581
8937
|
await handleTalkerText(ctx, key);
|
|
8582
8938
|
return;
|
|
@@ -8712,7 +9068,7 @@ bot.on((0, filters_1.message)('text'), async (ctx) => {
|
|
|
8712
9068
|
}
|
|
8713
9069
|
}
|
|
8714
9070
|
// `/runners` → «Enter another address»: this General message is the address runners dial. A slash command wins over the wait.
|
|
8715
|
-
if (await handleRunnersAddressText(key, text))
|
|
9071
|
+
if (ctx.from !== undefined && (await handleRunnersAddressText(key, text, ctx.from)))
|
|
8716
9072
|
return;
|
|
8717
9073
|
// Session is mid-startup → buffer the prompt and replay it once the agent is
|
|
8718
9074
|
// ready, instead of dropping it into the "no agent running" guidance below.
|
|
@@ -8895,13 +9251,13 @@ bot.on((0, filters_1.message)('text'), async (ctx) => {
|
|
|
8895
9251
|
// REPLY or FORWARD folds its context into the prompt (see `getMessageContext`).
|
|
8896
9252
|
if (adapter.checkIsActive(key)) {
|
|
8897
9253
|
const messageContext = getMessageContext(key, ctx.message);
|
|
8898
|
-
await deliverActivePrompt(key, adapter, text, { source: 'text', requesterId: (0, topicRequest_1.getTopicRequesterId)(ctx.from) }, ctx.message.date * 1000, messageContext);
|
|
9254
|
+
await deliverActivePrompt(key, adapter, text, { source: 'text', requesterId: (0, topicRequest_1.getTopicRequesterId)(ctx.from) }, ctx.message.date * 1000, messageContext, { replyToMessageId: (0, inbound_1.getTelegramReplyTargetId)(ctx.message) });
|
|
8899
9255
|
return;
|
|
8900
9256
|
}
|
|
8901
9257
|
// A sleeping conversation (its process stopped, its session kept) is resumed by
|
|
8902
9258
|
// the message itself (L-D4) — the prompt continues the same conversation.
|
|
8903
9259
|
if (await resumeSleepingSessionForPrompt(key)) {
|
|
8904
|
-
await deliverActivePrompt(key, (0, createAdapter_1.getThreadAdapter)(key), text, { source: 'text', requesterId: (0, topicRequest_1.getTopicRequesterId)(ctx.from) }, ctx.message.date * 1000, getMessageContext(key, ctx.message));
|
|
9260
|
+
await deliverActivePrompt(key, (0, createAdapter_1.getThreadAdapter)(key), text, { source: 'text', requesterId: (0, topicRequest_1.getTopicRequesterId)(ctx.from) }, ctx.message.date * 1000, getMessageContext(key, ctx.message), { replyToMessageId: (0, inbound_1.getTelegramReplyTargetId)(ctx.message) });
|
|
8905
9261
|
return;
|
|
8906
9262
|
}
|
|
8907
9263
|
// Idle thread — guide the user. Three sub-states:
|
|
@@ -8964,8 +9320,10 @@ bot.on((0, filters_1.message)('voice'), async (ctx) => {
|
|
|
8964
9320
|
// clock runs from the voice's arrival, so a voice waiting in line behind an earlier one gets its note too; the job finishes it
|
|
8965
9321
|
// the moment its text arrives, and the `finally` is the backstop for a job that never ran or ended some other way.
|
|
8966
9322
|
const progressNote = startVoiceProgressNote(key);
|
|
9323
|
+
// What the job needs to treat the transcript as a LATE ANSWER when the voice note is a reply to a set-aside question's message.
|
|
9324
|
+
const reply = { from: ctx.from, role: speaker.role, messageId: ctx.message.message_id, replyToMessageId: (0, inbound_1.getTelegramReplyTargetId)(ctx.message) };
|
|
8967
9325
|
void (0, voiceQueue_1.getVoiceTranscriptionQueue)(key)
|
|
8968
|
-
.run(() => processVoiceJob(key, fileId, durationSeconds, (0, topicRequest_1.getTopicRequesterId)(ctx.from), warmedEndpoint, progressNote, sentAtMs, messageContext))
|
|
9326
|
+
.run(() => processVoiceJob(key, fileId, durationSeconds, (0, topicRequest_1.getTopicRequesterId)(ctx.from), warmedEndpoint, progressNote, reply, sentAtMs, messageContext))
|
|
8969
9327
|
.catch((err) => {
|
|
8970
9328
|
console.error('[Bot] Voice job error (already handled):', err);
|
|
8971
9329
|
})
|
|
@@ -8987,9 +9345,10 @@ bot.on((0, filters_1.message)('voice'), async (ctx) => {
|
|
|
8987
9345
|
* (the job reuses that one ask — see `warmUpFirstEngine`), and `progressNote`, the
|
|
8988
9346
|
* «transcribing…» note armed on arrival, which the job finishes as soon as the
|
|
8989
9347
|
* text is here or the voice failed — BEFORE the echo or the failure notice, never
|
|
8990
|
-
* at the end of the job (delivering the prompt may take long).
|
|
9348
|
+
* at the end of the job (delivering the prompt may take long). `reply` says who sent the voice note and what it replies to: a voice reply
|
|
9349
|
+
* to a question the bot set aside is that question's late answer, its transcript the answer (like a typed reply).
|
|
8991
9350
|
*/
|
|
8992
|
-
async function processVoiceJob(key, fileId, durationSeconds, requesterId, warmedEndpoint, progressNote, sentAtMs, messageContext) {
|
|
9351
|
+
async function processVoiceJob(key, fileId, durationSeconds, requesterId, warmedEndpoint, progressNote, reply, sentAtMs, messageContext) {
|
|
8993
9352
|
try {
|
|
8994
9353
|
// Audit S14 / #33: `getFileLink` builds the bot-token URL in one
|
|
8995
9354
|
// place inside Telegraf instead of us materialising the token in a
|
|
@@ -9035,6 +9394,11 @@ async function processVoiceJob(key, fileId, durationSeconds, requesterId, warmed
|
|
|
9035
9394
|
// surfaces immediately instead of queuing behind the thread's streaming
|
|
9036
9395
|
// agent output (which is what made it arrive minutes late under load).
|
|
9037
9396
|
void replyToThread(key, (0, i18n_1.t)('voice.transcribed', { text: transcript }), {}, { unpaced: true }).catch(() => { });
|
|
9397
|
+
// A voice REPLY to a question the bot set aside is its late answer, as a typed reply is: the transcript is the answer (a topic member's
|
|
9398
|
+
// only when it names an option; a forwarded voice note never answers). Taken before any other route, like the typed one — answering the
|
|
9399
|
+
// agent's question is the one thing foreign words may do here.
|
|
9400
|
+
if (await answerSetAsideQuestionByReply(reply.from, key, { message_id: reply.messageId, text: transcript, replyToMessageId: reply.replyToMessageId, isForwarded: messageContext?.isForwarded === true }, reply.role))
|
|
9401
|
+
return;
|
|
9038
9402
|
// `/reminders` step 4 accepts a voice note as well as typed text, so the
|
|
9039
9403
|
// transcript is routed here — right after the 🎤 echo and BEFORE the
|
|
9040
9404
|
// startup-buffer / natural-language-start / binding gates, which would
|
|
@@ -9229,13 +9593,13 @@ async function downloadIncomingFile(ctx, key, meta, onError) {
|
|
|
9229
9593
|
*/
|
|
9230
9594
|
const promptDeliveryDeps = {
|
|
9231
9595
|
startupBuffer: startupPromptBuffer,
|
|
9232
|
-
forwardPrompt: (key, text) => forwardPromptToAgent(key, (0, createAdapter_1.getThreadAdapter)(key), text),
|
|
9596
|
+
forwardPrompt: (key, text, options) => forwardPromptToAgent(key, (0, createAdapter_1.getThreadAdapter)(key), text, undefined, { isPersonInput: options.isPersonInput }),
|
|
9233
9597
|
announceQueued: async (key) => {
|
|
9234
9598
|
await replyToThread(key, (0, i18n_1.t)('agent.queued_starting', { label: (0, createAdapter_1.getThreadAdapter)(key).label }));
|
|
9235
9599
|
},
|
|
9236
9600
|
};
|
|
9237
|
-
function deliverPromptOrBuffer(key, promptText, isStarting, onBufferedSettled) {
|
|
9238
|
-
return (0, promptDelivery_1.deliverPromptOrBuffer)(promptDeliveryDeps, key, promptText, isStarting, onBufferedSettled);
|
|
9601
|
+
function deliverPromptOrBuffer(key, promptText, isStarting, onBufferedSettled, options = {}) {
|
|
9602
|
+
return (0, promptDelivery_1.deliverPromptOrBuffer)(promptDeliveryDeps, key, promptText, isStarting, onBufferedSettled, options);
|
|
9239
9603
|
}
|
|
9240
9604
|
/**
|
|
9241
9605
|
* @description Per-(thread, media_group) album batcher. Telegram delivers an
|
|
@@ -9268,12 +9632,13 @@ const albumCollector = (0, mediaGroupCollector_1.createMediaGroupCollector)({
|
|
|
9268
9632
|
try {
|
|
9269
9633
|
const opening = await openTopicRequest(key, promptText, { source: 'album', requesterId: orderedItems[0].requesterId }, messageContext);
|
|
9270
9634
|
const quotedPrompt = getPromptWithThreadMessageContext(key, promptText, messageContext);
|
|
9271
|
-
const delivery = await deliverPromptOrBuffer(key, `${opening.header}${quotedPrompt}`, isStarting);
|
|
9635
|
+
const delivery = await deliverPromptOrBuffer(key, `${opening.header}${quotedPrompt}`, isStarting, undefined, { isPersonInput: true });
|
|
9272
9636
|
await settleTopicRequestAfterDelivery(key, opening, delivery);
|
|
9273
9637
|
}
|
|
9274
9638
|
catch (err) {
|
|
9639
|
+
// The files were downloaded already (each item before the flush): what failed is the album's prompt.
|
|
9275
9640
|
console.error('[Bot] album flush failed:', err);
|
|
9276
|
-
await replyToThread(key, (0, i18n_1.t)('
|
|
9641
|
+
await replyToThread(key, (0, i18n_1.t)('agent.prompt_not_delivered', { error: err instanceof Error ? err.message : String(err) })).catch(() => { });
|
|
9277
9642
|
}
|
|
9278
9643
|
});
|
|
9279
9644
|
},
|
|
@@ -9353,7 +9718,7 @@ async function handleIncomingFile(ctx, key, isFromTalker) {
|
|
|
9353
9718
|
const messageContext = getMessageContext(key, ctx.message);
|
|
9354
9719
|
const opening = await openTopicRequest(key, promptText, { source: 'file', requesterId: (0, topicRequest_1.getTopicRequesterId)(ctx.from) }, messageContext);
|
|
9355
9720
|
const quotedPrompt = getPromptWithThreadMessageContext(key, promptText, messageContext);
|
|
9356
|
-
const delivery = await deliverPromptOrBuffer(key, `${opening.header}${quotedPrompt}`, isStarting);
|
|
9721
|
+
const delivery = await deliverPromptOrBuffer(key, `${opening.header}${quotedPrompt}`, isStarting, undefined, { isPersonInput: true });
|
|
9357
9722
|
await settleTopicRequestAfterDelivery(key, opening, delivery);
|
|
9358
9723
|
}
|
|
9359
9724
|
bot.on(
|
|
@@ -9525,7 +9890,9 @@ bot.on((0, filters_1.message)('forum_topic_created'), async (ctx) => {
|
|
|
9525
9890
|
/**
|
|
9526
9891
|
* @description A forum topic was renamed (or its icon changed). When the name
|
|
9527
9892
|
* changed, persist it so the thread-context preamble can tell the agent its
|
|
9528
|
-
* current topic name
|
|
9893
|
+
* current topic name — the owner's OWN name: a trailing status mark of the bot's
|
|
9894
|
+
* is cut off it (`getOwnerRenameOutcome`), and the name saved is remembered as the
|
|
9895
|
+
* one the topic shows now. Admin-gated like the created/closed/reopened trio: a
|
|
9529
9896
|
* non-authorised member's rename must not reshape what the bot remembers.
|
|
9530
9897
|
*
|
|
9531
9898
|
* This is also the ONLY way the bot learns the name of a pre-existing topic
|
|
@@ -9541,18 +9908,76 @@ bot.on((0, filters_1.message)('forum_topic_edited'), async (ctx) => {
|
|
|
9541
9908
|
if (!newName)
|
|
9542
9909
|
return;
|
|
9543
9910
|
const userId = ctx.from?.id;
|
|
9911
|
+
// The bot's OWN rename (its status mark) comes back as this service message: never an owner's rename (stored as a name) nor a
|
|
9912
|
+
// stranger's (a `[security]` line) — only a line to delete, so the topic shows no trace of the change.
|
|
9913
|
+
if (userId !== undefined && userId === bot.botInfo?.id) {
|
|
9914
|
+
await topicIndicator.handleOwnRenameLine(key, ctx.message.message_id);
|
|
9915
|
+
return;
|
|
9916
|
+
}
|
|
9544
9917
|
if (!userId || !(await checkIsAllowedUser(ctx))) {
|
|
9545
9918
|
console.warn(`[security] forum_topic_edited in chat ${ctx.chat.id} by user ${userId ?? '?'} (not a group admin) — name not updated`);
|
|
9546
9919
|
return;
|
|
9547
9920
|
}
|
|
9548
|
-
|
|
9549
|
-
|
|
9921
|
+
await applyOwnerTopicRename(key, newName);
|
|
9922
|
+
});
|
|
9923
|
+
/**
|
|
9924
|
+
* @description An authorised sender renamed a topic: what the bot keeps of its name. Shared by the live `forum_topic_edited` update and
|
|
9925
|
+
* the renames read before a cold start drops the waiting updates (`applyRenamesThatWaitedForColdStart`).
|
|
9926
|
+
*/
|
|
9927
|
+
async function applyOwnerTopicRename(key, newName) {
|
|
9928
|
+
const binding = state.getBinding(key);
|
|
9929
|
+
// The owner's own words are what is kept: a trailing mark of the bot's is not part of them (`getOwnerRenameOutcome`).
|
|
9930
|
+
const renamed = (0, topicIndicatorPlan_1.getOwnerRenameOutcome)(newName, binding?.indicatorAppliedName, binding?.topicName, topicIndicator.getRecentAppliedNames(key));
|
|
9931
|
+
if (binding) {
|
|
9932
|
+
// The name saved IS what the topic shows now; the candidate (a guess) is settled by it.
|
|
9933
|
+
await state.setBindingTopicNaming(key, {
|
|
9934
|
+
topicName: renamed.base,
|
|
9935
|
+
topicNameCandidate: null,
|
|
9936
|
+
indicatorAppliedName: newName,
|
|
9937
|
+
indicatorDroppedMark: renamed.droppedMark,
|
|
9938
|
+
});
|
|
9939
|
+
// What the topic shows now is the owner's name (with or without our mark): look at it again.
|
|
9940
|
+
topicIndicator.requestRefresh(key);
|
|
9550
9941
|
}
|
|
9551
9942
|
else {
|
|
9552
9943
|
// No binding yet — keep the freshest name for a later fuzzy auto-bind.
|
|
9553
|
-
pendingTopicNames.set((0, sessionKey_1.keyToString)(key), { name:
|
|
9944
|
+
pendingTopicNames.set((0, sessionKey_1.keyToString)(key), { name: renamed.base, ts: Date.now(), isFromAdmin: true });
|
|
9554
9945
|
}
|
|
9555
|
-
}
|
|
9946
|
+
}
|
|
9947
|
+
/**
|
|
9948
|
+
* @description A COLD start drops the updates that waited while the bot was down, and with them an owner's rename of a topic — the bot
|
|
9949
|
+
* would write the old name plus a mark over it. So they are read once first (`waitingTopicRenames.ts`) and only the renames of bound
|
|
9950
|
+
* topics, by an authorised sender, are applied through {@link applyOwnerTopicRename}; the bot's own «renamed» lines are deleted as a live
|
|
9951
|
+
* one is; everything else is dropped by the launch as before. Never throws: a read that fails is the old behaviour.
|
|
9952
|
+
*/
|
|
9953
|
+
async function applyRenamesThatWaitedForColdStart() {
|
|
9954
|
+
const renames = await (0, waitingTopicRenames_1.readWaitingTopicRenames)((request) => bot.telegram.callApi('getUpdates', request), (error) => console.warn('[boot] reading the topic renames that waited failed — they are dropped with the other updates:', error instanceof Error ? error.message : error), botAllowedUpdates);
|
|
9955
|
+
const botUserId = bot.botInfo?.id ?? (await bot.telegram.getMe()).id;
|
|
9956
|
+
let appliedCount = 0;
|
|
9957
|
+
for (const renamed of renames) {
|
|
9958
|
+
const chat = renamed.chat;
|
|
9959
|
+
const key = getThreadKeyForRoute({
|
|
9960
|
+
chat: { id: chat.id, type: chat.type, is_forum: 'is_forum' in chat ? chat.is_forum : undefined },
|
|
9961
|
+
message: { message_thread_id: renamed.message_thread_id, is_topic_message: renamed.is_topic_message },
|
|
9962
|
+
});
|
|
9963
|
+
if (!key)
|
|
9964
|
+
continue;
|
|
9965
|
+
const senderId = renamed.from?.id;
|
|
9966
|
+
if (senderId !== undefined && senderId === botUserId) {
|
|
9967
|
+
await topicIndicator.handleOwnRenameLine(key, renamed.message_id);
|
|
9968
|
+
continue;
|
|
9969
|
+
}
|
|
9970
|
+
if (!state.getBinding(key))
|
|
9971
|
+
continue;
|
|
9972
|
+
if (!(await checkIsAllowedSender(checkIsOwnerDm(chat), senderId))) {
|
|
9973
|
+
console.warn(`[security] forum_topic_edited in chat ${chat.id} by user ${senderId ?? '?'} (not a group admin) — name not updated`);
|
|
9974
|
+
continue;
|
|
9975
|
+
}
|
|
9976
|
+
await applyOwnerTopicRename(key, renamed.forum_topic_edited.name);
|
|
9977
|
+
appliedCount += 1;
|
|
9978
|
+
}
|
|
9979
|
+
console.log(`Cold start: ${renames.length} topic rename(s) waited while the bot was down, ${appliedCount} applied; the other waiting updates are dropped`);
|
|
9980
|
+
}
|
|
9556
9981
|
// Audit S2 / #5: closed/reopened events can come from a member who isn't an
|
|
9557
9982
|
// authorised user. We deliberately diverge from "trust Telegram's state":
|
|
9558
9983
|
// better to leave our `closed` flag stale than to let a non-authorised user
|
|
@@ -9867,8 +10292,12 @@ bot.action(timezonePicker_1.zonePickCallbackRe, async (ctx) => {
|
|
|
9867
10292
|
});
|
|
9868
10293
|
registerModelCallbacks();
|
|
9869
10294
|
registerCompactionCallbacks();
|
|
10295
|
+
// The buttons of a set-aside question (`qs_<id>_<i>`): disjoint from the live (`qa_`) and the re-asked (`reask_`) ones.
|
|
10296
|
+
registerQuestionSetAsideCallbacks(bot);
|
|
9870
10297
|
registerAutoContinueLimitsCallbacks();
|
|
9871
10298
|
registerBotSkillsCallbacks();
|
|
10299
|
+
registerQuestionWaitCallbacks();
|
|
10300
|
+
registerTopicStatusCallbacks();
|
|
9872
10301
|
registerTopicAccessCallbacks();
|
|
9873
10302
|
registerTaskAgentsCallbacks();
|
|
9874
10303
|
registerRunnersCallbacks();
|
|
@@ -10019,11 +10448,22 @@ bot.action(/^qa_(\d+)_(\d+)$/, async (ctx) => {
|
|
|
10019
10448
|
const qIdx = parseInt(ctx.match[1], 10);
|
|
10020
10449
|
const optIdx = parseInt(ctx.match[2], 10);
|
|
10021
10450
|
const kStr = (0, sessionKey_1.keyToString)(key);
|
|
10451
|
+
// A button still showing on the message of a question the bot SET ASIDE meanwhile (the edit to the `qs_` buttons is paced by the send
|
|
10452
|
+
// gate, or was refused): that question is open and answerable, so the tap answers IT through the set-aside path.
|
|
10453
|
+
if (await answerLiveTapOnSetAsideQuestion(ctx, speaker, qIdx, optIdx))
|
|
10454
|
+
return;
|
|
10022
10455
|
const pending = pendingQuestions.get(kStr);
|
|
10023
10456
|
if (!pending) {
|
|
10024
10457
|
await ctx.answerCbQuery((0, i18n_1.t)('cb.no_pending_question'));
|
|
10025
10458
|
return;
|
|
10026
10459
|
}
|
|
10460
|
+
// A button on a message of a set-aside question that is not the open one is stale: that question is no longer the one waiting, and
|
|
10461
|
+
// its `qa_<i>_<j>` would answer whatever the agent asks next.
|
|
10462
|
+
const tappedMessageId = (0, callbackMessage_1.getCallbackMessageId)(ctx);
|
|
10463
|
+
if (tappedMessageId !== null && checkIsSetAsideQuestionMessage(key, tappedMessageId)) {
|
|
10464
|
+
await ctx.answerCbQuery((0, i18n_1.t)('cb.no_pending_question'));
|
|
10465
|
+
return;
|
|
10466
|
+
}
|
|
10027
10467
|
// A button must belong to the question currently on screen. With sequential
|
|
10028
10468
|
// posting we only ever show `currentIndex`, so a click for any other index is
|
|
10029
10469
|
// a stale button from a question that was already answered/advanced.
|
|
@@ -10072,7 +10512,7 @@ async function bufferPromptDuringStartup(key, text, intake, messageContext) {
|
|
|
10072
10512
|
notePersonActivity(key);
|
|
10073
10513
|
const opening = await openTopicRequest(key, text, intake, messageContext);
|
|
10074
10514
|
const quotedText = getPromptWithThreadMessageContext(key, text, messageContext);
|
|
10075
|
-
await deliverPromptOrBuffer(key, `${opening.header}${quotedText}`, true);
|
|
10515
|
+
await deliverPromptOrBuffer(key, `${opening.header}${quotedText}`, true, undefined, { isPersonInput: true });
|
|
10076
10516
|
trackTopicRequestTurn(key, opening);
|
|
10077
10517
|
}
|
|
10078
10518
|
/**
|
|
@@ -10092,7 +10532,9 @@ async function bufferPromptDuringStartup(key, text, intake, messageContext) {
|
|
|
10092
10532
|
* `answerQuestion`). The tmux-scrape Claude and the terminal never reach it (no `pendingQuestions` entry): for them
|
|
10093
10533
|
* `forwardPromptToAgent` interrupts the TUI selector itself.
|
|
10094
10534
|
*/
|
|
10095
|
-
async function deliverActivePrompt(key, adapter, text, intake, sentAtMs, messageContext
|
|
10535
|
+
async function deliverActivePrompt(key, adapter, text, intake, sentAtMs, messageContext,
|
|
10536
|
+
/** `replyToMessageId`: the message the text is genuinely a reply to (`getTelegramReplyTargetId`), `null` for none. */
|
|
10537
|
+
options = {}) {
|
|
10096
10538
|
// A FORWARDED message is content, never control input: it answers no question and purges no context, whatever its words are.
|
|
10097
10539
|
// A topic member's words are not the operator's either — but a bare option number of theirs DOES answer the agent's question
|
|
10098
10540
|
// (members may answer questions, the one thing foreign words may do here), so the two answer routes below ask `isForwarded`
|
|
@@ -10107,9 +10549,14 @@ async function deliverActivePrompt(key, adapter, text, intake, sentAtMs, message
|
|
|
10107
10549
|
notePersonActivity(key);
|
|
10108
10550
|
const pending = pendingQuestions.get((0, sessionKey_1.keyToString)(key));
|
|
10109
10551
|
if (pending && adapter.answerQuestion) {
|
|
10552
|
+
// A REPLY to a message other than the question that waits NOW (one that was answered, closed or set aside, or any other message)
|
|
10553
|
+
// is not a response to this question: no number in it is a pick — «2» typed as a reply to an old question's message would answer
|
|
10554
|
+
// the one the owner never looked at. Its words still move the agent on like any text: below, they cancel the waiting question.
|
|
10555
|
+
const { replyToMessageId } = options;
|
|
10556
|
+
const isReplyToAnotherMessage = replyToMessageId != null && replyToMessageId !== pending.messageId && replyToMessageId !== pending.originalMessageId;
|
|
10110
10557
|
const currentQuestion = pending.data.questions[pending.currentIndex];
|
|
10111
10558
|
const route = (0, openCodeQuestionFlow_1.getQuestionReplyRoute)(text, currentQuestion);
|
|
10112
|
-
if (route.kind === 'answer' && !isForwarded) {
|
|
10559
|
+
if (route.kind === 'answer' && !isForwarded && !isReplyToAnotherMessage) {
|
|
10113
10560
|
// Answering a pending question (bare digit) is a pick, not a prompt about
|
|
10114
10561
|
// the quote — the reply context is deliberately dropped here. Not a request
|
|
10115
10562
|
// either: the turn it unblocks continues under the open one. A forwarded digit
|
|
@@ -10144,6 +10591,15 @@ async function deliverActivePrompt(key, adapter, text, intake, sentAtMs, message
|
|
|
10144
10591
|
adapter.sendSignal(key, 'SIGINT');
|
|
10145
10592
|
await replyToThread(key, (0, i18n_1.t)('agent.question_cancelled_for_prompt'));
|
|
10146
10593
|
}
|
|
10594
|
+
return deliverPromptByState(key, adapter, text, intake, sentAtMs, messageContext);
|
|
10595
|
+
}
|
|
10596
|
+
/**
|
|
10597
|
+
* @description The end of {@link deliverActivePrompt}, shared with the delivery of a late answer ({@link deliverLateAnswerPrompt}): open
|
|
10598
|
+
* the request the prompt belongs to (none for `intake` null — an answer to the agent's own question is never a request), deliver it by
|
|
10599
|
+
* the state of the session NOW — buffered behind a start, waking a sleeping conversation, or forwarded to the live one — and settle
|
|
10600
|
+
* the request. It touches no pending question and no wedged turn: that is the caller's.
|
|
10601
|
+
*/
|
|
10602
|
+
async function deliverPromptByState(key, adapter, text, intake, sentAtMs, messageContext) {
|
|
10147
10603
|
// The request (S7) is opened AFTER the user takeover cancelled an armed limit
|
|
10148
10604
|
// wait (the handlers' `cancelApiRetry`) and before the forward, so its id is
|
|
10149
10605
|
// durable by the time the agent reads it.
|
|
@@ -10155,10 +10611,10 @@ async function deliverActivePrompt(key, adapter, text, intake, sentAtMs, message
|
|
|
10155
10611
|
checkIsWindowOpen: () => startupPromptBuffer.checkIsStarting((0, sessionKey_1.keyToString)(key)),
|
|
10156
10612
|
checkIsSessionActive: () => adapter.checkIsActive(key),
|
|
10157
10613
|
buffer: async () => {
|
|
10158
|
-
await deliverPromptOrBuffer(key, `${opening.header}${getPromptWithThreadMessageContext(key, text, messageContext)}`, true);
|
|
10614
|
+
await deliverPromptOrBuffer(key, `${opening.header}${getPromptWithThreadMessageContext(key, text, messageContext)}`, true, undefined, { isPersonInput: true });
|
|
10159
10615
|
},
|
|
10160
10616
|
wake: () => wakeSleepingSessionForPrompt(key),
|
|
10161
|
-
forward: () => forwardPromptToAgent(key, (0, createAdapter_1.getThreadAdapter)(key), text, sentAtMs, { messageContext, requestHeader: opening.header }),
|
|
10617
|
+
forward: () => forwardPromptToAgent(key, (0, createAdapter_1.getThreadAdapter)(key), text, sentAtMs, { messageContext, requestHeader: opening.header, isPersonInput: true }),
|
|
10162
10618
|
reportNoSession: async (isAlreadyTold) => {
|
|
10163
10619
|
if (!isAlreadyTold)
|
|
10164
10620
|
await replyToThread(key, (0, i18n_1.t)('agent.no_session'));
|
|
@@ -10167,6 +10623,22 @@ async function deliverActivePrompt(key, adapter, text, intake, sentAtMs, message
|
|
|
10167
10623
|
await settleTopicRequestAfterDelivery(key, opening, outcome);
|
|
10168
10624
|
return outcome;
|
|
10169
10625
|
}
|
|
10626
|
+
/**
|
|
10627
|
+
* @description Deliver a LATE ANSWER to the agent — what the owner chose for a question the bot set aside, worded by
|
|
10628
|
+
* `buildLateAnswerPrompt` — as a message of the owner's: written to a live session behind whatever it is doing, buffered behind a
|
|
10629
|
+
* start, or waking a sleeping conversation. Unlike {@link deliverActivePrompt} it is NOT free text for the question the agent may be
|
|
10630
|
+
* waiting on NOW (that one is a different question, and the owner has not answered it): it never cancels it and never aborts a
|
|
10631
|
+
* wedged turn. It cancels an armed usage-limit wait first, as typed text does. It carries no message context: the text is the bot's
|
|
10632
|
+
* block, and a topic member's answer says who gave it inside the answer itself (an author mark ahead of it would end at the block's
|
|
10633
|
+
* own header).
|
|
10634
|
+
*/
|
|
10635
|
+
async function deliverLateAnswerPrompt(key, text) {
|
|
10636
|
+
// The owner took over, like with any message they type: an armed usage-limit wait is over (the answer is not written INTO it, and its
|
|
10637
|
+
// own «continue» nudge would come on top of the answer later).
|
|
10638
|
+
cancelApiRetry(key);
|
|
10639
|
+
noteThreadUserActivity(key);
|
|
10640
|
+
return deliverPromptByState(key, (0, createAdapter_1.getThreadAdapter)(key), text, null);
|
|
10641
|
+
}
|
|
10170
10642
|
/**
|
|
10171
10643
|
* @description Close the on-screen state of a pending question that ends without an answer: clear the bot's
|
|
10172
10644
|
* pending-question state (which unpins it) and edit the question's message so its buttons are gone and a note says that
|
|
@@ -10225,7 +10697,7 @@ async function cancelPendingQuestionAndForward(key, adapter, text, sentAtMs, mes
|
|
|
10225
10697
|
if (!didLabelQuestionMessage) {
|
|
10226
10698
|
await replyToThread(key, (0, i18n_1.t)('agent.question_cancelled_for_prompt'));
|
|
10227
10699
|
}
|
|
10228
|
-
return forwardPromptToAgent(key, adapter, text, sentAtMs, { messageContext, requestHeader });
|
|
10700
|
+
return forwardPromptToAgent(key, adapter, text, sentAtMs, { messageContext, requestHeader, isPersonInput: true });
|
|
10229
10701
|
}
|
|
10230
10702
|
/**
|
|
10231
10703
|
* @description Record one answer for the CURRENTLY shown OpenCode question and
|
|
@@ -10255,7 +10727,7 @@ async function applyQuestionAnswerInner(key, answerForCurrent, answeredBy) {
|
|
|
10255
10727
|
const { nextState, action } = (0, openCodeQuestionFlow_1.recordAnswerAndAdvance)(pending, answeredBy === undefined ? answerForCurrent : (0, authorMark_1.getAnswerWithAttribution)(answerForCurrent, answeredBy));
|
|
10256
10728
|
// Mark the answered question's message as done: the question stays as asked, the chosen answer takes the place of
|
|
10257
10729
|
// its buttons.
|
|
10258
|
-
const isAnswerShown = pending.messageId !== null && answeredQuestion !== undefined && await
|
|
10730
|
+
const isAnswerShown = pending.messageId !== null && answeredQuestion !== undefined && await editQuestionMessageWithNote(key, pending.messageId, answeredQuestion, (0, i18n_1.t)('agent.question_answered_note', { answer: answerForCurrent.join(', ') }));
|
|
10259
10731
|
if (action.kind === 'submit') {
|
|
10260
10732
|
const adapter = (0, createAdapter_1.getThreadAdapter)(key);
|
|
10261
10733
|
clearPendingQuestion(key);
|
|
@@ -11295,6 +11767,22 @@ function handleSubagentStatus(key, payload) {
|
|
|
11295
11767
|
}
|
|
11296
11768
|
})();
|
|
11297
11769
|
}
|
|
11770
|
+
/**
|
|
11771
|
+
* @description The question wait changed (`/question_wait`): the questions that wait now are timed again from the moment each was
|
|
11772
|
+
* asked — one conversation's (`key`), or, when the instance value changed, every waiting one (those that follow it get a new moment,
|
|
11773
|
+
* the others keep theirs). A wait that is already over sets the question aside at once; «Wait for my answer» takes the timer off.
|
|
11774
|
+
*/
|
|
11775
|
+
function rearmQuestionSetAsideTimers(key) {
|
|
11776
|
+
if (key !== null) {
|
|
11777
|
+
armQuestionSetAsideTimer(key);
|
|
11778
|
+
return;
|
|
11779
|
+
}
|
|
11780
|
+
for (const keyString of pendingQuestions.keys()) {
|
|
11781
|
+
const pendingKey = (0, sessionKey_1.tryKeyFromString)(keyString);
|
|
11782
|
+
if (pendingKey)
|
|
11783
|
+
armQuestionSetAsideTimer(pendingKey);
|
|
11784
|
+
}
|
|
11785
|
+
}
|
|
11298
11786
|
function handleAgentQuestion(key, questionData) {
|
|
11299
11787
|
console.log(`[Bot] question ${(0, sessionKey_1.keyToString)(key)} (${questionData.requestId}): ${questionData.questions.length}`);
|
|
11300
11788
|
// Idempotent across restart: this handler ALSO fires from the adapter's
|
|
@@ -11310,6 +11798,16 @@ function handleAgentQuestion(key, questionData) {
|
|
|
11310
11798
|
if (persistedQuestion && persistedQuestion.data.requestId === questionData.requestId) {
|
|
11311
11799
|
return;
|
|
11312
11800
|
}
|
|
11801
|
+
// A question whose set-aside copy is still open in the topic is not posted again: the agent is told it is the same one.
|
|
11802
|
+
if (answerQuestionAskedAgain(key, questionData))
|
|
11803
|
+
return;
|
|
11804
|
+
postAgentQuestion(key, questionData);
|
|
11805
|
+
}
|
|
11806
|
+
/**
|
|
11807
|
+
* @description Put a question the agent asked to the topic as the one that WAITS: the question UI takes over from the agent's
|
|
11808
|
+
* status, the message is posted (and pinned) in the lifecycle queue, and the question wait starts.
|
|
11809
|
+
*/
|
|
11810
|
+
function postAgentQuestion(key, questionData) {
|
|
11313
11811
|
// The agent asks anew: a question the idle compaction re-asked earlier is superseded, and its buttons would now answer
|
|
11314
11812
|
// the wrong question — it is closed as unanswered.
|
|
11315
11813
|
closeReAskedQuestion(key);
|
|
@@ -11351,12 +11849,29 @@ function handleAgentQuestion(key, questionData) {
|
|
|
11351
11849
|
messageId: null,
|
|
11352
11850
|
answers: new Array(questionData.questions.length).fill(null),
|
|
11353
11851
|
currentIndex: 0,
|
|
11852
|
+
askedAt: Date.now(),
|
|
11354
11853
|
});
|
|
11854
|
+
// The question waits for the owner only for the question wait: then the agent is told to go on without it.
|
|
11855
|
+
armQuestionSetAsideTimer(key);
|
|
11355
11856
|
void runQuestionLifecycleOp(key, async () => {
|
|
11356
11857
|
await streamedOutputLanding;
|
|
11357
11858
|
await postPendingQuestionAt(key);
|
|
11358
11859
|
});
|
|
11359
11860
|
}
|
|
11861
|
+
/**
|
|
11862
|
+
* @description Post a question as a NEW message of the topic — its text (header, question, numbered options with their descriptions)
|
|
11863
|
+
* with `keyboard` as its buttons. Resolves the id of the message, `null` when no send landed.
|
|
11864
|
+
*
|
|
11865
|
+
* Markdown first, then plain when Telegram refuses it. Only a post that FAILED is retried: one whose outcome is unknown may already
|
|
11866
|
+
* be in the topic, and a second copy of the question would be posted under it (its id stays unknown; its buttons still answer it).
|
|
11867
|
+
*/
|
|
11868
|
+
async function sendQuestionMessage(key, question, keyboard) {
|
|
11869
|
+
let outcome = await replyToThreadDetailed(key, (0, openCodeQuestionFlow_1.buildQuestionBodyLines)(question, escapeMarkdown).join('\n'), (0, questionKeyboards_1.buildKeyboardExtra)(keyboard, { parse_mode: 'Markdown' }));
|
|
11870
|
+
if (outcome.kind === 'failed') {
|
|
11871
|
+
outcome = await replyToThreadDetailed(key, (0, openCodeQuestionFlow_1.buildQuestionBodyLinesPlain)(question).join('\n'), (0, questionKeyboards_1.buildKeyboardExtra)(keyboard));
|
|
11872
|
+
}
|
|
11873
|
+
return outcome.kind === 'sent' ? outcome.messageId : null;
|
|
11874
|
+
}
|
|
11360
11875
|
/**
|
|
11361
11876
|
* @description Render + send ONE OpenCode question (the one at the pending
|
|
11362
11877
|
* state's `currentIndex`) as the newest thread message, then patch the
|
|
@@ -11418,13 +11933,7 @@ async function postPendingQuestionAt(key) {
|
|
|
11418
11933
|
? (0, questionKeyboards_1.buildQuestionOptionsKeyboard)(question, (optionIndex) => `qa_${qIdx}_${optionIndex}`)
|
|
11419
11934
|
: undefined;
|
|
11420
11935
|
try {
|
|
11421
|
-
|
|
11422
|
-
// Markdown rejected — retry plain. Only a post that FAILED: one whose outcome is unknown may already be in the topic, and a
|
|
11423
|
-
// second copy of the question would be posted under it (its id stays unknown; its buttons still answer it).
|
|
11424
|
-
if (outcome.kind === 'failed') {
|
|
11425
|
-
outcome = await replyToThreadDetailed(key, (0, openCodeQuestionFlow_1.buildQuestionBodyLinesPlain)(question).join('\n'), (0, questionKeyboards_1.buildKeyboardExtra)(keyboard));
|
|
11426
|
-
}
|
|
11427
|
-
const messageId = outcome.kind === 'sent' ? outcome.messageId : null;
|
|
11936
|
+
const messageId = await sendQuestionMessage(key, question, keyboard);
|
|
11428
11937
|
if (messageId !== null) {
|
|
11429
11938
|
// Patch the messageId on the existing entry (it may already have been
|
|
11430
11939
|
// cleared/advanced by an answer callback firing in between). Route
|
|
@@ -11494,6 +12003,8 @@ function handleAgentClosed(key) {
|
|
|
11494
12003
|
// A closed session has nothing to resume — drop any armed retry silently.
|
|
11495
12004
|
cancelApiRetry(key);
|
|
11496
12005
|
clearAuthNotice(key); // session closed → retire any pinned logged-out notice
|
|
12006
|
+
// The process died on its own: the topic's name says stuck until the next turn (the banner refresh below asks for the mark).
|
|
12007
|
+
topicsStuckUntilNextTurn.add((0, sessionKey_1.keyToString)(key));
|
|
11497
12008
|
// A closed session has nothing to compact — drop the idle watchdog + any arm.
|
|
11498
12009
|
clearThreadCompaction(key);
|
|
11499
12010
|
const adapter = (0, createAdapter_1.getThreadAdapter)(key);
|
|
@@ -11551,10 +12062,16 @@ async function noteLostWork(key, lostWork, reason) {
|
|
|
11551
12062
|
reason,
|
|
11552
12063
|
isLimitWaitArmed,
|
|
11553
12064
|
msSinceLastAutoResume: lastAutoResumeAt === undefined ? null : now - lastAutoResumeAt,
|
|
11554
|
-
// A tracker issue's agent answers only through a request: a bare note would have nowhere to answer.
|
|
12065
|
+
// A tracker issue's agent answers only through a request: a bare note would have nowhere to answer — its open request is woken instead.
|
|
11555
12066
|
isRequestRequired: !(0, sessionKeyCodec_1.checkIsTelegramKey)(key),
|
|
12067
|
+
hasOpenRequest: (topicRequestLedger?.listOpenRequestsOf(key).length ?? 0) > 0,
|
|
11556
12068
|
});
|
|
11557
|
-
|
|
12069
|
+
let planText = plan.isAutoResume ? 'resuming it with a note' : 'the note rides the next prompt';
|
|
12070
|
+
if (plan.isRequestWake)
|
|
12071
|
+
planText = 'its open request is woken, and the note rides that wake';
|
|
12072
|
+
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}`);
|
|
12073
|
+
if (plan.isRequestWake)
|
|
12074
|
+
scheduleTrackerRestartWake(key, `its process ended (${reason}) with its own work pending`);
|
|
11558
12075
|
let linePlan = plan;
|
|
11559
12076
|
if (plan.isAutoResume) {
|
|
11560
12077
|
await state.setLostWorkResumedAt(key, now);
|
|
@@ -11565,6 +12082,43 @@ async function noteLostWork(key, lostWork, reason) {
|
|
|
11565
12082
|
if ((0, sessionKeyCodec_1.checkIsTelegramKey)(key))
|
|
11566
12083
|
replyToThread(key, (0, lostWork_1.formatLostWorkTopicLine)(record, linePlan, pendingWorkHoldHours, i18n_1.t)).catch(() => { });
|
|
11567
12084
|
}
|
|
12085
|
+
/**
|
|
12086
|
+
* @description Wake the open requests of a tracker conversation whose process is gone — `restarted`, staggered by the
|
|
12087
|
+
* wake-up engine — instead of leaving them to the 90-minute backstop. A Telegram topic resumes through its own
|
|
12088
|
+
* lost-work path and is never woken here. The lost-work cooldown guards it as well: a conversation woken
|
|
12089
|
+
* automatically within it is left to the backstop, so a crash loop is no wake loop.
|
|
12090
|
+
*/
|
|
12091
|
+
function scheduleTrackerRestartWake(key, why) {
|
|
12092
|
+
if ((0, sessionKeyCodec_1.checkIsTelegramKey)(key) || !requestWakeUpEngine)
|
|
12093
|
+
return;
|
|
12094
|
+
const lastAutoResumeAt = state.getLostWorkResumedAt(key);
|
|
12095
|
+
if (lastAutoResumeAt !== undefined && Date.now() - lastAutoResumeAt < lostWork_1.lostWorkResumeCooldownMs) {
|
|
12096
|
+
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`);
|
|
12097
|
+
return;
|
|
12098
|
+
}
|
|
12099
|
+
if (requestWakeUpEngine.scheduleRestartWake(key))
|
|
12100
|
+
console.log(`[requests] ${(0, sessionKey_1.keyToString)(key)}: ${why}; its open request is woken shortly`);
|
|
12101
|
+
}
|
|
12102
|
+
/**
|
|
12103
|
+
* @description The boot's pass over the open requests of tracker conversations: one whose process did not come back
|
|
12104
|
+
* with the boot (not adopted — the conversation sleeps) and that waits for nothing of its own — no post retry, no
|
|
12105
|
+
* progress follow-up, no armed usage-limit wait, not given up — is woken `restarted` ({@link scheduleTrackerRestartWake}).
|
|
12106
|
+
* A process that died with its own work pending is in it too: its lost-work note rides the same wake.
|
|
12107
|
+
*/
|
|
12108
|
+
function scheduleRestartWakesAtBoot(requestLedger) {
|
|
12109
|
+
const keys = new Map();
|
|
12110
|
+
for (const { key, request } of requestLedger.listOpenRequests()) {
|
|
12111
|
+
if ((0, sessionKeyCodec_1.checkIsTelegramKey)(key) || keys.has((0, sessionKey_1.keyToString)(key)))
|
|
12112
|
+
continue;
|
|
12113
|
+
if ((0, wakeUpRules_1.checkIsWakingStopped)(request) || request.nextPostRetryAt !== undefined || request.nextWakeAt !== undefined)
|
|
12114
|
+
continue;
|
|
12115
|
+
if ((0, createAdapter_1.getThreadAdapter)(key).checkIsActive(key) || getArmedApiRetry(key)?.kind === 'usageLimit')
|
|
12116
|
+
continue;
|
|
12117
|
+
keys.set((0, sessionKey_1.keyToString)(key), key);
|
|
12118
|
+
}
|
|
12119
|
+
for (const key of keys.values())
|
|
12120
|
+
scheduleTrackerRestartWake(key, 'its session did not come back with the boot while a request was open');
|
|
12121
|
+
}
|
|
11568
12122
|
/**
|
|
11569
12123
|
* @description Resume the conversation with the lost-work note as its prompt; `false` when the post failed — the note
|
|
11570
12124
|
* then stays for the next prompt.
|
|
@@ -11586,12 +12140,35 @@ function createLostWorkPostDeps() {
|
|
|
11586
12140
|
return {
|
|
11587
12141
|
...createSessionPostDeps(),
|
|
11588
12142
|
forwardPrompt: async (conversationKey, text) => {
|
|
11589
|
-
|
|
12143
|
+
const buffered = createBufferedOutcome();
|
|
12144
|
+
const delivery = await deliverPromptOrBuffer((0, sessionKey_1.keyFromString)(conversationKey), text, startupPromptBuffer.checkIsStarting(conversationKey), buffered.settle);
|
|
12145
|
+
if (delivery === 'buffered')
|
|
12146
|
+
await buffered.assertReplayed();
|
|
12147
|
+
},
|
|
12148
|
+
};
|
|
12149
|
+
}
|
|
12150
|
+
/**
|
|
12151
|
+
* @description How a prompt that waited in the startup buffer ended, for a post that must know it reached the session:
|
|
12152
|
+
* `settle` is the buffer's callback, `assertReplayed` resolves once it was replayed into the session and rejects when it
|
|
12153
|
+
* was dropped — the start failed, or its write did not reach the agent.
|
|
12154
|
+
*/
|
|
12155
|
+
function createBufferedOutcome() {
|
|
12156
|
+
let settle = () => { };
|
|
12157
|
+
const outcome = new Promise((resolve) => {
|
|
12158
|
+
settle = resolve;
|
|
12159
|
+
});
|
|
12160
|
+
return {
|
|
12161
|
+
settle: (result) => settle(result),
|
|
12162
|
+
assertReplayed: async () => {
|
|
12163
|
+
if ((await outcome) !== 'replayed')
|
|
12164
|
+
throw new Error('the prompt waited for the session to start and never reached the agent');
|
|
11590
12165
|
},
|
|
11591
12166
|
};
|
|
11592
12167
|
}
|
|
11593
12168
|
function handleAgentError(key, error) {
|
|
11594
12169
|
console.error(`[Bot] adapter error ${(0, sessionKey_1.keyToString)(key)}:`, error.message);
|
|
12170
|
+
topicsStuckUntilNextTurn.add((0, sessionKey_1.keyToString)(key));
|
|
12171
|
+
topicIndicator.requestRefresh(key);
|
|
11595
12172
|
stopClaudeLiveness(key);
|
|
11596
12173
|
supersedeStatusFrames(key);
|
|
11597
12174
|
deleteStatusMessage(key).catch(() => { });
|
|
@@ -11680,6 +12257,8 @@ function handleAgentStopped(key) {
|
|
|
11680
12257
|
* never told it.
|
|
11681
12258
|
*/
|
|
11682
12259
|
function handleConversationLost(key) {
|
|
12260
|
+
topicsStuckUntilNextTurn.add((0, sessionKey_1.keyToString)(key));
|
|
12261
|
+
topicIndicator.requestRefresh(key);
|
|
11683
12262
|
dropLostConversationWatermark(key);
|
|
11684
12263
|
clearThreadContextMarker(key);
|
|
11685
12264
|
replyToThread(key, (0, i18n_1.t)('agent.resume_failed_fresh')).catch(() => { });
|
|
@@ -11739,6 +12318,8 @@ exports.COMMANDS_MENU = [
|
|
|
11739
12318
|
{ command: 'compact_summary', description: '📄 Post the compaction summary (toggle)' },
|
|
11740
12319
|
{ command: 'compact_self_review', description: '💡 Agent self-review on compaction: its mistakes and what to change in its instructions' },
|
|
11741
12320
|
{ command: 'bot_skills', description: '🧰 The bot\'s own skills for agents (on/off)' },
|
|
12321
|
+
{ command: 'question_wait', description: '⏳ How long the agent waits for your answer to its question' },
|
|
12322
|
+
{ command: 'topic_status', description: '❓ Marks at the end of topic names: question, working, finished, asleep' },
|
|
11742
12323
|
{ command: 'task_agents', description: '🧵 How many tracker task agents work at once' },
|
|
11743
12324
|
{ command: 'runners', description: '🖥 Runners — machines for the agents\' tests and builds' },
|
|
11744
12325
|
{ command: 'accounts', description: '👤 Claude accounts and OpenCode providers (switch, add, re-login, remove, connect, disconnect)' },
|
|
@@ -12235,6 +12816,8 @@ function restorePendingQuestions() {
|
|
|
12235
12816
|
// handlers. Migrate to the new shape and re-persist so disk catches up.
|
|
12236
12817
|
const migrated = (0, openCodeQuestionFlow_1.migratePendingQuestionState)(value);
|
|
12237
12818
|
setPendingQuestion(key, migrated);
|
|
12819
|
+
// The rest of its wait, counted from when it was asked — not a new one.
|
|
12820
|
+
armQuestionSetAsideTimer(key);
|
|
12238
12821
|
restored += 1;
|
|
12239
12822
|
}
|
|
12240
12823
|
else {
|
|
@@ -12252,6 +12835,28 @@ function restorePendingQuestions() {
|
|
|
12252
12835
|
}
|
|
12253
12836
|
console.log(`[reattach] pending questions: restored ${restored}, dropped ${dropped}`);
|
|
12254
12837
|
}
|
|
12838
|
+
/**
|
|
12839
|
+
* @description Boot: the questions the bot set aside keep their buttons while their conversation can still be resumed (a live
|
|
12840
|
+
* adopted process, or a sleeping conversation whose id is kept — a late answer wakes it); those of a conversation that was released
|
|
12841
|
+
* while the bot was down end as «not answered», their pins released. MUST run AFTER {@link reattachExistingSessions} so session
|
|
12842
|
+
* activity is known. A platform this instance does not serve is left alone, like {@link restorePendingQuestions}.
|
|
12843
|
+
*/
|
|
12844
|
+
function restoreSetAsideQuestions() {
|
|
12845
|
+
for (const keyStr of Object.keys(state.getSetAsideQuestions())) {
|
|
12846
|
+
let key;
|
|
12847
|
+
try {
|
|
12848
|
+
key = (0, sessionKey_1.keyFromString)(keyStr);
|
|
12849
|
+
}
|
|
12850
|
+
catch {
|
|
12851
|
+
continue;
|
|
12852
|
+
}
|
|
12853
|
+
if (!(0, connectorSet_1.checkIsServedConversation)(key, ENV.servedPlatforms))
|
|
12854
|
+
continue;
|
|
12855
|
+
if ((0, createAdapter_1.getThreadAdapter)(key).checkIsActive(key) || getResumableSessionId(key) !== null)
|
|
12856
|
+
continue;
|
|
12857
|
+
closeSetAsideQuestionsInBackground(key);
|
|
12858
|
+
}
|
|
12859
|
+
}
|
|
12255
12860
|
/**
|
|
12256
12861
|
* @description Bring back the questions the idle compaction re-asked, at boot. One whose conversation can still be
|
|
12257
12862
|
* resumed (a live adopted process, or a sleeping conversation whose id is kept) gets its buttons working again — a tap
|
|
@@ -12824,8 +13429,12 @@ function createSessionPostDeps() {
|
|
|
12824
13429
|
// A scheduled run in a topic with requests on is a request (S7); a tracker's
|
|
12825
13430
|
// post arrives with its request already open and its header in the text.
|
|
12826
13431
|
const opening = await openTopicRequest(key, text, { source: 'scheduledRun', requesterId: topicRequest_1.scheduledRunRequester });
|
|
12827
|
-
const
|
|
13432
|
+
const buffered = createBufferedOutcome();
|
|
13433
|
+
const delivery = await deliverPromptOrBuffer(key, `${opening.header}${text}`, startupPromptBuffer.checkIsStarting(conversationKey), buffered.settle);
|
|
12828
13434
|
await settleTopicRequestAfterDelivery(key, opening, delivery);
|
|
13435
|
+
// A prompt that waited for the session's start counts only once it reached it: a replay whose write failed is a failed post.
|
|
13436
|
+
if (delivery === 'buffered')
|
|
13437
|
+
await buffered.assertReplayed();
|
|
12829
13438
|
},
|
|
12830
13439
|
now: () => Date.now(),
|
|
12831
13440
|
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
@@ -13211,6 +13820,15 @@ function createJiraSessionDeps(requestLedger, slots, adapterName) {
|
|
|
13211
13820
|
if (!posted.isHeld)
|
|
13212
13821
|
await requestWakeUpEngine?.trackForwardedTurn(key, requestId, { isRequestPrompt: true });
|
|
13213
13822
|
},
|
|
13823
|
+
// An issue update (a comment for an open hand-over request) opens no request: the turn it starts is that request's.
|
|
13824
|
+
postUpdate: async (key, prompt, getTargetRequestId) => {
|
|
13825
|
+
notePersonActivity(key);
|
|
13826
|
+
const posted = await (0, postToSession_1.postToSession)(sessionPostDeps, (0, sessionKey_1.keyToString)(key), prompt, adapterName);
|
|
13827
|
+
if (!posted.ok)
|
|
13828
|
+
throw new Error(posted.reason === 'forward-failed' ? posted.error : `session ${posted.reason}`);
|
|
13829
|
+
if (!posted.isHeld)
|
|
13830
|
+
await requestWakeUpEngine?.trackForwardedTurn(key, getTargetRequestId());
|
|
13831
|
+
},
|
|
13214
13832
|
};
|
|
13215
13833
|
}
|
|
13216
13834
|
async function startBot() {
|
|
@@ -13226,6 +13844,8 @@ async function startBot() {
|
|
|
13226
13844
|
// docs/troubleshooting.md's two-instances section tells the operator to compare this
|
|
13227
13845
|
// exact line across instances.
|
|
13228
13846
|
state = await (0, state_1.getStateStore)({ saveDebounceMs: ENV.testTimings.stateSaveDebounceMs });
|
|
13847
|
+
// A watched worker created, ended or paused, a question set aside or closed: the topic's name follows.
|
|
13848
|
+
state.setStatusSourceChangeListener((key) => topicIndicator.requestRefresh(key));
|
|
13229
13849
|
console.log(`[startup] DATA_DIR=${path.dirname(state.stateFilePath)}`);
|
|
13230
13850
|
// R13: before anything reads, rewrites or acts on the state, it must hold only
|
|
13231
13851
|
// conversations of the platforms this instance serves.
|
|
@@ -13319,6 +13939,11 @@ async function startBot() {
|
|
|
13319
13939
|
return result.ok ? (result.alertRef ?? null) : null;
|
|
13320
13940
|
},
|
|
13321
13941
|
backstopMs: (0, wakeUpRules_1.getRequestBackstopMs)(process.env.REQUEST_BACKSTOP_MINUTES),
|
|
13942
|
+
restartWakeStaggerMs: ENV.testTimings.requestRestartWakeStaggerMs,
|
|
13943
|
+
// The stamp of the lost-work cooldown: a conversation woken after a restart is not woken so again within it.
|
|
13944
|
+
noteRestartWakeDelivered: (key) => {
|
|
13945
|
+
void state.setLostWorkResumedAt(key, Date.now());
|
|
13946
|
+
},
|
|
13322
13947
|
pollIntervalMs: ENV.testTimings.requestTurnPollMs,
|
|
13323
13948
|
sweepIntervalMs: ENV.testTimings.requestSweepIntervalMs,
|
|
13324
13949
|
firstPostRetryDelayMs: ENV.testTimings.requestFirstPostRetryDelayMs,
|
|
@@ -13404,6 +14029,9 @@ async function startBot() {
|
|
|
13404
14029
|
// Output means a turn is under way — the wake-up engine's busy-onset signal, and the todo reminder's.
|
|
13405
14030
|
requestWakeUpEngine?.noteAgentOutput(key);
|
|
13406
14031
|
todoReminderEngine?.noteAgentOutput(key);
|
|
14032
|
+
// …and the topic's name shows it: an agent that went wrong is no longer stuck once a turn runs.
|
|
14033
|
+
topicsStuckUntilNextTurn.delete((0, sessionKey_1.keyToString)(key));
|
|
14034
|
+
topicIndicator.requestRefresh(key);
|
|
13407
14035
|
};
|
|
13408
14036
|
(0, createAdapter_1.registerAdapterEventHandlers)({
|
|
13409
14037
|
onOutput: (key, output, meta) => (0, adapterEventRouting_1.dispatchAdapterEvent)(key, 'output', () => {
|
|
@@ -13421,7 +14049,11 @@ async function startBot() {
|
|
|
13421
14049
|
markThreadTurnProducedOutput(key);
|
|
13422
14050
|
noteThreadActivity(key);
|
|
13423
14051
|
}),
|
|
13424
|
-
onStatus: (key, status) => (0, adapterEventRouting_1.dispatchAdapterEvent)(key, 'status', () =>
|
|
14052
|
+
onStatus: (key, status) => (0, adapterEventRouting_1.dispatchAdapterEvent)(key, 'status', () => {
|
|
14053
|
+
// A status frame (a tool call, thinking) is the first sign of a turn that produces no text yet.
|
|
14054
|
+
topicIndicator.requestRefresh(key);
|
|
14055
|
+
return withThreadLocale(key, () => handleAdapterStatus(key, status));
|
|
14056
|
+
}),
|
|
13425
14057
|
onQuestion: (key, question) => (0, adapterEventRouting_1.dispatchAdapterEvent)(key, 'question', () => withThreadLocale(key, () => handleAgentQuestion(key, question))),
|
|
13426
14058
|
onThinking: (key, payload) => (0, adapterEventRouting_1.dispatchAdapterEvent)(key, 'thinking', () => withThreadLocale(key, () => handleAgentThinking(key, payload))),
|
|
13427
14059
|
onToolResult: (key, payload) => (0, adapterEventRouting_1.dispatchAdapterEvent)(key, 'toolResult', () => withThreadLocale(key, () => handleAgentToolResult(key, payload))),
|
|
@@ -13577,6 +14209,8 @@ async function startBot() {
|
|
|
13577
14209
|
// The questions the idle compaction re-asked: their buttons come back while the conversation can be resumed,
|
|
13578
14210
|
// else the message is closed.
|
|
13579
14211
|
restoreReAskedQuestions();
|
|
14212
|
+
// The questions the bot set aside: their buttons stay while the conversation can be resumed, else they are closed.
|
|
14213
|
+
restoreSetAsideQuestions();
|
|
13580
14214
|
// Re-arm persisted API-error retries (S6) so a pending kick survives the
|
|
13581
14215
|
// restart. AFTER restorePendingQuestions so the kick lands in a live
|
|
13582
14216
|
// session; a past fireAt fires one delayed catch-up.
|
|
@@ -13608,6 +14242,8 @@ async function startBot() {
|
|
|
13608
14242
|
markSessionsRestored();
|
|
13609
14243
|
// From here the engine can tell a live turn from a dead session.
|
|
13610
14244
|
requestWakeUpEngine?.start();
|
|
14245
|
+
// A tracker conversation whose process did not survive the downtime resumes its open request now, not at the backstop.
|
|
14246
|
+
scheduleRestartWakesAtBoot(requestLedger);
|
|
13611
14247
|
todoReminderEngine?.start();
|
|
13612
14248
|
jiraConnector?.start(createJiraSessionDeps(requestLedger, slots, jiraConnector.adapterName));
|
|
13613
14249
|
},
|
|
@@ -13632,9 +14268,11 @@ async function startBot() {
|
|
|
13632
14268
|
// and the CLI never retries a failed MCP server. Fire-and-forget.
|
|
13633
14269
|
healSchedulerMcpForActiveSessions();
|
|
13634
14270
|
},
|
|
13635
|
-
// Boot catch-up replay: arm every persisted job,
|
|
14271
|
+
// Boot catch-up replay: arm every persisted job, START one catch-up per
|
|
13636
14272
|
// missed run. Independent of the MCP server (delivery does not need it).
|
|
13637
|
-
|
|
14273
|
+
// It never waits for a delivery — one waits for its agent, which may wait for
|
|
14274
|
+
// an answer that only polling (started after this phase) can bring.
|
|
14275
|
+
rearmSchedules: () => schedulerEngine.rearmAll(),
|
|
13638
14276
|
});
|
|
13639
14277
|
// 5a. Refresh pinned banners for every binding. Threads that have a
|
|
13640
14278
|
// stored `pinnedStatusMessageId` get their banner edited in place;
|
|
@@ -13833,6 +14471,7 @@ async function startBot() {
|
|
|
13833
14471
|
schedulerEngine?.shutdown();
|
|
13834
14472
|
requestWakeUpEngine?.stop();
|
|
13835
14473
|
todoReminderEngine?.stop();
|
|
14474
|
+
topicIndicator.stop();
|
|
13836
14475
|
jiraConnector?.stop();
|
|
13837
14476
|
if (isSchedulerMcpStarted)
|
|
13838
14477
|
void schedulerMcpHandle.stop().catch(() => { });
|
|
@@ -13924,6 +14563,18 @@ async function startBot() {
|
|
|
13924
14563
|
// The local speech engine: clean up after an earlier run, re-attach to / start its install. Starts no process.
|
|
13925
14564
|
void bootSttLocalEngine().catch((e) => console.warn('[STT] boot step failed:', e instanceof Error ? e.message : e));
|
|
13926
14565
|
console.log(`Launching Telegraf bot (long polling, dropPendingUpdates=${bootMode.dropPendingUpdates})...`);
|
|
14566
|
+
// The marks of the topic names are written once the updates that waited are handled — an owner's rename made while the bot was down is
|
|
14567
|
+
// learned first (on a COLD start, which drops the waiting updates, it is read before the drop) — and looked at again every few minutes.
|
|
14568
|
+
// `launch` below returns only when the bot stops.
|
|
14569
|
+
if (bootMode.dropPendingUpdates) {
|
|
14570
|
+
try {
|
|
14571
|
+
await applyRenamesThatWaitedForColdStart();
|
|
14572
|
+
}
|
|
14573
|
+
catch (error) {
|
|
14574
|
+
console.warn('[boot] applying the topic renames that waited failed:', error instanceof Error ? error.message : error);
|
|
14575
|
+
}
|
|
14576
|
+
}
|
|
14577
|
+
topicIndicator.start();
|
|
13927
14578
|
try {
|
|
13928
14579
|
await bot.launch({
|
|
13929
14580
|
dropPendingUpdates: bootMode.dropPendingUpdates,
|