typeclaw 0.48.2 → 0.48.4

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 (40) hide show
  1. package/package.json +2 -2
  2. package/scripts/dump-system-prompt.ts +146 -11
  3. package/src/agent/index.ts +35 -9
  4. package/src/agent/plugin-tools.ts +21 -0
  5. package/src/agent/todo/continuation-policy.ts +11 -1
  6. package/src/agent/todo/continuation-state.ts +3 -1
  7. package/src/agent/todo/continuation-wiring.ts +2 -0
  8. package/src/agent/tool-file-safety.ts +19 -3
  9. package/src/agent/tools/channel-reply.ts +18 -1
  10. package/src/agent/tools/runtime-notice.ts +29 -0
  11. package/src/bundled-plugins/github-cli-auth/git-command.ts +497 -652
  12. package/src/bundled-plugins/memory/load-memory.ts +23 -27
  13. package/src/bundled-plugins/security/index.ts +1 -0
  14. package/src/bundled-plugins/security/policies/private-surface-read.ts +152 -40
  15. package/src/channels/adapters/discord-bot-reactions.ts +1 -0
  16. package/src/channels/adapters/discord-bot.ts +11 -2
  17. package/src/channels/adapters/discord-reactions.ts +1 -0
  18. package/src/channels/adapters/discord.ts +1 -0
  19. package/src/channels/adapters/slack-bot.ts +11 -2
  20. package/src/channels/adapters/slack.ts +1 -0
  21. package/src/channels/completion-claim.ts +307 -0
  22. package/src/channels/router.ts +307 -102
  23. package/src/channels/types.ts +4 -1
  24. package/src/cli/hostd.ts +1 -1
  25. package/src/config/providers.ts +16 -10
  26. package/src/hostd/kakao-renewal-manager.ts +23 -11
  27. package/src/init/models-dev.ts +25 -8
  28. package/src/mcp/client.ts +65 -7
  29. package/src/mcp/tools.ts +71 -4
  30. package/src/permissions/index.ts +1 -0
  31. package/src/permissions/permissions.ts +23 -0
  32. package/src/plugin/index.ts +1 -0
  33. package/src/plugin/manager.ts +19 -1
  34. package/src/plugin/types.ts +9 -0
  35. package/src/sandbox/canonical-secrets.ts +24 -4
  36. package/src/sandbox/hidden-paths.ts +8 -3
  37. package/src/sandbox/index.ts +2 -0
  38. package/src/secrets/kakao-renewal.ts +123 -20
  39. package/src/skills/typeclaw-permissions/SKILL.md +13 -1
  40. package/src/skills/typeclaw-plugins/SKILL.md +91 -11
@@ -28,6 +28,7 @@ import {
28
28
  recordTurnStart,
29
29
  runIdleContinuation,
30
30
  } from '@/agent/todo/continuation-wiring'
31
+ import { defuseRuntimeMarkers } from '@/agent/tools/runtime-notice'
31
32
  import { SUBAGENT_OUTPUT_TOOL_NAME } from '@/agent/tools/subagent-output'
32
33
  import { promptPersistentTurnWithFallback } from '@/agent/turn-runner'
33
34
  import { type Command, type CommandPermission, type CommandResult, createCommandRegistry } from '@/commands'
@@ -39,6 +40,7 @@ import type { Stream } from '@/stream'
39
40
 
40
41
  import { extractMentionedUserIds } from './adapters/mention-hints'
41
42
  import { formatChannelCommandHelp } from './commands'
43
+ import { isQualifyingWorkResult } from './completion-claim'
42
44
  import { detectContinuationWillingness } from './continuation-willingness'
43
45
  import { describeError } from './describe-error'
44
46
  import {
@@ -196,6 +198,7 @@ export const SESSION_GC_INTERVAL_MS = 60 * 1000
196
198
  // recovery paths (`source: 'system'`) bypass.
197
199
  export const MAX_CHANNEL_SENDS_PER_TURN = 10
198
200
  export const ENGAGE_REACTION_EMOJI = 'eyes'
201
+ export const CONTINUATION_REACTION_EMOJI = 'hourglass_flowing_sand'
199
202
  // Best-effort "zipping it / going quiet" ack dropped on the triggering message
200
203
  // when the model disengages (channel_disengage); fire-and-forget like engage :eyes:.
201
204
  export const DISENGAGE_REACTION_EMOJI = 'zipper_mouth_face'
@@ -456,20 +459,31 @@ export const MAX_WILLINGNESS_NUDGES = 1
456
459
  // Injected when a reply that ended the turn (terminal-reply abort) promised to
457
460
  // keep working but omitted `more_work_this_turn: true`. Reminder-only, SYSTEM MESSAGE
458
461
  // framing so persona-rich models do not reply to the notice itself.
462
+ // Leads with the DELIVERY imperative, mirroring SEND_WILLINGNESS_NUDGE below. An
463
+ // earlier revision closed on a bare "If there is nothing left to do, reply with
464
+ // `NO_REPLY`" and production models took that door after doing the promised work:
465
+ // "nothing left to DO" reads as satisfied the moment the investigation finishes,
466
+ // so the turn exited silent while still holding the answer. Splitting "no work
467
+ // left" from "nothing to report", and scoping NO_REPLY to already-delivered, is
468
+ // the load-bearing part of this wording — do not collapse it back.
459
469
  export const WILLINGNESS_NUDGE = [
460
470
  '---',
461
471
  '**[SYSTEM MESSAGE — not from a human]**',
462
472
  '',
463
- 'Your last reply said you would keep working this turn, but it ended right',
464
- 'after sending — a successful channel reply ends the turn unless you set',
473
+ 'Your last reply promised the human you would keep working, but the turn ended',
474
+ 'right after sending — a successful channel reply ends the turn unless you set',
465
475
  '`more_work_this_turn: true` on it. This is an automated signal from the channel',
466
476
  'router, not a message from anyone in the chat. **Do not acknowledge or reply to',
467
477
  'this notice itself.**',
468
478
  '',
469
- 'If you still have work to do (fetch data, run a tool, spawn a subagent, then',
470
- 'reply with the result), do it now — and on the status reply that precedes more',
471
- 'work this turn, set `more_work_this_turn: true`. If there is nothing left to do,',
472
- 'reply with `NO_REPLY`.',
479
+ 'Someone is waiting on the result you just promised. Do the work now (fetch data,',
480
+ 'run a tool, spawn a subagent) and post what you find — and on any further status',
481
+ 'reply that precedes more work this turn, set `more_work_this_turn: true`. If you',
482
+ 'already did the work, post the conclusion you reached: having no work left is NOT',
483
+ 'the same as having nothing to report, and a promise that never lands reads to the',
484
+ 'human as being ignored.',
485
+ '',
486
+ '`NO_REPLY` is correct ONLY if the result you promised is already in the channel.',
473
487
  '',
474
488
  '---',
475
489
  ].join('\n')
@@ -480,6 +494,10 @@ export const WILLINGNESS_NUDGE = [
480
494
  // needs `more_work_this_turn: true`; this path is a `channel_send` (which never ends the
481
495
  // turn) whose follow-up degenerated, so the model just needs to emit the reply it
482
496
  // already worked out. Shares MAX_WILLINGNESS_NUDGES so a turn can't double-nudge.
497
+ // Scopes NO_REPLY the same way WILLINGNESS_NUDGE does, and for the same reason:
498
+ // both nudges share `willingnessNudges`, so both are covered by the
499
+ // `no_reply_after_willingness_nudge` fallback. A nudge that still advertised
500
+ // NO_REPLY as an ordinary exit would contradict the guard that answers it.
483
501
  export const SEND_WILLINGNESS_NUDGE = [
484
502
  '---',
485
503
  '**[SYSTEM MESSAGE — not from a human]**',
@@ -489,8 +507,12 @@ export const SEND_WILLINGNESS_NUDGE = [
489
507
  'message. This is an automated signal from the channel router, not a message',
490
508
  'from anyone in the chat. **Do not acknowledge or reply to this notice itself.**',
491
509
  '',
492
- 'Send the answer you just worked out now via your channel send tool. If you',
493
- 'genuinely have nothing to report, reply with `NO_REPLY`.',
510
+ 'Send the answer you just worked out now via your channel send tool. Post what',
511
+ 'you found even if the finding is "no change" or "it failed" — someone is waiting',
512
+ 'on the result you promised, and having no work left is not the same as having',
513
+ 'nothing to report.',
514
+ '',
515
+ '`NO_REPLY` is correct ONLY if the result you promised is already in the channel.',
494
516
  '',
495
517
  '---',
496
518
  ].join('\n')
@@ -906,6 +928,12 @@ type LiveSession = {
906
928
  // legitimately keeps its "seen, not replying" ack, unlike the transient
907
929
  // engage :eyes: which teardown must strip.
908
930
  activeSilentAckReactions: Array<Promise<ReactionRef | null>>
931
+ // One add promise per willingness status posted by the agent, resolving to
932
+ // the removable reaction-instance ref. Cross-turn state on purpose: the
933
+ // hourglass stays visible until a substantive result, fallback, explicit
934
+ // silence, stop, or teardown retires every outstanding promise. Storing the
935
+ // promise synchronously prevents cleanup racing a slow reaction add.
936
+ activeContinuationReactions: Array<Promise<ReactionRef | null>>
909
937
  lastTurnAuthorIds: Set<string>
910
938
  // Mirror of currentTurnAuthorId at end-of-turn (the LAST speaker of the
911
939
  // prior batch), preserved across the drain finally-block which resets
@@ -931,6 +959,11 @@ type LiveSession = {
931
959
  // the drain loop's run condition checks BOTH queues so a system
932
960
  // reminder alone is enough to trigger a turn.
933
961
  pendingSystemReminders: string[]
962
+ // True only for the reminder-only iteration that consumed a willingness
963
+ // nudge. `willingnessNudges` persists across the logical turn, so it remains
964
+ // nonzero after a substantive result and would misclassify NO_REPLY from a
965
+ // later unrelated reminder as another dropped promise.
966
+ willingnessReminderIteration: boolean
934
967
  consecutiveSends: Map<string, number>
935
968
  // Per-(chat:thread) text of the last reserved bot send. Set
936
969
  // SYNCHRONOUSLY inside router.send before the outbound callback awaits,
@@ -1041,6 +1074,10 @@ type LiveSession = {
1041
1074
  // reason-specific stranded-toolUse recovery logs. `turnSeq`-stamped so stale
1042
1075
  // abort provenance from an earlier turn can never leak into a later retry.
1043
1076
  abortReasonThisTurn: { turnSeq: number; reason: string } | null
1077
+ // Set synchronously when a user invokes /stop so user intent supersedes a
1078
+ // terminal-reply stamp even while abort delivery or outcome persistence is
1079
+ // still in flight. Cleared only when a fresh real-user batch starts.
1080
+ userStoppedTurnSeq: number | null
1044
1081
  // One-shot output-token budget for the NEXT `session.prompt()` only.
1045
1082
  // `installChannelOutputCap` reads and clears it per stream call, so it
1046
1083
  // overrides the default backstop for exactly one re-prompt. Set by the
@@ -1133,6 +1170,10 @@ type LiveSession = {
1133
1170
  // retry iterations that end the turn. Reset ONLY on a real user batch,
1134
1171
  // beside `githubReviewOutputTurn`.
1135
1172
  toolExecutionThisLogicalTurn: boolean
1173
+ // Successful, non-communication, non-control tool output observed during
1174
+ // this logical turn. Unlike toolExecutionThisLogicalTurn, channel_reply and
1175
+ // todo/control calls cannot satisfy a later durable completion claim.
1176
+ qualifyingWorkThisLogicalTurn: boolean
1136
1177
  // True while a successful `channel_reply({ more_work_this_turn: true })`
1137
1178
  // promise remains unfulfilled in this LOGICAL turn. Unlike the per-iteration
1138
1179
  // `continueReplyTurn` stamp used by retry authorization and empty-stop
@@ -1201,6 +1242,10 @@ type LiveSession = {
1201
1242
  unsubProviderErrors: (() => void) | null
1202
1243
  unsubTypingActivity: (() => void) | null
1203
1244
  unsubTodoOutcome: (() => void) | null
1245
+ // Serializes outcome persistence. The tail always fulfills so one disk
1246
+ // failure cannot poison every later turn; its value separately reports
1247
+ // whether the latest write succeeded before continuation reads state.
1248
+ todoOutcomeWrite: Promise<boolean>
1204
1249
  }
1205
1250
 
1206
1251
  // `event` is null for command invocations that originated outside the inbound
@@ -1271,6 +1316,7 @@ export type ChannelRouter = {
1271
1316
  chat: string
1272
1317
  thread?: string | null
1273
1318
  }) => number
1319
+ hasQualifyingWorkThisLogicalTurn?: (target: ChannelKey) => boolean
1274
1320
  getSendRate: (target: {
1275
1321
  adapter: ChannelKey['adapter']
1276
1322
  workspace: string
@@ -1575,6 +1621,9 @@ export type CreateChannelRouterOptions = {
1575
1621
  // than pre-seeding pendingSystemReminders from onPrompt (which would pass even if
1576
1622
  // the resolver moved ahead of the continuation).
1577
1623
  runIdleContinuation?: typeof runIdleContinuation
1624
+ // Test seam for holding an outcome write open and asserting drain ordering.
1625
+ // Production always uses the real persistence function.
1626
+ recordTurnOutcome?: typeof recordTurnOutcome
1578
1627
  // Test seam: override the ensureLive watchdog ceiling so the timeout path
1579
1628
  // is exercisable in <100ms instead of the 30s production default.
1580
1629
  ensureLiveTimeoutMs?: number
@@ -2238,6 +2287,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2238
2287
  originRef,
2239
2288
  promptQueue: [],
2240
2289
  pendingSystemReminders: [],
2290
+ willingnessReminderIteration: false,
2241
2291
  contextBuffer: [],
2242
2292
  currentTurnAttachments: [],
2243
2293
  historyTimedAttachments: [],
@@ -2263,6 +2313,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2263
2313
  pendingTurnReactions: [],
2264
2314
  silentAckTurn: null,
2265
2315
  activeSilentAckReactions: [],
2316
+ activeContinuationReactions: [],
2266
2317
  // `lastTurnAuthorId` (string, used for `lastInboundAuthorId` in
2267
2318
  // origin) and `lastTurnAuthorIds` (Set, used by
2268
2319
  // `grantStickyForReplyTargets` as the fallback when
@@ -2292,6 +2343,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2292
2343
  lastTerminalReplyAbort: null,
2293
2344
  continueReplyTurn: null,
2294
2345
  abortReasonThisTurn: null,
2346
+ userStoppedTurnSeq: null,
2295
2347
  nextPromptMaxTokens: undefined,
2296
2348
  skippedTurn: null,
2297
2349
  skipLockedSendTurn: null,
@@ -2300,6 +2352,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2300
2352
  stagedFallbackCause: null,
2301
2353
  githubReviewOutputTurn: null,
2302
2354
  toolExecutionThisLogicalTurn: false,
2355
+ qualifyingWorkThisLogicalTurn: false,
2303
2356
  promisedWorkOutstandingThisLogicalTurn: false,
2304
2357
  pendingQuoteCandidate: null,
2305
2358
  recentEngagedPeerBotTurns: [],
@@ -2315,6 +2368,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2315
2368
  unsubProviderErrors: null,
2316
2369
  unsubTypingActivity: null,
2317
2370
  unsubTodoOutcome: null,
2371
+ todoOutcomeWrite: Promise.resolve(true),
2318
2372
  }
2319
2373
  // Raw text is logged on EVERY attempt for operators; the user-facing
2320
2374
  // notice is deferred. The upstream SDK retries internally, and each retry
@@ -2332,13 +2386,24 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2332
2386
  live.unsubTodoOutcome = created.session.subscribe((event: unknown) => {
2333
2387
  const usage = extractTurnUsage(event)
2334
2388
  if (usage === null) return
2335
- void recordTurnOutcome({
2389
+ const stampedAbort = live.abortReasonThisTurn
2390
+ const termination: 'terminal-after-channel-reply' | undefined =
2391
+ usage.stopReason === 'aborted' &&
2392
+ live.userStoppedTurnSeq !== live.turnSeq &&
2393
+ stampedAbort?.turnSeq === live.turnSeq &&
2394
+ stampedAbort.reason === 'terminal_after_channel_reply'
2395
+ ? 'terminal-after-channel-reply'
2396
+ : undefined
2397
+ if (stampedAbort?.turnSeq === live.turnSeq) live.abortReasonThisTurn = null
2398
+ const outcomeArgs = {
2336
2399
  agentDir: options.agentDir,
2337
2400
  origin: buildLiveOrigin(live),
2338
2401
  turnId: live.sessionId,
2339
2402
  stopReason: usage.stopReason,
2403
+ ...(termination !== undefined ? { termination } : {}),
2340
2404
  ...(usage.tokens !== undefined ? { tokens: usage.tokens } : {}),
2341
- }).catch((err) => logger.error(`[channels] ${live.keyId}: todo outcome capture failed: ${describeError(err)}`))
2405
+ }
2406
+ enqueueTodoOutcomeWrite(live, outcomeArgs)
2342
2407
  })
2343
2408
  live.unsubTypingActivity = subscribeTypingActivity(created.session, live)
2344
2409
  installChannelReplyTerminalHook(live)
@@ -2681,6 +2746,15 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2681
2746
  agent.afterToolCall = async (context, signal) => {
2682
2747
  const result = prior ? await prior(context, signal) : undefined
2683
2748
  const details = context.result.details as { ok?: unknown; more_work_this_turn?: unknown } | undefined
2749
+ if (
2750
+ isQualifyingWorkResult({
2751
+ toolName: context.toolCall.name,
2752
+ isError: context.isError,
2753
+ details: context.result.details,
2754
+ })
2755
+ ) {
2756
+ live.qualifyingWorkThisLogicalTurn = true
2757
+ }
2684
2758
  const succeeded = context.toolCall.name === 'channel_reply' && !context.isError && details?.ok === true
2685
2759
  const keepTurnAlive = details?.more_work_this_turn === true
2686
2760
  if (succeeded) {
@@ -2693,7 +2767,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2693
2767
  live.continueReplyTurn = { turnSeq: live.turnSeq, sendCount: live.successfulChannelSends }
2694
2768
  }
2695
2769
  }
2696
- if (succeeded && !keepTurnAlive && agent.signal?.aborted !== true) {
2770
+ if (succeeded && !keepTurnAlive && agent.signal?.aborted !== true && live.userStoppedTurnSeq !== live.turnSeq) {
2697
2771
  logger.info(`[channels] ${live.keyId} terminal_after_channel_reply`)
2698
2772
  const replyText = (context.toolCall.arguments as { text?: unknown } | undefined)?.text
2699
2773
  live.lastTerminalReplyAbort = typeof replyText === 'string' ? { turnSeq: live.turnSeq, text: replyText } : null
@@ -2813,34 +2887,51 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2813
2887
  const maybeContinueTodosChannel = async (live: LiveSession): Promise<void> => {
2814
2888
  if (live.destroyed) return
2815
2889
  if (live.promptQueue.length > 0 || live.pendingSystemReminders.length > 0) return
2816
- try {
2817
- await (options.runIdleContinuation ?? runIdleContinuation)({
2818
- agentDir: options.agentDir,
2819
- origin: buildLiveOrigin(live),
2820
- deliver: (text) => {
2821
- live.pendingSystemReminders.push(text)
2822
- },
2823
- })
2824
- } catch (err) {
2825
- logger.warn(`[channels] ${live.keyId}: todo continuation failed: ${describeError(err)}`)
2826
- }
2890
+ // Joined to the outcome-write chain so a concurrent /stop's durable abort is
2891
+ // ORDERED AFTER this decision's own state write instead of racing it. The
2892
+ // decision itself awaits disk, so the stop marker is re-read at delivery
2893
+ // time too: a user who stops mid-decision must not receive the reminder.
2894
+ const decision = live.todoOutcomeWrite.then(async () => {
2895
+ try {
2896
+ await (options.runIdleContinuation ?? runIdleContinuation)({
2897
+ agentDir: options.agentDir,
2898
+ origin: buildLiveOrigin(live),
2899
+ deliver: (text) => {
2900
+ if (live.destroyed || live.userStoppedTurnSeq === live.turnSeq) {
2901
+ logger.info(`[channels] ${live.keyId}: dropping todo continuation reminder after user stop`)
2902
+ return
2903
+ }
2904
+ live.pendingSystemReminders.push(text)
2905
+ },
2906
+ })
2907
+ } catch (err) {
2908
+ logger.warn(`[channels] ${live.keyId}: todo continuation failed: ${describeError(err)}`)
2909
+ }
2910
+ return true
2911
+ })
2912
+ live.todoOutcomeWrite = decision
2913
+ await decision
2827
2914
  }
2828
2915
 
2829
2916
  const postEmptyTurnFallback = async (live: LiveSession, cause: string): Promise<void> => {
2830
2917
  logger.warn(`[channels] ${live.keyId} empty_turn_fallback cause=${cause}`)
2831
2918
  live.emptyTurnFallbackTurn = live.turnSeq
2832
- const result = await send(
2833
- {
2834
- adapter: live.key.adapter,
2835
- workspace: live.key.workspace,
2836
- chat: live.key.chat,
2837
- thread: live.key.thread,
2838
- text: EMPTY_TURN_FALLBACK_TEXT,
2839
- },
2840
- { source: 'system', outputKind: 'meta' },
2841
- )
2842
- if (!result.ok) {
2843
- logger.warn(`[channels] ${live.keyId}: empty-turn fallback send failed: ${result.error}`)
2919
+ try {
2920
+ const result = await send(
2921
+ {
2922
+ adapter: live.key.adapter,
2923
+ workspace: live.key.workspace,
2924
+ chat: live.key.chat,
2925
+ thread: live.key.thread,
2926
+ text: EMPTY_TURN_FALLBACK_TEXT,
2927
+ },
2928
+ { source: 'system', outputKind: 'meta' },
2929
+ )
2930
+ if (!result.ok) {
2931
+ logger.warn(`[channels] ${live.keyId}: empty-turn fallback send failed: ${result.error}`)
2932
+ }
2933
+ } finally {
2934
+ void dropContinuationReactions(live)
2844
2935
  }
2845
2936
  }
2846
2937
 
@@ -2953,6 +3044,31 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2953
3044
  }
2954
3045
  }
2955
3046
 
3047
+ const enqueueTodoOutcomeWrite = (
3048
+ live: LiveSession,
3049
+ args: Parameters<typeof recordTurnOutcome>[0],
3050
+ ): Promise<boolean> => {
3051
+ const write = live.todoOutcomeWrite.then(async () => {
3052
+ try {
3053
+ await (options.recordTurnOutcome ?? recordTurnOutcome)(args)
3054
+ return true
3055
+ } catch (err) {
3056
+ logger.error(`[channels] ${live.keyId}: todo outcome capture failed: ${describeError(err)}`)
3057
+ return false
3058
+ }
3059
+ })
3060
+ live.todoOutcomeWrite = write
3061
+ return write
3062
+ }
3063
+
3064
+ const awaitLatestTodoOutcomeWrite = async (live: LiveSession): Promise<boolean> => {
3065
+ while (true) {
3066
+ const write = live.todoOutcomeWrite
3067
+ const succeeded = await write
3068
+ if (write === live.todoOutcomeWrite) return succeeded
3069
+ }
3070
+ }
3071
+
2956
3072
  const fireSessionEnd = async (live: LiveSession): Promise<void> => {
2957
3073
  if (!live.hooks) return
2958
3074
  try {
@@ -2963,12 +3079,22 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2963
3079
  }
2964
3080
 
2965
3081
  const stopCurrentChannelTurn = async (live: LiveSession): Promise<void> => {
3082
+ live.userStoppedTurnSeq = live.turnSeq
3083
+ live.lastTerminalReplyAbort = null
3084
+ live.abortReasonThisTurn = { turnSeq: live.turnSeq, reason: 'user_stop' }
2966
3085
  if (live.debounceTimer) clearTimeout(live.debounceTimer)
2967
3086
  live.debounceTimer = null
2968
3087
  live.firstUnprocessedAt = 0
2969
3088
  live.promptQueue.length = 0
2970
3089
  live.pendingSystemReminders.length = 0
2971
3090
  live.continueReplyTurn = null
3091
+ void dropContinuationReactions(live)
3092
+ enqueueTodoOutcomeWrite(live, {
3093
+ agentDir: options.agentDir,
3094
+ origin: buildLiveOrigin(live),
3095
+ turnId: live.sessionId,
3096
+ stopReason: 'aborted',
3097
+ })
2972
3098
  await stopTypingHeartbeat(live)
2973
3099
  try {
2974
3100
  await live.session.abort()
@@ -2976,6 +3102,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2976
3102
  } catch (err) {
2977
3103
  logger.warn(`[channels] ${live.keyId}: command /stop abort failed: ${describeError(err)}`)
2978
3104
  }
3105
+ await awaitLatestTodoOutcomeWrite(live)
2979
3106
  }
2980
3107
 
2981
3108
  // ensureLive() installs a session BEFORE the engage/observe decision, so a
@@ -3089,6 +3216,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3089
3216
  const observed = live.contextBuffer.splice(0, live.contextBuffer.length)
3090
3217
  const reminders = live.pendingSystemReminders.splice(0, live.pendingSystemReminders.length)
3091
3218
  live.currentTurnAttachments = collectTurnAttachments(observed, batch)
3219
+ live.willingnessReminderIteration =
3220
+ batch.length === 0 && reminders.some((r) => r === WILLINGNESS_NUDGE || r === SEND_WILLINGNESS_NUDGE)
3092
3221
 
3093
3222
  if (batch.length > 0) {
3094
3223
  // A fresh user batch starts a NEW logical turn. Drop any provider
@@ -3136,12 +3265,14 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3136
3265
  live.stagedFallbackCause = null
3137
3266
  }
3138
3267
  live.abortReasonThisTurn = null
3268
+ live.userStoppedTurnSeq = null
3139
3269
  live.nextPromptMaxTokens = undefined
3140
3270
  // Cleared with the retry budgets (NOT beside resetReviewTurn below) so a
3141
3271
  // review landed earlier in this logical turn keeps suppressing the
3142
3272
  // empty-turn fallback across the reminder-only retry iterations.
3143
3273
  live.githubReviewOutputTurn = null
3144
3274
  live.toolExecutionThisLogicalTurn = false
3275
+ live.qualifyingWorkThisLogicalTurn = false
3145
3276
  live.promisedWorkOutstandingThisLogicalTurn = false
3146
3277
  } else if (live.lastTurnAuthorId !== null) {
3147
3278
  live.currentTurnEngageReactions = []
@@ -3200,6 +3331,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3200
3331
  live.policyDeniedToolSendsThisTurn.clear()
3201
3332
  resetReviewTurn(live.sessionId)
3202
3333
  const isRealUserTurn = batch.length > 0
3334
+ await awaitLatestTodoOutcomeWrite(live)
3335
+ await recordTodoTurnStart(live, isRealUserTurn)
3203
3336
  const retrievalQuery = composeRetrievalQuery(batch)
3204
3337
  // A fresh real-user batch opens a new logical turn. Capture its question
3205
3338
  // shape as PENDING (committed only once the turn completes below). The
@@ -3345,8 +3478,14 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3345
3478
  await fireSessionTurnEnd(live)
3346
3479
  }
3347
3480
  await fireSessionIdle(live)
3348
- await recordTodoTurnStart(live, isRealUserTurn)
3349
- await maybeContinueTodosChannel(live)
3481
+ const outcomeWriteSucceeded = await awaitLatestTodoOutcomeWrite(live)
3482
+ if (!outcomeWriteSucceeded) {
3483
+ logger.warn(`[channels] ${live.keyId}: skipping todo continuation after failed outcome write`)
3484
+ } else if (live.userStoppedTurnSeq === live.turnSeq) {
3485
+ logger.info(`[channels] ${live.keyId}: skipping todo continuation after user stop`)
3486
+ } else {
3487
+ await maybeContinueTodosChannel(live)
3488
+ }
3350
3489
  await resolveStagedFallback(live)
3351
3490
  live.lastTurnAuthorIds = new Set(live.currentTurnAuthorIds)
3352
3491
  if (live.currentTurnAuthorId !== null) {
@@ -4491,8 +4630,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4491
4630
  live.pendingQuoteCandidate = null
4492
4631
  }
4493
4632
  const text = normalizeSendText(msg.text)
4494
- const outputKind =
4495
- opts?.outputKind ?? (text !== undefined && detectContinuationWillingness(text) ? 'status' : 'substantive')
4633
+ const continuationWillingness = text !== undefined && detectContinuationWillingness(text)
4634
+ const outputKind = opts?.outputKind ?? (continuationWillingness ? 'status' : 'substantive')
4496
4635
 
4497
4636
  // Central enforcement. Tool-initiated sends are subject to two policies:
4498
4637
  // a per-turn count cap (kills runaway loops regardless of content) and
@@ -4586,6 +4725,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4586
4725
  let delivered = false
4587
4726
  let messageId: string | undefined
4588
4727
  let messageIds: readonly string[] | undefined
4728
+ let reactionRef: ReactionRef | undefined
4589
4729
  try {
4590
4730
  for (const cb of snapshot) {
4591
4731
  const result = await cb(msg)
@@ -4593,6 +4733,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4593
4733
  delivered = true
4594
4734
  messageId = result.messageId
4595
4735
  messageIds = result.messageIds
4736
+ reactionRef = result.reactionRef
4596
4737
  break
4597
4738
  }
4598
4739
  lastError = result.error
@@ -4623,6 +4764,12 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4623
4764
  return { ok: false, error: lastError ?? 'no callback accepted the outbound', code: 'callback-rejected' }
4624
4765
  }
4625
4766
 
4767
+ if (live && continuationWillingness && reactionRef !== undefined) {
4768
+ reactOnContinuationWillingness(live, reactionRef)
4769
+ } else if (live && !continuationWillingness && outputKind === 'substantive') {
4770
+ void dropContinuationReactions(live)
4771
+ }
4772
+
4626
4773
  if (live) {
4627
4774
  live.successfulChannelSends++
4628
4775
  // Promise fulfillment follows OUTPUT KIND, never source:
@@ -4687,6 +4834,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4687
4834
  ok: true,
4688
4835
  ...(messageId !== undefined ? { messageId } : {}),
4689
4836
  ...(messageIds !== undefined ? { messageIds } : {}),
4837
+ ...(reactionRef !== undefined ? { reactionRef } : {}),
4690
4838
  }
4691
4839
  }
4692
4840
 
@@ -4729,6 +4877,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4729
4877
  live.skippedTurn = null
4730
4878
  logger.info(`[channels] ${live.keyId} skipped_by_tool reason=${JSON.stringify(reason)}`)
4731
4879
  armSilentTurnAck(live, 'skip_response')
4880
+ void dropContinuationReactions(live)
4732
4881
  return
4733
4882
  }
4734
4883
  if (live.skippedTurn !== null && live.skippedTurn.turnSeq === live.turnSeq) {
@@ -5092,9 +5241,23 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5092
5241
  await postEmptyTurnFallback(live, 'empty_stop_after_tool_work_retries_exhausted')
5093
5242
  return
5094
5243
  }
5244
+ // Explicit NO_REPLY normally records a deliberate choice to stay silent.
5245
+ // Only the reminder iteration that consumed a willingness nudge is different:
5246
+ // the turn-persistent nudge budget remains nonzero after a substantive result,
5247
+ // so using it here would post a bogus fallback on a later unrelated reminder.
5248
+ if (
5249
+ isNoReplySignal(assistantText) &&
5250
+ live.willingnessReminderIteration &&
5251
+ live.successfulChannelSends === successfulSendsBeforePrompt &&
5252
+ live.promptQueue.length === 0
5253
+ ) {
5254
+ await postEmptyTurnFallback(live, 'no_reply_after_willingness_nudge')
5255
+ return
5256
+ }
5095
5257
  const leakedReasoning = !isNoReplySignal(assistantText)
5096
5258
  logger.info(`[channels] ${live.keyId} no_reply${leakedReasoning ? ' (with_leaked_reasoning)' : ''}`)
5097
5259
  armSilentTurnAck(live, 'no_reply')
5260
+ void dropContinuationReactions(live)
5098
5261
  return
5099
5262
  }
5100
5263
 
@@ -5290,6 +5453,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5290
5453
  return live.consecutiveSends.get(consecutiveSendKey(target.chat, target.thread)) ?? 0
5291
5454
  }
5292
5455
 
5456
+ const hasQualifyingWorkThisLogicalTurn = (target: ChannelKey): boolean => {
5457
+ return liveSessions.get(channelKeyId(target))?.qualifyingWorkThisLogicalTurn === true
5458
+ }
5459
+
5293
5460
  const getSendRate = (target: {
5294
5461
  adapter: ChannelKey['adapter']
5295
5462
  workspace: string
@@ -5322,6 +5489,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5322
5489
  clearQueuedEngageReactions(live)
5323
5490
  dropEngageReactions(live, live.currentTurnEngageReactions)
5324
5491
  live.currentTurnEngageReactions = []
5492
+ void dropContinuationReactions(live)
5325
5493
  if (live.debounceTimer) clearTimeout(live.debounceTimer)
5326
5494
  live.debounceTimer = null
5327
5495
  live.unsubProviderErrors?.()
@@ -5359,12 +5527,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5359
5527
  if (live.draining) continue
5360
5528
  if (live.promptQueue.length > 0) continue
5361
5529
  // pendingSystemReminders is checked alongside promptQueue because both
5362
- // represent pending work that drain() will process. Today's only
5363
- // populator (injectSubagentCompletionReminder) also fires drain()
5364
- // synchronously, which sets draining=true and shadows this guard via
5365
- // the line above — but the guard exists to keep the invariant honest
5366
- // for any future caller that queues a reminder without immediately
5367
- // waking the drain loop.
5530
+ // represent pending work that drain() will process. Reminder injection
5531
+ // wakes an idle session immediately, but deliberately leaves a pending
5532
+ // inbound debounce in charge so both queues coalesce into one turn.
5368
5533
  if (live.pendingSystemReminders.length > 0) continue
5369
5534
  if (t - live.lastInboundAt <= SESSION_IDLE_MS) continue
5370
5535
  if (isPinnedByRunningChild(live.sessionId, live.keyId, 'idle_gc evicting')) continue
@@ -5760,17 +5925,12 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5760
5925
  // hard-block that legitimate fetch.
5761
5926
  forgetSharedLoopGuardTool(live.sessionId, SUBAGENT_OUTPUT_TOOL_NAME)
5762
5927
  logger.info(`[channels] ${live.keyId}: subagent-completion reminder queued task=${args.taskId} ok=${args.ok}`)
5763
- // Wake the drain loop. If a turn is already in flight, the wakeup is
5764
- // a no-op because drain() will pick up the reminder on its next
5765
- // iteration (it now gates on promptQueue OR pendingSystemReminders).
5766
- // If the session is idle, fire drain() immediately rather than going
5767
- // through the debounce path — the reminder is not a user inbound,
5768
- // so the "coalesce nearby inbounds" rationale for debouncing does
5769
- // not apply. Mirrors the TUI path's `idle ? 'interrupt' : 'queue'`
5770
- // semantics: the channel router doesn't have a `delivery: interrupt`
5771
- // mechanism (no in-flight abort during a turn), but firing drain()
5772
- // immediately is the equivalent for an idle session.
5773
- if (!live.draining) {
5928
+ // Wake an idle session immediately, but leave an already-scheduled inbound
5929
+ // debounce in charge. Starting a fire-and-forget drain here would splice
5930
+ // both queues before the debounce owner can await that drain, making the
5931
+ // caller observe an in-progress turn and defeating deterministic coalescing.
5932
+ // An in-flight drain picks up the reminder on its next iteration.
5933
+ if (!live.draining && live.debounceTimer === null) {
5774
5934
  void drain(live)
5775
5935
  }
5776
5936
  return { kind: 'delivered', keyId: live.keyId }
@@ -6009,10 +6169,71 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6009
6169
  ).then(() => undefined)
6010
6170
  }
6011
6171
 
6172
+ const reactOnContinuationWillingness = (live: LiveSession, reactionRef: ReactionRef): void => {
6173
+ const addResult = react({
6174
+ adapter: live.key.adapter,
6175
+ workspace: live.key.workspace,
6176
+ chat: live.key.chat,
6177
+ thread: live.key.thread,
6178
+ reactionRef,
6179
+ emoji: CONTINUATION_REACTION_EMOJI,
6180
+ })
6181
+ void addResult
6182
+ .then((result) => {
6183
+ if (!result.ok && result.code !== 'unsupported') {
6184
+ logger.info(
6185
+ `[channels] continuation-react failed adapter=${live.key.adapter} chat=${live.key.chat}: ${result.error}`,
6186
+ )
6187
+ }
6188
+ })
6189
+ .catch((err) => {
6190
+ logger.info(
6191
+ `[channels] continuation-react threw adapter=${live.key.adapter} chat=${live.key.chat}: ${describeError(err)}`,
6192
+ )
6193
+ })
6194
+ live.activeContinuationReactions.push(
6195
+ addResult.then((result) => (result.ok ? (result.reactionRef ?? null) : null)).catch(() => null),
6196
+ )
6197
+ }
6198
+
6199
+ const dropContinuationReactions = (live: LiveSession): Promise<void> => {
6200
+ const addPromises = live.activeContinuationReactions
6201
+ if (addPromises.length === 0) return Promise.resolve()
6202
+ live.activeContinuationReactions = []
6203
+ return Promise.all(
6204
+ addPromises.map((addPromise) =>
6205
+ addPromise
6206
+ .then((reactionRef) => {
6207
+ if (reactionRef === null) return undefined
6208
+ return removeReaction({
6209
+ adapter: live.key.adapter,
6210
+ workspace: live.key.workspace,
6211
+ chat: live.key.chat,
6212
+ thread: live.key.thread,
6213
+ reactionRef,
6214
+ })
6215
+ })
6216
+ .then((result) => {
6217
+ if (result && !result.ok && result.code !== 'unsupported' && result.code !== 'not-found') {
6218
+ logger.info(
6219
+ `[channels] continuation-unreact failed adapter=${live.key.adapter} chat=${live.key.chat}: ${result.error}`,
6220
+ )
6221
+ }
6222
+ })
6223
+ .catch((err) => {
6224
+ logger.info(
6225
+ `[channels] continuation-unreact threw adapter=${live.key.adapter} chat=${live.key.chat}: ${describeError(err)}`,
6226
+ )
6227
+ }),
6228
+ ),
6229
+ ).then(() => undefined)
6230
+ }
6231
+
6012
6232
  return {
6013
6233
  route,
6014
6234
  send,
6015
6235
  getConsecutiveSendCount,
6236
+ hasQualifyingWorkThisLogicalTurn,
6016
6237
  getSendRate,
6017
6238
  registerOutbound,
6018
6239
  unregisterOutbound,
@@ -6228,7 +6449,7 @@ function isWakeRequest(observed: readonly ObservedInbound[], trigger: QueuedInbo
6228
6449
  })
6229
6450
  }
6230
6451
 
6231
- function composeTurnPrompt(
6452
+ export function composeTurnPrompt(
6232
6453
  observed: readonly ObservedInbound[],
6233
6454
  batch: readonly QueuedInbound[],
6234
6455
  state: {
@@ -6293,16 +6514,13 @@ function composeTurnPrompt(
6293
6514
  '---',
6294
6515
  '**[SYSTEM MESSAGE — not from a human]**',
6295
6516
  '',
6296
- `The TypeClaw runtime detected that peer bots have engaged you ${MAX_CONSECUTIVE_PEER_BOT_TURNS_SINCE_HUMAN}+ times in`,
6297
- `a row without any human input (or ${MAX_PEER_BOT_TURNS_IN_WINDOW}+ times in the last ${PEER_BOT_TURNS_WINDOW_MS / 1000}s). This message`,
6298
- 'is an automated signal from the channel router, not a message from anyone',
6299
- 'in the chat. **Do not acknowledge or reply to this notice.**',
6300
- '',
6301
- 'Guidance:',
6302
- '- If the current message clearly needs a reply, send one and ignore this notice.',
6303
- '- If continuing would add noise, reply with `NO_REPLY` to stay silent this turn.',
6517
+ 'Automated signal from the channel router, not a message from anyone in the chat.',
6518
+ '**Do not acknowledge or reply to this notice.**',
6304
6519
  '',
6305
- 'This notice clears automatically once a human posts again.',
6520
+ `Peer bots have engaged you ${MAX_CONSECUTIVE_PEER_BOT_TURNS_SINCE_HUMAN}+ times in a row with no human input (or ${MAX_PEER_BOT_TURNS_IN_WINDOW}+ times in`,
6521
+ `the last ${PEER_BOT_TURNS_WINDOW_MS / 1000}s). If the current message clearly needs a reply, send one and ignore`,
6522
+ 'this notice; if continuing would add noise, reply `NO_REPLY` to stay silent this',
6523
+ 'turn. Clears automatically once a human posts again.',
6306
6524
  '',
6307
6525
  '---',
6308
6526
  '',
@@ -6322,24 +6540,16 @@ function composeTurnPrompt(
6322
6540
  '---',
6323
6541
  '**[SYSTEM MESSAGE — not from a human]**',
6324
6542
  '',
6325
- 'You are in a group chat with multiple people. This is an automated',
6326
- 'signal from the channel router, not a message from anyone in the chat.',
6543
+ 'Automated signal from the channel router, not a message from anyone in the chat.',
6327
6544
  '**Do not acknowledge or reply to this notice.**',
6328
6545
  '',
6329
- 'You are woken on every message from someone you recently talked with, so',
6330
- 'most turns you should stay quiet. In a group the target shifts every',
6331
- 'message: before replying, identify who THIS latest message is aimed at.',
6332
- 'Reply ONLY when:',
6333
- '- the current message is addressed to you (by name, @-mention, or reply), or',
6334
- '- it directly continues your own last exchange and clearly wants an answer',
6335
- ' (e.g. a follow-up question about what you just said).',
6336
- '',
6337
- 'If it is aimed at someone else — another person by name or @-mention, a',
6338
- 'reply to their message, or another bot — it is not your turn, even if you',
6339
- 'were just talking with its author. Otherwise too — chatter, side-',
6340
- 'conversation, banter, or anything not actually waiting on you — reply with',
6341
- '`NO_REPLY` (or call `skip_response`) to stay silent and keep watching.',
6342
- 'When unsure, prefer silence.',
6546
+ 'You are in a group chat and are woken on every message from anyone you recently',
6547
+ 'talked with, so most turns you should stay quiet. The target shifts every message:',
6548
+ 'before replying, identify who THIS latest message is aimed at. Reply ONLY if it is',
6549
+ 'addressed to you (by name, @-mention, or reply), or clearly continues your own last',
6550
+ 'exchange and wants an answer. If it is aimed at someone else — another person or',
6551
+ 'another bot — or is chatter not actually waiting on you, reply `NO_REPLY` (or call',
6552
+ '`skip_response`) to stay silent and keep watching. When unsure, prefer silence.',
6343
6553
  '',
6344
6554
  '---',
6345
6555
  '',
@@ -6351,7 +6561,7 @@ function composeTurnPrompt(
6351
6561
  // real request sits under "Recent context (not addressed to you)". This
6352
6562
  // re-licenses the model to act on that recent conversation. Placed
6353
6563
  // immediately BEFORE the Recent context block, and the nudge text points at
6354
- // that section BY NAME ("the Recent context section below") rather than by
6564
+ // that section BY NAME (the "Recent context" section below) rather than by
6355
6565
  // position, so the reference is unambiguous regardless of render order.
6356
6566
  // Cache-neutral (user-turn suffix), and skipped when the loop guard already
6357
6567
  // fired to avoid stacking two notices in one turn.
@@ -6360,25 +6570,16 @@ function composeTurnPrompt(
6360
6570
  '---',
6361
6571
  '**[SYSTEM MESSAGE — not from a human]**',
6362
6572
  '',
6363
- 'You were just @-mentioned with little or no text — effectively a "wake up',
6364
- 'and look" ping, not a question in itself. This is an automated signal from',
6365
- 'the channel router, not a message from anyone in the chat. **Do not',
6366
- 'acknowledge or reply to this notice.**',
6367
- '',
6368
- 'A bare ping like this almost always means: "respond to what was just',
6369
- 'said." Look at the "Recent context" section below (it shows who sent each',
6370
- 'message):',
6371
- '- If a recent message clearly wants a response and is relevant to you —',
6372
- ' whether the person who pinged you sent it, or someone else did and the',
6373
- ' pinger is looping you in — treat THAT message as the real request and',
6374
- ' answer it directly. Do not ask "what do you need?" when the answer is',
6375
- ' already in that recent context.',
6376
- '- If several recent messages are relevant, address the substantive one(s).',
6377
- '- If nothing in that recent context actually needs you (the ping was a',
6378
- ' mistake, or the conversation moved on), a brief "what\'s up?" is fine.',
6573
+ 'Automated signal from the channel router, not a message from anyone in the chat.',
6574
+ '**Do not acknowledge or reply to this notice.**',
6379
6575
  '',
6380
- 'When in doubt, prefer answering the most recent substantive message over',
6381
- 'asking what they meant.',
6576
+ 'You were @-mentioned with little or no text — a "wake up and look" ping, not a',
6577
+ 'question in itself. It almost always means "respond to what was just said". Look',
6578
+ 'at the "Recent context" section below (it shows who sent each message): if a recent',
6579
+ 'message wants a response and is relevant to you — whether the pinger sent it or is',
6580
+ 'looping you in — treat THAT as the real request and answer it directly rather than',
6581
+ 'asking "what do you need?". If several are relevant, address the substantive one(s).',
6582
+ 'If nothing there actually needs you, a brief "what\'s up?" is fine.',
6382
6583
  '',
6383
6584
  '---',
6384
6585
  '',
@@ -6450,7 +6651,11 @@ function formatAuthorLine(
6450
6651
  ): string {
6451
6652
  const tag = authorIsBot ? ' [bot]' : ''
6452
6653
  const stamp = ts > 0 ? `[${new Date(ts).toISOString()}] ` : ''
6453
- return `${stamp}${formatAuthorAttribution(adapter, authorId, authorName)}${tag}: ${capObservedText(text, maxChars)}`
6654
+ // Defuse the whole composed line, not just the body: a display name is
6655
+ // attacker-chosen too, so a forged marker can arrive through either half.
6656
+ return defuseRuntimeMarkers(
6657
+ `${stamp}${formatAuthorAttribution(adapter, authorId, authorName)}${tag}: ${capObservedText(text, maxChars)}`,
6658
+ )
6454
6659
  }
6455
6660
 
6456
6661
  // Cap by whole code points so truncation never splits a surrogate pair (emoji,
@@ -6579,7 +6784,7 @@ export function renderQuoteAnchor(source: QuoteAnchorSource): string {
6579
6784
  ? `${collapsed.slice(0, QUOTED_REPLY_EXCERPT_MAX_CHARS - 1)}…`
6580
6785
  : collapsed
6581
6786
  const mention = formatAuthorReference(source.adapter, source.authorId, source.authorName)
6582
- return `> ${mention}: ${excerpt}`
6787
+ return defuseRuntimeMarkers(`> ${mention}: ${excerpt}`)
6583
6788
  }
6584
6789
 
6585
6790
  // Separates the anchor from the reply with a blank line (`\n\n`), not a