charness 4.1.0 → 4.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/DEVELOPMENT.md +1 -1
  3. package/SETUP.md +34 -8
  4. package/dist/adapters/claudeJsonStreamAdapter.d.ts +60 -5
  5. package/dist/adapters/claudeJsonStreamAdapter.d.ts.map +1 -1
  6. package/dist/adapters/claudeJsonStreamAdapter.js +128 -14
  7. package/dist/adapters/claudeJsonStreamAdapter.js.map +1 -1
  8. package/dist/bot.d.ts.map +1 -1
  9. package/dist/bot.js +164 -31
  10. package/dist/bot.js.map +1 -1
  11. package/dist/connectors/jira/answerSink.d.ts +8 -0
  12. package/dist/connectors/jira/answerSink.d.ts.map +1 -1
  13. package/dist/connectors/jira/answerSink.js +15 -0
  14. package/dist/connectors/jira/answerSink.js.map +1 -1
  15. package/dist/connectors/jira/config.d.ts +16 -0
  16. package/dist/connectors/jira/config.d.ts.map +1 -1
  17. package/dist/connectors/jira/config.js +21 -2
  18. package/dist/connectors/jira/config.js.map +1 -1
  19. package/dist/connectors/jira/connector.d.ts +10 -3
  20. package/dist/connectors/jira/connector.d.ts.map +1 -1
  21. package/dist/connectors/jira/connector.js +21 -3
  22. package/dist/connectors/jira/connector.js.map +1 -1
  23. package/dist/connectors/jira/inbound.d.ts +200 -18
  24. package/dist/connectors/jira/inbound.d.ts.map +1 -1
  25. package/dist/connectors/jira/inbound.js +814 -43
  26. package/dist/connectors/jira/inbound.js.map +1 -1
  27. package/dist/connectors/jira/prompt.d.ts +46 -0
  28. package/dist/connectors/jira/prompt.d.ts.map +1 -1
  29. package/dist/connectors/jira/prompt.js +123 -15
  30. package/dist/connectors/jira/prompt.js.map +1 -1
  31. package/dist/connectors/jira/trigger.d.ts +27 -4
  32. package/dist/connectors/jira/trigger.d.ts.map +1 -1
  33. package/dist/connectors/jira/trigger.js +35 -1
  34. package/dist/connectors/jira/trigger.js.map +1 -1
  35. package/dist/connectors/jira/triggerLog.d.ts +60 -5
  36. package/dist/connectors/jira/triggerLog.d.ts.map +1 -1
  37. package/dist/connectors/jira/triggerLog.js +116 -7
  38. package/dist/connectors/jira/triggerLog.js.map +1 -1
  39. package/dist/connectors/telegram/commands/runners.d.ts +28 -1
  40. package/dist/connectors/telegram/commands/runners.d.ts.map +1 -1
  41. package/dist/connectors/telegram/commands/runners.js +75 -40
  42. package/dist/connectors/telegram/commands/runners.js.map +1 -1
  43. package/dist/connectors/telegram/sendOutcome.d.ts +3 -1
  44. package/dist/connectors/telegram/sendOutcome.d.ts.map +1 -1
  45. package/dist/connectors/telegram/sendOutcome.js.map +1 -1
  46. package/dist/connectors/telegram/telegramFailureRetry.d.ts +8 -0
  47. package/dist/connectors/telegram/telegramFailureRetry.d.ts.map +1 -1
  48. package/dist/connectors/telegram/telegramFailureRetry.js +8 -0
  49. package/dist/connectors/telegram/telegramFailureRetry.js.map +1 -1
  50. package/dist/i18n/de.d.ts.map +1 -1
  51. package/dist/i18n/de.js +4 -0
  52. package/dist/i18n/de.js.map +1 -1
  53. package/dist/i18n/en.d.ts.map +1 -1
  54. package/dist/i18n/en.js +4 -0
  55. package/dist/i18n/en.js.map +1 -1
  56. package/dist/i18n/es.d.ts.map +1 -1
  57. package/dist/i18n/es.js +4 -0
  58. package/dist/i18n/es.js.map +1 -1
  59. package/dist/i18n/fr.d.ts.map +1 -1
  60. package/dist/i18n/fr.js +4 -0
  61. package/dist/i18n/fr.js.map +1 -1
  62. package/dist/i18n/hi.d.ts.map +1 -1
  63. package/dist/i18n/hi.js +4 -0
  64. package/dist/i18n/hi.js.map +1 -1
  65. package/dist/i18n/ja.d.ts.map +1 -1
  66. package/dist/i18n/ja.js +4 -0
  67. package/dist/i18n/ja.js.map +1 -1
  68. package/dist/i18n/ka.d.ts.map +1 -1
  69. package/dist/i18n/ka.js +4 -0
  70. package/dist/i18n/ka.js.map +1 -1
  71. package/dist/i18n/pt.d.ts.map +1 -1
  72. package/dist/i18n/pt.js +4 -0
  73. package/dist/i18n/pt.js.map +1 -1
  74. package/dist/i18n/ru.d.ts.map +1 -1
  75. package/dist/i18n/ru.js +4 -0
  76. package/dist/i18n/ru.js.map +1 -1
  77. package/dist/i18n/uk.d.ts.map +1 -1
  78. package/dist/i18n/uk.js +4 -0
  79. package/dist/i18n/uk.js.map +1 -1
  80. package/dist/i18n/uz.d.ts.map +1 -1
  81. package/dist/i18n/uz.js +4 -0
  82. package/dist/i18n/uz.js.map +1 -1
  83. package/dist/i18n/zh.d.ts.map +1 -1
  84. package/dist/i18n/zh.js +4 -0
  85. package/dist/i18n/zh.js.map +1 -1
  86. package/dist/i18n.d.ts.map +1 -1
  87. package/dist/i18n.js +2 -1
  88. package/dist/i18n.js.map +1 -1
  89. package/dist/requests/requestHeader.d.ts.map +1 -1
  90. package/dist/requests/requestHeader.js +1 -0
  91. package/dist/requests/requestHeader.js.map +1 -1
  92. package/dist/requests/types.d.ts +4 -1
  93. package/dist/requests/types.d.ts.map +1 -1
  94. package/dist/requests/wakeUpEngine.d.ts +31 -1
  95. package/dist/requests/wakeUpEngine.d.ts.map +1 -1
  96. package/dist/requests/wakeUpEngine.js +94 -2
  97. package/dist/requests/wakeUpEngine.js.map +1 -1
  98. package/dist/requests/wakeUpRules.d.ts +7 -0
  99. package/dist/requests/wakeUpRules.d.ts.map +1 -1
  100. package/dist/requests/wakeUpRules.js +14 -0
  101. package/dist/requests/wakeUpRules.js.map +1 -1
  102. package/dist/scheduler/engine.d.ts +17 -4
  103. package/dist/scheduler/engine.d.ts.map +1 -1
  104. package/dist/scheduler/engine.js +55 -10
  105. package/dist/scheduler/engine.js.map +1 -1
  106. package/dist/scheduler/mcpBoot.d.ts +6 -2
  107. package/dist/scheduler/mcpBoot.d.ts.map +1 -1
  108. package/dist/scheduler/mcpBoot.js +7 -1
  109. package/dist/scheduler/mcpBoot.js.map +1 -1
  110. package/dist/scheduler/mcpSurface.d.ts.map +1 -1
  111. package/dist/scheduler/mcpSurface.js +18 -9
  112. package/dist/scheduler/mcpSurface.js.map +1 -1
  113. package/dist/sendErrorClassifier.d.ts +6 -0
  114. package/dist/sendErrorClassifier.d.ts.map +1 -1
  115. package/dist/sendErrorClassifier.js +9 -0
  116. package/dist/sendErrorClassifier.js.map +1 -1
  117. package/dist/startupPromptBuffer.d.ts +8 -8
  118. package/dist/startupPromptBuffer.d.ts.map +1 -1
  119. package/dist/startupPromptBuffer.js +7 -5
  120. package/dist/startupPromptBuffer.js.map +1 -1
  121. package/dist/testTimings.d.ts +3 -2
  122. package/dist/testTimings.d.ts.map +1 -1
  123. package/dist/testTimings.js +3 -1
  124. package/dist/testTimings.js.map +1 -1
  125. package/dist/threadRouting.d.ts +23 -0
  126. package/dist/threadRouting.d.ts.map +1 -1
  127. package/dist/threadRouting.js +28 -0
  128. package/dist/threadRouting.js.map +1 -1
  129. package/dist/trackers/taskAgentSlots.d.ts +42 -3
  130. package/dist/trackers/taskAgentSlots.d.ts.map +1 -1
  131. package/dist/trackers/taskAgentSlots.js +31 -11
  132. package/dist/trackers/taskAgentSlots.js.map +1 -1
  133. package/dist/types.d.ts +7 -0
  134. package/dist/types.d.ts.map +1 -1
  135. package/dist/utils/fileSendPlan.d.ts +30 -8
  136. package/dist/utils/fileSendPlan.d.ts.map +1 -1
  137. package/dist/utils/fileSendPlan.js +37 -12
  138. package/dist/utils/fileSendPlan.js.map +1 -1
  139. package/dist/utils/fileSendService.d.ts +1 -1
  140. package/dist/utils/fileSendService.d.ts.map +1 -1
  141. package/dist/utils/fileSendService.js +9 -1
  142. package/dist/utils/fileSendService.js.map +1 -1
  143. package/dist/utils/imageDimensions.d.ts +32 -0
  144. package/dist/utils/imageDimensions.d.ts.map +1 -0
  145. package/dist/utils/imageDimensions.js +181 -0
  146. package/dist/utils/imageDimensions.js.map +1 -0
  147. package/dist/utils/jsonStreamHost.d.ts +35 -9
  148. package/dist/utils/jsonStreamHost.d.ts.map +1 -1
  149. package/dist/utils/jsonStreamHost.js +59 -16
  150. package/dist/utils/jsonStreamHost.js.map +1 -1
  151. package/dist/utils/lostWork.d.ts +8 -2
  152. package/dist/utils/lostWork.d.ts.map +1 -1
  153. package/dist/utils/lostWork.js +9 -5
  154. package/dist/utils/lostWork.js.map +1 -1
  155. package/dist/utils/promptDelivery.d.ts +11 -2
  156. package/dist/utils/promptDelivery.d.ts.map +1 -1
  157. package/dist/utils/promptDelivery.js +3 -3
  158. package/dist/utils/promptDelivery.js.map +1 -1
  159. package/npm-shrinkwrap.json +2 -2
  160. package/package.json +1 -1
package/dist/bot.js CHANGED
@@ -2730,6 +2730,21 @@ async function authoriseContext(ctx) {
2730
2730
  noteGroupTitle(ctx, key);
2731
2731
  return key;
2732
2732
  }
2733
+ /**
2734
+ * @description The gate of a tap on a pairing line's «jobs at once» row (`/runners`): the line is sent to the admin who asked for it in a
2735
+ * PRIVATE message, so the tap comes from their own chat with the bot — which the DM surface does not serve unless it is the owner's
2736
+ * (`authoriseContext` refuses it). A group admin tapping in a chat that is theirs gets that chat's key (`getOwnPrivateChatKey`); every
2737
+ * other tap — the group, the owner's DM — takes the usual admin gate. The key, or `null` when refused.
2738
+ */
2739
+ async function authorisePairingTap(ctx) {
2740
+ if (ctx.chat?.type === 'private' && !checkIsDmChat(ctx)) {
2741
+ const key = (0, threadRouting_1.getOwnPrivateChatKey)({ chatType: ctx.chat.type, chatId: ctx.chat.id, userId: ctx.from?.id, adminIds: await adminCache.getAdminIds() });
2742
+ if (key === null)
2743
+ console.warn(`[security] ignored update from chat ${ctx.chat.id} user ${ctx.from?.id ?? '?'} (not a group admin in their own private chat)`);
2744
+ return key;
2745
+ }
2746
+ return authoriseContext(ctx);
2747
+ }
2733
2748
  /**
2734
2749
  * Refresh the group-title cache from an accepted update — supergroups always carry `chat.title`. Feeds the thread-context
2735
2750
  * preamble (S2). Cheap, idempotent, and the one place every accepted update funnels through. A private chat (DM key) has
@@ -3307,7 +3322,9 @@ async function unpinThreadQuestion(key) {
3307
3322
  */
3308
3323
  function buildSendExtra(key, extra) {
3309
3324
  const base = extra;
3310
- if (checkIsGeneral(key))
3325
+ // The main thread of ANY private chat — the owner's DM and an admin's own chat alike — has no topic to name: Telegram answers a
3326
+ // `message_thread_id` there with «message thread not found».
3327
+ if (checkIsGeneral(key) || (0, threadRouting_1.checkIsPrivateChatMainKey)(key))
3311
3328
  return { ...base };
3312
3329
  // Audit S20 / #36: spread `base` BEFORE `message_thread_id` so a
3313
3330
  // caller passing `message_thread_id: undefined` in `extra` can't
@@ -3374,7 +3391,7 @@ async function replyToThreadDetailed(key, text, extra = {}, options = {}) {
3374
3391
  if ((0, rateLimiter_1.checkIsSendOutcomeUnknownError)(e2))
3375
3392
  return reportUnknown();
3376
3393
  await handleSendError(key, e2);
3377
- return { kind: 'failed', isRetryable: (0, telegramFailureRetry_1.checkIsTelegramFailureRetryable)(e2) };
3394
+ return (0, telegramFailureRetry_1.getFailedSendOutcome)(e2);
3378
3395
  }
3379
3396
  }
3380
3397
  // A double-429 (rate-limited even after withRateLimitRetry's single
@@ -3383,7 +3400,7 @@ async function replyToThreadDetailed(key, text, extra = {}, options = {}) {
3383
3400
  // re-arm a bounded redelivery (its late re-send was the OUT-OF-ORDER cause
3384
3401
  // the user reported) — the rare 429 is just logged via handleSendError.
3385
3402
  await handleSendError(key, e);
3386
- return { kind: 'failed', isRetryable: (0, telegramFailureRetry_1.checkIsTelegramFailureRetryable)(e) };
3403
+ return (0, telegramFailureRetry_1.getFailedSendOutcome)(e);
3387
3404
  }
3388
3405
  finally {
3389
3406
  releaseSecret?.();
@@ -4954,17 +4971,19 @@ async function replayBufferedPrompts(key) {
4954
4971
  // like the API-error retry's nudge, hears whether it reached the session).
4955
4972
  await startupPromptBuffer.replayPrompts((0, sessionKey_1.keyToString)(key), {
4956
4973
  isSessionActive,
4957
- forward: async (prompt) => { await forwardPromptToAgent(key, adapter, prompt); },
4974
+ forward: async (prompt, isPersonInput) => { await forwardPromptToAgent(key, adapter, prompt, undefined, { isPersonInput }); },
4958
4975
  });
4959
4976
  if (!isSessionActive)
4960
4977
  return;
4961
4978
  // R23: prompts held during a usage-limit wait that ended with the previous
4962
- // session go to this one — on their own when nothing above carried them.
4979
+ // session go to this one — on their own when nothing above carried them. They
4980
+ // are what people asked for meanwhile: a write that fails is told in the topic
4981
+ // like a person's own message, never only logged.
4963
4982
  const heldText = limitHeldPrompts.releaseAll(key);
4964
4983
  if (heldText === null)
4965
4984
  return;
4966
4985
  try {
4967
- await forwardPromptToAgent(key, adapter, heldText);
4986
+ await forwardPromptToAgent(key, adapter, heldText, undefined, { isPersonInput: true });
4968
4987
  }
4969
4988
  catch (err) {
4970
4989
  console.error('[replayBufferedPrompts] forwarding the held prompts failed:', err);
@@ -5013,7 +5032,11 @@ async function forwardPromptToAgent(key, adapter, text, sentAtMs, options = {})
5013
5032
  checkIsWindowOpen: () => startupPromptBuffer.checkIsStarting((0, sessionKey_1.keyToString)(key)),
5014
5033
  checkIsSessionActive: () => adapter.checkIsActive(key) && !(isTechnicalPrompt && (adapter.checkIsBusy?.(key) ?? false)),
5015
5034
  buffer: async () => {
5016
- await deliverPromptOrBuffer(key, `${options.requestHeader ?? ''}${getPromptWithThreadMessageContext(key, text, options.messageContext)}`, true);
5035
+ // A bot-made prompt (a wake-up) that waits here counts only once its replay reached the agent, as at any other buffer.
5036
+ const buffered = createBufferedOutcome();
5037
+ await deliverPromptOrBuffer(key, `${options.requestHeader ?? ''}${getPromptWithThreadMessageContext(key, text, options.messageContext)}`, true, buffered.settle, { isPersonInput: options.isPersonInput });
5038
+ if (options.isPersonInput !== true)
5039
+ await buffered.assertReplayed();
5017
5040
  },
5018
5041
  wake: () => wakeSleepingSessionForPrompt(key),
5019
5042
  forward: async () => {
@@ -5068,8 +5091,10 @@ async function forwardPromptToLiveAgent(key, adapter, text, sentAtMs, options =
5068
5091
  // The request header (S7) leads the per-message body, like the message context and
5069
5092
  // unlike the once-per-change thread preamble: it names THIS message's request.
5070
5093
  const messageBody = options.requestHeader ? `${options.requestHeader}${quotedBody}` : quotedBody;
5071
- // A loss the agent was not told about yet (`utils/lostWork.ts`) rides the first real prompt, once, ahead of it.
5072
- const lostWorkRecord = isReplayable && adapter.name !== 'terminal' ? state.getLostWork(key) : undefined;
5094
+ // A loss the agent was not told about yet (`utils/lostWork.ts`) rides the first real prompt, once, ahead of it — a
5095
+ // request's reminder included: the wake of a tracker request whose process a restart left behind is how its agent hears.
5096
+ const isLostWorkNoteCarried = (isReplayable || options.isRequestReminder === true) && adapter.name !== 'terminal';
5097
+ const lostWorkRecord = isLostWorkNoteCarried ? state.getLostWork(key) : undefined;
5073
5098
  const body = lostWorkRecord ? `${(0, lostWork_1.buildLostWorkNote)(lostWorkRecord, (0, i18n_1.getLocaleEndonym)((0, i18n_1.getActiveLang)()))}\n\n${messageBody}` : messageBody;
5074
5099
  // Cache the (reply-folded) prompt so a wedged OpenCode session can be recovered
5075
5100
  // by restarting fresh and replaying it — replaying WITH the quote is correct.
@@ -5134,10 +5159,10 @@ async function forwardPromptToLiveAgent(key, adapter, text, sentAtMs, options =
5134
5159
  if (adapter.detachRunningSubagents && !isTechnicalPrompt) {
5135
5160
  await adapter.detachRunningSubagents(key);
5136
5161
  }
5137
- adapter.sendInput(key, promptText);
5138
- // Told only once the prompt carrying the note reached a live session: a forward that failed keeps it for the next.
5139
- if (lostWorkRecord && adapter.checkIsActive(key))
5140
- void state.clearLostWork(key);
5162
+ // A backend that can tell whether the prompt reached the agent (the json-stream host's stdin write) is asked to: a
5163
+ // write that failed rejects this forward, so its caller — a tracker post, a wake-up — knows the prompt never arrived
5164
+ // and retries, instead of believing it delivered. The input is handed over synchronously either way; only its outcome is awaited.
5165
+ const written = adapter.sendInputAndWait ? adapter.sendInputAndWait(key, promptText) : (adapter.sendInput(key, promptText), Promise.resolve());
5141
5166
  // S2 busy-onset arm: start the Claude liveness loop the moment the prompt is
5142
5167
  // forwarded — driven by `checkIsBusy`, not by waiting for an opportunistic
5143
5168
  // scrape emit that may never come during a long quiet think. The arming grace
@@ -5146,6 +5171,26 @@ async function forwardPromptToLiveAgent(key, adapter, text, sentAtMs, options =
5146
5171
  // choke point (user text, voice, scheduled run, api-retry continue, buffered
5147
5172
  // replay), so every path that makes Claude busy now raises the working frame.
5148
5173
  startClaudeLiveness(key, 'busyOnset');
5174
+ // Told only once the prompt carrying the note reached a live session: a forward that failed keeps it for the next.
5175
+ const noteToldIfDelivered = () => {
5176
+ if (lostWorkRecord && adapter.checkIsActive(key))
5177
+ void state.clearLostWork(key);
5178
+ };
5179
+ // A person's own message never holds the topic's update queue on its write — a CLI that stops reading its input would
5180
+ // keep `/esc` and every tap behind it for minutes —: they are told when it failed. Every other prompt (a tracker's post,
5181
+ // a wake-up, a scheduled run, a retry's nudge, the todo reminder) awaits it: one that never arrived is retried.
5182
+ if (options.isPersonInput === true) {
5183
+ void written.then(noteToldIfDelivered, (error) => reportUndeliveredTopicPrompt(key, error));
5184
+ return;
5185
+ }
5186
+ await written;
5187
+ noteToldIfDelivered();
5188
+ }
5189
+ /** @description A topic's prompt whose write into the agent failed (the forward did not wait for it): one line says so. */
5190
+ function reportUndeliveredTopicPrompt(key, error) {
5191
+ const message = error instanceof Error ? error.message : String(error);
5192
+ console.warn(`[forward] ${(0, sessionKey_1.keyToString)(key)}: the prompt did not reach the agent: ${message}`);
5193
+ void withThreadLocale(key, () => replyToThread(key, (0, i18n_1.t)('agent.prompt_not_delivered', { error: message }))).catch(() => { });
5149
5194
  }
5150
5195
  /**
5151
5196
  * @description Return the prompt text with the thread-context preamble glued
@@ -6902,6 +6947,7 @@ const { registerRunnersCommands, registerRunnersCallbacks, handleRunnersAddressT
6902
6947
  // What this instance has told about where the runners' links come from: once per new concern, pinned in General.
6903
6948
  linkNoticesPath: path.join((0, state_1.resolveDataDir)(), 'runner-link-notices.json'),
6904
6949
  cacheDir: runnersCacheDir,
6950
+ authorisePairingTap,
6905
6951
  getGeneralKey: () => getOperatorGeneralKey(),
6906
6952
  pinMessage: (key, messageId) => pinMessageQuiet(key, messageId, { disableNotification: false }),
6907
6953
  sweepExpiredCodes: async (nowMs) => { await (0, hubPairing_1.sweepExpiredPairings)(runnersHub, nowMs); },
@@ -8405,7 +8451,7 @@ command('schedule', async (ctx, key, parsed) => {
8405
8451
  await replyToThread(key, result.message);
8406
8452
  const isStarting = startupPromptBuffer.checkIsStarting((0, sessionKey_1.keyToString)(key));
8407
8453
  const opening = await openTopicRequest(key, wrappedPrompt, { source: 'schedule', requesterId: (0, topicRequest_1.getTopicRequesterId)(ctx.from) });
8408
- const delivery = await deliverPromptOrBuffer(key, `${opening.header}${wrappedPrompt}`, isStarting);
8454
+ const delivery = await deliverPromptOrBuffer(key, `${opening.header}${wrappedPrompt}`, isStarting, undefined, { isPersonInput: true });
8409
8455
  await settleTopicRequestAfterDelivery(key, opening, delivery);
8410
8456
  });
8411
8457
  const reminderWizards = new Map();
@@ -8712,7 +8758,7 @@ bot.on((0, filters_1.message)('text'), async (ctx) => {
8712
8758
  }
8713
8759
  }
8714
8760
  // `/runners` → «Enter another address»: this General message is the address runners dial. A slash command wins over the wait.
8715
- if (await handleRunnersAddressText(key, text))
8761
+ if (ctx.from !== undefined && (await handleRunnersAddressText(key, text, ctx.from)))
8716
8762
  return;
8717
8763
  // Session is mid-startup → buffer the prompt and replay it once the agent is
8718
8764
  // ready, instead of dropping it into the "no agent running" guidance below.
@@ -9229,13 +9275,13 @@ async function downloadIncomingFile(ctx, key, meta, onError) {
9229
9275
  */
9230
9276
  const promptDeliveryDeps = {
9231
9277
  startupBuffer: startupPromptBuffer,
9232
- forwardPrompt: (key, text) => forwardPromptToAgent(key, (0, createAdapter_1.getThreadAdapter)(key), text),
9278
+ forwardPrompt: (key, text, options) => forwardPromptToAgent(key, (0, createAdapter_1.getThreadAdapter)(key), text, undefined, { isPersonInput: options.isPersonInput }),
9233
9279
  announceQueued: async (key) => {
9234
9280
  await replyToThread(key, (0, i18n_1.t)('agent.queued_starting', { label: (0, createAdapter_1.getThreadAdapter)(key).label }));
9235
9281
  },
9236
9282
  };
9237
- function deliverPromptOrBuffer(key, promptText, isStarting, onBufferedSettled) {
9238
- return (0, promptDelivery_1.deliverPromptOrBuffer)(promptDeliveryDeps, key, promptText, isStarting, onBufferedSettled);
9283
+ function deliverPromptOrBuffer(key, promptText, isStarting, onBufferedSettled, options = {}) {
9284
+ return (0, promptDelivery_1.deliverPromptOrBuffer)(promptDeliveryDeps, key, promptText, isStarting, onBufferedSettled, options);
9239
9285
  }
9240
9286
  /**
9241
9287
  * @description Per-(thread, media_group) album batcher. Telegram delivers an
@@ -9268,12 +9314,13 @@ const albumCollector = (0, mediaGroupCollector_1.createMediaGroupCollector)({
9268
9314
  try {
9269
9315
  const opening = await openTopicRequest(key, promptText, { source: 'album', requesterId: orderedItems[0].requesterId }, messageContext);
9270
9316
  const quotedPrompt = getPromptWithThreadMessageContext(key, promptText, messageContext);
9271
- const delivery = await deliverPromptOrBuffer(key, `${opening.header}${quotedPrompt}`, isStarting);
9317
+ const delivery = await deliverPromptOrBuffer(key, `${opening.header}${quotedPrompt}`, isStarting, undefined, { isPersonInput: true });
9272
9318
  await settleTopicRequestAfterDelivery(key, opening, delivery);
9273
9319
  }
9274
9320
  catch (err) {
9321
+ // The files were downloaded already (each item before the flush): what failed is the album's prompt.
9275
9322
  console.error('[Bot] album flush failed:', err);
9276
- await replyToThread(key, (0, i18n_1.t)('file.download_failed')).catch(() => { });
9323
+ await replyToThread(key, (0, i18n_1.t)('agent.prompt_not_delivered', { error: err instanceof Error ? err.message : String(err) })).catch(() => { });
9277
9324
  }
9278
9325
  });
9279
9326
  },
@@ -9353,7 +9400,7 @@ async function handleIncomingFile(ctx, key, isFromTalker) {
9353
9400
  const messageContext = getMessageContext(key, ctx.message);
9354
9401
  const opening = await openTopicRequest(key, promptText, { source: 'file', requesterId: (0, topicRequest_1.getTopicRequesterId)(ctx.from) }, messageContext);
9355
9402
  const quotedPrompt = getPromptWithThreadMessageContext(key, promptText, messageContext);
9356
- const delivery = await deliverPromptOrBuffer(key, `${opening.header}${quotedPrompt}`, isStarting);
9403
+ const delivery = await deliverPromptOrBuffer(key, `${opening.header}${quotedPrompt}`, isStarting, undefined, { isPersonInput: true });
9357
9404
  await settleTopicRequestAfterDelivery(key, opening, delivery);
9358
9405
  }
9359
9406
  bot.on(
@@ -10072,7 +10119,7 @@ async function bufferPromptDuringStartup(key, text, intake, messageContext) {
10072
10119
  notePersonActivity(key);
10073
10120
  const opening = await openTopicRequest(key, text, intake, messageContext);
10074
10121
  const quotedText = getPromptWithThreadMessageContext(key, text, messageContext);
10075
- await deliverPromptOrBuffer(key, `${opening.header}${quotedText}`, true);
10122
+ await deliverPromptOrBuffer(key, `${opening.header}${quotedText}`, true, undefined, { isPersonInput: true });
10076
10123
  trackTopicRequestTurn(key, opening);
10077
10124
  }
10078
10125
  /**
@@ -10155,10 +10202,10 @@ async function deliverActivePrompt(key, adapter, text, intake, sentAtMs, message
10155
10202
  checkIsWindowOpen: () => startupPromptBuffer.checkIsStarting((0, sessionKey_1.keyToString)(key)),
10156
10203
  checkIsSessionActive: () => adapter.checkIsActive(key),
10157
10204
  buffer: async () => {
10158
- await deliverPromptOrBuffer(key, `${opening.header}${getPromptWithThreadMessageContext(key, text, messageContext)}`, true);
10205
+ await deliverPromptOrBuffer(key, `${opening.header}${getPromptWithThreadMessageContext(key, text, messageContext)}`, true, undefined, { isPersonInput: true });
10159
10206
  },
10160
10207
  wake: () => wakeSleepingSessionForPrompt(key),
10161
- forward: () => forwardPromptToAgent(key, (0, createAdapter_1.getThreadAdapter)(key), text, sentAtMs, { messageContext, requestHeader: opening.header }),
10208
+ forward: () => forwardPromptToAgent(key, (0, createAdapter_1.getThreadAdapter)(key), text, sentAtMs, { messageContext, requestHeader: opening.header, isPersonInput: true }),
10162
10209
  reportNoSession: async (isAlreadyTold) => {
10163
10210
  if (!isAlreadyTold)
10164
10211
  await replyToThread(key, (0, i18n_1.t)('agent.no_session'));
@@ -10225,7 +10272,7 @@ async function cancelPendingQuestionAndForward(key, adapter, text, sentAtMs, mes
10225
10272
  if (!didLabelQuestionMessage) {
10226
10273
  await replyToThread(key, (0, i18n_1.t)('agent.question_cancelled_for_prompt'));
10227
10274
  }
10228
- return forwardPromptToAgent(key, adapter, text, sentAtMs, { messageContext, requestHeader });
10275
+ return forwardPromptToAgent(key, adapter, text, sentAtMs, { messageContext, requestHeader, isPersonInput: true });
10229
10276
  }
10230
10277
  /**
10231
10278
  * @description Record one answer for the CURRENTLY shown OpenCode question and
@@ -11551,10 +11598,16 @@ async function noteLostWork(key, lostWork, reason) {
11551
11598
  reason,
11552
11599
  isLimitWaitArmed,
11553
11600
  msSinceLastAutoResume: lastAutoResumeAt === undefined ? null : now - lastAutoResumeAt,
11554
- // A tracker issue's agent answers only through a request: a bare note would have nowhere to answer.
11601
+ // A tracker issue's agent answers only through a request: a bare note would have nowhere to answer — its open request is woken instead.
11555
11602
  isRequestRequired: !(0, sessionKeyCodec_1.checkIsTelegramKey)(key),
11603
+ hasOpenRequest: (topicRequestLedger?.listOpenRequestsOf(key).length ?? 0) > 0,
11556
11604
  });
11557
- 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' : ''}); ${plan.isAutoResume ? 'resuming it with a note' : 'the note rides the next prompt'}`);
11605
+ let planText = plan.isAutoResume ? 'resuming it with a note' : 'the note rides the next prompt';
11606
+ if (plan.isRequestWake)
11607
+ planText = 'its open request is woken, and the note rides that wake';
11608
+ console.log(`[lost-work] ${kStr}: the process ended (${reason}) with the agent's own work pending (${record.backgroundTasks.length} background task(s), ${record.scheduledJobCount} scheduled job(s)${record.hasUnreadTaskResult ? ', an unread task result' : ''}${record.wasTurnInFlight ? ', a cut-off turn' : ''}); ${planText}`);
11609
+ if (plan.isRequestWake)
11610
+ scheduleTrackerRestartWake(key, `its process ended (${reason}) with its own work pending`);
11558
11611
  let linePlan = plan;
11559
11612
  if (plan.isAutoResume) {
11560
11613
  await state.setLostWorkResumedAt(key, now);
@@ -11565,6 +11618,43 @@ async function noteLostWork(key, lostWork, reason) {
11565
11618
  if ((0, sessionKeyCodec_1.checkIsTelegramKey)(key))
11566
11619
  replyToThread(key, (0, lostWork_1.formatLostWorkTopicLine)(record, linePlan, pendingWorkHoldHours, i18n_1.t)).catch(() => { });
11567
11620
  }
11621
+ /**
11622
+ * @description Wake the open requests of a tracker conversation whose process is gone — `restarted`, staggered by the
11623
+ * wake-up engine — instead of leaving them to the 90-minute backstop. A Telegram topic resumes through its own
11624
+ * lost-work path and is never woken here. The lost-work cooldown guards it as well: a conversation woken
11625
+ * automatically within it is left to the backstop, so a crash loop is no wake loop.
11626
+ */
11627
+ function scheduleTrackerRestartWake(key, why) {
11628
+ if ((0, sessionKeyCodec_1.checkIsTelegramKey)(key) || !requestWakeUpEngine)
11629
+ return;
11630
+ const lastAutoResumeAt = state.getLostWorkResumedAt(key);
11631
+ if (lastAutoResumeAt !== undefined && Date.now() - lastAutoResumeAt < lostWork_1.lostWorkResumeCooldownMs) {
11632
+ console.log(`[requests] ${(0, sessionKey_1.keyToString)(key)}: ${why}; it was woken automatically less than ${lostWork_1.lostWorkResumeCooldownMs / 60_000} min ago, so the backstop takes it`);
11633
+ return;
11634
+ }
11635
+ if (requestWakeUpEngine.scheduleRestartWake(key))
11636
+ console.log(`[requests] ${(0, sessionKey_1.keyToString)(key)}: ${why}; its open request is woken shortly`);
11637
+ }
11638
+ /**
11639
+ * @description The boot's pass over the open requests of tracker conversations: one whose process did not come back
11640
+ * with the boot (not adopted — the conversation sleeps) and that waits for nothing of its own — no post retry, no
11641
+ * progress follow-up, no armed usage-limit wait, not given up — is woken `restarted` ({@link scheduleTrackerRestartWake}).
11642
+ * A process that died with its own work pending is in it too: its lost-work note rides the same wake.
11643
+ */
11644
+ function scheduleRestartWakesAtBoot(requestLedger) {
11645
+ const keys = new Map();
11646
+ for (const { key, request } of requestLedger.listOpenRequests()) {
11647
+ if ((0, sessionKeyCodec_1.checkIsTelegramKey)(key) || keys.has((0, sessionKey_1.keyToString)(key)))
11648
+ continue;
11649
+ if ((0, wakeUpRules_1.checkIsWakingStopped)(request) || request.nextPostRetryAt !== undefined || request.nextWakeAt !== undefined)
11650
+ continue;
11651
+ if ((0, createAdapter_1.getThreadAdapter)(key).checkIsActive(key) || getArmedApiRetry(key)?.kind === 'usageLimit')
11652
+ continue;
11653
+ keys.set((0, sessionKey_1.keyToString)(key), key);
11654
+ }
11655
+ for (const key of keys.values())
11656
+ scheduleTrackerRestartWake(key, 'its session did not come back with the boot while a request was open');
11657
+ }
11568
11658
  /**
11569
11659
  * @description Resume the conversation with the lost-work note as its prompt; `false` when the post failed — the note
11570
11660
  * then stays for the next prompt.
@@ -11586,7 +11676,28 @@ function createLostWorkPostDeps() {
11586
11676
  return {
11587
11677
  ...createSessionPostDeps(),
11588
11678
  forwardPrompt: async (conversationKey, text) => {
11589
- await deliverPromptOrBuffer((0, sessionKey_1.keyFromString)(conversationKey), text, startupPromptBuffer.checkIsStarting(conversationKey));
11679
+ const buffered = createBufferedOutcome();
11680
+ const delivery = await deliverPromptOrBuffer((0, sessionKey_1.keyFromString)(conversationKey), text, startupPromptBuffer.checkIsStarting(conversationKey), buffered.settle);
11681
+ if (delivery === 'buffered')
11682
+ await buffered.assertReplayed();
11683
+ },
11684
+ };
11685
+ }
11686
+ /**
11687
+ * @description How a prompt that waited in the startup buffer ended, for a post that must know it reached the session:
11688
+ * `settle` is the buffer's callback, `assertReplayed` resolves once it was replayed into the session and rejects when it
11689
+ * was dropped — the start failed, or its write did not reach the agent.
11690
+ */
11691
+ function createBufferedOutcome() {
11692
+ let settle = () => { };
11693
+ const outcome = new Promise((resolve) => {
11694
+ settle = resolve;
11695
+ });
11696
+ return {
11697
+ settle: (result) => settle(result),
11698
+ assertReplayed: async () => {
11699
+ if ((await outcome) !== 'replayed')
11700
+ throw new Error('the prompt waited for the session to start and never reached the agent');
11590
11701
  },
11591
11702
  };
11592
11703
  }
@@ -12824,8 +12935,12 @@ function createSessionPostDeps() {
12824
12935
  // A scheduled run in a topic with requests on is a request (S7); a tracker's
12825
12936
  // post arrives with its request already open and its header in the text.
12826
12937
  const opening = await openTopicRequest(key, text, { source: 'scheduledRun', requesterId: topicRequest_1.scheduledRunRequester });
12827
- const delivery = await deliverPromptOrBuffer(key, `${opening.header}${text}`, startupPromptBuffer.checkIsStarting(conversationKey));
12938
+ const buffered = createBufferedOutcome();
12939
+ const delivery = await deliverPromptOrBuffer(key, `${opening.header}${text}`, startupPromptBuffer.checkIsStarting(conversationKey), buffered.settle);
12828
12940
  await settleTopicRequestAfterDelivery(key, opening, delivery);
12941
+ // A prompt that waited for the session's start counts only once it reached it: a replay whose write failed is a failed post.
12942
+ if (delivery === 'buffered')
12943
+ await buffered.assertReplayed();
12829
12944
  },
12830
12945
  now: () => Date.now(),
12831
12946
  sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
@@ -13211,6 +13326,15 @@ function createJiraSessionDeps(requestLedger, slots, adapterName) {
13211
13326
  if (!posted.isHeld)
13212
13327
  await requestWakeUpEngine?.trackForwardedTurn(key, requestId, { isRequestPrompt: true });
13213
13328
  },
13329
+ // An issue update (a comment for an open hand-over request) opens no request: the turn it starts is that request's.
13330
+ postUpdate: async (key, prompt, getTargetRequestId) => {
13331
+ notePersonActivity(key);
13332
+ const posted = await (0, postToSession_1.postToSession)(sessionPostDeps, (0, sessionKey_1.keyToString)(key), prompt, adapterName);
13333
+ if (!posted.ok)
13334
+ throw new Error(posted.reason === 'forward-failed' ? posted.error : `session ${posted.reason}`);
13335
+ if (!posted.isHeld)
13336
+ await requestWakeUpEngine?.trackForwardedTurn(key, getTargetRequestId());
13337
+ },
13214
13338
  };
13215
13339
  }
13216
13340
  async function startBot() {
@@ -13319,6 +13443,11 @@ async function startBot() {
13319
13443
  return result.ok ? (result.alertRef ?? null) : null;
13320
13444
  },
13321
13445
  backstopMs: (0, wakeUpRules_1.getRequestBackstopMs)(process.env.REQUEST_BACKSTOP_MINUTES),
13446
+ restartWakeStaggerMs: ENV.testTimings.requestRestartWakeStaggerMs,
13447
+ // The stamp of the lost-work cooldown: a conversation woken after a restart is not woken so again within it.
13448
+ noteRestartWakeDelivered: (key) => {
13449
+ void state.setLostWorkResumedAt(key, Date.now());
13450
+ },
13322
13451
  pollIntervalMs: ENV.testTimings.requestTurnPollMs,
13323
13452
  sweepIntervalMs: ENV.testTimings.requestSweepIntervalMs,
13324
13453
  firstPostRetryDelayMs: ENV.testTimings.requestFirstPostRetryDelayMs,
@@ -13608,6 +13737,8 @@ async function startBot() {
13608
13737
  markSessionsRestored();
13609
13738
  // From here the engine can tell a live turn from a dead session.
13610
13739
  requestWakeUpEngine?.start();
13740
+ // A tracker conversation whose process did not survive the downtime resumes its open request now, not at the backstop.
13741
+ scheduleRestartWakesAtBoot(requestLedger);
13611
13742
  todoReminderEngine?.start();
13612
13743
  jiraConnector?.start(createJiraSessionDeps(requestLedger, slots, jiraConnector.adapterName));
13613
13744
  },
@@ -13632,9 +13763,11 @@ async function startBot() {
13632
13763
  // and the CLI never retries a failed MCP server. Fire-and-forget.
13633
13764
  healSchedulerMcpForActiveSessions();
13634
13765
  },
13635
- // Boot catch-up replay: arm every persisted job, fire one catch-up per
13766
+ // Boot catch-up replay: arm every persisted job, START one catch-up per
13636
13767
  // missed run. Independent of the MCP server (delivery does not need it).
13637
- rearmSchedules: () => schedulerEngine.rearmAll().catch((e) => console.error('[scheduler] rearmAll failed:', e)),
13768
+ // It never waits for a delivery — one waits for its agent, which may wait for
13769
+ // an answer that only polling (started after this phase) can bring.
13770
+ rearmSchedules: () => schedulerEngine.rearmAll(),
13638
13771
  });
13639
13772
  // 5a. Refresh pinned banners for every binding. Threads that have a
13640
13773
  // stored `pinnedStatusMessageId` get their banner edited in place;