charness 4.2.0 → 4.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +168 -2
- package/DEVELOPMENT.md +58 -10
- package/LICENSE +331 -151
- package/MIGRATION_3_TO_4.md +8 -5
- package/README.md +21 -9
- package/SETUP.md +54 -10
- package/agent-plugin/README.md +10 -3
- package/agent-plugin/skills/charness-delegate-claude/SKILL.md +18 -27
- package/agent-plugin/skills/charness-delegate-opencode/SKILL.md +5 -3
- package/agent-plugin/skills/charness-orchestration/SKILL.md +62 -16
- package/dist/adapters/claudeCliAdapter.d.ts +4 -0
- package/dist/adapters/claudeCliAdapter.d.ts.map +1 -1
- package/dist/adapters/claudeCliAdapter.js +13 -0
- package/dist/adapters/claudeCliAdapter.js.map +1 -1
- package/dist/adapters/claudeJsonStreamAdapter.d.ts +136 -10
- package/dist/adapters/claudeJsonStreamAdapter.d.ts.map +1 -1
- package/dist/adapters/claudeJsonStreamAdapter.js +365 -77
- package/dist/adapters/claudeJsonStreamAdapter.js.map +1 -1
- package/dist/adapters/createAdapter.d.ts +12 -3
- package/dist/adapters/createAdapter.d.ts.map +1 -1
- package/dist/adapters/createAdapter.js +39 -13
- package/dist/adapters/createAdapter.js.map +1 -1
- package/dist/adapters/openCodeAdapter.d.ts +34 -0
- package/dist/adapters/openCodeAdapter.d.ts.map +1 -1
- package/dist/adapters/openCodeAdapter.js +118 -11
- package/dist/adapters/openCodeAdapter.js.map +1 -1
- package/dist/apiErrorRetry.d.ts +11 -3
- package/dist/apiErrorRetry.d.ts.map +1 -1
- package/dist/apiErrorRetry.js +33 -3
- package/dist/apiErrorRetry.js.map +1 -1
- package/dist/apiRetryKick.d.ts +18 -7
- package/dist/apiRetryKick.d.ts.map +1 -1
- package/dist/apiRetryKick.js +26 -13
- package/dist/apiRetryKick.js.map +1 -1
- package/dist/bot.d.ts +2 -6
- package/dist/bot.d.ts.map +1 -1
- package/dist/bot.js +2055 -653
- package/dist/bot.js.map +1 -1
- package/dist/cli/claudeProfiles.d.ts +28 -6
- package/dist/cli/claudeProfiles.d.ts.map +1 -1
- package/dist/cli/claudeProfiles.js +89 -22
- package/dist/cli/claudeProfiles.js.map +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +2 -1
- package/dist/cli.js.map +1 -1
- package/dist/connectors/jira/answerSink.d.ts +102 -7
- package/dist/connectors/jira/answerSink.d.ts.map +1 -1
- package/dist/connectors/jira/answerSink.js +366 -60
- package/dist/connectors/jira/answerSink.js.map +1 -1
- package/dist/connectors/jira/answerThreads.d.ts +44 -0
- package/dist/connectors/jira/answerThreads.d.ts.map +1 -0
- package/dist/connectors/jira/answerThreads.js +85 -0
- package/dist/connectors/jira/answerThreads.js.map +1 -0
- package/dist/connectors/jira/client.d.ts +67 -2
- package/dist/connectors/jira/client.d.ts.map +1 -1
- package/dist/connectors/jira/client.js +176 -4
- package/dist/connectors/jira/client.js.map +1 -1
- package/dist/connectors/jira/config.d.ts +6 -0
- package/dist/connectors/jira/config.d.ts.map +1 -1
- package/dist/connectors/jira/config.js +14 -1
- package/dist/connectors/jira/config.js.map +1 -1
- package/dist/connectors/jira/connector.d.ts +19 -0
- package/dist/connectors/jira/connector.d.ts.map +1 -1
- package/dist/connectors/jira/connector.js +68 -6
- package/dist/connectors/jira/connector.js.map +1 -1
- package/dist/connectors/jira/contextPreamble.d.ts.map +1 -1
- package/dist/connectors/jira/contextPreamble.js +6 -1
- package/dist/connectors/jira/contextPreamble.js.map +1 -1
- package/dist/connectors/jira/inbound.d.ts +21 -6
- package/dist/connectors/jira/inbound.d.ts.map +1 -1
- package/dist/connectors/jira/inbound.js +22 -16
- package/dist/connectors/jira/inbound.js.map +1 -1
- package/dist/connectors/jira/issueBlocks.d.ts +8 -1
- package/dist/connectors/jira/issueBlocks.d.ts.map +1 -1
- package/dist/connectors/jira/issueBlocks.js +38 -2
- package/dist/connectors/jira/issueBlocks.js.map +1 -1
- package/dist/connectors/jira/operatorIssue.d.ts +28 -0
- package/dist/connectors/jira/operatorIssue.d.ts.map +1 -0
- package/dist/connectors/jira/operatorIssue.js +81 -0
- package/dist/connectors/jira/operatorIssue.js.map +1 -0
- package/dist/connectors/jira/outbound.d.ts +8 -4
- package/dist/connectors/jira/outbound.d.ts.map +1 -1
- package/dist/connectors/jira/outbound.js +16 -8
- package/dist/connectors/jira/outbound.js.map +1 -1
- package/dist/connectors/jira/outgoingFileCheck.d.ts +37 -0
- package/dist/connectors/jira/outgoingFileCheck.d.ts.map +1 -0
- package/dist/connectors/jira/outgoingFileCheck.js +279 -0
- package/dist/connectors/jira/outgoingFileCheck.js.map +1 -0
- package/dist/connectors/jira/outgoingFiles.d.ts +81 -0
- package/dist/connectors/jira/outgoingFiles.d.ts.map +1 -0
- package/dist/connectors/jira/outgoingFiles.js +268 -0
- package/dist/connectors/jira/outgoingFiles.js.map +1 -0
- package/dist/connectors/jira/progressComments.d.ts +69 -0
- package/dist/connectors/jira/progressComments.d.ts.map +1 -0
- package/dist/connectors/jira/progressComments.js +136 -0
- package/dist/connectors/jira/progressComments.js.map +1 -0
- package/dist/connectors/jira/prompt.d.ts +5 -1
- package/dist/connectors/jira/prompt.d.ts.map +1 -1
- package/dist/connectors/jira/prompt.js +23 -3
- package/dist/connectors/jira/prompt.js.map +1 -1
- package/dist/connectors/jira/promptSpill.js +1 -1
- package/dist/connectors/jira/promptSpill.js.map +1 -1
- package/dist/connectors/jira/trigger.d.ts +13 -5
- package/dist/connectors/jira/trigger.d.ts.map +1 -1
- package/dist/connectors/jira/trigger.js +13 -7
- package/dist/connectors/jira/trigger.js.map +1 -1
- package/dist/connectors/jira/uploadedFiles.d.ts +48 -0
- package/dist/connectors/jira/uploadedFiles.d.ts.map +1 -0
- package/dist/connectors/jira/uploadedFiles.js +123 -0
- package/dist/connectors/jira/uploadedFiles.js.map +1 -0
- package/dist/connectors/telegram/commands/backendSwitch.d.ts +9 -1
- package/dist/connectors/telegram/commands/backendSwitch.d.ts.map +1 -1
- package/dist/connectors/telegram/commands/backendSwitch.js +17 -8
- package/dist/connectors/telegram/commands/backendSwitch.js.map +1 -1
- package/dist/connectors/telegram/commands/botSkills.d.ts +2 -0
- package/dist/connectors/telegram/commands/botSkills.d.ts.map +1 -1
- package/dist/connectors/telegram/commands/botSkills.js +17 -2
- package/dist/connectors/telegram/commands/botSkills.js.map +1 -1
- package/dist/connectors/telegram/commands/claudeAccounts.d.ts +6 -0
- package/dist/connectors/telegram/commands/claudeAccounts.d.ts.map +1 -1
- package/dist/connectors/telegram/commands/claudeAccounts.js +22 -4
- package/dist/connectors/telegram/commands/claudeAccounts.js.map +1 -1
- package/dist/connectors/telegram/commands/compaction.d.ts +14 -3
- package/dist/connectors/telegram/commands/compaction.d.ts.map +1 -1
- package/dist/connectors/telegram/commands/compaction.js +261 -96
- package/dist/connectors/telegram/commands/compaction.js.map +1 -1
- package/dist/connectors/telegram/commands/limitReminders.d.ts +21 -0
- package/dist/connectors/telegram/commands/limitReminders.d.ts.map +1 -0
- package/dist/connectors/telegram/commands/limitReminders.js +95 -0
- package/dist/connectors/telegram/commands/limitReminders.js.map +1 -0
- package/dist/connectors/telegram/commands/limitsBoard.d.ts +4 -0
- package/dist/connectors/telegram/commands/limitsBoard.d.ts.map +1 -1
- package/dist/connectors/telegram/commands/limitsBoard.js +27 -6
- package/dist/connectors/telegram/commands/limitsBoard.js.map +1 -1
- package/dist/connectors/telegram/commands/modelProviders.d.ts +2 -2
- package/dist/connectors/telegram/commands/modelProviders.d.ts.map +1 -1
- package/dist/connectors/telegram/commands/modelProviders.js +27 -16
- package/dist/connectors/telegram/commands/modelProviders.js.map +1 -1
- package/dist/connectors/telegram/commands/topicCommand.d.ts.map +1 -1
- package/dist/connectors/telegram/commands/topicCommand.js +7 -2
- package/dist/connectors/telegram/commands/topicCommand.js.map +1 -1
- package/dist/connectors/telegram/commands/workerRoles.d.ts +25 -0
- package/dist/connectors/telegram/commands/workerRoles.d.ts.map +1 -0
- package/dist/connectors/telegram/commands/workerRoles.js +259 -0
- package/dist/connectors/telegram/commands/workerRoles.js.map +1 -0
- package/dist/connectors/telegram/groupWelcome.d.ts +12 -0
- package/dist/connectors/telegram/groupWelcome.d.ts.map +1 -0
- package/dist/connectors/telegram/groupWelcome.js +12 -0
- package/dist/connectors/telegram/groupWelcome.js.map +1 -0
- package/dist/connectors/telegram/inbound.d.ts +7 -0
- package/dist/connectors/telegram/inbound.d.ts.map +1 -1
- package/dist/connectors/telegram/inbound.js +10 -0
- package/dist/connectors/telegram/inbound.js.map +1 -1
- package/dist/connectors/telegram/outputFlushPlan.d.ts +12 -0
- package/dist/connectors/telegram/outputFlushPlan.d.ts.map +1 -1
- package/dist/connectors/telegram/outputFlushPlan.js +12 -0
- package/dist/connectors/telegram/outputFlushPlan.js.map +1 -1
- package/dist/connectors/telegram/runnerPairingMessages.d.ts +1 -1
- package/dist/connectors/telegram/topicIndicator.d.ts +1 -1
- package/dist/connectors/telegram/topicIndicator.d.ts.map +1 -1
- package/dist/connectors/telegram/topicIndicator.js +103 -5
- package/dist/connectors/telegram/topicIndicator.js.map +1 -1
- package/dist/effortLevels.d.ts +6 -0
- package/dist/effortLevels.d.ts.map +1 -1
- package/dist/effortLevels.js +6 -1
- package/dist/effortLevels.js.map +1 -1
- package/dist/i18n/de.d.ts.map +1 -1
- package/dist/i18n/de.js +95 -14
- package/dist/i18n/de.js.map +1 -1
- package/dist/i18n/en.d.ts.map +1 -1
- package/dist/i18n/en.js +95 -14
- package/dist/i18n/en.js.map +1 -1
- package/dist/i18n/es.d.ts.map +1 -1
- package/dist/i18n/es.js +95 -14
- package/dist/i18n/es.js.map +1 -1
- package/dist/i18n/fr.d.ts.map +1 -1
- package/dist/i18n/fr.js +95 -14
- package/dist/i18n/fr.js.map +1 -1
- package/dist/i18n/hi.d.ts.map +1 -1
- package/dist/i18n/hi.js +95 -14
- package/dist/i18n/hi.js.map +1 -1
- package/dist/i18n/ja.d.ts.map +1 -1
- package/dist/i18n/ja.js +95 -14
- package/dist/i18n/ja.js.map +1 -1
- package/dist/i18n/ka.d.ts.map +1 -1
- package/dist/i18n/ka.js +95 -14
- package/dist/i18n/ka.js.map +1 -1
- package/dist/i18n/pt.d.ts.map +1 -1
- package/dist/i18n/pt.js +95 -14
- package/dist/i18n/pt.js.map +1 -1
- package/dist/i18n/ru.d.ts.map +1 -1
- package/dist/i18n/ru.js +95 -14
- package/dist/i18n/ru.js.map +1 -1
- package/dist/i18n/uk.d.ts.map +1 -1
- package/dist/i18n/uk.js +95 -14
- package/dist/i18n/uk.js.map +1 -1
- package/dist/i18n/uz.d.ts.map +1 -1
- package/dist/i18n/uz.js +95 -14
- package/dist/i18n/uz.js.map +1 -1
- package/dist/i18n/zh.d.ts.map +1 -1
- package/dist/i18n/zh.js +95 -14
- package/dist/i18n/zh.js.map +1 -1
- package/dist/instanceSettings.d.ts +24 -2
- package/dist/instanceSettings.d.ts.map +1 -1
- package/dist/instanceSettings.js +75 -3
- package/dist/instanceSettings.js.map +1 -1
- package/dist/limitNotes/engine.d.ts +47 -0
- package/dist/limitNotes/engine.d.ts.map +1 -0
- package/dist/limitNotes/engine.js +98 -0
- package/dist/limitNotes/engine.js.map +1 -0
- package/dist/limitNotes/noteText.d.ts +33 -0
- package/dist/limitNotes/noteText.d.ts.map +1 -0
- package/dist/limitNotes/noteText.js +55 -0
- package/dist/limitNotes/noteText.js.map +1 -0
- package/dist/limitNotes/plan.d.ts +147 -0
- package/dist/limitNotes/plan.d.ts.map +1 -0
- package/dist/limitNotes/plan.js +323 -0
- package/dist/limitNotes/plan.js.map +1 -0
- package/dist/limitNotes/reminderChoices.d.ts +30 -0
- package/dist/limitNotes/reminderChoices.d.ts.map +1 -0
- package/dist/limitNotes/reminderChoices.js +48 -0
- package/dist/limitNotes/reminderChoices.js.map +1 -0
- package/dist/limitNotes/service.d.ts +106 -0
- package/dist/limitNotes/service.d.ts.map +1 -0
- package/dist/limitNotes/service.js +169 -0
- package/dist/limitNotes/service.js.map +1 -0
- package/dist/openCodeSessionTitle.js +1 -1
- package/dist/openCodeSessionTitle.js.map +1 -1
- package/dist/outputTrace.d.ts +19 -0
- package/dist/outputTrace.d.ts.map +1 -1
- package/dist/outputTrace.js +23 -2
- package/dist/outputTrace.js.map +1 -1
- package/dist/platform/answerSink.d.ts +23 -0
- package/dist/platform/answerSink.d.ts.map +1 -1
- package/dist/platform/answerSink.js.map +1 -1
- package/dist/platform/operatorAlert.d.ts +24 -0
- package/dist/platform/operatorAlert.d.ts.map +1 -0
- package/dist/platform/operatorAlert.js +9 -0
- package/dist/platform/operatorAlert.js.map +1 -0
- package/dist/postToSession.d.ts +34 -2
- package/dist/postToSession.d.ts.map +1 -1
- package/dist/postToSession.js +31 -2
- package/dist/postToSession.js.map +1 -1
- package/dist/remoteRun/exitCodes.d.ts +2 -2
- package/dist/remoteRun/exitCodes.d.ts.map +1 -1
- package/dist/remoteRun/exitCodes.js +2 -2
- package/dist/remoteRun/exitCodes.js.map +1 -1
- package/dist/remoteRun/foreground.d.ts.map +1 -1
- package/dist/remoteRun/foreground.js +5 -1
- package/dist/remoteRun/foreground.js.map +1 -1
- package/dist/remoteRun/runnerClient.d.ts +1 -1
- package/dist/remoteRun/runnerClient.d.ts.map +1 -1
- package/dist/remoteRun/runnerClient.js +3 -3
- package/dist/remoteRun/runnerClient.js.map +1 -1
- package/dist/requests/answerRequest.d.ts +3 -0
- package/dist/requests/answerRequest.d.ts.map +1 -1
- package/dist/requests/answerRequest.js +9 -2
- package/dist/requests/answerRequest.js.map +1 -1
- package/dist/requests/limitWaitAnswer.d.ts +14 -0
- package/dist/requests/limitWaitAnswer.d.ts.map +1 -1
- package/dist/requests/limitWaitAnswer.js +26 -4
- package/dist/requests/limitWaitAnswer.js.map +1 -1
- package/dist/requests/requestHeader.d.ts +37 -5
- package/dist/requests/requestHeader.d.ts.map +1 -1
- package/dist/requests/requestHeader.js +70 -17
- package/dist/requests/requestHeader.js.map +1 -1
- package/dist/requests/scheduleWait.d.ts +79 -0
- package/dist/requests/scheduleWait.d.ts.map +1 -0
- package/dist/requests/scheduleWait.js +101 -0
- package/dist/requests/scheduleWait.js.map +1 -0
- package/dist/requests/sessionTurnProbe.d.ts +26 -3
- package/dist/requests/sessionTurnProbe.d.ts.map +1 -1
- package/dist/requests/sessionTurnProbe.js +22 -3
- package/dist/requests/sessionTurnProbe.js.map +1 -1
- package/dist/requests/topicRequestSettle.d.ts +13 -7
- package/dist/requests/topicRequestSettle.d.ts.map +1 -1
- package/dist/requests/topicRequestSettle.js +2 -2
- package/dist/requests/topicRequestSettle.js.map +1 -1
- package/dist/requests/trackerTurnPoster.d.ts +30 -0
- package/dist/requests/trackerTurnPoster.d.ts.map +1 -0
- package/dist/requests/trackerTurnPoster.js +36 -0
- package/dist/requests/trackerTurnPoster.js.map +1 -0
- package/dist/requests/types.d.ts +26 -5
- package/dist/requests/types.d.ts.map +1 -1
- package/dist/requests/wakeUpEngine.d.ts +201 -12
- package/dist/requests/wakeUpEngine.d.ts.map +1 -1
- package/dist/requests/wakeUpEngine.js +514 -44
- package/dist/requests/wakeUpEngine.js.map +1 -1
- package/dist/requests/wakeUpRules.d.ts +185 -14
- package/dist/requests/wakeUpRules.d.ts.map +1 -1
- package/dist/requests/wakeUpRules.js +169 -36
- package/dist/requests/wakeUpRules.js.map +1 -1
- package/dist/resumeContext.d.ts +2 -2
- package/dist/resumeContext.js +3 -3
- package/dist/resumeContext.js.map +1 -1
- package/dist/runnerUtility/adminService.js +1 -1
- package/dist/runnerUtility/adminService.js.map +1 -1
- package/dist/runnerUtility/guiAgent.d.ts +1 -1
- package/dist/runnerUtility/guiAgent.d.ts.map +1 -1
- package/dist/runnerUtility/guiAgent.js +1 -1
- package/dist/runnerUtility/guiAgent.js.map +1 -1
- package/dist/runnerUtility/managedNode.d.ts +3 -3
- package/dist/runnerUtility/managedNode.d.ts.map +1 -1
- package/dist/runnerUtility/managedNode.js +2 -2
- package/dist/runnerUtility/managedNode.js.map +1 -1
- package/dist/runnerUtility/runnerConfig.d.ts +1 -1
- package/dist/runnerUtility/runnerHome.d.ts +1 -1
- package/dist/runnerUtility/runnerHome.js +1 -1
- package/dist/runnerUtility/serviceCommon.d.ts +1 -1
- package/dist/runnerUtility/serviceCommon.d.ts.map +1 -1
- package/dist/runnerUtility/serviceCommon.js +1 -1
- package/dist/runnerUtility/serviceCommon.js.map +1 -1
- package/dist/runners/bootstrapLine.js +1 -1
- package/dist/runners/hubPackage.d.ts +1 -1
- package/dist/runners/hubPackage.js +3 -3
- package/dist/runners/hubPackage.js.map +1 -1
- package/dist/runners/hubPaths.d.ts +1 -1
- package/dist/runners/hubPaths.d.ts.map +1 -1
- package/dist/runners/runnerLock.d.ts +2 -2
- package/dist/runners/runnerLock.d.ts.map +1 -1
- package/dist/runners/runnerLock.js +2 -2
- package/dist/runners/runnerLock.js.map +1 -1
- package/dist/scheduler/checkRun.d.ts +2 -0
- package/dist/scheduler/checkRun.d.ts.map +1 -1
- package/dist/scheduler/checkRun.js +5 -1
- package/dist/scheduler/checkRun.js.map +1 -1
- package/dist/scheduler/delivery.d.ts +57 -0
- package/dist/scheduler/delivery.d.ts.map +1 -1
- package/dist/scheduler/delivery.js +152 -14
- package/dist/scheduler/delivery.js.map +1 -1
- package/dist/scheduler/injection.d.ts +6 -0
- package/dist/scheduler/injection.d.ts.map +1 -1
- package/dist/scheduler/injection.js +10 -0
- package/dist/scheduler/injection.js.map +1 -1
- package/dist/scheduler/mcpSurface.d.ts +68 -4
- package/dist/scheduler/mcpSurface.d.ts.map +1 -1
- package/dist/scheduler/mcpSurface.js +363 -189
- package/dist/scheduler/mcpSurface.js.map +1 -1
- package/dist/scheduler/rebindResume.d.ts +24 -0
- package/dist/scheduler/rebindResume.d.ts.map +1 -1
- package/dist/scheduler/rebindResume.js +32 -0
- package/dist/scheduler/rebindResume.js.map +1 -1
- package/dist/scheduler/scheduleToolWording.d.ts +29 -0
- package/dist/scheduler/scheduleToolWording.d.ts.map +1 -0
- package/dist/scheduler/scheduleToolWording.js +117 -0
- package/dist/scheduler/scheduleToolWording.js.map +1 -0
- package/dist/scheduler/scheduledRunTarget.d.ts +90 -0
- package/dist/scheduler/scheduledRunTarget.d.ts.map +1 -0
- package/dist/scheduler/scheduledRunTarget.js +92 -0
- package/dist/scheduler/scheduledRunTarget.js.map +1 -0
- package/dist/scheduler/store.d.ts +2 -0
- package/dist/scheduler/store.d.ts.map +1 -1
- package/dist/scheduler/store.js +2 -0
- package/dist/scheduler/store.js.map +1 -1
- package/dist/scheduler/types.d.ts +10 -0
- package/dist/scheduler/types.d.ts.map +1 -1
- package/dist/scheduler/workerWatch.d.ts +2 -0
- package/dist/scheduler/workerWatch.d.ts.map +1 -1
- package/dist/scheduler/workerWatch.js +3 -3
- package/dist/scheduler/workerWatch.js.map +1 -1
- package/dist/selfUpdate/constants.d.ts +2 -0
- package/dist/selfUpdate/constants.d.ts.map +1 -1
- package/dist/selfUpdate/constants.js +3 -1
- package/dist/selfUpdate/constants.js.map +1 -1
- package/dist/selfUpdate/emittedSource.d.ts.map +1 -1
- package/dist/selfUpdate/emittedSource.js +1 -1
- package/dist/selfUpdate/emittedSource.js.map +1 -1
- package/dist/selfUpdate/updateRuntime.js +1 -1
- package/dist/selfUpdate/updateRuntime.js.map +1 -1
- package/dist/sessionPick.d.ts +1 -1
- package/dist/sessionPick.js +1 -1
- package/dist/shutdown.d.ts +12 -0
- package/dist/shutdown.d.ts.map +1 -1
- package/dist/shutdown.js +11 -0
- package/dist/shutdown.js.map +1 -1
- package/dist/startupPromptBuffer.d.ts +35 -6
- package/dist/startupPromptBuffer.d.ts.map +1 -1
- package/dist/startupPromptBuffer.js +70 -21
- package/dist/startupPromptBuffer.js.map +1 -1
- package/dist/state.d.ts +173 -25
- package/dist/state.d.ts.map +1 -1
- package/dist/state.js +282 -58
- package/dist/state.js.map +1 -1
- package/dist/testTimings.d.ts +8 -3
- package/dist/testTimings.d.ts.map +1 -1
- package/dist/testTimings.js +15 -2
- package/dist/testTimings.js.map +1 -1
- package/dist/threadContextPreamble.d.ts +7 -0
- package/dist/threadContextPreamble.d.ts.map +1 -1
- package/dist/threadContextPreamble.js +11 -0
- package/dist/threadContextPreamble.js.map +1 -1
- package/dist/threadRouting.d.ts +12 -0
- package/dist/threadRouting.d.ts.map +1 -1
- package/dist/threadRouting.js +15 -0
- package/dist/threadRouting.js.map +1 -1
- package/dist/todos/midTurn.d.ts +15 -41
- package/dist/todos/midTurn.d.ts.map +1 -1
- package/dist/todos/midTurn.js +27 -171
- package/dist/todos/midTurn.js.map +1 -1
- package/dist/types.d.ts +147 -23
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +10 -0
- package/dist/types.js.map +1 -1
- package/dist/utils/backendSwitchPlan.d.ts +3 -3
- package/dist/utils/backendSwitchPlan.js +3 -3
- package/dist/utils/claudeAccountAlert.d.ts +104 -0
- package/dist/utils/claudeAccountAlert.d.ts.map +1 -0
- package/dist/utils/claudeAccountAlert.js +130 -0
- package/dist/utils/claudeAccountAlert.js.map +1 -0
- package/dist/utils/claudeAccountPickerPlan.d.ts +7 -0
- package/dist/utils/claudeAccountPickerPlan.d.ts.map +1 -1
- package/dist/utils/claudeAccountPickerPlan.js +13 -2
- package/dist/utils/claudeAccountPickerPlan.js.map +1 -1
- package/dist/utils/claudeAuthRefusal.d.ts +122 -0
- package/dist/utils/claudeAuthRefusal.d.ts.map +1 -0
- package/dist/utils/claudeAuthRefusal.js +228 -0
- package/dist/utils/claudeAuthRefusal.js.map +1 -0
- package/dist/utils/claudeCompactHook.d.ts +6 -6
- package/dist/utils/claudeCompactHook.js +8 -8
- package/dist/utils/claudeCompactHook.js.map +1 -1
- package/dist/utils/claudeProfileUsageViews.d.ts +54 -2
- package/dist/utils/claudeProfileUsageViews.d.ts.map +1 -1
- package/dist/utils/claudeProfileUsageViews.js +44 -1
- package/dist/utils/claudeProfileUsageViews.js.map +1 -1
- package/dist/utils/claudeProfiles.d.ts.map +1 -1
- package/dist/utils/claudeProfiles.js +10 -1
- package/dist/utils/claudeProfiles.js.map +1 -1
- package/dist/utils/claudeRuntimeInfo.d.ts +24 -0
- package/dist/utils/claudeRuntimeInfo.d.ts.map +1 -1
- package/dist/utils/claudeRuntimeInfo.js +128 -3
- package/dist/utils/claudeRuntimeInfo.js.map +1 -1
- package/dist/utils/claudeScheduledJobs.d.ts +6 -2
- package/dist/utils/claudeScheduledJobs.d.ts.map +1 -1
- package/dist/utils/claudeScheduledJobs.js +10 -2
- package/dist/utils/claudeScheduledJobs.js.map +1 -1
- package/dist/utils/claudeSessionTitle.js +1 -1
- package/dist/utils/claudeSessionTitle.js.map +1 -1
- package/dist/utils/claudeStreamJson.d.ts +28 -2
- package/dist/utils/claudeStreamJson.d.ts.map +1 -1
- package/dist/utils/claudeStreamJson.js +33 -3
- package/dist/utils/claudeStreamJson.js.map +1 -1
- package/dist/utils/claudeTranscriptEpoch.d.ts +14 -0
- package/dist/utils/claudeTranscriptEpoch.d.ts.map +1 -1
- package/dist/utils/claudeTranscriptEpoch.js +79 -19
- package/dist/utils/claudeTranscriptEpoch.js.map +1 -1
- package/dist/utils/claudeUsage.d.ts +103 -7
- package/dist/utils/claudeUsage.d.ts.map +1 -1
- package/dist/utils/claudeUsage.js +108 -15
- package/dist/utils/claudeUsage.js.map +1 -1
- package/dist/utils/compactOnIdle.d.ts +139 -29
- package/dist/utils/compactOnIdle.d.ts.map +1 -1
- package/dist/utils/compactOnIdle.js +163 -36
- package/dist/utils/compactOnIdle.js.map +1 -1
- package/dist/utils/conversationEnding.d.ts +76 -0
- package/dist/utils/conversationEnding.d.ts.map +1 -0
- package/dist/utils/conversationEnding.js +117 -0
- package/dist/utils/conversationEnding.js.map +1 -0
- package/dist/utils/doctorLine.d.ts +10 -0
- package/dist/utils/doctorLine.d.ts.map +1 -1
- package/dist/utils/doctorLine.js +16 -0
- package/dist/utils/doctorLine.js.map +1 -1
- package/dist/utils/fallbackBridge.d.ts.map +1 -1
- package/dist/utils/fallbackBridge.js +2 -1
- package/dist/utils/fallbackBridge.js.map +1 -1
- package/dist/utils/fallbackChain.d.ts +2 -0
- package/dist/utils/fallbackChain.d.ts.map +1 -1
- package/dist/utils/fallbackChain.js +4 -3
- package/dist/utils/fallbackChain.js.map +1 -1
- package/dist/utils/fallbackSwitchNotice.d.ts +11 -4
- package/dist/utils/fallbackSwitchNotice.d.ts.map +1 -1
- package/dist/utils/fallbackSwitchNotice.js +9 -5
- package/dist/utils/fallbackSwitchNotice.js.map +1 -1
- package/dist/utils/fileSendService.d.ts +31 -0
- package/dist/utils/fileSendService.d.ts.map +1 -1
- package/dist/utils/fileSendService.js +45 -2
- package/dist/utils/fileSendService.js.map +1 -1
- package/dist/utils/jsonStreamHost.d.ts +2 -0
- package/dist/utils/jsonStreamHost.d.ts.map +1 -1
- package/dist/utils/jsonStreamHost.js +4 -1
- package/dist/utils/jsonStreamHost.js.map +1 -1
- package/dist/utils/jsonStreamPendingWork.d.ts +14 -2
- package/dist/utils/jsonStreamPendingWork.d.ts.map +1 -1
- package/dist/utils/jsonStreamPendingWork.js +25 -5
- package/dist/utils/jsonStreamPendingWork.js.map +1 -1
- package/dist/utils/jsonStreamUnconsumedInput.d.ts +80 -0
- package/dist/utils/jsonStreamUnconsumedInput.d.ts.map +1 -0
- package/dist/utils/jsonStreamUnconsumedInput.js +99 -0
- package/dist/utils/jsonStreamUnconsumedInput.js.map +1 -0
- package/dist/utils/limitEpisodeRecovery.d.ts +43 -4
- package/dist/utils/limitEpisodeRecovery.d.ts.map +1 -1
- package/dist/utils/limitEpisodeRecovery.js +107 -20
- package/dist/utils/limitEpisodeRecovery.js.map +1 -1
- package/dist/utils/limitHeldPrompts.d.ts +21 -11
- package/dist/utils/limitHeldPrompts.d.ts.map +1 -1
- package/dist/utils/limitHeldPrompts.js +12 -9
- package/dist/utils/limitHeldPrompts.js.map +1 -1
- package/dist/utils/limitRemindersScreenPlan.d.ts +63 -0
- package/dist/utils/limitRemindersScreenPlan.d.ts.map +1 -0
- package/dist/utils/limitRemindersScreenPlan.js +121 -0
- package/dist/utils/limitRemindersScreenPlan.js.map +1 -0
- package/dist/utils/limitSwitchPlan.d.ts +51 -14
- package/dist/utils/limitSwitchPlan.d.ts.map +1 -1
- package/dist/utils/limitSwitchPlan.js +33 -15
- package/dist/utils/limitSwitchPlan.js.map +1 -1
- package/dist/utils/limitsBoardPlan.d.ts +16 -7
- package/dist/utils/limitsBoardPlan.d.ts.map +1 -1
- package/dist/utils/limitsBoardPlan.js +41 -9
- package/dist/utils/limitsBoardPlan.js.map +1 -1
- package/dist/utils/lostWork.d.ts +16 -2
- package/dist/utils/lostWork.d.ts.map +1 -1
- package/dist/utils/lostWork.js +16 -3
- package/dist/utils/lostWork.js.map +1 -1
- package/dist/utils/messageContext.d.ts +2 -2
- package/dist/utils/messageContext.js +2 -2
- package/dist/utils/midTurnInbox.d.ts +79 -0
- package/dist/utils/midTurnInbox.d.ts.map +1 -0
- package/dist/utils/midTurnInbox.js +265 -0
- package/dist/utils/midTurnInbox.js.map +1 -0
- package/dist/utils/promptDelivery.d.ts +70 -22
- package/dist/utils/promptDelivery.d.ts.map +1 -1
- package/dist/utils/promptDelivery.js +100 -42
- package/dist/utils/promptDelivery.js.map +1 -1
- package/dist/utils/topicIndicatorPlan.d.ts +13 -3
- package/dist/utils/topicIndicatorPlan.d.ts.map +1 -1
- package/dist/utils/topicIndicatorPlan.js +26 -4
- package/dist/utils/topicIndicatorPlan.js.map +1 -1
- package/dist/utils/topicRequest.d.ts +3 -0
- package/dist/utils/topicRequest.d.ts.map +1 -1
- package/dist/utils/topicRequest.js +4 -0
- package/dist/utils/topicRequest.js.map +1 -1
- package/dist/utils/workerRoles.d.ts +122 -0
- package/dist/utils/workerRoles.d.ts.map +1 -0
- package/dist/utils/workerRoles.js +160 -0
- package/dist/utils/workerRoles.js.map +1 -0
- package/dist/utils/workerRolesScreenPlan.d.ts +118 -0
- package/dist/utils/workerRolesScreenPlan.d.ts.map +1 -0
- package/dist/utils/workerRolesScreenPlan.js +232 -0
- package/dist/utils/workerRolesScreenPlan.js.map +1 -0
- package/dist/utils/workingSignals.d.ts +59 -0
- package/dist/utils/workingSignals.d.ts.map +1 -0
- package/dist/utils/workingSignals.js +60 -0
- package/dist/utils/workingSignals.js.map +1 -0
- package/licensing.json +88 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +7 -7
- package/{remoteRun → runner-scripts}/runner.sh +6 -3
- package/LICENSE-COMMERCIAL.md +0 -142
- package/dist/agentTrigger.d.ts +0 -28
- package/dist/agentTrigger.d.ts.map +0 -1
- package/dist/agentTrigger.js +0 -53
- package/dist/agentTrigger.js.map +0 -1
- /package/{remoteRun → runner-scripts}/ensureNode.sh +0 -0
- /package/{remoteRun → runner-scripts}/runner-package-lock.json +0 -0
package/dist/bot.js
CHANGED
|
@@ -60,9 +60,6 @@ const sessionKeyCodec_1 = require("./connectors/telegram/sessionKeyCodec");
|
|
|
60
60
|
// Arms the Jira key codec: a Jira conversation's key read back from `state.json`
|
|
61
61
|
// or a tmux / json-stream name must decode in every boot mode.
|
|
62
62
|
require("./connectors/jira/sessionKeyCodec");
|
|
63
|
-
// Pure parser lives in `./agentTrigger` so it can be unit-tested without
|
|
64
|
-
// booting Telegraf (audit S19 / #25).
|
|
65
|
-
const agentTrigger_1 = require("./agentTrigger");
|
|
66
63
|
const sessionPick_1 = require("./sessionPick");
|
|
67
64
|
const claudeCliAdapter_1 = require("./adapters/claudeCliAdapter");
|
|
68
65
|
const openCodeAdapter_1 = require("./adapters/openCodeAdapter");
|
|
@@ -78,9 +75,15 @@ const waitingTopicRenames_1 = require("./connectors/telegram/waitingTopicRenames
|
|
|
78
75
|
const topicIndicatorSources_1 = require("./utils/topicIndicatorSources");
|
|
79
76
|
const rateLimiter_1 = require("./rateLimiter");
|
|
80
77
|
const testTimings_1 = require("./testTimings");
|
|
78
|
+
const service_1 = require("./limitNotes/service");
|
|
79
|
+
const engine_1 = require("./limitNotes/engine");
|
|
80
|
+
const noteText_1 = require("./limitNotes/noteText");
|
|
81
|
+
const plan_1 = require("./limitNotes/plan");
|
|
82
|
+
const reminderChoices_1 = require("./limitNotes/reminderChoices");
|
|
81
83
|
const installManager_1 = require("./installManager");
|
|
82
84
|
const startupReadiness_1 = require("./utils/startupReadiness");
|
|
83
85
|
const doctorLine_1 = require("./utils/doctorLine");
|
|
86
|
+
const groupWelcome_1 = require("./connectors/telegram/groupWelcome");
|
|
84
87
|
const nativeWindows_1 = require("./utils/nativeWindows");
|
|
85
88
|
const state_1 = require("./state");
|
|
86
89
|
const diagLog_1 = require("./diagLog");
|
|
@@ -127,6 +130,7 @@ const postToSession_1 = require("./postToSession");
|
|
|
127
130
|
const limitHeldPrompts_1 = require("./utils/limitHeldPrompts");
|
|
128
131
|
const adoptReplayGate_1 = require("./utils/adoptReplayGate");
|
|
129
132
|
const topicRequestSettle_1 = require("./requests/topicRequestSettle");
|
|
133
|
+
const trackerTurnPoster_1 = require("./requests/trackerTurnPoster");
|
|
130
134
|
const promptDelivery_1 = require("./utils/promptDelivery");
|
|
131
135
|
const apiRetryKick_1 = require("./apiRetryKick");
|
|
132
136
|
const limitHeldPromptQueue_1 = require("./utils/limitHeldPromptQueue");
|
|
@@ -143,6 +147,7 @@ const sendErrorClassifier_1 = require("./sendErrorClassifier");
|
|
|
143
147
|
const pinnedStatus_1 = require("./pinnedStatus");
|
|
144
148
|
const progressLine_1 = require("./progressLine");
|
|
145
149
|
const startupPromptBuffer_1 = require("./startupPromptBuffer");
|
|
150
|
+
const conversationEnding_1 = require("./utils/conversationEnding");
|
|
146
151
|
const renderAgentHtml_1 = require("./connectors/telegram/renderAgentHtml");
|
|
147
152
|
const messageSplit_1 = require("./connectors/telegram/messageSplit");
|
|
148
153
|
const foldedMessage_1 = require("./connectors/telegram/foldedMessage");
|
|
@@ -220,7 +225,7 @@ const agentEnvironment_1 = require("./utils/agentEnvironment");
|
|
|
220
225
|
const folderGit_1 = require("./utils/folderGit");
|
|
221
226
|
const checkStatus_1 = require("./scheduler/checkStatus");
|
|
222
227
|
const workerActivity_1 = require("./scheduler/workerActivity");
|
|
223
|
-
const
|
|
228
|
+
const engine_2 = require("./scheduler/engine");
|
|
224
229
|
const recurrence_1 = require("./scheduler/recurrence");
|
|
225
230
|
const mcpSurface_1 = require("./scheduler/mcpSurface");
|
|
226
231
|
const injection_1 = require("./scheduler/injection");
|
|
@@ -236,6 +241,7 @@ const projects_1 = require("./todos/projects");
|
|
|
236
241
|
const board_1 = require("./todos/board");
|
|
237
242
|
const tools_1 = require("./todos/tools");
|
|
238
243
|
const midTurn_1 = require("./todos/midTurn");
|
|
244
|
+
const midTurnInbox_1 = require("./utils/midTurnInbox");
|
|
239
245
|
const answerTail_1 = require("./requests/answerTail");
|
|
240
246
|
const answerSink_1 = require("./connectors/telegram/answerSink");
|
|
241
247
|
const answerSink_2 = require("./platform/answerSink");
|
|
@@ -243,6 +249,7 @@ const sessionTurnProbe_1 = require("./requests/sessionTurnProbe");
|
|
|
243
249
|
const limitWaitAnswer_1 = require("./requests/limitWaitAnswer");
|
|
244
250
|
const localClock_1 = require("./utils/localClock");
|
|
245
251
|
const wakeUpEngine_1 = require("./requests/wakeUpEngine");
|
|
252
|
+
const scheduleWait_1 = require("./requests/scheduleWait");
|
|
246
253
|
const wakeUpRules_1 = require("./requests/wakeUpRules");
|
|
247
254
|
const requestHeader_1 = require("./requests/requestHeader");
|
|
248
255
|
const directoryThreads_1 = require("./scheduler/directoryThreads");
|
|
@@ -263,8 +270,10 @@ const reminders_1 = require("./connectors/telegram/commands/reminders");
|
|
|
263
270
|
const modelProviders_1 = require("./connectors/telegram/commands/modelProviders");
|
|
264
271
|
const callbackToast_2 = require("./connectors/telegram/commands/callbackToast");
|
|
265
272
|
const compaction_1 = require("./connectors/telegram/commands/compaction");
|
|
273
|
+
const claudeRuntimeInfo_1 = require("./utils/claudeRuntimeInfo");
|
|
266
274
|
const autoContinueLimits_1 = require("./connectors/telegram/commands/autoContinueLimits");
|
|
267
275
|
const botSkills_2 = require("./connectors/telegram/commands/botSkills");
|
|
276
|
+
const workerRoles_1 = require("./connectors/telegram/commands/workerRoles");
|
|
268
277
|
const questionWait_1 = require("./connectors/telegram/commands/questionWait");
|
|
269
278
|
const topicStatus_1 = require("./connectors/telegram/commands/topicStatus");
|
|
270
279
|
const topicAccess_1 = require("./connectors/telegram/commands/topicAccess");
|
|
@@ -282,7 +291,10 @@ const claudeAccounts_1 = require("./connectors/telegram/commands/claudeAccounts"
|
|
|
282
291
|
const claudeProfiles_1 = require("./utils/claudeProfiles");
|
|
283
292
|
const claudeUsage_1 = require("./utils/claudeUsage");
|
|
284
293
|
const claudeUsageRefresher_1 = require("./utils/claudeUsageRefresher");
|
|
294
|
+
const workerRoles_2 = require("./utils/workerRoles");
|
|
285
295
|
const claudeProfileSync_1 = require("./utils/claudeProfileSync");
|
|
296
|
+
const claudeAccountAlert_1 = require("./utils/claudeAccountAlert");
|
|
297
|
+
const claudeAuthRefusal_1 = require("./utils/claudeAuthRefusal");
|
|
286
298
|
const openCodeUsage_1 = require("./utils/openCodeUsage");
|
|
287
299
|
const usageRefreshBudget_1 = require("./utils/usageRefreshBudget");
|
|
288
300
|
const claudeLimitSwitch_1 = require("./utils/claudeLimitSwitch");
|
|
@@ -295,6 +307,7 @@ const fallbackChain_1 = require("./utils/fallbackChain");
|
|
|
295
307
|
const fallbackBridge_1 = require("./utils/fallbackBridge");
|
|
296
308
|
const fallbackChain_2 = require("./connectors/telegram/commands/fallbackChain");
|
|
297
309
|
const limitsBoard_1 = require("./connectors/telegram/commands/limitsBoard");
|
|
310
|
+
const limitReminders_1 = require("./connectors/telegram/commands/limitReminders");
|
|
298
311
|
const todo_1 = require("./connectors/telegram/commands/todo");
|
|
299
312
|
const backendSwitch_1 = require("./connectors/telegram/commands/backendSwitch");
|
|
300
313
|
const operatorSwitchPlan_1 = require("./utils/operatorSwitchPlan");
|
|
@@ -626,9 +639,11 @@ const telegramOutbound = (0, outbound_1.createTelegramConnectorOutbound)({
|
|
|
626
639
|
* conversation only through {@link getOutboundFor}, so a Jira conversation's
|
|
627
640
|
* stream never lands in a Telegram send.
|
|
628
641
|
*/
|
|
642
|
+
/** The Jira connector's file send, set once the lazily loaded connector is ready (`send_file_to_user` on an issue). */
|
|
643
|
+
let jiraFileSender = null;
|
|
629
644
|
const connectorOutbounds = new Map([
|
|
630
645
|
['telegram', telegramOutbound],
|
|
631
|
-
['jira', (0, outbound_3.createJiraConnectorOutbound)()],
|
|
646
|
+
['jira', (0, outbound_3.createJiraConnectorOutbound)(() => jiraFileSender)],
|
|
632
647
|
]);
|
|
633
648
|
function getOutboundFor(key) {
|
|
634
649
|
return (0, outbound_2.getConnectorOutbound)(connectorOutbounds, key);
|
|
@@ -772,6 +787,7 @@ bot.use(async (ctx, next) => {
|
|
|
772
787
|
preview: messageText === undefined
|
|
773
788
|
? callbackData
|
|
774
789
|
: (0, recvPreviewRedaction_1.getRecvTracePreview)(messageText, isThreadPendingProviderConnect, awaitedSttStep),
|
|
790
|
+
topicName: (0, outputTrace_1.getForumTopicServiceName)(message),
|
|
775
791
|
tgDateSec: message?.date,
|
|
776
792
|
});
|
|
777
793
|
return next();
|
|
@@ -989,9 +1005,11 @@ const noTopicRequest = { header: '', requestId: null };
|
|
|
989
1005
|
* `null` intake is a prompt that is not a request by rule — an answer to the
|
|
990
1006
|
* agent's own question, delivered as a prompt. The intake's requester decides
|
|
991
1007
|
* which open request, if any, the new one supersedes (`requestGroup.ts`); the
|
|
992
|
-
* header then names the replaced ones.
|
|
1008
|
+
* header then names the replaced ones. `onCreated` runs with the new id inside
|
|
1009
|
+
* the create, synchronously with the request appearing open (a person's prompt
|
|
1010
|
+
* marks itself in delivery there: {@link deliverPersonPromptInRequest}).
|
|
993
1011
|
*/
|
|
994
|
-
async function openTopicRequest(key, text, intake, messageContext) {
|
|
1012
|
+
async function openTopicRequest(key, text, intake, messageContext, onCreated) {
|
|
995
1013
|
if (intake === null || !topicRequestLedger || !(0, sessionKeyCodec_1.checkIsTelegramKey)(key))
|
|
996
1014
|
return noTopicRequest;
|
|
997
1015
|
const view = state.getDisplayPrefs(key).view;
|
|
@@ -1001,7 +1019,10 @@ async function openTopicRequest(key, text, intake, messageContext) {
|
|
|
1001
1019
|
// AGAIN when the session never took it in; the raw text would come back without the forwarded mark or the quote.
|
|
1002
1020
|
const promptBody = getPromptWithThreadMessageContext(key, text, messageContext);
|
|
1003
1021
|
const request = await topicRequestLedger.createRequest(key, (0, topicRequest_1.getTopicRequestOrigin)(intake), {
|
|
1004
|
-
createPrompt: (requestId, supersededRequestIds) =>
|
|
1022
|
+
createPrompt: (requestId, supersededRequestIds) => {
|
|
1023
|
+
onCreated?.(requestId);
|
|
1024
|
+
return (0, topicRequest_1.buildTopicRequestPrompt)({ requestId, source: intake.source, view, supersededRequestIds, promptBody, sender: messageContext?.nonOperatorSender });
|
|
1025
|
+
},
|
|
1005
1026
|
});
|
|
1006
1027
|
return { header: (0, topicRequest_1.buildTopicRequestHeader)(request.id, intake.source, view, request.supersededRequestIds, messageContext?.nonOperatorSender), requestId: request.id };
|
|
1007
1028
|
}
|
|
@@ -1010,9 +1031,9 @@ async function openTopicRequest(key, text, intake, messageContext) {
|
|
|
1010
1031
|
* wake-up engine watches the turn of a prompt that reached a session (or waits behind its start), and a prompt that found no
|
|
1011
1032
|
* session closes the request it opened. Both ports are read at call time: the engine and the ledger are assigned at boot.
|
|
1012
1033
|
*/
|
|
1013
|
-
const {
|
|
1014
|
-
trackTurn: async (key, requestId) => {
|
|
1015
|
-
await requestWakeUpEngine?.trackForwardedTurn(key, requestId, { isRequestPrompt: true });
|
|
1034
|
+
const { settleAfterDelivery: settleTopicRequestAfterDelivery } = (0, topicRequestSettle_1.createTopicRequestSettler)({
|
|
1035
|
+
trackTurn: async (key, requestId, { isScheduledRun }) => {
|
|
1036
|
+
await requestWakeUpEngine?.trackForwardedTurn(key, requestId, { isRequestPrompt: true, isScheduledRun });
|
|
1016
1037
|
},
|
|
1017
1038
|
cancelRequest: async (requestId) => {
|
|
1018
1039
|
await topicRequestLedger?.closeRequest(requestId, 'cancelled');
|
|
@@ -1072,6 +1093,44 @@ const readTodoSettings = (0, instanceSettings_1.createTodoSettingsReader)(() =>
|
|
|
1072
1093
|
function getTodoReminderIntervalMsNow() {
|
|
1073
1094
|
return (0, nag_1.getTodoReminderIntervalMs)(readTodoSettings(), ENV.testTimings.todoReminderIntervalMs);
|
|
1074
1095
|
}
|
|
1096
|
+
/** `settings.json`'s `limitReminders` (General's interval for the accounts note), re-read when the file changes. */
|
|
1097
|
+
const readLimitRemindersSettings = (0, instanceSettings_1.createLimitRemindersSettingsReader)(() => (0, instanceSettings_1.getInstanceSettingsPath)(), (line) => console.error(line));
|
|
1098
|
+
/** The worker roles the operator changed (`/workers`): read at every `claude_profiles` call, so a change reaches the next launch. */
|
|
1099
|
+
const readWorkerRolesSettings = (0, instanceSettings_1.createWorkerRolesSettingsReader)(() => (0, instanceSettings_1.getInstanceSettingsPath)(), (line) => console.error(line));
|
|
1100
|
+
/** The accounts note's interval of a conversation in ms (its own choice, else General's, else 1 h; the test window replaces it); `null` = Off. */
|
|
1101
|
+
function getConversationLimitReminderIntervalMs(key) {
|
|
1102
|
+
return (0, reminderChoices_1.getLimitReminderIntervalMs)((0, reminderChoices_1.resolveLimitRemindersMinutes)(readLimitRemindersSettings(), state.getLimitRemindersOverride(key)), ENV.testTimings.limitReminderIntervalMs);
|
|
1103
|
+
}
|
|
1104
|
+
/** The quiet period, the summary floor and the orchestration window of the accounts note, with the test windows applied. */
|
|
1105
|
+
function getLimitNoteWindows() {
|
|
1106
|
+
return {
|
|
1107
|
+
...plan_1.defaultLimitNoteWindows,
|
|
1108
|
+
minQuietMs: ENV.testTimings.limitNoteQuietMs ?? plan_1.defaultLimitNoteWindows.minQuietMs,
|
|
1109
|
+
summaryFloorMs: ENV.testTimings.limitNoteSummaryFloorMs ?? plan_1.defaultLimitNoteWindows.summaryFloorMs,
|
|
1110
|
+
};
|
|
1111
|
+
}
|
|
1112
|
+
let limitNotes = null;
|
|
1113
|
+
/**
|
|
1114
|
+
* The accounts note (`limitNotes/`): what a carrier prompt, a bot send tool's result and the two orchestration calls
|
|
1115
|
+
* (`claude_profiles`, a worker watch) say to it. It reads the usage cache and the conversation's record and writes only the record —
|
|
1116
|
+
* it never stamps activity, writes to an agent, wakes a session or opens a request (`limitNotes/README.md` § Lifecycle safety).
|
|
1117
|
+
*/
|
|
1118
|
+
function getLimitNotes() {
|
|
1119
|
+
limitNotes ??= (0, service_1.createLimitNotes)({
|
|
1120
|
+
getRecord: (key) => state.getLimitNoteRecord(key),
|
|
1121
|
+
setRecord: (key, record) => state.setLimitNoteRecord(key, record),
|
|
1122
|
+
getIntervalMs: getConversationLimitReminderIntervalMs,
|
|
1123
|
+
getWindows: getLimitNoteWindows,
|
|
1124
|
+
// The report `claude_profiles` answers a new worker's launch with: the same pick and order, never a second ranking.
|
|
1125
|
+
getReport: (nowMs) => (0, claudeProfileUsageViews_1.buildClaudeProfilesCreditReport)(getClaudeProfileUsageViews(), null, nowMs, { chainScope: (0, fallbackChain_1.getClaudeLaunchChainScope)(state.getFallbackChain()) }),
|
|
1126
|
+
getOpenCodeUsage: () => state.getOpenCodeProviderUsages(),
|
|
1127
|
+
getTimezone: getCurrentTimezone,
|
|
1128
|
+
getBackendName: (key) => (0, createAdapter_1.getThreadAdapterNameRaw)(key) ?? state.getAgent(key)?.name,
|
|
1129
|
+
getNowMs: Date.now,
|
|
1130
|
+
log: (line) => console.log(line),
|
|
1131
|
+
});
|
|
1132
|
+
return limitNotes;
|
|
1133
|
+
}
|
|
1075
1134
|
/**
|
|
1076
1135
|
* The reminder line a prompt forwarded now carries (D11 form a), or `null`; taking it counts as delivered. The lists
|
|
1077
1136
|
* are a courtesy to the agent: a failure here is logged and the prompt goes on without the line.
|
|
@@ -1087,6 +1146,8 @@ function takeTodoPromptReminder(key) {
|
|
|
1087
1146
|
}
|
|
1088
1147
|
/** The staleness reminder's poll (`todos/reminderEngine.ts`), built at boot and started once the sessions are restored. */
|
|
1089
1148
|
let todoReminderEngine = null;
|
|
1149
|
+
/** The accounts note's mid-turn delivery (`limitNotes/engine.ts`); built at boot, started with the sessions restored. */
|
|
1150
|
+
let limitNotesEngine = null;
|
|
1090
1151
|
let todoRepositories = null;
|
|
1091
1152
|
/** Which folders are one git repository (`todos/projects.ts`), cached; the root commits persist in `DATA_DIR/todos`. */
|
|
1092
1153
|
function getTodoRepositories() {
|
|
@@ -1202,12 +1263,21 @@ function noteTodoFreshContext(key) {
|
|
|
1202
1263
|
console.error(`[todos] ${(0, sessionKey_1.keyToString)(key)}: the board's seen state could not be reset:`, e instanceof Error ? e.message : e);
|
|
1203
1264
|
}
|
|
1204
1265
|
}
|
|
1266
|
+
let midTurnInbox = null;
|
|
1267
|
+
/**
|
|
1268
|
+
* The per-session mid-turn inbox a running Claude agent reads after its next tool call (`utils/midTurnInbox.ts`): the project board's
|
|
1269
|
+
* section and the accounts note's. One `PostToolUse` hook serves both; each section is offered and withdrawn on its own rules.
|
|
1270
|
+
*/
|
|
1271
|
+
function getMidTurnInbox() {
|
|
1272
|
+
midTurnInbox ??= (0, midTurnInbox_1.createMidTurnInbox)({ inboxDir: (0, midTurnInbox_1.getMidTurnInboxDir)(getDataDir()) });
|
|
1273
|
+
return midTurnInbox;
|
|
1274
|
+
}
|
|
1205
1275
|
let todoMidTurn = null;
|
|
1206
1276
|
/** Mid-turn delivery of the board (`todos/midTurn.ts`): the Claude inbox hook, the note into a running OpenCode turn. */
|
|
1207
1277
|
function getTodoMidTurn() {
|
|
1208
1278
|
todoMidTurn ??= (0, midTurn_1.createTodoMidTurn)({
|
|
1209
1279
|
board: getTodoBoard(),
|
|
1210
|
-
|
|
1280
|
+
inbox: getMidTurnInbox(),
|
|
1211
1281
|
getClaudeSessionId: (key) => {
|
|
1212
1282
|
const adapterName = (0, createAdapter_1.getThreadAdapterNameRaw)(key) ?? state.getAgent(key)?.name;
|
|
1213
1283
|
return adapterName !== undefined && (0, createAdapter_1.checkIsClaudeBackend)(adapterName) ? getResumableSessionId(key) : null;
|
|
@@ -1231,6 +1301,18 @@ function discardTodoInbox(key) {
|
|
|
1231
1301
|
console.error(`[todos] ${(0, sessionKey_1.keyToString)(key)}: the mid-turn inbox could not be withdrawn:`, e instanceof Error ? e.message : e);
|
|
1232
1302
|
}
|
|
1233
1303
|
}
|
|
1304
|
+
/**
|
|
1305
|
+
* A turn start the bot makes, a session boundary: the accounts note's mid-turn section of the inbox is withdrawn unseen — a tool call of
|
|
1306
|
+
* the old turn must not take a note the prompt may carry itself, or one meant for a session that is gone — and the note stays due.
|
|
1307
|
+
*/
|
|
1308
|
+
function withdrawAccountsInbox(key) {
|
|
1309
|
+
try {
|
|
1310
|
+
getMidTurnInbox().withdraw(key, 'accounts');
|
|
1311
|
+
}
|
|
1312
|
+
catch (e) {
|
|
1313
|
+
console.error(`[limit-notes] ${(0, sessionKey_1.keyToString)(key)}: the mid-turn inbox could not be withdrawn:`, e instanceof Error ? e.message : e);
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1234
1316
|
/**
|
|
1235
1317
|
* The board block a prompt forwarded now carries (D20), or `null`; taking it counts as seen. A failure never stops the prompt.
|
|
1236
1318
|
* Synchronous: it sits between the forward's decision and the write (see `TodoBoard.takePromptBoard`).
|
|
@@ -1638,6 +1720,26 @@ const wedgeRecoveryTier = new Map();
|
|
|
1638
1720
|
* like one, and a reminder on top would be a second recovery of the same turn.
|
|
1639
1721
|
*/
|
|
1640
1722
|
const wedgeRecoveriesInFlight = new Set();
|
|
1723
|
+
/**
|
|
1724
|
+
* Threads whose API error the bot is still handling with NOTHING armed — «wait for reset» off, a used-up credit balance, an account
|
|
1725
|
+
* refusal or a logged-out notice ({@link handleApiError}), by how many such errors are in hand: from the error, which the adapter
|
|
1726
|
+
* reports right before the turn's end, until that handling's stop, move or wait has landed. The request wake-up probe reads it as «not
|
|
1727
|
+
* a turn end»: decided at once, the turn that ended on the error would be a silent one, and its reminder written into the limited or
|
|
1728
|
+
* refused session would end on the same error — the second silent turn, the give-up. A branch that arms a retry is held by the timer.
|
|
1729
|
+
*/
|
|
1730
|
+
const apiErrorsInHandling = new Map();
|
|
1731
|
+
/** Hold `key`'s turn end ({@link apiErrorsInHandling}) until `handling` — an API error's stop, move or wait — has settled. */
|
|
1732
|
+
function holdTurnEndWhileHandlingApiError(key, handling) {
|
|
1733
|
+
const k = (0, sessionKey_1.keyToString)(key);
|
|
1734
|
+
apiErrorsInHandling.set(k, (apiErrorsInHandling.get(k) ?? 0) + 1);
|
|
1735
|
+
void handling.finally(() => {
|
|
1736
|
+
const count = (apiErrorsInHandling.get(k) ?? 1) - 1;
|
|
1737
|
+
if (count > 0)
|
|
1738
|
+
apiErrorsInHandling.set(k, count);
|
|
1739
|
+
else
|
|
1740
|
+
apiErrorsInHandling.delete(k);
|
|
1741
|
+
});
|
|
1742
|
+
}
|
|
1641
1743
|
/**
|
|
1642
1744
|
* @description `apiError` from the adapter — arm (or escalate) an auto-retry, or
|
|
1643
1745
|
* give up. The pure decision lives in {@link decideRetryAction}; this handler is
|
|
@@ -1664,11 +1766,11 @@ function handleApiError(key, cls, options = {}) {
|
|
|
1664
1766
|
}
|
|
1665
1767
|
// A used-up API credit balance: no wait refills it — the account is marked, and the chain or the operator takes over.
|
|
1666
1768
|
if (cls.kind === 'usageLimit' && cls.isBalanceExhausted === true) {
|
|
1667
|
-
|
|
1769
|
+
holdTurnEndWhileHandlingApiError(key, handleBalanceExhausted(key, cls));
|
|
1668
1770
|
return;
|
|
1669
1771
|
}
|
|
1670
1772
|
// An unconfirmed usage limit is probed first; it reaches the wait below only once confirmed.
|
|
1671
|
-
if (cls.kind === 'usageLimit' && cls.isUnconfirmed === true && handleUnconfirmedLimit(key))
|
|
1773
|
+
if (cls.kind === 'usageLimit' && cls.isUnconfirmed === true && handleUnconfirmedLimit(key, options.isRecoveredEpisode === true ? options.episodeWrittenAtMs : undefined))
|
|
1672
1774
|
return;
|
|
1673
1775
|
if (cls.kind === 'usageLimit' && !state.checkIsAutoContinueOnLimitEnabled(key)) {
|
|
1674
1776
|
const isFirstOffNotice = !autoContinueOffNoticedThreads.has(k);
|
|
@@ -1677,7 +1779,7 @@ function handleApiError(key, cls, options = {}) {
|
|
|
1677
1779
|
// Each repeat is offered to the open request: the dedup is per request, so one
|
|
1678
1780
|
// opened after the first notice still hears about the limit (and is stopped).
|
|
1679
1781
|
const wait = { kind: 'autoResumeOff' };
|
|
1680
|
-
|
|
1782
|
+
holdTurnEndWhileHandlingApiError(key, announceUsageLimitOrSwitch(key, cls, Date.now(), wait, 0, isFirstOffNotice));
|
|
1681
1783
|
return;
|
|
1682
1784
|
}
|
|
1683
1785
|
const entry = apiRetryTimers.get(k);
|
|
@@ -1691,10 +1793,11 @@ function handleApiError(key, cls, options = {}) {
|
|
|
1691
1793
|
now,
|
|
1692
1794
|
prev,
|
|
1693
1795
|
});
|
|
1694
|
-
// auth / logged out →
|
|
1695
|
-
// notice
|
|
1796
|
+
// auth / logged out → never a timer. A json-stream Claude conversation moves to another signed-in account and goes on
|
|
1797
|
+
// there (`handleClaudeAuthRefusal`; the frozen tmux backend keeps the notice alone); anything else, or nowhere to go,
|
|
1798
|
+
// surfaces a pinned notice — deduped to one per episode inside `surfaceLoggedOutNotice`.
|
|
1696
1799
|
if (action.action === 'surface') {
|
|
1697
|
-
|
|
1800
|
+
holdTurnEndWhileHandlingApiError(key, (0, createAdapter_1.getThreadAdapter)(key) instanceof claudeJsonStreamAdapter_1.ClaudeJsonStreamAdapter ? handleClaudeAuthRefusal(key, cls) : surfaceLoggedOutNotice(key));
|
|
1698
1801
|
return;
|
|
1699
1802
|
}
|
|
1700
1803
|
if (action.action === 'ignore')
|
|
@@ -1768,7 +1871,7 @@ function armApiRetryTimer(key, arming) {
|
|
|
1768
1871
|
clearSavedFiredLimitProbe(key);
|
|
1769
1872
|
const timer = setTimeout(() => {
|
|
1770
1873
|
void fireApiRetry(key);
|
|
1771
|
-
}, Math.min(arming.delayMs,
|
|
1874
|
+
}, Math.min(arming.delayMs, engine_2.maxTimeoutMs));
|
|
1772
1875
|
timer.unref?.();
|
|
1773
1876
|
apiRetryTimers.set((0, sessionKey_1.keyToString)(key), {
|
|
1774
1877
|
timer,
|
|
@@ -1785,10 +1888,11 @@ function armApiRetryTimer(key, arming) {
|
|
|
1785
1888
|
/**
|
|
1786
1889
|
* @description An UNCONFIRMED usage limit (`isUnconfirmed`) of `key`: the probe retry it gets first — or `false` when the
|
|
1787
1890
|
* limit is confirmed and takes the usual usage-limit wait. Confirmed when it came again right after the probe fired, or
|
|
1788
|
-
* the topic's account shows a window at 100 % ({@link checkIsTopicAccountUsageExhausted})
|
|
1789
|
-
*
|
|
1891
|
+
* the topic's account shows a window at 100 % ({@link checkIsTopicAccountUsageExhausted}) — in a reading taken no earlier than
|
|
1892
|
+
* `readingNotBeforeMs` when given (a recovered episode's own time); a retry already pending — the probe or a short retry — takes
|
|
1893
|
+
* it with it (`true`, nothing more to do).
|
|
1790
1894
|
*/
|
|
1791
|
-
function handleUnconfirmedLimit(key) {
|
|
1895
|
+
function handleUnconfirmedLimit(key, readingNotBeforeMs) {
|
|
1792
1896
|
const k = (0, sessionKey_1.keyToString)(key);
|
|
1793
1897
|
const entry = apiRetryTimers.get(k);
|
|
1794
1898
|
// A retry already pending (the probe itself, or a short retry) takes this error with it — as `decideRetryAction`
|
|
@@ -1798,7 +1902,7 @@ function handleUnconfirmedLimit(key) {
|
|
|
1798
1902
|
return true;
|
|
1799
1903
|
}
|
|
1800
1904
|
const isRepeatAfterProbe = entry?.isLimitProbe === true && entry.firedAt !== null && Date.now() - entry.firedAt <= apiErrorRetry_1.retryRecurrenceGraceMs;
|
|
1801
|
-
const action = (0, apiErrorRetry_1.getUnconfirmedLimitAction)({ isRepeatAfterProbe, isUsageExhausted: checkIsTopicAccountUsageExhausted(key) });
|
|
1905
|
+
const action = (0, apiErrorRetry_1.getUnconfirmedLimitAction)({ isRepeatAfterProbe, isUsageExhausted: checkIsTopicAccountUsageExhausted(key, readingNotBeforeMs) });
|
|
1802
1906
|
if (action === 'waitForReset') {
|
|
1803
1907
|
console.log(`[apiRetry] ${k}: the unconfirmed usage limit is confirmed (${isRepeatAfterProbe ? 'it came again after the probe' : 'the account is marked limited or reads a window at 100 %'}) — waiting for the reset`);
|
|
1804
1908
|
return false;
|
|
@@ -1811,16 +1915,18 @@ function handleUnconfirmedLimit(key) {
|
|
|
1811
1915
|
}
|
|
1812
1916
|
/**
|
|
1813
1917
|
* @description Whether the topic's account usage reading proves its limit: a Claude topic's live profile marked limited
|
|
1814
|
-
* (a rejected `rate_limit_event`) or showing a window its model drains at 100
|
|
1815
|
-
*
|
|
1918
|
+
* (a rejected `rate_limit_event`) or showing a window its model drains at 100 % — in a reading taken no earlier than
|
|
1919
|
+
* `readingNotBeforeMs` when given (`checkIsClaudeUsageExhausted`). Other backends carry no reading for the account an
|
|
1920
|
+
* unconfirmed wording names: `false`, and only a repeat confirms it.
|
|
1816
1921
|
*/
|
|
1817
|
-
function checkIsTopicAccountUsageExhausted(key) {
|
|
1922
|
+
function checkIsTopicAccountUsageExhausted(key, readingNotBeforeMs) {
|
|
1818
1923
|
if (!checkIsClaudeProfileBackend(key))
|
|
1819
1924
|
return false;
|
|
1820
1925
|
const info = state.getClaudeProfileInfo(resolveLiveClaudeProfileName(key));
|
|
1821
1926
|
const limitedUntilMs = info?.limitedUntil ? Date.parse(info.limitedUntil) : Number.NaN;
|
|
1822
1927
|
const nowMs = Date.now();
|
|
1823
|
-
return (Number.isFinite(limitedUntilMs) && limitedUntilMs > nowMs)
|
|
1928
|
+
return (Number.isFinite(limitedUntilMs) && limitedUntilMs > nowMs)
|
|
1929
|
+
|| (0, claudeUsage_1.checkIsClaudeUsageExhausted)(info?.usage, getThreadClaudeModel(key), nowMs, { readNotBeforeMs: readingNotBeforeMs });
|
|
1824
1930
|
}
|
|
1825
1931
|
/**
|
|
1826
1932
|
* @description R23: hold a prompt that arrives while `key` waits out an ARMED
|
|
@@ -1896,23 +2002,36 @@ const apiRetryKickDeps = {
|
|
|
1896
2002
|
},
|
|
1897
2003
|
getResumeMessage: (key, retryKind) => (0, limitHeldPrompts_1.getLimitResumeMessage)({
|
|
1898
2004
|
continueNudge: (0, i18n_1.t)('apiRetry.continueNudge'),
|
|
1899
|
-
|
|
1900
|
-
? (0, requestHeader_1.
|
|
2005
|
+
untakenRequestPrompts: retryKind === 'usageLimit'
|
|
2006
|
+
? (0, requestHeader_1.getPromptsNotTakenIn)(requestLimitWaitAnswerDeps?.ledger.listOpenRequestsOf(key) ?? [])
|
|
1901
2007
|
: undefined,
|
|
1902
2008
|
}),
|
|
1903
2009
|
// `ensureAgentSession` is already satisfied by a start ANOTHER caller has under way — the session is
|
|
1904
2010
|
// not there to take the nudge yet, so it goes through the startup buffer, not straight to the adapter.
|
|
1905
2011
|
// The buffer is in memory: the kick keeps the saved record until the buffer settles the nudge.
|
|
1906
|
-
deliverNudge: (key, text, onBufferedSettled) => deliverPromptOrBuffer(key, text,
|
|
2012
|
+
deliverNudge: (key, text, onBufferedSettled) => deliverPromptOrBuffer(key, text, onBufferedSettled),
|
|
1907
2013
|
trackContinuation: async (key, options) => {
|
|
1908
2014
|
await requestWakeUpEngine?.trackContinuationTurn(key, options);
|
|
1909
2015
|
},
|
|
1910
2016
|
resumeOnRung: async (key, rung) => {
|
|
1911
2017
|
const from = getTopicFallbackPosition(key);
|
|
2018
|
+
const ownLimitedUntil = from?.backend === 'claude' ? state.getClaudeProfileInfo(from.profile)?.limitedUntil : undefined;
|
|
2019
|
+
const end = (0, limitSwitchPlan_1.decideAimedWaitEnd)({
|
|
2020
|
+
isTelegram: (0, sessionKeyCodec_1.checkIsTelegramKey)(key),
|
|
2021
|
+
isAutoSwitchEnabled: state.checkIsClaudeAutoSwitchOnLimitEnabled(key),
|
|
2022
|
+
ownLimitedUntilMs: ownLimitedUntil === undefined ? null : Date.parse(ownLimitedUntil),
|
|
2023
|
+
nowMs: Date.now(),
|
|
2024
|
+
});
|
|
2025
|
+
if (end.action === 'waitOwnReset') {
|
|
2026
|
+
await rearmLimitWaitForOwnReset(key, end.untilMs);
|
|
2027
|
+
return 'waitingAgain';
|
|
2028
|
+
}
|
|
2029
|
+
if (end.action === 'resumeHere')
|
|
2030
|
+
return 'notMoved';
|
|
1912
2031
|
if (from !== null && (0, fallbackChain_1.checkIsSameFallbackAccount)(from, rung))
|
|
1913
|
-
return
|
|
2032
|
+
return 'notMoved'; // already there
|
|
1914
2033
|
const outcome = await switchTopicToFallbackEntry(key, from, rung, { isAnnounced: true, isAutomatic: true });
|
|
1915
|
-
return outcome.isSwitched;
|
|
2034
|
+
return outcome.isSwitched ? 'moved' : 'notMoved';
|
|
1916
2035
|
},
|
|
1917
2036
|
clearSavedRetry: clearSavedApiRetry,
|
|
1918
2037
|
saveFiredLimitProbe: (key, firedAt) => {
|
|
@@ -2034,12 +2153,21 @@ async function handleBalanceExhausted(key, cls) {
|
|
|
2034
2153
|
}
|
|
2035
2154
|
if (plan.action === 'auto') {
|
|
2036
2155
|
const to = plan.to;
|
|
2037
|
-
|
|
2038
|
-
|
|
2039
|
-
const
|
|
2040
|
-
|
|
2041
|
-
|
|
2042
|
-
|
|
2156
|
+
// A move onto the other backend ends the conversation it leaves, known now: held ahead of the paced notice, so a stop under way
|
|
2157
|
+
// drops what it held instead of resuming the backend whose credit is used up (review 24, own pass).
|
|
2158
|
+
const ending = checkIsFallbackMoveAcrossBackends(key, plan.from, to) ? conversationEndings.hold(key) : undefined;
|
|
2159
|
+
let outcome;
|
|
2160
|
+
try {
|
|
2161
|
+
if ((0, sessionKeyCodec_1.checkIsTelegramKey)(key))
|
|
2162
|
+
await replyToThread(key, notice);
|
|
2163
|
+
outcome = await switchTopicToFallbackEntry(key, plan.from, to, { isAnnounced: true, isAutomatic: true, ending }).catch((e) => {
|
|
2164
|
+
console.warn(`[fallback] ${k}: the auto-switch to ${formatFallbackEntry(to)} failed:`, e instanceof Error ? e.message : e);
|
|
2165
|
+
return { isSwitched: false };
|
|
2166
|
+
});
|
|
2167
|
+
}
|
|
2168
|
+
finally {
|
|
2169
|
+
ending?.release();
|
|
2170
|
+
}
|
|
2043
2171
|
// The notice is already in the topic; an open request still hears that the work stopped.
|
|
2044
2172
|
if (!outcome.isSwitched)
|
|
2045
2173
|
await announceLimitWait(key, stopped, texts, false);
|
|
@@ -2076,7 +2204,7 @@ function retargetLimitWait(key, episodeId, earliest) {
|
|
|
2076
2204
|
return null;
|
|
2077
2205
|
const fireAt = earliest.untilMs + apiErrorRetry_1.resetBufferMs;
|
|
2078
2206
|
clearTimeout(entry.timer);
|
|
2079
|
-
entry.timer = setTimeout(() => { void fireApiRetry(key); }, Math.min(Math.max(fireAt - Date.now(), 0),
|
|
2207
|
+
entry.timer = setTimeout(() => { void fireApiRetry(key); }, Math.min(Math.max(fireAt - Date.now(), 0), engine_2.maxTimeoutMs));
|
|
2080
2208
|
entry.timer.unref?.();
|
|
2081
2209
|
entry.fireAt = fireAt;
|
|
2082
2210
|
entry.resumeOn = earliest.entry;
|
|
@@ -2087,6 +2215,21 @@ function retargetLimitWait(key, episodeId, earliest) {
|
|
|
2087
2215
|
.catch((e) => console.error('[apiRetry] persist failed:', e));
|
|
2088
2216
|
return wait;
|
|
2089
2217
|
}
|
|
2218
|
+
/**
|
|
2219
|
+
* @description The end of a wait aimed at another account, for a tracker conversation whose automatic switch was turned OFF
|
|
2220
|
+
* meanwhile (`decideAimedWaitEnd`): it stays where it is, and a new wait is armed for its own account's reset (`untilMs` + the
|
|
2221
|
+
* usual buffer), its record replacing the one that fired, and told to the open request like any limit wait.
|
|
2222
|
+
*/
|
|
2223
|
+
async function rearmLimitWaitForOwnReset(key, untilMs) {
|
|
2224
|
+
const k = (0, sessionKey_1.keyToString)(key);
|
|
2225
|
+
const fired = apiRetryTimers.get(k);
|
|
2226
|
+
const attempt = fired?.attempt ?? 1;
|
|
2227
|
+
const fireAt = untilMs + apiErrorRetry_1.resetBufferMs;
|
|
2228
|
+
const wait = { kind: 'afterReset', resetAt: untilMs, fireAt };
|
|
2229
|
+
armApiRetryTimer(key, { kind: 'usageLimit', attempt, fireAt, delayMs: Math.max(fireAt - Date.now(), 0), attemptsByKind: fired?.attemptsByKind, limitWait: wait });
|
|
2230
|
+
console.log(`[fallback] ${k}: auto switch is off now — the wait aimed at another account goes on until its own account is back (${new Date(untilMs).toISOString()})`);
|
|
2231
|
+
await announceLimitWait(key, wait, getLimitWaitTexts(key, wait, attempt), false);
|
|
2232
|
+
}
|
|
2090
2233
|
/**
|
|
2091
2234
|
* @description A request opened during a usage-limit wait hears about it too
|
|
2092
2235
|
* (the ledger's create hook): a scheduled run or a tracker event does not cancel
|
|
@@ -2109,7 +2252,8 @@ function announceLimitWaitToNewRequest(key) {
|
|
|
2109
2252
|
* @description Both texts of a limit wait, from ONE branch on how it ends, in the
|
|
2110
2253
|
* thread's locale. A wait ending on another day names the date. The
|
|
2111
2254
|
* `/limits` + `/limits_autoswitch` pointer names Telegram commands — elsewhere it would
|
|
2112
|
-
* be noise; the "auto-resume is off" text carries its own.
|
|
2255
|
+
* be noise; the "auto-resume is off" text carries its own. A wait aimed at another
|
|
2256
|
+
* rung names it in a topic only (`resumeOn`).
|
|
2113
2257
|
*/
|
|
2114
2258
|
function getLimitWaitTexts(key, wait, attempt, resumeOn) {
|
|
2115
2259
|
if (wait.kind === 'autoResumeOff') {
|
|
@@ -2122,7 +2266,8 @@ function getLimitWaitTexts(key, wait, attempt, resumeOn) {
|
|
|
2122
2266
|
const zoneSuffix = (0, sessionKeyCodec_1.checkIsTelegramKey)(key) ? '' : ` ${getCurrentTimezone()}`;
|
|
2123
2267
|
const time = `${(0, localClock_1.formatLocalClockWithDateIfNotToday)(wait.kind === 'afterReset' ? wait.resetAt : wait.fireAt, nowMs)}${zoneSuffix}`;
|
|
2124
2268
|
const model = resumeOn ? formatFallbackEntry(resumeOn) : '';
|
|
2125
|
-
|
|
2269
|
+
// A tracker's requester learns when the answer comes, not on which of the operator's accounts.
|
|
2270
|
+
const [noticeText, answerText] = wait.kind === 'afterReset' && resumeOn && (0, sessionKeyCodec_1.checkIsTelegramKey)(key)
|
|
2126
2271
|
? [(0, i18n_1.t)('apiRetry.usageLimitResetOnRungNotice', { time, model }), (0, i18n_1.t)('requests.limit.answerAfterResetOnRungNotice', { time, model })]
|
|
2127
2272
|
: wait.kind === 'afterReset'
|
|
2128
2273
|
? [(0, i18n_1.t)('apiRetry.usageLimitResetNotice', { time }), (0, i18n_1.t)('requests.limit.answerAfterResetNotice', { time })]
|
|
@@ -2223,25 +2368,28 @@ async function handleNoResponseWithLocale(key) {
|
|
|
2223
2368
|
await replyToThread(key, (0, i18n_1.t)('agent.session_recovering'));
|
|
2224
2369
|
}
|
|
2225
2370
|
else if (action === 'fork') {
|
|
2226
|
-
// Restore the last dialog into a fresh, unwedged session.
|
|
2371
|
+
// Restore the last dialog into a fresh, unwedged session — as the conversation's one transition, like every start.
|
|
2227
2372
|
await replyToThread(key, (0, i18n_1.t)('agent.session_recovering'));
|
|
2228
|
-
const
|
|
2229
|
-
|
|
2230
|
-
|
|
2231
|
-
|
|
2232
|
-
|
|
2373
|
+
const startMsg = await runCommandSessionTransition(key, async () => {
|
|
2374
|
+
const forkedId = await adapter.forkSession(key);
|
|
2375
|
+
if (forkedId) {
|
|
2376
|
+
await persistSessionStart(key, adapter);
|
|
2377
|
+
return '';
|
|
2378
|
+
}
|
|
2233
2379
|
// Fork failed → fall back immediately to a blank restart this tier.
|
|
2234
2380
|
await releaseThreadSession(key);
|
|
2235
|
-
|
|
2236
|
-
|
|
2237
|
-
|
|
2238
|
-
|
|
2381
|
+
return startAgentSession(key);
|
|
2382
|
+
});
|
|
2383
|
+
if (startMsg)
|
|
2384
|
+
await replyToThread(key, startMsg);
|
|
2239
2385
|
}
|
|
2240
2386
|
else {
|
|
2241
2387
|
// action === 'restart': blank fresh session (dialog dropped).
|
|
2242
2388
|
await replyToThread(key, (0, i18n_1.t)('agent.session_restarting'));
|
|
2243
|
-
await
|
|
2244
|
-
|
|
2389
|
+
const startMsg = await runCommandSessionTransition(key, async () => {
|
|
2390
|
+
await releaseThreadSession(key);
|
|
2391
|
+
return startAgentSession(key);
|
|
2392
|
+
});
|
|
2245
2393
|
if (startMsg)
|
|
2246
2394
|
await replyToThread(key, startMsg);
|
|
2247
2395
|
}
|
|
@@ -2473,6 +2621,11 @@ function clearThreadContextMarker(key) {
|
|
|
2473
2621
|
// this session will take is withdrawn.
|
|
2474
2622
|
noteTodoFreshContext(key);
|
|
2475
2623
|
discardTodoInbox(key);
|
|
2624
|
+
// …and for the accounts notes: a mid-turn note waiting for a tool call of a session that is going away is withdrawn FIRST — a
|
|
2625
|
+
// file the hook already took is counted as delivered there, and that record must not land after the reset below — then the agent no
|
|
2626
|
+
// longer holds the picture its last note showed (the reminder clock stays).
|
|
2627
|
+
withdrawAccountsInbox(key);
|
|
2628
|
+
state.clearLimitNoteFingerprint(key);
|
|
2476
2629
|
}
|
|
2477
2630
|
function getThreadMessageState(key) {
|
|
2478
2631
|
const k = (0, sessionKey_1.keyToString)(key);
|
|
@@ -4509,6 +4662,10 @@ function listAvailableSubdirs(workRoot, limit = 200) {
|
|
|
4509
4662
|
function stopAllAdaptersFor(key, adapterNames) {
|
|
4510
4663
|
return (0, createAdapter_1.stopAllAdaptersFor)(key, createAdapter_1.getAdapter, adapterNames);
|
|
4511
4664
|
}
|
|
4665
|
+
/** {@link stopAllAdaptersFor} that resolves once every process it stopped is gone (`stopSessionAndWait` where the adapter has it). */
|
|
4666
|
+
function stopAndWaitAllAdaptersFor(key, adapterNames) {
|
|
4667
|
+
return (0, createAdapter_1.stopAndWaitAllAdaptersFor)(key, createAdapter_1.getAdapter, adapterNames);
|
|
4668
|
+
}
|
|
4512
4669
|
/**
|
|
4513
4670
|
* @description Explicit-stop teardown used by `/new`:
|
|
4514
4671
|
* sweep every adapter active for the thread, then RELEASE the persisted session
|
|
@@ -4572,14 +4729,20 @@ function closeSetAsideQuestionsInBackground(key) {
|
|
|
4572
4729
|
*
|
|
4573
4730
|
* Resolves the work the stop cut off that the agent's next prompt is told about (`null`: none), so a caller's line to
|
|
4574
4731
|
* the operator is derived from the very record the note lists.
|
|
4732
|
+
*
|
|
4733
|
+
* Onto another agent or a shell it closes the conversation's requests (`cancelEndingConversationRequests`), telling a person whose words
|
|
4734
|
+
* the agent never took in; `options.promptsReachedOrHeld` is a reading of «taken in» a bridged move took ahead of its bridge (absent: read
|
|
4735
|
+
* here, before the old process is stopped). `options.isConversationKept` keeps the set-aside questions (an automatic move).
|
|
4575
4736
|
*/
|
|
4576
4737
|
async function switchThreadAdapter(key, newName, options = {}) {
|
|
4577
4738
|
const prevName = (0, createAdapter_1.getThreadAdapterNameRaw)(key);
|
|
4578
4739
|
// Another agent or a shell takes the topic over: the open request belonged to
|
|
4579
|
-
// the old conversation, so it closes
|
|
4580
|
-
//
|
|
4740
|
+
// the old conversation, so it closes instead of a later wake-up reminding (or,
|
|
4741
|
+
// in a terminal, TYPING into) a session that never saw it — and a person whose
|
|
4742
|
+
// words the agent never read is told (review 25 #3).
|
|
4581
4743
|
if (prevName && !(0, createAdapter_1.checkIsSameConversationSwitch)(prevName, newName)) {
|
|
4582
|
-
|
|
4744
|
+
// A bridged move hands in what it read ahead of its bridge, so the reading and the bridge describe the same moment (review 27 nit 5).
|
|
4745
|
+
cancelEndingConversationRequests(key, options.promptsReachedOrHeld);
|
|
4583
4746
|
// Nor does the conversation left behind get its re-asked question answered: its buttons would send the label into the new one.
|
|
4584
4747
|
closeReAskedQuestion(key);
|
|
4585
4748
|
// The same for the questions it had set aside — unless the bot moved the conversation itself (an automatic usage-limit
|
|
@@ -4808,23 +4971,20 @@ const adoptedPerTurnStopPollMs = 5000;
|
|
|
4808
4971
|
async function startAgentSession(key, args) {
|
|
4809
4972
|
const kStr = (0, sessionKey_1.keyToString)(key);
|
|
4810
4973
|
// The bound folder IS the agent's cwd — refuse to start without one. The
|
|
4811
|
-
// command
|
|
4974
|
+
// command callers gate on the binding too, but a binding
|
|
4812
4975
|
// can vanish (/unbind) between their check and here, so re-check before any
|
|
4813
4976
|
// side effect (startup window / markers) opens.
|
|
4814
4977
|
const workDirDecision = getWorkDirStartDecision(key);
|
|
4815
|
-
if (!workDirDecision.ok)
|
|
4978
|
+
if (!workDirDecision.ok) {
|
|
4979
|
+
// A failed resume's window this start was to take over has nowhere to go either (a start with no window discards nothing).
|
|
4980
|
+
startupPromptBuffer.discardPrompts(kStr);
|
|
4816
4981
|
return workDirDecision.message;
|
|
4982
|
+
}
|
|
4817
4983
|
const workDir = workDirDecision.workDir;
|
|
4818
4984
|
// Open the startup window synchronously (before the first await) so text
|
|
4819
|
-
// typed right after `/claude` / `/opencode` is buffered, not dropped.
|
|
4985
|
+
// typed right after `/claude` / `/opencode` is buffered, not dropped. A failed resume's window may be open already: this start takes
|
|
4986
|
+
// it over, and its replay writes what the resume held.
|
|
4820
4987
|
startupPromptBuffer.markStarting(kStr);
|
|
4821
|
-
// A fresh session is a new conversation — clear any spent compact-on-idle latch
|
|
4822
|
-
// (D2) so this session can idle-compact even if the PREVIOUS session in this
|
|
4823
|
-
// thread already fired one (its latch persisted). The user starting the agent
|
|
4824
|
-
// is the genuine user action that re-arms it.
|
|
4825
|
-
if (state.checkIsCompactIdleLatched(key)) {
|
|
4826
|
-
void state.setCompactIdleLatched(key, false);
|
|
4827
|
-
}
|
|
4828
4988
|
markNeedsNewMessage(key);
|
|
4829
4989
|
// Fresh session — the agent's context is empty, so the next prompt must
|
|
4830
4990
|
// re-carry the thread-context preamble. Forget the last-injected marker.
|
|
@@ -4895,11 +5055,10 @@ function getAgentStartFailureText(adapterLabel, error, formatError) {
|
|
|
4895
5055
|
/**
|
|
4896
5056
|
* @description Ensure the thread `key` has an agent session ready to take a
|
|
4897
5057
|
* prompt, starting one if needed — the single choke point shared by the
|
|
4898
|
-
*
|
|
5058
|
+
* `/schedule` command (S7), the voice and text prompt routes, and the scheduler
|
|
4899
5059
|
* delivery (S4). It does NOT itself send any user-facing reply: it returns the
|
|
4900
5060
|
* outcome (and the message to show) so each caller decides its own messaging
|
|
4901
|
-
* (e.g. the
|
|
4902
|
-
* on `unbound`, the scheduler annotates the run ledger instead).
|
|
5061
|
+
* (e.g. the scheduler annotates the run ledger instead of replying).
|
|
4903
5062
|
*
|
|
4904
5063
|
* Cases:
|
|
4905
5064
|
* - already active → `{ ok: true }` (no message; nothing started).
|
|
@@ -4908,11 +5067,10 @@ function getAgentStartFailureText(adapterLabel, error, formatError) {
|
|
|
4908
5067
|
* - no session, has binding, but no adapter resolves (no explicit pick, no
|
|
4909
5068
|
* in-memory/persisted choice, no `fallbackAdapterName`) →
|
|
4910
5069
|
* `{ ok: false, reason: 'no-adapter' }` — refuse rather than silently launch
|
|
4911
|
-
* a default backend (interactive
|
|
4912
|
-
*
|
|
4913
|
-
* - no session, has binding → resolve the adapter name (
|
|
4914
|
-
*
|
|
4915
|
-
* `agents[key].name` → `fallbackAdapterName`), `switchThreadAdapter`
|
|
5070
|
+
* a default backend (an interactive start picks its adapter first, so this
|
|
5071
|
+
* only bites a `/schedule`/scheduler fire on a never-started topic).
|
|
5072
|
+
* - no session, has binding → resolve the adapter name (in-memory
|
|
5073
|
+
* thread pick → persisted `agents[key].name` → `fallbackAdapterName`), `switchThreadAdapter`
|
|
4916
5074
|
* + `startAgentSession`, then report `ok` from whether the session came up.
|
|
4917
5075
|
*/
|
|
4918
5076
|
async function ensureAgentSession(key, options = {}) {
|
|
@@ -4925,14 +5083,45 @@ async function ensureAgentSession(key, options = {}) {
|
|
|
4925
5083
|
* {@link ensureAgentSession} and {@link suspendThreadSession}.
|
|
4926
5084
|
*/
|
|
4927
5085
|
const sessionTransitions = new keyedTransitionQueue_1.KeyedTransitionQueue();
|
|
5086
|
+
/**
|
|
5087
|
+
* @description Run a start or resume a COMMAND makes — `/new`, a first `/claude` / `/opencode`, `/claude_mode`'s switch, `/resume`'s
|
|
5088
|
+
* pick, the wedge recovery's restart or fork — as the conversation's one transition, like an ensure or an idle stop. No two of them
|
|
5089
|
+
* overlap, so no startup window is opened by one and ended by another, and an ensure that comes meanwhile waits for it instead of
|
|
5090
|
+
* starting or resuming a second session beside it (review 20 nit 3). Never call it from inside a transition: the queue would wait for
|
|
5091
|
+
* itself.
|
|
5092
|
+
*/
|
|
5093
|
+
function runCommandSessionTransition(key, transition) {
|
|
5094
|
+
return sessionTransitions.run((0, sessionKey_1.keyToString)(key), async () => {
|
|
5095
|
+
await waitForPendingRespawn(key);
|
|
5096
|
+
return transition();
|
|
5097
|
+
});
|
|
5098
|
+
}
|
|
5099
|
+
/**
|
|
5100
|
+
* Conversations a command is about to END or REPLACE — `/new`, a `/resume` pick, `/quit`, leaving the folder, `/quitall`, a move across
|
|
5101
|
+
* backends, a start onto another agent or a shell —, each held from the moment the bot knows the command ends it (ahead of the toast of
|
|
5102
|
+
* its tap, a paced send, a move's bridge: review 24 #1) until its OWN transition begins (`utils/conversationEnding.ts`): a transition
|
|
5103
|
+
* queued ahead of it — a stop's resume for the prompts it held, a start's or a resume's replay of its window — drops those prompts instead
|
|
5104
|
+
* of writing them into the conversation the command ends, where they would start a turn the command then kills, unread and untold; a
|
|
5105
|
+
* person is told, and nothing is resumed or started for them (review 21 nit 4, review 22 nit 3, review 23 #1). Not `/claude_mode`: it
|
|
5106
|
+
* keeps the conversation, and a prompt written to the old backend's process is posted again by the turn's wake (R21).
|
|
5107
|
+
*/
|
|
5108
|
+
const conversationEndings = new conversationEnding_1.ConversationEndings({ toConversationKey: sessionKey_1.keyToString, runTransition: runCommandSessionTransition });
|
|
5109
|
+
/**
|
|
5110
|
+
* @description A json-stream re-spawn (a model, effort or account change, a deferred one at a turn's end) replaces the process inside the
|
|
5111
|
+
* adapter, outside this queue, with the process down for seconds: an ensure or a command transition waits for it first, and then reads the
|
|
5112
|
+
* re-spawned process live instead of starting or resuming a second one beside it (review 21 nit 6).
|
|
5113
|
+
*/
|
|
5114
|
+
async function waitForPendingRespawn(key) {
|
|
5115
|
+
await (0, createAdapter_1.getThreadAdapter)(key).waitForRespawn?.(key);
|
|
5116
|
+
}
|
|
4928
5117
|
async function ensureAgentSessionNow(key, options) {
|
|
5118
|
+
await waitForPendingRespawn(key);
|
|
4929
5119
|
// Resolve which adapter to run. `getThreadAdapterNameRaw` returns the
|
|
4930
5120
|
// in-memory pick WITHOUT any default fallback, so "no pick yet" stays
|
|
4931
5121
|
// distinguishable and the chain never silently defaults to a backend. When
|
|
4932
5122
|
// nothing resolves (bound topic that never picked an agent, no caller
|
|
4933
5123
|
// fallback) we REFUSE — the user must start/pick an agent first.
|
|
4934
|
-
const adapterName =
|
|
4935
|
-
(0, createAdapter_1.getThreadAdapterNameRaw)(key) ??
|
|
5124
|
+
const adapterName = (0, createAdapter_1.getThreadAdapterNameRaw)(key) ??
|
|
4936
5125
|
state.getAgent(key)?.name ??
|
|
4937
5126
|
options.fallbackAdapterName ??
|
|
4938
5127
|
null;
|
|
@@ -4944,7 +5133,10 @@ async function ensureAgentSessionNow(key, options) {
|
|
|
4944
5133
|
console.log(`[lifecycle] ${(0, sessionKey_1.keyToString)(key)}: the per-turn pick is kept; this session runs without the per-turn stop`);
|
|
4945
5134
|
}
|
|
4946
5135
|
const plan = (0, ensureSessionPlan_1.getEnsureSessionPlan)({
|
|
4947
|
-
|
|
5136
|
+
// Whether the process takes input, as a prompt reads it: a process the adapter is stopping by itself (a torn stdin frame's suspend,
|
|
5137
|
+
// outside this queue) is resumed — the resume joins that stop — instead of read `ready` while the prompt meets a dying process (review
|
|
5138
|
+
// 25 nit 4). Every other stop runs in this queue and is over before the plan reads.
|
|
5139
|
+
isActive: checkIsAcceptingInput(key),
|
|
4948
5140
|
isStarting: startupPromptBuffer.checkIsStarting((0, sessionKey_1.keyToString)(key)),
|
|
4949
5141
|
hasBinding: state.getBinding(key) !== undefined,
|
|
4950
5142
|
adapterName,
|
|
@@ -4967,14 +5159,20 @@ async function ensureAgentSessionNow(key, options) {
|
|
|
4967
5159
|
if (resumeFailure === null)
|
|
4968
5160
|
return { ok: true, message: '', isFresh: false };
|
|
4969
5161
|
const failureAction = (0, ensureSessionPlan_1.getResumeFailureAction)(resumeFailure, options.isResumeOnly === true);
|
|
5162
|
+
// The failed resume's window is still open with what it holds (`resumeSleepingSession`): a way that starts nothing ends it here,
|
|
5163
|
+
// its prompts dropped; a fresh start takes it over and its replay writes them into the fresh session.
|
|
4970
5164
|
if (failureAction === 'reportUnavailable') {
|
|
5165
|
+
startupPromptBuffer.discardPrompts((0, sessionKey_1.keyToString)(key));
|
|
4971
5166
|
return { ok: false, reason: 'start-failed', message: (0, i18n_1.t)('agent.serverUnavailableNotice', { label: (0, createAdapter_1.getThreadAdapter)(key).label }) };
|
|
4972
5167
|
}
|
|
4973
5168
|
if (failureAction === 'fail') {
|
|
5169
|
+
startupPromptBuffer.discardPrompts((0, sessionKey_1.keyToString)(key));
|
|
4974
5170
|
return { ok: false, reason: 'resume-failed', message: (0, i18n_1.t)('agent.resume_failed_fresh') };
|
|
4975
5171
|
}
|
|
4976
5172
|
// The previous conversation is lost to this topic: say so in one line, then start fresh. A fresh start that
|
|
4977
|
-
// fails too says only why: "a fresh session was started" would be false.
|
|
5173
|
+
// fails too says only why: "a fresh session was started" would be false. The fresh start writes the people's prompts the resume
|
|
5174
|
+
// held; what the bot made for the lost conversation is dropped, for its caller to post again its own way.
|
|
5175
|
+
startupPromptBuffer.discardBotPrompts((0, sessionKey_1.keyToString)(key));
|
|
4978
5176
|
const startMessage = await startAgentSession(key, options.args);
|
|
4979
5177
|
if (!(0, createAdapter_1.getThreadAdapter)(key).checkIsActive(key))
|
|
4980
5178
|
return { ok: false, reason: 'start-failed', message: startMessage };
|
|
@@ -5006,13 +5204,17 @@ function getResumableSessionId(key) {
|
|
|
5006
5204
|
* @description Resume a sleeping conversation SILENTLY (L-D4): no "started" notice,
|
|
5007
5205
|
* no recap — the next prompt simply continues it. Opens the startup window first so
|
|
5008
5206
|
* a message typed meanwhile is buffered and replayed, like a fresh start. The
|
|
5009
|
-
* conversation keeps its compaction
|
|
5207
|
+
* conversation keeps its compaction bookkeeping, its thread-context marker and its
|
|
5010
5208
|
* start time: nothing about it changed, only the process is back. Resolves
|
|
5011
5209
|
* `null` once resumed, else how it failed — the backend refused the id or the
|
|
5012
5210
|
* process did not come up, or the backend's server could not be brought up; the
|
|
5013
5211
|
* caller decides what follows ({@link getResumeFailureAction}).
|
|
5212
|
+
*
|
|
5213
|
+
* A failed resume leaves its window OPEN, with every prompt it holds: the caller ends it — a fresh start that follows takes it over
|
|
5214
|
+
* (its replay writes them into the fresh session), and a way that starts nothing discards them. Settled `dropped` here, they were lost
|
|
5215
|
+
* although a fresh session came up a moment later (review 19 #1).
|
|
5014
5216
|
*/
|
|
5015
|
-
async function resumeSleepingSession(key, sessionId) {
|
|
5217
|
+
async function resumeSleepingSession(key, sessionId, resumeOptions = {}) {
|
|
5016
5218
|
const kStr = (0, sessionKey_1.keyToString)(key);
|
|
5017
5219
|
const workDirDecision = getWorkDirStartDecision(key);
|
|
5018
5220
|
if (!workDirDecision.ok)
|
|
@@ -5023,29 +5225,38 @@ async function resumeSleepingSession(key, sessionId) {
|
|
|
5023
5225
|
try {
|
|
5024
5226
|
// A conversation the bot saw take a turn whose transcript is now missing is lost, not new: the resume fails.
|
|
5025
5227
|
const isConversationRecorded = (0, ensureSessionPlan_1.checkIsConversationRecorded)(state.getAgent(key)?.seenWatermark, sessionId);
|
|
5026
|
-
await adapter.resumeSession(key, workDirDecision.workDir, sessionId, { isConversationRecorded });
|
|
5228
|
+
await adapter.resumeSession(key, workDirDecision.workDir, sessionId, { ...resumeOptions, isConversationRecorded });
|
|
5027
5229
|
await persistSessionStart(key, adapter);
|
|
5230
|
+
// A resume that did not come up takes nothing: the window stays for the caller's fresh start, or its discard.
|
|
5231
|
+
if (!adapter.checkIsActive(key))
|
|
5232
|
+
return 'refused';
|
|
5028
5233
|
console.log(`[ensure] resumed the sleeping session of ${kStr}`);
|
|
5029
5234
|
void replayBufferedPrompts(key);
|
|
5030
|
-
return
|
|
5235
|
+
return null;
|
|
5031
5236
|
}
|
|
5032
5237
|
catch (e) {
|
|
5033
5238
|
console.warn(`[ensure] could not resume the sleeping session of ${kStr}:`, e instanceof Error ? e.message : e);
|
|
5034
|
-
// A fresh start (if the caller takes one) re-opens its own window; otherwise the held prompts have nowhere to go.
|
|
5035
|
-
startupPromptBuffer.discardPrompts(kStr);
|
|
5036
5239
|
return e instanceof backendUnavailableError_1.AgentBackendUnavailableError ? 'backendUnavailable' : 'refused';
|
|
5037
5240
|
}
|
|
5038
5241
|
}
|
|
5039
5242
|
/**
|
|
5040
5243
|
* @description A command that needs a live agent (`/compact`, `/model`, `/effort`)
|
|
5041
|
-
* on a topic whose session sleeps: wake it first
|
|
5042
|
-
* (only when the resume failed and
|
|
5043
|
-
*
|
|
5044
|
-
|
|
5045
|
-
|
|
5046
|
-
|
|
5047
|
-
|
|
5048
|
-
|
|
5244
|
+
* on a topic whose session sleeps, or is being stopped: wake it first, through the
|
|
5245
|
+
* conversation's queue. Returns the notice to post (only when the resume failed and
|
|
5246
|
+
* a fresh session took its place), `''` when nothing was said (a live session too),
|
|
5247
|
+
* `null` when there is no conversation to wake.
|
|
5248
|
+
*/
|
|
5249
|
+
function wakeSleepingSession(key) {
|
|
5250
|
+
// Through the queue even when the process still looks live: a stop under way (the seconds after every per-turn answer) is waited for
|
|
5251
|
+
// and the conversation resumed after it, so the pick that follows applies to the resumed process; a live one is `ready` at once
|
|
5252
|
+
// (review 23 nit 3). Whether there is a conversation to wake is read INSIDE the queue: a release queued ahead (`/quitall` from General)
|
|
5253
|
+
// leaves none, and a fresh agent is not started for the pick; a move hands the topic over first, and the caller reads the adapter
|
|
5254
|
+
// after this (review 24 nit 2). A resume that fails still starts fresh, as any ensure's does.
|
|
5255
|
+
return sessionTransitions.run((0, sessionKey_1.keyToString)(key), async () => {
|
|
5256
|
+
if (getResumableSessionId(key) === null)
|
|
5257
|
+
return null;
|
|
5258
|
+
return (await ensureAgentSessionNow(key, {})).message;
|
|
5259
|
+
});
|
|
5049
5260
|
}
|
|
5050
5261
|
/**
|
|
5051
5262
|
* @description The idle stop (lifecycle plan L3): stop the topic's process, the
|
|
@@ -5053,7 +5264,11 @@ async function wakeSleepingSession(key) {
|
|
|
5053
5264
|
* The startup window is held open while the process stops, so a prompt arriving
|
|
5054
5265
|
* meanwhile is buffered instead of written to a dying process; once the process
|
|
5055
5266
|
* is gone the window closes WITHOUT dropping those prompts, and if any wait the
|
|
5056
|
-
* session is resumed for them at once (its own window replays them)
|
|
5267
|
+
* session is resumed for them at once (its own window replays them) — also when
|
|
5268
|
+
* the stop threw, so a held prompt never waits in a closed buffer. A conversation
|
|
5269
|
+
* a command queued behind it ends or replaces (every release, `/new`, the `/resume` pick,
|
|
5270
|
+
* a move or a start onto another backend: held from the moment the bot knows the command
|
|
5271
|
+
* ends it until its own transition begins) starts nothing for them: they are dropped (a person is told). The
|
|
5057
5272
|
* "working" check is repeated inside the transition: a turn may have started
|
|
5058
5273
|
* while the fire waited its turn in the queue.
|
|
5059
5274
|
*/
|
|
@@ -5072,32 +5287,72 @@ async function suspendThreadSession(key) {
|
|
|
5072
5287
|
return;
|
|
5073
5288
|
}
|
|
5074
5289
|
autoStopUnsupportedLoggedKeys.delete(kStr);
|
|
5075
|
-
|
|
5076
|
-
|
|
5077
|
-
|
|
5078
|
-
|
|
5079
|
-
|
|
5080
|
-
|
|
5081
|
-
|
|
5082
|
-
|
|
5083
|
-
|
|
5084
|
-
|
|
5085
|
-
|
|
5086
|
-
|
|
5087
|
-
|
|
5088
|
-
|
|
5089
|
-
|
|
5090
|
-
|
|
5091
|
-
|
|
5092
|
-
|
|
5093
|
-
|
|
5290
|
+
try {
|
|
5291
|
+
await sessionTransitions.run(kStr, async () => {
|
|
5292
|
+
// A json-stream re-spawn under way or about to start (a model, effort or account change) is over first, as for every transition
|
|
5293
|
+
// in the queue: a stop beside it would terminate the process it replaces, and the prompts it held would be left in a closed
|
|
5294
|
+
// buffer (review 22 #1 b). The stop then reads the re-spawned process.
|
|
5295
|
+
await waitForPendingRespawn(key);
|
|
5296
|
+
// Decide on what the process wrote up to now, not on the last tail poll: a background task's turn may have just begun.
|
|
5297
|
+
adapter.refreshWorkingState?.(key);
|
|
5298
|
+
if (!adapter.checkIsActive(key) || adapter.checkIsWorking?.(key))
|
|
5299
|
+
return;
|
|
5300
|
+
startupPromptBuffer.markStarting(kStr);
|
|
5301
|
+
console.log(`[compact-on-idle] ${kStr} stopping the idle process; a prompt that comes meanwhile is held`);
|
|
5302
|
+
try {
|
|
5303
|
+
await adapter.suspendSession(key);
|
|
5304
|
+
console.log(`[compact-on-idle] ${kStr} process stopped; the session sleeps and resumes on the next message`);
|
|
5305
|
+
}
|
|
5306
|
+
finally {
|
|
5307
|
+
startupPromptBuffer.closeWindow(kStr);
|
|
5308
|
+
// Still the stop's transition, also when the stop threw: a start or resume a command makes (`/new`, …) waits for it in the
|
|
5309
|
+
// queue, so the prompts the stop held go to the conversation they were written in (review 20 nit 3).
|
|
5310
|
+
await resumeForHeldPrompts(key);
|
|
5311
|
+
}
|
|
5312
|
+
});
|
|
5313
|
+
}
|
|
5314
|
+
finally {
|
|
5315
|
+
// A sleeping per-turn session with a compaction due gets its idle timer from the persisted stamps (L-D7).
|
|
5316
|
+
rearmThreadIdleTimer(key);
|
|
5317
|
+
}
|
|
5318
|
+
}
|
|
5319
|
+
/**
|
|
5320
|
+
* @description After an idle stop, whatever its end, inside the stop's own transition: the prompts its window held go to the
|
|
5321
|
+
* conversation resumed for them (`ensureAgentSessionNow`: the queued ensure would wait for this very transition). A conversation a
|
|
5322
|
+
* command queued behind the stop ends or replaces — a release, `/new`, a `/resume` pick, a move or a start onto another backend:
|
|
5323
|
+
* {@link conversationEndings} — must not be resumed only to be killed by that command: they are dropped, a person told to send
|
|
5324
|
+
* theirs again, and nothing starts (review 23 #1). A conversation with no id left (its topic deleted) is the same drop, as a guard. A
|
|
5325
|
+
* conversation that is already live when the ensure returns (it found it `ready`) gets them replayed into it; one the ensure could not
|
|
5326
|
+
* bring up without discarding them has them dropped — no way out of a stop leaves them in a closed buffer.
|
|
5327
|
+
*/
|
|
5328
|
+
async function resumeForHeldPrompts(key) {
|
|
5329
|
+
const kStr = (0, sessionKey_1.keyToString)(key);
|
|
5330
|
+
if (!startupPromptBuffer.checkHasPrompts(kStr))
|
|
5331
|
+
return;
|
|
5332
|
+
if (conversationEndings.checkIsEnding(kStr) || getResumableSessionId(key) === null) {
|
|
5333
|
+
console.log(`[compact-on-idle] ${kStr}: a command ends the conversation (or it has no id left); the prompts the stop held are dropped`);
|
|
5334
|
+
startupPromptBuffer.discardPrompts(kStr);
|
|
5335
|
+
return;
|
|
5336
|
+
}
|
|
5337
|
+
const ensured = await ensureAgentSessionNow(key, {});
|
|
5338
|
+
// A resume (or the fresh start after a failed one) took them over; nothing is left to do.
|
|
5339
|
+
if (!startupPromptBuffer.checkHasPrompts(kStr) || startupPromptBuffer.checkIsStarting(kStr))
|
|
5340
|
+
return;
|
|
5341
|
+
// The ensure found the conversation already live (`ready`) and replayed nothing: they are written into it here (review 22 #1 c). Not
|
|
5342
|
+
// awaited, as a resume's replay: a write on the adopted-session path may wake the conversation, and that ensure queues behind this very
|
|
5343
|
+
// transition.
|
|
5344
|
+
if (ensured.ok)
|
|
5345
|
+
void replayBufferedPrompts(key);
|
|
5346
|
+
// The ensure failed without discarding them (an unbound or deleted topic, no adapter): dropped, a person told (review 23 nit 6).
|
|
5347
|
+
else
|
|
5348
|
+
startupPromptBuffer.discardPrompts(kStr);
|
|
5094
5349
|
}
|
|
5095
5350
|
/** Conversations already told once that their CLI is too old for the auto-stop (L-D10). */
|
|
5096
5351
|
const autoStopUnsupportedLoggedKeys = new Set();
|
|
5097
5352
|
/**
|
|
5098
5353
|
* @description `turnEnded` from a json-stream adapter. The idle countdown runs from
|
|
5099
5354
|
* the end of the last turn: an idle fire that found the turn still running is not
|
|
5100
|
-
* rescheduled (
|
|
5355
|
+
* rescheduled (the turn's own end re-arms it), and a turn whose answer went out through `answer_request`
|
|
5101
5356
|
* produces no later output to re-arm it — the process would never reach its idle
|
|
5102
5357
|
* compaction and stop, and its pending-work hold would never be enforced. (A
|
|
5103
5358
|
* bot-issued compaction's own turn end is skipped by the arming's loop guard.)
|
|
@@ -5111,17 +5366,48 @@ const autoStopUnsupportedLoggedKeys = new Set();
|
|
|
5111
5366
|
* `postToSession` that polled the session idle and ensures it again (`postToSession.ts`) therefore always finds
|
|
5112
5367
|
* the stop already on the transition queue and runs after it. Keep it that way — an await ahead of the queueing
|
|
5113
5368
|
* would let that ensure run beside the stop and forward to the process it ends.
|
|
5114
|
-
|
|
5115
|
-
|
|
5369
|
+
*
|
|
5370
|
+
* It is also where the next turn's boundary is marked when a prompt was forwarded before this turn ended
|
|
5371
|
+
* (`checkShouldMarkNewMessageAfterTurnEnd`): the adapter emits the turn's closing text synchronously BEFORE this event,
|
|
5372
|
+
* and the group transport queues it in the same tick, so the mark set here is the one the next turn's first text takes.
|
|
5373
|
+
*/
|
|
5374
|
+
function handleAgentTurnEnded(key, turnEnd) {
|
|
5375
|
+
// No tool call of this turn is left to take a mid-turn accounts note: withdrawn unseen, it stays due.
|
|
5376
|
+
withdrawAccountsInbox(key);
|
|
5377
|
+
getLimitNotes().noteTurnEnd(key);
|
|
5116
5378
|
noteThreadActivity(key);
|
|
5379
|
+
// Started here, before the per-turn stop below is queued: the process is read while it is still the session's.
|
|
5380
|
+
noteThreadTurnContext(key);
|
|
5117
5381
|
topicIndicator.requestRefresh(key);
|
|
5118
5382
|
const adapter = (0, createAdapter_1.getThreadAdapter)(key);
|
|
5119
|
-
|
|
5120
|
-
|
|
5121
|
-
|
|
5383
|
+
// The boundary of the next turn, reported by the adapter: the turn's closing text was queued before this event (the adapter emits it first,
|
|
5384
|
+
// in the same tick), so a mark the forward of the next prompt set earlier is spent by now. Input still on its way is that turn's — after a
|
|
5385
|
+
// turn that ended in an error too.
|
|
5386
|
+
if ((0, sessionKeyCodec_1.checkIsTelegramKey)(key) && (0, outputFlushPlan_1.checkShouldMarkNewMessageAfterTurnEnd)({ outputsDeltas: adapter.outputsDeltas === true, hasInputOnItsWay: turnEnd.hasInputOnItsWay }))
|
|
5387
|
+
markNeedsNewMessage(key);
|
|
5388
|
+
if (adapter.name === adapterNames_1.claudePerTurnAdapterName && !checkIsDeferredCompactionArmed(key) && !adapter.checkIsWorking?.(key)) {
|
|
5389
|
+
void suspendThreadSession(key).catch((e) => console.warn(`[lifecycle] the per-turn stop of ${(0, sessionKey_1.keyToString)(key)} failed:`, e instanceof Error ? e.message : e));
|
|
5390
|
+
}
|
|
5391
|
+
// The turn's end is decided at the adapter's own turn-end event (json-stream Claude, both lifecycles) — after the per-turn stop is
|
|
5392
|
+
// queued: its window opens only in a later tick, and once it is over the session is gone, which a watch reads as «tracking lost», never
|
|
5393
|
+
// as an end. A reminder this decides is handed to a post waiting for this turn, which writes its own prompt first; with none waiting it
|
|
5394
|
+
// resumes the session through the ensure, which queues behind the stop (`requests/README.md` § Turn starts).
|
|
5395
|
+
settleEndedTurnsAndHandOver(key);
|
|
5396
|
+
}
|
|
5397
|
+
/**
|
|
5398
|
+
* @description Settle `key`'s watches whose turn already ended (`RequestWakeUpEngine.settleEndedTurnsOf`, synchronous up to the
|
|
5399
|
+
* decisions) and hand the reminders they decided, once persisted, to a post on its way to its write (`deliverOrHandOverWake`), else
|
|
5400
|
+
* deliver them at once — at the adapter's turn end ({@link handleAgentTurnEnded}) and at the write choke point, whose write runs in
|
|
5401
|
+
* this tick, so a reminder follows that write, and a post that waited writes its prompt first. Never rejects.
|
|
5402
|
+
*/
|
|
5403
|
+
function settleEndedTurnsAndHandOver(key) {
|
|
5404
|
+
const engine = requestWakeUpEngine;
|
|
5405
|
+
if (!engine)
|
|
5122
5406
|
return;
|
|
5123
|
-
void
|
|
5407
|
+
void engine.settleEndedTurnsOf(key).then((deliverSettledWakes) => engine.deliverOrHandOverWake(key, deliverSettledWakes));
|
|
5124
5408
|
}
|
|
5409
|
+
/** No reminder to deliver: what a settle resolves, and what a post's release is, while the wake-up engine is not up yet. */
|
|
5410
|
+
const deliverNoSettledWakes = async () => { };
|
|
5125
5411
|
/**
|
|
5126
5412
|
* @description A prompt (text, voice, file, a re-asked question's answer) arrives
|
|
5127
5413
|
* in a topic whose conversation sleeps: resume it so the prompt continues it.
|
|
@@ -5133,11 +5419,23 @@ function handleAgentTurnEnded(key) {
|
|
|
5133
5419
|
async function resumeSleepingSessionForPrompt(key, sendNotice = (text) => replyToThread(key, text)) {
|
|
5134
5420
|
return (await wakeSleepingSessionForPrompt(key, sendNotice)).isAwake;
|
|
5135
5421
|
}
|
|
5136
|
-
/**
|
|
5422
|
+
/**
|
|
5423
|
+
* @description {@link resumeSleepingSessionForPrompt}, also saying whether it posted a notice (a start that failed says why). Whether there
|
|
5424
|
+
* is a conversation to wake is read again INSIDE the conversation's queue, as the wake of `/model`, `/effort` and `/compact` does: a release
|
|
5425
|
+
* queued ahead (`/quitall` from General, a `/quit` that a voice note's transcript waited behind) clears the ids, and the wake then starts
|
|
5426
|
+
* nothing — `isEnded`, which a person's prompt is told as the release's refusal — instead of a fresh conversation the operator just quit
|
|
5427
|
+
* (review 25 #2). A resume that fails still starts fresh, as any ensure's does.
|
|
5428
|
+
*/
|
|
5137
5429
|
async function wakeSleepingSessionForPrompt(key, sendNotice = (text) => replyToThread(key, text)) {
|
|
5138
5430
|
if (checkIsGeneral(key) || !state.getBinding(key) || getResumableSessionId(key) === null)
|
|
5139
5431
|
return { isAwake: false, isNoticePosted: false };
|
|
5140
|
-
const ensured = await
|
|
5432
|
+
const ensured = await sessionTransitions.run((0, sessionKey_1.keyToString)(key), async () => {
|
|
5433
|
+
if (!state.getBinding(key) || getResumableSessionId(key) === null)
|
|
5434
|
+
return null;
|
|
5435
|
+
return ensureAgentSessionNow(key, {});
|
|
5436
|
+
});
|
|
5437
|
+
if (ensured === null)
|
|
5438
|
+
return { isAwake: false, isNoticePosted: false, isEnded: true };
|
|
5141
5439
|
if (ensured.message)
|
|
5142
5440
|
await sendNotice(ensured.message);
|
|
5143
5441
|
return { isAwake: ensured.ok && (0, createAdapter_1.getThreadAdapter)(key).checkIsActive(key), isNoticePosted: Boolean(ensured.message) };
|
|
@@ -5148,29 +5446,50 @@ async function wakeSleepingSessionForPrompt(key, sendNotice = (text) => replyToT
|
|
|
5148
5446
|
* routine as a live message (new-message marker + loader + `sendInput`).
|
|
5149
5447
|
*/
|
|
5150
5448
|
async function replayBufferedPrompts(key) {
|
|
5449
|
+
// A command that ends or replaces the conversation (a release, `/new`, a `/resume` pick, a move or a start onto another backend) waits
|
|
5450
|
+
// behind the start or resume replaying this window: what the window holds was not sent for the conversation the command ends, so it is
|
|
5451
|
+
// dropped — a person told to send it again — not written there (review 22 nit 3, review 23 #1).
|
|
5452
|
+
if (conversationEndings.checkIsEnding((0, sessionKey_1.keyToString)(key))) {
|
|
5453
|
+
console.log(`[startup] ${(0, sessionKey_1.keyToString)(key)}: a command ends the conversation; the prompts its window held are dropped`);
|
|
5454
|
+
startupPromptBuffer.discardPrompts((0, sessionKey_1.keyToString)(key));
|
|
5455
|
+
return;
|
|
5456
|
+
}
|
|
5151
5457
|
const adapter = (0, createAdapter_1.getThreadAdapter)(key);
|
|
5152
5458
|
const isSessionActive = adapter.checkIsActive(key);
|
|
5153
5459
|
// The buffer closes the window synchronously and settles every prompt it held (a sender waiting on one,
|
|
5154
5460
|
// like the API-error retry's nudge, hears whether it reached the session).
|
|
5461
|
+
// The whole replay — the buffered prompts and the held ones after them — is still the start for the wake-up engine's turn probe
|
|
5462
|
+
// (`StartupPromptBuffer.checkIsReplaying`): no watch made during the start is read as a turn that ended (`requests/README.md` § Turn starts).
|
|
5155
5463
|
await startupPromptBuffer.replayPrompts((0, sessionKey_1.keyToString)(key), {
|
|
5156
5464
|
isSessionActive,
|
|
5157
|
-
forward: async (prompt,
|
|
5465
|
+
forward: async (prompt, options) => {
|
|
5466
|
+
const outcome = await forwardPromptToAgent(key, adapter, prompt, undefined, options);
|
|
5467
|
+
// A guard: the replay writes into the process the start brought up, never an adopted one, so no wake can come up empty here. If
|
|
5468
|
+
// one did, the buffer settles the prompt `dropped` — never «replayed» for a prompt no agent got (review 21, own pass).
|
|
5469
|
+
if (outcome === 'noSession')
|
|
5470
|
+
throw new Error(noSessionForPostError);
|
|
5471
|
+
},
|
|
5472
|
+
afterReplay: async () => {
|
|
5473
|
+
// A command that ends or replaces the conversation runs (a move's own start among them): the held prompts wait for the first
|
|
5474
|
+
// prompt it hands over — a replayable one, which carries them after its own text (R23) — instead of reaching the new agent ahead of
|
|
5475
|
+
// the move's bridge; with none, the next prompt carries them (review 26 #5).
|
|
5476
|
+
if (conversationEndings.checkIsRefusingMessages((0, sessionKey_1.keyToString)(key)))
|
|
5477
|
+
return;
|
|
5478
|
+
// R23: prompts held during a usage-limit wait that ended with the previous
|
|
5479
|
+
// session go to this one — on their own when nothing above carried them. They
|
|
5480
|
+
// are what people asked for meanwhile: a write that fails is told in the topic
|
|
5481
|
+
// like a person's own message, never only logged.
|
|
5482
|
+
const heldText = limitHeldPrompts.releaseAll(key);
|
|
5483
|
+
if (heldText === null)
|
|
5484
|
+
return;
|
|
5485
|
+
try {
|
|
5486
|
+
await forwardPromptToAgent(key, adapter, heldText, undefined, { isPersonInput: true });
|
|
5487
|
+
}
|
|
5488
|
+
catch (err) {
|
|
5489
|
+
console.error('[replayBufferedPrompts] forwarding the held prompts failed:', err);
|
|
5490
|
+
}
|
|
5491
|
+
},
|
|
5158
5492
|
});
|
|
5159
|
-
if (!isSessionActive)
|
|
5160
|
-
return;
|
|
5161
|
-
// R23: prompts held during a usage-limit wait that ended with the previous
|
|
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.
|
|
5165
|
-
const heldText = limitHeldPrompts.releaseAll(key);
|
|
5166
|
-
if (heldText === null)
|
|
5167
|
-
return;
|
|
5168
|
-
try {
|
|
5169
|
-
await forwardPromptToAgent(key, adapter, heldText, undefined, { isPersonInput: true });
|
|
5170
|
-
}
|
|
5171
|
-
catch (err) {
|
|
5172
|
-
console.error('[replayBufferedPrompts] forwarding the held prompts failed:', err);
|
|
5173
|
-
}
|
|
5174
5493
|
}
|
|
5175
5494
|
/**
|
|
5176
5495
|
* @description Forward one user prompt to a live agent: mark the thread for a
|
|
@@ -5213,16 +5532,33 @@ async function forwardPromptToAgent(key, adapter, text, sentAtMs, options = {})
|
|
|
5213
5532
|
// A technical prompt (the standalone todo reminder) goes only into a session that is live and idle now, and is otherwise
|
|
5214
5533
|
// dropped without a word: never buffered, never a resume, never a "no session" line to the person.
|
|
5215
5534
|
const isTechnicalPrompt = options.isTechnicalPrompt === true;
|
|
5535
|
+
const isPersonInput = options.isPersonInput === true;
|
|
5216
5536
|
const outcome = await (0, promptDelivery_1.deliverLatePrompt)({
|
|
5217
5537
|
isTechnical: isTechnicalPrompt,
|
|
5538
|
+
// A post waits again here, after the replay wait: a move may have begun during it (review 28 nit 2).
|
|
5539
|
+
waitBeforeRoute: options.waitBeforeRoute,
|
|
5218
5540
|
checkIsWindowOpen: () => startupPromptBuffer.checkIsStarting((0, sessionKey_1.keyToString)(key)),
|
|
5219
|
-
|
|
5541
|
+
// Whether the process takes input, as every routing point reads it: one a release or a move is stopping takes nothing (review 25
|
|
5542
|
+
// nit 7). A technical prompt goes only into an idle one.
|
|
5543
|
+
checkIsSessionActive: () => checkIsAcceptingInput(key) && !(isTechnicalPrompt && (adapter.checkIsBusy?.(key) ?? false)),
|
|
5544
|
+
// A person's prompt is refused while a command ends or replaces the conversation, as at its own write (review 25 #1).
|
|
5545
|
+
...(isPersonInput ? {
|
|
5546
|
+
checkIsRefused: () => checkIsPersonPromptRefused(key, options.requestId ?? null),
|
|
5547
|
+
reportRefused: () => reportDroppedPersonPrompt(key, options.requestId ?? null, true),
|
|
5548
|
+
} : {}),
|
|
5220
5549
|
buffer: async () => {
|
|
5550
|
+
const bufferedText = `${options.requestHeader ?? ''}${getPromptWithThreadMessageContext(key, text, options.messageContext)}`;
|
|
5551
|
+
// A post's wait is for this delivery's own routing; the startup buffer keeps none for the replay (`deliverPromptOrBuffer`).
|
|
5552
|
+
const bufferedOptions = { isPersonInput: options.isPersonInput, isAccountsNoteCarrier: options.isAccountsNoteCarrier, lostWorkTelling: options.lostWorkTelling, waitBeforeRoute: options.waitBeforeRoute };
|
|
5553
|
+
// A person's prompt that is dropped there is told about and closes its request, as at the person's own buffer.
|
|
5554
|
+
if (isPersonInput) {
|
|
5555
|
+
await deliverPromptOrBuffer(key, bufferedText, createPersonBufferedSettle(key, options.requestId ?? null), bufferedOptions);
|
|
5556
|
+
return;
|
|
5557
|
+
}
|
|
5221
5558
|
// A bot-made prompt (a wake-up) that waits here counts only once its replay reached the agent, as at any other buffer.
|
|
5222
5559
|
const buffered = createBufferedOutcome();
|
|
5223
|
-
await deliverPromptOrBuffer(key,
|
|
5224
|
-
|
|
5225
|
-
await buffered.assertReplayed();
|
|
5560
|
+
await deliverPromptOrBuffer(key, bufferedText, buffered.settle, bufferedOptions);
|
|
5561
|
+
await buffered.assertReplayed();
|
|
5226
5562
|
},
|
|
5227
5563
|
wake: () => wakeSleepingSessionForPrompt(key),
|
|
5228
5564
|
forward: async () => {
|
|
@@ -5241,6 +5577,18 @@ async function forwardPromptToAgent(key, adapter, text, sentAtMs, options = {})
|
|
|
5241
5577
|
}
|
|
5242
5578
|
/** @description The forward itself, for a session that is ready to take the prompt: {@link forwardPromptToAgent} minus the replay wait. */
|
|
5243
5579
|
async function forwardPromptToLiveAgent(key, adapter, text, sentAtMs, options = {}) {
|
|
5580
|
+
// A new prompt starts or joins a turn: the watches whose turn already ENDED are settled first, synchronously and before the write
|
|
5581
|
+
// (no await may precede it), so the new turn never runs under the watch of the turn before it (`requests/README.md` § Turn starts).
|
|
5582
|
+
// Their reminders are delivered once persisted — after this write, which runs in this tick, or, while a post is on its way to its
|
|
5583
|
+
// write, after that post's prompt (the todo reminder written at a turn end is such a write).
|
|
5584
|
+
settleEndedTurnsAndHandOver(key);
|
|
5585
|
+
// Any write during the replay of a start's buffer — a replayed prompt, the held prompts after them, a prompt written at once while it
|
|
5586
|
+
// runs — goes to the process the replay writes the buffer into (`noteReplayedWrite`); no write outside a replay names anything.
|
|
5587
|
+
if (startupPromptBuffer.checkIsReplaying((0, sessionKey_1.keyToString)(key)))
|
|
5588
|
+
requestWakeUpEngine?.noteReplayedWrite(key);
|
|
5589
|
+
// Every write stamps the process it goes to, so a watch tracked once that process went down (a re-spawn right after a post's write)
|
|
5590
|
+
// is named from the write (review 22 nit 2).
|
|
5591
|
+
requestWakeUpEngine?.noteWrite(key);
|
|
5244
5592
|
// A forwarded prompt is thread activity — reset the compact-on-idle watchdog (F2).
|
|
5245
5593
|
noteThreadActivity(key);
|
|
5246
5594
|
const isTechnicalPrompt = options.isTechnicalPrompt ?? false;
|
|
@@ -5281,7 +5629,9 @@ async function forwardPromptToLiveAgent(key, adapter, text, sentAtMs, options =
|
|
|
5281
5629
|
// request's reminder included: the wake of a tracker request whose process a restart left behind is how its agent hears.
|
|
5282
5630
|
const isLostWorkNoteCarried = (isReplayable || options.isRequestReminder === true) && adapter.name !== 'terminal';
|
|
5283
5631
|
const lostWorkRecord = isLostWorkNoteCarried ? state.getLostWork(key) : undefined;
|
|
5284
|
-
const body = lostWorkRecord
|
|
5632
|
+
const body = lostWorkRecord
|
|
5633
|
+
? `${(0, lostWork_1.buildLostWorkNote)(lostWorkRecord, (0, i18n_1.getLocaleEndonym)((0, i18n_1.getActiveLang)()), { telling: options.lostWorkTelling ?? 'plain' })}\n\n${messageBody}`
|
|
5634
|
+
: messageBody;
|
|
5285
5635
|
// Cache the (reply-folded) prompt so a wedged OpenCode session can be recovered
|
|
5286
5636
|
// by restarting fresh and replaying it — replaying WITH the quote is correct.
|
|
5287
5637
|
// A genuine new prompt also opens a fresh recovery episode (clears the guard).
|
|
@@ -5311,6 +5661,8 @@ async function forwardPromptToLiveAgent(key, adapter, text, sentAtMs, options =
|
|
|
5311
5661
|
// then the todo list's staleness reminder rides the next real prompt from any source (D11 form a) — never a slash
|
|
5312
5662
|
// command or a shell line; the reminder never rides the standalone reminder itself.
|
|
5313
5663
|
const isTodoDecorated = !isSlashCommand && adapter.name !== 'terminal';
|
|
5664
|
+
// Any forward is a turn start (a slash command too: `/compact` opens a held turn): the accounts note's mid-turn section goes.
|
|
5665
|
+
withdrawAccountsInbox(key);
|
|
5314
5666
|
if (isTodoDecorated)
|
|
5315
5667
|
discardTodoInbox(key);
|
|
5316
5668
|
const todoBoardBlock = isTodoDecorated ? takeTodoPromptBoard(key) : null;
|
|
@@ -5319,6 +5671,14 @@ async function forwardPromptToLiveAgent(key, adapter, text, sentAtMs, options =
|
|
|
5319
5671
|
const todoReminderLine = isTodoDecorated && !isTechnicalPrompt ? takeTodoPromptReminder(key) : null;
|
|
5320
5672
|
if (todoReminderLine !== null)
|
|
5321
5673
|
promptText = `${promptText}\n\n${todoReminderLine}`;
|
|
5674
|
+
// The accounts note (`limitNotes/`) is the LAST block of a carrier prompt — a turn the person or the scheduler starts — inside the
|
|
5675
|
+
// ONE text written to the agent: never a write of its own, never an activity stamp (`limitNotes/README.md` § Lifecycle safety).
|
|
5676
|
+
// Told only once the prompt that carries it reached a live session, like the lost-work note below.
|
|
5677
|
+
const accountsNote = (0, service_1.checkIsAccountsNoteCarried)({ isCarrier: options.isAccountsNoteCarrier, isSlashCommand, adapterName: adapter.name })
|
|
5678
|
+
? getLimitNotes().takeTurnStartNote(key, (0, service_1.getAccountsNoteQuietMs)({ lastTurnEndAt: state.getCompactIdleTracking(key).lastTurnEndAt, isBusy: adapter.checkIsBusy?.(key), nowMs: Date.now() }))
|
|
5679
|
+
: null;
|
|
5680
|
+
if (accountsNote !== null)
|
|
5681
|
+
promptText = (0, noteText_1.appendLimitNote)(promptText, accountsNote.text);
|
|
5322
5682
|
markNeedsNewMessage(key);
|
|
5323
5683
|
// A new prompt is a new turn: lift the S2 idle-suppress latch and re-base the
|
|
5324
5684
|
// working-status elapsed so the next busy period shows a fresh 0:00 counter
|
|
@@ -5348,6 +5708,11 @@ async function forwardPromptToLiveAgent(key, adapter, text, sentAtMs, options =
|
|
|
5348
5708
|
// A backend that can tell whether the prompt reached the agent (the json-stream host's stdin write) is asked to: a
|
|
5349
5709
|
// write that failed rejects this forward, so its caller — a tracker post, a wake-up — knows the prompt never arrived
|
|
5350
5710
|
// and retries, instead of believing it delivered. The input is handed over synchronously either way; only its outcome is awaited.
|
|
5711
|
+
// The turn this prompt opens on an idle session is a BOOKKEEPING turn unless a person, a tracker or the scheduler started it (a slash
|
|
5712
|
+
// command is neither: a skill's turn does real work, a compaction's is held open anyway): the mid-turn engine gives such a turn no
|
|
5713
|
+
// reminder, as its start carried none. Read after the interrupt above, so a person's prompt that ended a bookkeeping turn is judged
|
|
5714
|
+
// on its own.
|
|
5715
|
+
getLimitNotes().noteTurnStart(key, { isBookkeeping: options.isAccountsNoteCarrier !== true && !isSlashCommand, isSessionIdle: adapter.checkIsBusy?.(key) === false });
|
|
5351
5716
|
const written = adapter.sendInputAndWait ? adapter.sendInputAndWait(key, promptText) : (adapter.sendInput(key, promptText), Promise.resolve());
|
|
5352
5717
|
// S2 busy-onset arm: start the Claude liveness loop the moment the prompt is
|
|
5353
5718
|
// forwarded — driven by `checkIsBusy`, not by waiting for an opportunistic
|
|
@@ -5361,7 +5726,17 @@ async function forwardPromptToLiveAgent(key, adapter, text, sentAtMs, options =
|
|
|
5361
5726
|
const noteToldIfDelivered = () => {
|
|
5362
5727
|
if (lostWorkRecord && adapter.checkIsActive(key))
|
|
5363
5728
|
void state.clearLostWork(key);
|
|
5729
|
+
// The note is in flight until here: recorded when the session got the prompt, given back when it was gone.
|
|
5730
|
+
if (accountsNote !== null) {
|
|
5731
|
+
if (adapter.checkIsActive(key))
|
|
5732
|
+
accountsNote.markDelivered();
|
|
5733
|
+
else
|
|
5734
|
+
accountsNote.release();
|
|
5735
|
+
}
|
|
5364
5736
|
};
|
|
5737
|
+
// A write that failed gives the note back too: the next carrier prompt carries it (the failure itself is handled below, as ever).
|
|
5738
|
+
if (accountsNote !== null)
|
|
5739
|
+
void written.catch(() => accountsNote.release());
|
|
5365
5740
|
// A person's own message never holds the topic's update queue on its write — a CLI that stops reading its input would
|
|
5366
5741
|
// keep `/esc` and every tap behind it for minutes —: they are told when it failed. Every other prompt (a tracker's post,
|
|
5367
5742
|
// a wake-up, a scheduled run, a retry's nudge, the todo reminder) awaits it: one that never arrived is retried.
|
|
@@ -5485,10 +5860,6 @@ function getPromptWithThreadMessageContext(key, text, messageContext) {
|
|
|
5485
5860
|
});
|
|
5486
5861
|
}
|
|
5487
5862
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
5488
|
-
// Natural-language start phrases (`claude ...`, `opencode ...`)
|
|
5489
|
-
// ═══════════════════════════════════════════════════════════════════════════════
|
|
5490
|
-
// (Parser imported up-top — see `parseAgentTrigger` import.)
|
|
5491
|
-
// ═══════════════════════════════════════════════════════════════════════════════
|
|
5492
5863
|
// Model selection helper — used by /model and the numeric-reply flow
|
|
5493
5864
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
5494
5865
|
function formatTimeAgo(date) {
|
|
@@ -5567,7 +5938,7 @@ const botCore = {
|
|
|
5567
5938
|
cancelConversationRequest,
|
|
5568
5939
|
wakeSleepingSession,
|
|
5569
5940
|
};
|
|
5570
|
-
const { checkIsThreadCompacting, noteThreadActivity,
|
|
5941
|
+
const { checkIsThreadCompacting, noteThreadActivity, noteThreadTurnContext, markThreadTurnProducedOutput, postOwnCompactionInstructionGaps, routeStreamedCompactionSummaryTail, clearThreadCompaction, rearmThreadIdleTimer, armDeferredCompaction, checkIsDeferredCompactionArmed, threadsCompacting, answerReAskedQuestionByNumber, reAskInterruptedQuestion, restoreReAskedQuestion, closeSavedReAskedQuestion, closeReAskedQuestion, syncThreadCompactSelfReviewFlags, syncAllCompactSelfReviewFlags, registerCompactionCommands, registerCompactionCallbacks, } = (0, compaction_1.createCompaction)({
|
|
5571
5942
|
...botCore,
|
|
5572
5943
|
startTypingLoader,
|
|
5573
5944
|
forwardPromptToAgent: async (key, adapter, text) => { await forwardPromptToAgent(key, adapter, text); },
|
|
@@ -5581,6 +5952,7 @@ const { checkIsThreadCompacting, noteThreadActivity, noteThreadUserActivity, mar
|
|
|
5581
5952
|
suspendThreadSession,
|
|
5582
5953
|
// L-D7: a sleeping per-turn session is woken for its idle compaction — a resume only, never a fresh start.
|
|
5583
5954
|
resumeSleepingSessionForCompaction: async (key) => (await ensureAgentSession(key, { isResumeOnly: true })).ok && (0, createAdapter_1.getThreadAdapter)(key).checkIsActive(key),
|
|
5955
|
+
readSleepingContext: readSleepingConversationContext,
|
|
5584
5956
|
getThreadAdapter: createAdapter_1.getThreadAdapter,
|
|
5585
5957
|
// An answer to the agent's own question is never a request (S7), even delivered as a prompt.
|
|
5586
5958
|
// The label of a re-asked question reaches the agent as a prompt; a topic member's carries their mark, the operator's stays bare.
|
|
@@ -6090,43 +6462,35 @@ async function pauseThreadSchedulesOnUnbind(key) {
|
|
|
6090
6462
|
}, key);
|
|
6091
6463
|
}
|
|
6092
6464
|
/**
|
|
6093
|
-
* @description
|
|
6094
|
-
*
|
|
6095
|
-
|
|
6096
|
-
|
|
6097
|
-
|
|
6098
|
-
|
|
6099
|
-
|
|
6465
|
+
* @description The scheduler's ports for resuming a conversation's unbound-paused jobs (`scheduler/rebindResume.ts`);
|
|
6466
|
+
* `announceResumed` is the platform's way of saying so.
|
|
6467
|
+
*/
|
|
6468
|
+
function createRebindResumePorts(announceResumed) {
|
|
6469
|
+
return {
|
|
6470
|
+
listThreadSchedules: (key) => state.getThreadSchedules(key),
|
|
6471
|
+
removeSchedule: (jobId) => state.removeSchedule(jobId),
|
|
6472
|
+
upsertSchedule: (record) => state.upsertSchedule(record),
|
|
6473
|
+
armJob: (record) => schedulerEngine?.armJob(record),
|
|
6474
|
+
disarmJob: (jobId) => schedulerEngine?.disarmJob(jobId),
|
|
6475
|
+
announceResumed,
|
|
6476
|
+
now: () => Date.now(),
|
|
6477
|
+
};
|
|
6478
|
+
}
|
|
6479
|
+
/**
|
|
6480
|
+
* @description Resume the schedules paused for `'unbound'` on `key` when its topic is rebound (S8), with ONE notice in the
|
|
6481
|
+
* topic carrying the resumed count (`scheduler/rebindResume.ts`).
|
|
6100
6482
|
*/
|
|
6101
6483
|
async function resumeThreadSchedulesOnRebind(key) {
|
|
6102
|
-
|
|
6103
|
-
|
|
6104
|
-
|
|
6105
|
-
|
|
6106
|
-
|
|
6107
|
-
|
|
6108
|
-
|
|
6109
|
-
|
|
6110
|
-
|
|
6111
|
-
|
|
6112
|
-
await state.removeSchedule(record.id);
|
|
6113
|
-
schedulerEngine?.disarmJob(record.id);
|
|
6114
|
-
continue;
|
|
6115
|
-
}
|
|
6116
|
-
const updated = {
|
|
6117
|
-
...record,
|
|
6118
|
-
nextRunAt: action.nextRunAt,
|
|
6119
|
-
updatedAt: new Date(nowMs).toISOString(),
|
|
6120
|
-
};
|
|
6121
|
-
delete updated.isPaused;
|
|
6122
|
-
delete updated.pauseReason;
|
|
6123
|
-
await state.upsertSchedule(updated);
|
|
6124
|
-
schedulerEngine?.armJob(updated);
|
|
6125
|
-
resumed += 1;
|
|
6126
|
-
}
|
|
6127
|
-
if (resumed > 0) {
|
|
6128
|
-
await replyToThread(key, (0, i18n_1.t)('schedule.resumedRebind', { count: resumed }));
|
|
6129
|
-
}
|
|
6484
|
+
await (0, rebindResume_1.resumeSchedulesPausedForUnbound)(createRebindResumePorts((count) => replyToThread(key, (0, i18n_1.t)('schedule.resumedRebind', { count })).then(() => undefined)), key);
|
|
6485
|
+
}
|
|
6486
|
+
/**
|
|
6487
|
+
* @description Resume the jobs a tracker conversation's fire paused for a folder it could not use, once a request of the issue
|
|
6488
|
+
* finds the folder usable again — what `/bind` does in a topic. The bot posts nothing on an issue: the resume is one log line.
|
|
6489
|
+
*/
|
|
6490
|
+
async function resumeTrackerSchedulesOnRebind(key) {
|
|
6491
|
+
await (0, rebindResume_1.resumeSchedulesPausedForUnbound)(createRebindResumePorts(async (count) => {
|
|
6492
|
+
console.log(`[scheduler] ${count} job(s) of ${(0, sessionKey_1.keyToString)(key)} resumed: its folder is usable again`);
|
|
6493
|
+
}), key);
|
|
6130
6494
|
}
|
|
6131
6495
|
/**
|
|
6132
6496
|
* @description Arm a thread's await-folder-name mode for the `/bind`
|
|
@@ -6287,16 +6651,21 @@ command('bind', async (_ctx, key, parsed) => {
|
|
|
6287
6651
|
* pinned banner, release persisted session ids, pause the thread's schedules,
|
|
6288
6652
|
* then wipe the binding. Shared by the `/bind` picker's «leave current dir»
|
|
6289
6653
|
* button (the old `/unbind` command was folded into it). Safe to call only on a
|
|
6290
|
-
* BOUND, non-General topic — the leave button only renders there.
|
|
6654
|
+
* BOUND, non-General topic — the leave button only renders there. `ending` is the
|
|
6655
|
+
* tap's hold on the conversation, taken ahead of its toast (review 24 #1).
|
|
6291
6656
|
*/
|
|
6292
|
-
async function unbindThread(key) {
|
|
6657
|
+
async function unbindThread(key, ending) {
|
|
6293
6658
|
// Mark this thread as in-flight unbinding so the adapter's synchronous
|
|
6294
6659
|
// `stopped` event doesn't race us and re-pin a stale "idle" banner over
|
|
6295
6660
|
// the message we're about to delete.
|
|
6296
6661
|
const kStr = (0, sessionKey_1.keyToString)(key);
|
|
6297
6662
|
unbindingKeys.add(kStr);
|
|
6298
|
-
// Leaving the folder ends the conversation's work: its open
|
|
6299
|
-
|
|
6663
|
+
// Leaving the folder ends the conversation's work: its open requests close, a person whose words the agent never read told (review 26
|
|
6664
|
+
// #2) — read now, ahead of the stop.
|
|
6665
|
+
cancelEndingConversationRequests(key);
|
|
6666
|
+
// Refused until the binding is gone, past the hold's transition: a post that waited (`waitForConversationChange`) then meets an unbound
|
|
6667
|
+
// topic and pauses its job, instead of starting a fresh agent in the folder being left (review 27 nit 4).
|
|
6668
|
+
const stopRefusingMessages = conversationEndings.refuseMessages(key);
|
|
6300
6669
|
try {
|
|
6301
6670
|
// Order matters: drop the pin FIRST (while binding.pinnedStatusMessageId
|
|
6302
6671
|
// is still readable), then stop the session, then wipe the binding.
|
|
@@ -6307,24 +6676,35 @@ async function unbindThread(key) {
|
|
|
6307
6676
|
if (pendingQuestions.has(kStr))
|
|
6308
6677
|
await retirePendingQuestion(key);
|
|
6309
6678
|
// Stop any running session before discarding the binding so we don't leave
|
|
6310
|
-
// an orphan tmux/SSE stream pointing at a directory we no longer track.
|
|
6311
|
-
|
|
6312
|
-
|
|
6313
|
-
|
|
6314
|
-
|
|
6315
|
-
|
|
6316
|
-
|
|
6317
|
-
|
|
6318
|
-
|
|
6319
|
-
|
|
6320
|
-
|
|
6321
|
-
|
|
6322
|
-
|
|
6679
|
+
// an orphan tmux/SSE stream pointing at a directory we no longer track. As the
|
|
6680
|
+
// conversation's one transition, after a re-spawn: a start, a resume or a
|
|
6681
|
+
// re-spawn in flight is over first, so none brings a process back for the
|
|
6682
|
+
// conversation released here (review 22, own pass). Held as ending it since the
|
|
6683
|
+
// tap, ahead of the toast, the unpin and the question's retirement above: a stop
|
|
6684
|
+
// queued ahead drops what it held (review 23 #1, review 24 #1). The stop is waited
|
|
6685
|
+
// for, so nothing queued behind writes into a process still exiting (review 23 nit 4).
|
|
6686
|
+
await ending.run(async () => {
|
|
6687
|
+
const adapter = (0, createAdapter_1.getThreadAdapter)(key);
|
|
6688
|
+
if (adapter.checkIsActive(key)) {
|
|
6689
|
+
// Close any still-pending OpenCode question on the server BEFORE stopping
|
|
6690
|
+
// the session — a stopped session can't accept the reject, and an
|
|
6691
|
+
// unrejected question re-surfaces on the next reattach. No-op for Claude /
|
|
6692
|
+
// no pending question.
|
|
6693
|
+
adapter.rejectQuestion?.(key);
|
|
6694
|
+
try {
|
|
6695
|
+
if (adapter.stopSessionAndWait)
|
|
6696
|
+
await adapter.stopSessionAndWait(key);
|
|
6697
|
+
else
|
|
6698
|
+
adapter.stopSession(key);
|
|
6699
|
+
}
|
|
6700
|
+
catch (e) {
|
|
6701
|
+
console.warn(`[unbind] stopSession failed for ${kStr}:`, e);
|
|
6702
|
+
}
|
|
6323
6703
|
}
|
|
6324
|
-
|
|
6325
|
-
|
|
6326
|
-
|
|
6327
|
-
|
|
6704
|
+
// Release persisted session ids too — otherwise re-binding this thread
|
|
6705
|
+
// later + a bot restart would resurrect the old session the user unbound.
|
|
6706
|
+
await releaseConversationIds(key);
|
|
6707
|
+
});
|
|
6328
6708
|
// Pause this thread's schedules BEFORE dropping the binding: a fire against
|
|
6329
6709
|
// an unbound topic can't deliver, so the jobs park (paused + disarmed) and
|
|
6330
6710
|
// the next /bind resumes them. `removeBinding` only touches bindings/agents/
|
|
@@ -6338,6 +6718,7 @@ async function unbindThread(key) {
|
|
|
6338
6718
|
await replyToThread(key, (0, i18n_1.t)('thread.unbound'));
|
|
6339
6719
|
}
|
|
6340
6720
|
finally {
|
|
6721
|
+
stopRefusingMessages();
|
|
6341
6722
|
unbindingKeys.delete(kStr);
|
|
6342
6723
|
}
|
|
6343
6724
|
}
|
|
@@ -6433,19 +6814,29 @@ command('new', async (_ctx, key) => {
|
|
|
6433
6814
|
await replyToThread(key, (0, i18n_1.t)('thread.bind_required'));
|
|
6434
6815
|
return;
|
|
6435
6816
|
}
|
|
6436
|
-
// A fresh session does not know the old one's
|
|
6437
|
-
|
|
6817
|
+
// A fresh session does not know the old one's requests: they close, a person whose words the agent never read told (review 26 #2).
|
|
6818
|
+
cancelEndingConversationRequests(key);
|
|
6438
6819
|
// Release the current session (sweep + clear ids) via `releaseThreadSession`.
|
|
6439
6820
|
// The fresh start below uses the thread's current adapter, so we keep the
|
|
6440
|
-
// adapter selection untouched.
|
|
6441
|
-
|
|
6821
|
+
// adapter selection untouched. Both as the conversation's one transition: an idle stop under way ends first — dropping what it held,
|
|
6822
|
+
// the person told, since this command holds the conversation as ending (review 25 nit 6) —, and no ensure starts a second session beside
|
|
6823
|
+
// this one.
|
|
6442
6824
|
// `startAgentSession` handles startup buffering, the typing-loader boot, and
|
|
6443
6825
|
// the preamble-marker reset. It returns `''` for a self-greeting agent (Claude
|
|
6444
6826
|
// prints its own banner) — show a notice only for a non-empty ready text.
|
|
6445
|
-
|
|
6827
|
+
// Held as ending the conversation while it waits: a stop under way drops what it held instead of resuming the old conversation (review
|
|
6828
|
+
// 21 nit 4); a person's message is refused until the fresh start is over (review 25 #1).
|
|
6829
|
+
const msg = await startFreshSessionForNew(key);
|
|
6446
6830
|
if (msg)
|
|
6447
6831
|
await replyToThread(key, msg);
|
|
6448
6832
|
});
|
|
6833
|
+
/** `/new`'s release and fresh start, as the conversation's one transition, the conversation held as ending until that transition begins. */
|
|
6834
|
+
function startFreshSessionForNew(key) {
|
|
6835
|
+
return conversationEndings.hold(key).run(async () => {
|
|
6836
|
+
await releaseThreadSession(key);
|
|
6837
|
+
return startAgentSession(key);
|
|
6838
|
+
});
|
|
6839
|
+
}
|
|
6449
6840
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
6450
6841
|
// /whoami /version /help /status (global) — debug & onboarding
|
|
6451
6842
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
@@ -6714,7 +7105,7 @@ async function sendBindingWelcome(key, subdir, notes = {}) {
|
|
|
6714
7105
|
if (welcomeMessageId !== null)
|
|
6715
7106
|
openWelcomeMessages.remember((0, sessionKey_1.keyToString)(key), welcomeMessageId, Date.now());
|
|
6716
7107
|
// Every bind ends in this welcome, so every bind sweeps here — after the welcome, and NOT waited for: what follows a bind
|
|
6717
|
-
// (an agent start
|
|
7108
|
+
// (an agent start) must not hang on the deletions and edits, which are paced sends.
|
|
6718
7109
|
void stripWelcomeKeyboards(key, outdatedWelcomeIds);
|
|
6719
7110
|
void closeOpenBindMessages(key);
|
|
6720
7111
|
}
|
|
@@ -6750,6 +7141,7 @@ async function runDoctor() {
|
|
|
6750
7141
|
lines.push(nativeWindowsLine);
|
|
6751
7142
|
// 1. Bot admin permissions in the configured group.
|
|
6752
7143
|
const groupId = getAllowedGroupId();
|
|
7144
|
+
let isBotAdmin = false;
|
|
6753
7145
|
if (groupId === null) {
|
|
6754
7146
|
lines.push({ status: 'warn', label: (0, i18n_1.t)('doctor.bot_admin'), hint: (0, i18n_1.t)('pair.not_paired') });
|
|
6755
7147
|
}
|
|
@@ -6758,6 +7150,7 @@ async function runDoctor() {
|
|
|
6758
7150
|
const botId = bot.botInfo?.id ?? (await bot.telegram.getMe()).id;
|
|
6759
7151
|
const member = await bot.telegram.getChatMember(groupId, botId);
|
|
6760
7152
|
if (member.status === 'administrator') {
|
|
7153
|
+
isBotAdmin = true;
|
|
6761
7154
|
lines.push({ status: 'ok', label: (0, i18n_1.t)('doctor.bot_admin') });
|
|
6762
7155
|
lines.push({
|
|
6763
7156
|
status: member.can_manage_topics ? 'ok' : 'fail',
|
|
@@ -6790,15 +7183,13 @@ async function runDoctor() {
|
|
|
6790
7183
|
hint: (0, i18n_1.t)('doctor.no_admin_info'),
|
|
6791
7184
|
});
|
|
6792
7185
|
}
|
|
6793
|
-
// 2. Privacy mode (
|
|
6794
|
-
// but `getMe().can_read_all_group_messages === false` indicates it's on
|
|
7186
|
+
// 2. Privacy mode — only a non-admin bot depends on it (`getPrivacyDoctorLine`). The Bot API doesn't expose the mode itself,
|
|
7187
|
+
// but `getMe().can_read_all_group_messages === false` indicates it's on.
|
|
6795
7188
|
try {
|
|
6796
7189
|
const me = await bot.telegram.getMe();
|
|
6797
|
-
|
|
6798
|
-
|
|
6799
|
-
|
|
6800
|
-
hint: (0, i18n_1.t)('doctor.privacy_hint'),
|
|
6801
|
-
});
|
|
7190
|
+
const privacyLine = (0, doctorLine_1.getPrivacyDoctorLine)({ isBotAdmin, canReadAllGroupMessages: me.can_read_all_group_messages }, i18n_1.t);
|
|
7191
|
+
if (privacyLine)
|
|
7192
|
+
lines.push(privacyLine);
|
|
6802
7193
|
}
|
|
6803
7194
|
catch { /* skip silently — covered by admin check above */ }
|
|
6804
7195
|
// 3. WORK_ROOT.
|
|
@@ -6923,15 +7314,18 @@ command('mcp', async (_ctx, key) => {
|
|
|
6923
7314
|
*
|
|
6924
7315
|
* `adapterName` is typed `string` because the button passes a raw callback match;
|
|
6925
7316
|
* an unknown name makes `getThreadAdapter` throw, which the caller wrapping this
|
|
6926
|
-
* (the `agent_*` action) turns into a "unknown agent" answer.
|
|
7317
|
+
* (the `agent_*` action) turns into a "unknown agent" answer. `ending` is the
|
|
7318
|
+
* caller's hold on the conversation when it already knows the start leaves it
|
|
7319
|
+
* (an agent button onto a shell, held ahead of its toast); without one the start
|
|
7320
|
+
* holds it itself once it knows.
|
|
6927
7321
|
*/
|
|
6928
|
-
async function handleAgentStart(key, adapterName, args) {
|
|
7322
|
+
async function handleAgentStart(key, adapterName, args, ending) {
|
|
6929
7323
|
if (checkIsGeneral(key)) {
|
|
6930
7324
|
await replyToThread(key, (0, i18n_1.t)('error.start_in_general'));
|
|
6931
7325
|
return;
|
|
6932
7326
|
}
|
|
6933
|
-
// Refuse to start an agent without a binding
|
|
6934
|
-
//
|
|
7327
|
+
// Refuse to start an agent without a binding: starting without one would silently launch against WORK_ROOT,
|
|
7328
|
+
// which is almost never wanted (plan §11 Этап 4).
|
|
6935
7329
|
if (!state.getBinding(key)) {
|
|
6936
7330
|
const subdirs = listAvailableSubdirs(ENV.workRoot);
|
|
6937
7331
|
const extra = (0, bindPicker_1.buildBindKeyboard)(subdirs, 0, bindPicker_1.BIND_PAGE_SIZE, !!state.getBinding(key));
|
|
@@ -6945,19 +7339,51 @@ async function handleAgentStart(key, adapterName, args) {
|
|
|
6945
7339
|
const targetFamily = (0, backendSwitchPlan_1.getBackendFamily)(adapterName);
|
|
6946
7340
|
if (targetFamily !== null && await askBeforeCrossBackendSwitch(key, targetFamily, args))
|
|
6947
7341
|
return;
|
|
6948
|
-
|
|
6949
|
-
|
|
6950
|
-
|
|
6951
|
-
|
|
6952
|
-
|
|
7342
|
+
// The switch runs as the conversation's one transition, after a re-spawn — a start or resume of the old backend in flight is over first
|
|
7343
|
+
// and none comes back beside the new one — and, when it leaves the conversation (another agent or a shell), held as ending it from here,
|
|
7344
|
+
// as a move is (review 23 nit 2), unless the caller held it already.
|
|
7345
|
+
const switchAdapter = () => switchThreadAdapter(key, adapterName);
|
|
7346
|
+
const isLeavingConversation = checkIsStartLeavingConversation(key, adapterName);
|
|
7347
|
+
// A start that leaves the conversation refuses a person's message until the new agent's start is over, as a move does until its first
|
|
7348
|
+
// prompt reached the other backend: between the switch and that start no agent takes it, and the start's window belongs to an agent that
|
|
7349
|
+
// does not know the conversation (review 25 #1, own pass).
|
|
7350
|
+
const stopRefusingMessages = isLeavingConversation ? conversationEndings.refuseMessages(key) : null;
|
|
7351
|
+
let msg;
|
|
7352
|
+
try {
|
|
7353
|
+
if (isLeavingConversation) {
|
|
7354
|
+
await (ending ?? conversationEndings.hold(key)).run(switchAdapter);
|
|
7355
|
+
}
|
|
7356
|
+
else {
|
|
7357
|
+
ending?.release();
|
|
7358
|
+
await runCommandSessionTransition(key, switchAdapter);
|
|
7359
|
+
}
|
|
7360
|
+
const adapter = (0, createAdapter_1.getThreadAdapter)(key);
|
|
7361
|
+
if (adapter.checkIsActive(key)) {
|
|
7362
|
+
await replyToThread(key, (0, i18n_1.t)('agent.already_active', { label: adapter.label }));
|
|
7363
|
+
return;
|
|
7364
|
+
}
|
|
7365
|
+
// A sleeping conversation is woken, not replaced (L-D4): `/new` is the fresh start. A first start is the conversation's one
|
|
7366
|
+
// transition too, and finds a session another trigger started meanwhile instead of starting a second one beside it.
|
|
7367
|
+
msg = getResumableSessionId(key) !== null
|
|
7368
|
+
? (await ensureAgentSession(key, { args })).message
|
|
7369
|
+
: await runCommandSessionTransition(key, async () => ((0, createAdapter_1.getThreadAdapter)(key).checkIsActive(key)
|
|
7370
|
+
? (0, i18n_1.t)('agent.already_active', { label: (0, createAdapter_1.getThreadAdapter)(key).label })
|
|
7371
|
+
: startAgentSession(key, args)));
|
|
7372
|
+
}
|
|
7373
|
+
finally {
|
|
7374
|
+
stopRefusingMessages?.();
|
|
6953
7375
|
}
|
|
6954
|
-
// A sleeping conversation is woken, not replaced (L-D4): `/new` is the fresh start.
|
|
6955
|
-
const msg = getResumableSessionId(key) !== null
|
|
6956
|
-
? (await ensureAgentSession(key, { args })).message
|
|
6957
|
-
: await startAgentSession(key, args);
|
|
6958
7376
|
if (msg)
|
|
6959
7377
|
await replyToThread(key, msg);
|
|
6960
7378
|
}
|
|
7379
|
+
/**
|
|
7380
|
+
* @description Whether starting `startAdapterName` (already resolved, `resolveStartAdapterName`) leaves the conversation the topic holds:
|
|
7381
|
+
* onto another agent or a shell. A switch within the Claude family keeps it (`checkIsSameConversationSwitch`).
|
|
7382
|
+
*/
|
|
7383
|
+
function checkIsStartLeavingConversation(key, startAdapterName) {
|
|
7384
|
+
const previousName = (0, createAdapter_1.getThreadAdapterNameRaw)(key);
|
|
7385
|
+
return previousName !== undefined && !(0, createAdapter_1.checkIsSameConversationSwitch)(previousName, startAdapterName);
|
|
7386
|
+
}
|
|
6961
7387
|
/**
|
|
6962
7388
|
* @description Thin wrapper extracting the trailing args from the command text
|
|
6963
7389
|
* for {@link handleAgentStart}. The args are everything after the command word
|
|
@@ -7024,6 +7450,12 @@ async function applyClaudeBackendSwitch(key, target) {
|
|
|
7024
7450
|
if (refusal)
|
|
7025
7451
|
return (0, i18n_1.t)('claudeMode.perTurn_refused', { version: refusal.version, min: claudeCodeVersion_1.minAutoStopClaudeCodeVersion });
|
|
7026
7452
|
}
|
|
7453
|
+
// As the conversation's one transition: the stop of the old backend and the resume on the new one never overlap an ensure or an idle
|
|
7454
|
+
// stop (review 20 nit 3).
|
|
7455
|
+
return runCommandSessionTransition(key, () => switchClaudeBackendNow(key, target, label));
|
|
7456
|
+
}
|
|
7457
|
+
/** {@link applyClaudeBackendSwitch}'s switch itself, inside the conversation's transition. */
|
|
7458
|
+
async function switchClaudeBackendNow(key, target, label) {
|
|
7027
7459
|
const wasActive = (0, createAdapter_1.getThreadAdapter)(key).checkIsActive(key);
|
|
7028
7460
|
const sessionId = state.getAgent(key)?.claudeSessionId;
|
|
7029
7461
|
// Stops the previous backend, records the pick, keeps `claudeSessionId`.
|
|
@@ -7035,19 +7467,16 @@ async function applyClaudeBackendSwitch(key, target) {
|
|
|
7035
7467
|
const decision = getWorkDirStartDecision(key);
|
|
7036
7468
|
if (!decision.ok)
|
|
7037
7469
|
return `${decision.message}${backgroundStoppedSuffix}`;
|
|
7038
|
-
const targetAdapter = (0, createAdapter_1.getThreadAdapter)(key);
|
|
7039
7470
|
sendThreadTypingIndicator(key).catch(() => { });
|
|
7040
|
-
if (sessionId
|
|
7041
|
-
markNeedsNewMessage(key);
|
|
7471
|
+
if (sessionId) {
|
|
7042
7472
|
clearThreadContextMarker(key);
|
|
7043
|
-
|
|
7044
|
-
|
|
7045
|
-
await persistSessionStart(key, targetAdapter);
|
|
7473
|
+
// The resume opens its startup window as a wake's does: a prompt that comes meanwhile waits and is replayed (review 20 nit 3).
|
|
7474
|
+
if ((await resumeSleepingSession(key, sessionId, { isWithRecentContext: true })) === null) {
|
|
7046
7475
|
return `${(0, i18n_1.t)('claudeMode.switched_resumed', { label })}${backgroundStoppedSuffix}`;
|
|
7047
7476
|
}
|
|
7048
|
-
|
|
7049
|
-
|
|
7050
|
-
|
|
7477
|
+
console.error(`[claude_mode] ${(0, sessionKey_1.keyToString)(key)}: the resume on the new backend failed; starting fresh`);
|
|
7478
|
+
// The fresh start takes the failed resume's window over, as after a failed wake: the people's prompts go to the fresh session.
|
|
7479
|
+
startupPromptBuffer.discardBotPrompts((0, sessionKey_1.keyToString)(key));
|
|
7051
7480
|
}
|
|
7052
7481
|
const msg = await startAgentSession(key);
|
|
7053
7482
|
return `${msg || (0, i18n_1.t)('claudeMode.switched_fresh', { label })}${backgroundStoppedSuffix}`;
|
|
@@ -7119,9 +7548,29 @@ const { applyAutoContinueLimits, consumeAutoContinueLimitsPicker, registerAutoCo
|
|
|
7119
7548
|
getRequestWakeUpEngine: () => requestWakeUpEngine,
|
|
7120
7549
|
});
|
|
7121
7550
|
registerAutoContinueLimitsCommands();
|
|
7551
|
+
// ── The worker roles (`/workers`): `connectors/telegram/commands/workerRoles.ts`, `utils/workerRolesScreenPlan.ts`, `utils/workerRoles.ts` ──
|
|
7552
|
+
const { registerWorkerRolesCommands, registerWorkerRolesCallbacks, openScreen: openWorkerRolesScreen } = (0, workerRoles_1.createWorkerRoles)({
|
|
7553
|
+
...botCore,
|
|
7554
|
+
readWorkerRoles: readWorkerRolesSettings,
|
|
7555
|
+
saveWorkerRoles: (workerRoles) => (0, instanceSettings_1.saveInstanceSettingsChange)((0, instanceSettings_1.getInstanceSettingsPath)(), { workerRoles }),
|
|
7556
|
+
getSettingsPath: () => (0, instanceSettings_1.getInstanceSettingsPath)(),
|
|
7557
|
+
listOpenCodeModels: async () => (await readOpenCodeCatalogForWorker()) ?? [],
|
|
7558
|
+
getOpenCodeModelVariants: async (model) => {
|
|
7559
|
+
try {
|
|
7560
|
+
return (await (0, createAdapter_1.getAdapter)(adapterNames_1.openCodeAdapterName).getCatalogModelVariants?.(model)) ?? [];
|
|
7561
|
+
}
|
|
7562
|
+
catch (e) {
|
|
7563
|
+
console.warn('[workers] reading the variants of an OpenCode model failed:', e instanceof Error ? e.message : e);
|
|
7564
|
+
return [];
|
|
7565
|
+
}
|
|
7566
|
+
},
|
|
7567
|
+
readIsBotSkillsEnabled: () => (0, botSkills_1.readBotSkillsInstanceValue)(botSkillsSources).isEnabled,
|
|
7568
|
+
});
|
|
7569
|
+
registerWorkerRolesCommands();
|
|
7122
7570
|
// ── «Bot skills» switch (`/bot_skills`): `connectors/telegram/commands/botSkills.ts`, `utils/botSkills.ts` ──
|
|
7123
7571
|
const { registerBotSkillsCommands, registerBotSkillsCallbacks } = (0, botSkills_2.createBotSkills)({
|
|
7124
7572
|
...botCore,
|
|
7573
|
+
openWorkerRolesScreen,
|
|
7125
7574
|
readBotSkills: botSkillsReader,
|
|
7126
7575
|
readBotSkillsInstanceValue: () => (0, botSkills_1.readBotSkillsInstanceValue)(botSkillsSources),
|
|
7127
7576
|
checkIsOpenCodeTopic: (key) => ((0, createAdapter_1.getThreadAdapterNameRaw)(key) ?? state.getAgent(key)?.name) === adapterNames_1.openCodeAdapterName,
|
|
@@ -7219,7 +7668,7 @@ const { registerRunnersCommands, registerRunnersCallbacks, handleRunnersAddressT
|
|
|
7219
7668
|
applyGroups: (runner) => (0, runnerGroups_1.applyRunnerGroups)(runnersHub, runner, runnersCacheDir),
|
|
7220
7669
|
readRunnerHost: (0, instanceSettings_1.createRunnerHostReader)(() => (0, instanceSettings_1.getInstanceSettingsPath)(), (line) => console.error(line)),
|
|
7221
7670
|
saveRunnerHost: (address) => (0, instanceSettings_1.saveInstanceSettingsChange)((0, instanceSettings_1.getInstanceSettingsPath)(), { runnerHost: address }),
|
|
7222
|
-
getBotLabel
|
|
7671
|
+
getBotLabel,
|
|
7223
7672
|
readOverview: (nowMs) => (0, runnersOverview_1.readRunnersOverview)(runnersHub, runnersCacheDir, nowMs),
|
|
7224
7673
|
// The 20 s deadline of the live probe, which the test seam may shorten (a flow that must see a BUSY machine cannot wait it out).
|
|
7225
7674
|
probeOverview: (overview, nowMs) => (0, runnersOverview_1.probeRunnersOverview)(runnersHub, overview, runnersCacheDir, nowMs, ENV.testTimings.remoteRunProbeDeadlineMs),
|
|
@@ -7241,20 +7690,433 @@ function repairClaudeProfileFolder(configDir) {
|
|
|
7241
7690
|
(0, claudeProfiles_1.repairClaudeProfileFolderForLaunch)({ dataDir: (0, state_1.resolveDataDir)(), configDir });
|
|
7242
7691
|
}
|
|
7243
7692
|
/**
|
|
7244
|
-
* @description The Claude config directory a conversation's NEXT process starts with: its
|
|
7245
|
-
*
|
|
7246
|
-
* every spawn, so the folder is repaired here ({@link repairClaudeProfileFolder}). A profile
|
|
7693
|
+
* @description The Claude config directory a conversation's NEXT process starts with: its account profile's directory
|
|
7694
|
+
* ({@link resolveThreadClaudeProfileForLaunch}: never one known not to work), `null` for the default profile. Registered as the
|
|
7695
|
+
* adapters' reader at boot, and read by every spawn, so the folder is repaired here ({@link repairClaudeProfileFolder}). A profile
|
|
7247
7696
|
* whose directory vanished (a hand-cleaned `DATA_DIR`) runs on the default rather than failing the spawn.
|
|
7248
7697
|
*/
|
|
7249
|
-
function resolveThreadClaudeConfigDir(key) {
|
|
7250
|
-
const name =
|
|
7251
|
-
const dir = (0, claudeProfiles_1.resolveClaudeProfileDir)((0, state_1.resolveDataDir)(), name);
|
|
7252
|
-
if (dir !== null && !fs.existsSync(dir)) {
|
|
7253
|
-
console.warn(`[account] ${(0, sessionKey_1.keyToString)(key)}: the directory of profile ${name} is missing; its process runs on the default profile`);
|
|
7254
|
-
return null;
|
|
7698
|
+
function resolveThreadClaudeConfigDir(key) {
|
|
7699
|
+
const name = resolveThreadClaudeProfileForLaunch(key);
|
|
7700
|
+
const dir = (0, claudeProfiles_1.resolveClaudeProfileDir)((0, state_1.resolveDataDir)(), name);
|
|
7701
|
+
if (dir !== null && !fs.existsSync(dir)) {
|
|
7702
|
+
console.warn(`[account] ${(0, sessionKey_1.keyToString)(key)}: the directory of profile ${name} is missing; its process runs on the default profile`);
|
|
7703
|
+
return null;
|
|
7704
|
+
}
|
|
7705
|
+
repairClaudeProfileFolder(dir);
|
|
7706
|
+
return dir;
|
|
7707
|
+
}
|
|
7708
|
+
/**
|
|
7709
|
+
* @description The account profile a conversation's next Claude process starts on — start, resume and account switch alike (the
|
|
7710
|
+
* reader every spawn goes through, {@link resolveThreadClaudeConfigDir}): the profile it resolves to, unless that account is known
|
|
7711
|
+
* not to work — not signed in by its last probe, or refused by the CLI since (`utils/claudeAuthRefusal.ts`). Then the conversation
|
|
7712
|
+
* goes where `claude_profiles` sends a session leaving that account (`resolveClaudeProfileForLaunch`), recorded as its own
|
|
7713
|
+
* pick the way the limit move records it: a resume carries the same conversation onto the other account, and it stays there when
|
|
7714
|
+
* the first one is signed in again. With no other account usable it stays (and the refusal is surfaced as before).
|
|
7715
|
+
*/
|
|
7716
|
+
function resolveThreadClaudeProfileForLaunch(key) {
|
|
7717
|
+
const resolved = state.resolveClaudeProfileName(key);
|
|
7718
|
+
settleClaudeAuthRefusal(resolved);
|
|
7719
|
+
const record = state.getClaudeProfileInfo(resolved);
|
|
7720
|
+
// The common case reads nothing more: the views and the `/limits` list only matter for an account that cannot run.
|
|
7721
|
+
if (!(0, claudeAuthRefusal_1.checkIsClaudeProfileKnownUnusable)(record))
|
|
7722
|
+
return resolved;
|
|
7723
|
+
const launch = (0, claudeProfileUsageViews_1.resolveClaudeProfileForLaunch)({ ...getClaudeConversationPickContext(key), resolved, record });
|
|
7724
|
+
if (!launch.isMoved)
|
|
7725
|
+
return resolved;
|
|
7726
|
+
const reason = (0, claudeAuthRefusal_1.describeClaudeProfileUsability)((0, claudeAuthRefusal_1.getClaudeProfileUsability)(record));
|
|
7727
|
+
console.log(`[accounts] ${(0, sessionKey_1.keyToString)(key)}: profile ${resolved} cannot run it (${reason}) — the session starts on ${launch.name}`);
|
|
7728
|
+
void state.setClaudeProfileOverride(key, launch.name).catch((e) => console.warn(`[accounts] ${(0, sessionKey_1.keyToString)(key)}: recording the move to ${launch.name} failed:`, e instanceof Error ? e.message : e));
|
|
7729
|
+
return launch.name;
|
|
7730
|
+
}
|
|
7731
|
+
/**
|
|
7732
|
+
* @description What picking the account a Claude conversation goes to reads (`utils/claudeProfileUsageViews.ts`: the account
|
|
7733
|
+
* `claude_profiles` names for a session leaving one it cannot run on): every profile's view as of now, the conversation's model
|
|
7734
|
+
* (`null` = none named: a new conversation), the `/limits` list's word on the accounts.
|
|
7735
|
+
*/
|
|
7736
|
+
function getClaudeConversationPickContext(key) {
|
|
7737
|
+
return {
|
|
7738
|
+
views: getClaudeProfileUsageViews(),
|
|
7739
|
+
model: key === null ? null : getThreadClaudeModel(key),
|
|
7740
|
+
nowMs: Date.now(),
|
|
7741
|
+
chainScope: (0, fallbackChain_1.getClaudeLaunchChainScope)(state.getFallbackChain()),
|
|
7742
|
+
};
|
|
7743
|
+
}
|
|
7744
|
+
/**
|
|
7745
|
+
* @description End the CLI's refusal of the account `name` once it is over (`getClaudeAuthRefusalEnd`): a new login in its folder, or —
|
|
7746
|
+
* a bare 401 / 403 not held until a new login — a probe after it that found the account signed in, which is kept as such (no sign-in
|
|
7747
|
+
* happened: a repeat is held, and nobody is told «signed in again»). Cheap — one small file read, only for a refused account — so every
|
|
7748
|
+
* launch on the account and every profile scan run it.
|
|
7749
|
+
*/
|
|
7750
|
+
function settleClaudeAuthRefusal(name) {
|
|
7751
|
+
const record = state.getClaudeProfileInfo(name);
|
|
7752
|
+
const refusal = record?.authRefusal;
|
|
7753
|
+
if (!record || !refusal)
|
|
7754
|
+
return;
|
|
7755
|
+
const loginStamp = (0, claudeAuthRefusal_1.readClaudeLoginStamp)((0, claudeProfiles_1.resolveClaudeProfileDir)((0, state_1.resolveDataDir)(), name));
|
|
7756
|
+
const end = (0, claudeAuthRefusal_1.getClaudeAuthRefusalEnd)({ refusal, loginStamp, loggedIn: record.loggedIn, statusCheckedAt: record.statusCheckedAt });
|
|
7757
|
+
if (end === null)
|
|
7758
|
+
return;
|
|
7759
|
+
const ending = end === 'statusCheck'
|
|
7760
|
+
? state.endClaudeProfileAuthRefusalByStatusCheck(name, new Date().toISOString())
|
|
7761
|
+
: state.setClaudeProfileAuthRefusal(name, null);
|
|
7762
|
+
void ending.catch((e) => console.warn(`[accounts] profile ${name}: ending its refusal failed:`, e instanceof Error ? e.message : e));
|
|
7763
|
+
noteClaudeProfileUsability();
|
|
7764
|
+
}
|
|
7765
|
+
/**
|
|
7766
|
+
* The CLI's refusal of the account `name` now (`buildClaudeAuthRefusalMark`): the stamp of the login it refused, the CLI's words, and
|
|
7767
|
+
* held until a new login when it repeats a bare 401 / 403 a status check ended lately.
|
|
7768
|
+
*/
|
|
7769
|
+
function buildClaudeAuthRefusal(name, reason, cliText) {
|
|
7770
|
+
return (0, claudeAuthRefusal_1.buildClaudeAuthRefusalMark)({
|
|
7771
|
+
reason,
|
|
7772
|
+
login: (0, claudeAuthRefusal_1.readClaudeLoginStamp)((0, claudeProfiles_1.resolveClaudeProfileDir)((0, state_1.resolveDataDir)(), name)),
|
|
7773
|
+
detail: cliText === undefined ? null : (0, claudeAccountAlert_1.getClaudeAccountAlertDetail)(cliText),
|
|
7774
|
+
nowMs: Date.now(),
|
|
7775
|
+
endedByStatusCheck: state.getClaudeProfileInfo(name)?.authRefusalEndedByStatusCheck,
|
|
7776
|
+
});
|
|
7777
|
+
}
|
|
7778
|
+
/** The last state of each account the log said ({@link noteClaudeProfileUsability}); in memory — a restart says the unusable ones again. */
|
|
7779
|
+
const loggedClaudeProfileUsability = new Map();
|
|
7780
|
+
/**
|
|
7781
|
+
* @description Say in the log, once per change, that an account stopped or started being usable for a conversation
|
|
7782
|
+
* (`[accounts] profile default: not signed in — new sessions go to second`). Run after every profile scan and every refusal
|
|
7783
|
+
* mark or end, so a sign-out the poll finds, a refusal on a turn and a sign-in again each leave one line.
|
|
7784
|
+
*/
|
|
7785
|
+
function noteClaudeProfileUsability() {
|
|
7786
|
+
const current = new Map();
|
|
7787
|
+
const backByStatusCheck = new Set();
|
|
7788
|
+
const nowMs = Date.now();
|
|
7789
|
+
for (const view of getClaudeProfileUsageViews()) {
|
|
7790
|
+
const record = state.getClaudeProfileInfo(view.name);
|
|
7791
|
+
current.set(view.name, (0, claudeAuthRefusal_1.getClaudeProfileUsability)(record));
|
|
7792
|
+
if ((0, claudeAuthRefusal_1.checkIsClaudeProfileBackByStatusCheck)(record, nowMs))
|
|
7793
|
+
backByStatusCheck.add(view.name);
|
|
7794
|
+
}
|
|
7795
|
+
const lines = (0, claudeAuthRefusal_1.listClaudeProfileUsabilityLines)({
|
|
7796
|
+
previous: loggedClaudeProfileUsability,
|
|
7797
|
+
current,
|
|
7798
|
+
getInstead: (name) => (0, claudeProfileUsageViews_1.pickClaudeProfileInstead)({ ...getClaudeConversationPickContext(null), currentProfile: name }),
|
|
7799
|
+
backByStatusCheck,
|
|
7800
|
+
});
|
|
7801
|
+
for (const line of lines)
|
|
7802
|
+
console.log(line);
|
|
7803
|
+
loggedClaudeProfileUsability.clear();
|
|
7804
|
+
for (const [name, usability] of current)
|
|
7805
|
+
loggedClaudeProfileUsability.set(name, usability);
|
|
7806
|
+
if (!isOperatorAlertOpen)
|
|
7807
|
+
return;
|
|
7808
|
+
tellOperatorAboutClaudeAccounts(current, backByStatusCheck);
|
|
7809
|
+
void resumeConversationsWaitingForAccount();
|
|
7810
|
+
}
|
|
7811
|
+
/** The channels besides General that operator alerts go to (a connector's own: Jira's operator issue); set at boot. */
|
|
7812
|
+
let operatorAlertChannels = [];
|
|
7813
|
+
/**
|
|
7814
|
+
* Until the boot has restored the sessions and knows its channels, a change of the accounts is only logged: nobody is told yet (the
|
|
7815
|
+
* persisted record keeps the change for the first round after) and no waiting conversation is resumed.
|
|
7816
|
+
*/
|
|
7817
|
+
let isOperatorAlertOpen = false;
|
|
7818
|
+
/** At boot, once the sessions are restored and the connectors' channels are known: the first round tells and resumes. */
|
|
7819
|
+
function openOperatorAlerts() {
|
|
7820
|
+
isOperatorAlertOpen = true;
|
|
7821
|
+
noteClaudeProfileUsability();
|
|
7822
|
+
}
|
|
7823
|
+
/**
|
|
7824
|
+
* @description Tell the operator, once per change, about the accounts that cannot work because of their sign-in and those usable again
|
|
7825
|
+
* (`utils/claudeAccountAlert.ts`): the record of what was told is kept in the same tick, so two rounds close together never tell it
|
|
7826
|
+
* twice, and a round that changes nothing writes nothing.
|
|
7827
|
+
*/
|
|
7828
|
+
function tellOperatorAboutClaudeAccounts(current, backByStatusCheck) {
|
|
7829
|
+
const details = new Map();
|
|
7830
|
+
for (const name of current.keys()) {
|
|
7831
|
+
const detail = state.getClaudeProfileInfo(name)?.authRefusal?.detail;
|
|
7832
|
+
if (detail)
|
|
7833
|
+
details.set(name, detail);
|
|
7834
|
+
}
|
|
7835
|
+
const previous = state.getClaudeAccountAlertState();
|
|
7836
|
+
const { alert, next } = (0, claudeAccountAlert_1.planClaudeAccountAlert)({
|
|
7837
|
+
previous,
|
|
7838
|
+
current,
|
|
7839
|
+
details,
|
|
7840
|
+
defaultProfile: state.getClaudeProfileGlobalDefault(),
|
|
7841
|
+
instead: (0, claudeProfileUsageViews_1.pickClaudeProfileInstead)({ ...getClaudeConversationPickContext(null), currentProfile: null }),
|
|
7842
|
+
backByStatusCheck,
|
|
7843
|
+
});
|
|
7844
|
+
if (alert === null && JSON.stringify(previous) === JSON.stringify(next))
|
|
7845
|
+
return;
|
|
7846
|
+
void state.setClaudeAccountAlertState(next).catch((e) => console.warn('[accounts] keeping what the operator was told failed:', e instanceof Error ? e.message : e));
|
|
7847
|
+
if (alert !== null)
|
|
7848
|
+
void deliverClaudeAccountAlert(alert);
|
|
7849
|
+
// An account back by a status check alone leaves quietly: with no told account left, the pin goes all the same.
|
|
7850
|
+
else
|
|
7851
|
+
void releaseClaudeAccountAlertPin();
|
|
7852
|
+
}
|
|
7853
|
+
/**
|
|
7854
|
+
* @description Unpin the account alert in General once no told account is left unusable; nothing while one is, or when none is
|
|
7855
|
+
* pinned. Changes only the pin of the record as it is now.
|
|
7856
|
+
*/
|
|
7857
|
+
async function releaseClaudeAccountAlertPin() {
|
|
7858
|
+
const current = state.getClaudeAccountAlertState();
|
|
7859
|
+
const pinnedMessageId = current?.pinnedMessageId;
|
|
7860
|
+
if (!current || current.alerted.length > 0 || pinnedMessageId === undefined)
|
|
7861
|
+
return;
|
|
7862
|
+
await state.setClaudeAccountAlertPinnedMessageId(null);
|
|
7863
|
+
const generalKey = ENV.isTelegramServed ? getOperatorGeneralKey() : null;
|
|
7864
|
+
if (generalKey !== null)
|
|
7865
|
+
void unpinMessageQuiet(generalKey, pinnedMessageId);
|
|
7866
|
+
}
|
|
7867
|
+
/**
|
|
7868
|
+
* @description How to sign an account in again on the bot's host, for a channel read outside Telegram (the Jira operator issue): the
|
|
7869
|
+
* CLI's own sign-in under the account's folder, as the bot's OS user.
|
|
7870
|
+
*/
|
|
7871
|
+
function getHostClaudeSignInHow(name) {
|
|
7872
|
+
const dir = (0, claudeProfiles_1.resolveClaudeProfileDir)((0, state_1.resolveDataDir)(), name);
|
|
7873
|
+
const command = dir === null ? 'claude auth login' : `CLAUDE_CONFIG_DIR=${dir} claude auth login`;
|
|
7874
|
+
return `\`${command}\` on the bot's host, as its OS user`;
|
|
7875
|
+
}
|
|
7876
|
+
/**
|
|
7877
|
+
* @description Post an account alert to the operator: in General (Telegram, the chat's language, pinned while it asks to act) and on
|
|
7878
|
+
* every connector's channel (English). A failed post is logged, never retried — an alert told twice is worse.
|
|
7879
|
+
*/
|
|
7880
|
+
async function deliverClaudeAccountAlert(alert) {
|
|
7881
|
+
const lost = alert.lost.map((loss) => `${loss.name} (${loss.usability})`).join(', ');
|
|
7882
|
+
console.log(`[accounts] operator alert: ${lost ? `cannot work: ${lost}; conversations go to ${alert.instead ?? 'no account — they wait'}` : ''}${alert.back.length > 0 ? `${lost ? '; ' : ''}usable again: ${alert.back.join(', ')}` : ''}`);
|
|
7883
|
+
const posts = [];
|
|
7884
|
+
if (ENV.isTelegramServed)
|
|
7885
|
+
posts.push(postClaudeAccountAlertToTelegram(alert));
|
|
7886
|
+
const isActionRequired = alert.lost.length > 0;
|
|
7887
|
+
for (const channel of operatorAlertChannels) {
|
|
7888
|
+
const text = (0, i18n_1.runWithLocale)('en', () => (0, claudeAccountAlert_1.renderClaudeAccountAlert)(alert, getHostClaudeSignInHow));
|
|
7889
|
+
posts.push(channel.post(text, { isActionRequired }).then((result) => {
|
|
7890
|
+
if (!result.ok)
|
|
7891
|
+
console.warn(`[accounts] the operator alert did not reach ${channel.label}: ${result.error}`);
|
|
7892
|
+
}));
|
|
7893
|
+
}
|
|
7894
|
+
await Promise.all(posts);
|
|
7895
|
+
}
|
|
7896
|
+
/**
|
|
7897
|
+
* @description The account alert in General, like the updater's: worded in that chat's language, the sign-in named as
|
|
7898
|
+
* `/accounts login <name>`; an alert that asks to act is pinned (the pin is what reaches a muted operator) in place of the previous
|
|
7899
|
+
* one, and once no told account is left unusable the pin goes. `isPrivateChatClosed`: Telegram refused the private message about a
|
|
7900
|
+
* signed-out account (403) — the alert then also asks the operator to open a private chat with the bot.
|
|
7901
|
+
*/
|
|
7902
|
+
async function postClaudeAccountAlertToGeneral(alert, options) {
|
|
7903
|
+
const generalKey = getOperatorGeneralKey();
|
|
7904
|
+
if (generalKey === null) {
|
|
7905
|
+
console.log('[accounts] no General topic to post the account alert in');
|
|
7906
|
+
return;
|
|
7907
|
+
}
|
|
7908
|
+
const renderOptions = options.isPrivateChatClosed ? { closedPrivateChatBot: getBotLabel() } : {};
|
|
7909
|
+
const text = withThreadLocale(generalKey, () => (0, claudeAccountAlert_1.renderClaudeAccountAlert)(alert, (name) => `/accounts login ${name}`, renderOptions));
|
|
7910
|
+
const messageId = await replyToThread(generalKey, text);
|
|
7911
|
+
if (alert.lost.length === 0 || messageId === null) {
|
|
7912
|
+
await releaseClaudeAccountAlertPin();
|
|
7913
|
+
return;
|
|
7914
|
+
}
|
|
7915
|
+
await pinMessageQuiet(generalKey, messageId, { disableNotification: false });
|
|
7916
|
+
// Read AFTER the waits, and only the pin is written: a round in between may have told another account, and that must stay told.
|
|
7917
|
+
const previousPinnedId = state.getClaudeAccountAlertState()?.pinnedMessageId;
|
|
7918
|
+
await state.setClaudeAccountAlertPinnedMessageId(messageId);
|
|
7919
|
+
if (previousPinnedId !== undefined && previousPinnedId !== messageId)
|
|
7920
|
+
void unpinMessageQuiet(generalKey, previousPinnedId);
|
|
7921
|
+
}
|
|
7922
|
+
/**
|
|
7923
|
+
* @description The account alert on Telegram. The private messages go FIRST — General's notice has to know whether Telegram refused them
|
|
7924
|
+
* (a person who never opened the bot's private chat), because then it also asks the operator to open one — and the accounts signed in
|
|
7925
|
+
* again get their earlier private message turned into «signed in again» beside General's post.
|
|
7926
|
+
*/
|
|
7927
|
+
async function postClaudeAccountAlertToTelegram(alert) {
|
|
7928
|
+
const isPrivateChatClosed = await sendClaudeAccountSignOutDms(alert);
|
|
7929
|
+
await Promise.all([postClaudeAccountAlertToGeneral(alert, { isPrivateChatClosed }), settleClaudeAccountSignOutDms(alert)]);
|
|
7930
|
+
}
|
|
7931
|
+
/**
|
|
7932
|
+
* @description Tell the operator, in a PRIVATE message from the bot, about each account that is signed out in this alert: one short
|
|
7933
|
+
* line naming it and a button that starts its sign-in (`acct_signin_<name>`, the 🔑 of `/accounts`) — General is muted for the operator,
|
|
7934
|
+
* a private message is not. It rides the alert, so it is sent once per sign-out (not per refusal), and again only after the account was
|
|
7935
|
+
* signed in again and signed out again; the General notice is posted as before. The message's id is kept (`signOutMessageIds`) so it can
|
|
7936
|
+
* be turned into «signed in again» later. Nothing is sent when the operator's private chat is not a surface the bot serves (no
|
|
7937
|
+
* `OWNER_USER_ID`, `CHAT_MODE=group`) or already IS where General's notice went (`CHAT_MODE=dm`); a person who never opened the bot's
|
|
7938
|
+
* private chat cannot be written to (Telegram's 403): that is said in the log and returned (`true`), and General's notice says so.
|
|
7939
|
+
* Never retried — a second send could tell it twice.
|
|
7940
|
+
*/
|
|
7941
|
+
async function sendClaudeAccountSignOutDms(alert) {
|
|
7942
|
+
const names = (0, claudeAccountAlert_1.listClaudeAccountSignOutNames)(alert);
|
|
7943
|
+
if (names.length === 0)
|
|
7944
|
+
return false;
|
|
7945
|
+
const privateKey = getOperatorPrivateChatKey();
|
|
7946
|
+
if (privateKey === null) {
|
|
7947
|
+
console.log(`[accounts] no private chat with the operator to tell them ${names.join(', ')} is signed out (General has it)`);
|
|
7948
|
+
return false;
|
|
7949
|
+
}
|
|
7950
|
+
let isPrivateChatClosed = false;
|
|
7951
|
+
for (const name of names) {
|
|
7952
|
+
const dm = withThreadLocale(privateKey, () => (0, claudeAccountAlert_1.renderClaudeAccountSignOutDm)(name));
|
|
7953
|
+
const outcome = await replyToThreadDetailed(privateKey, dm.text, telegraf_1.Markup.inlineKeyboard([[telegraf_1.Markup.button.callback(dm.buttonLabel, dm.callbackData)]]));
|
|
7954
|
+
if (outcome.kind === 'sent') {
|
|
7955
|
+
console.log(`[accounts] told the operator in a private message that ${name} is signed out`);
|
|
7956
|
+
await state.setClaudeAccountAlertSignOutMessageId(name, outcome.messageId);
|
|
7957
|
+
// The account may have been signed in again while the message was on its way: it is out of date already.
|
|
7958
|
+
if ((0, claudeAuthRefusal_1.getClaudeProfileUsability)(state.getClaudeProfileInfo(name)) === 'usable')
|
|
7959
|
+
await markClaudeAccountSignOutDmSignedIn(privateKey, name, outcome.messageId);
|
|
7960
|
+
}
|
|
7961
|
+
else if (outcome.kind === 'failed' && outcome.isForbidden === true) {
|
|
7962
|
+
isPrivateChatClosed = true;
|
|
7963
|
+
console.log(`[accounts] the operator's private chat is closed to the bot (they never opened it, or blocked it): ${name} is signed out, General has it`);
|
|
7964
|
+
}
|
|
7965
|
+
else {
|
|
7966
|
+
console.warn(`[accounts] the private message to the operator about ${name} did not go out (${outcome.kind})`);
|
|
7967
|
+
}
|
|
7968
|
+
}
|
|
7969
|
+
return isPrivateChatClosed;
|
|
7970
|
+
}
|
|
7971
|
+
/** The earlier private sign-out messages of the accounts this alert says are signed in again become «signed in again» (`alert.backMessageIds`). */
|
|
7972
|
+
async function settleClaudeAccountSignOutDms(alert) {
|
|
7973
|
+
const messageIds = Object.entries(alert.backMessageIds ?? {});
|
|
7974
|
+
const privateKey = messageIds.length === 0 ? null : getOperatorPrivateChatKey();
|
|
7975
|
+
if (privateKey === null)
|
|
7976
|
+
return;
|
|
7977
|
+
for (const [name, messageId] of messageIds)
|
|
7978
|
+
await markClaudeAccountSignOutDmSignedIn(privateKey, name, messageId);
|
|
7979
|
+
}
|
|
7980
|
+
/**
|
|
7981
|
+
* @description Turn the private sign-out message of `name` into «signed in again»: its text is the one of General's «signed in again» line
|
|
7982
|
+
* and the edit leaves it no button (the Bot API drops the keyboard of a message edited without one), so a tap on a message that is no
|
|
7983
|
+
* longer true is impossible. Best-effort, never retried: a message that stays as it was is harmless — its button only starts a sign-in.
|
|
7984
|
+
*/
|
|
7985
|
+
async function markClaudeAccountSignOutDmSignedIn(privateKey, name, messageId) {
|
|
7986
|
+
await state.setClaudeAccountAlertSignOutMessageId(name, null);
|
|
7987
|
+
const text = withThreadLocale(privateKey, () => (0, i18n_1.t)('accounts.alert.back', { name }));
|
|
7988
|
+
if (await editThreadMessage(privateKey, messageId, text))
|
|
7989
|
+
console.log(`[accounts] the private message about ${name} now says it is signed in again`);
|
|
7990
|
+
else
|
|
7991
|
+
console.warn(`[accounts] the private message about ${name} could not be turned into «signed in again»`);
|
|
7992
|
+
}
|
|
7993
|
+
/** A resume of the conversations waiting for an account runs one at a time. */
|
|
7994
|
+
let isResumingAccountWaits = false;
|
|
7995
|
+
/**
|
|
7996
|
+
* @description The conversations a refused turn left with no account to move to (`claudeAccountWaits`) go on once one can work:
|
|
7997
|
+
* each is moved onto the account it resolves to now (the launch pick leaves the refused one) and gets the continue prompt — or its
|
|
7998
|
+
* open requests' prompts not taken in — with its requests woken again, as after a usage-limit wait. Run after every round of the
|
|
7999
|
+
* accounts' states; nothing happens while no account is usable.
|
|
8000
|
+
*/
|
|
8001
|
+
async function resumeConversationsWaitingForAccount() {
|
|
8002
|
+
if (isResumingAccountWaits)
|
|
8003
|
+
return;
|
|
8004
|
+
const waiting = state.listClaudeAccountWaits();
|
|
8005
|
+
if (waiting.length === 0)
|
|
8006
|
+
return;
|
|
8007
|
+
if ((0, claudeProfileUsageViews_1.pickClaudeProfileInstead)({ ...getClaudeConversationPickContext(null), currentProfile: null }) === null)
|
|
8008
|
+
return;
|
|
8009
|
+
isResumingAccountWaits = true;
|
|
8010
|
+
try {
|
|
8011
|
+
for (const key of waiting) {
|
|
8012
|
+
await state.setWaitingForClaudeAccount(key, false);
|
|
8013
|
+
if (!(0, connectorSet_1.checkIsServedConversation)(key, ENV.servedPlatforms) || !checkIsClaudeProfileBackend(key))
|
|
8014
|
+
continue;
|
|
8015
|
+
try {
|
|
8016
|
+
await applyClaudeProfileToThread(key, { isAfterLimit: true });
|
|
8017
|
+
console.log(`[accounts] ${(0, sessionKey_1.keyToString)(key)}: a Claude account can work again — the conversation goes on (${state.resolveClaudeProfileName(key)})`);
|
|
8018
|
+
await resumeTopicOnNewSession(key, {
|
|
8019
|
+
modelToPin: null,
|
|
8020
|
+
getFirstPrompt: () => (0, limitHeldPrompts_1.getLimitResumeMessage)({
|
|
8021
|
+
continueNudge: (0, i18n_1.t)('apiRetry.continueNudge'),
|
|
8022
|
+
untakenRequestPrompts: (0, requestHeader_1.getPromptsNotTakenIn)(requestLimitWaitAnswerDeps?.ledger.listOpenRequestsOf(key) ?? []),
|
|
8023
|
+
}),
|
|
8024
|
+
});
|
|
8025
|
+
}
|
|
8026
|
+
catch (e) {
|
|
8027
|
+
console.warn(`[accounts] ${(0, sessionKey_1.keyToString)(key)}: resuming the conversation failed:`, e instanceof Error ? e.message : e);
|
|
8028
|
+
}
|
|
8029
|
+
}
|
|
8030
|
+
}
|
|
8031
|
+
finally {
|
|
8032
|
+
isResumingAccountWaits = false;
|
|
8033
|
+
}
|
|
8034
|
+
}
|
|
8035
|
+
/**
|
|
8036
|
+
* @description The profile scan (`utils/claudeProfileSync.ts`) the usage poll and `/accounts` run, followed by the refusals it may
|
|
8037
|
+
* end: an account signed in again since the CLI refused it is usable again from here.
|
|
8038
|
+
*/
|
|
8039
|
+
async function syncClaudeProfilesAndRefusals(options = {}) {
|
|
8040
|
+
const result = await claudeProfileSync.sync(options);
|
|
8041
|
+
for (const name of Object.keys(state.getAllClaudeProfileInfos()))
|
|
8042
|
+
settleClaudeAuthRefusal(name);
|
|
8043
|
+
noteClaudeProfileUsability();
|
|
8044
|
+
return result;
|
|
8045
|
+
}
|
|
8046
|
+
/**
|
|
8047
|
+
* @description The CLI refused the account a json-stream Claude conversation runs on (an `auth` error: signed out, a login expired
|
|
8048
|
+
* or revoked, its organization turned Claude subscription use off, a bare 401 / 403). The account is marked refused
|
|
8049
|
+
* (`utils/claudeAuthRefusal.ts`) until it is signed in again, and the conversation makes the limit move
|
|
8050
|
+
* ({@link switchTopicToFallbackEntry}, same conversation) to the account `claude_profiles` names for it
|
|
8051
|
+
* (`planClaudeAuthRefusalMove`); the dead turn goes on there — the continue prompt, or the open requests' prompts not
|
|
8052
|
+
* taken in. Not tied to the auto-switch setting: a refused account comes back by no wait. With no other account usable, a move
|
|
8053
|
+
* that fails, or an error replayed from before this boot (the login may have been fixed since; it is not marked), the pinned
|
|
8054
|
+
* logged-out notice as before.
|
|
8055
|
+
*/
|
|
8056
|
+
async function handleClaudeAuthRefusal(key, cls) {
|
|
8057
|
+
const k = (0, sessionKey_1.keyToString)(key);
|
|
8058
|
+
const from = getTopicFallbackPosition(key);
|
|
8059
|
+
if (from?.backend !== 'claude') {
|
|
8060
|
+
await surfaceLoggedOutNotice(key);
|
|
8061
|
+
return;
|
|
8062
|
+
}
|
|
8063
|
+
const reason = cls.authReason ?? 'signedOut';
|
|
8064
|
+
const refusal = buildClaudeAuthRefusal(from.profile, reason, cls.authDetail);
|
|
8065
|
+
const plan = (0, claudeProfileUsageViews_1.planClaudeAuthRefusalMove)({ ...getClaudeConversationPickContext(key), refused: from.profile, refusal, isReplayed: cls.isReplayed === true });
|
|
8066
|
+
if (!plan.isMarked) {
|
|
8067
|
+
await surfaceLoggedOutNotice(key);
|
|
8068
|
+
return;
|
|
8069
|
+
}
|
|
8070
|
+
await state.setClaudeProfileAuthRefusal(from.profile, refusal);
|
|
8071
|
+
noteClaudeProfileUsability();
|
|
8072
|
+
const instead = plan.to;
|
|
8073
|
+
if (instead === null) {
|
|
8074
|
+
console.log(`[accounts] ${k}: profile ${from.profile} was refused (${claudeAuthRefusal_1.claudeAuthRefusalWords[reason]}) and no other account can take the conversation over — it waits for one`);
|
|
8075
|
+
await waitForClaudeAccount(key);
|
|
8076
|
+
return;
|
|
8077
|
+
}
|
|
8078
|
+
console.log(`[accounts] ${k}: profile ${from.profile} was refused (${claudeAuthRefusal_1.claudeAuthRefusalWords[reason]}) — moving the conversation to ${instead}`);
|
|
8079
|
+
const to = { backend: 'claude', profile: instead, model: null };
|
|
8080
|
+
// A topic hears it from the move's own notice; a tracker issue from the bot's answer to its open requests, in plain words.
|
|
8081
|
+
if (!(0, sessionKeyCodec_1.checkIsTelegramKey)(key) && requestLimitWaitAnswerDeps) {
|
|
8082
|
+
await (0, limitWaitAnswer_1.answerOpenRequestsWithBotNotice)(requestLimitWaitAnswerDeps, key, {
|
|
8083
|
+
identity: `claudeAccountMove:${instead}`,
|
|
8084
|
+
body: (0, i18n_1.t)('requests.account.movedAnswer', { from: from.profile, reason: (0, claudeAccountAlert_1.formatClaudeAccountRefusal)(reason), to: instead }),
|
|
8085
|
+
isWakeStopped: false,
|
|
8086
|
+
}).catch((e) => console.warn(`[accounts] ${k}: telling the requests about the move failed:`, e instanceof Error ? e.message : e));
|
|
8087
|
+
}
|
|
8088
|
+
try {
|
|
8089
|
+
await switchTopicToFallbackEntry(key, from, to, { isAnnounced: true, isAutomatic: true, reason: 'signIn' });
|
|
8090
|
+
}
|
|
8091
|
+
catch (e) {
|
|
8092
|
+
console.warn(`[accounts] ${k}: moving the conversation to ${instead} failed:`, e instanceof Error ? e.message : e);
|
|
8093
|
+
await surfaceLoggedOutNotice(key);
|
|
8094
|
+
}
|
|
8095
|
+
}
|
|
8096
|
+
/**
|
|
8097
|
+
* @description A refused turn with no other Claude account to move to: the conversation WAITS for one (`claudeAccountWaits`) — its
|
|
8098
|
+
* requests are no longer woken (a reminder would only meet the same refusal, and its give-up would read as the agent's silence), a
|
|
8099
|
+
* topic gets the pinned logged-out notice, a tracker issue the bot's own answer saying in plain words that no account of the AI can
|
|
8100
|
+
* work, why, that the operator was told, and that the work goes on once one is signed in again
|
|
8101
|
+
* ({@link resumeConversationsWaitingForAccount}).
|
|
8102
|
+
*/
|
|
8103
|
+
async function waitForClaudeAccount(key) {
|
|
8104
|
+
await state.setWaitingForClaudeAccount(key, true);
|
|
8105
|
+
await requestWakeUpEngine?.stopWakingForLimitWait(key);
|
|
8106
|
+
if ((0, sessionKeyCodec_1.checkIsTelegramKey)(key) || !requestLimitWaitAnswerDeps) {
|
|
8107
|
+
await surfaceLoggedOutNotice(key);
|
|
8108
|
+
return;
|
|
7255
8109
|
}
|
|
7256
|
-
|
|
7257
|
-
|
|
8110
|
+
const reasons = getClaudeProfileUsageViews()
|
|
8111
|
+
.map((view) => ({ name: view.name, usability: (0, claudeAuthRefusal_1.getClaudeProfileUsability)(state.getClaudeProfileInfo(view.name)) }))
|
|
8112
|
+
.flatMap(({ name, usability }) => (usability === 'usable' ? [] : [`«${name}» ${(0, claudeAccountAlert_1.formatClaudeAccountRefusal)(usability)}`]))
|
|
8113
|
+
.join('; ');
|
|
8114
|
+
await (0, limitWaitAnswer_1.answerOpenRequestsWithBotNotice)(requestLimitWaitAnswerDeps, key, {
|
|
8115
|
+
// One wait, one answer per request: a later refused turn of the same wait (a new request's prompt) answers only the new request.
|
|
8116
|
+
identity: 'claudeAccountWait',
|
|
8117
|
+
body: (0, i18n_1.t)('requests.account.noneUsableAnswer', { reasons }),
|
|
8118
|
+
isWakeStopped: true,
|
|
8119
|
+
}).catch((e) => console.warn(`[accounts] ${(0, sessionKey_1.keyToString)(key)}: telling the requests about the wait failed:`, e instanceof Error ? e.message : e));
|
|
7258
8120
|
}
|
|
7259
8121
|
/**
|
|
7260
8122
|
* `claude auth status --json` under `configDir` (`null` = `~/.claude`) as its sessions see it: never through an
|
|
@@ -7353,7 +8215,7 @@ const claudeProfileSync = (0, claudeProfileSync_1.createClaudeProfileSync)({
|
|
|
7353
8215
|
* `rate_limit_event` frames the json-stream sessions report. Snapshots live on the profile records.
|
|
7354
8216
|
*/
|
|
7355
8217
|
const claudeUsageRefresher = (0, claudeUsageRefresher_1.createClaudeUsageRefresher)({
|
|
7356
|
-
syncProfiles: () =>
|
|
8218
|
+
syncProfiles: () => syncClaudeProfilesAndRefusals(),
|
|
7357
8219
|
listProfiles: () => [
|
|
7358
8220
|
{
|
|
7359
8221
|
name: claudeProfiles_1.defaultClaudeProfileName, configDir: null,
|
|
@@ -7515,7 +8377,7 @@ function readStatusAccountSource(name) {
|
|
|
7515
8377
|
syncClaudeApiCreditAnchors();
|
|
7516
8378
|
const info = state.getClaudeProfileInfo(name);
|
|
7517
8379
|
return {
|
|
7518
|
-
name, email: info?.email ?? null, loggedIn: info
|
|
8380
|
+
name, email: info?.email ?? null, loggedIn: (0, claudeAuthRefusal_1.getClaudeProfileSignedIn)(info), limitedUntil: info?.limitedUntil ?? null,
|
|
7519
8381
|
billing: info?.billing ?? null, creditExhaustedAt: info?.creditExhaustedAt ?? null, ...(info?.apiSpend ? { apiSpend: info.apiSpend } : {}),
|
|
7520
8382
|
};
|
|
7521
8383
|
}
|
|
@@ -7616,16 +8478,20 @@ function getConversationAccountState(key) {
|
|
|
7616
8478
|
return { isLimited: checkIsFuture(info?.limitedUntil) || info?.creditExhaustedAt !== undefined, isApiBilled: info?.billing === 'api' };
|
|
7617
8479
|
}
|
|
7618
8480
|
/**
|
|
7619
|
-
* @description A person wrote in the conversation (a message, voice, file, album; an issue's request): the
|
|
7620
|
-
*
|
|
8481
|
+
* @description A person wrote in the conversation (a message, voice, file, album; an issue's request): the idle countdown
|
|
8482
|
+
* restarts, the todo reminder's silence after ignored reminders ends (D13), and a question the
|
|
7621
8483
|
* idle compaction re-asked is closed as unanswered — they wrote something else instead of tapping it, like a live
|
|
7622
8484
|
* question a message cancels, and its buttons must not be tapped later onto whatever the agent asks next. A tap on the
|
|
7623
8485
|
* re-asked question takes its record before it gets here, so it is not closed by its own answer.
|
|
7624
8486
|
*/
|
|
7625
8487
|
function notePersonActivity(key) {
|
|
7626
|
-
|
|
8488
|
+
noteThreadActivity(key);
|
|
7627
8489
|
getTodoRegistry().notePersonActivity(key);
|
|
7628
8490
|
closeReAskedQuestion(key);
|
|
8491
|
+
// Their words go to the agent now — on an account that works, or back into the wait if none does — so no later resume adds a nudge.
|
|
8492
|
+
if (state.checkIsWaitingForClaudeAccount(key)) {
|
|
8493
|
+
void state.setWaitingForClaudeAccount(key, false).catch((e) => console.warn(`[accounts] ${(0, sessionKey_1.keyToString)(key)}: ending the wait for an account failed:`, e instanceof Error ? e.message : e));
|
|
8494
|
+
}
|
|
7629
8495
|
}
|
|
7630
8496
|
/**
|
|
7631
8497
|
* @description What a usage limit on `key` leads to (`utils/fallbackChain.ts`): the rung the topic is on is
|
|
@@ -7636,10 +8502,10 @@ function notePersonActivity(key) {
|
|
|
7636
8502
|
* 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
8503
|
* switch from, or when no rung can take over.
|
|
7638
8504
|
*
|
|
7639
|
-
* A conversation of another platform (a Jira issue) takes the AUTOMATIC
|
|
7640
|
-
* Claude rungs when it has any (else the ranking), never an OpenCode rung (a cross-backend hand-over has no surface there).
|
|
7641
|
-
*
|
|
7642
|
-
* Telegram's
|
|
8505
|
+
* A conversation of another platform (a Jira issue) takes the AUTOMATIC moves only, and only between Claude accounts: the chain's
|
|
8506
|
+
* Claude rungs when it has any (else the ranking), never an OpenCode rung (a cross-backend hand-over has no surface there). With no
|
|
8507
|
+
* account free its wait, like a topic's, ends at the EARLIEST reset of those accounts (`earliest`) and the retry kick moves it there;
|
|
8508
|
+
* the offer's buttons are Telegram's. With auto-switch OFF, or on OpenCode, such a conversation waits for its own reset.
|
|
7643
8509
|
*/
|
|
7644
8510
|
async function planFallbackSwitch(key, cls, episodeId) {
|
|
7645
8511
|
const from = getTopicFallbackPosition(key);
|
|
@@ -7673,7 +8539,7 @@ async function planFallbackSwitch(key, cls, episodeId) {
|
|
|
7673
8539
|
// a stuck usage endpoint must never hold the switch or the wait notice of a topic that just hit its limit.
|
|
7674
8540
|
await (0, usageRefreshBudget_1.refreshUsageWithinBudget)((options) => claudeUsageRefresher.refreshAll(options));
|
|
7675
8541
|
const detection = await detectFallbackOptions();
|
|
7676
|
-
const { plan,
|
|
8542
|
+
const { plan, waitTarget } = (0, limitSwitchPlan_1.decideLimitSwitch)({
|
|
7677
8543
|
isTelegram,
|
|
7678
8544
|
from,
|
|
7679
8545
|
chain: state.getFallbackChain(),
|
|
@@ -7686,15 +8552,9 @@ async function planFallbackSwitch(key, cls, episodeId) {
|
|
|
7686
8552
|
else
|
|
7687
8553
|
fallbackSwitchOffers.delete(k);
|
|
7688
8554
|
const detail = plan.action === 'auto' ? ` → ${formatFallbackEntry(plan.to)}` : plan.action === 'offer' ? ` [${plan.candidates.map(formatFallbackEntry).join(', ')}]` : '';
|
|
7689
|
-
// Nothing has room: the wait should end on the rung whose limit resets EARLIEST, not necessarily this one
|
|
7690
|
-
|
|
7691
|
-
|
|
7692
|
-
const found = (0, fallbackChain_1.pickEarliestResetRung)({ chain: waitRungs, current: from, detection, nowMs: Date.now() });
|
|
7693
|
-
if (found && !found.isCurrent)
|
|
7694
|
-
earliest = { entry: found.entry, untilMs: found.untilMs };
|
|
7695
|
-
}
|
|
7696
|
-
console.log(`[fallback] ${k}: usage limit on ${formatFallbackEntry(from)}; switch plan: ${plan.action}${detail}${earliest ? `; earliest reset: ${formatFallbackEntry(earliest.entry)} at ${new Date(earliest.untilMs).toISOString()}` : ''}`);
|
|
7697
|
-
return { ...plan, from, earliest };
|
|
8555
|
+
// Nothing has room: the wait should end on the rung whose limit resets EARLIEST, not necessarily this one.
|
|
8556
|
+
console.log(`[fallback] ${k}: usage limit on ${formatFallbackEntry(from)}; switch plan: ${plan.action}${detail}${waitTarget ? `; earliest reset: ${formatFallbackEntry(waitTarget.entry)} at ${new Date(waitTarget.untilMs).toISOString()}` : ''}`);
|
|
8557
|
+
return { ...plan, from, earliest: waitTarget };
|
|
7698
8558
|
}
|
|
7699
8559
|
/** When the rung that hit the limit comes back, as a clock in the topic's zone; `null` when unknown or past. */
|
|
7700
8560
|
function getFallbackResetTime(from) {
|
|
@@ -7712,8 +8572,8 @@ function getFallbackResetTime(from) {
|
|
|
7712
8572
|
* The «switched» notice (`utils/fallbackSwitchNotice.ts`), with the reset of the exhausted rung when known — and, onto
|
|
7713
8573
|
* an account billed to API credits, the line that it costs money per request and what it has spent so far.
|
|
7714
8574
|
*/
|
|
7715
|
-
function getFallbackSwitchedNotice(from, to, runningModel) {
|
|
7716
|
-
const notice = (0, fallbackSwitchNotice_1.buildFallbackSwitchedNotice)({ from, to, resetTime: getFallbackResetTime(from), runningModel });
|
|
8575
|
+
function getFallbackSwitchedNotice(from, to, runningModel, reason = 'limit') {
|
|
8576
|
+
const notice = (0, fallbackSwitchNotice_1.buildFallbackSwitchedNotice)({ from, to, resetTime: getFallbackResetTime(from), runningModel, reason });
|
|
7717
8577
|
const info = to.backend === 'claude' ? state.getClaudeProfileInfo(to.profile) : undefined;
|
|
7718
8578
|
if (to.backend !== 'claude' || info?.billing !== 'api')
|
|
7719
8579
|
return notice;
|
|
@@ -7805,14 +8665,29 @@ function formatThreadBackend(key) {
|
|
|
7805
8665
|
* deliver it. After a limit the turn is dead, so a working Claude session is moved at once; only one that cannot
|
|
7806
8666
|
* be re-spawned yet (a tmux session with nothing to resume) keeps its wait and moves at turn end. Returns whether
|
|
7807
8667
|
* the work continues now and the notice that says so (posted here only when `isAnnounced` — the auto-switch has no
|
|
7808
|
-
* other voice, while a tapped button's notice is edited into the same line by its handler).
|
|
8668
|
+
* other voice, while a tapped button's notice is edited into the same line by its handler). `reason: 'signIn'` is the same
|
|
8669
|
+
* move off a Claude account the CLI refused ({@link handleClaudeAuthRefusal}): only its notices and log line differ.
|
|
8670
|
+
*
|
|
8671
|
+
* A move onto the other backend refuses a person's message from here — nothing is awaited before — until it ends: its first prompt has
|
|
8672
|
+
* reached the new backend, or it failed (`ConversationEndings.refuseMessages`, review 25 #1). Written into the backend being left, the
|
|
8673
|
+
* message would be lost with it; written into the new one ahead of the bridge, it would reach an agent that does not know the
|
|
8674
|
+
* conversation yet; and between the two there is no agent to take it.
|
|
7809
8675
|
*/
|
|
7810
8676
|
async function switchTopicToFallbackEntry(key, from, to, options) {
|
|
8677
|
+
const stopRefusingMessages = checkIsFallbackMoveAcrossBackends(key, from, to) ? conversationEndings.refuseMessages(key) : null;
|
|
8678
|
+
try {
|
|
8679
|
+
return await switchTopicToFallbackEntryNow(key, from, to, options);
|
|
8680
|
+
}
|
|
8681
|
+
finally {
|
|
8682
|
+
stopRefusingMessages?.();
|
|
8683
|
+
}
|
|
8684
|
+
}
|
|
8685
|
+
/** @description {@link switchTopicToFallbackEntry} itself, under the refusal its caller took for a move onto the other backend. */
|
|
8686
|
+
async function switchTopicToFallbackEntryNow(key, from, to, options) {
|
|
8687
|
+
const reason = options.reason ?? 'limit';
|
|
7811
8688
|
const k = (0, sessionKey_1.keyToString)(key);
|
|
7812
8689
|
const fromLabel = from ? formatFallbackEntry(from) : '?';
|
|
7813
8690
|
const toLabel = formatFallbackEntry(to);
|
|
7814
|
-
// An OpenCode topic on the server's default model has no rung (`from` is null), yet it is on OpenCode all the same.
|
|
7815
|
-
const isSameFamily = (from?.backend ?? getTopicBackendFamily(key)) === to.backend;
|
|
7816
8691
|
const runningModel = readRunningModelBeforeMove(key, from, to);
|
|
7817
8692
|
// The notice is a topic message: a conversation of another platform (a Jira issue) hears nothing — the log line below says it — and
|
|
7818
8693
|
// its work simply continues.
|
|
@@ -7842,7 +8717,7 @@ async function switchTopicToFallbackEntry(key, from, to, options) {
|
|
|
7842
8717
|
}
|
|
7843
8718
|
if (outcome === 'deferred' || outcome === 'restartRequired') {
|
|
7844
8719
|
fallbackSwitchOffers.delete(k);
|
|
7845
|
-
const notice = (0, fallbackSwitchNotice_1.buildFallbackDeferredNotice)(from, to);
|
|
8720
|
+
const notice = (0, fallbackSwitchNotice_1.buildFallbackDeferredNotice)(from, to, reason);
|
|
7846
8721
|
await say(notice);
|
|
7847
8722
|
return { isSwitched: false, notice };
|
|
7848
8723
|
}
|
|
@@ -7852,26 +8727,38 @@ async function switchTopicToFallbackEntry(key, from, to, options) {
|
|
|
7852
8727
|
if (cutOffWork)
|
|
7853
8728
|
await foldLostWorkIntoNextPrompt(key, { ...cutOffWork, reason: 'restarted', lostAt: Date.now() });
|
|
7854
8729
|
}
|
|
7855
|
-
else if (
|
|
8730
|
+
else if (to.backend === 'opencode' && !checkIsFallbackMoveAcrossBackends(key, from, to)) {
|
|
7856
8731
|
const error = await (0, createAdapter_1.getThreadAdapter)(key).setModel?.(key, (0, fallbackChain_1.buildOpenCodeModelLabel)(to));
|
|
7857
8732
|
if (error)
|
|
7858
8733
|
return fail(error);
|
|
7859
8734
|
}
|
|
7860
8735
|
else {
|
|
7861
|
-
|
|
7862
|
-
|
|
7863
|
-
|
|
7864
|
-
|
|
7865
|
-
|
|
7866
|
-
|
|
7867
|
-
|
|
7868
|
-
|
|
8736
|
+
// Onto the other backend, which ends the conversation the move leaves: held from here — nothing above awaits —, ahead of the bridge,
|
|
8737
|
+
// unless the caller held it already, so a stop under way drops what it held instead of resuming the backend being left (review 24 #1).
|
|
8738
|
+
const ending = options.ending ?? conversationEndings.hold(key);
|
|
8739
|
+
// What the agent took in, read at the moment the bridge reads its transcript: a message it takes in later is in neither (review 27
|
|
8740
|
+
// nit 5).
|
|
8741
|
+
const promptsReachedOrHeld = requestWakeUpEngine?.readPromptsReachedOrHeld(key);
|
|
8742
|
+
let bridge;
|
|
8743
|
+
try {
|
|
8744
|
+
bridge = await buildFallbackBridge(key, {
|
|
8745
|
+
fromLabel: from ? formatFallbackEntry(from) : formatThreadBackend(key),
|
|
8746
|
+
toLabel: toLabel,
|
|
8747
|
+
reason: 'limit',
|
|
8748
|
+
resetsAtText: getFallbackResetTime(from),
|
|
8749
|
+
});
|
|
8750
|
+
// An automatic fallback keeps the conversation (parked, bridged): the questions it had set aside stay open for a late answer.
|
|
8751
|
+
isStoppingBackground = await moveTopicToOtherBackend(key, ending, to.backend, to.backend === 'claude' ? to.profile : null, { isConversationKept: options.isAutomatic === true, promptsReachedOrHeld });
|
|
8752
|
+
}
|
|
8753
|
+
finally {
|
|
8754
|
+
ending.release();
|
|
8755
|
+
}
|
|
7869
8756
|
if (to.backend === 'opencode') {
|
|
7870
8757
|
const error = await (0, createAdapter_1.getThreadAdapter)(key).setModel?.(key, (0, fallbackChain_1.buildOpenCodeModelLabel)(to));
|
|
7871
8758
|
if (error)
|
|
7872
8759
|
return fail(error);
|
|
7873
8760
|
}
|
|
7874
|
-
firstPrompt = { text: bridge,
|
|
8761
|
+
firstPrompt = { text: bridge, carriedRequestIds: [] };
|
|
7875
8762
|
}
|
|
7876
8763
|
// From the end of the wait until the continue prompt is forwarded, the idle the limit left behind is not a turn end (the
|
|
7877
8764
|
// same hold a retry kick has): the model pin below re-spawns the session for seconds, and a wake-up engine that polled
|
|
@@ -7881,15 +8768,15 @@ async function switchTopicToFallbackEntry(key, from, to, options) {
|
|
|
7881
8768
|
apiRetryKicksInFlight.add(k);
|
|
7882
8769
|
try {
|
|
7883
8770
|
cancelApiRetry(key); // retires the offer too: the switch consumed it
|
|
7884
|
-
const notice = `${getFallbackSwitchedNotice(from, to, runningModel)}${isStoppingBackground ? `\n${(0, i18n_1.t)('fallback.backgroundStopped')}` : ''}`;
|
|
7885
|
-
console.log(`[fallback] ${k}: switched from ${fromLabel} to ${toLabel} after a usage limit${firstPrompt ? ' (cross-backend, bridged)' : ''}; resuming`);
|
|
8771
|
+
const notice = `${getFallbackSwitchedNotice(from, to, runningModel, reason)}${isStoppingBackground ? `\n${(0, i18n_1.t)('fallback.backgroundStopped')}` : ''}`;
|
|
8772
|
+
console.log(`[fallback] ${k}: switched from ${fromLabel} to ${toLabel} after ${reason === 'signIn' ? 'its account was refused' : 'a usage limit'}${firstPrompt ? ' (cross-backend, bridged)' : ''}; resuming`);
|
|
7886
8773
|
await say(notice);
|
|
7887
8774
|
await resumeTopicOnNewSession(key, {
|
|
7888
8775
|
modelToPin: (0, fallbackChain_1.getFallbackModelToPin)(to, runningModel),
|
|
7889
8776
|
// Read after the session is up: the open requests may have changed while it started.
|
|
7890
8777
|
getFirstPrompt: () => firstPrompt ?? (0, limitHeldPrompts_1.getLimitResumeMessage)({
|
|
7891
8778
|
continueNudge: (0, i18n_1.t)('apiRetry.continueNudge'),
|
|
7892
|
-
|
|
8779
|
+
untakenRequestPrompts: (0, requestHeader_1.getPromptsNotTakenIn)(requestLimitWaitAnswerDeps?.ledger.listOpenRequestsOf(key) ?? []),
|
|
7893
8780
|
}),
|
|
7894
8781
|
});
|
|
7895
8782
|
return { isSwitched: true, notice };
|
|
@@ -7899,18 +8786,37 @@ async function switchTopicToFallbackEntry(key, from, to, options) {
|
|
|
7899
8786
|
apiRetryKicksInFlight.delete(k);
|
|
7900
8787
|
}
|
|
7901
8788
|
}
|
|
8789
|
+
/**
|
|
8790
|
+
* @description Whether {@link switchTopicToFallbackEntry} moves `key` from `from` onto `to` ACROSS backends — the move that ends the
|
|
8791
|
+
* conversation it leaves — rather than to another Claude account or another OpenCode model of the same conversation.
|
|
8792
|
+
*/
|
|
8793
|
+
function checkIsFallbackMoveAcrossBackends(key, from, to) {
|
|
8794
|
+
if (from?.backend === 'claude' && to.backend === 'claude')
|
|
8795
|
+
return false;
|
|
8796
|
+
// An OpenCode topic on the server's default model has no rung (`from` is null), yet it is on OpenCode all the same.
|
|
8797
|
+
const isSameFamily = (from?.backend ?? getTopicBackendFamily(key)) === to.backend;
|
|
8798
|
+
return !(isSameFamily && to.backend === 'opencode');
|
|
8799
|
+
}
|
|
7902
8800
|
/**
|
|
7903
8801
|
* @description The move ACROSS backends both the usage-limit switch and the operator's manual switch make, first
|
|
7904
8802
|
* half: record `account` as the topic's own Claude pick when one is given (the chain's rung, the operator's pick — a
|
|
7905
8803
|
* switch that only names the account the topic follows passes `null`), then `switchThreadAdapter` stops the old
|
|
7906
8804
|
* session, parks its id and brings back the target family's parked one. The context bridge is built BEFORE this, while
|
|
7907
|
-
* the adapter being left still runs
|
|
7908
|
-
*
|
|
8805
|
+
* the adapter being left still runs, and the caller's `ending` holds the conversation from before the bridge.
|
|
8806
|
+
* `options.promptsReachedOrHeld` is what the agent took in, read when the bridge was built: it is handed to `switchThreadAdapter`'s close
|
|
8807
|
+
* of the requests, so a message is either carried by the bridge or told, never neither (review 27 nit 5). Resolves
|
|
8808
|
+
* whether the stop took background work with it — the caller tells the operator (the agent is told by the next prompt,
|
|
8809
|
+
* `switchThreadAdapter`).
|
|
7909
8810
|
*/
|
|
7910
|
-
async function moveTopicToOtherBackend(key, backend, account, options = {}) {
|
|
8811
|
+
async function moveTopicToOtherBackend(key, ending, backend, account, options = {}) {
|
|
7911
8812
|
if (account !== null)
|
|
7912
8813
|
await state.setClaudeProfileOverride(key, account);
|
|
7913
|
-
|
|
8814
|
+
// The old backend's stop and the id parking run as the conversation's one transition, after a re-spawn: a start or resume of the
|
|
8815
|
+
// old backend in flight is over first, and none comes back beside the new one (review 22, own pass). Held as ending the conversation
|
|
8816
|
+
// it leaves: what a stop queued ahead held is dropped with the line, never resumed into the backend being left — the bridge was built
|
|
8817
|
+
// before the move and never carries it (review 23 #1, review 24 #1).
|
|
8818
|
+
const lostWork = await ending.run(() => switchThreadAdapter(key, backend === 'claude' ? (0, createAdapter_1.resolveClaudeBackendName)(key) : adapterNames_1.openCodeAdapterName, options));
|
|
8819
|
+
return (0, lostWork_1.checkHasLostBackgroundWork)(lostWork);
|
|
7914
8820
|
}
|
|
7915
8821
|
/**
|
|
7916
8822
|
* @description The second half, after a move (across backends or between accounts): start or resume the topic's
|
|
@@ -7933,8 +8839,24 @@ async function resumeTopicOnNewSession(key, options) {
|
|
|
7933
8839
|
const prompt = options.getFirstPrompt();
|
|
7934
8840
|
if (prompt === null)
|
|
7935
8841
|
return;
|
|
7936
|
-
|
|
7937
|
-
|
|
8842
|
+
// The move's continuation is tracked — every open request's counters reset, a limit stop lifted — only once its first prompt reached a
|
|
8843
|
+
// session: at once when forwarded, at its replay when it waited in a startup window. One that reached none (no session left, or a
|
|
8844
|
+
// window that dropped it) starts no turn, and a watch tracked for it would wait for good (review 20 #1).
|
|
8845
|
+
// The requests whose prompts it carries are named as it was built, never read again at its replay (review 21 nit 3).
|
|
8846
|
+
const trackContinuation = () => requestWakeUpEngine?.trackContinuationTurn(key, { isCountersReset: true, carriedRequestIds: prompt.carriedRequestIds }) ?? Promise.resolve();
|
|
8847
|
+
const delivery = await deliverPromptOrBuffer(key, prompt.text, (outcome) => {
|
|
8848
|
+
if (outcome === 'replayed') {
|
|
8849
|
+
trackContinuation().catch((e) => console.error(`[fallback] ${k}: tracking the move's replayed first prompt failed:`, e instanceof Error ? e.message : e));
|
|
8850
|
+
return;
|
|
8851
|
+
}
|
|
8852
|
+
console.warn(`[fallback] ${k}: the first prompt after the move waited for a session start that dropped it; no turn is tracked for it`);
|
|
8853
|
+
});
|
|
8854
|
+
if (delivery === 'noSession') {
|
|
8855
|
+
console.warn(`[fallback] ${k}: the first prompt after the move reached no session; no turn is tracked for it`);
|
|
8856
|
+
return;
|
|
8857
|
+
}
|
|
8858
|
+
if (delivery === 'forwarded')
|
|
8859
|
+
await trackContinuation();
|
|
7938
8860
|
}
|
|
7939
8861
|
// ── a MANUAL switch between the two backends (`utils/backendSwitchPlan.ts`, `commands/backendSwitch.ts`) ──
|
|
7940
8862
|
/** The backend family the topic's agent runs on now (its in-memory pick, else the persisted one); `null` for none or a shell. */
|
|
@@ -7967,7 +8889,7 @@ async function resolveBackendSwitchTarget(key, backend) {
|
|
|
7967
8889
|
}
|
|
7968
8890
|
/**
|
|
7969
8891
|
* @description The gate every MANUAL start of the other backend goes through (`/claude`, `/opencode`, the agent
|
|
7970
|
-
* buttons
|
|
8892
|
+
* buttons): when the topic runs the other backend and holds a conversation,
|
|
7971
8893
|
* ask first and let the answer make the switch. Returns whether it asked — the caller then stops; `false` means
|
|
7972
8894
|
* nothing to hand over (a fresh topic, the same backend, a shell) and the caller goes ahead as it always did.
|
|
7973
8895
|
* `userMessage` is the text typed with the command; the switch passes it on inside the context bridge.
|
|
@@ -7992,25 +8914,45 @@ async function askBeforeCrossBackendSwitch(key, backend, userMessage) {
|
|
|
7992
8914
|
* `/claude` / `/opencode` do. `userMessage` rides inside the bridge.
|
|
7993
8915
|
*/
|
|
7994
8916
|
async function executeBackendSwitch(key, target, options) {
|
|
7995
|
-
|
|
7996
|
-
|
|
7997
|
-
|
|
7998
|
-
|
|
7999
|
-
|
|
8000
|
-
|
|
8001
|
-
|
|
8002
|
-
|
|
8003
|
-
|
|
8004
|
-
|
|
8005
|
-
|
|
8006
|
-
|
|
8007
|
-
|
|
8008
|
-
|
|
8009
|
-
|
|
8010
|
-
|
|
8011
|
-
|
|
8012
|
-
|
|
8013
|
-
|
|
8917
|
+
// A person's message is refused from here until the new backend took the move's first prompt (the bridge, or the start that carries the
|
|
8918
|
+
// text typed with the command), as in the limit move (review 25 #1) — the tap's hold refuses it until this takes over.
|
|
8919
|
+
const stopRefusingMessages = conversationEndings.refuseMessages(key);
|
|
8920
|
+
try {
|
|
8921
|
+
// The move ends the conversation it leaves: held from here, ahead of the bridge, unless the tap that asked for it holds it already —
|
|
8922
|
+
// a stop under way drops what it held instead of resuming the backend being left (review 24 #1).
|
|
8923
|
+
const ending = options.ending ?? conversationEndings.hold(key);
|
|
8924
|
+
// What the agent took in, read at the moment the bridge reads its transcript (review 27 nit 5).
|
|
8925
|
+
const promptsReachedOrHeld = requestWakeUpEngine?.readPromptsReachedOrHeld(key);
|
|
8926
|
+
let bridge;
|
|
8927
|
+
let isStoppingBackground;
|
|
8928
|
+
try {
|
|
8929
|
+
bridge = options.isBridged
|
|
8930
|
+
? await buildFallbackBridge(key, {
|
|
8931
|
+
fromLabel: formatThreadBackend(key),
|
|
8932
|
+
toLabel: (0, backendSwitchPlan_1.formatBackendSwitchBridgeLabel)(target),
|
|
8933
|
+
reason: 'manual',
|
|
8934
|
+
resetsAtText: null,
|
|
8935
|
+
userMessage: options.userMessage,
|
|
8936
|
+
})
|
|
8937
|
+
: null;
|
|
8938
|
+
isStoppingBackground = await moveTopicToOtherBackend(key, ending, target.backend, target.backend === 'claude' && target.isProfilePicked ? target.profile : null, { promptsReachedOrHeld });
|
|
8939
|
+
}
|
|
8940
|
+
finally {
|
|
8941
|
+
ending.release();
|
|
8942
|
+
}
|
|
8943
|
+
// The operator hears that the background work died with the old session; its agent hears it in the first prompt.
|
|
8944
|
+
if (isStoppingBackground)
|
|
8945
|
+
await replyToThread(key, (0, i18n_1.t)('fallback.backgroundStopped'));
|
|
8946
|
+
cancelApiRetry(key); // a wait armed for the backend just left is over
|
|
8947
|
+
await resumeTopicOnNewSession(key, {
|
|
8948
|
+
modelToPin: (0, backendSwitchPlan_1.getBackendSwitchModelToPin)(target),
|
|
8949
|
+
getFirstPrompt: () => (bridge === null ? null : { text: bridge, carriedRequestIds: [] }),
|
|
8950
|
+
args: bridge === null ? options.userMessage : undefined,
|
|
8951
|
+
});
|
|
8952
|
+
}
|
|
8953
|
+
finally {
|
|
8954
|
+
stopRefusingMessages();
|
|
8955
|
+
}
|
|
8014
8956
|
}
|
|
8015
8957
|
/**
|
|
8016
8958
|
* @description Whether a pick, made while a usage-limit wait is armed, names another model of the SAME Claude account that the
|
|
@@ -8056,7 +8998,9 @@ async function switchTopicByOperator(key, to) {
|
|
|
8056
8998
|
from,
|
|
8057
8999
|
to,
|
|
8058
9000
|
currentFamily,
|
|
8059
|
-
|
|
9001
|
+
// Read only where it decides: with a wait armed a pick on the other backend is the limit move whatever it finds, so nothing is read
|
|
9002
|
+
// ahead of the move's hold on the conversation (review 24, own pass).
|
|
9003
|
+
hasConversation: !isUsageLimitWaitArmed && currentFamily !== null && currentFamily !== to.backend && await checkHasConversationToHandOver(key),
|
|
8060
9004
|
isPickBeyondLimit: isUsageLimitWaitArmed && await checkIsPickBeyondLimit(from, to),
|
|
8061
9005
|
});
|
|
8062
9006
|
const target = buildBackendSwitchTargetOfRung(to);
|
|
@@ -8072,8 +9016,7 @@ async function switchTopicByOperator(key, to) {
|
|
|
8072
9016
|
}
|
|
8073
9017
|
case 'sameFamily': {
|
|
8074
9018
|
if (to.backend === 'opencode') {
|
|
8075
|
-
const
|
|
8076
|
-
const { isOk, message, setModelError } = await applyModelSelection(adapter, key, (0, fallbackChain_1.buildOpenCodeModelLabel)(to));
|
|
9019
|
+
const { isOk, message, setModelError } = await applyModelSelection(key, (0, fallbackChain_1.buildOpenCodeModelLabel)(to));
|
|
8077
9020
|
return isOk ? { kind: 'switched', text: message, label } : { kind: 'refused', text: (0, i18n_1.t)('cb.model_error', { error: setModelError ?? message }) };
|
|
8078
9021
|
}
|
|
8079
9022
|
const runningModel = readRunningModelBeforeMove(key, from, to);
|
|
@@ -8089,7 +9032,7 @@ async function switchTopicByOperator(key, to) {
|
|
|
8089
9032
|
const modelToPin = (0, fallbackChain_1.getFallbackModelToPin)(to, runningModel);
|
|
8090
9033
|
if (modelToPin === null)
|
|
8091
9034
|
return { kind: 'switched', text: switchedText === '' && to.model !== null ? (0, i18n_1.t)('cb.model_set', { model: to.model }) : switchedText, label };
|
|
8092
|
-
const { isOk, message, setModelError } = await applyModelSelection(
|
|
9035
|
+
const { isOk, message, setModelError } = await applyModelSelection(key, modelToPin);
|
|
8093
9036
|
if (!isOk)
|
|
8094
9037
|
return { kind: 'refused', text: (0, i18n_1.t)('cb.model_error', { error: setModelError ?? message }) };
|
|
8095
9038
|
return { kind: 'switched', text: switchedText === '' ? message : `${switchedText}\n${message}`, label };
|
|
@@ -8110,7 +9053,8 @@ async function switchTopicByOperator(key, to) {
|
|
|
8110
9053
|
const { askBackendSwitch, registerBackendSwitchCallbacks } = (0, backendSwitch_1.createBackendSwitch)({
|
|
8111
9054
|
...botCore,
|
|
8112
9055
|
getCurrentFamily: getTopicBackendFamily,
|
|
8113
|
-
|
|
9056
|
+
holdConversationEnding: (key) => conversationEndings.hold(key),
|
|
9057
|
+
performBackendSwitch: (key, target, options) => executeBackendSwitch(key, target, { isBridged: true, userMessage: options.userMessage, ending: options.ending }),
|
|
8114
9058
|
});
|
|
8115
9059
|
/**
|
|
8116
9060
|
* @description A tap on a «switch to …» button of a limit notice: honoured only while the thread's open offer
|
|
@@ -8134,20 +9078,52 @@ async function takeFallbackSwitchOffer(key, episodeId, index) {
|
|
|
8134
9078
|
* refuses for the balance; otherwise the account is just kept off agents for an hour. The check runs beside the usage refresh
|
|
8135
9079
|
* with a timeout of its own, so the answer is held for the longer of the two, never their sum. The refresh is waited for only
|
|
8136
9080
|
* up to `claudeLaunchRefreshBudgetMs`; past it the cached figures are answered (an agent that waits on a silent tool call is
|
|
8137
|
-
* dropped by its own client after 300 s).
|
|
9081
|
+
* dropped by its own client after 300 s). A query by worker ROLE (`/workers`, `utils/workerRoles.ts`) reads the role's default first:
|
|
9082
|
+
* a Claude role's model goes into the pick (the Fable window counts for a Fable role); an OpenCode role's model is checked against
|
|
9083
|
+
* the catalog, read beside the refresh within the same budget — an unread catalog never makes the role unavailable.
|
|
8138
9084
|
*/
|
|
8139
9085
|
async function listClaudeProfilesForAgent(query) {
|
|
9086
|
+
const workerRoles = readWorkerRolesSettings();
|
|
9087
|
+
const isOpenCodeRole = query.role !== null && (0, workerRoles_2.resolveWorkerRole)(workerRoles, query.role).value.cli === 'opencode';
|
|
8140
9088
|
// The agent launches its worker under whichever folder the answer names, so every folder is put right before it is named.
|
|
8141
9089
|
for (const view of getClaudeProfileUsageViews())
|
|
8142
9090
|
repairClaudeProfileFolder(view.configDir);
|
|
8143
9091
|
const stoppedApiProfile = (0, claudeApiAgentStop_1.getApiProfileStoppedByAgent)(getClaudeProfileUsageViews(), query, Date.now());
|
|
8144
|
-
await Promise.all([
|
|
9092
|
+
const [openCodeCatalog] = await Promise.all([
|
|
9093
|
+
isOpenCodeRole ? readOpenCodeCatalogForWorker() : Promise.resolve(null),
|
|
8145
9094
|
(0, claudeUsageRefresher_1.refreshClaudeUsageForLaunch)(claudeUsageRefresher, { currentProfile: query.currentProfile, isStoppedByLimit: query.isStoppedByLimit, maxAgeMs: claudeUsageRefresher_1.claudeUsageOnDemandMaxAgeMs }),
|
|
8146
9095
|
stoppedApiProfile === null
|
|
8147
9096
|
? Promise.resolve()
|
|
8148
9097
|
: (0, claudeApiAgentStop_1.verifyClaudeApiAgentStop)(stoppedApiProfile, claudeApiAgentStopPorts).then(() => undefined, (e) => console.warn(`[credit] ${stoppedApiProfile}: checking an agent's stop report failed:`, e instanceof Error ? e.message : e)),
|
|
8149
9098
|
]);
|
|
8150
|
-
|
|
9099
|
+
const report = (0, claudeProfileUsageViews_1.buildClaudeProfilesCreditReport)(getClaudeProfileUsageViews(), (0, workerRoles_2.getWorkerRolePickModel)(workerRoles, query.role, query.model), Date.now(), {
|
|
9100
|
+
currentProfile: query.currentProfile,
|
|
9101
|
+
isStoppedByLimit: query.isStoppedByLimit,
|
|
9102
|
+
lastRunEndedAtMs: query.lastRunEndedAtMs,
|
|
9103
|
+
chainScope: (0, fallbackChain_1.getClaudeLaunchChainScope)(state.getFallbackChain()),
|
|
9104
|
+
});
|
|
9105
|
+
const worker = (0, workerRoles_2.buildWorkerRoleReportForQuery)(workerRoles, query.role, report.profiles, openCodeCatalog);
|
|
9106
|
+
return worker === null ? report : { ...report, worker };
|
|
9107
|
+
}
|
|
9108
|
+
/**
|
|
9109
|
+
* The OpenCode catalog for a worker role's check, waited for at most the launch refresh budget; `null` when it could not be read in
|
|
9110
|
+
* time (or failed) — the role is then NOT called unavailable. The adapter caches the list, so a recent read answers at once.
|
|
9111
|
+
*/
|
|
9112
|
+
async function readOpenCodeCatalogForWorker() {
|
|
9113
|
+
let budgetTimer;
|
|
9114
|
+
const budget = new Promise((resolve) => {
|
|
9115
|
+
budgetTimer = setTimeout(() => resolve(null), claudeUsageRefresher_1.claudeLaunchRefreshBudgetMs);
|
|
9116
|
+
});
|
|
9117
|
+
const read = (async () => (await (0, createAdapter_1.getAdapter)(adapterNames_1.openCodeAdapterName).getAvailableModels?.()) ?? null)().catch((e) => {
|
|
9118
|
+
console.warn('[workers] the OpenCode catalog is unavailable:', e instanceof Error ? e.message : e);
|
|
9119
|
+
return null;
|
|
9120
|
+
});
|
|
9121
|
+
try {
|
|
9122
|
+
return await Promise.race([read, budget]);
|
|
9123
|
+
}
|
|
9124
|
+
finally {
|
|
9125
|
+
clearTimeout(budgetTimer);
|
|
9126
|
+
}
|
|
8151
9127
|
}
|
|
8152
9128
|
const { registerFallbackChainCommands, registerFallbackChainCallbacks, openAutoSwitchView, runAutoSwitchCommand, applyAutoSwitch } = (0, fallbackChain_2.createFallbackChain)({
|
|
8153
9129
|
...botCore,
|
|
@@ -8168,6 +9144,12 @@ const { registerTodoCommands, registerTodoCallbacks } = (0, todo_1.createTodo)({
|
|
|
8168
9144
|
getConversationLabel: getTodoConversationLabel,
|
|
8169
9145
|
checkIsConversationAsleep: (conversationKey) => getTodoSessionActivity(conversationKey) === 'asleep',
|
|
8170
9146
|
});
|
|
9147
|
+
// ── The limit reminders (`/limits_reminders`): `connectors/telegram/commands/limitReminders.ts`, `utils/limitRemindersScreenPlan.ts` ──
|
|
9148
|
+
const { registerLimitRemindersCommands, registerLimitRemindersCallbacks, openPicker: openLimitRemindersPicker, getRowLabel: getLimitRemindersRowLabel } = (0, limitReminders_1.createLimitReminders)({
|
|
9149
|
+
...botCore,
|
|
9150
|
+
readInstanceLimitReminders: readLimitRemindersSettings,
|
|
9151
|
+
getSettingsPath: () => (0, instanceSettings_1.getInstanceSettingsPath)(),
|
|
9152
|
+
});
|
|
8171
9153
|
const { registerLimitsBoardCommands, registerLimitsBoardCallbacks } = (0, limitsBoard_1.createLimitsBoard)({
|
|
8172
9154
|
...botCore,
|
|
8173
9155
|
getInstanceTimezone: getCurrentTimezone,
|
|
@@ -8179,17 +9161,20 @@ const { registerLimitsBoardCommands, registerLimitsBoardCallbacks } = (0, limits
|
|
|
8179
9161
|
listClaudeModels: async (key) => (await (0, createAdapter_1.getThreadAdapter)(key).getAvailableModels?.()) ?? [],
|
|
8180
9162
|
runAutoSwitchCommand,
|
|
8181
9163
|
getArmedLimitRetryFireAt,
|
|
9164
|
+
getRemindersRowLabel: getLimitRemindersRowLabel,
|
|
9165
|
+
openRemindersPicker: openLimitRemindersPicker,
|
|
8182
9166
|
});
|
|
8183
9167
|
const { registerClaudeAccountCommands, registerClaudeAccountCallbacks, checkIsAwaitingProfileName, cancelProfileNameCapture, submitProfileName, pickClaudeAccount, onClaudeProfileAuthStatus: recordClaudeProfileAuthStatus, onClaudeProfileApiKey: storeClaudeProfileApiKey, } = (0, claudeAccounts_1.createClaudeAccounts)({
|
|
8184
9168
|
...botCore,
|
|
8185
9169
|
getDataDir: state_1.resolveDataDir,
|
|
8186
9170
|
getInstanceTimezone: getCurrentTimezone,
|
|
8187
9171
|
refreshClaudeUsage: (options) => claudeUsageRefresher.refreshAll(options),
|
|
8188
|
-
syncClaudeProfiles: (options) =>
|
|
9172
|
+
syncClaudeProfiles: (options) => syncClaudeProfilesAndRefusals(options),
|
|
8189
9173
|
readClaudeAuthStatus: readClaudeAuthStatusUnder,
|
|
8190
9174
|
startClaudeProfileLogin: (key, profile) => startClaudeAuthLogin(key, profile),
|
|
8191
9175
|
applyClaudeProfile: applyClaudePickToThread,
|
|
8192
9176
|
applyClaudeProfileEverywhere,
|
|
9177
|
+
noteClaudeAccountsChanged: () => noteClaudeProfileUsability(),
|
|
8193
9178
|
switchTopicByOperator,
|
|
8194
9179
|
detectOpenCodeProviders: async () => (0, fallbackChain_1.listOpenCodeProviders)((await (0, createAdapter_1.getAdapter)(adapterNames_1.openCodeAdapterName).getAvailableModels?.()) ?? []),
|
|
8195
9180
|
listOpenCodeModels: async () => (await (0, createAdapter_1.getAdapter)(adapterNames_1.openCodeAdapterName).getAvailableModels?.()) ?? [],
|
|
@@ -8230,6 +9215,7 @@ registerClaudeAccountCommands();
|
|
|
8230
9215
|
registerTopicCommand();
|
|
8231
9216
|
registerFallbackChainCommands();
|
|
8232
9217
|
registerLimitsBoardCommands();
|
|
9218
|
+
registerLimitRemindersCommands();
|
|
8233
9219
|
registerTodoCommands();
|
|
8234
9220
|
registerSttCommands();
|
|
8235
9221
|
const { registerSelfUpdateCommands, registerSelfUpdateCallbacks } = (0, selfUpdate_1.createSelfUpdate)({
|
|
@@ -8325,15 +9311,28 @@ async function handleSessionsList(key) {
|
|
|
8325
9311
|
* Recovers the full session id from `threadSessionLists`; if the cache was
|
|
8326
9312
|
* lost (bot restarted between showing the list and the pick), reports it
|
|
8327
9313
|
* via `onExpired`. Returns the user-facing result message to send, or
|
|
8328
|
-
* `null` when `onExpired` already handled the stale-cache case.
|
|
8329
|
-
|
|
8330
|
-
|
|
8331
|
-
|
|
8332
|
-
|
|
9314
|
+
* `null` when `onExpired` already handled the stale-cache case. `ending` is the
|
|
9315
|
+
* button's hold on the conversation, taken ahead of its toast; the digit reply
|
|
9316
|
+
* has none, and the pick holds it here (review 24 #1).
|
|
9317
|
+
*/
|
|
9318
|
+
async function resumeSessionByIndex(key, idx, onExpired, ending) {
|
|
9319
|
+
const sessionId = getListedSessionId(key, idx);
|
|
9320
|
+
if (sessionId === null) {
|
|
9321
|
+
ending?.release();
|
|
8333
9322
|
await onExpired();
|
|
8334
9323
|
return null;
|
|
8335
9324
|
}
|
|
8336
|
-
|
|
9325
|
+
// As the conversation's one transition: no ensure resumes the old conversation beside the pick, and no idle stop runs under it
|
|
9326
|
+
// (review 20 nit 3). A prompt that comes meanwhile routes to a wake, whose ensure waits for the pick in the same queue.
|
|
9327
|
+
return (ending ?? conversationEndings.hold(key)).run(() => resumePickedSession(key, sessionId));
|
|
9328
|
+
}
|
|
9329
|
+
/** The session id at `idx` in the thread's last shown `/sessions` list; `null` when that list is gone (a restart) or holds no such row. */
|
|
9330
|
+
function getListedSessionId(key, idx) {
|
|
9331
|
+
const list = threadSessionLists.get((0, sessionKey_1.keyToString)(key));
|
|
9332
|
+
return list !== undefined && idx >= 0 && idx < list.length ? list[idx] : null;
|
|
9333
|
+
}
|
|
9334
|
+
/** {@link resumeSessionByIndex}'s resume of the picked session, inside the conversation's transition. */
|
|
9335
|
+
async function resumePickedSession(key, sessionId) {
|
|
8337
9336
|
// Pick-mode is armed only by `handleSessionsList` (binding-gated), but a
|
|
8338
9337
|
// binding can vanish (/unbind) between listing and picking — resume must
|
|
8339
9338
|
// never run against an unbound thread (no WORK_ROOT fallback).
|
|
@@ -8343,13 +9342,17 @@ async function resumeSessionByIndex(key, idx, onExpired) {
|
|
|
8343
9342
|
const workDir = workDirDecision.workDir;
|
|
8344
9343
|
const adapter = (0, createAdapter_1.getThreadAdapter)(key);
|
|
8345
9344
|
markNeedsNewMessage(key);
|
|
9345
|
+
// What the conversation being left took in, read off its process before the resume replaces it: the requests close only once the pick
|
|
9346
|
+
// came up (a failed pick keeps the conversation it meant to leave), and by then the probe reads the picked one (review 26 #1).
|
|
9347
|
+
const promptsReachedOrHeld = requestWakeUpEngine?.readPromptsReachedOrHeld(key);
|
|
8346
9348
|
try {
|
|
8347
9349
|
// The ONLY resume path that posts the "last N messages" context block —
|
|
8348
9350
|
// silent re-attach (bot restart) and crash recovery must stay quiet.
|
|
8349
9351
|
await adapter.resumeSession(key, workDir, sessionId, { isWithRecentContext: true });
|
|
8350
|
-
// Another session took over this topic; it does not know the open
|
|
8351
|
-
// for the conversation it replaces would send its label into the
|
|
8352
|
-
|
|
9352
|
+
// Another session took over this topic; it does not know the open requests — a person whose words the agent never read is told
|
|
9353
|
+
// (review 26 #2) —, and the question the idle compaction re-asked for the conversation it replaces would send its label into the
|
|
9354
|
+
// picked one.
|
|
9355
|
+
cancelEndingConversationRequests(key, promptsReachedOrHeld);
|
|
8353
9356
|
closeReAskedQuestion(key);
|
|
8354
9357
|
closeSetAsideQuestionsInBackground(key);
|
|
8355
9358
|
// Persist the PICKED id — without this the next restart re-attaches to
|
|
@@ -8395,14 +9398,20 @@ command('quitall', async (_ctx, key) => {
|
|
|
8395
9398
|
let stopped = 0;
|
|
8396
9399
|
let active = 0;
|
|
8397
9400
|
// A Telegram command stops Telegram sessions only: a Jira issue's work is not this topic's to stop (J2b, R3).
|
|
8398
|
-
|
|
8399
|
-
|
|
8400
|
-
|
|
9401
|
+
const conversations = (0, foreignKeyFallbacks_1.getTelegramConversations)(state.listBindings());
|
|
9402
|
+
// Each topic as its one transition, after a re-spawn and marked as ended, as `/quit` (review 22 own pass, review 23 #1); the topics side
|
|
9403
|
+
// by side, so one waiting behind a long resume holds no other back, and each waits for its own processes' exits (review 23 nit 4).
|
|
9404
|
+
await Promise.all(conversations.map(async ({ key: bKey }) => {
|
|
9405
|
+
cancelEndingConversationRequests(bKey);
|
|
9406
|
+
const result = await conversationEndings.hold(bKey).run(async () => {
|
|
9407
|
+
const swept = await stopAndWaitAllAdaptersFor(bKey);
|
|
9408
|
+
// Same release-for-good semantics as `/quit`, per swept thread.
|
|
9409
|
+
await releaseConversationIds(bKey);
|
|
9410
|
+
return swept;
|
|
9411
|
+
});
|
|
8401
9412
|
active += result.attempted;
|
|
8402
9413
|
stopped += result.stopped.length;
|
|
8403
|
-
|
|
8404
|
-
await releaseConversationIds(bKey);
|
|
8405
|
-
}
|
|
9414
|
+
}));
|
|
8406
9415
|
if (active === 0) {
|
|
8407
9416
|
await replyToThread(key, (0, i18n_1.t)('quit_all.none_active'));
|
|
8408
9417
|
return;
|
|
@@ -8440,54 +9449,58 @@ command(['quit', 'q'], async (_ctx, key) => {
|
|
|
8440
9449
|
// does NOT go through releaseThreadSession (it stops adapters + clears ids
|
|
8441
9450
|
// inline), so the cancel is wired here explicitly.
|
|
8442
9451
|
cancelApiRetry(key);
|
|
8443
|
-
|
|
9452
|
+
// /quit ends the work: its open requests close, a person whose words the agent never read told (review 26 #2) — read now, while the
|
|
9453
|
+
// process is still the one that took them in or not.
|
|
9454
|
+
cancelEndingConversationRequests(key);
|
|
8444
9455
|
cancelClaudeAuthLogin(key); // /quit teardown → kill any in-flight /login pty
|
|
8445
9456
|
cancelOpenCodeOAuthLogin(key); // /quit teardown → kill any in-flight /connect oauth pty
|
|
8446
9457
|
clearAuthNotice(key); // /quit teardown → retire any pinned logged-out notice
|
|
8447
|
-
|
|
8448
|
-
|
|
8449
|
-
|
|
8450
|
-
//
|
|
8451
|
-
|
|
8452
|
-
|
|
8453
|
-
|
|
8454
|
-
|
|
8455
|
-
|
|
8456
|
-
|
|
8457
|
-
//
|
|
8458
|
-
|
|
8459
|
-
|
|
8460
|
-
|
|
8461
|
-
|
|
9458
|
+
// As the conversation's one transition (it waits for a json-stream re-spawn first): a start, a resume or a re-spawn in flight is
|
|
9459
|
+
// over before /quit reads what runs, so none brings a process back for a conversation /quit released (review 22, own pass), and a
|
|
9460
|
+
// start or resume that comes after waits behind it. Marked as ending the conversation: a stop queued ahead drops what it held instead
|
|
9461
|
+
// of resuming the conversation for it (review 23 #1).
|
|
9462
|
+
const reply = await conversationEndings.hold(key).run(async () => {
|
|
9463
|
+
const adapter = (0, createAdapter_1.getThreadAdapter)(key);
|
|
9464
|
+
const adapterName = (0, createAdapter_1.getThreadAdapterNameRaw)(key);
|
|
9465
|
+
const primaryActive = adapter.checkIsActive(key);
|
|
9466
|
+
// Defensive: any *other* adapter that's also active for this thread is
|
|
9467
|
+
// a leftover from a previous botched switch. Kill it first so it can't
|
|
9468
|
+
// keep streaming after the user's "quit". Re-using the sweep helper
|
|
9469
|
+
// instead of an open-coded loop avoids drift between the call sites.
|
|
9470
|
+
const otherAdapters = (0, createAdapter_1.getKnownAdapterNames)().filter(n => n !== adapterName);
|
|
9471
|
+
stopAllAdaptersFor(key, otherAdapters);
|
|
9472
|
+
if (!primaryActive) {
|
|
9473
|
+
// A sleeping conversation is released for good: the next message gets the no-agent hint, /claude or /opencode starts a fresh one.
|
|
9474
|
+
if (getResumableSessionId(key) !== null) {
|
|
9475
|
+
await releaseConversationIds(key);
|
|
9476
|
+
return (0, i18n_1.t)('agent.sleeping_released');
|
|
9477
|
+
}
|
|
9478
|
+
return 'No agent running';
|
|
8462
9479
|
}
|
|
8463
|
-
|
|
8464
|
-
|
|
8465
|
-
|
|
8466
|
-
|
|
8467
|
-
|
|
8468
|
-
|
|
8469
|
-
|
|
8470
|
-
|
|
8471
|
-
|
|
8472
|
-
|
|
8473
|
-
|
|
8474
|
-
|
|
8475
|
-
|
|
8476
|
-
|
|
8477
|
-
|
|
8478
|
-
return;
|
|
8479
|
-
}
|
|
8480
|
-
// OpenCode, terminal, any future adapter: tear down via stopSession. «Stopped» is said once it is: a `/claude` sent on the
|
|
8481
|
-
// reply must find the session gone, not «already running» — as one transition, so a start or resume waits behind it.
|
|
8482
|
-
await sessionTransitions.run((0, sessionKey_1.keyToString)(key), async () => {
|
|
9480
|
+
markNeedsNewMessage(key);
|
|
9481
|
+
// Close any still-pending OpenCode question on the server BEFORE the teardown
|
|
9482
|
+
// below (a stopped session can't accept the reject; an unrejected question
|
|
9483
|
+
// re-surfaces on the next reattach). No-op for Claude / no pending question.
|
|
9484
|
+
adapter.rejectQuestion?.(key);
|
|
9485
|
+
if (adapterName === 'claude') {
|
|
9486
|
+
adapter.sendSignal(key, 'SIGINT');
|
|
9487
|
+
await new Promise((r) => setTimeout(r, CLAUDE_DOUBLE_SIGINT_GAP_MS));
|
|
9488
|
+
adapter.sendSignal(key, 'SIGINT');
|
|
9489
|
+
// Explicit quit releases the session for good — no auto-reattach later.
|
|
9490
|
+
await state.clearAgentSessionIds(key);
|
|
9491
|
+
return (0, i18n_1.t)('agent.exit_signal_sent', { label: adapter.label });
|
|
9492
|
+
}
|
|
9493
|
+
// OpenCode, terminal, any future adapter: tear down via stopSession. «Stopped» is said once it is: a `/claude` sent on the
|
|
9494
|
+
// reply must find the session gone, not «already running».
|
|
8483
9495
|
if (adapter.stopSessionAndWait)
|
|
8484
9496
|
await adapter.stopSessionAndWait(key);
|
|
8485
9497
|
else
|
|
8486
9498
|
adapter.stopSession(key);
|
|
9499
|
+
// Explicit quit releases the session for good — no auto-reattach later.
|
|
9500
|
+
await state.clearAgentSessionIds(key);
|
|
9501
|
+
return (0, i18n_1.t)('agent.stopped', { label: adapter.label });
|
|
8487
9502
|
});
|
|
8488
|
-
|
|
8489
|
-
await state.clearAgentSessionIds(key);
|
|
8490
|
-
await replyToThread(key, (0, i18n_1.t)('agent.stopped', { label: adapter.label }));
|
|
9503
|
+
await replyToThread(key, reply);
|
|
8491
9504
|
});
|
|
8492
9505
|
// ── tmux-style controls (Claude CLI) ──
|
|
8493
9506
|
command('c', async (_ctx, key) => {
|
|
@@ -8726,8 +9739,8 @@ command('timestamps', async (_ctx, key, parsed) => {
|
|
|
8726
9739
|
* Routing mirrors the plain-text handler via the shared choke points:
|
|
8727
9740
|
* `ensureAgentSession` does the bind-check + start (returns `unbound` →
|
|
8728
9741
|
* bind-required reply, same as every agent-facing path), then
|
|
8729
|
-
* `
|
|
8730
|
-
*
|
|
9742
|
+
* `deliverPromptByState` opens the request and routes the prompt at its write:
|
|
9743
|
+
* forwarded (active) or buffered (mid-startup, or behind a stop).
|
|
8731
9744
|
*/
|
|
8732
9745
|
command('schedule', async (ctx, key, parsed) => {
|
|
8733
9746
|
const text = parsed.argsText;
|
|
@@ -8755,10 +9768,7 @@ command('schedule', async (ctx, key, parsed) => {
|
|
|
8755
9768
|
// Fresh-start notice (empty when the session was already active / starting).
|
|
8756
9769
|
if (result.message)
|
|
8757
9770
|
await replyToThread(key, result.message);
|
|
8758
|
-
|
|
8759
|
-
const opening = await openTopicRequest(key, wrappedPrompt, { source: 'schedule', requesterId: (0, topicRequest_1.getTopicRequesterId)(ctx.from) });
|
|
8760
|
-
const delivery = await deliverPromptOrBuffer(key, `${opening.header}${wrappedPrompt}`, isStarting, undefined, { isPersonInput: true });
|
|
8761
|
-
await settleTopicRequestAfterDelivery(key, opening, delivery);
|
|
9771
|
+
await deliverPromptByState(key, wrappedPrompt, { source: 'schedule', requesterId: (0, topicRequest_1.getTopicRequesterId)(ctx.from) });
|
|
8762
9772
|
});
|
|
8763
9773
|
const reminderWizards = new Map();
|
|
8764
9774
|
const { cancelReminderWizard, claimReminderTextCapture, expireReminderWizard, finishReminderWizard, registerReminderCommands, registerReminderCallbacks, } = (0, reminders_1.createReminders)({
|
|
@@ -8847,7 +9857,7 @@ const botCommands = new Set([
|
|
|
8847
9857
|
'start', 'claude', 'opencode', 'oc', 'terminal', 'agent', 'sessions', 'resume', 'cancel', 'model', 'connect',
|
|
8848
9858
|
'disconnect', 'stop', 'stopall', 'stop-all', 'quit-all', 'status', 'c', 'y', 'n', 'enter', 'up', 'down', 'tab', 'esc', 'escape', 'interrupt', 'output', 'clear_messages',
|
|
8849
9859
|
'bind', 'topic', 'unbind', 'where', 'ls', 'list', 'new', 'whoami', 'version', 'help', 'language', 'lang',
|
|
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',
|
|
9860
|
+
'doctor', 'mcp', 'rename_session', 'compact', 'compact_on_idle', 'compact_summary', 'compact_self_review', 'bot_skills', 'workers', 'worker_models', 'question_wait', 'topic_status', 'task_agents', 'runners', 'auto_continue_limits', 'limits', 'limits_autoswitch', 'limits_reminders', 'limit_reminders', 'trace', 'timestamps', 'timezone', 'schedule', 'reminders', 'todo', 'thinking', 'tool_results',
|
|
8851
9861
|
'subagent', 'claude_mode', 'effort', 'verbosity', 'quit', 'q', 'quitall', 'pair', 'account', 'accounts', 'fallback', 'stt', 'voice', 'speech', 'update', 'access',
|
|
8852
9862
|
]);
|
|
8853
9863
|
/**
|
|
@@ -8861,7 +9871,7 @@ const forwardedClearCommand = '/clear';
|
|
|
8861
9871
|
// Text message handler — main conversational entrypoint
|
|
8862
9872
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
8863
9873
|
/**
|
|
8864
|
-
* @description A talker's text — the one early branch, so no armed step, command
|
|
9874
|
+
* @description A talker's text — the one early branch, so no armed step, command or guide of the admin path
|
|
8865
9875
|
* can be reached by checks spread through the handler. What it does: it is refused if it is a slash text (agent slash
|
|
8866
9876
|
* commands control the conversation, and the commands the bot owns were decided before the message got here); a pasted
|
|
8867
9877
|
* OAuth callback URL is deleted as a secret, whoever sent it; a raw-shell topic is refused; otherwise it is a prompt like any
|
|
@@ -8899,8 +9909,8 @@ async function handleTalkerText(ctx, key) {
|
|
|
8899
9909
|
const messageContext = getMessageContext(key, ctx.message);
|
|
8900
9910
|
const intake = { source: 'text', requesterId: (0, topicRequest_1.getTopicRequesterId)(ctx.from) };
|
|
8901
9911
|
const sentAtMs = ctx.message.date * 1000;
|
|
8902
|
-
if (
|
|
8903
|
-
await
|
|
9912
|
+
if (checkIsArrivalRoutedAtWrite(key)) {
|
|
9913
|
+
await deliverPromptDuringStartup(key, text, intake, messageContext);
|
|
8904
9914
|
return;
|
|
8905
9915
|
}
|
|
8906
9916
|
if (adapter.checkIsActive(key)) {
|
|
@@ -8950,7 +9960,7 @@ bot.on((0, filters_1.message)('text'), async (ctx) => {
|
|
|
8950
9960
|
const text = (0, utils_1.stripCommandBotMention)(ctx.message.text.trim());
|
|
8951
9961
|
const kStr = (0, sessionKey_1.keyToString)(key);
|
|
8952
9962
|
// A FORWARDED message is content, never control input: its words are somebody else's, so a `/quit` in it is not an
|
|
8953
|
-
// order, a bare digit is not a pick or an answer
|
|
9963
|
+
// order, a bare digit is not a pick or an answer — the mark the agent reads says so. The routes
|
|
8954
9964
|
// that take text as an ANSWER the bot asked for (a pasted code, a name, a key, a reminder's text) still take it.
|
|
8955
9965
|
const isForwarded = (0, inbound_1.checkIsTelegramForward)(ctx.message);
|
|
8956
9966
|
const isSlashText = !isForwarded && text.startsWith('/');
|
|
@@ -9071,13 +10081,15 @@ bot.on((0, filters_1.message)('text'), async (ctx) => {
|
|
|
9071
10081
|
if (ctx.from !== undefined && (await handleRunnersAddressText(key, text, ctx.from)))
|
|
9072
10082
|
return;
|
|
9073
10083
|
// Session is mid-startup → buffer the prompt and replay it once the agent is
|
|
9074
|
-
// ready, instead of dropping it into the "no agent running" guidance below.
|
|
9075
|
-
|
|
9076
|
-
|
|
10084
|
+
// ready, instead of dropping it into the "no agent running" guidance below. A
|
|
10085
|
+
// command ending or replacing the conversation → refused at the write, never the
|
|
10086
|
+
// guidance nor a write into the agent it ends (review 25 #1).
|
|
10087
|
+
if (checkIsArrivalRoutedAtWrite(key)) {
|
|
10088
|
+
await deliverPromptDuringStartup(key, text, { source: 'text', requesterId: (0, topicRequest_1.getTopicRequesterId)(ctx.from) }, getMessageContext(key, ctx.message));
|
|
9077
10089
|
return;
|
|
9078
10090
|
}
|
|
9079
10091
|
// Set when this very message bound the topic: its welcome is already the answer, so the idle-thread hint at the end
|
|
9080
|
-
// stays out
|
|
10092
|
+
// stays out.
|
|
9081
10093
|
let isJustAutoBound = false;
|
|
9082
10094
|
// Audit S2 / #5: if `forum_topic_created` was emitted by a non-allowed
|
|
9083
10095
|
// admin, we stashed the topic name in `pendingTopicNames` without
|
|
@@ -9130,12 +10142,11 @@ bot.on((0, filters_1.message)('text'), async (ctx) => {
|
|
|
9130
10142
|
// Numeric model selection after `/model`.
|
|
9131
10143
|
// Audit S12 / #20: previous code returned only when `adapter.setModel` was
|
|
9132
10144
|
// truthy; on adapters that don't implement it (legacy void return) execution
|
|
9133
|
-
// fell through and the same numeric reply was
|
|
9134
|
-
// natural-language start + forwarded to the agent. `applyNumberedModelPick`
|
|
10145
|
+
// fell through and the same numeric reply was forwarded to the agent as a prompt. `applyNumberedModelPick`
|
|
9135
10146
|
// always replies (even for the unsupported case), so we always return after a
|
|
9136
10147
|
// numeric pick — the user clearly intended a model pick, not a prompt.
|
|
9137
10148
|
if (!isForwarded && /^\d+$/.test(text) && awaitingModelSelection.has(kStr)) {
|
|
9138
|
-
await applyNumberedModelPick(
|
|
10149
|
+
await applyNumberedModelPick(key, parseInt(text, 10));
|
|
9139
10150
|
return;
|
|
9140
10151
|
}
|
|
9141
10152
|
// Session-pick mode (armed by `/sessions` / `/resume`). Only while the
|
|
@@ -9166,41 +10177,6 @@ bot.on((0, filters_1.message)('text'), async (ctx) => {
|
|
|
9166
10177
|
// passthrough: not a number — exit pick-mode and let normal handling run.
|
|
9167
10178
|
awaitingSessionSelection.delete(kStr);
|
|
9168
10179
|
}
|
|
9169
|
-
// Natural-language start.
|
|
9170
|
-
if (!isForwarded && !adapter.checkIsActive(key)) {
|
|
9171
|
-
const startMatch = (0, agentTrigger_1.parseAgentTrigger)(text);
|
|
9172
|
-
if (startMatch.isMatch && startMatch.adapterName) {
|
|
9173
|
-
if (checkIsGeneral(key)) {
|
|
9174
|
-
await replyToThread(key, (0, i18n_1.t)('error.start_in_general'));
|
|
9175
|
-
return;
|
|
9176
|
-
}
|
|
9177
|
-
// The other backend, with a conversation to hand over: ask first (a shell is no backend to hand over to).
|
|
9178
|
-
const requestedFamily = (0, backendSwitchPlan_1.getBackendFamily)(startMatch.adapterName);
|
|
9179
|
-
if (requestedFamily !== null && state.getBinding(key) && await askBeforeCrossBackendSwitch(key, requestedFamily, startMatch.args))
|
|
9180
|
-
return;
|
|
9181
|
-
// The shared `ensureAgentSession` does the bind-check + switch + start.
|
|
9182
|
-
// The explicit matched adapter wins (`preferredAdapterName`), named the way
|
|
9183
|
-
// `/claude` names it: `claude` is the topic's Claude backend, never the bare
|
|
9184
|
-
// tmux one. The phrase's trailing args ride along. On `unbound` we keep this
|
|
9185
|
-
// path's own reply: the folder picker (plan §11 Этап 4 — starting without a
|
|
9186
|
-
// binding would silently launch against WORK_ROOT, which is almost never wanted).
|
|
9187
|
-
const result = await ensureAgentSession(key, {
|
|
9188
|
-
preferredAdapterName: (0, createAdapter_1.resolveStartAdapterName)(key, startMatch.adapterName),
|
|
9189
|
-
args: startMatch.args,
|
|
9190
|
-
});
|
|
9191
|
-
if (!result.ok && result.reason === 'unbound') {
|
|
9192
|
-
const subdirs = listAvailableSubdirs(ENV.workRoot);
|
|
9193
|
-
const extra = (0, bindPicker_1.buildBindKeyboard)(subdirs, 0, bindPicker_1.BIND_PAGE_SIZE, !!state.getBinding(key));
|
|
9194
|
-
await replyToThread(key, (0, i18n_1.t)('thread.no_binding'), extra);
|
|
9195
|
-
return;
|
|
9196
|
-
}
|
|
9197
|
-
// Empty when a self-greeting agent started (its banner is the cue) — guard
|
|
9198
|
-
// like the /schedule consumer so we never post a blank message.
|
|
9199
|
-
if (result.message)
|
|
9200
|
-
await replyToThread(key, result.message);
|
|
9201
|
-
return;
|
|
9202
|
-
}
|
|
9203
|
-
}
|
|
9204
10180
|
// Claude TUI prompt on screen + a bare control reply (option digit or y/n)
|
|
9205
10181
|
// → drive it in place. `getClaudeReplyRoute` decides precedence: a real
|
|
9206
10182
|
// AskUserQuestion SELECTOR wins for a control reply; free-form prose breaks
|
|
@@ -9331,7 +10307,7 @@ bot.on((0, filters_1.message)('voice'), async (ctx) => {
|
|
|
9331
10307
|
});
|
|
9332
10308
|
/**
|
|
9333
10309
|
* @description Background worker for a single voice note: download → transcribe
|
|
9334
|
-
* → status emit → (buffer /
|
|
10310
|
+
* → status emit → (buffer / binding checks / forward).
|
|
9335
10311
|
* Byte-for-byte the old voice handler's post-gate body — moved verbatim out of
|
|
9336
10312
|
* the handler so it runs OFF the telegraf update loop (per-thread serialized).
|
|
9337
10313
|
* Uses only `key`/`bot`, never the request `ctx`, so it survives past the
|
|
@@ -9401,7 +10377,7 @@ async function processVoiceJob(key, fileId, durationSeconds, requesterId, warmed
|
|
|
9401
10377
|
return;
|
|
9402
10378
|
// `/reminders` step 4 accepts a voice note as well as typed text, so the
|
|
9403
10379
|
// transcript is routed here — right after the 🎤 echo and BEFORE the
|
|
9404
|
-
// startup-buffer /
|
|
10380
|
+
// startup-buffer / binding gates, which would
|
|
9405
10381
|
// otherwise treat it as a prompt. Same single creation path as the text side.
|
|
9406
10382
|
// The step is an ADMIN's: a topic member's voice note neither fills it nor closes it when it has expired — it goes on as a prompt.
|
|
9407
10383
|
const reminderVoiceRoute = (0, messageContext_1.checkIsForeignWords)(messageContext) ? null : claimReminderTextCapture(key);
|
|
@@ -9411,41 +10387,12 @@ async function processVoiceJob(key, fileId, durationSeconds, requesterId, warmed
|
|
|
9411
10387
|
}
|
|
9412
10388
|
if (reminderVoiceRoute === 'expired')
|
|
9413
10389
|
await expireReminderWizard(key);
|
|
9414
|
-
// Session is mid-startup → buffer the transcript and replay it once ready
|
|
9415
|
-
|
|
9416
|
-
|
|
10390
|
+
// Session is mid-startup → buffer the transcript and replay it once ready; a command ends or replaces the conversation → refused at
|
|
10391
|
+
// the write (review 25 #1: a transcript is ready seconds after its voice note, often while a move or a release runs).
|
|
10392
|
+
if (checkIsArrivalRoutedAtWrite(key)) {
|
|
10393
|
+
await deliverPromptDuringStartup(key, transcript, { source: 'voice', requesterId }, messageContext);
|
|
9417
10394
|
return;
|
|
9418
10395
|
}
|
|
9419
|
-
// A FORWARDED voice note saying «Claude», or a topic member's, is somebody else's words, not the operator's order to start an agent.
|
|
9420
|
-
if (!(0, messageContext_1.checkIsForeignWords)(messageContext) && !(0, createAdapter_1.getThreadAdapter)(key).checkIsActive(key)) {
|
|
9421
|
-
const startMatch = (0, agentTrigger_1.parseAgentTrigger)(transcript);
|
|
9422
|
-
if (startMatch.isMatch && startMatch.adapterName) {
|
|
9423
|
-
if (checkIsGeneral(key)) {
|
|
9424
|
-
await replyToThread(key, (0, i18n_1.t)('error.start_in_general'));
|
|
9425
|
-
return;
|
|
9426
|
-
}
|
|
9427
|
-
const requestedFamily = (0, backendSwitchPlan_1.getBackendFamily)(startMatch.adapterName);
|
|
9428
|
-
if (requestedFamily !== null && state.getBinding(key) && await askBeforeCrossBackendSwitch(key, requestedFamily, startMatch.args))
|
|
9429
|
-
return;
|
|
9430
|
-
// Same choke point as the text trigger (L-D4): a sleeping conversation is
|
|
9431
|
-
// woken, never replaced by a fresh start; `unbound` keeps the folder picker.
|
|
9432
|
-
const result = await ensureAgentSession(key, {
|
|
9433
|
-
preferredAdapterName: (0, createAdapter_1.resolveStartAdapterName)(key, startMatch.adapterName),
|
|
9434
|
-
args: startMatch.args,
|
|
9435
|
-
});
|
|
9436
|
-
if (!result.ok && result.reason === 'unbound') {
|
|
9437
|
-
const subdirs = listAvailableSubdirs(ENV.workRoot);
|
|
9438
|
-
const extra = (0, bindPicker_1.buildBindKeyboard)(subdirs, 0, bindPicker_1.BIND_PAGE_SIZE, !!state.getBinding(key));
|
|
9439
|
-
await replyToThread(key, (0, i18n_1.t)('thread.no_binding'), extra);
|
|
9440
|
-
return;
|
|
9441
|
-
}
|
|
9442
|
-
// Empty for a self-greeting agent (Claude self-announces) — the typing
|
|
9443
|
-
// loader covers the gap; show a notice only when there's ready text.
|
|
9444
|
-
if (result.message)
|
|
9445
|
-
await replyToThread(key, result.message);
|
|
9446
|
-
return;
|
|
9447
|
-
}
|
|
9448
|
-
}
|
|
9449
10396
|
// A voice prompt wakes a sleeping conversation like a text one does (L-D4).
|
|
9450
10397
|
if (!(0, createAdapter_1.getThreadAdapter)(key).checkIsActive(key) && !(await resumeSleepingSessionForPrompt(key))) {
|
|
9451
10398
|
await sendNoAgentGuidance(key, messageContext?.nonOperatorSender !== undefined, (text, extra) => replyToThread(key, text, extra));
|
|
@@ -9522,9 +10469,13 @@ async function sendNoAgentGuidance(key, isFromTalker, sendHint) {
|
|
|
9522
10469
|
* album path can dedupe it to once-per-album; the single-file path passes
|
|
9523
10470
|
* `replyToThread` verbatim.
|
|
9524
10471
|
*/
|
|
9525
|
-
async function checkFileIntakeGatePassed(key,
|
|
9526
|
-
|
|
9527
|
-
if (
|
|
10472
|
+
async function checkFileIntakeGatePassed(key, sendHint, isFromTalker) {
|
|
10473
|
+
// A command ends or replaces the conversation: the file is not delivered, and nothing is downloaded for it (review 25 #1).
|
|
10474
|
+
if (conversationEndings.checkIsRefusingMessages((0, sessionKey_1.keyToString)(key))) {
|
|
10475
|
+
await sendHint((0, i18n_1.t)('agent.queued_prompt_dropped_by_command'));
|
|
10476
|
+
return false;
|
|
10477
|
+
}
|
|
10478
|
+
if (startupPromptBuffer.checkIsStarting((0, sessionKey_1.keyToString)(key)) || (0, createAdapter_1.getThreadAdapter)(key).checkIsActive(key))
|
|
9528
10479
|
return true;
|
|
9529
10480
|
// A file sent to a sleeping conversation wakes it (L-D4) and is taken in by the resumed session.
|
|
9530
10481
|
if (await resumeSleepingSessionForPrompt(key, sendHint))
|
|
@@ -9583,31 +10534,57 @@ async function downloadIncomingFile(ctx, key, meta, onError) {
|
|
|
9583
10534
|
}
|
|
9584
10535
|
}
|
|
9585
10536
|
/**
|
|
9586
|
-
* @description Deliver one already-built prompt to the thread's agent,
|
|
9587
|
-
*
|
|
9588
|
-
*
|
|
9589
|
-
*
|
|
9590
|
-
*
|
|
9591
|
-
*
|
|
9592
|
-
* startup-window handling never drifts between them.
|
|
10537
|
+
* @description Deliver one already-built prompt to the thread's agent, routed at the moment of the write
|
|
10538
|
+
* (`utils/promptDelivery.ts`): behind an open start or stop window it is buffered, into a live session it is forwarded through the
|
|
10539
|
+
* normal choke point, and a conversation with neither is woken first. The single "buffer-or-forward" unit of every prompt that may
|
|
10540
|
+
* meet a start or a stop — the person's prompts through {@link deliverPromptByState}'s buffer step, a scheduled run, the Jira
|
|
10541
|
+
* connector's posts, the lost-work post, an API-error retry's "continue" nudge and a move's first prompt — so the window handling
|
|
10542
|
+
* never drifts between them, and no caller hands it a state it read before an await.
|
|
9593
10543
|
*/
|
|
9594
10544
|
const promptDeliveryDeps = {
|
|
9595
10545
|
startupBuffer: startupPromptBuffer,
|
|
9596
|
-
forwardPrompt: (key, text, options) => forwardPromptToAgent(key, (0, createAdapter_1.getThreadAdapter)(key), text, undefined, { isPersonInput: options.isPersonInput }),
|
|
10546
|
+
forwardPrompt: (key, text, options) => forwardPromptToAgent(key, (0, createAdapter_1.getThreadAdapter)(key), text, undefined, { isPersonInput: options.isPersonInput, isAccountsNoteCarrier: options.isAccountsNoteCarrier, lostWorkTelling: options.lostWorkTelling, waitBeforeRoute: options.waitBeforeRoute }),
|
|
10547
|
+
checkIsSessionActive: (key) => checkIsAcceptingInput(key),
|
|
10548
|
+
// A tracker conversation has no topic to say a resume's notice in: it is logged.
|
|
10549
|
+
wakeSession: (key) => ((0, sessionKeyCodec_1.checkIsTelegramKey)(key)
|
|
10550
|
+
? wakeSleepingSessionForPrompt(key)
|
|
10551
|
+
: wakeSleepingSessionForPrompt(key, async (notice) => { console.log(`[promptDelivery] ${(0, sessionKey_1.keyToString)(key)}: ${notice}`); })),
|
|
10552
|
+
checkIsRefusingMessages: (key) => conversationEndings.checkIsRefusingMessages((0, sessionKey_1.keyToString)(key)),
|
|
10553
|
+
reportNoSession: async (key, isAlreadyTold, options) => {
|
|
10554
|
+
console.warn(`[promptDelivery] ${(0, sessionKey_1.keyToString)(key)}: no session is left to take the prompt, and nothing could be woken for it`);
|
|
10555
|
+
// Only a person's own prompt is theirs to be told about; what the bot made says so in its own way (its caller reads `noSession`).
|
|
10556
|
+
if (options.isPersonInput === true && !isAlreadyTold)
|
|
10557
|
+
await replyToThread(key, (0, i18n_1.t)('agent.no_session'));
|
|
10558
|
+
},
|
|
10559
|
+
reportRefused: async (key, options) => {
|
|
10560
|
+
console.warn(`[promptDelivery] ${(0, sessionKey_1.keyToString)(key)}: a command ends or replaces the conversation; the prompt is not delivered`);
|
|
10561
|
+
if (options.isPersonInput === true)
|
|
10562
|
+
await replyToThread(key, (0, i18n_1.t)('agent.queued_prompt_dropped_by_command'));
|
|
10563
|
+
},
|
|
9597
10564
|
announceQueued: async (key) => {
|
|
9598
10565
|
await replyToThread(key, (0, i18n_1.t)('agent.queued_starting', { label: (0, createAdapter_1.getThreadAdapter)(key).label }));
|
|
9599
10566
|
},
|
|
9600
10567
|
};
|
|
9601
|
-
|
|
9602
|
-
|
|
10568
|
+
/**
|
|
10569
|
+
* @description Whether a prompt written now reaches `key`'s live process (`AgentAdapter.checkIsAcceptingInput`, else `checkIsActive`): a
|
|
10570
|
+
* process a release or a move is stopping opens no window, and a prompt written into it is abandoned while its request reads it as
|
|
10571
|
+
* written — routed as no live session, it wakes the conversation, whose ensure waits behind that stop (review 24 nit 3).
|
|
10572
|
+
*/
|
|
10573
|
+
function checkIsAcceptingInput(key) {
|
|
10574
|
+
const adapter = (0, createAdapter_1.getThreadAdapter)(key);
|
|
10575
|
+
return adapter.checkIsAcceptingInput?.(key) ?? adapter.checkIsActive(key);
|
|
10576
|
+
}
|
|
10577
|
+
function deliverPromptOrBuffer(key, promptText, onBufferedSettled, options = {}) {
|
|
10578
|
+
return (0, promptDelivery_1.deliverPromptOrBuffer)(promptDeliveryDeps, key, promptText, onBufferedSettled, options);
|
|
9603
10579
|
}
|
|
9604
10580
|
/**
|
|
9605
10581
|
* @description Per-(thread, media_group) album batcher. Telegram delivers an
|
|
9606
10582
|
* album as N messages sharing `media_group_id` in a quick burst; this coalesces
|
|
9607
10583
|
* them so the agent gets ONE combined prompt after the burst settles, and gating
|
|
9608
|
-
* / error hints fire once per album. The flush
|
|
9609
|
-
* through {@link
|
|
9610
|
-
* so a session that finished booting mid-burst
|
|
10584
|
+
* / error hints fire once per album. The flush delivers the combined prompt
|
|
10585
|
+
* through {@link deliverPromptByState}, routed at its write — after the flush's
|
|
10586
|
+
* request is opened — so a session that finished booting (or stopping) mid-burst
|
|
10587
|
+
* takes it the way it stands then.
|
|
9611
10588
|
*/
|
|
9612
10589
|
const albumCollector = (0, mediaGroupCollector_1.createMediaGroupCollector)({
|
|
9613
10590
|
debounceMs: ALBUM_DEBOUNCE_MS,
|
|
@@ -9623,17 +10600,13 @@ const albumCollector = (0, mediaGroupCollector_1.createMediaGroupCollector)({
|
|
|
9623
10600
|
const caption = orderedItems.find((item) => item.caption && item.caption.trim())?.caption;
|
|
9624
10601
|
const messageContext = orderedItems.find((item) => item.messageContext)?.messageContext;
|
|
9625
10602
|
const promptText = (0, fileIntake_1.buildAlbumPromptText)(files, caption);
|
|
9626
|
-
const isStarting = startupPromptBuffer.checkIsStarting((0, sessionKey_1.keyToString)(key));
|
|
9627
10603
|
// User took over (album upload) before a pending API-error retry fired →
|
|
9628
10604
|
// cancel it silently, like the text/voice handlers.
|
|
9629
10605
|
cancelApiRetry(key);
|
|
9630
|
-
// A user album is genuine user activity
|
|
10606
|
+
// A user album is genuine user activity: the idle countdown restarts.
|
|
9631
10607
|
notePersonActivity(key);
|
|
9632
10608
|
try {
|
|
9633
|
-
|
|
9634
|
-
const quotedPrompt = getPromptWithThreadMessageContext(key, promptText, messageContext);
|
|
9635
|
-
const delivery = await deliverPromptOrBuffer(key, `${opening.header}${quotedPrompt}`, isStarting, undefined, { isPersonInput: true });
|
|
9636
|
-
await settleTopicRequestAfterDelivery(key, opening, delivery);
|
|
10609
|
+
await deliverPromptByState(key, promptText, { source: 'album', requesterId: orderedItems[0].requesterId }, undefined, messageContext);
|
|
9637
10610
|
}
|
|
9638
10611
|
catch (err) {
|
|
9639
10612
|
// The files were downloaded already (each item before the flush): what failed is the album's prompt.
|
|
@@ -9663,10 +10636,9 @@ function parseAlbumGroupKey(groupKey) {
|
|
|
9663
10636
|
*/
|
|
9664
10637
|
async function handleAlbumFile(ctx, key, meta, mediaGroupId, isFromTalker) {
|
|
9665
10638
|
const groupKey = buildAlbumGroupKey(key, mediaGroupId);
|
|
9666
|
-
const isStarting = startupPromptBuffer.checkIsStarting((0, sessionKey_1.keyToString)(key));
|
|
9667
10639
|
// Gate per item, but reply at most once per album. The guard is claimed
|
|
9668
10640
|
// lazily so a passing gate never burns the one-shot slot.
|
|
9669
|
-
const gatePassed = await checkFileIntakeGatePassed(key,
|
|
10641
|
+
const gatePassed = await checkFileIntakeGatePassed(key, async (text, extra) => {
|
|
9670
10642
|
if (albumCollector.checkShouldAnnounceOnce(groupKey)) {
|
|
9671
10643
|
await replyToThread(key, text, extra);
|
|
9672
10644
|
}
|
|
@@ -9701,8 +10673,7 @@ async function handleIncomingFile(ctx, key, isFromTalker) {
|
|
|
9701
10673
|
await handleAlbumFile(ctx, key, meta, mediaGroupId, isFromTalker);
|
|
9702
10674
|
return;
|
|
9703
10675
|
}
|
|
9704
|
-
const
|
|
9705
|
-
const gatePassed = await checkFileIntakeGatePassed(key, isStarting, (text, extra) => replyToThread(key, text, extra), isFromTalker);
|
|
10676
|
+
const gatePassed = await checkFileIntakeGatePassed(key, (text, extra) => replyToThread(key, text, extra), isFromTalker);
|
|
9706
10677
|
if (!gatePassed)
|
|
9707
10678
|
return;
|
|
9708
10679
|
const savedPath = await downloadIncomingFile(ctx, key, meta, (text) => replyToThread(key, text));
|
|
@@ -9712,14 +10683,11 @@ async function handleIncomingFile(ctx, key, isFromTalker) {
|
|
|
9712
10683
|
// User took over (file upload) before a pending API-error retry fired →
|
|
9713
10684
|
// cancel it silently, like the text/voice handlers.
|
|
9714
10685
|
cancelApiRetry(key);
|
|
9715
|
-
// A user file is genuine user activity
|
|
10686
|
+
// A user file is genuine user activity: the idle countdown restarts.
|
|
9716
10687
|
notePersonActivity(key);
|
|
9717
10688
|
// A file sent as a REPLY carries the message it answers, a forwarded one its origin, as a typed or spoken message does.
|
|
9718
10689
|
const messageContext = getMessageContext(key, ctx.message);
|
|
9719
|
-
|
|
9720
|
-
const quotedPrompt = getPromptWithThreadMessageContext(key, promptText, messageContext);
|
|
9721
|
-
const delivery = await deliverPromptOrBuffer(key, `${opening.header}${quotedPrompt}`, isStarting, undefined, { isPersonInput: true });
|
|
9722
|
-
await settleTopicRequestAfterDelivery(key, opening, delivery);
|
|
10690
|
+
await deliverPromptByState(key, promptText, { source: 'file', requesterId: (0, topicRequest_1.getTopicRequesterId)(ctx.from) }, undefined, messageContext);
|
|
9723
10691
|
}
|
|
9724
10692
|
bot.on(
|
|
9725
10693
|
// anyOf-composed per-kind filter — `message('photo', 'document', …)` would
|
|
@@ -9763,34 +10731,36 @@ bot.on('edited_message', async (ctx) => {
|
|
|
9763
10731
|
// my_chat_member — auto-welcome when the bot is added to the group (§20.2)
|
|
9764
10732
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
9765
10733
|
/**
|
|
9766
|
-
* @description Detect when *this* bot
|
|
9767
|
-
* post
|
|
10734
|
+
* @description Detect when *this* bot JOINS the configured group and
|
|
10735
|
+
* post the greeting into General (`formatGroupWelcome`: what the bot is, the
|
|
10736
|
+
* version that runs, the setup steps). Without this, a fresh deployment is
|
|
9768
10737
|
* silent: the user adds the bot, sees nothing, and has to dig through the
|
|
9769
|
-
* README to find out what
|
|
10738
|
+
* README to find out what rights the bot needs.
|
|
9770
10739
|
*
|
|
9771
10740
|
* Filters:
|
|
9772
10741
|
* - chat must be the allowlisted group (we don't react in foreign chats),
|
|
9773
10742
|
* - the member that changed must be us (other admins being promoted etc.
|
|
9774
10743
|
* are not interesting),
|
|
9775
|
-
* -
|
|
9776
|
-
*
|
|
10744
|
+
* - the change must be a join (`checkHasJoinedGroup`): out of the group
|
|
10745
|
+
* before, a member or an administrator now. The greeting's own steps —
|
|
10746
|
+
* make the bot an admin, add a right `/doctor` asked for — are
|
|
10747
|
+
* `my_chat_member` changes too, and must not bring it back.
|
|
9777
10748
|
*/
|
|
9778
10749
|
bot.on('my_chat_member', async (ctx) => {
|
|
9779
10750
|
const chat = ctx.chat;
|
|
9780
10751
|
if (!chat || chat.id !== getAllowedGroupId())
|
|
9781
10752
|
return;
|
|
9782
10753
|
const upd = ctx.update.my_chat_member;
|
|
9783
|
-
const newMember = upd.new_chat_member;
|
|
9784
10754
|
const botId = bot.botInfo?.id;
|
|
9785
|
-
if (!botId ||
|
|
10755
|
+
if (!botId || upd.new_chat_member.user.id !== botId)
|
|
9786
10756
|
return;
|
|
9787
|
-
if (
|
|
10757
|
+
if (!(0, inbound_1.checkHasJoinedGroup)(upd.old_chat_member, upd.new_chat_member))
|
|
9788
10758
|
return;
|
|
9789
10759
|
// We don't know which message_thread_id General actually has on this
|
|
9790
10760
|
// group (it can be 1, or undefined for non-forum chats). For a forum
|
|
9791
10761
|
// supergroup it's always the constant `GENERAL_THREAD_ID = 1`.
|
|
9792
10762
|
const generalKey = (0, sessionKeyCodec_1.makeTelegramKey)(chat.id, threadRouting_1.GENERAL_THREAD_ID);
|
|
9793
|
-
await replyToThread(generalKey, (0,
|
|
10763
|
+
await replyToThread(generalKey, (0, groupWelcome_1.formatGroupWelcome)(i18n_1.t, { workRoot: ENV.workRoot }), { parse_mode: 'Markdown' });
|
|
9794
10764
|
});
|
|
9795
10765
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
9796
10766
|
// chat_member — admin promotion/demotion invalidates the admin cache
|
|
@@ -9911,7 +10881,7 @@ bot.on((0, filters_1.message)('forum_topic_edited'), async (ctx) => {
|
|
|
9911
10881
|
// 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
10882
|
// stranger's (a `[security]` line) — only a line to delete, so the topic shows no trace of the change.
|
|
9913
10883
|
if (userId !== undefined && userId === bot.botInfo?.id) {
|
|
9914
|
-
await topicIndicator.handleOwnRenameLine(key, ctx.message.message_id);
|
|
10884
|
+
await topicIndicator.handleOwnRenameLine(key, ctx.message.message_id, newName);
|
|
9915
10885
|
return;
|
|
9916
10886
|
}
|
|
9917
10887
|
if (!userId || !(await checkIsAllowedUser(ctx))) {
|
|
@@ -9964,7 +10934,7 @@ async function applyRenamesThatWaitedForColdStart() {
|
|
|
9964
10934
|
continue;
|
|
9965
10935
|
const senderId = renamed.from?.id;
|
|
9966
10936
|
if (senderId !== undefined && senderId === botUserId) {
|
|
9967
|
-
await topicIndicator.handleOwnRenameLine(key, renamed.message_id);
|
|
10937
|
+
await topicIndicator.handleOwnRenameLine(key, renamed.message_id, renamed.forum_topic_edited.name);
|
|
9968
10938
|
continue;
|
|
9969
10939
|
}
|
|
9970
10940
|
if (!state.getBinding(key))
|
|
@@ -10112,8 +11082,16 @@ bot.action(bindPicker_1.bindLeaveCurrentCallback, async (ctx) => {
|
|
|
10112
11082
|
// Claimed like a bind: two taps in a row unbind once, and a picker a bind holds is no more a place to leave from.
|
|
10113
11083
|
const pickerMessageId = (0, callbackMessage_1.getCallbackMessageId)(ctx);
|
|
10114
11084
|
const run = await bindPickerClaims.runClaimed(key, pickerMessageId, async () => {
|
|
10115
|
-
|
|
10116
|
-
|
|
11085
|
+
// Leaving the folder ends the conversation, known at the tap: held from here, ahead of the toast and the leave's paced sends, so a stop
|
|
11086
|
+
// under way drops what it held instead of resuming the conversation for it in the folder being left (review 24 #1).
|
|
11087
|
+
const ending = conversationEndings.hold(key);
|
|
11088
|
+
try {
|
|
11089
|
+
await (0, callbackToast_1.answerCallbackQuerySafely)(ctx);
|
|
11090
|
+
await unbindThread(key, ending);
|
|
11091
|
+
}
|
|
11092
|
+
finally {
|
|
11093
|
+
ending.release();
|
|
11094
|
+
}
|
|
10117
11095
|
if (pickerMessageId !== null)
|
|
10118
11096
|
await removeBindPicker(key, pickerMessageId);
|
|
10119
11097
|
await closeOpenBindMessages(key);
|
|
@@ -10296,6 +11274,7 @@ registerCompactionCallbacks();
|
|
|
10296
11274
|
registerQuestionSetAsideCallbacks(bot);
|
|
10297
11275
|
registerAutoContinueLimitsCallbacks();
|
|
10298
11276
|
registerBotSkillsCallbacks();
|
|
11277
|
+
registerWorkerRolesCallbacks();
|
|
10299
11278
|
registerQuestionWaitCallbacks();
|
|
10300
11279
|
registerTopicStatusCallbacks();
|
|
10301
11280
|
registerTopicAccessCallbacks();
|
|
@@ -10305,6 +11284,7 @@ registerBackendSwitchCallbacks();
|
|
|
10305
11284
|
registerClaudeAccountCallbacks();
|
|
10306
11285
|
registerFallbackChainCallbacks();
|
|
10307
11286
|
registerLimitsBoardCallbacks();
|
|
11287
|
+
registerLimitRemindersCallbacks();
|
|
10308
11288
|
registerTodoCallbacks();
|
|
10309
11289
|
registerSttCallbacks();
|
|
10310
11290
|
registerSelfUpdateCallbacks();
|
|
@@ -10376,12 +11356,21 @@ bot.action(/^agent_(.+)$/, async (ctx) => {
|
|
|
10376
11356
|
// Resolve up-front so an unknown name throws into the catch (→ "unknown
|
|
10377
11357
|
// agent") before any side effect, and so the toast can name the label.
|
|
10378
11358
|
const adapter = (0, createAdapter_1.getAdapter)(adapterName);
|
|
10379
|
-
|
|
10380
|
-
//
|
|
10381
|
-
|
|
10382
|
-
|
|
10383
|
-
|
|
10384
|
-
|
|
11359
|
+
// A tap onto a shell from an agent's conversation ends it, known now: held ahead of the toast, so a stop under way drops what it held
|
|
11360
|
+
// instead of resuming the conversation for it (review 24, own pass). Onto the other agent the hand-over read decides first.
|
|
11361
|
+
const startAdapterName = (0, createAdapter_1.resolveStartAdapterName)(key, adapterName);
|
|
11362
|
+
const ending = (0, backendSwitchPlan_1.getBackendFamily)(startAdapterName) === null && checkIsStartLeavingConversation(key, startAdapterName) ? conversationEndings.hold(key) : undefined;
|
|
11363
|
+
try {
|
|
11364
|
+
await ctx.answerCbQuery((0, i18n_1.t)('cb.agent_switched', { label: adapter.label }));
|
|
11365
|
+
// One-tap start: switch + start the agent (was select-only — the user then
|
|
11366
|
+
// had to type /claude). `handleAgentStart` owns the General / binding /
|
|
11367
|
+
// already-active guards and the self-greeting ready-text suppression, and
|
|
11368
|
+
// `switchThreadAdapter` inside it persists the adapter choice.
|
|
11369
|
+
await handleAgentStart(key, adapterName, undefined, ending);
|
|
11370
|
+
}
|
|
11371
|
+
finally {
|
|
11372
|
+
ending?.release();
|
|
11373
|
+
}
|
|
10385
11374
|
if (state.getBinding(key)) {
|
|
10386
11375
|
await updatePinnedStatus(key).catch(() => { });
|
|
10387
11376
|
}
|
|
@@ -10408,15 +11397,23 @@ bot.action(/^resume_(\d+)$/, async (ctx) => {
|
|
|
10408
11397
|
await ctx.answerCbQuery((0, i18n_1.t)('cb.access_denied'));
|
|
10409
11398
|
return;
|
|
10410
11399
|
}
|
|
10411
|
-
await ctx.answerCbQuery();
|
|
10412
11400
|
const idx = Number(ctx.match[1]);
|
|
10413
|
-
//
|
|
10414
|
-
|
|
10415
|
-
const
|
|
10416
|
-
|
|
10417
|
-
|
|
10418
|
-
|
|
10419
|
-
|
|
11401
|
+
// The pick replaces the conversation, known at the tap: held ahead of the toast, so a stop under way drops what it held instead of
|
|
11402
|
+
// resuming the conversation the pick leaves (review 24 #1). A row the list no longer has replaces nothing.
|
|
11403
|
+
const ending = getListedSessionId(key, idx) === null ? undefined : conversationEndings.hold(key);
|
|
11404
|
+
try {
|
|
11405
|
+
await ctx.answerCbQuery();
|
|
11406
|
+
// A pick from the button also closes pick-mode (mirrors a digit reply).
|
|
11407
|
+
awaitingSessionSelection.delete((0, sessionKey_1.keyToString)(key));
|
|
11408
|
+
const result = await resumeSessionByIndex(key, idx, async () => {
|
|
11409
|
+
await replyToThread(key, (0, i18n_1.t)('session.expired'));
|
|
11410
|
+
}, ending);
|
|
11411
|
+
if (result !== null)
|
|
11412
|
+
await replyToThread(key, result);
|
|
11413
|
+
}
|
|
11414
|
+
finally {
|
|
11415
|
+
ending?.release();
|
|
11416
|
+
}
|
|
10420
11417
|
});
|
|
10421
11418
|
// The agent's own question buttons (`qa_`, and `reask_` in the compaction module) are the taps a talker may make: they answer the
|
|
10422
11419
|
// agent, so they ask the speaker gate; every other button — `opt_`, which types a digit into whatever a Claude TUI shows, included —
|
|
@@ -10492,14 +11489,26 @@ bot.action(/^qa_(\d+)_(\d+)$/, async (ctx) => {
|
|
|
10492
11489
|
}
|
|
10493
11490
|
});
|
|
10494
11491
|
/**
|
|
10495
|
-
* @description
|
|
10496
|
-
*
|
|
10497
|
-
*
|
|
10498
|
-
*
|
|
10499
|
-
*
|
|
10500
|
-
* otherwise reach the agent without the message it points at, or as the operator's own words.
|
|
11492
|
+
* @description Whether a person's text or voice note that arrives now takes {@link deliverPromptDuringStartup}'s route — routed only at
|
|
11493
|
+
* its write — rather than the live-agent route or the no-agent guidance: the session is starting or being stopped (its window open), or a
|
|
11494
|
+
* command ends or replaces the conversation (`ConversationEndings.checkIsRefusingMessages`: the write refuses it, its request closed and
|
|
11495
|
+
* the person told — never written into the agent the command ends, never «Run /claude or /opencode» while a move starts the next one,
|
|
11496
|
+
* review 25 #1).
|
|
10501
11497
|
*/
|
|
10502
|
-
|
|
11498
|
+
function checkIsArrivalRoutedAtWrite(key) {
|
|
11499
|
+
const conversationKey = (0, sessionKey_1.keyToString)(key);
|
|
11500
|
+
return startupPromptBuffer.checkIsStarting(conversationKey) || conversationEndings.checkIsRefusingMessages(conversationKey);
|
|
11501
|
+
}
|
|
11502
|
+
/**
|
|
11503
|
+
* @description Deliver a free-form prompt (text OR voice) that ARRIVED while the thread's session is starting or being stopped, or while a
|
|
11504
|
+
* command ends or replaces the conversation ({@link checkIsArrivalRoutedAtWrite}) — the startup twin of {@link deliverActivePrompt}: no
|
|
11505
|
+
* pending question or wedged turn is looked at (a session in its window has none to answer). The window it arrived in only chose this
|
|
11506
|
+
* route: the prompt itself is routed by {@link deliverPromptByState} when it is written, after its request was opened, so a window that
|
|
11507
|
+
* closed meanwhile never keeps it — it goes to the session that window brought up, or wakes the one its stop left asleep — and a command
|
|
11508
|
+
* still running then refuses it. A buffered prompt carries its request's header and its message-context block
|
|
11509
|
+
* (`deliverPersonPromptAtWrite`), since the replay forwards the buffered text as is.
|
|
11510
|
+
*/
|
|
11511
|
+
async function deliverPromptDuringStartup(key, text, intake, messageContext) {
|
|
10503
11512
|
// The same for a bare option number typed in that window: it answers the question asked again. A FORWARDED "1" is somebody
|
|
10504
11513
|
// else's words, not the operator's pick: it is delivered, marked, like any other message. A topic member's number DOES
|
|
10505
11514
|
// answer — the one thing foreign words may do here: members answer the agent's questions, and only that (every other
|
|
@@ -10507,13 +11516,10 @@ async function bufferPromptDuringStartup(key, text, intake, messageContext) {
|
|
|
10507
11516
|
if (messageContext?.isForwarded !== true && await answerReAskedQuestionByNumber(key, text, messageContext))
|
|
10508
11517
|
return;
|
|
10509
11518
|
// A person wrote, in a window where the session is starting or being stopped: it counts like a message that reaches
|
|
10510
|
-
// `deliverActivePrompt` — the idle
|
|
11519
|
+
// `deliverActivePrompt` — the idle countdown restarts, and a question the idle compaction re-asked is closed (the idle fire
|
|
10511
11520
|
// posts it just before the stop, so this window is where a message instead of a tap most often lands).
|
|
10512
11521
|
notePersonActivity(key);
|
|
10513
|
-
|
|
10514
|
-
const quotedText = getPromptWithThreadMessageContext(key, text, messageContext);
|
|
10515
|
-
await deliverPromptOrBuffer(key, `${opening.header}${quotedText}`, true, undefined, { isPersonInput: true });
|
|
10516
|
-
trackTopicRequestTurn(key, opening);
|
|
11522
|
+
await deliverPromptByState(key, text, intake, undefined, messageContext);
|
|
10517
11523
|
}
|
|
10518
11524
|
/**
|
|
10519
11525
|
* @description The single choke point for delivering a free-form prompt (text OR
|
|
@@ -10543,8 +11549,7 @@ options = {}) {
|
|
|
10543
11549
|
// A bare option number answers the question the idle compaction asked again (a tap's own label comes in with no intake).
|
|
10544
11550
|
if (intake !== null && !isForwarded && await answerReAskedQuestionByNumber(key, text, messageContext))
|
|
10545
11551
|
return null;
|
|
10546
|
-
// A genuine USER message (text or voice) —
|
|
10547
|
-
// the next idle period can compact again (D2), whether it answers a pending
|
|
11552
|
+
// A genuine USER message (text or voice) — the idle countdown restarts, whether it answers a pending
|
|
10548
11553
|
// question or is a fresh prompt.
|
|
10549
11554
|
notePersonActivity(key);
|
|
10550
11555
|
const pending = pendingQuestions.get((0, sessionKey_1.keyToString)(key));
|
|
@@ -10565,9 +11570,7 @@ options = {}) {
|
|
|
10565
11570
|
return null;
|
|
10566
11571
|
}
|
|
10567
11572
|
// Free-form text cancels the question and is a fresh prompt — a request (S7).
|
|
10568
|
-
|
|
10569
|
-
const delivery = await cancelPendingQuestionAndForward(key, adapter, text, sentAtMs, messageContext, opening.header);
|
|
10570
|
-
await settleTopicRequestAfterDelivery(key, opening, delivery);
|
|
11573
|
+
await deliverPersonPromptInRequest(key, text, intake, messageContext, (opening) => cancelPendingQuestionAndForward(key, adapter, text, sentAtMs, messageContext, opening, intake !== null));
|
|
10571
11574
|
return null;
|
|
10572
11575
|
}
|
|
10573
11576
|
// A bare `/clear` forwarded to the agent wipes its context (Claude TUI), so
|
|
@@ -10591,38 +11594,140 @@ options = {}) {
|
|
|
10591
11594
|
adapter.sendSignal(key, 'SIGINT');
|
|
10592
11595
|
await replyToThread(key, (0, i18n_1.t)('agent.question_cancelled_for_prompt'));
|
|
10593
11596
|
}
|
|
10594
|
-
return deliverPromptByState(key,
|
|
11597
|
+
return deliverPromptByState(key, text, intake, sentAtMs, messageContext);
|
|
10595
11598
|
}
|
|
10596
11599
|
/**
|
|
10597
|
-
* @description The
|
|
10598
|
-
*
|
|
10599
|
-
*
|
|
10600
|
-
* the request. It touches no pending question and no wedged turn: that is the
|
|
11600
|
+
* @description The ONE way a person's prompt is delivered — text, voice, a file, an album, `/schedule`, a re-asked question's label, a
|
|
11601
|
+
* late answer (the end of {@link deliverActivePrompt} and {@link deliverPromptDuringStartup}): open the request the prompt belongs to
|
|
11602
|
+
* (none for `intake` null — an answer to the agent's own question is never a request), deliver it by the state of the session at the
|
|
11603
|
+
* write ({@link deliverPersonPromptAtWrite}), and settle the request. It touches no pending question and no wedged turn: that is the
|
|
11604
|
+
* caller's.
|
|
10601
11605
|
*/
|
|
10602
|
-
async function deliverPromptByState(key,
|
|
11606
|
+
async function deliverPromptByState(key, text, intake, sentAtMs, messageContext) {
|
|
10603
11607
|
// The request (S7) is opened AFTER the user takeover cancelled an armed limit
|
|
10604
11608
|
// wait (the handlers' `cancelApiRetry`) and before the forward, so its id is
|
|
10605
11609
|
// durable by the time the agent reads it.
|
|
10606
|
-
|
|
10607
|
-
//
|
|
10608
|
-
|
|
10609
|
-
|
|
10610
|
-
|
|
11610
|
+
// A person's prompt that opens a request starts a turn that may carry the accounts note; the answer to the agent's own question
|
|
11611
|
+
// (`intake` null) is bookkeeping and never does.
|
|
11612
|
+
return deliverPersonPromptInRequest(key, text, intake, messageContext, (opening) => deliverPersonPromptAtWrite(key, text, { opening, sentAtMs, messageContext, isAccountsNoteCarrier: intake !== null }));
|
|
11613
|
+
}
|
|
11614
|
+
/**
|
|
11615
|
+
* The person's prompts on their way to their write, request id → conversation: from the moment the request is created — inside the
|
|
11616
|
+
* create, synchronously with it appearing open — until the prompt's delivery is settled. An ending command's cancel does not tell them:
|
|
11617
|
+
* the prompt's own route tells its person (refused while the command runs, refused once it is over because the command closed its request
|
|
11618
|
+
* — {@link personPromptsEndedInDelivery} —, or with no session), and the command telling it too gave the person the line twice, or a false
|
|
11619
|
+
* one (review 27 #1).
|
|
11620
|
+
*/
|
|
11621
|
+
const personPromptsInDelivery = new Map();
|
|
11622
|
+
/**
|
|
11623
|
+
* The requests of {@link personPromptsInDelivery} an ending command closed (`cancelEndingConversationRequests`, marked at its call): the
|
|
11624
|
+
* prompt is refused at its write even once the command is over, never written into the conversation that follows under a request that is
|
|
11625
|
+
* closed — unwatched, and naming a request its agent cannot answer (review 28 nit 4).
|
|
11626
|
+
*/
|
|
11627
|
+
const personPromptsEndedInDelivery = new Set();
|
|
11628
|
+
/**
|
|
11629
|
+
* @description Open a person's prompt's request (`openTopicRequest`), `deliver` the prompt and settle the request by where it went,
|
|
11630
|
+
* the request marked in delivery ({@link personPromptsInDelivery}) from its creation until the settle is over, on every way out. The one
|
|
11631
|
+
* way a person's prompt that may open a request is delivered: {@link deliverPromptByState} and the free text that cancels a question.
|
|
11632
|
+
*/
|
|
11633
|
+
async function deliverPersonPromptInRequest(key, text, intake, messageContext, deliver) {
|
|
11634
|
+
const marked = { requestId: null };
|
|
11635
|
+
try {
|
|
11636
|
+
const opening = await openTopicRequest(key, text, intake, messageContext, (requestId) => {
|
|
11637
|
+
marked.requestId = requestId;
|
|
11638
|
+
personPromptsInDelivery.set(requestId, (0, sessionKey_1.keyToString)(key));
|
|
11639
|
+
});
|
|
11640
|
+
const outcome = await deliver(opening);
|
|
11641
|
+
await settleTopicRequestAfterDelivery(key, opening, outcome);
|
|
11642
|
+
return outcome;
|
|
11643
|
+
}
|
|
11644
|
+
finally {
|
|
11645
|
+
if (marked.requestId !== null) {
|
|
11646
|
+
personPromptsInDelivery.delete(marked.requestId);
|
|
11647
|
+
personPromptsEndedInDelivery.delete(marked.requestId);
|
|
11648
|
+
}
|
|
11649
|
+
}
|
|
11650
|
+
}
|
|
11651
|
+
/**
|
|
11652
|
+
* @description Whether a person's prompt is refused at its write: a command ends or replaces the conversation now (review 25 #1), or one
|
|
11653
|
+
* closed the prompt's request while it was in delivery — then it is refused once the command is over as well (review 28 nit 4).
|
|
11654
|
+
*/
|
|
11655
|
+
function checkIsPersonPromptRefused(key, requestId) {
|
|
11656
|
+
return conversationEndings.checkIsRefusingMessages((0, sessionKey_1.keyToString)(key)) || (requestId !== null && personPromptsEndedInDelivery.has(requestId));
|
|
11657
|
+
}
|
|
11658
|
+
/**
|
|
11659
|
+
* @description Write a person's prompt by the state of the session NOW (`deliverLatePrompt`), never by one read before an await: the
|
|
11660
|
+
* idle stop or a start may have begun or ended during the caller's awaits (its request opened, a file downloaded, a question
|
|
11661
|
+
* cancelled). A command that ends or replaces the conversation runs → refused, ahead of any window: its request closed, the person told
|
|
11662
|
+
* (review 25 #1); a start's or a stop's window open → buffered behind it, its header and message-context block folded in (the replay
|
|
11663
|
+
* forwards the text as is); a live session → forwarded; neither → the sleeping conversation is woken, then forwarded. A wake that finds
|
|
11664
|
+
* nothing tells the person, unless it said why itself; one that found the conversation ended by a release while it waited says that
|
|
11665
|
+
* (review 25 #2). The forward can itself end in no session — a prompt that waited for an adopt replay found the session gone and nothing
|
|
11666
|
+
* to wake; it has told the person already (`forwardPromptToAgent`).
|
|
11667
|
+
*/
|
|
11668
|
+
function deliverPersonPromptAtWrite(key, text, options) {
|
|
11669
|
+
const { opening, sentAtMs, messageContext, isAccountsNoteCarrier } = options;
|
|
11670
|
+
const { header: requestHeader, requestId } = opening;
|
|
11671
|
+
return (0, promptDelivery_1.deliverLatePrompt)({
|
|
10611
11672
|
checkIsWindowOpen: () => startupPromptBuffer.checkIsStarting((0, sessionKey_1.keyToString)(key)),
|
|
10612
|
-
checkIsSessionActive: () =>
|
|
11673
|
+
checkIsSessionActive: () => checkIsAcceptingInput(key),
|
|
11674
|
+
// A command ends or replaces the conversation, or one closed this prompt's request while it was in delivery: the prompt is not
|
|
11675
|
+
// delivered — read ahead of any window (review 25 #1, review 28 nit 4).
|
|
11676
|
+
checkIsRefused: () => checkIsPersonPromptRefused(key, requestId),
|
|
11677
|
+
// The request closes here, ahead of the line, so a switch closing the conversation's requests meanwhile does not tell it again; the
|
|
11678
|
+
// caller's own close of a `noSession` prompt then finds it closed.
|
|
11679
|
+
reportRefused: () => reportDroppedPersonPrompt(key, requestId, true),
|
|
10613
11680
|
buffer: async () => {
|
|
10614
|
-
|
|
11681
|
+
const bufferedText = `${requestHeader}${getPromptWithThreadMessageContext(key, text, messageContext)}`;
|
|
11682
|
+
await deliverPromptOrBuffer(key, bufferedText, createPersonBufferedSettle(key, requestId), { isPersonInput: true, isAccountsNoteCarrier });
|
|
10615
11683
|
},
|
|
10616
11684
|
wake: () => wakeSleepingSessionForPrompt(key),
|
|
10617
|
-
forward: () => forwardPromptToAgent(key, (0, createAdapter_1.getThreadAdapter)(key), text, sentAtMs, { messageContext, requestHeader
|
|
11685
|
+
forward: () => forwardPromptToAgent(key, (0, createAdapter_1.getThreadAdapter)(key), text, sentAtMs, { messageContext, requestHeader, requestId, isPersonInput: true, isAccountsNoteCarrier }),
|
|
10618
11686
|
reportNoSession: async (isAlreadyTold) => {
|
|
10619
11687
|
if (!isAlreadyTold)
|
|
10620
11688
|
await replyToThread(key, (0, i18n_1.t)('agent.no_session'));
|
|
10621
11689
|
},
|
|
10622
11690
|
});
|
|
10623
|
-
await settleTopicRequestAfterDelivery(key, opening, outcome);
|
|
10624
|
-
return outcome;
|
|
10625
11691
|
}
|
|
11692
|
+
/**
|
|
11693
|
+
* @description The settle of a person's prompt that waits in a startup buffer. One its window's end DROPPED — the start failed, nothing
|
|
11694
|
+
* started after a failed resume, its replay's write threw, a command that ends or replaces the conversation waits behind it — never
|
|
11695
|
+
* reached the agent, and nothing else will post it: the request it opened closes (`cancelled`, like a prompt that found no session; its
|
|
11696
|
+
* watch goes with it) and the person, who was told it is queued, is told why: that the agent was starting, or — read at the drop, while
|
|
11697
|
+
* the command holds the conversation — that the conversation was being ended or switched (review 24 nit 5). Fire and forget: a failure
|
|
11698
|
+
* is logged.
|
|
11699
|
+
*/
|
|
11700
|
+
function createPersonBufferedSettle(key, requestId) {
|
|
11701
|
+
return (outcome) => {
|
|
11702
|
+
if (outcome !== 'dropped')
|
|
11703
|
+
return;
|
|
11704
|
+
const isDroppedForEndingCommand = conversationEndings.checkIsEnding((0, sessionKey_1.keyToString)(key));
|
|
11705
|
+
void withThreadLocale(key, () => reportDroppedPersonPrompt(key, requestId, isDroppedForEndingCommand)).catch((e) => console.error(`[startupPromptBuffer] ${(0, sessionKey_1.keyToString)(key)}: reporting a dropped message failed:`, e));
|
|
11706
|
+
};
|
|
11707
|
+
}
|
|
11708
|
+
/**
|
|
11709
|
+
* @description A person's prompt that never reached the agent — dropped from a window, or refused while a command ends or replaces the
|
|
11710
|
+
* conversation: its request closes and the person is told why. Marked in {@link personDropsBeingTold} from the call (synchronously, in the
|
|
11711
|
+
* drop's own tick) until the request is closed and the line out, so a switch that closes the conversation's requests meanwhile does not
|
|
11712
|
+
* tell the same message again.
|
|
11713
|
+
*/
|
|
11714
|
+
async function reportDroppedPersonPrompt(key, requestId, isDroppedForEndingCommand) {
|
|
11715
|
+
if (requestId !== null)
|
|
11716
|
+
personDropsBeingTold.add(requestId);
|
|
11717
|
+
try {
|
|
11718
|
+
console.warn(`[startupPromptBuffer] ${(0, sessionKey_1.keyToString)(key)}: a message never reached the agent${isDroppedForEndingCommand ? ' (a command ends the conversation)' : ''}; ${requestId ?? 'no request'} is closed`);
|
|
11719
|
+
await settleTopicRequestAfterDelivery(key, { requestId }, 'noSession');
|
|
11720
|
+
await replyToThread(key, isDroppedForEndingCommand
|
|
11721
|
+
? (0, i18n_1.t)('agent.queued_prompt_dropped_by_command')
|
|
11722
|
+
: (0, i18n_1.t)('agent.queued_prompt_dropped', { label: (0, createAdapter_1.getThreadAdapter)(key).label }));
|
|
11723
|
+
}
|
|
11724
|
+
finally {
|
|
11725
|
+
if (requestId !== null)
|
|
11726
|
+
personDropsBeingTold.delete(requestId);
|
|
11727
|
+
}
|
|
11728
|
+
}
|
|
11729
|
+
/** The requests whose person's drop is being told right now ({@link reportDroppedPersonPrompt}): a switch's close tells none of them. */
|
|
11730
|
+
const personDropsBeingTold = new Set();
|
|
10626
11731
|
/**
|
|
10627
11732
|
* @description Deliver a LATE ANSWER to the agent — what the owner chose for a question the bot set aside, worded by
|
|
10628
11733
|
* `buildLateAnswerPrompt` — as a message of the owner's: written to a live session behind whatever it is doing, buffered behind a
|
|
@@ -10636,8 +11741,8 @@ async function deliverLateAnswerPrompt(key, text) {
|
|
|
10636
11741
|
// 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
11742
|
// own «continue» nudge would come on top of the answer later).
|
|
10638
11743
|
cancelApiRetry(key);
|
|
10639
|
-
|
|
10640
|
-
return deliverPromptByState(key,
|
|
11744
|
+
noteThreadActivity(key);
|
|
11745
|
+
return deliverPromptByState(key, text, null);
|
|
10641
11746
|
}
|
|
10642
11747
|
/**
|
|
10643
11748
|
* @description Close the on-screen state of a pending question that ends without an answer: clear the bot's
|
|
@@ -10678,7 +11783,9 @@ function retirePendingQuestionInBackground(key) {
|
|
|
10678
11783
|
* close it on the server, abort the wedged OpenCode turn (`SIGINT` → `/session/:id/
|
|
10679
11784
|
* abort`), post the "previous question cancelled" notice, then forward.
|
|
10680
11785
|
*/
|
|
10681
|
-
async function cancelPendingQuestionAndForward(key, adapter, text, sentAtMs, messageContext,
|
|
11786
|
+
async function cancelPendingQuestionAndForward(key, adapter, text, sentAtMs, messageContext, opening = noTopicRequest,
|
|
11787
|
+
/** The prompt opened a request (a person's free text, not the label of a tap): it may carry the accounts note. */
|
|
11788
|
+
isAccountsNoteCarrier = false) {
|
|
10682
11789
|
// When the question bubble itself was closed with its «not answered» note, that IS the
|
|
10683
11790
|
// cancellation notice — a second standalone "previous question cancelled" line is
|
|
10684
11791
|
// pure noise (the reported triple message). The standalone notice is kept only
|
|
@@ -10697,7 +11804,8 @@ async function cancelPendingQuestionAndForward(key, adapter, text, sentAtMs, mes
|
|
|
10697
11804
|
if (!didLabelQuestionMessage) {
|
|
10698
11805
|
await replyToThread(key, (0, i18n_1.t)('agent.question_cancelled_for_prompt'));
|
|
10699
11806
|
}
|
|
10700
|
-
|
|
11807
|
+
// Routed at the write: the SIGINT ended the turn, and a per-turn topic's stop may have begun (or ended) during the notice.
|
|
11808
|
+
return deliverPersonPromptAtWrite(key, text, { opening, sentAtMs, messageContext, isAccountsNoteCarrier });
|
|
10701
11809
|
}
|
|
10702
11810
|
/**
|
|
10703
11811
|
* @description Record one answer for the CURRENTLY shown OpenCode question and
|
|
@@ -11360,9 +12468,11 @@ function handleAgentToolResult(key, payload) {
|
|
|
11360
12468
|
const action = (0, toolResultRender_1.getToolResultRenderAction)(state.getDisplayPrefs(key).toolResults);
|
|
11361
12469
|
if (action === 'drop')
|
|
11362
12470
|
return;
|
|
12471
|
+
// The accounts note rides the END of a bot send tool's result for the agent only (`limitNotes/noteText.ts`): the topic never shows it.
|
|
12472
|
+
const output = (0, injection_1.checkIsBotMcpToolName)(payload.tool) ? (0, noteText_1.stripLimitNote)(payload.output) : payload.output;
|
|
11363
12473
|
const { text, isTruncated } = action === 'truncated'
|
|
11364
|
-
? (0, toolResultRender_1.getTruncatedToolResult)(
|
|
11365
|
-
: { text:
|
|
12474
|
+
? (0, toolResultRender_1.getTruncatedToolResult)(output)
|
|
12475
|
+
: { text: output, isTruncated: false };
|
|
11366
12476
|
const header = payload.title ? `🔧 ${payload.tool} → ${payload.title}` : `🔧 ${payload.tool} →`;
|
|
11367
12477
|
const footer = isTruncated ? `\n${(0, i18n_1.t)('toolResults.truncated_footer')}` : '';
|
|
11368
12478
|
void sendStandaloneAgentMessage(key, `${header}\n${(0, toolResultRender_1.buildFencedToolResultBody)(text)}${footer}`);
|
|
@@ -11983,6 +13093,8 @@ function handleQuestionGone(key) {
|
|
|
11983
13093
|
void unpinThreadQuestion(key);
|
|
11984
13094
|
}
|
|
11985
13095
|
function handleAgentClosed(key) {
|
|
13096
|
+
// A process that is gone takes no mid-turn accounts note.
|
|
13097
|
+
withdrawAccountsInbox(key);
|
|
11986
13098
|
// What the process held that died with it (its own background work), taken before the cleanup below.
|
|
11987
13099
|
const lostWork = takeLostWorkOf(key);
|
|
11988
13100
|
// Session is gone — the not-yet-sent output gets its ONE final attempt (a 429
|
|
@@ -12071,7 +13183,7 @@ async function noteLostWork(key, lostWork, reason) {
|
|
|
12071
13183
|
planText = 'its open request is woken, and the note rides that wake';
|
|
12072
13184
|
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
13185
|
if (plan.isRequestWake)
|
|
12074
|
-
scheduleTrackerRestartWake(key, `its process ended (${reason}) with its own work pending
|
|
13186
|
+
scheduleTrackerRestartWake(key, `its process ended (${reason}) with its own work pending`, { isLostWork: true });
|
|
12075
13187
|
let linePlan = plan;
|
|
12076
13188
|
if (plan.isAutoResume) {
|
|
12077
13189
|
await state.setLostWorkResumedAt(key, now);
|
|
@@ -12088,7 +13200,7 @@ async function noteLostWork(key, lostWork, reason) {
|
|
|
12088
13200
|
* lost-work path and is never woken here. The lost-work cooldown guards it as well: a conversation woken
|
|
12089
13201
|
* automatically within it is left to the backstop, so a crash loop is no wake loop.
|
|
12090
13202
|
*/
|
|
12091
|
-
function scheduleTrackerRestartWake(key, why) {
|
|
13203
|
+
function scheduleTrackerRestartWake(key, why, options = {}) {
|
|
12092
13204
|
if ((0, sessionKeyCodec_1.checkIsTelegramKey)(key) || !requestWakeUpEngine)
|
|
12093
13205
|
return;
|
|
12094
13206
|
const lastAutoResumeAt = state.getLostWorkResumedAt(key);
|
|
@@ -12096,8 +13208,12 @@ function scheduleTrackerRestartWake(key, why) {
|
|
|
12096
13208
|
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
13209
|
return;
|
|
12098
13210
|
}
|
|
12099
|
-
if (requestWakeUpEngine.scheduleRestartWake(key))
|
|
13211
|
+
if (requestWakeUpEngine.scheduleRestartWake(key, options)) {
|
|
12100
13212
|
console.log(`[requests] ${(0, sessionKey_1.keyToString)(key)}: ${why}; its open request is woken shortly`);
|
|
13213
|
+
return;
|
|
13214
|
+
}
|
|
13215
|
+
// Said, not silent: the caller's own line may have promised a wake (`noteLostWork`).
|
|
13216
|
+
console.log(`[requests] ${(0, sessionKey_1.keyToString)(key)}: ${why}; no wake was scheduled (one is already waiting, or no open request needs it: each is held by a watch that owes nobody an answer, as at a boot)`);
|
|
12101
13217
|
}
|
|
12102
13218
|
/**
|
|
12103
13219
|
* @description The boot's pass over the open requests of tracker conversations: one whose process did not come back
|
|
@@ -12135,22 +13251,27 @@ async function resumeConversationForLostWork(key) {
|
|
|
12135
13251
|
await state.setLostWork(key, (0, lostWork_1.mergeLostWorkRecords)(state.getLostWork(key), record));
|
|
12136
13252
|
return false;
|
|
12137
13253
|
}
|
|
13254
|
+
/** Why a session post failed when its prompt found no session at the write and nothing to wake (`deliverPromptOrBuffer` → `noSession`). */
|
|
13255
|
+
const noSessionForPostError = 'the session went away before the prompt was written, and nothing could be woken for it';
|
|
12138
13256
|
/** The session post of a lost-work note: a bot note to the agent, not a request — no request is opened for it. */
|
|
12139
13257
|
function createLostWorkPostDeps() {
|
|
12140
13258
|
return {
|
|
12141
13259
|
...createSessionPostDeps(),
|
|
12142
13260
|
forwardPrompt: async (conversationKey, text) => {
|
|
12143
13261
|
const buffered = createBufferedOutcome();
|
|
12144
|
-
const delivery = await
|
|
13262
|
+
const delivery = await deliverPostPrompt((0, sessionKey_1.keyFromString)(conversationKey), text, buffered.settle);
|
|
12145
13263
|
if (delivery === 'buffered')
|
|
12146
13264
|
await buffered.assertReplayed();
|
|
13265
|
+
if (delivery === 'noSession')
|
|
13266
|
+
throw new Error(noSessionForPostError);
|
|
12147
13267
|
},
|
|
12148
13268
|
};
|
|
12149
13269
|
}
|
|
12150
13270
|
/**
|
|
12151
13271
|
* @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
|
|
12153
|
-
*
|
|
13272
|
+
* `settle` is the buffer's callback; `getOutcome` resolves with that outcome (`replayed` or `dropped`) for a caller that acts on
|
|
13273
|
+
* either (the scheduler's request a fire opened closes on `dropped`); `assertReplayed` resolves once it was replayed into the session
|
|
13274
|
+
* and rejects when it was dropped — the start failed, or its write did not reach the agent.
|
|
12154
13275
|
*/
|
|
12155
13276
|
function createBufferedOutcome() {
|
|
12156
13277
|
let settle = () => { };
|
|
@@ -12159,12 +13280,15 @@ function createBufferedOutcome() {
|
|
|
12159
13280
|
});
|
|
12160
13281
|
return {
|
|
12161
13282
|
settle: (result) => settle(result),
|
|
13283
|
+
getOutcome: () => outcome,
|
|
12162
13284
|
assertReplayed: async () => {
|
|
12163
13285
|
if ((await outcome) !== 'replayed')
|
|
12164
|
-
throw new Error(
|
|
13286
|
+
throw new Error(bufferedPromptDroppedError);
|
|
12165
13287
|
},
|
|
12166
13288
|
};
|
|
12167
13289
|
}
|
|
13290
|
+
/** Why a post whose prompt waited for a session start failed: the window dropped it. */
|
|
13291
|
+
const bufferedPromptDroppedError = 'the prompt waited for the session to start and never reached the agent';
|
|
12168
13292
|
function handleAgentError(key, error) {
|
|
12169
13293
|
console.error(`[Bot] adapter error ${(0, sessionKey_1.keyToString)(key)}:`, error.message);
|
|
12170
13294
|
topicsStuckUntilNextTurn.add((0, sessionKey_1.keyToString)(key));
|
|
@@ -12194,6 +13318,8 @@ function clearForeignSessionState(key) {
|
|
|
12194
13318
|
* and `openCodeAdapter` (`emit('started', key)`).
|
|
12195
13319
|
*/
|
|
12196
13320
|
function handleAgentStarted(key) {
|
|
13321
|
+
// A note written for the session this one replaces is never taken by the new one.
|
|
13322
|
+
withdrawAccountsInbox(key);
|
|
12197
13323
|
updatePinnedStatus(key).catch(() => { });
|
|
12198
13324
|
// A fresh/adopted session arms the compact-on-idle watchdog (F2); it won't fire
|
|
12199
13325
|
// until a turn produces output AND the topic then sits idle (no catch-up burst).
|
|
@@ -12281,6 +13407,7 @@ function dropLostConversationWatermark(key) {
|
|
|
12281
13407
|
* Posts nothing — `/status` says the agent sleeps.
|
|
12282
13408
|
*/
|
|
12283
13409
|
function handleAgentSuspended(key) {
|
|
13410
|
+
withdrawAccountsInbox(key);
|
|
12284
13411
|
clearGoneProcessFrames(key);
|
|
12285
13412
|
updatePinnedStatus(key).catch(() => { });
|
|
12286
13413
|
// An idle stop takes pending work with it only once the hold ran out.
|
|
@@ -12318,6 +13445,7 @@ exports.COMMANDS_MENU = [
|
|
|
12318
13445
|
{ command: 'compact_summary', description: '📄 Post the compaction summary (toggle)' },
|
|
12319
13446
|
{ command: 'compact_self_review', description: '💡 Agent self-review on compaction: its mistakes and what to change in its instructions' },
|
|
12320
13447
|
{ command: 'bot_skills', description: '🧰 The bot\'s own skills for agents (on/off)' },
|
|
13448
|
+
{ command: 'workers', description: '🛠 Worker models and effort per role' },
|
|
12321
13449
|
{ command: 'question_wait', description: '⏳ How long the agent waits for your answer to its question' },
|
|
12322
13450
|
{ command: 'topic_status', description: '❓ Marks at the end of topic names: question, working, finished, asleep' },
|
|
12323
13451
|
{ command: 'task_agents', description: '🧵 How many tracker task agents work at once' },
|
|
@@ -12325,6 +13453,7 @@ exports.COMMANDS_MENU = [
|
|
|
12325
13453
|
{ command: 'accounts', description: '👤 Claude accounts and OpenCode providers (switch, add, re-login, remove, connect, disconnect)' },
|
|
12326
13454
|
{ command: 'limits', description: '🚧 Usage limits — switch this topic' },
|
|
12327
13455
|
{ command: 'limits_autoswitch', description: '🔁 Automatic switching on a usage limit' },
|
|
13456
|
+
{ command: 'limits_reminders', description: '🔔 How often agents are reminded of the accounts\' limits' },
|
|
12328
13457
|
{ command: 'stt', description: '🎙 Voice recognition: engines, language, local engine' },
|
|
12329
13458
|
{ command: 'update', description: '🔄 Bot updates: automatic, notify only, off' },
|
|
12330
13459
|
{ command: 'schedule', description: '⏰ Schedule a prompt (agent does the work)' },
|
|
@@ -12943,29 +14072,66 @@ function restoreApiRetries() {
|
|
|
12943
14072
|
console.log(`[reattach] api retries: re-armed ${restored}`);
|
|
12944
14073
|
}
|
|
12945
14074
|
/**
|
|
12946
|
-
* @description
|
|
12947
|
-
*
|
|
12948
|
-
*
|
|
12949
|
-
*
|
|
12950
|
-
* log and changes its identity, so a NEW parked error is still recovered.
|
|
14075
|
+
* @description What a json-stream conversation's `stdout.jsonl` says of a limit episode now: the log's identity (ONE stat:
|
|
14076
|
+
* size and mtime describe the same instant) and the error it is parked on, with that error's place in the log
|
|
14077
|
+
* (`findParkedTerminalError` over the tail — never the whole log). `null` when there is no log; `parked` is `null` when the log
|
|
14078
|
+
* is not parked on an error, or its tail could not be read (`tailError` says why).
|
|
12951
14079
|
*/
|
|
12952
|
-
function
|
|
12953
|
-
const agent = state.getAgent(key);
|
|
12954
|
-
if (!agent || !(0, adapterNames_1.checkIsJsonStreamBackend)(agent.name))
|
|
12955
|
-
return;
|
|
12956
|
-
const { stdoutFile } = (0, jsonStreamHost_1.getJsonStreamSessionPaths)((0, jsonStreamHost_1.resolveJsonStreamSessionDir)(getDataDir(), key));
|
|
14080
|
+
function readLimitEpisodeEvidence(stdoutFile) {
|
|
12957
14081
|
let log;
|
|
12958
14082
|
try {
|
|
12959
14083
|
const stat = fs.statSync(stdoutFile);
|
|
12960
14084
|
log = { sizeBytes: stat.size, mtimeMs: stat.mtimeMs };
|
|
12961
14085
|
}
|
|
12962
14086
|
catch {
|
|
12963
|
-
return; // no stdout log for this thread — nothing a boot could recover
|
|
14087
|
+
return null; // no stdout log for this thread — nothing a boot could recover
|
|
14088
|
+
}
|
|
14089
|
+
if (log.sizeBytes === 0)
|
|
14090
|
+
return { log, parked: null };
|
|
14091
|
+
try {
|
|
14092
|
+
const tailStart = Math.max(0, log.sizeBytes - limitEpisodeRecovery_1.limitEpisodeTailMaxBytes);
|
|
14093
|
+
return { log, parked: (0, limitEpisodeRecovery_1.findParkedTerminalError)((0, jsonStreamHost_1.readFileByteRange)(stdoutFile, tailStart, log.sizeBytes), tailStart) };
|
|
12964
14094
|
}
|
|
14095
|
+
catch (tailError) {
|
|
14096
|
+
return { log, parked: null, tailError };
|
|
14097
|
+
}
|
|
14098
|
+
}
|
|
14099
|
+
/**
|
|
14100
|
+
* @description Record a json-stream conversation's parked limit error, as the log holds it now, as an episode already handled
|
|
14101
|
+
* (`limitEpisodesRecovered`, the marker {@link recoverLimitEpisodesFromDisk} checks). A live wait that ends without its resume —
|
|
14102
|
+
* «⏭ Skip once», a give-up, a used-up balance — leaves the error it waited on as the log's last terminal frame, and the next
|
|
14103
|
+
* boot's recovery armed it again: only the recovery itself wrote the marker. The marker names that error's place in the log, so
|
|
14104
|
+
* the frames a later boot appends after it (its `mcp_status` reply) leave it handled, while a NEW parked error is still recovered.
|
|
14105
|
+
*/
|
|
14106
|
+
function markLimitEpisodeSettled(key) {
|
|
14107
|
+
const agent = state.getAgent(key);
|
|
14108
|
+
if (!agent || !(0, adapterNames_1.checkIsJsonStreamBackend)(agent.name))
|
|
14109
|
+
return;
|
|
14110
|
+
const { stdoutFile } = (0, jsonStreamHost_1.getJsonStreamSessionPaths)((0, jsonStreamHost_1.resolveJsonStreamSessionDir)(getDataDir(), key));
|
|
14111
|
+
const evidence = readLimitEpisodeEvidence(stdoutFile);
|
|
14112
|
+
if (evidence === null)
|
|
14113
|
+
return;
|
|
12965
14114
|
void state
|
|
12966
|
-
.setLimitEpisodeRecovered(key, log)
|
|
14115
|
+
.setLimitEpisodeRecovered(key, (0, limitEpisodeRecovery_1.buildLimitEpisodeMarker)(evidence.log, evidence.parked))
|
|
12967
14116
|
.catch((e) => console.error('[limitRecovery] marker persist failed:', e));
|
|
12968
14117
|
}
|
|
14118
|
+
/**
|
|
14119
|
+
* @description What a conversation whose process is STOPPED (a sleeping per-turn session) weighs, read from its Claude transcript by the
|
|
14120
|
+
* session id and work folder the bot persisted — a stopped session has no live adapter state to ask. The idle compaction measures it
|
|
14121
|
+
* at its mark, before it decides to resume the session for a compaction. `null` when there is no session id or folder or no transcript.
|
|
14122
|
+
*/
|
|
14123
|
+
async function readSleepingConversationContext(key, isBaselineNeeded) {
|
|
14124
|
+
const claudeSessionId = state.getAgent(key)?.claudeSessionId;
|
|
14125
|
+
const workDirDecision = getWorkDirStartDecision(key);
|
|
14126
|
+
if (!claudeSessionId || !workDirDecision.ok)
|
|
14127
|
+
return null;
|
|
14128
|
+
const transcriptPath = (0, claudeCliAdapter_1.getClaudeTranscriptPath)(workDirDecision.workDir, claudeSessionId);
|
|
14129
|
+
const [lastContextTokens, firstCallContextTokens] = await Promise.all([
|
|
14130
|
+
(0, claudeRuntimeInfo_1.readClaudeContextUsedTokens)(transcriptPath),
|
|
14131
|
+
isBaselineNeeded ? (0, claudeRuntimeInfo_1.readClaudeFirstCallContextTokens)(transcriptPath) : null,
|
|
14132
|
+
]);
|
|
14133
|
+
return { lastContextTokens, firstCallContextTokens };
|
|
14134
|
+
}
|
|
12969
14135
|
/**
|
|
12970
14136
|
* @description When the parked `errorText` of a json-stream conversation was written, from its Claude transcript's
|
|
12971
14137
|
* API-error entry ({@link readTranscriptErrorWrittenAtMs}); `null` when the transcript tail cannot be read or holds no such
|
|
@@ -13003,11 +14169,20 @@ const limitEpisodesOwnedByRecovery = new Set();
|
|
|
13003
14169
|
* error's own time) resumes at once: the retry plan clamps the negative delay to
|
|
13004
14170
|
* zero, and {@link handleApiError} announces no limit for a window that is over.
|
|
13005
14171
|
*
|
|
13006
|
-
* Each arming STAMPS the
|
|
14172
|
+
* Each arming STAMPS the episode (`state.json` `limitEpisodesRecovered`): the parked
|
|
14173
|
+
* error's place in the log and a stamp of its whole `result` line (`buildLimitEpisodeMarker`), so
|
|
13007
14174
|
* an episode is recovered at most once: «⏭ Skip once», a user takeover and a
|
|
13008
14175
|
* give-up all clear the armed record while leaving the same trailing error in the
|
|
13009
14176
|
* log, and hot mode reloads the bot on every code change — without the stamp each
|
|
13010
|
-
* reload resurrected the settled wait.
|
|
14177
|
+
* reload resurrected the settled wait. The place, not the log's size and mtime:
|
|
14178
|
+
* every boot asks an adopted session for its `mcp_status`, whose reply lands in the
|
|
14179
|
+
* log AFTER this step, so a stamp of the whole log was out of date by the next boot
|
|
14180
|
+
* and each restart re-armed the same parked error.
|
|
14181
|
+
*
|
|
14182
|
+
* The usage poll of this boot runs beside the reattach, so a recovered UNCONFIRMED
|
|
14183
|
+
* wording must not be confirmed by a reading the poll has not re-read or marked stale
|
|
14184
|
+
* yet: a reading older than the error proves nothing about it (`episodeWrittenAtMs`,
|
|
14185
|
+
* {@link handleUnconfirmedLimit}) — it is probed, and the probe's repeat confirms it.
|
|
13011
14186
|
*/
|
|
13012
14187
|
function recoverLimitEpisodesFromDisk() {
|
|
13013
14188
|
const now = Date.now();
|
|
@@ -13025,30 +14200,22 @@ function recoverLimitEpisodesFromDisk() {
|
|
|
13025
14200
|
continue;
|
|
13026
14201
|
const keyStr = (0, sessionKey_1.keyToString)(key);
|
|
13027
14202
|
const { stdoutFile } = (0, jsonStreamHost_1.getJsonStreamSessionPaths)((0, jsonStreamHost_1.resolveJsonStreamSessionDir)(getDataDir(), key));
|
|
13028
|
-
|
|
13029
|
-
|
|
13030
|
-
let log;
|
|
13031
|
-
try {
|
|
13032
|
-
const stat = fs.statSync(stdoutFile);
|
|
13033
|
-
log = { sizeBytes: stat.size, mtimeMs: stat.mtimeMs };
|
|
13034
|
-
}
|
|
13035
|
-
catch {
|
|
14203
|
+
const evidence = readLimitEpisodeEvidence(stdoutFile);
|
|
14204
|
+
if (evidence === null || evidence.log.sizeBytes === 0)
|
|
13036
14205
|
continue; // no stdout log for this thread (yet) — nothing to recover
|
|
13037
|
-
|
|
13038
|
-
|
|
13039
|
-
|
|
13040
|
-
let errorText = null;
|
|
13041
|
-
try {
|
|
13042
|
-
const tail = (0, jsonStreamHost_1.readFileByteRange)(stdoutFile, Math.max(0, log.sizeBytes - limitEpisodeRecovery_1.limitEpisodeTailMaxBytes), log.sizeBytes);
|
|
13043
|
-
errorText = (0, limitEpisodeRecovery_1.getLastTerminalErrorText)(tail.toString('utf8'));
|
|
13044
|
-
}
|
|
13045
|
-
catch (e) {
|
|
13046
|
-
console.warn(`[limitRecovery] ${keyStr}: cannot read stdout tail:`, e instanceof Error ? e.message : e);
|
|
14206
|
+
if (evidence.tailError !== undefined) {
|
|
14207
|
+
const reason = evidence.tailError;
|
|
14208
|
+
console.warn(`[limitRecovery] ${keyStr}: cannot read stdout tail:`, reason instanceof Error ? reason.message : reason);
|
|
13047
14209
|
continue;
|
|
13048
14210
|
}
|
|
14211
|
+
const { log, parked } = evidence;
|
|
14212
|
+
const errorText = parked?.text ?? null;
|
|
14213
|
+
const errorWrittenAtMs = errorText === null ? null : readParkedErrorWrittenAtMs(key, agent.claudeSessionId, errorText);
|
|
13049
14214
|
const decision = (0, limitEpisodeRecovery_1.decideLimitEpisodeRecovery)({
|
|
13050
14215
|
errorText,
|
|
13051
|
-
|
|
14216
|
+
errorEndOffset: parked?.endOffset ?? null,
|
|
14217
|
+
errorStamp: parked?.stamp ?? null,
|
|
14218
|
+
errorWrittenAtMs,
|
|
13052
14219
|
log,
|
|
13053
14220
|
handled: state.getLimitEpisodeRecovered(key),
|
|
13054
14221
|
now,
|
|
@@ -13060,17 +14227,20 @@ function recoverLimitEpisodesFromDisk() {
|
|
|
13060
14227
|
continue;
|
|
13061
14228
|
}
|
|
13062
14229
|
console.log(`[limitRecovery] ${keyStr}: re-arming a limit wait left over from before the restart`);
|
|
13063
|
-
// Stamp the
|
|
13064
|
-
// a
|
|
13065
|
-
// (
|
|
14230
|
+
// Stamp the episode BEFORE arming: this parked error is now handled, so a later boot must not recover it again even
|
|
14231
|
+
// once the armed record is gone («⏭ Skip once», a user takeover, or a give-up all clear it) — nor once frames that are
|
|
14232
|
+
// no turn (this very boot's `mcp_status` reply) land after it: the marker names the error's place, not the log's size.
|
|
13066
14233
|
void state
|
|
13067
|
-
.setLimitEpisodeRecovered(key, log)
|
|
14234
|
+
.setLimitEpisodeRecovered(key, (0, limitEpisodeRecovery_1.buildLimitEpisodeMarker)(log, parked))
|
|
13068
14235
|
.catch(e => console.error('[limitRecovery] marker persist failed:', e));
|
|
13069
14236
|
// This episode is the recovery's alone: the adopt replays the same error once the boot releases its output (after this
|
|
13070
14237
|
// step), and `handleApiError` leaves that copy out until the replay is over.
|
|
13071
14238
|
limitEpisodesOwnedByRecovery.add(keyStr);
|
|
13072
14239
|
void ((0, createAdapter_1.getAdapter)(agent.name).whenAdoptReplayed?.(key) ?? Promise.resolve()).then(() => limitEpisodesOwnedByRecovery.delete(keyStr));
|
|
13073
|
-
|
|
14240
|
+
// A usage reading older than the error proves nothing about it (an unconfirmed wording is probed, not confirmed by it):
|
|
14241
|
+
// this boot's usage poll, started before the reattach, may not have re-read the account or marked its reading stale yet.
|
|
14242
|
+
const episodeWrittenAtMs = errorWrittenAtMs ?? log.mtimeMs;
|
|
14243
|
+
void withThreadLocale(key, () => handleApiError(key, decision.cls, { isRecoveredEpisode: true, episodeWrittenAtMs }));
|
|
13074
14244
|
recovered += 1;
|
|
13075
14245
|
}
|
|
13076
14246
|
if (recovered > 0)
|
|
@@ -13299,8 +14469,11 @@ let connectorConversationHooks = new Map();
|
|
|
13299
14469
|
* {@link clearThreadContextMarker}, which a stop clears too.
|
|
13300
14470
|
*/
|
|
13301
14471
|
function noteConversationContextReset(key, reason) {
|
|
13302
|
-
// A completed compaction or a fresh session: the agent forgot the board too (D20).
|
|
14472
|
+
// A completed compaction or a fresh session: the agent forgot the board too (D20), and the picture of the accounts' limits.
|
|
13303
14473
|
noteTodoFreshContext(key);
|
|
14474
|
+
// The accounts note's inbox first (see `clearThreadContextMarker`): a note the hook took before the compaction is recorded, then forgotten.
|
|
14475
|
+
withdrawAccountsInbox(key);
|
|
14476
|
+
state.clearLimitNoteFingerprint(key);
|
|
13304
14477
|
connectorConversationHooks.get(key.platform)?.onContextReset(key, reason);
|
|
13305
14478
|
}
|
|
13306
14479
|
/**
|
|
@@ -13348,9 +14521,14 @@ async function prepareRequestWakeUpSession(key, message, fallbackAdapterName) {
|
|
|
13348
14521
|
*/
|
|
13349
14522
|
async function forwardRequestWakeUp(key, _request, message) {
|
|
13350
14523
|
// The request's own prompt re-posted (R21) counts as that prompt, not a reminder.
|
|
13351
|
-
await forwardPromptToAgent(key, (0, createAdapter_1.getThreadAdapter)(key), message.text, undefined, {
|
|
14524
|
+
const outcome = await forwardPromptToAgent(key, (0, createAdapter_1.getThreadAdapter)(key), message.text, undefined, {
|
|
13352
14525
|
isRequestReminder: !message.isRequestPrompt,
|
|
14526
|
+
lostWorkTelling: message.isAnswerOptional === true ? 'watchHeld' : 'plain',
|
|
13353
14527
|
});
|
|
14528
|
+
// A wake that waited for an adopted session's replay and then found no session reached no agent: a failed wake (a post retry later,
|
|
14529
|
+
// the backstop for a restart wake, else `wakeFailed`), never a delivered one whose turn the engine would watch (review 21, own pass).
|
|
14530
|
+
if (outcome === 'noSession')
|
|
14531
|
+
throw new Error(noSessionForPostError);
|
|
13354
14532
|
}
|
|
13355
14533
|
/**
|
|
13356
14534
|
* @description Remind the agent, in its own session, of what it wrote after its
|
|
@@ -13361,8 +14539,8 @@ async function remindAnswerTail(key, text) {
|
|
|
13361
14539
|
const ensured = await ensureAgentSession(key, { isResumeOnly: true });
|
|
13362
14540
|
if (!ensured.ok || !(0, createAdapter_1.getThreadAdapter)(key).checkIsActive(key))
|
|
13363
14541
|
return false;
|
|
13364
|
-
|
|
13365
|
-
return true;
|
|
14542
|
+
// `false` when it waited for an adopted session's replay and then found no session (review 21, own pass).
|
|
14543
|
+
return (await forwardPromptToAgent(key, (0, createAdapter_1.getThreadAdapter)(key), text, undefined, { isRequestReminder: true })) !== 'noSession';
|
|
13366
14544
|
}
|
|
13367
14545
|
/**
|
|
13368
14546
|
* @description How a conversation's session stands right now (`requests/sessionTurnProbe.ts`) — the one probe the
|
|
@@ -13376,7 +14554,9 @@ const probeThreadTurn = (0, sessionTurnProbe_1.createSessionTurnProbe)({
|
|
|
13376
14554
|
getApiRetryTimer: (keyString) => apiRetryTimers.get(keyString)?.timer,
|
|
13377
14555
|
checkIsWedgeRecoveryInFlight: (keyString) => wedgeRecoveriesInFlight.has(keyString),
|
|
13378
14556
|
checkIsRetryKickInFlight: (keyString) => apiRetryKicksInFlight.has(keyString),
|
|
14557
|
+
checkIsApiErrorInHandling: (keyString) => apiErrorsInHandling.has(keyString),
|
|
13379
14558
|
checkIsSessionStarting: (keyString) => startupPromptBuffer.checkIsStarting(keyString),
|
|
14559
|
+
checkIsReplayingBufferedPrompts: (keyString) => startupPromptBuffer.checkIsReplaying(keyString),
|
|
13380
14560
|
serializeKey: sessionKey_1.keyToString,
|
|
13381
14561
|
});
|
|
13382
14562
|
/**
|
|
@@ -13395,18 +14575,53 @@ async function postTodoReminder(key, text) {
|
|
|
13395
14575
|
return isPosted && !isDropped;
|
|
13396
14576
|
}
|
|
13397
14577
|
/**
|
|
13398
|
-
* @description The person
|
|
13399
|
-
*
|
|
13400
|
-
*
|
|
13401
|
-
*
|
|
14578
|
+
* @description The person interrupted the turn (`/esc` and its aliases, `/c`): the conversation goes on, but its open requests close
|
|
14579
|
+
* silently and nothing wakes them. A command that ends or replaces the conversation closes them through
|
|
14580
|
+
* {@link cancelEndingConversationRequests} instead, which tells a person whose words were never read. Safe before the engine exists
|
|
14581
|
+
* (early boot).
|
|
13402
14582
|
*/
|
|
13403
14583
|
function cancelConversationRequest(key) {
|
|
13404
14584
|
void requestWakeUpEngine?.cancelConversation(key).catch((e) => console.warn(`[requests] cancelling the request of ${(0, sessionKey_1.keyToString)(key)} failed:`, e instanceof Error ? e.message : e));
|
|
13405
14585
|
}
|
|
14586
|
+
/**
|
|
14587
|
+
* @description A command that ends or replaces the conversation — `/new`, the `/resume` pick, `/quit`, leaving the folder, each `/quitall`
|
|
14588
|
+
* topic, a move across backends, a start onto another agent or a shell (`switchThreadAdapter`) — closes its open requests, and a person
|
|
14589
|
+
* whose words the agent never took in is told: nobody reads them (review 25 #3; one rule for every such command, review 26 #2). A request
|
|
14590
|
+
* the agent took in closes in silence: its words are in the conversation it had. «Taken in» is the persisted mark or what the live process
|
|
14591
|
+
* says NOW (`readPromptsReachedOrHeld`, read synchronously here — call it before the command stops the process — or handed in by a command
|
|
14592
|
+
* that reads it earlier: the `/resume` pick ahead of the resume that replaces the process, a bridged move ahead of its bridge, so the
|
|
14593
|
+
* reading and the bridge describe the same moment): the mark lags until a settle or the 10-second poll (review 26 #1, review 27 nit 5).
|
|
14594
|
+
* Three prompts are not told here, so each person is told once: one waiting in a window — that window's drop tells it; one on its way to
|
|
14595
|
+
* its write ({@link personPromptsInDelivery}) — its own route refuses it, also once this command is over, since its request is closed here
|
|
14596
|
+
* ({@link personPromptsEndedInDelivery}, marked at this call; review 27 #1, review 28 nit 4); and one whose drop is already being told
|
|
14597
|
+
* (`personDropsBeingTold`). Fire and forget. An interrupt keeps {@link cancelConversationRequest}'s silent close.
|
|
14598
|
+
*/
|
|
14599
|
+
function cancelEndingConversationRequests(key, reachedOrHeld) {
|
|
14600
|
+
const engine = requestWakeUpEngine;
|
|
14601
|
+
if (!engine)
|
|
14602
|
+
return;
|
|
14603
|
+
// Not the cancel's to tell: what the live process took in or a window holds, and a person's prompt on its way to its write (review 27 #1)
|
|
14604
|
+
// — which its own route refuses, even once this command is over, since the cancel closes its request (review 28 nit 4).
|
|
14605
|
+
const promptsReachedOrHeld = new Set([...(reachedOrHeld ?? engine.readPromptsReachedOrHeld(key)), ...personPromptsInDelivery.keys()]);
|
|
14606
|
+
for (const [requestId, conversationKey] of personPromptsInDelivery) {
|
|
14607
|
+
if (conversationKey === (0, sessionKey_1.keyToString)(key))
|
|
14608
|
+
personPromptsEndedInDelivery.add(requestId);
|
|
14609
|
+
}
|
|
14610
|
+
void (async () => {
|
|
14611
|
+
const unreadRequestIds = (await engine.cancelConversation(key, promptsReachedOrHeld)).filter((requestId) => !personDropsBeingTold.has(requestId));
|
|
14612
|
+
// A topic line: a tracker conversation never moves to another agent (its fallback stays within Claude).
|
|
14613
|
+
if (unreadRequestIds.length === 0 || !(0, sessionKeyCodec_1.checkIsTelegramKey)(key))
|
|
14614
|
+
return;
|
|
14615
|
+
console.warn(`[requests] ${(0, sessionKey_1.keyToString)(key)}: the conversation ended before its agent read ${unreadRequestIds.join(', ')}; the requests are closed and the topic told`);
|
|
14616
|
+
await withThreadLocale(key, () => replyToThread(key, (0, i18n_1.t)('agent.queued_prompt_dropped_by_command')));
|
|
14617
|
+
})().catch((e) => console.warn(`[requests] cancelling the requests of ${(0, sessionKey_1.keyToString)(key)} as its conversation ends failed:`, e instanceof Error ? e.message : e));
|
|
14618
|
+
}
|
|
13406
14619
|
/**
|
|
13407
14620
|
* @description How a prompt is posted into a conversation's session — the deps of
|
|
13408
14621
|
* {@link postToSession}, shared by the scheduler's fire and the Jira connector's
|
|
13409
|
-
* requests (Jira plan J5, D21).
|
|
14622
|
+
* requests (Jira plan J5, D21). The forward opens no request: a Jira request arrives with its request open and its header in the
|
|
14623
|
+
* text, and a scheduled run meets a topic's requests through the scheduler's own topic ports ({@link forwardScheduledRun},
|
|
14624
|
+
* {@link forwardTopicSchedulerRequestRun}).
|
|
13410
14625
|
*/
|
|
13411
14626
|
function createSessionPostDeps() {
|
|
13412
14627
|
return {
|
|
@@ -13425,21 +14640,120 @@ function createSessionPostDeps() {
|
|
|
13425
14640
|
return { ok: false, reason };
|
|
13426
14641
|
},
|
|
13427
14642
|
forwardPrompt: async (conversationKey, text) => {
|
|
13428
|
-
const key = (0, sessionKey_1.keyFromString)(conversationKey);
|
|
13429
|
-
// A scheduled run in a topic with requests on is a request (S7); a tracker's
|
|
13430
|
-
// post arrives with its request already open and its header in the text.
|
|
13431
|
-
const opening = await openTopicRequest(key, text, { source: 'scheduledRun', requesterId: topicRequest_1.scheduledRunRequester });
|
|
13432
14643
|
const buffered = createBufferedOutcome();
|
|
13433
|
-
const delivery = await
|
|
13434
|
-
await settleTopicRequestAfterDelivery(key, opening, delivery);
|
|
14644
|
+
const delivery = await deliverPostPrompt((0, sessionKey_1.keyFromString)(conversationKey), text, buffered.settle, { isAccountsNoteCarrier: true });
|
|
13435
14645
|
// 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
14646
|
if (delivery === 'buffered')
|
|
13437
14647
|
await buffered.assertReplayed();
|
|
14648
|
+
// The session the post ensured went to sleep before the write, and nothing could be woken for it: no turn will take the prompt.
|
|
14649
|
+
if (delivery === 'noSession')
|
|
14650
|
+
throw new Error(noSessionForPostError);
|
|
13438
14651
|
},
|
|
14652
|
+
// The watches whose turn ended are settled before the post picks a request and builds its text; the reminders they decided, and the
|
|
14653
|
+
// ones handed to the post while it waited, are delivered after the post's own write (`requests/README.md` § Turn starts).
|
|
14654
|
+
settleEndedTurns: (conversationKey) => requestWakeUpEngine?.settleEndedTurnsForPost((0, sessionKey_1.keyFromString)(conversationKey)) ?? Promise.resolve(deliverNoSettledWakes),
|
|
14655
|
+
notePostInFlight: (conversationKey) => requestWakeUpEngine?.notePostInFlight((0, sessionKey_1.keyFromString)(conversationKey)) ?? deliverNoSettledWakes,
|
|
14656
|
+
// A command that ends or replaces the conversation runs: the post waits for it to be over, then goes to what follows — in a move,
|
|
14657
|
+
// after the bridge its own ensure would otherwise overtake (review 26 #5).
|
|
14658
|
+
waitForConversationChange: (conversationKey) => conversationEndings.waitForMessagesAccepted(conversationKey),
|
|
13439
14659
|
now: () => Date.now(),
|
|
13440
14660
|
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
13441
14661
|
};
|
|
13442
14662
|
}
|
|
14663
|
+
/**
|
|
14664
|
+
* @description A bot-made post's write: the last await before EACH routing of it waits while a command ends or replaces the
|
|
14665
|
+
* conversation (`ConversationEndings.waitForMessagesAccepted`, handed to the route as `waitBeforeRoute`) — before the first routing, and
|
|
14666
|
+
* again after a wake brought the conversation back or an adopt replay was waited out, with only synchronous code between each wait and
|
|
14667
|
+
* its routing. The post's earlier waits (`postToSession`) come before its ensures; after them a topic fire still queues behind the
|
|
14668
|
+
* topic's previous fire, may open the scheduler's request, or wakes the conversation — a move that began meanwhile would otherwise get
|
|
14669
|
+
* the prompt written into the backend it leaves, past the bridge it already built, and the run lost while recorded as delivered (review 27
|
|
14670
|
+
* nit 2, review 28 nit 2). A scheduled run's `headerRequest` — the request its header names, and the conversation's refusal serial when
|
|
14671
|
+
* that request was picked — is refused at a routing whose serial moved and whose request is closed (mini-review of round 28, #3; of round
|
|
14672
|
+
* 29, #2).
|
|
14673
|
+
*/
|
|
14674
|
+
function deliverPostPrompt(key, text, onBufferedSettled, options = {}, headerRequest = null) {
|
|
14675
|
+
const conversationKey = (0, sessionKey_1.keyToString)(key);
|
|
14676
|
+
return deliverPromptOrBuffer(key, text, onBufferedSettled, {
|
|
14677
|
+
...options,
|
|
14678
|
+
waitBeforeRoute: async () => {
|
|
14679
|
+
await conversationEndings.waitForMessagesAccepted(conversationKey);
|
|
14680
|
+
// A command ran since the pick — during this wait, or one that began and ended between two routings (an adopt replay's wait, a
|
|
14681
|
+
// wake's notice) — and closed the request this run's header names: written now, the agent that follows would read a request it
|
|
14682
|
+
// cannot answer, in a turn nothing watches. Refused before it routes; the fire picks again.
|
|
14683
|
+
if (headerRequest !== null && checkIsHeaderRequestClosedByCommand(conversationKey, headerRequest)) {
|
|
14684
|
+
throw new delivery_1.ScheduledRunTargetClosedError(headerRequest.requestId);
|
|
14685
|
+
}
|
|
14686
|
+
},
|
|
14687
|
+
});
|
|
14688
|
+
}
|
|
14689
|
+
/**
|
|
14690
|
+
* @description The header's request of a Telegram topic's scheduled run, with the refusal serial read at its pick (by default now: call it
|
|
14691
|
+
* synchronously with the pick). A tracker conversation stays out (`null`): it never takes a refusal, a move across backends being a
|
|
14692
|
+
* topic's only.
|
|
14693
|
+
*/
|
|
14694
|
+
function getScheduledRunHeaderRequest(key, requestId, refusalSerialAtPick = conversationEndings.readRefusalSerial((0, sessionKey_1.keyToString)(key))) {
|
|
14695
|
+
if (requestId === null || !(0, sessionKeyCodec_1.checkIsTelegramKey)(key))
|
|
14696
|
+
return null;
|
|
14697
|
+
return { requestId, refusalSerialAtPick };
|
|
14698
|
+
}
|
|
14699
|
+
/** @description Whether a command ran since the header's request was picked and that request is closed now. */
|
|
14700
|
+
function checkIsHeaderRequestClosedByCommand(conversationKey, headerRequest) {
|
|
14701
|
+
return conversationEndings.readRefusalSerial(conversationKey) !== headerRequest.refusalSerialAtPick
|
|
14702
|
+
&& topicRequestLedger?.getOpenRequestById(headerRequest.requestId) === undefined;
|
|
14703
|
+
}
|
|
14704
|
+
/**
|
|
14705
|
+
* @description Write a scheduled run's prompt into a conversation's session and watch the turn it starts as the scheduled run of
|
|
14706
|
+
* the request it RIDES (`ridden`; `null` when none is open — a tracker's — so no turn is watched): a Jira issue's open request, or a
|
|
14707
|
+
* topic's job request or scheduler's request, told whether the fire's job is one of that request's own (`isRequestJob`). It goes through
|
|
14708
|
+
* the buffer-or-forward unit and opens no request: the request it rides owes the answer (`scheduler/scheduledRunTarget.ts`). A prompt
|
|
14709
|
+
* that never reached the agent — its window dropped it, or it found no session and nothing to wake — fails the post, as every session
|
|
14710
|
+
* post does: its run records the error, and a check's failure wake clears `isCheckFailing` so its next failing run wakes the agent again
|
|
14711
|
+
* (review 21 #2). No turn is watched for it.
|
|
14712
|
+
*/
|
|
14713
|
+
async function forwardScheduledRun(conversationKey, text, ridden) {
|
|
14714
|
+
const key = (0, sessionKey_1.keyFromString)(conversationKey);
|
|
14715
|
+
// Read in the tick of the pick (the caller picked `ridden` and called here with no await between).
|
|
14716
|
+
const headerRequest = getScheduledRunHeaderRequest(key, ridden?.requestId ?? null);
|
|
14717
|
+
const buffered = createBufferedOutcome();
|
|
14718
|
+
// A tracker fire whose ridden request owes nothing, or with none open: its header says when to answer, so a lost-work note riding it
|
|
14719
|
+
// defers to it and claims no watch (a comment notifies the requester and the issue's watchers). A topic keeps its own resume and wording.
|
|
14720
|
+
const lostWorkTelling = !(0, sessionKeyCodec_1.checkIsTelegramKey)(key) && ridden?.isAnswerOwed !== true ? 'runHeader' : 'plain';
|
|
14721
|
+
const delivery = await deliverPostPrompt(key, text, buffered.settle, { isAccountsNoteCarrier: true, lostWorkTelling }, headerRequest);
|
|
14722
|
+
// A prompt that waited for the session's start counts only once it reached it: a replay whose write failed is a failed post.
|
|
14723
|
+
if (delivery === 'buffered')
|
|
14724
|
+
await buffered.assertReplayed();
|
|
14725
|
+
if (delivery === 'noSession')
|
|
14726
|
+
throw new Error(noSessionForPostError);
|
|
14727
|
+
if (ridden !== null) {
|
|
14728
|
+
await requestWakeUpEngine?.trackForwardedTurn(key, ridden.requestId, { isRequestPrompt: false, isScheduledRun: true, isRequestJob: ridden.isRequestJob });
|
|
14729
|
+
}
|
|
14730
|
+
}
|
|
14731
|
+
/**
|
|
14732
|
+
* @description A topic's scheduled run with no request to ride (`pickTopicRunTarget` → `ownRequest`): open the scheduler's request
|
|
14733
|
+
* (S7, the scheduler's requester — it replaces only one the bot gave up on), forward the prompt behind its header and settle it as
|
|
14734
|
+
* the request's own scheduled run — the turn is tracked as one. A prompt that never reached the agent (its window dropped it, or it
|
|
14735
|
+
* found no session) closes the request nobody was told about and fails the post, as {@link forwardScheduledRun} does (review 21 #2).
|
|
14736
|
+
*/
|
|
14737
|
+
async function forwardTopicSchedulerRequestRun(conversationKey, text) {
|
|
14738
|
+
const key = (0, sessionKey_1.keyFromString)(conversationKey);
|
|
14739
|
+
// Read at the pick, ahead of the open: a command during the open's flush closes the request it opens, and counts.
|
|
14740
|
+
const refusalSerialAtPick = conversationEndings.readRefusalSerial(conversationKey);
|
|
14741
|
+
const opening = await openTopicRequest(key, text, { source: 'scheduledRun', requesterId: topicRequest_1.scheduledRunRequester });
|
|
14742
|
+
const buffered = createBufferedOutcome();
|
|
14743
|
+
const headerRequest = getScheduledRunHeaderRequest(key, opening.requestId, refusalSerialAtPick);
|
|
14744
|
+
const delivery = await deliverPostPrompt(key, `${opening.header}${text}`, buffered.settle, { isAccountsNoteCarrier: true }, headerRequest);
|
|
14745
|
+
// A prompt that waited for the session's start counts only once it reached it, and only then is its turn watched (a watch made in
|
|
14746
|
+
// the window would wait for good if the window dropped it). Dropped, the scheduler's request nobody was told about closes like one
|
|
14747
|
+
// that found no session, and the post fails.
|
|
14748
|
+
if (delivery === 'buffered' && (await buffered.getOutcome()) === 'dropped') {
|
|
14749
|
+
await settleTopicRequestAfterDelivery(key, opening, 'noSession');
|
|
14750
|
+
throw new Error(bufferedPromptDroppedError);
|
|
14751
|
+
}
|
|
14752
|
+
await settleTopicRequestAfterDelivery(key, { ...opening, isScheduledRun: true }, delivery);
|
|
14753
|
+
// Closed by the settle when no session was left to take the prompt: the post fails, not read as delivered.
|
|
14754
|
+
if (delivery === 'noSession')
|
|
14755
|
+
throw new Error(noSessionForPostError);
|
|
14756
|
+
}
|
|
13443
14757
|
/**
|
|
13444
14758
|
* @description Construct the scheduler stack (S8): run ledger → delivery (thin
|
|
13445
14759
|
* lambdas over the bot's existing send/session functions) → timer engine
|
|
@@ -13505,6 +14819,34 @@ function wireScheduler(wiring) {
|
|
|
13505
14819
|
return decision.kind === 'proceed' ? (0, workerActivity_1.readWorkerActivity)(path.resolve(decision.workDir, runDir)) : null;
|
|
13506
14820
|
},
|
|
13507
14821
|
statusIntervalOverrideMs: ENV.testTimings.checkStatusIntervalMs,
|
|
14822
|
+
// A topic whose view has requests: a fire rides the job's request or the scheduler's, and opens the scheduler's only when there is
|
|
14823
|
+
// none to ride (`scheduler/scheduledRunTarget.ts`).
|
|
14824
|
+
topicRun: {
|
|
14825
|
+
getRequestView: (threadKeyStr) => {
|
|
14826
|
+
const key = (0, sessionKey_1.keyFromString)(threadKeyStr);
|
|
14827
|
+
if (!(0, sessionKeyCodec_1.checkIsTelegramKey)(key))
|
|
14828
|
+
return null;
|
|
14829
|
+
const { view } = state.getDisplayPrefs(key);
|
|
14830
|
+
return (0, topicView_1.checkAreRequestsEnabled)(view) ? { isPlainTextHidden: !(0, topicView_1.checkIsStreamShown)(view) } : null;
|
|
14831
|
+
},
|
|
14832
|
+
listOpenRequests: (threadKeyStr) => wiring.requestLedger.listOpenRequestsOf((0, sessionKey_1.keyFromString)(threadKeyStr)),
|
|
14833
|
+
forwardRun: forwardScheduledRun,
|
|
14834
|
+
forwardOwnRequestRun: forwardTopicSchedulerRequestRun,
|
|
14835
|
+
},
|
|
14836
|
+
// A Jira issue's fires post nothing there and ride the open request (`scheduler/scheduledRunTarget.ts`).
|
|
14837
|
+
...(jiraConnector
|
|
14838
|
+
? {
|
|
14839
|
+
trackerRun: {
|
|
14840
|
+
describeConversation: (threadKeyStr) => {
|
|
14841
|
+
const key = (0, sessionKey_1.keyFromString)(threadKeyStr);
|
|
14842
|
+
return key.platform === 'jira' ? jiraConnector.describeConversation(key) : null;
|
|
14843
|
+
},
|
|
14844
|
+
listOpenRequests: (threadKeyStr) => wiring.requestLedger.listOpenRequestsOf((0, sessionKey_1.keyFromString)(threadKeyStr)),
|
|
14845
|
+
forwardRun: forwardScheduledRun,
|
|
14846
|
+
fallbackAdapterName: jiraConnector.adapterName,
|
|
14847
|
+
},
|
|
14848
|
+
}
|
|
14849
|
+
: {}),
|
|
13508
14850
|
});
|
|
13509
14851
|
/**
|
|
13510
14852
|
* The engine's deliver callback: the S4 pipeline plus the S8 unbound-pause
|
|
@@ -13518,11 +14860,15 @@ function wireScheduler(wiring) {
|
|
|
13518
14860
|
if (outcome.status === 'failed' && outcome.error === delivery_1.unboundDeliveryError) {
|
|
13519
14861
|
await state.setSchedulePaused(job.id, true, 'unbound');
|
|
13520
14862
|
schedulerEngine?.disarmJob(job.id);
|
|
13521
|
-
|
|
14863
|
+
// The bot posts nothing on an issue: a tracker conversation's pause is a log line, and its jobs resume with its next usable bind.
|
|
14864
|
+
if ((0, sessionKeyCodec_1.checkIsTelegramKey)(key))
|
|
14865
|
+
await withThreadLocale(key, () => replyToThread(key, (0, i18n_1.t)('schedule.pausedUnbound', { count: 1 }))).catch(() => { });
|
|
14866
|
+
else
|
|
14867
|
+
console.log(`[scheduler] job ${job.id} of ${job.threadKey} paused: its folder is not usable; it resumes when a request finds the folder usable again`);
|
|
13522
14868
|
}
|
|
13523
14869
|
return outcome;
|
|
13524
14870
|
};
|
|
13525
|
-
schedulerEngine = (0,
|
|
14871
|
+
schedulerEngine = (0, engine_2.createSchedulerEngine)({
|
|
13526
14872
|
store: state,
|
|
13527
14873
|
ledger,
|
|
13528
14874
|
deliver,
|
|
@@ -13557,11 +14903,45 @@ function wireScheduler(wiring) {
|
|
|
13557
14903
|
sendMessagesToThread,
|
|
13558
14904
|
compactConversation: (threadKeyStr) => armDeferredCompaction((0, sessionKey_1.keyFromString)(threadKeyStr)),
|
|
13559
14905
|
listClaudeProfiles: listClaudeProfilesForAgent,
|
|
14906
|
+
// The accounts note (`limitNotes/`): the send tools' results carry it, and the two calls that mark a conversation as launching workers record it.
|
|
14907
|
+
takeLimitNoteForSend: (threadKeyStr) => {
|
|
14908
|
+
const key = (0, sessionKey_1.tryKeyFromString)(threadKeyStr);
|
|
14909
|
+
return key === null ? null : getLimitNotes().takeSendResultNote(key);
|
|
14910
|
+
},
|
|
14911
|
+
noteLimitProfilesCall: (threadKeyStr) => {
|
|
14912
|
+
const key = (0, sessionKey_1.tryKeyFromString)(threadKeyStr);
|
|
14913
|
+
if (key === null)
|
|
14914
|
+
return;
|
|
14915
|
+
// The agent looks now: a reminder still waiting in its inbox is stale before it is read — the hook runs after this tool's result —
|
|
14916
|
+
// so it is withdrawn (a file the hook already took is recorded first), then the look is recorded over it.
|
|
14917
|
+
withdrawAccountsInbox(key);
|
|
14918
|
+
getLimitNotes().noteProfilesCall(key);
|
|
14919
|
+
},
|
|
14920
|
+
noteLimitWorkerWatch: (threadKeyStr) => {
|
|
14921
|
+
const key = (0, sessionKey_1.tryKeyFromString)(threadKeyStr);
|
|
14922
|
+
if (key !== null)
|
|
14923
|
+
getLimitNotes().noteWorkerWatch(key);
|
|
14924
|
+
},
|
|
14925
|
+
// The request a job is armed under (`ScheduleRecord.requestId`): the one the agent works on — the request whose forward started the
|
|
14926
|
+
// running turn (the scheduler's request too, when its fire did); the scheduler's request is passed over only where no turn tells.
|
|
14927
|
+
getArmingRequestId: (threadKeyStr) => {
|
|
14928
|
+
const key = (0, sessionKey_1.tryKeyFromString)(threadKeyStr);
|
|
14929
|
+
if (key === null)
|
|
14930
|
+
return undefined;
|
|
14931
|
+
return requestWakeUpEngine?.getArmingRequestIdOf(key) ?? (0, scheduleWait_1.pickRequestToArmUnder)(wiring.requestLedger.listOpenRequestsOf(key), []);
|
|
14932
|
+
},
|
|
13560
14933
|
getRemoteRunRunnerLines: () => (0, runnerSummary_1.getRunnerSummaryLines)(),
|
|
13561
14934
|
// A refused tool call leaves one line in the bounded diagnostic log (agent-diag.log): the SDK refuses before the bot sees it.
|
|
13562
14935
|
logDiagnostic: diagLog_1.appendDiagLog,
|
|
13563
14936
|
...(jiraConnector
|
|
13564
|
-
? {
|
|
14937
|
+
? {
|
|
14938
|
+
fetchJiraAttachment: (threadKeyStr, attachmentId) => jiraConnector.fetchAttachment((0, sessionKey_1.keyFromString)(threadKeyStr), attachmentId),
|
|
14939
|
+
// Through the issue's outbound, like a topic's file send: the agent-facing tool is a connector delivery.
|
|
14940
|
+
sendJiraFiles: (threadKeyStr, request) => {
|
|
14941
|
+
const key = (0, sessionKey_1.keyFromString)(threadKeyStr);
|
|
14942
|
+
return getOutboundFor(key).deliverFile(key, request);
|
|
14943
|
+
},
|
|
14944
|
+
}
|
|
13565
14945
|
: {}),
|
|
13566
14946
|
// Read per request: General can turn the shared lists off, and the tools go with them.
|
|
13567
14947
|
get todos() {
|
|
@@ -13621,6 +15001,14 @@ function getOperatorGeneralKey() {
|
|
|
13621
15001
|
const ownerUserId = getOwnerUserId();
|
|
13622
15002
|
return Number.isFinite(ownerUserId) ? (0, sessionKeyCodec_1.makeTelegramKey)(ownerUserId, threadRouting_1.DM_GENERAL_THREAD_ID) : null;
|
|
13623
15003
|
}
|
|
15004
|
+
/** How the bot is named to the operator: its `@username`, else the host it runs on. */
|
|
15005
|
+
function getBotLabel() {
|
|
15006
|
+
return bot.botInfo?.username === undefined ? os.hostname() : `@${bot.botInfo.username}`;
|
|
15007
|
+
}
|
|
15008
|
+
/** The operator's private chat to message them in (`resolveOperatorPrivateChatKey`); `null` when none would do. */
|
|
15009
|
+
function getOperatorPrivateChatKey() {
|
|
15010
|
+
return (0, threadRouting_1.resolveOperatorPrivateChatKey)({ isDmSurfaceActive: checkIsDmSurfaceActive(), ownerUserId: getOwnerUserId(), generalKey: getOperatorGeneralKey() });
|
|
15011
|
+
}
|
|
13624
15012
|
/**
|
|
13625
15013
|
* @description Say an update message in General, worded in that chat's language: pinned when it asks the operator to act, with
|
|
13626
15014
|
* the install tap (the version printed on the button is the version it installs) when it offers one. A failed send or pin is
|
|
@@ -13803,32 +15191,20 @@ function createJiraSessionDeps(requestLedger, slots, adapterName) {
|
|
|
13803
15191
|
bindConversation: async (key, folder) => {
|
|
13804
15192
|
if (state.getBinding(key)?.subdir !== folder)
|
|
13805
15193
|
await state.setBinding(key, folder);
|
|
15194
|
+
// A fire that found no usable folder paused its job; a request that finds it usable resumes it, as `/bind` does in a topic.
|
|
15195
|
+
if ((0, validation_1.resolveBoundWorkDir)(ENV.workRoot, state.getBinding(key)).kind === 'proceed') {
|
|
15196
|
+
await resumeTrackerSchedulesOnRebind(key).catch((e) => console.warn(`[scheduler] resume-on-rebind failed for ${(0, sessionKey_1.keyToString)(key)}:`, e));
|
|
15197
|
+
}
|
|
13806
15198
|
},
|
|
13807
15199
|
createRequest: (key, origin, createPrompt) => requestLedger.createRequest(key, origin, { createPrompt }),
|
|
13808
15200
|
listOpenRequests: (key) => requestLedger.listOpenRequestsOf(key),
|
|
13809
|
-
|
|
13810
|
-
|
|
13811
|
-
|
|
13812
|
-
|
|
13813
|
-
|
|
13814
|
-
|
|
13815
|
-
|
|
13816
|
-
await requestWakeUpEngine?.notePostFailed(key, requestId);
|
|
13817
|
-
throw new Error(posted.reason === 'forward-failed' ? posted.error : `session ${posted.reason}`);
|
|
13818
|
-
}
|
|
13819
|
-
// A held request is tracked when the wait's resume, or else its next wake-up, posts its prompt (R21).
|
|
13820
|
-
if (!posted.isHeld)
|
|
13821
|
-
await requestWakeUpEngine?.trackForwardedTurn(key, requestId, { isRequestPrompt: true });
|
|
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
|
-
},
|
|
15201
|
+
// A request is the issue's "user message" (L-D5): posting it restarts the idle countdown, like a topic's message does. An issue
|
|
15202
|
+
// update (a comment for an open hand-over request) opens no request: the turn it starts is that request's.
|
|
15203
|
+
...(0, trackerTurnPoster_1.createTrackerTurnPoster)({
|
|
15204
|
+
post: (key, prompt, options) => (0, postToSession_1.postToSession)(sessionPostDeps, (0, sessionKey_1.keyToString)(key), prompt, adapterName, options),
|
|
15205
|
+
notePersonActivity,
|
|
15206
|
+
getEngine: () => requestWakeUpEngine,
|
|
15207
|
+
}),
|
|
13832
15208
|
};
|
|
13833
15209
|
}
|
|
13834
15210
|
async function startBot() {
|
|
@@ -13888,7 +15264,10 @@ async function startBot() {
|
|
|
13888
15264
|
(0, claudeApiCreditRecheck_1.startClaudeApiCreditRechecks)(claudeApiCreditRecheckPorts, ENV.testTimings.creditRecheckPollMs ?? claudeApiCreditRecheck_1.claudeApiCreditRecheckPollMs);
|
|
13889
15265
|
const jiraConnector = ENV.servedPlatforms.has('jira') ? await prepareJiraConnectorOrExit() : null;
|
|
13890
15266
|
todoJiraConversations = jiraConnector;
|
|
15267
|
+
// The operator issue plays General's part for the alerts only the operator can act on (a Claude account signed out).
|
|
15268
|
+
operatorAlertChannels = jiraConnector?.operatorChannel ? [jiraConnector.operatorChannel] : [];
|
|
13891
15269
|
if (jiraConnector) {
|
|
15270
|
+
jiraFileSender = (key, request) => jiraConnector.sendFiles(key, request);
|
|
13892
15271
|
const { launchDefaults } = jiraConnector;
|
|
13893
15272
|
(0, createAdapter_1.registerSessionLaunchDefaultsReader)((key) => (key.platform === 'jira' ? launchDefaults : null));
|
|
13894
15273
|
}
|
|
@@ -13927,6 +15306,7 @@ async function startBot() {
|
|
|
13927
15306
|
requestWakeUpEngine = new wakeUpEngine_1.RequestWakeUpEngine({
|
|
13928
15307
|
ledger: requestLedger,
|
|
13929
15308
|
probeTurn: probeThreadTurn,
|
|
15309
|
+
refreshProcessState: (key) => (0, createAdapter_1.getThreadAdapter)(key).refreshWorkingState?.(key),
|
|
13930
15310
|
prepareWakeUpSession: (key, message) => prepareRequestWakeUpSession(key, message, key.platform === 'jira' ? jiraConnector?.adapterName : undefined),
|
|
13931
15311
|
forwardWakeUp: forwardRequestWakeUp,
|
|
13932
15312
|
deliverAlert: async (key, request, reason) => {
|
|
@@ -13947,6 +15327,11 @@ async function startBot() {
|
|
|
13947
15327
|
pollIntervalMs: ENV.testTimings.requestTurnPollMs,
|
|
13948
15328
|
sweepIntervalMs: ENV.testTimings.requestSweepIntervalMs,
|
|
13949
15329
|
firstPostRetryDelayMs: ENV.testTimings.requestFirstPostRetryDelayMs,
|
|
15330
|
+
progressFollowUpMs: ENV.testTimings.progressFollowUpMs,
|
|
15331
|
+
// A request waits for its schedule while a job armed under it counts (`requests/scheduleWait.ts`): read when a decision is made.
|
|
15332
|
+
getScheduleWait: (key, request) => (0, scheduleWait_1.getRequestScheduleWait)(state.getThreadSchedules(key), request),
|
|
15333
|
+
// A tracker issue is never reminded on a clock: a progress note with nothing armed under it gets one nudge, the next stall the give-up.
|
|
15334
|
+
getWakeUpRules: (key) => ((0, sessionKeyCodec_1.checkIsTelegramKey)(key) ? 'topic' : 'tracker'),
|
|
13950
15335
|
// Only a Telegram topic in the answers-only view hides the stream from someone who expects to see the work.
|
|
13951
15336
|
checkIsAnswerTailWatched: (key) => (0, sessionKeyCodec_1.checkIsTelegramKey)(key) && !(0, topicView_1.checkIsStreamShown)(state.getDisplayPrefs(key).view),
|
|
13952
15337
|
remindAnswerTail,
|
|
@@ -13969,7 +15354,19 @@ async function startBot() {
|
|
|
13969
15354
|
midTurn: getTodoMidTurn(),
|
|
13970
15355
|
pollIntervalMs: ENV.testTimings.todoReminderPollMs,
|
|
13971
15356
|
});
|
|
13972
|
-
|
|
15357
|
+
// The accounts note's mid-turn delivery polls the same turns, for Claude on the json-stream host only (`limitNotes/engine.ts`).
|
|
15358
|
+
limitNotesEngine = new engine_1.LimitNotesEngine({
|
|
15359
|
+
listConversations: () => state.listBindings().map(({ key }) => key),
|
|
15360
|
+
getClaudeSessionId: (key) => {
|
|
15361
|
+
const adapterName = (0, createAdapter_1.getThreadAdapterNameRaw)(key) ?? state.getAgent(key)?.name;
|
|
15362
|
+
return adapterName !== undefined && (0, adapterNames_1.checkIsJsonStreamBackend)(adapterName) ? getResumableSessionId(key) : null;
|
|
15363
|
+
},
|
|
15364
|
+
probeTurn: probeThreadTurn,
|
|
15365
|
+
notes: getLimitNotes(),
|
|
15366
|
+
inbox: getMidTurnInbox(),
|
|
15367
|
+
pollIntervalMs: ENV.testTimings.limitNoteEnginePollMs,
|
|
15368
|
+
});
|
|
15369
|
+
getMidTurnInbox().clearAll();
|
|
13973
15370
|
warmTodoProjects();
|
|
13974
15371
|
// Snapshot the persisted transient status-frame ids (S2) NOW, before reattach
|
|
13975
15372
|
// can run any frame-id setter. A reattached session's first frame lifecycle
|
|
@@ -14074,11 +15471,11 @@ async function startBot() {
|
|
|
14074
15471
|
}),
|
|
14075
15472
|
onStopped: (key) => (0, adapterEventRouting_1.dispatchAdapterEvent)(key, 'stopped', () => withThreadLocale(key, () => handleAgentStopped(key)), () => clearForeignSessionState(key)),
|
|
14076
15473
|
onSuspended: (key) => (0, adapterEventRouting_1.dispatchAdapterEvent)(key, 'suspended', () => withThreadLocale(key, () => handleAgentSuspended(key)), () => scheduleLostWorkNote(key, takeLostWorkOf(key), 'holdExpired')),
|
|
14077
|
-
onTurnEnded: (key) => (0, adapterEventRouting_1.dispatchAdapterEvent)(key, 'turnEnded', () => {
|
|
15474
|
+
onTurnEnded: (key, turnEnd) => (0, adapterEventRouting_1.dispatchAdapterEvent)(key, 'turnEnded', () => {
|
|
14078
15475
|
// Every platform's (the route is `all`): the todo reminder's turn end, which the per-turn stop below would
|
|
14079
15476
|
// otherwise hide from its poll.
|
|
14080
15477
|
void todoReminderEngine?.noteAdapterTurnEnd(key).catch((e) => console.warn(`[todos] the turn end of ${(0, sessionKey_1.keyToString)(key)} was not noted:`, e instanceof Error ? e.message : e));
|
|
14081
|
-
handleAgentTurnEnded(key);
|
|
15478
|
+
handleAgentTurnEnded(key, turnEnd);
|
|
14082
15479
|
}),
|
|
14083
15480
|
onContextCompacted: (key, trigger) => (0, adapterEventRouting_1.dispatchAdapterEvent)(key, 'contextCompacted', () => {
|
|
14084
15481
|
noteConversationContextReset(key, `compaction (${trigger ?? 'bot'})`);
|
|
@@ -14245,7 +15642,10 @@ async function startBot() {
|
|
|
14245
15642
|
// A tracker conversation whose process did not survive the downtime resumes its open request now, not at the backstop.
|
|
14246
15643
|
scheduleRestartWakesAtBoot(requestLedger);
|
|
14247
15644
|
todoReminderEngine?.start();
|
|
15645
|
+
limitNotesEngine?.start();
|
|
14248
15646
|
jiraConnector?.start(createJiraSessionDeps(requestLedger, slots, jiraConnector.adapterName));
|
|
15647
|
+
// The accounts' changes found while booting are told now, and the conversations waiting for an account may go on.
|
|
15648
|
+
openOperatorAlerts();
|
|
14249
15649
|
},
|
|
14250
15650
|
healActiveSessions: () => {
|
|
14251
15651
|
// When this boot ADOPTED an already-running opencode, that server may
|
|
@@ -14455,6 +15855,9 @@ async function startBot() {
|
|
|
14455
15855
|
exit,
|
|
14456
15856
|
drainPendingUpdates: () => updateDispatcher.drainIdle(updateDrainTimeoutMs),
|
|
14457
15857
|
finalizePendingOutput: () => finalizePendingOutputOnShutdown(),
|
|
15858
|
+
// The agents' tool calls already running (an answer being posted and pinned) finish before the server goes: cut, the agent
|
|
15859
|
+
// would be told the call failed although the requester already sees its answer.
|
|
15860
|
+
stopBotMcp: isSchedulerMcpStarted ? () => schedulerMcpHandle.stop({ drainMs: mcpSurface_1.schedulerMcpShutdownDrainMs }) : undefined,
|
|
14458
15861
|
clearTransientFrames: () => sweepTransientFramesOnShutdown(),
|
|
14459
15862
|
// A hot worker's reload keeps the sidecar for the next worker to adopt; the supervisor stops it for good.
|
|
14460
15863
|
stopSidecars: (0, installManager_1.checkIsOpenCodeExternalHost)() ? undefined : () => sttOwner.stop(),
|
|
@@ -14471,10 +15874,9 @@ async function startBot() {
|
|
|
14471
15874
|
schedulerEngine?.shutdown();
|
|
14472
15875
|
requestWakeUpEngine?.stop();
|
|
14473
15876
|
todoReminderEngine?.stop();
|
|
15877
|
+
limitNotesEngine?.stop();
|
|
14474
15878
|
topicIndicator.stop();
|
|
14475
15879
|
jiraConnector?.stop();
|
|
14476
|
-
if (isSchedulerMcpStarted)
|
|
14477
|
-
void schedulerMcpHandle.stop().catch(() => { });
|
|
14478
15880
|
updateEngine?.stop();
|
|
14479
15881
|
},
|
|
14480
15882
|
});
|