charness 4.1.0 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (312) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/DEVELOPMENT.md +11 -5
  3. package/{COMMERCIAL-LICENSE.md → LICENSE-COMMERCIAL.md} +1 -1
  4. package/MIGRATION_3_TO_4.md +1 -1
  5. package/README.md +4 -1
  6. package/SETUP.md +37 -9
  7. package/agent-plugin/skills/charness-delegate-claude/SKILL.md +1 -0
  8. package/agent-plugin/skills/charness-orchestration/SKILL.md +1 -0
  9. package/dist/adapters/adapterNames.d.ts +2 -0
  10. package/dist/adapters/adapterNames.d.ts.map +1 -1
  11. package/dist/adapters/adapterNames.js +3 -1
  12. package/dist/adapters/adapterNames.js.map +1 -1
  13. package/dist/adapters/claudeJsonStreamAdapter.d.ts +74 -5
  14. package/dist/adapters/claudeJsonStreamAdapter.d.ts.map +1 -1
  15. package/dist/adapters/claudeJsonStreamAdapter.js +164 -20
  16. package/dist/adapters/claudeJsonStreamAdapter.js.map +1 -1
  17. package/dist/adapters/openCodeAdapter.d.ts +31 -2
  18. package/dist/adapters/openCodeAdapter.d.ts.map +1 -1
  19. package/dist/adapters/openCodeAdapter.js +84 -8
  20. package/dist/adapters/openCodeAdapter.js.map +1 -1
  21. package/dist/adapters/terminalAdapter.d.ts.map +1 -1
  22. package/dist/adapters/terminalAdapter.js +2 -1
  23. package/dist/adapters/terminalAdapter.js.map +1 -1
  24. package/dist/bot.d.ts.map +1 -1
  25. package/dist/bot.js +769 -118
  26. package/dist/bot.js.map +1 -1
  27. package/dist/cli/claudeProfiles.d.ts +3 -0
  28. package/dist/cli/claudeProfiles.d.ts.map +1 -1
  29. package/dist/cli/claudeProfiles.js +8 -0
  30. package/dist/cli/claudeProfiles.js.map +1 -1
  31. package/dist/connectors/jira/answerSink.d.ts +8 -0
  32. package/dist/connectors/jira/answerSink.d.ts.map +1 -1
  33. package/dist/connectors/jira/answerSink.js +15 -0
  34. package/dist/connectors/jira/answerSink.js.map +1 -1
  35. package/dist/connectors/jira/config.d.ts +16 -0
  36. package/dist/connectors/jira/config.d.ts.map +1 -1
  37. package/dist/connectors/jira/config.js +21 -2
  38. package/dist/connectors/jira/config.js.map +1 -1
  39. package/dist/connectors/jira/connector.d.ts +10 -3
  40. package/dist/connectors/jira/connector.d.ts.map +1 -1
  41. package/dist/connectors/jira/connector.js +21 -3
  42. package/dist/connectors/jira/connector.js.map +1 -1
  43. package/dist/connectors/jira/inbound.d.ts +200 -18
  44. package/dist/connectors/jira/inbound.d.ts.map +1 -1
  45. package/dist/connectors/jira/inbound.js +814 -43
  46. package/dist/connectors/jira/inbound.js.map +1 -1
  47. package/dist/connectors/jira/prompt.d.ts +46 -0
  48. package/dist/connectors/jira/prompt.d.ts.map +1 -1
  49. package/dist/connectors/jira/prompt.js +123 -15
  50. package/dist/connectors/jira/prompt.js.map +1 -1
  51. package/dist/connectors/jira/trigger.d.ts +27 -4
  52. package/dist/connectors/jira/trigger.d.ts.map +1 -1
  53. package/dist/connectors/jira/trigger.js +35 -1
  54. package/dist/connectors/jira/trigger.js.map +1 -1
  55. package/dist/connectors/jira/triggerLog.d.ts +60 -5
  56. package/dist/connectors/jira/triggerLog.d.ts.map +1 -1
  57. package/dist/connectors/jira/triggerLog.js +116 -7
  58. package/dist/connectors/jira/triggerLog.js.map +1 -1
  59. package/dist/connectors/telegram/commands/botCore.d.ts +5 -2
  60. package/dist/connectors/telegram/commands/botCore.d.ts.map +1 -1
  61. package/dist/connectors/telegram/commands/claudeAccounts.d.ts +5 -0
  62. package/dist/connectors/telegram/commands/claudeAccounts.d.ts.map +1 -1
  63. package/dist/connectors/telegram/commands/claudeAccounts.js +15 -39
  64. package/dist/connectors/telegram/commands/claudeAccounts.js.map +1 -1
  65. package/dist/connectors/telegram/commands/compaction.d.ts +6 -0
  66. package/dist/connectors/telegram/commands/compaction.d.ts.map +1 -1
  67. package/dist/connectors/telegram/commands/compaction.js +8 -1
  68. package/dist/connectors/telegram/commands/compaction.js.map +1 -1
  69. package/dist/connectors/telegram/commands/questionSetAside.d.ts +111 -0
  70. package/dist/connectors/telegram/commands/questionSetAside.d.ts.map +1 -0
  71. package/dist/connectors/telegram/commands/questionSetAside.js +637 -0
  72. package/dist/connectors/telegram/commands/questionSetAside.js.map +1 -0
  73. package/dist/connectors/telegram/commands/questionWait.d.ts +21 -0
  74. package/dist/connectors/telegram/commands/questionWait.d.ts.map +1 -0
  75. package/dist/connectors/telegram/commands/questionWait.js +109 -0
  76. package/dist/connectors/telegram/commands/questionWait.js.map +1 -0
  77. package/dist/connectors/telegram/commands/runners.d.ts +28 -1
  78. package/dist/connectors/telegram/commands/runners.d.ts.map +1 -1
  79. package/dist/connectors/telegram/commands/runners.js +75 -40
  80. package/dist/connectors/telegram/commands/runners.js.map +1 -1
  81. package/dist/connectors/telegram/commands/topicAccess.js +1 -1
  82. package/dist/connectors/telegram/commands/topicAccess.js.map +1 -1
  83. package/dist/connectors/telegram/commands/topicCommand.d.ts +0 -2
  84. package/dist/connectors/telegram/commands/topicCommand.d.ts.map +1 -1
  85. package/dist/connectors/telegram/commands/topicCommand.js +4 -5
  86. package/dist/connectors/telegram/commands/topicCommand.js.map +1 -1
  87. package/dist/connectors/telegram/commands/topicStatus.d.ts +24 -0
  88. package/dist/connectors/telegram/commands/topicStatus.d.ts.map +1 -0
  89. package/dist/connectors/telegram/commands/topicStatus.js +148 -0
  90. package/dist/connectors/telegram/commands/topicStatus.js.map +1 -0
  91. package/dist/connectors/telegram/firstUpdateBatchNote.d.ts +30 -0
  92. package/dist/connectors/telegram/firstUpdateBatchNote.d.ts.map +1 -0
  93. package/dist/connectors/telegram/firstUpdateBatchNote.js +39 -0
  94. package/dist/connectors/telegram/firstUpdateBatchNote.js.map +1 -0
  95. package/dist/connectors/telegram/inbound.d.ts +12 -0
  96. package/dist/connectors/telegram/inbound.d.ts.map +1 -1
  97. package/dist/connectors/telegram/inbound.js +31 -3
  98. package/dist/connectors/telegram/inbound.js.map +1 -1
  99. package/dist/connectors/telegram/sendOutcome.d.ts +3 -1
  100. package/dist/connectors/telegram/sendOutcome.d.ts.map +1 -1
  101. package/dist/connectors/telegram/sendOutcome.js.map +1 -1
  102. package/dist/connectors/telegram/telegramFailureRetry.d.ts +8 -0
  103. package/dist/connectors/telegram/telegramFailureRetry.d.ts.map +1 -1
  104. package/dist/connectors/telegram/telegramFailureRetry.js +8 -0
  105. package/dist/connectors/telegram/telegramFailureRetry.js.map +1 -1
  106. package/dist/connectors/telegram/topicIndicator.d.ts +86 -0
  107. package/dist/connectors/telegram/topicIndicator.d.ts.map +1 -0
  108. package/dist/connectors/telegram/topicIndicator.js +490 -0
  109. package/dist/connectors/telegram/topicIndicator.js.map +1 -0
  110. package/dist/connectors/telegram/waitingTopicRenames.d.ts +39 -0
  111. package/dist/connectors/telegram/waitingTopicRenames.d.ts.map +1 -0
  112. package/dist/connectors/telegram/waitingTopicRenames.js +48 -0
  113. package/dist/connectors/telegram/waitingTopicRenames.js.map +1 -0
  114. package/dist/i18n/de.d.ts.map +1 -1
  115. package/dist/i18n/de.js +51 -0
  116. package/dist/i18n/de.js.map +1 -1
  117. package/dist/i18n/en.d.ts.map +1 -1
  118. package/dist/i18n/en.js +51 -0
  119. package/dist/i18n/en.js.map +1 -1
  120. package/dist/i18n/es.d.ts.map +1 -1
  121. package/dist/i18n/es.js +51 -0
  122. package/dist/i18n/es.js.map +1 -1
  123. package/dist/i18n/fr.d.ts.map +1 -1
  124. package/dist/i18n/fr.js +51 -0
  125. package/dist/i18n/fr.js.map +1 -1
  126. package/dist/i18n/hi.d.ts.map +1 -1
  127. package/dist/i18n/hi.js +51 -0
  128. package/dist/i18n/hi.js.map +1 -1
  129. package/dist/i18n/ja.d.ts.map +1 -1
  130. package/dist/i18n/ja.js +51 -0
  131. package/dist/i18n/ja.js.map +1 -1
  132. package/dist/i18n/ka.d.ts.map +1 -1
  133. package/dist/i18n/ka.js +51 -0
  134. package/dist/i18n/ka.js.map +1 -1
  135. package/dist/i18n/pt.d.ts.map +1 -1
  136. package/dist/i18n/pt.js +51 -0
  137. package/dist/i18n/pt.js.map +1 -1
  138. package/dist/i18n/ru.d.ts.map +1 -1
  139. package/dist/i18n/ru.js +51 -0
  140. package/dist/i18n/ru.js.map +1 -1
  141. package/dist/i18n/uk.d.ts.map +1 -1
  142. package/dist/i18n/uk.js +51 -0
  143. package/dist/i18n/uk.js.map +1 -1
  144. package/dist/i18n/uz.d.ts.map +1 -1
  145. package/dist/i18n/uz.js +51 -0
  146. package/dist/i18n/uz.js.map +1 -1
  147. package/dist/i18n/zh.d.ts.map +1 -1
  148. package/dist/i18n/zh.js +51 -0
  149. package/dist/i18n/zh.js.map +1 -1
  150. package/dist/i18n.d.ts.map +1 -1
  151. package/dist/i18n.js +2 -1
  152. package/dist/i18n.js.map +1 -1
  153. package/dist/instanceSettings.d.ts +19 -1
  154. package/dist/instanceSettings.d.ts.map +1 -1
  155. package/dist/instanceSettings.js +35 -2
  156. package/dist/instanceSettings.js.map +1 -1
  157. package/dist/openCodeOpenQuestion.d.ts +12 -4
  158. package/dist/openCodeOpenQuestion.d.ts.map +1 -1
  159. package/dist/openCodeOpenQuestion.js +16 -7
  160. package/dist/openCodeOpenQuestion.js.map +1 -1
  161. package/dist/openCodeQuestionFlow.d.ts +10 -2
  162. package/dist/openCodeQuestionFlow.d.ts.map +1 -1
  163. package/dist/openCodeQuestionFlow.js +27 -5
  164. package/dist/openCodeQuestionFlow.js.map +1 -1
  165. package/dist/postToSession.d.ts +9 -0
  166. package/dist/postToSession.d.ts.map +1 -1
  167. package/dist/postToSession.js +15 -2
  168. package/dist/postToSession.js.map +1 -1
  169. package/dist/requests/requestHeader.d.ts.map +1 -1
  170. package/dist/requests/requestHeader.js +1 -0
  171. package/dist/requests/requestHeader.js.map +1 -1
  172. package/dist/requests/types.d.ts +4 -1
  173. package/dist/requests/types.d.ts.map +1 -1
  174. package/dist/requests/wakeUpEngine.d.ts +31 -1
  175. package/dist/requests/wakeUpEngine.d.ts.map +1 -1
  176. package/dist/requests/wakeUpEngine.js +94 -2
  177. package/dist/requests/wakeUpEngine.js.map +1 -1
  178. package/dist/requests/wakeUpRules.d.ts +7 -0
  179. package/dist/requests/wakeUpRules.d.ts.map +1 -1
  180. package/dist/requests/wakeUpRules.js +14 -0
  181. package/dist/requests/wakeUpRules.js.map +1 -1
  182. package/dist/scheduler/engine.d.ts +17 -4
  183. package/dist/scheduler/engine.d.ts.map +1 -1
  184. package/dist/scheduler/engine.js +55 -10
  185. package/dist/scheduler/engine.js.map +1 -1
  186. package/dist/scheduler/mcpBoot.d.ts +6 -2
  187. package/dist/scheduler/mcpBoot.d.ts.map +1 -1
  188. package/dist/scheduler/mcpBoot.js +7 -1
  189. package/dist/scheduler/mcpBoot.js.map +1 -1
  190. package/dist/scheduler/mcpSurface.d.ts.map +1 -1
  191. package/dist/scheduler/mcpSurface.js +18 -9
  192. package/dist/scheduler/mcpSurface.js.map +1 -1
  193. package/dist/sendErrorClassifier.d.ts +6 -0
  194. package/dist/sendErrorClassifier.d.ts.map +1 -1
  195. package/dist/sendErrorClassifier.js +9 -0
  196. package/dist/sendErrorClassifier.js.map +1 -1
  197. package/dist/startupPromptBuffer.d.ts +8 -8
  198. package/dist/startupPromptBuffer.d.ts.map +1 -1
  199. package/dist/startupPromptBuffer.js +7 -5
  200. package/dist/startupPromptBuffer.js.map +1 -1
  201. package/dist/state.d.ts +98 -6
  202. package/dist/state.d.ts.map +1 -1
  203. package/dist/state.js +149 -7
  204. package/dist/state.js.map +1 -1
  205. package/dist/testTimings.d.ts +12 -3
  206. package/dist/testTimings.d.ts.map +1 -1
  207. package/dist/testTimings.js +23 -2
  208. package/dist/testTimings.js.map +1 -1
  209. package/dist/threadRouting.d.ts +23 -0
  210. package/dist/threadRouting.d.ts.map +1 -1
  211. package/dist/threadRouting.js +28 -0
  212. package/dist/threadRouting.js.map +1 -1
  213. package/dist/todos/registry.d.ts +2 -0
  214. package/dist/todos/registry.d.ts.map +1 -1
  215. package/dist/todos/registry.js +3 -1
  216. package/dist/todos/registry.js.map +1 -1
  217. package/dist/trackers/taskAgentSlots.d.ts +42 -3
  218. package/dist/trackers/taskAgentSlots.d.ts.map +1 -1
  219. package/dist/trackers/taskAgentSlots.js +31 -11
  220. package/dist/trackers/taskAgentSlots.js.map +1 -1
  221. package/dist/types.d.ts +95 -0
  222. package/dist/types.d.ts.map +1 -1
  223. package/dist/utils/claudeCompactHook.d.ts +3 -1
  224. package/dist/utils/claudeCompactHook.d.ts.map +1 -1
  225. package/dist/utils/claudeCompactHook.js +3 -1
  226. package/dist/utils/claudeCompactHook.js.map +1 -1
  227. package/dist/utils/claudeLimitSwitch.d.ts +1 -1
  228. package/dist/utils/claudeLimitSwitch.d.ts.map +1 -1
  229. package/dist/utils/claudeLimitSwitch.js +1 -1
  230. package/dist/utils/claudeLimitSwitch.js.map +1 -1
  231. package/dist/utils/claudeProfileSync.d.ts +88 -0
  232. package/dist/utils/claudeProfileSync.d.ts.map +1 -0
  233. package/dist/utils/claudeProfileSync.js +198 -0
  234. package/dist/utils/claudeProfileSync.js.map +1 -0
  235. package/dist/utils/claudeProfiles.d.ts +101 -6
  236. package/dist/utils/claudeProfiles.d.ts.map +1 -1
  237. package/dist/utils/claudeProfiles.js +288 -23
  238. package/dist/utils/claudeProfiles.js.map +1 -1
  239. package/dist/utils/claudeUsageRefresher.d.ts +8 -1
  240. package/dist/utils/claudeUsageRefresher.d.ts.map +1 -1
  241. package/dist/utils/claudeUsageRefresher.js +11 -1
  242. package/dist/utils/claudeUsageRefresher.js.map +1 -1
  243. package/dist/utils/cutButtonLabel.d.ts +7 -0
  244. package/dist/utils/cutButtonLabel.d.ts.map +1 -0
  245. package/dist/utils/cutButtonLabel.js +17 -0
  246. package/dist/utils/cutButtonLabel.js.map +1 -0
  247. package/dist/utils/fileSendPlan.d.ts +30 -8
  248. package/dist/utils/fileSendPlan.d.ts.map +1 -1
  249. package/dist/utils/fileSendPlan.js +37 -12
  250. package/dist/utils/fileSendPlan.js.map +1 -1
  251. package/dist/utils/fileSendService.d.ts +1 -1
  252. package/dist/utils/fileSendService.d.ts.map +1 -1
  253. package/dist/utils/fileSendService.js +9 -1
  254. package/dist/utils/fileSendService.js.map +1 -1
  255. package/dist/utils/imageDimensions.d.ts +32 -0
  256. package/dist/utils/imageDimensions.d.ts.map +1 -0
  257. package/dist/utils/imageDimensions.js +181 -0
  258. package/dist/utils/imageDimensions.js.map +1 -0
  259. package/dist/utils/jsonStreamHost.d.ts +35 -9
  260. package/dist/utils/jsonStreamHost.d.ts.map +1 -1
  261. package/dist/utils/jsonStreamHost.js +59 -16
  262. package/dist/utils/jsonStreamHost.js.map +1 -1
  263. package/dist/utils/limitSwitchPlan.d.ts +44 -0
  264. package/dist/utils/limitSwitchPlan.d.ts.map +1 -0
  265. package/dist/utils/limitSwitchPlan.js +54 -0
  266. package/dist/utils/limitSwitchPlan.js.map +1 -0
  267. package/dist/utils/lostWork.d.ts +8 -2
  268. package/dist/utils/lostWork.d.ts.map +1 -1
  269. package/dist/utils/lostWork.js +9 -5
  270. package/dist/utils/lostWork.js.map +1 -1
  271. package/dist/utils/promptDelivery.d.ts +11 -2
  272. package/dist/utils/promptDelivery.d.ts.map +1 -1
  273. package/dist/utils/promptDelivery.js +3 -3
  274. package/dist/utils/promptDelivery.js.map +1 -1
  275. package/dist/utils/questionWaitChoices.d.ts +20 -0
  276. package/dist/utils/questionWaitChoices.d.ts.map +1 -0
  277. package/dist/utils/questionWaitChoices.js +31 -0
  278. package/dist/utils/questionWaitChoices.js.map +1 -0
  279. package/dist/utils/questionWaitPlan.d.ts +166 -0
  280. package/dist/utils/questionWaitPlan.d.ts.map +1 -0
  281. package/dist/utils/questionWaitPlan.js +237 -0
  282. package/dist/utils/questionWaitPlan.js.map +1 -0
  283. package/dist/utils/replyQuote.d.ts +10 -0
  284. package/dist/utils/replyQuote.d.ts.map +1 -1
  285. package/dist/utils/replyQuote.js +18 -7
  286. package/dist/utils/replyQuote.js.map +1 -1
  287. package/dist/utils/talkerAccess.d.ts +2 -2
  288. package/dist/utils/talkerAccess.d.ts.map +1 -1
  289. package/dist/utils/talkerAccess.js +5 -4
  290. package/dist/utils/talkerAccess.js.map +1 -1
  291. package/dist/utils/telegramError.d.ts +6 -0
  292. package/dist/utils/telegramError.d.ts.map +1 -1
  293. package/dist/utils/telegramError.js +12 -0
  294. package/dist/utils/telegramError.js.map +1 -1
  295. package/dist/utils/topicAccessScreenPlan.d.ts +1 -1
  296. package/dist/utils/topicAccessScreenPlan.d.ts.map +1 -1
  297. package/dist/utils/topicAccessScreenPlan.js +3 -7
  298. package/dist/utils/topicAccessScreenPlan.js.map +1 -1
  299. package/dist/utils/topicIndicatorPlan.d.ts +143 -0
  300. package/dist/utils/topicIndicatorPlan.d.ts.map +1 -0
  301. package/dist/utils/topicIndicatorPlan.js +202 -0
  302. package/dist/utils/topicIndicatorPlan.js.map +1 -0
  303. package/dist/utils/topicIndicatorSources.d.ts +40 -0
  304. package/dist/utils/topicIndicatorSources.d.ts.map +1 -0
  305. package/dist/utils/topicIndicatorSources.js +31 -0
  306. package/dist/utils/topicIndicatorSources.js.map +1 -0
  307. package/dist/utils/topicStatusPlan.d.ts +90 -0
  308. package/dist/utils/topicStatusPlan.d.ts.map +1 -0
  309. package/dist/utils/topicStatusPlan.js +160 -0
  310. package/dist/utils/topicStatusPlan.js.map +1 -0
  311. package/npm-shrinkwrap.json +2 -2
  312. package/package.json +2 -2
@@ -0,0 +1,637 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.setAsideRetryLimit = void 0;
4
+ exports.createQuestionSetAside = createQuestionSetAside;
5
+ const sessionKey_1 = require("../../../sessionKey");
6
+ const i18n_1 = require("../../../i18n");
7
+ const questionWaitPlan_1 = require("../../../utils/questionWaitPlan");
8
+ const questionWaitChoices_1 = require("../../../utils/questionWaitChoices");
9
+ const authorMark_1 = require("../../../utils/authorMark");
10
+ const inbound_1 = require("../inbound");
11
+ const callbackMessage_1 = require("./callbackMessage");
12
+ const callbackToast_1 = require("./callbackToast");
13
+ const questionKeyboards_1 = require("../questionKeyboards");
14
+ /** The prefix of a set-aside question's button data: `qs_<record id>_<option index>`. */
15
+ const setAsideButtonPrefix = 'qs_';
16
+ /** After the agent's server could not confirm a waiting question, or did not take what sets it aside, it is tried again at most this many times (a pause of {@link setAsideRetryDelayMs} between). */
17
+ exports.setAsideRetryLimit = 3;
18
+ /**
19
+ * @description Build the question set-aside over its ports. It returns the timer's arm and clear (the bot arms it when the
20
+ * agent asks and when a restart restores a waiting question, and clears it with the pending question) and the set-aside
21
+ * itself, which the idle fire and the asked-again check call too.
22
+ */
23
+ function createQuestionSetAside(ports) {
24
+ const { getState, withThreadLocale, authoriseSpeaker, replyToThread, pendingQuestions, getThreadAdapter, runQuestionLifecycleOp, setPendingQuestion, clearPendingQuestion, releasePendingQuestionToSetAside, editQuestionMessageWithNote, closeQuestionMessage, unpinMessage, pinMessageSilently, sendQuestionMessage, deliverLateAnswer, markNeedsNewMessage, getQuestionWaitChoice, shortenedWaitMs, postQuestionAnew, } = ports;
25
+ const retryDelayMs = ports.retryDelayMs ?? questionWaitChoices_1.setAsideRetryDelayMs;
26
+ /** One timer per waiting question, by conversation: it fires at `askedAt + wait`, whatever the agent's process does. */
27
+ const timers = new Map();
28
+ /** How many times the wait of a question has ended again for want of the server's word, by conversation and request. */
29
+ const retryAttempts = new Map();
30
+ /** How many times the reply that set a question aside failed to reach the agent's server, by conversation and request. */
31
+ const replyFailures = new Map();
32
+ /** One pending re-try of such a reply per conversation. */
33
+ const replyRetryTimers = new Map();
34
+ /** The set-aside records whose message says the server did not confirm the «go on» reply, by conversation and record id (in memory only: see {@link SetAsideNoteState}). */
35
+ const notTakenNotes = new Set();
36
+ /** What is counted for a question: the conversation and the request (or, for the notes of a record, the record id). */
37
+ const getAttemptKey = (key, id) => `${(0, sessionKey_1.keyToString)(key)}:${id}`;
38
+ /** Forget every count of the conversation's questions (its question was answered, closed or timed again). */
39
+ function forgetAttempts(key) {
40
+ const prefix = `${(0, sessionKey_1.keyToString)(key)}:`;
41
+ for (const counts of [retryAttempts, replyFailures]) {
42
+ for (const attemptKey of [...counts.keys()])
43
+ if (attemptKey.startsWith(prefix))
44
+ counts.delete(attemptKey);
45
+ }
46
+ for (const recordKey of [...notTakenNotes])
47
+ if (recordKey.startsWith(prefix))
48
+ notTakenNotes.delete(recordKey);
49
+ }
50
+ /** The conversation's open set-aside questions, oldest first. */
51
+ function getSetAsideRecords(key) {
52
+ return getState().getSetAsideQuestions()[(0, sessionKey_1.keyToString)(key)] ?? [];
53
+ }
54
+ /** The option buttons of a set-aside question: their data names the record, `qs_<record id>_<option index>`. */
55
+ function buildSetAsideKeyboard(record, question) {
56
+ return (0, questionKeyboards_1.buildQuestionOptionsKeyboard)(question, (optionIndex) => `${setAsideButtonPrefix}${record.id}_${optionIndex}`);
57
+ }
58
+ function stopSetAsideTimer(key) {
59
+ const kStr = (0, sessionKey_1.keyToString)(key);
60
+ const timer = timers.get(kStr);
61
+ if (timer)
62
+ clearTimeout(timer);
63
+ timers.delete(kStr);
64
+ }
65
+ /** The conversation's question left the pending state, or its wait is timed afresh: no timer, and no count of tries made for it. */
66
+ function clearQuestionSetAsideTimer(key) {
67
+ stopSetAsideTimer(key);
68
+ forgetAttempts(key);
69
+ }
70
+ /** Set a question aside after `delayMs`: the one timer of the conversation — the wait's own, and the wait ending again after the server's silence. */
71
+ function armSetAsideTimer(key, requestId, delayMs) {
72
+ stopSetAsideTimer(key);
73
+ const kStr = (0, sessionKey_1.keyToString)(key);
74
+ const timer = setTimeout(() => {
75
+ timers.delete(kStr);
76
+ void withThreadLocale(key, () => setPendingQuestionAside(key, requestId))
77
+ .catch((error) => console.error('[questionSetAside] setting the question aside failed:', error));
78
+ }, delayMs);
79
+ timer.unref();
80
+ timers.set(kStr, timer);
81
+ }
82
+ /**
83
+ * @description Arm the timer of the conversation's waiting question: at `askedAt + wait` — the original ask moment, so a restart
84
+ * that restores the question arms the REST of its wait, not a new one — the question is set aside. No timer for a wait that
85
+ * never ends («Wait for my answer»). A question saved before `askedAt` existed counts from now (and keeps that from then on).
86
+ */
87
+ function armQuestionSetAsideTimer(key) {
88
+ clearQuestionSetAsideTimer(key);
89
+ const kStr = (0, sessionKey_1.keyToString)(key);
90
+ const pending = pendingQuestions.get(kStr);
91
+ if (!pending)
92
+ return;
93
+ const nowMs = Date.now();
94
+ if (pending.askedAt === undefined) {
95
+ pending.askedAt = nowMs;
96
+ setPendingQuestion(key, pending);
97
+ }
98
+ const delayMs = (0, questionWaitPlan_1.getQuestionSetAsideDelayMs)(pending.askedAt, getQuestionWaitChoice(key), nowMs, shortenedWaitMs);
99
+ if (delayMs === null)
100
+ return;
101
+ armSetAsideTimer(key, pending.data.requestId, delayMs);
102
+ }
103
+ /**
104
+ * @description Set the conversation's waiting question `requestId` aside: the agent is told to go on without it, the question
105
+ * leaves `pendingQuestions` (so everything that asks «is the agent blocked on a question?» now says no), becomes a record of
106
+ * the conversation's set-aside list, and its message is edited to say so — keeping its buttons (their data now names the
107
+ * record) and its pin. A sixth open question closes the oldest as «not answered». Resolves whether the question was set aside:
108
+ * `false` — and nothing set aside — when it is no longer the one waiting (answered or closed while the timer waited its turn
109
+ * in the lifecycle queue, or the agent asked the next one meanwhile) or the backend cannot set a question aside.
110
+ *
111
+ * When the bot holds the question but the adapter says it holds none, what that means depends on the backend:
112
+ * - json-stream: the CLI's own question is the authority (the bot reads its sidecar before it restores its copy), so none is held
113
+ * — the bot's copy is stale (the agent was told and the bot died before it saved): one log line, and it is closed as «not
114
+ * answered», never left as a waiting question nothing can end;
115
+ * - OpenCode: the adapter only CACHES the server's registry (a reattach that could not read it leaves it empty), so «none» means
116
+ * «not known»: the server is asked (`resyncOpenQuestion`). It holds the question → the adapter takes it and the question is set
117
+ * aside after all; it confirms there is none → the bot's copy is closed as above; it cannot tell → nothing is closed, one log
118
+ * line, and the wait ends again after {@link setAsideRetryDelayMs}, at most {@link setAsideRetryLimit} times.
119
+ */
120
+ async function setPendingQuestionAside(key, requestId) {
121
+ return runQuestionLifecycleOp(key, async () => {
122
+ const kStr = (0, sessionKey_1.keyToString)(key);
123
+ if (pendingQuestions.get(kStr)?.data.requestId !== requestId)
124
+ return false;
125
+ const adapter = getThreadAdapter(key);
126
+ if (!adapter.setQuestionAside)
127
+ return false;
128
+ // Taken BEFORE the adapter is told: from the moment it is told to the removal of the question from the pending state nothing
129
+ // is awaited, so a question the agent asks next (its handler runs on the event, outside this queue) cannot arrive in between
130
+ // and be removed with this one. The number only has to be unique, so one that is not used is no loss.
131
+ const sequence = await getState().takeNextSetAsideQuestionSequence(key);
132
+ const pending = pendingQuestions.get(kStr);
133
+ // The agent asked the next question while the counter was taken: this one is gone from the pending state already.
134
+ if (!pending || pending.data.requestId !== requestId)
135
+ return false;
136
+ const nowMs = Date.now();
137
+ const askedAtMs = pending.askedAt ?? nowMs;
138
+ const text = (0, questionWaitPlan_1.buildQuestionSetAsideText)({ questions: pending.data.questions, answers: pending.answers, askedAtMs, nowMs });
139
+ const recordId = (0, questionWaitPlan_1.createSetAsideQuestionId)(sequence);
140
+ // The adapter checks the request id once more, against the question it holds.
141
+ if (!adapter.setQuestionAside(key, requestId, text, pending.answers, handleReplySettled(key, requestId, recordId))) {
142
+ const resynced = await settleQuestionTheAdapterDoesNotHold(key, adapter, pending, text, recordId);
143
+ if (resynced === 'ended')
144
+ return false;
145
+ }
146
+ forgetAttempt(key, requestId);
147
+ const record = {
148
+ id: recordId,
149
+ messageId: pending.messageId,
150
+ // A re-posted question has two messages: the live copy (`messageId`) and the original it left up.
151
+ ...(pending.originalMessageId != null && pending.originalMessageId !== pending.messageId ? { originalMessageId: pending.originalMessageId } : {}),
152
+ questions: pending.data.questions,
153
+ answers: pending.answers,
154
+ lateFromIndex: pending.answers.findIndex((answer) => answer === null),
155
+ askedAt: askedAtMs,
156
+ setAsideAt: nowMs,
157
+ };
158
+ const released = releasePendingQuestionToSetAside(key);
159
+ markNeedsNewMessage(key);
160
+ await released;
161
+ const { records, evicted } = (0, questionWaitPlan_1.addSetAsideQuestion)(getSetAsideRecords(key), record);
162
+ await getState().setSetAsideQuestions(key, records);
163
+ await showQuestionSetAside(key, record);
164
+ for (const closedRecord of evicted)
165
+ await closeSetAsideRecord(key, closedRecord, 'unanswered');
166
+ // A question the agent's server holds BESIDE this one (its parallel tool calls) was never shown: it is handed to the bot now, as
167
+ // the question that waits. Not awaited — the server may still list this question for a moment, so it is left out.
168
+ void adapter.surfaceOpenQuestion?.(key, requestId);
169
+ return true;
170
+ });
171
+ }
172
+ /** Forget the counts of one question: it was told to go on, or it is gone. */
173
+ function forgetAttempt(key, requestId) {
174
+ retryAttempts.delete(getAttemptKey(key, requestId));
175
+ replyFailures.delete(getAttemptKey(key, requestId));
176
+ }
177
+ /**
178
+ * @description What the agent's server made of the reply that set question `requestId` aside (the one that became the record
179
+ * `recordId`), as `setQuestionAside`'s `onSettled` hands it over. A reply the server took ends the count of failures — and, when the
180
+ * question's message had been told «the server did not take it», takes that note back. One it did not take is
181
+ * {@link countReplyFailure}.
182
+ */
183
+ function handleReplySettled(key, requestId, recordId) {
184
+ return (isSent) => {
185
+ if (isSent) {
186
+ replyFailures.delete(getAttemptKey(key, requestId));
187
+ if (notTakenNotes.delete(getAttemptKey(key, recordId)))
188
+ void rewriteSetAsideNote(key, recordId, 'wentOn');
189
+ return;
190
+ }
191
+ countReplyFailure(key, requestId, recordId, `did not take the reply that sets the question ${requestId} aside`);
192
+ };
193
+ }
194
+ /**
195
+ * One more failure to get the question `requestId` aside on the agent's server — its reply was not taken, or the server could not be
196
+ * read to find the question again. The question stays OPEN there: the topic says «the agent went on» and nothing waits on the bot's
197
+ * side, yet the agent stands still on it. After a pause the question is handed to the bot again (`surfaceOpenQuestion`), which finds
198
+ * its record and tells the agent once more as a question asked again ({@link surfaceQuestionAgain}). At most
199
+ * {@link setAsideRetryLimit} times; then the topic is told — a message, and the pinned message's own note, which no longer says the
200
+ * agent went on but that the server did not confirm it — so a stuck agent is not left to a console line.
201
+ */
202
+ function countReplyFailure(key, requestId, recordId, cause) {
203
+ const attemptKey = getAttemptKey(key, requestId);
204
+ const failures = (replyFailures.get(attemptKey) ?? 0) + 1;
205
+ replyFailures.set(attemptKey, failures);
206
+ const kStr = (0, sessionKey_1.keyToString)(key);
207
+ if (failures > exports.setAsideRetryLimit) {
208
+ console.warn(`[questionSetAside] ${kStr}: the agent's server ${cause} ${failures} times; it may still wait for it`);
209
+ replyFailures.delete(attemptKey);
210
+ clearTimeout(replyRetryTimers.get(kStr));
211
+ replyRetryTimers.delete(kStr);
212
+ notTakenNotes.add(getAttemptKey(key, recordId));
213
+ void rewriteSetAsideNote(key, recordId, 'unconfirmed');
214
+ void replyToThread(key, withThreadLocale(key, () => (0, i18n_1.t)('agent.set_aside_reply_failed_notice')));
215
+ return;
216
+ }
217
+ console.warn(`[questionSetAside] ${kStr}: the agent's server ${cause}; trying again in ${retryDelayMs / 1000} s (try ${failures} of ${exports.setAsideRetryLimit})`);
218
+ clearTimeout(replyRetryTimers.get(kStr));
219
+ const timer = setTimeout(() => {
220
+ replyRetryTimers.delete(kStr);
221
+ void surfaceQuestionAgain(key, requestId, recordId);
222
+ }, retryDelayMs);
223
+ timer.unref();
224
+ replyRetryTimers.set(kStr, timer);
225
+ }
226
+ /**
227
+ * The pause after a reply the server did not take is over: the server's own question is handed to the bot again. When it is
228
+ * shown (`emitted`) the telling runs once more and its outcome comes back through {@link handleReplySettled}; when the server holds
229
+ * none any more nothing waits and the count ends; when it could not be read the question may still be open there, which is another
230
+ * failure — the chain never stops silently on a read that failed.
231
+ */
232
+ async function surfaceQuestionAgain(key, requestId, recordId) {
233
+ const outcome = await getThreadAdapter(key).surfaceOpenQuestion?.(key);
234
+ if (outcome === 'readFailed')
235
+ countReplyFailure(key, requestId, recordId, `could not be read to find the question ${requestId} again`);
236
+ else if (outcome === 'none')
237
+ replyFailures.delete(getAttemptKey(key, requestId));
238
+ }
239
+ /**
240
+ * The adapter would not set the bot's waiting question aside (see {@link setPendingQuestionAside} for what that means per backend).
241
+ * Resolves `told` when the adapter took it on a second try after it re-read the server's registry — the caller goes on to save the
242
+ * record — and `ended` when it did not: the bot's copy was closed (nothing is held), or left waiting with one more try armed.
243
+ * Nothing is awaited between the second try and the return, like the first.
244
+ */
245
+ async function settleQuestionTheAdapterDoesNotHold(key, adapter, pending, text, recordId) {
246
+ const kStr = (0, sessionKey_1.keyToString)(key);
247
+ const { requestId } = pending.data;
248
+ // A backend with no registry of its own to ask holds exactly what it says it holds.
249
+ const server = adapter.resyncOpenQuestion ? await adapter.resyncOpenQuestion(key, requestId) : 'none';
250
+ // The agent asked the next question, or this one was answered, while the server was asked: it is not this one's business any more.
251
+ if (pendingQuestions.get(kStr) !== pending)
252
+ return 'ended';
253
+ if (server === 'held' && adapter.setQuestionAside?.(key, requestId, text, pending.answers, handleReplySettled(key, requestId, recordId)))
254
+ return 'told';
255
+ if (server === 'none') {
256
+ await dropQuestionTheAdapterDoesNotHold(key, adapter, pending);
257
+ return 'ended';
258
+ }
259
+ const attemptKey = getAttemptKey(key, requestId);
260
+ const attempt = (retryAttempts.get(attemptKey) ?? 0) + 1;
261
+ retryAttempts.set(attemptKey, attempt);
262
+ const isRetried = attempt <= exports.setAsideRetryLimit;
263
+ console.warn(`[questionSetAside] ${kStr}: the agent's server did not confirm the question ${requestId} (${server}); it stays waiting${isRetried ? `, the wait ends again in ${retryDelayMs / 1000} s (try ${attempt} of ${exports.setAsideRetryLimit})` : ', no more tries'}`);
264
+ if (isRetried)
265
+ armRetry(key, requestId);
266
+ return 'ended';
267
+ }
268
+ /** The wait of a question ends again after the server did not confirm it. */
269
+ function armRetry(key, requestId) {
270
+ armSetAsideTimer(key, requestId, retryDelayMs);
271
+ }
272
+ /**
273
+ * @description The idle fire (`compaction.ts`) meets a question that still waits: it is set aside NOW — earlier than its wait —
274
+ * instead of the idle compaction rejecting it, compacting, stopping the process and asking it again. Not for «Wait for my
275
+ * answer» (today's flow stays for that choice), and not when nothing waits. Resolves whether the question was set aside; `false`
276
+ * leaves everything as it was, so the caller goes on with the flow it had.
277
+ */
278
+ async function setPendingQuestionAsideAtIdle(key) {
279
+ const pending = pendingQuestions.get((0, sessionKey_1.keyToString)(key));
280
+ if (!pending || getQuestionWaitChoice(key) === 'untilAnswered')
281
+ return false;
282
+ return setPendingQuestionAside(key, pending.data.requestId);
283
+ }
284
+ /**
285
+ * @description The agent asks a question whose set-aside copy is still open in the topic (`getSetAsideRecordAskedAgain`) — it did
286
+ * not take «do not ask it again». It is told AT ONCE, in the set-aside text worded «still open», that it is the same question and
287
+ * nobody answered it yet; nothing else happens: no second message, no pin, no record, no timer, nothing waiting. Returns whether it
288
+ * took the question over (the caller posts nothing then); the telling runs in the lifecycle queue, after whatever is in flight. When
289
+ * by then the record is gone (answered or closed meanwhile) or the agent's side cannot be told, the question is posted like a new
290
+ * one ({@link QuestionSetAsidePorts.postQuestionAnew}): an agent left blocked on a question nobody sees is the worse failure.
291
+ */
292
+ function answerQuestionAskedAgain(key, questionData) {
293
+ if (!(0, questionWaitPlan_1.getSetAsideRecordAskedAgain)(getSetAsideRecords(key), questionData.questions))
294
+ return false;
295
+ void runQuestionLifecycleOp(key, () => tellAgentQuestionIsStillOpen(key, questionData))
296
+ .catch((error) => {
297
+ console.error('[questionSetAside] telling the agent its question is still open failed:', error);
298
+ return false;
299
+ })
300
+ .then((isTold) => {
301
+ if (isTold)
302
+ return;
303
+ console.warn(`[questionSetAside] ${(0, sessionKey_1.keyToString)(key)}: the question ${questionData.requestId} the agent asked again could not be answered as «still open»; it is posted as a new one`);
304
+ postQuestionAnew(key, questionData);
305
+ });
306
+ return true;
307
+ }
308
+ /** The record the question repeats is read AGAIN, now that the queue got to it; resolves whether the agent was told. */
309
+ async function tellAgentQuestionIsStillOpen(key, questionData) {
310
+ const found = (0, questionWaitPlan_1.getSetAsideRecordAskedAgain)(getSetAsideRecords(key), questionData.questions);
311
+ if (!found)
312
+ return false;
313
+ const { record, answers } = found;
314
+ const text = (0, questionWaitPlan_1.buildQuestionSetAsideText)({ questions: record.questions, answers: record.answers, askedAtMs: record.askedAt, nowMs: Date.now(), isAlreadyOpen: true });
315
+ return getThreadAdapter(key).setQuestionAside?.(key, questionData.requestId, text, answers, handleReplySettled(key, questionData.requestId, record.id)) === true;
316
+ }
317
+ /**
318
+ * The bot's copy of a waiting question that the agent's side confirms it holds no such question for: stale, so it ends as «not
319
+ * answered». The question the agent's side holds INSTEAD (a backend whose server can hold another one than the bot knew of) was
320
+ * never shown: it is handed to the bot now, after the stale copy is gone, so it shows as the question that waits.
321
+ */
322
+ async function dropQuestionTheAdapterDoesNotHold(key, adapter, pending) {
323
+ console.warn(`[questionSetAside] ${(0, sessionKey_1.keyToString)(key)}: the agent holds no question ${pending.data.requestId}, so there is nothing to set aside; the bot's copy is closed as not answered`);
324
+ forgetAttempt(key, pending.data.requestId);
325
+ clearPendingQuestion(key);
326
+ const question = pending.data.questions[pending.currentIndex];
327
+ if (pending.messageId !== null && question)
328
+ await closeQuestionMessage(key, pending.messageId, question, 'unanswered');
329
+ await adapter.surfaceOpenQuestion?.(key);
330
+ }
331
+ /**
332
+ * @description Edit the question's message to the set-aside look: the question as asked, a note under it («the agent went on
333
+ * without your answer — you can still answer», or, when the agent's server did not confirm the message that tells it to go on, «the server
334
+ * did not confirm it — if the agent seems stuck, send it any message»), and the option buttons, whose data now names the record. The message is not
335
+ * re-posted, not deleted, not unpinned. When the edit fails the old buttons never stay (they would answer the agent's NEXT
336
+ * question): they are replaced by the record's, or taken off. The record is saved and open either way.
337
+ */
338
+ async function showQuestionSetAside(key, record, state = 'wentOn') {
339
+ const target = (0, questionWaitPlan_1.getSetAsideAnswerTarget)(record);
340
+ if (record.messageId === null || !target)
341
+ return;
342
+ const note = withThreadLocale(key, () => (0, i18n_1.t)(state === 'wentOn' ? 'agent.question_set_aside_note' : 'agent.question_set_aside_not_taken_note'));
343
+ const isEdited = await editQuestionMessageWithNote(key, record.messageId, target.question, note, buildSetAsideKeyboard(record, target.question));
344
+ if (!isEdited)
345
+ console.warn(`[questionSetAside] the note could not be written under the question (record ${record.id})`);
346
+ }
347
+ /**
348
+ * The note of record `recordId`'s message changes with what became of the reply that told the agent to go on. Decided inside the
349
+ * lifecycle queue against the record as it is THEN: one that was answered or closed meanwhile has a message that is no longer the
350
+ * note's to rewrite — its «✅ Answer» must stay.
351
+ */
352
+ async function rewriteSetAsideNote(key, recordId, state) {
353
+ try {
354
+ await runQuestionLifecycleOp(key, async () => {
355
+ const record = getSetAsideRecords(key).find((candidate) => candidate.id === recordId);
356
+ if (record)
357
+ await showQuestionSetAside(key, record, state);
358
+ });
359
+ }
360
+ catch (error) {
361
+ console.error(`[questionSetAside] ${(0, sessionKey_1.keyToString)(key)}: rewriting the note of the set-aside question ${recordId} failed:`, error);
362
+ }
363
+ }
364
+ /**
365
+ * @description Whether `messageId` is a message of one of the conversation's set-aside questions. A stale `qa_<i>_<j>` button on
366
+ * such a message (its edit to the set-aside look never landed) must never answer the question the agent asks next.
367
+ */
368
+ function checkIsSetAsideQuestionMessage(key, messageId) {
369
+ return getSetAsideRecords(key).some((record) => (0, questionWaitPlan_1.checkIsSetAsideRecordMessage)(record, messageId));
370
+ }
371
+ /**
372
+ * @description End a set-aside record that is no longer open (evicted by a sixth question, ended with its conversation): its
373
+ * message is closed without deleting it, and its pin is released.
374
+ */
375
+ async function closeSetAsideRecord(key, record, ending) {
376
+ notTakenNotes.delete(getAttemptKey(key, record.id));
377
+ const question = (0, questionWaitPlan_1.getSetAsideAnswerTarget)(record)?.question ?? record.questions[0];
378
+ if (record.messageId === null || !question)
379
+ return;
380
+ await closeQuestionMessage(key, record.messageId, question, ending);
381
+ await unpinMessage(key, record.messageId);
382
+ }
383
+ // ── a late answer ──
384
+ /**
385
+ * Who answered, as the agent must read it: the description of a topic member (`topic member "Tess Talker" (@tess)`), `undefined`
386
+ * for the operator. The late-answer message is the BOT's block — a member's author mark ahead of it would end at its own header
387
+ * («everything after it up to the next line that starts with `[` is theirs»), so the attribution travels INSIDE each answer, as
388
+ * it does for the answer to a waiting question.
389
+ */
390
+ function getAnsweringMember(from, role) {
391
+ return role === 'talker' && from ? (0, inbound_1.getTelegramTalkerContext)(from).nonOperatorSender : undefined;
392
+ }
393
+ /** The records whose last answer is on its way to the agent: a second tap on one of them answers nothing. */
394
+ const answeringRecords = new Set();
395
+ /** The late answers of a record — the questions from `lateFromIndex` on — with the one given now (already attributed, like the kept ones). */
396
+ function buildLateEntries(record, questionIndex, answer) {
397
+ const [first, ...rest] = record.questions.slice(record.lateFromIndex).map((question, offset) => {
398
+ const index = record.lateFromIndex + offset;
399
+ return { question, answer: index === questionIndex ? answer : record.answers[index] ?? [] };
400
+ });
401
+ if (!first)
402
+ throw new Error(`set-aside question ${record.id} has no late question`);
403
+ return [first, ...rest];
404
+ }
405
+ /**
406
+ * @description Give the answer `answer` to the question `target` names of a set-aside record. The record's questions are answered in
407
+ * order, as on screen:
408
+ * - while another question of the record is still open the answer is KEPT: the next question is posted as a message of its own
409
+ * with the set-aside look, and only then does the answered question's message close with «✅ Answer: …» (the agent hears
410
+ * nothing yet; an answer whose next question could not be posted is not taken);
411
+ * - the last one sends ONE late-answer message with every late answer to the agent (`deliverLateAnswer`); only once it reached
412
+ * a session is the record over — its message closes with the answer, its pin is released. A conversation with no session to
413
+ * take it leaves the record open.
414
+ * Everything is decided inside the question lifecycle queue, against the record as it is THEN: an answer meant for a question that
415
+ * is no longer the open one (two taps made at once, the first of which moved the record on) is `gone`, never given to the next
416
+ * question. `answeredBy` (see {@link getAnsweringMember}) rides inside the answer. Resolves the outcome and whether the topic now
417
+ * shows the whole answer (the question's message was edited to carry it).
418
+ */
419
+ async function giveSetAsideAnswer(key, request) {
420
+ const { target: meant } = request;
421
+ const answeringKey = `${(0, sessionKey_1.keyToString)(key)}:${meant.recordId}`;
422
+ const attributed = request.answeredBy === undefined ? request.answer : (0, authorMark_1.getAnswerWithAttribution)(request.answer, request.answeredBy);
423
+ const step = await runQuestionLifecycleOp(key, async () => {
424
+ const record = getSetAsideRecords(key).find((candidate) => candidate.id === meant.recordId);
425
+ const open = record ? (0, questionWaitPlan_1.getSetAsideAnswerTarget)(record) : null;
426
+ if (!record || !open || open.index !== meant.questionIndex || !(0, questionWaitPlan_1.checkIsSetAsideRecordMessage)(record, meant.messageId) || answeringRecords.has(answeringKey))
427
+ return { kind: 'gone' };
428
+ const isLastOpenQuestion = record.answers.every((answer, index) => answer !== null || index === open.index);
429
+ if (!isLastOpenQuestion) {
430
+ const collected = await collectLateAnswer(key, record, open, request.answer, attributed);
431
+ return collected === null ? { kind: 'notPosted' } : { kind: 'collected', isAnswerShown: collected };
432
+ }
433
+ answeringRecords.add(answeringKey);
434
+ return { kind: 'last', record, open };
435
+ });
436
+ if (step.kind === 'gone' || step.kind === 'notPosted')
437
+ return { outcome: step.kind, isAnswerShown: false };
438
+ if (step.kind === 'collected')
439
+ return { outcome: 'collected', isAnswerShown: step.isAnswerShown };
440
+ try {
441
+ const prompt = (0, questionWaitPlan_1.buildLateAnswerPrompt)({
442
+ entries: buildLateEntries(step.record, step.open.index, attributed),
443
+ askedAtMs: step.record.askedAt,
444
+ setAsideAtMs: step.record.setAsideAt,
445
+ nowMs: Date.now(),
446
+ });
447
+ const delivery = await deliverLateAnswer(key, prompt);
448
+ if (delivery === 'noSession')
449
+ return { outcome: 'noSession', isAnswerShown: false };
450
+ const isAnswerShown = await runQuestionLifecycleOp(key, () => finishSetAsideRecord(key, step.record, step.open.question, request.answer));
451
+ return { outcome: 'answered', isAnswerShown };
452
+ }
453
+ finally {
454
+ answeringRecords.delete(answeringKey);
455
+ }
456
+ }
457
+ /** The record's last open question was answered and delivered: the record is over. Its message carries the answer, its pin goes. */
458
+ async function finishSetAsideRecord(key, record, question, answer) {
459
+ notTakenNotes.delete(getAttemptKey(key, record.id));
460
+ await getState().setSetAsideQuestions(key, getSetAsideRecords(key).filter((candidate) => candidate.id !== record.id));
461
+ if (record.messageId === null)
462
+ return false;
463
+ const isAnswerShown = await closeQuestionMessage(key, record.messageId, question, { answer: answer.join(', ') });
464
+ await unpinMessage(key, record.messageId);
465
+ return isAnswerShown;
466
+ }
467
+ /**
468
+ * One answer of a record with more questions still open. The next open question is posted FIRST, as a message of its own in the
469
+ * set-aside look; only once it is there is the answer kept in the saved record and the answered question's message closed with it
470
+ * («✅ Answer: …», its pin released, the new message pinned). A post that fails changes nothing — the answer is not taken, the
471
+ * record stays on this question — and resolves `null`. Otherwise resolves whether the answered question's message shows the answer.
472
+ * `answer` is the plain one (the note under the question), `attributed` the one the record keeps for the agent.
473
+ */
474
+ async function collectLateAnswer(key, record, open, answer, attributed) {
475
+ const answers = record.answers.slice();
476
+ answers[open.index] = attributed;
477
+ const nextQuestion = record.questions[answers.findIndex((candidate) => candidate === null)];
478
+ const nextMessageId = nextQuestion ? await sendQuestionMessage(key, nextQuestion, buildSetAsideKeyboard(record, nextQuestion)) : null;
479
+ if (nextMessageId === null) {
480
+ console.warn(`[questionSetAside] the next question of record ${record.id} could not be posted; the answer was not taken`);
481
+ return null;
482
+ }
483
+ // The record keeps what it needs for the questions left: the first message of the answered question is not theirs.
484
+ const updated = {
485
+ id: record.id,
486
+ messageId: nextMessageId,
487
+ questions: record.questions,
488
+ answers,
489
+ lateFromIndex: record.lateFromIndex,
490
+ askedAt: record.askedAt,
491
+ setAsideAt: record.setAsideAt,
492
+ };
493
+ await getState().setSetAsideQuestions(key, getSetAsideRecords(key).map((candidate) => (candidate.id === record.id ? updated : candidate)));
494
+ let isAnswerShown = false;
495
+ if (record.messageId !== null) {
496
+ isAnswerShown = await closeQuestionMessage(key, record.messageId, open.question, { answer: answer.join(', ') });
497
+ await unpinMessage(key, record.messageId);
498
+ }
499
+ await pinMessageSilently(key, nextMessageId);
500
+ await showQuestionSetAside(key, updated);
501
+ return isAnswerShown;
502
+ }
503
+ /** What the topic is told when an answer was not taken: the question is no longer open, or the next question could not be posted. */
504
+ async function tellAnswerNotTaken(key, outcome) {
505
+ await replyToThread(key, withThreadLocale(key, () => (0, i18n_1.t)(outcome === 'gone' ? 'agent.set_aside_question_gone_notice' : 'agent.set_aside_next_question_failed_notice')));
506
+ }
507
+ /**
508
+ * @description A tap on a button of a set-aside question (`qs_<record id>_<option index>`). A topic member may answer the agent's
509
+ * question, as for a waiting one (the speaker gate, not the admin one). The tap must be on the message of the question that is
510
+ * open NOW — a button left on a message that carries a result, or on one of another record, answers nothing — and the toast is
511
+ * the label (the closed question carries it whole). The answer is meant for the question it was tapped on: one that is no longer
512
+ * the open one by the time it is taken (a double tap) is not given to the next.
513
+ */
514
+ async function handleSetAsideTap(ctx, recordId, optionIndex) {
515
+ const speaker = await authoriseSpeaker(ctx);
516
+ if (!speaker) {
517
+ await ctx.answerCbQuery((0, i18n_1.t)('cb.access_denied'));
518
+ return;
519
+ }
520
+ await answerSetAsideTap(ctx, speaker, getSetAsideRecords(speaker.key).find((candidate) => candidate.id === recordId), optionIndex);
521
+ }
522
+ /**
523
+ * @description The tap of an authorised `speaker` on option `optionIndex` of `record` (`undefined`: no such record any more),
524
+ * answered with the toast and the late answer — the part of a `qs_` tap that comes after the record is found.
525
+ */
526
+ async function answerSetAsideTap(ctx, speaker, record, optionIndex) {
527
+ const { key } = speaker;
528
+ const recordId = record?.id ?? '';
529
+ const open = record ? (0, questionWaitPlan_1.getSetAsideAnswerTarget)(record) : null;
530
+ const tappedMessageId = (0, callbackMessage_1.getCallbackMessageId)(ctx);
531
+ // A second tap made while the first answer of the record's last question is still on its way answers nothing — in the toast alone:
532
+ // the topic shows the first answer, and a notice beside it would read as «your answer was not sent».
533
+ const isLastAnswerOnItsWay = answeringRecords.has(`${(0, sessionKey_1.keyToString)(key)}:${recordId}`);
534
+ if (!record || !open || tappedMessageId === null || record.messageId !== tappedMessageId || isLastAnswerOnItsWay) {
535
+ await ctx.answerCbQuery((0, i18n_1.t)('cb.no_pending_question'));
536
+ return;
537
+ }
538
+ const label = open.question.options[optionIndex]?.label;
539
+ if (!label) {
540
+ await ctx.answerCbQuery((0, i18n_1.t)('cb.invalid_option'));
541
+ return;
542
+ }
543
+ const isLabelCut = await (0, callbackToast_1.answerCallbackWithFittedText)(ctx, label);
544
+ const { outcome, isAnswerShown } = await giveSetAsideAnswer(key, {
545
+ target: { recordId, questionIndex: open.index, messageId: tappedMessageId },
546
+ answer: [label],
547
+ answeredBy: getAnsweringMember(ctx.from, speaker.role),
548
+ });
549
+ if (outcome === 'gone' || outcome === 'notPosted')
550
+ await tellAnswerNotTaken(key, outcome);
551
+ // The closed question carries the whole label; one that could not be edited does not, and a toast cut it.
552
+ else if (outcome === 'answered' && !isAnswerShown && isLabelCut)
553
+ await replyToThread(key, label);
554
+ }
555
+ /**
556
+ * @description A LIVE button (`qa_<question>_<option>`) tapped on the message of a question the bot has SET ASIDE meanwhile: the
557
+ * edit that swaps its buttons for the `qs_` ones is paced by the send gate, so for a moment the message still shows the old ones
558
+ * (and may keep them when the edit is refused). The question is still open and answerable, so the tap answers IT, through the
559
+ * set-aside path, as its own `qs_` button would — never «no pending question», and never the question the agent asks next (that
560
+ * one is answered by its own message's buttons only). Resolves whether the tap was taken; `false` leaves it to the live path (the
561
+ * message is no set-aside question's, or the button is for a question of the call that is not the open one).
562
+ */
563
+ async function answerLiveTapOnSetAsideQuestion(ctx, speaker, questionIndex, optionIndex) {
564
+ const tappedMessageId = (0, callbackMessage_1.getCallbackMessageId)(ctx);
565
+ if (tappedMessageId === null)
566
+ return false;
567
+ const record = getSetAsideRecords(speaker.key).find((candidate) => candidate.messageId === tappedMessageId);
568
+ if (!record || (0, questionWaitPlan_1.getSetAsideAnswerTarget)(record)?.index !== questionIndex)
569
+ return false;
570
+ await answerSetAsideTap(ctx, speaker, record, optionIndex);
571
+ return true;
572
+ }
573
+ /**
574
+ * @description A text typed as a REPLY to a set-aside question's message (either of its messages, when it was re-posted) is its
575
+ * late answer: a bare option number in range picks that option, so does an option's own label, and — for the operator only — any
576
+ * other text is the answer itself (a topic member answers only with an option number or label: their other words are an ordinary
577
+ * prompt, as on the waiting-question route). A voice note is a reply too: the bot hands its transcript here. Resolves whether it
578
+ * was taken as one — otherwise it is an ordinary message. `role`: a topic member's answer reaches the agent as theirs (`from` says who). A
579
+ * reply that matched a question which is no longer the open one (a second reply made at once, a record closed meanwhile) is
580
+ * still no ordinary message — it was meant as an answer, so it is answered with a note, never passed on as a prompt or a pick.
581
+ */
582
+ async function answerSetAsideQuestionByReply(from, key, message, role) {
583
+ const { replyToMessageId } = message;
584
+ const setAside = getSetAsideRecords(key);
585
+ const text = message.text.trim();
586
+ // A slash command is no answer; a message that replies to nothing, or when nothing is set aside, is none either.
587
+ if (replyToMessageId === null || setAside.length === 0 || text === '' || (!message.isForwarded && text.startsWith('/')))
588
+ return false;
589
+ const route = (0, questionWaitPlan_1.getQuestionReplyRouteWithSetAside)({ text, replyToMessageId, liveQuestion: undefined, setAside, isForwarded: message.isForwarded, canAnswerWithFreeText: role === 'admin' });
590
+ if (route.kind !== 'answerSetAside')
591
+ return false;
592
+ await getState().pushMessageId(key, message.message_id);
593
+ const { outcome } = await giveSetAsideAnswer(key, {
594
+ target: { recordId: route.recordId, questionIndex: route.questionIndex, messageId: replyToMessageId },
595
+ answer: route.answer,
596
+ answeredBy: getAnsweringMember(from, role),
597
+ });
598
+ if (outcome === 'gone' || outcome === 'notPosted')
599
+ await tellAnswerNotTaken(key, outcome);
600
+ return true;
601
+ }
602
+ /** Register the buttons of a set-aside question (`qs_<record id>_<option index>`), disjoint from the live (`qa_`) and re-asked (`reask_`) ones. */
603
+ function registerQuestionSetAsideCallbacks(bot) {
604
+ bot.action(new RegExp(`^${setAsideButtonPrefix}([0-9a-z]+)_(\\d+)$`), (ctx) => handleSetAsideTap(ctx, ctx.match[1], parseInt(ctx.match[2], 10)));
605
+ }
606
+ // ── the end of a conversation ──
607
+ /**
608
+ * @description The conversation ended or was replaced (`/new`, `/quit`, `/quitall`, leaving the folder, another conversation or
609
+ * backend): every open set-aside question ends as «not answered», its pin released, and the saved list is emptied FIRST — a late
610
+ * tap finds nothing. Run in the question lifecycle queue, so it orders after a set-aside in flight (the question it is about to
611
+ * save is closed too, not left open for a conversation that is gone) and after an answer on its way.
612
+ */
613
+ function closeSetAsideQuestions(key) {
614
+ return runQuestionLifecycleOp(key, async () => {
615
+ const records = getSetAsideRecords(key);
616
+ if (records.length === 0)
617
+ return;
618
+ await getState().setSetAsideQuestions(key, []);
619
+ for (const record of records)
620
+ await closeSetAsideRecord(key, record, 'unanswered');
621
+ });
622
+ }
623
+ return {
624
+ armQuestionSetAsideTimer,
625
+ clearQuestionSetAsideTimer,
626
+ setPendingQuestionAside,
627
+ setPendingQuestionAsideAtIdle,
628
+ answerQuestionAskedAgain,
629
+ checkIsSetAsideQuestionMessage,
630
+ answerLiveTapOnSetAsideQuestion,
631
+ registerQuestionSetAsideCallbacks,
632
+ answerSetAsideQuestionByReply,
633
+ giveSetAsideAnswer,
634
+ closeSetAsideQuestions,
635
+ };
636
+ }
637
+ //# sourceMappingURL=questionSetAside.js.map