typeclaw 0.46.2 → 0.47.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 (42) hide show
  1. package/README.md +2 -1
  2. package/package.json +1 -1
  3. package/src/agent/git-nudge.ts +4 -12
  4. package/src/agent/session-origin.ts +8 -6
  5. package/src/agent/tools/channel-reply.ts +13 -13
  6. package/src/agent/tools/channel-send.ts +3 -3
  7. package/src/bundled-plugins/guard/policies/uncommitted-changes.ts +4 -11
  8. package/src/bundled-plugins/memory/dreaming.ts +28 -67
  9. package/src/bundled-plugins/memory/load-shards.ts +31 -3
  10. package/src/bundled-plugins/memory/memory-logger.ts +2 -1
  11. package/src/bundled-plugins/memory/memory-snapshot.ts +8 -0
  12. package/src/bundled-plugins/memory/vector/embedder.ts +28 -9
  13. package/src/bundled-plugins/security/policies/git-exfil.ts +45 -27
  14. package/src/channels/adapters/telegram-bot-classify.ts +29 -0
  15. package/src/channels/continuation-willingness.ts +2 -2
  16. package/src/channels/github-false-receipt.ts +4 -4
  17. package/src/channels/github-rereview-guard.ts +8 -8
  18. package/src/channels/router.ts +276 -58
  19. package/src/channels/types.ts +7 -0
  20. package/src/cli/command-meta.ts +2 -0
  21. package/src/cli/compose-stats.ts +103 -0
  22. package/src/cli/compose.ts +13 -0
  23. package/src/cli/index.ts +1 -0
  24. package/src/cli/stats.ts +134 -0
  25. package/src/compose/index.ts +1 -0
  26. package/src/compose/stats.ts +51 -0
  27. package/src/config/config.ts +14 -0
  28. package/src/config/index.ts +4 -0
  29. package/src/container/controller.ts +6 -0
  30. package/src/container/index.ts +1 -0
  31. package/src/container/log-archive.ts +448 -0
  32. package/src/container/shared.ts +30 -13
  33. package/src/container/start.ts +78 -63
  34. package/src/container/stats.ts +86 -0
  35. package/src/container/stop.ts +63 -36
  36. package/src/git/run.ts +60 -0
  37. package/src/init/restart-deps-preflight.ts +2 -2
  38. package/src/run/index.ts +5 -0
  39. package/src/run/resource-report.ts +226 -0
  40. package/src/sandbox/canonical-secrets.ts +1 -0
  41. package/src/skills/typeclaw-channel-github/SKILL.md +4 -4
  42. package/typeclaw.schema.json +14 -0
@@ -137,6 +137,13 @@ export const CONTEXT_BUFFER_SIZE = 20
137
137
  // subsequent turn until it ages out. Cap each observed message's text; the
138
138
  // addressed current message is never capped (it's the actual request).
139
139
  export const OBSERVED_MESSAGE_MAX_CHARS = 800
140
+ // A bare @mention (no text of its own) is a "wake up and look" ping, not a
141
+ // question — the user is signalling that a recent un-responded message is what
142
+ // they want a reply to. The wake-request nudge only fires when such a ping
143
+ // lands within this window of a recent observed message, so a mention that
144
+ // arrives long after the channel went quiet does not misread stale scrollback
145
+ // as the thing to answer.
146
+ export const WAKE_REQUEST_LOOKBACK_MS = 60_000
140
147
  // Discord's typing indicator expires after ~10s; an 8s heartbeat keeps it
141
148
  // continuously visible while we debounce + generate without spamming the API.
142
149
  // This is the default; an adapter whose platform expires the indicator sooner
@@ -364,7 +371,7 @@ export const EMPTY_TURN_RETRY_NUDGE = [
364
371
  // Reminder-only nudge for the stranded-toolUse-after-send retry. Distinct from
365
372
  // EMPTY_TURN_RETRY_NUDGE: that one diagnoses output-budget exhaustion and tells
366
373
  // the model to "answer directly", which makes a stranded investigation RE-RUN
367
- // its tools and strand again. Here the model already sent a `continue: true`
374
+ // its tools and strand again. Here the model already sent a `more_work_this_turn: true`
368
375
  // status ack and did real tool work; the turn just ended on an unanswered
369
376
  // toolUse before final prose. The prior toolUse/toolResult entries are still in
370
377
  // this session's branch on the re-prompt, so the recovery is to STOP, read what
@@ -417,8 +424,9 @@ export const COLD_START_REPLY_NUDGE = [
417
424
  // Reminder-only nudge for the empty-stop-after-tool-work retry. Distinct from
418
425
  // both EMPTY_TURN_RETRY_NUDGE (which misdiagnoses a clean `stop` as output-budget
419
426
  // exhaustion and, per its own docstring, makes the model RE-RUN its tools and
420
- // strand again) and STRANDED_TOOLUSE_CONTINUATION_NUDGE (which assumes a `continue:
421
- // true` status reply already landed). Here NO send landed, the model gathered real
427
+ // strand again) and STRANDED_TOOLUSE_CONTINUATION_NUDGE (which assumes a
428
+ // `more_work_this_turn: true` status reply already landed). Here NO send landed,
429
+ // the model gathered real
422
430
  // tool results, then the final completion came back as a bare empty `stop` — the
423
431
  // Fireworks/gpt empty-completion degeneration. The recovery is to READ the results
424
432
  // already in this branch, summarize, and reply — NOT to re-investigate. The
@@ -445,7 +453,7 @@ export const EMPTY_STOP_AFTER_TOOL_WORK_NUDGE = [
445
453
  // is a one-shot correction offer, not recovery from no output.
446
454
  export const MAX_WILLINGNESS_NUDGES = 1
447
455
  // Injected when a reply that ended the turn (terminal-reply abort) promised to
448
- // keep working but omitted `continue: true`. Reminder-only, SYSTEM MESSAGE
456
+ // keep working but omitted `more_work_this_turn: true`. Reminder-only, SYSTEM MESSAGE
449
457
  // framing so persona-rich models do not reply to the notice itself.
450
458
  export const WILLINGNESS_NUDGE = [
451
459
  '---',
@@ -453,14 +461,14 @@ export const WILLINGNESS_NUDGE = [
453
461
  '',
454
462
  'Your last reply said you would keep working this turn, but it ended right',
455
463
  'after sending — a successful channel reply ends the turn unless you set',
456
- '`continue: true` on it. This is an automated signal from the channel router,',
457
- 'not a message from anyone in the chat. **Do not acknowledge or reply to this',
458
- 'notice itself.**',
464
+ '`more_work_this_turn: true` on it. This is an automated signal from the channel',
465
+ 'router, not a message from anyone in the chat. **Do not acknowledge or reply to',
466
+ 'this notice itself.**',
459
467
  '',
460
468
  'If you still have work to do (fetch data, run a tool, spawn a subagent, then',
461
469
  'reply with the result), do it now — and on the status reply that precedes more',
462
- 'work this turn, set `continue: true`. If there is nothing left to do, reply',
463
- 'with `NO_REPLY`.',
470
+ 'work this turn, set `more_work_this_turn: true`. If there is nothing left to do,',
471
+ 'reply with `NO_REPLY`.',
464
472
  '',
465
473
  '---',
466
474
  ].join('\n')
@@ -468,7 +476,7 @@ export const WILLINGNESS_NUDGE = [
468
476
  // did fresh work after it, then ended on an EMPTY `stop` leaf — the answer was
469
477
  // computed but never sent (the Kimi/Fireworks empty-completion flake). Distinct
470
478
  // from WILLINGNESS_NUDGE: that path is a `channel_reply` that ended the turn and
471
- // needs `continue: true`; this path is a `channel_send` (which never ends the
479
+ // needs `more_work_this_turn: true`; this path is a `channel_send` (which never ends the
472
480
  // turn) whose follow-up degenerated, so the model just needs to emit the reply it
473
481
  // already worked out. Shares MAX_WILLINGNESS_NUDGES so a turn can't double-nudge.
474
482
  export const SEND_WILLINGNESS_NUDGE = [
@@ -705,6 +713,7 @@ type QueuedInbound = {
705
713
  reactionRef?: ReactionRef
706
714
  engageReaction?: Promise<ReactionRef | null>
707
715
  isBotMention: boolean
716
+ isBotMentionOnly?: boolean
708
717
  replyToBotMessageId: string | null
709
718
  isDm: boolean
710
719
  typingThread?: string
@@ -937,7 +946,7 @@ type LiveSession = {
937
946
  // channel send landed this turn. `validateChannelTurn` compares it to the
938
947
  // turn-end leaf: a DIFFERENT assistant `stop` leaf means the model replied,
939
948
  // kept working, then ended with FRESH final prose it forgot to deliver
940
- // (the `continue: true` progress-reply bug) — recover it. A leaf that still
949
+ // (the `more_work_this_turn: true` progress-reply bug) — recover it. A leaf that still
941
950
  // matches is narration the model emitted BEFORE/with the reply that already
942
951
  // landed, so it stays suppressed. Reset to null on every new prompt batch.
943
952
  lastSendLeafId: string | null
@@ -1009,14 +1018,14 @@ type LiveSession = {
1009
1018
  // nudge itself queues — same anti-reloop discipline as the empty-turn budget.
1010
1019
  willingnessNudges: number
1011
1020
  // Stashed by `installChannelReplyTerminalHook` just before it aborts the turn
1012
- // after a successful `channel_reply` that omitted `continue: true`. Read once
1021
+ // after a successful `channel_reply` that omitted `more_work_this_turn: true`. Read once
1013
1022
  // by `validateChannelTurn` to decide the continuation nudge. `turnSeq`-stamped
1014
1023
  // (like `skippedTurn`/`skipLockedSendTurn`) so a stale record from an earlier
1015
1024
  // turn can never trigger a nudge on a later one. `null` when no such reply
1016
1025
  // ended this turn.
1017
1026
  lastTerminalReplyAbort: { turnSeq: number; text: string } | null
1018
1027
  // Stamped by `installChannelReplyTerminalHook` when a successful `channel_reply`
1019
- // set `continue: true` — the machine-readable "I'll keep working this turn"
1028
+ // set `more_work_this_turn: true` — the machine-readable "I'll keep working this turn"
1020
1029
  // promise. `validateChannelTurn` reads it to recover a turn that made that promise,
1021
1030
  // did more work, then ended on a fresh empty `stop` (dropped its conclusion) —
1022
1031
  // independent of what natural-language phrase the ack used, so a persona speaking
@@ -1077,6 +1086,26 @@ type LiveSession = {
1077
1086
  // question escalation. Compared by `turnSeq` so a stale value can't leak across
1078
1087
  // turns.
1079
1088
  emptyTurnFallbackTurn: number | null
1089
+ // Set when a WILLINGNESS-ACK exhaustion path (empty_stop_after_continue_reply /
1090
+ // empty_stop_after_send_ack) would post EMPTY_TURN_FALLBACK_TEXT, but the model
1091
+ // just made a machine-readable promise to keep working (`more_work_this_turn: true` /
1092
+ // willingness phrase) and did post-ack tool work. Rather than posting the scary
1093
+ // "I got stuck" notice synchronously at validateChannelTurn — BEFORE the drain
1094
+ // loop runs maybeContinueTodosChannel, which can re-prompt the same logical turn
1095
+ // and land the real answer seconds later (the observed production false alarm) —
1096
+ // the cause is STAGED here and resolved after that continuation gets its chance:
1097
+ // discarded if a genuine reply lands or a continuation is queued, posted exactly
1098
+ // once if the turn genuinely stranded. Only the two willingness branches stage;
1099
+ // every other fallback path posts immediately as before (they carry no
1100
+ // continue-promise). Persists across reminder-only iterations (reset only on a
1101
+ // fresh user batch, beside the willingness/retry budgets) so a stage in one
1102
+ // iteration survives to the resolution after the next. `sendCountAtStage` is
1103
+ // `successfulChannelSends` at stage time — the resolver treats ONLY a send PAST
1104
+ // this baseline as a genuine recovery reply, because the willingness-ack that
1105
+ // triggered staging already bumped the turn-start count (the empty stop follows
1106
+ // a progress ack by definition), so a turn-start baseline would always read as
1107
+ // "already replied" and wrongly discard the fallback.
1108
+ stagedFallbackCause: { cause: string; sendCountAtStage: number } | null
1080
1109
  // Stamped with `turnSeq` when a formal GitHub review (APPROVE / REQUEST_CHANGES /
1081
1110
  // COMMENT) lands during this LOGICAL turn, via noteGithubReviewOutput off the
1082
1111
  // review-output observer. On a github PR channel the agent's real deliverable is
@@ -1456,6 +1485,17 @@ export type ChannelRouter = {
1456
1485
  lastTurnAuthorIds: readonly string[]
1457
1486
  }
1458
1487
  | undefined
1488
+ // Pushes a reminder onto the live session's `pendingSystemReminders`, the same
1489
+ // seam `runIdleContinuation`'s `deliver` callback uses when the todo/idle
1490
+ // continuation fires. Lets a test reproduce the production self-recovery race
1491
+ // (a continuation re-prompt queued after a willingness-ack strand) at the
1492
+ // channels layer, without coupling to todo-file persistence formats.
1493
+ injectContinuationReminder: (key: ChannelKey, text: string) => void
1494
+ // Enqueues a real user batch onto the live session's promptQueue via the same
1495
+ // `enqueue` path route() uses, letting a test reproduce a fresh inbound that
1496
+ // supersedes a still-pending staged fallback mid-drain (the A → staged B →
1497
+ // queued C question-signal supersession case) without the debounce timing dance.
1498
+ enqueueUserInbound: (key: ChannelKey, event: InboundMessage) => void
1459
1499
  // Returns a shallow copy of `live.originRef.current` for the live
1460
1500
  // session matching `key`, or undefined when no live session exists.
1461
1501
  // Exists so tests can assert on the per-turn origin that tool.before
@@ -1497,6 +1537,14 @@ export type CreateChannelRouterOptions = {
1497
1537
  // decision. Defaults to a stat()-based reader returning 0 for a missing or
1498
1538
  // unreadable file (grace then fails closed to roll-over-at-soft-TTL).
1499
1539
  measureTranscriptBytes?: (path: string) => number
1540
+ // Test seam: the idle/todo continuation driver, invoked from
1541
+ // maybeContinueTodosChannel AFTER validateChannelTurn. Defaults to the real
1542
+ // runIdleContinuation. Injecting it lets a test deliver the continuation at the
1543
+ // exact production phase (post-validation) so the drain-loop ordering —
1544
+ // resolveStagedFallback runs AFTER this delivery — is actually asserted, rather
1545
+ // than pre-seeding pendingSystemReminders from onPrompt (which would pass even if
1546
+ // the resolver moved ahead of the continuation).
1547
+ runIdleContinuation?: typeof runIdleContinuation
1500
1548
  // Test seam: override the ensureLive watchdog ceiling so the timeout path
1501
1549
  // is exercisable in <100ms instead of the 30s production default.
1502
1550
  ensureLiveTimeoutMs?: number
@@ -2219,6 +2267,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2219
2267
  skipLockedSendTurn: null,
2220
2268
  disengagedTurn: null,
2221
2269
  emptyTurnFallbackTurn: null,
2270
+ stagedFallbackCause: null,
2222
2271
  githubReviewOutputTurn: null,
2223
2272
  pendingQuoteCandidate: null,
2224
2273
  recentEngagedPeerBotTurns: [],
@@ -2587,20 +2636,21 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2587
2636
  // continue. A prior non-typeclaw `afterToolCall` (none today) would be
2588
2637
  // composed, not clobbered.
2589
2638
  //
2590
- // `channel_reply({ continue: true })` is the explicit opt-out: a mid-turn
2591
- // status reply ("working on it…") that the model follows with more work this
2592
- // turn. The tool surfaces that intent as `details.continue === true`, and we
2593
- // keep the follow-up so the turn proceeds. The kimi 32k loop only recurs when
2594
- // the model genuinely has nothing left to say after a reply, which `continue`
2595
- // asserts is not the case; Layer 2's maxTokens cap still bounds any misuse.
2639
+ // `channel_reply({ more_work_this_turn: true })` is the explicit opt-out: a
2640
+ // mid-turn status reply ("working on it…") that the model follows with more
2641
+ // work this turn. The tool surfaces that intent as
2642
+ // `details.more_work_this_turn === true`, and we keep the follow-up so the turn
2643
+ // proceeds. The kimi 32k loop only recurs when the model genuinely has nothing
2644
+ // left to say after a reply, which `more_work_this_turn` asserts is not the
2645
+ // case; Layer 2's maxTokens cap still bounds any misuse.
2596
2646
  const installChannelReplyTerminalHook = (live: LiveSession): void => {
2597
2647
  const { agent } = live.session
2598
2648
  const prior = agent.afterToolCall
2599
2649
  agent.afterToolCall = async (context, signal) => {
2600
2650
  const result = prior ? await prior(context, signal) : undefined
2601
- const details = context.result.details as { ok?: unknown; continue?: unknown } | undefined
2651
+ const details = context.result.details as { ok?: unknown; more_work_this_turn?: unknown } | undefined
2602
2652
  const succeeded = context.toolCall.name === 'channel_reply' && !context.isError && details?.ok === true
2603
- const keepTurnAlive = details?.continue === true
2653
+ const keepTurnAlive = details?.more_work_this_turn === true
2604
2654
  if (succeeded && keepTurnAlive) {
2605
2655
  live.continueReplyTurn = { turnSeq: live.turnSeq, sendCount: live.successfulChannelSends }
2606
2656
  }
@@ -2725,7 +2775,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2725
2775
  if (live.destroyed) return
2726
2776
  if (live.promptQueue.length > 0 || live.pendingSystemReminders.length > 0) return
2727
2777
  try {
2728
- await runIdleContinuation({
2778
+ await (options.runIdleContinuation ?? runIdleContinuation)({
2729
2779
  agentDir: options.agentDir,
2730
2780
  origin: buildLiveOrigin(live),
2731
2781
  deliver: (text) => {
@@ -2737,6 +2787,69 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2737
2787
  }
2738
2788
  }
2739
2789
 
2790
+ const postEmptyTurnFallback = async (live: LiveSession, cause: string): Promise<void> => {
2791
+ logger.warn(`[channels] ${live.keyId} empty_turn_fallback cause=${cause}`)
2792
+ live.emptyTurnFallbackTurn = live.turnSeq
2793
+ const result = await send(
2794
+ {
2795
+ adapter: live.key.adapter,
2796
+ workspace: live.key.workspace,
2797
+ chat: live.key.chat,
2798
+ thread: live.key.thread,
2799
+ text: EMPTY_TURN_FALLBACK_TEXT,
2800
+ },
2801
+ { source: 'system' },
2802
+ )
2803
+ if (!result.ok) {
2804
+ logger.warn(`[channels] ${live.keyId}: empty-turn fallback send failed: ${result.error}`)
2805
+ }
2806
+ }
2807
+
2808
+ // Resolve a fallback STAGED by a willingness-ack exhaustion path, run AFTER
2809
+ // maybeContinueTodosChannel so the idle/todo continuation has already had its
2810
+ // chance to queue a re-prompt (the mechanism that self-recovers the promised
2811
+ // work). Three outcomes, in precedence order:
2812
+ // 1. A genuine reply landed this logical turn (successfulChannelSends moved
2813
+ // past the turn-start baseline; the staged path never posts, so any bump
2814
+ // is real prose) → the model self-recovered, discard the stage silently.
2815
+ // 2. A re-prompt is queued (pendingSystemReminders from the continuation, or a
2816
+ // fresh user inbound in promptQueue) → recovery is still in flight or a new
2817
+ // turn supersedes; carry the stage forward to the next resolution (or let
2818
+ // the fresh turn's reset clear it) — do NOT post yet.
2819
+ // 3. Neither → the turn genuinely stranded with nothing following it; post the
2820
+ // visible fallback exactly once. This preserves the never-strand-on-silence
2821
+ // invariant for the true-stuck case while killing the production false alarm
2822
+ // where the continuation landed the real answer seconds after the stage.
2823
+ const resolveStagedFallback = async (live: LiveSession): Promise<void> => {
2824
+ const staged = live.stagedFallbackCause
2825
+ if (staged === null) return
2826
+ if (live.successfulChannelSends > staged.sendCountAtStage) {
2827
+ logger.info(`[channels] ${live.keyId} empty_turn_fallback_discarded cause=${staged.cause} reason=reply_landed`)
2828
+ live.stagedFallbackCause = null
2829
+ // Recovery genuinely answered the user, so the logical turn ends as a usable
2830
+ // reply — commit the question signal the try-block deferred while staged.
2831
+ if (live.pendingUserTurnSignal !== null) {
2832
+ live.lastQuestionSignal = live.pendingUserTurnSignal.signal
2833
+ live.pendingUserTurnSignal = null
2834
+ }
2835
+ return
2836
+ }
2837
+ if (live.promptQueue.length > 0 || live.pendingSystemReminders.length > 0) {
2838
+ // A re-prompt is still queued: keep both the stage and the pending signal for
2839
+ // the next resolution — the turn hasn't finished.
2840
+ logger.info(
2841
+ `[channels] ${live.keyId} empty_turn_fallback_deferred cause=${staged.cause} reason=continuation_queued`,
2842
+ )
2843
+ return
2844
+ }
2845
+ live.stagedFallbackCause = null
2846
+ // The fallback IS the turn's terminal (non-usable) output — clear both signals
2847
+ // so an older question can't leak the xhigh escalation across this failed turn.
2848
+ live.pendingUserTurnSignal = null
2849
+ live.lastQuestionSignal = null
2850
+ await postEmptyTurnFallback(live, staged.cause)
2851
+ }
2852
+
2740
2853
  const fireSessionTurnStart = async (live: LiveSession, userPrompt: string): Promise<{ results: string }> => {
2741
2854
  const retrievalContext = { results: '' }
2742
2855
  if (!live.hooks) return retrievalContext
@@ -2957,6 +3070,16 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2957
3070
  live.toolLeakRetries = 0
2958
3071
  live.emptyStopAfterToolWorkArmed = false
2959
3072
  live.willingnessNudges = 0
3073
+ // A fresh batch supersedes a still-pending staged fallback. That staged
3074
+ // turn produced no usable reply, so it must not leave the PRIOR turn's
3075
+ // committed lastQuestionSignal behind — otherwise the new question would
3076
+ // inherit an xhigh escalation across the superseded (failed) turn. Clear
3077
+ // the stale signal only when a stage was actually pending; a normal prior
3078
+ // turn's legitimately-committed signal is left intact.
3079
+ if (live.stagedFallbackCause !== null) {
3080
+ live.lastQuestionSignal = null
3081
+ live.stagedFallbackCause = null
3082
+ }
2960
3083
  live.abortReasonThisTurn = null
2961
3084
  live.nextPromptMaxTokens = undefined
2962
3085
  // Cleared with the retry budgets (NOT beside resetReviewTurn below) so a
@@ -3082,7 +3205,14 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3082
3205
  const fallbackPostedThisTurn = live.emptyTurnFallbackTurn === live.turnSeq
3083
3206
  const sentReplyThisTurn = live.successfulChannelSends > successfulSendsBeforePrompt
3084
3207
  const usableReplyThisTurn = sentReplyThisTurn && !fallbackPostedThisTurn && !providerErrorThisTurn
3085
- if (live.pendingUserTurnSignal !== null && !retryQueuedThisTurn) {
3208
+ // A staged (not-yet-posted) willingness fallback keeps the logical turn
3209
+ // OPEN, exactly like a queued retry: the progress ack that triggered
3210
+ // staging would otherwise read as `usableReplyThisTurn` and commit the
3211
+ // question signal, so a fallback turn would leak the `xhigh` escalation it
3212
+ // is meant to suppress. Leave the pending signal untouched here;
3213
+ // resolveStagedFallback finalizes it (commit on genuine recovery, clear on
3214
+ // fallback-post) once the continuation has run.
3215
+ if (live.pendingUserTurnSignal !== null && !retryQueuedThisTurn && live.stagedFallbackCause === null) {
3086
3216
  live.lastQuestionSignal = usableReplyThisTurn ? live.pendingUserTurnSignal.signal : null
3087
3217
  live.pendingUserTurnSignal = null
3088
3218
  }
@@ -3157,6 +3287,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3157
3287
  await fireSessionIdle(live)
3158
3288
  await recordTodoTurnStart(live, isRealUserTurn)
3159
3289
  await maybeContinueTodosChannel(live)
3290
+ await resolveStagedFallback(live)
3160
3291
  live.lastTurnAuthorIds = new Set(live.currentTurnAuthorIds)
3161
3292
  if (live.currentTurnAuthorId !== null) {
3162
3293
  live.lastTurnAuthorId = live.currentTurnAuthorId
@@ -3637,6 +3768,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3637
3768
  ...(event.reactionRef !== undefined ? { reactionRef: event.reactionRef } : {}),
3638
3769
  ...(engageReaction !== null ? { engageReaction } : {}),
3639
3770
  isBotMention: event.isBotMention,
3771
+ ...(event.isBotMentionOnly !== undefined ? { isBotMentionOnly: event.isBotMentionOnly } : {}),
3640
3772
  replyToBotMessageId: event.replyToBotMessageId,
3641
3773
  isDm: event.isDm,
3642
3774
  ...(event.typingThread !== undefined ? { typingThread: event.typingThread } : {}),
@@ -4477,7 +4609,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4477
4609
  }
4478
4610
 
4479
4611
  // The turn ended via the terminal-reply abort. If that reply promised to keep
4480
- // working but omitted `continue: true`, queue ONE reminder-only re-prompt so
4612
+ // working but omitted `more_work_this_turn: true`, queue ONE reminder-only re-prompt so
4481
4613
  // the model gets a second chance to actually do it. The abort already fired
4482
4614
  // (safe default preserved); this only adds an optional nudge. Bounded by
4483
4615
  // MAX_WILLINGNESS_NUDGES and gated on `promptQueue` being empty so a real
@@ -4522,22 +4654,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4522
4654
  live.skippedTurn = null
4523
4655
  logger.info(`[channels] ${live.keyId} skip_contested_by_send recovering reply`)
4524
4656
  }
4525
- const postEmptyTurnFallback = async (cause: string): Promise<void> => {
4526
- logger.warn(`[channels] ${live.keyId} empty_turn_fallback cause=${cause}`)
4527
- live.emptyTurnFallbackTurn = live.turnSeq
4528
- const result = await send(
4529
- {
4530
- adapter: live.key.adapter,
4531
- workspace: live.key.workspace,
4532
- chat: live.key.chat,
4533
- thread: live.key.thread,
4534
- text: EMPTY_TURN_FALLBACK_TEXT,
4535
- },
4536
- { source: 'system' },
4537
- )
4538
- if (!result.ok) {
4539
- logger.warn(`[channels] ${live.keyId}: empty-turn fallback send failed: ${result.error}`)
4540
- }
4657
+ const stageEmptyTurnFallback = (cause: string): void => {
4658
+ logger.warn(`[channels] ${live.keyId} empty_turn_fallback_staged cause=${cause}`)
4659
+ live.stagedFallbackCause = { cause, sendCountAtStage: live.successfulChannelSends }
4541
4660
  }
4542
4661
 
4543
4662
  // A formal GitHub review already landed this logical turn (APPROVE /
@@ -4579,10 +4698,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4579
4698
  )
4580
4699
  }
4581
4700
 
4582
- // A send landed this turn, but the model may have posted a `continue: true`
4701
+ // A send landed this turn, but the model may have posted a `more_work_this_turn: true`
4583
4702
  // progress reply, kept working, then ENDED with its final answer as plain
4584
4703
  // prose — never calling a channel tool again. The terminal-reply abort fires
4585
- // only for a `channel_reply` WITHOUT `continue: true`, so that `stopReason:
4704
+ // only for a `channel_reply` WITHOUT `more_work_this_turn: true`, so that `stopReason:
4586
4705
  // 'stop'` text leaf is left undelivered and unguarded (the false-receipt
4587
4706
  // guard is github-only). The discriminator is leaf IDENTITY: only when the
4588
4707
  // turn-end `stop` leaf is a DIFFERENT entry than the one in place at the last
@@ -4592,17 +4711,17 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4592
4711
  if (live.successfulChannelSends > successfulSendsBeforePrompt) {
4593
4712
  maybeNudgeContinuationWillingness(live)
4594
4713
 
4595
- // A `channel_reply({ continue: true })` progress ack landed this turn (the
4714
+ // A `channel_reply({ more_work_this_turn: true })` progress ack landed this turn (the
4596
4715
  // machine-readable "I'll keep working" promise — `continueReplyTurn` is stamped
4597
4716
  // by installChannelReplyTerminalHook), the model did more work, then ended on a
4598
4717
  // FRESH empty `stop` — dropping its conclusion. This is the SAME degeneration as
4599
- // the phrase-gated `channel_send` branch below, but keyed on the `continue: true`
4718
+ // the phrase-gated `channel_send` branch below, but keyed on the `more_work_this_turn: true`
4600
4719
  // FLAG instead of a natural-language willingness phrase. The flag is the robust
4601
4720
  // signal: it fires regardless of the ack's language or register, closing the gap
4602
4721
  // where a persona speaking a phrasing outside the willingness table (e.g. casual
4603
4722
  // Korean "확인해볼게") stranded the user in silence. The `attemptMadeToolCall`
4604
4723
  // half ties the first trigger to real post-ack work; `willingnessNudges > 0`
4605
- // lets a retry that re-emitted `continue: true` and re-stranded spend the shared
4724
+ // lets a retry that re-emitted `more_work_this_turn: true` and re-stranded spend the shared
4606
4725
  // budget toward the visible fallback instead of bailing silent. Same
4607
4726
  // MAX_WILLINGNESS_NUDGES bound, same empty-`promptQueue` gate (a coalesced live
4608
4727
  // inbound supersedes this turn's silence), and same nudge/fallback path as the
@@ -4628,7 +4747,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4628
4747
  )
4629
4748
  live.pendingSystemReminders.push(SEND_WILLINGNESS_NUDGE)
4630
4749
  } else {
4631
- await postEmptyTurnFallback('empty_stop_after_continue_reply_nudges_exhausted')
4750
+ stageEmptyTurnFallback('empty_stop_after_continue_reply_nudges_exhausted')
4632
4751
  }
4633
4752
  return
4634
4753
  }
@@ -4664,14 +4783,14 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4664
4783
  )
4665
4784
  live.pendingSystemReminders.push(SEND_WILLINGNESS_NUDGE)
4666
4785
  } else {
4667
- await postEmptyTurnFallback('empty_stop_after_send_ack_nudges_exhausted')
4786
+ stageEmptyTurnFallback('empty_stop_after_send_ack_nudges_exhausted')
4668
4787
  }
4669
4788
  return
4670
4789
  }
4671
4790
 
4672
4791
  const trailing = recoverableAssistantText(live.session)
4673
4792
  if (trailing === null || trailing.source !== 'leaf') {
4674
- // A `continue: true` status reply landed, then the turn stranded on an
4793
+ // A `more_work_this_turn: true` status reply landed, then the turn stranded on an
4675
4794
  // unanswered `toolUse` (the post-tool follow-up never produced an
4676
4795
  // assistant message — aborted loop / cancelled stream). The promised
4677
4796
  // work never finished, so the user is left with a bare "checking now…"
@@ -4701,7 +4820,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4701
4820
  )
4702
4821
  live.pendingSystemReminders.push(STRANDED_TOOLUSE_CONTINUATION_NUDGE)
4703
4822
  } else {
4704
- await postEmptyTurnFallback('stranded_toolUse_retries_exhausted')
4823
+ await postEmptyTurnFallback(live, 'stranded_toolUse_retries_exhausted')
4705
4824
  }
4706
4825
  }
4707
4826
  return
@@ -4817,7 +4936,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4817
4936
  live.pendingSystemReminders.push(EMPTY_TURN_RETRY_NUDGE)
4818
4937
  return
4819
4938
  }
4820
- await postEmptyTurnFallback(attemptedSendThisTurn ? 'send_thrash' : 'retries_exhausted')
4939
+ await postEmptyTurnFallback(live, attemptedSendThisTurn ? 'send_thrash' : 'retries_exhausted')
4821
4940
  return
4822
4941
  }
4823
4942
 
@@ -4852,7 +4971,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4852
4971
  live.pendingSystemReminders.push(COLD_START_REPLY_NUDGE)
4853
4972
  return
4854
4973
  }
4855
- await postEmptyTurnFallback('cold_start_solo_bare_empty_retries_exhausted')
4974
+ await postEmptyTurnFallback(live, 'cold_start_solo_bare_empty_retries_exhausted')
4856
4975
  return
4857
4976
  }
4858
4977
  // Deliberately AFTER the cold-start guard (that path has its own nudge). A
@@ -4888,7 +5007,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4888
5007
  live.pendingSystemReminders.push(EMPTY_STOP_AFTER_TOOL_WORK_NUDGE)
4889
5008
  return
4890
5009
  }
4891
- await postEmptyTurnFallback('empty_stop_after_tool_work_retries_exhausted')
5010
+ await postEmptyTurnFallback(live, 'empty_stop_after_tool_work_retries_exhausted')
4892
5011
  return
4893
5012
  }
4894
5013
  const leakedReasoning = !isNoReplySignal(assistantText)
@@ -5052,7 +5171,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5052
5171
  chat: live.key.chat,
5053
5172
  thread: live.key.thread,
5054
5173
  text,
5055
- isContinue: false,
5174
+ moreWorkThisTurn: false,
5056
5175
  resolveReviewThread: false,
5057
5176
  })
5058
5177
  if (falseReceipt.kind === 'block') return falseReceipt.reason
@@ -5064,7 +5183,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5064
5183
  thread: live.key.thread,
5065
5184
  text,
5066
5185
  wantsResolve: false,
5067
- isContinue: false,
5186
+ moreWorkThisTurn: false,
5068
5187
  getReviewState: (req) => getReviewState(req),
5069
5188
  })
5070
5189
  if (rereview.block) return rereview.reason
@@ -5945,6 +6064,16 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5945
6064
  lastTurnAuthorIds: Array.from(live.lastTurnAuthorIds),
5946
6065
  }
5947
6066
  },
6067
+ injectContinuationReminder: (key: ChannelKey, text: string): void => {
6068
+ const live = liveSessions.get(channelKeyId(key))
6069
+ if (!live) return
6070
+ live.pendingSystemReminders.push(text)
6071
+ },
6072
+ enqueueUserInbound: (key: ChannelKey, event: InboundMessage): void => {
6073
+ const live = liveSessions.get(channelKeyId(key))
6074
+ if (!live) return
6075
+ enqueue(live, event, null)
6076
+ },
5948
6077
  },
5949
6078
  }
5950
6079
  }
@@ -5967,6 +6096,56 @@ function findAttachmentById(attachments: readonly InboundAttachment[], id: numbe
5967
6096
  return null
5968
6097
  }
5969
6098
 
6099
+ // Strips the platform's user/group-mention markup so a bare ping can be told
6100
+ // from a mention that also carries real text. Slack and Discord both encode
6101
+ // mentions as `<@id>` / `<@id|name>` (users) and `<!subteam^ID>` / `<!channel>`
6102
+ // (groups); GitHub and the plain-name adapters have no wrapping syntax to strip,
6103
+ // so their text is returned as-is and a mention there is never classified thin.
6104
+ // Content-blind and script-agnostic: it removes only fixed markup, never words,
6105
+ // so it works identically for Korean, CJK, Arabic, or any other input.
6106
+ function stripMentionMarkup(text: string, adapter: AdapterId): string {
6107
+ switch (adapter) {
6108
+ case 'slack':
6109
+ case 'slack-bot':
6110
+ case 'discord':
6111
+ case 'discord-bot':
6112
+ return text.replace(/<[@!][^>]*>/g, ' ')
6113
+ default:
6114
+ return text
6115
+ }
6116
+ }
6117
+
6118
+ // A "wake request" is a mention whose only payload IS the mention: once the
6119
+ // markup is stripped the remainder is empty. That shape means "wake up and look
6120
+ // at what was just said", not a self-contained question, so the caller nudges
6121
+ // the model toward the recent conversation instead of asking "what do you need?".
6122
+ function isThinMention(trigger: QueuedInbound, adapter: AdapterId): boolean {
6123
+ if (!trigger.isBotMention) return false
6124
+ if (trigger.attachments !== undefined && trigger.attachments.length > 0) return false
6125
+ // Adapters whose visible text cannot reveal a bare ping (Telegram text_mention
6126
+ // renders as a display name) carry the authoritative signal; trust it. Others
6127
+ // fall back to stripping the platform's mention markup from the text.
6128
+ if (trigger.isBotMentionOnly !== undefined) return trigger.isBotMentionOnly
6129
+ return stripMentionMarkup(trigger.text, adapter).trim() === ''
6130
+ }
6131
+
6132
+ // True when the engaged trigger is a bare ping AND a real (non-prefetch) message
6133
+ // was observed within the lookback window. Author-agnostic on purpose: in a group
6134
+ // one person can drop a message and a DIFFERENT teammate can ping the bot to loop
6135
+ // it in, so the recent message need not come from the pinger. The age must be
6136
+ // non-negative: a message that arrives DURING the mention's debounce window is
6137
+ // appended to contextBuffer after the ping, so `receivedAt - o.receivedAt` goes
6138
+ // negative — that message came AFTER the ping and is not what the user was
6139
+ // pointing back at, so it must not satisfy the "recent PRECEDING message" test.
6140
+ function isWakeRequest(observed: readonly ObservedInbound[], trigger: QueuedInbound, adapter: AdapterId): boolean {
6141
+ if (!isThinMention(trigger, adapter)) return false
6142
+ return observed.some((o) => {
6143
+ if (o.source !== 'observed') return false
6144
+ const age = trigger.receivedAt - o.receivedAt
6145
+ return age >= 0 && age <= WAKE_REQUEST_LOOKBACK_MS
6146
+ })
6147
+ }
6148
+
5970
6149
  function composeTurnPrompt(
5971
6150
  observed: readonly ObservedInbound[],
5972
6151
  batch: readonly QueuedInbound[],
@@ -6084,6 +6263,45 @@ function composeTurnPrompt(
6084
6263
  '',
6085
6264
  )
6086
6265
  }
6266
+ // Wake-request nudge: same SYSTEM MESSAGE convention as the loop guard and
6267
+ // group nudge. The trigger is a bare ping (mention with no text of its own),
6268
+ // which the model would otherwise answer with "what do you need?" while the
6269
+ // real request sits under "Recent context (not addressed to you)". This
6270
+ // re-licenses the model to act on that recent conversation. Placed
6271
+ // immediately BEFORE the Recent context block, and the nudge text points at
6272
+ // that section BY NAME ("the Recent context section below") rather than by
6273
+ // position, so the reference is unambiguous regardless of render order.
6274
+ // Cache-neutral (user-turn suffix), and skipped when the loop guard already
6275
+ // fired to avoid stacking two notices in one turn.
6276
+ if (batch.length === 1 && !state.loopGuardActive && isWakeRequest(observed, batch[0]!, adapter)) {
6277
+ parts.push(
6278
+ '---',
6279
+ '**[SYSTEM MESSAGE — not from a human]**',
6280
+ '',
6281
+ 'You were just @-mentioned with little or no text — effectively a "wake up',
6282
+ 'and look" ping, not a question in itself. This is an automated signal from',
6283
+ 'the channel router, not a message from anyone in the chat. **Do not',
6284
+ 'acknowledge or reply to this notice.**',
6285
+ '',
6286
+ 'A bare ping like this almost always means: "respond to what was just',
6287
+ 'said." Look at the "Recent context" section below (it shows who sent each',
6288
+ 'message):',
6289
+ '- If a recent message clearly wants a response and is relevant to you —',
6290
+ ' whether the person who pinged you sent it, or someone else did and the',
6291
+ ' pinger is looping you in — treat THAT message as the real request and',
6292
+ ' answer it directly. Do not ask "what do you need?" when the answer is',
6293
+ ' already in that recent context.',
6294
+ '- If several recent messages are relevant, address the substantive one(s).',
6295
+ '- If nothing in that recent context actually needs you (the ping was a',
6296
+ ' mistake, or the conversation moved on), a brief "what\'s up?" is fine.',
6297
+ '',
6298
+ 'When in doubt, prefer answering the most recent substantive message over',
6299
+ 'asking what they meant.',
6300
+ '',
6301
+ '---',
6302
+ '',
6303
+ )
6304
+ }
6087
6305
  if (observed.length > 0) {
6088
6306
  parts.push('## Recent context (not addressed to you, for awareness only)')
6089
6307
  for (const o of observed) {
@@ -6760,7 +6978,7 @@ function assistantLeafStopReason(session: AgentSession): 'length' | 'error' | 'a
6760
6978
  // alongside its tool call and DID land a real send this turn (that trailing
6761
6979
  // `toolUse` is delivered narration, not a stranded promise — leave it alone).
6762
6980
  // Keys on the model having INTENDED to keep working with nothing yet said; used
6763
- // to re-prompt a turn that strands mid-work after a `continue: true` status
6981
+ // to re-prompt a turn that strands mid-work after a `more_work_this_turn: true` status
6764
6982
  // reply instead of ending in silence.
6765
6983
  function leafIsStrandedToolUse(session: AgentSession): boolean {
6766
6984
  const leaf = session.sessionManager.getLeafEntry()
@@ -6790,7 +7008,7 @@ function leafIsStrandedToolUse(session: AgentSession): boolean {
6790
7008
  // (the model did more work, then dropped its conclusion) from a legitimate
6791
7009
  // ack-then-stop where the model meant to wait for the user (leaf unchanged since
6792
7010
  // the send). The two willingness paths below layer their own promise-signal on top
6793
- // of this shape: `channel_reply({ continue: true })` via `continueReplyTurn`, and
7011
+ // of this shape: `channel_reply({ more_work_this_turn: true })` via `continueReplyTurn`, and
6794
7012
  // `channel_send` acks via the willingness phrase table.
6795
7013
  function isFreshEmptyStopAfterSend(live: LiveSession): boolean {
6796
7014
  const leaf = live.session.sessionManager.getLeafEntry()
@@ -6800,10 +7018,10 @@ function isFreshEmptyStopAfterSend(live: LiveSession): boolean {
6800
7018
  return leaf.id !== live.lastSendLeafId
6801
7019
  }
6802
7020
 
6803
- // The `channel_send` analogue of the `continue: true` recovery: the most recent
7021
+ // The `channel_send` analogue of the `more_work_this_turn: true` recovery: the most recent
6804
7022
  // send to this target was a continuation-willingness ack (by phrase), then the
6805
7023
  // model produced a fresh empty stop. `channel_send` keeps the turn alive without a
6806
- // `continue: true` flag and stamps no semantic marker, so the phrase table is the
7024
+ // `more_work_this_turn: true` flag and stamps no semantic marker, so the phrase table is the
6807
7025
  // only "I promised to keep working" signal available for that shape.
6808
7026
  function isEmptyStopAfterWillingnessAck(live: LiveSession): boolean {
6809
7027
  if (!isFreshEmptyStopAfterSend(live)) return false
@@ -80,6 +80,13 @@ export type InboundMessage = {
80
80
  // bounded loop guard so two or more bots cannot ping-pong forever.
81
81
  authorIsBot: boolean
82
82
  isBotMention: boolean
83
+ // Adapter-authoritative "this inbound is a bare ping — the mention IS the whole
84
+ // message" signal. Set only by adapters whose visible `text` cannot reveal it:
85
+ // Telegram renders a `text_mention` as the target's display NAME (not `<@id>`),
86
+ // so the router's markup-stripping cannot tell a bare ping from real text. When
87
+ // present the wake-request detector trusts it; when absent (Slack/Discord) the
88
+ // router falls back to stripping the platform's mention markup from `text`.
89
+ isBotMentionOnly?: boolean
83
90
  // When true, engagement treats this inbound as explicit-only: it skips
84
91
  // content-blind sticky credit AND plain-text alias matching, leaving only
85
92
  // structural DM / @mention / reply triggers. Used for GitHub PR review-thread