typeclaw 0.47.0 → 0.47.2

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.
@@ -371,7 +371,7 @@ export const EMPTY_TURN_RETRY_NUDGE = [
371
371
  // Reminder-only nudge for the stranded-toolUse-after-send retry. Distinct from
372
372
  // EMPTY_TURN_RETRY_NUDGE: that one diagnoses output-budget exhaustion and tells
373
373
  // the model to "answer directly", which makes a stranded investigation RE-RUN
374
- // 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`
375
375
  // status ack and did real tool work; the turn just ended on an unanswered
376
376
  // toolUse before final prose. The prior toolUse/toolResult entries are still in
377
377
  // this session's branch on the re-prompt, so the recovery is to STOP, read what
@@ -424,8 +424,9 @@ export const COLD_START_REPLY_NUDGE = [
424
424
  // Reminder-only nudge for the empty-stop-after-tool-work retry. Distinct from
425
425
  // both EMPTY_TURN_RETRY_NUDGE (which misdiagnoses a clean `stop` as output-budget
426
426
  // exhaustion and, per its own docstring, makes the model RE-RUN its tools and
427
- // strand again) and STRANDED_TOOLUSE_CONTINUATION_NUDGE (which assumes a `continue:
428
- // 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
429
430
  // tool results, then the final completion came back as a bare empty `stop` — the
430
431
  // Fireworks/gpt empty-completion degeneration. The recovery is to READ the results
431
432
  // already in this branch, summarize, and reply — NOT to re-investigate. The
@@ -452,7 +453,7 @@ export const EMPTY_STOP_AFTER_TOOL_WORK_NUDGE = [
452
453
  // is a one-shot correction offer, not recovery from no output.
453
454
  export const MAX_WILLINGNESS_NUDGES = 1
454
455
  // Injected when a reply that ended the turn (terminal-reply abort) promised to
455
- // keep working but omitted `continue: true`. Reminder-only, SYSTEM MESSAGE
456
+ // keep working but omitted `more_work_this_turn: true`. Reminder-only, SYSTEM MESSAGE
456
457
  // framing so persona-rich models do not reply to the notice itself.
457
458
  export const WILLINGNESS_NUDGE = [
458
459
  '---',
@@ -460,14 +461,14 @@ export const WILLINGNESS_NUDGE = [
460
461
  '',
461
462
  'Your last reply said you would keep working this turn, but it ended right',
462
463
  'after sending — a successful channel reply ends the turn unless you set',
463
- '`continue: true` on it. This is an automated signal from the channel router,',
464
- 'not a message from anyone in the chat. **Do not acknowledge or reply to this',
465
- '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.**',
466
467
  '',
467
468
  'If you still have work to do (fetch data, run a tool, spawn a subagent, then',
468
469
  'reply with the result), do it now — and on the status reply that precedes more',
469
- 'work this turn, set `continue: true`. If there is nothing left to do, reply',
470
- '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`.',
471
472
  '',
472
473
  '---',
473
474
  ].join('\n')
@@ -475,7 +476,7 @@ export const WILLINGNESS_NUDGE = [
475
476
  // did fresh work after it, then ended on an EMPTY `stop` leaf — the answer was
476
477
  // computed but never sent (the Kimi/Fireworks empty-completion flake). Distinct
477
478
  // from WILLINGNESS_NUDGE: that path is a `channel_reply` that ended the turn and
478
- // 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
479
480
  // turn) whose follow-up degenerated, so the model just needs to emit the reply it
480
481
  // already worked out. Shares MAX_WILLINGNESS_NUDGES so a turn can't double-nudge.
481
482
  export const SEND_WILLINGNESS_NUDGE = [
@@ -945,7 +946,7 @@ type LiveSession = {
945
946
  // channel send landed this turn. `validateChannelTurn` compares it to the
946
947
  // turn-end leaf: a DIFFERENT assistant `stop` leaf means the model replied,
947
948
  // kept working, then ended with FRESH final prose it forgot to deliver
948
- // (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
949
950
  // matches is narration the model emitted BEFORE/with the reply that already
950
951
  // landed, so it stays suppressed. Reset to null on every new prompt batch.
951
952
  lastSendLeafId: string | null
@@ -1017,14 +1018,14 @@ type LiveSession = {
1017
1018
  // nudge itself queues — same anti-reloop discipline as the empty-turn budget.
1018
1019
  willingnessNudges: number
1019
1020
  // Stashed by `installChannelReplyTerminalHook` just before it aborts the turn
1020
- // 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
1021
1022
  // by `validateChannelTurn` to decide the continuation nudge. `turnSeq`-stamped
1022
1023
  // (like `skippedTurn`/`skipLockedSendTurn`) so a stale record from an earlier
1023
1024
  // turn can never trigger a nudge on a later one. `null` when no such reply
1024
1025
  // ended this turn.
1025
1026
  lastTerminalReplyAbort: { turnSeq: number; text: string } | null
1026
1027
  // Stamped by `installChannelReplyTerminalHook` when a successful `channel_reply`
1027
- // 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"
1028
1029
  // promise. `validateChannelTurn` reads it to recover a turn that made that promise,
1029
1030
  // did more work, then ended on a fresh empty `stop` (dropped its conclusion) —
1030
1031
  // independent of what natural-language phrase the ack used, so a persona speaking
@@ -1085,6 +1086,26 @@ type LiveSession = {
1085
1086
  // question escalation. Compared by `turnSeq` so a stale value can't leak across
1086
1087
  // turns.
1087
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
1088
1109
  // Stamped with `turnSeq` when a formal GitHub review (APPROVE / REQUEST_CHANGES /
1089
1110
  // COMMENT) lands during this LOGICAL turn, via noteGithubReviewOutput off the
1090
1111
  // review-output observer. On a github PR channel the agent's real deliverable is
@@ -1464,6 +1485,17 @@ export type ChannelRouter = {
1464
1485
  lastTurnAuthorIds: readonly string[]
1465
1486
  }
1466
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
1467
1499
  // Returns a shallow copy of `live.originRef.current` for the live
1468
1500
  // session matching `key`, or undefined when no live session exists.
1469
1501
  // Exists so tests can assert on the per-turn origin that tool.before
@@ -1505,6 +1537,14 @@ export type CreateChannelRouterOptions = {
1505
1537
  // decision. Defaults to a stat()-based reader returning 0 for a missing or
1506
1538
  // unreadable file (grace then fails closed to roll-over-at-soft-TTL).
1507
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
1508
1548
  // Test seam: override the ensureLive watchdog ceiling so the timeout path
1509
1549
  // is exercisable in <100ms instead of the 30s production default.
1510
1550
  ensureLiveTimeoutMs?: number
@@ -2227,6 +2267,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2227
2267
  skipLockedSendTurn: null,
2228
2268
  disengagedTurn: null,
2229
2269
  emptyTurnFallbackTurn: null,
2270
+ stagedFallbackCause: null,
2230
2271
  githubReviewOutputTurn: null,
2231
2272
  pendingQuoteCandidate: null,
2232
2273
  recentEngagedPeerBotTurns: [],
@@ -2595,20 +2636,21 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2595
2636
  // continue. A prior non-typeclaw `afterToolCall` (none today) would be
2596
2637
  // composed, not clobbered.
2597
2638
  //
2598
- // `channel_reply({ continue: true })` is the explicit opt-out: a mid-turn
2599
- // status reply ("working on it…") that the model follows with more work this
2600
- // turn. The tool surfaces that intent as `details.continue === true`, and we
2601
- // keep the follow-up so the turn proceeds. The kimi 32k loop only recurs when
2602
- // the model genuinely has nothing left to say after a reply, which `continue`
2603
- // 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.
2604
2646
  const installChannelReplyTerminalHook = (live: LiveSession): void => {
2605
2647
  const { agent } = live.session
2606
2648
  const prior = agent.afterToolCall
2607
2649
  agent.afterToolCall = async (context, signal) => {
2608
2650
  const result = prior ? await prior(context, signal) : undefined
2609
- 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
2610
2652
  const succeeded = context.toolCall.name === 'channel_reply' && !context.isError && details?.ok === true
2611
- const keepTurnAlive = details?.continue === true
2653
+ const keepTurnAlive = details?.more_work_this_turn === true
2612
2654
  if (succeeded && keepTurnAlive) {
2613
2655
  live.continueReplyTurn = { turnSeq: live.turnSeq, sendCount: live.successfulChannelSends }
2614
2656
  }
@@ -2733,7 +2775,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2733
2775
  if (live.destroyed) return
2734
2776
  if (live.promptQueue.length > 0 || live.pendingSystemReminders.length > 0) return
2735
2777
  try {
2736
- await runIdleContinuation({
2778
+ await (options.runIdleContinuation ?? runIdleContinuation)({
2737
2779
  agentDir: options.agentDir,
2738
2780
  origin: buildLiveOrigin(live),
2739
2781
  deliver: (text) => {
@@ -2745,6 +2787,69 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2745
2787
  }
2746
2788
  }
2747
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
+
2748
2853
  const fireSessionTurnStart = async (live: LiveSession, userPrompt: string): Promise<{ results: string }> => {
2749
2854
  const retrievalContext = { results: '' }
2750
2855
  if (!live.hooks) return retrievalContext
@@ -2965,6 +3070,16 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2965
3070
  live.toolLeakRetries = 0
2966
3071
  live.emptyStopAfterToolWorkArmed = false
2967
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
+ }
2968
3083
  live.abortReasonThisTurn = null
2969
3084
  live.nextPromptMaxTokens = undefined
2970
3085
  // Cleared with the retry budgets (NOT beside resetReviewTurn below) so a
@@ -3090,7 +3205,14 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3090
3205
  const fallbackPostedThisTurn = live.emptyTurnFallbackTurn === live.turnSeq
3091
3206
  const sentReplyThisTurn = live.successfulChannelSends > successfulSendsBeforePrompt
3092
3207
  const usableReplyThisTurn = sentReplyThisTurn && !fallbackPostedThisTurn && !providerErrorThisTurn
3093
- 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) {
3094
3216
  live.lastQuestionSignal = usableReplyThisTurn ? live.pendingUserTurnSignal.signal : null
3095
3217
  live.pendingUserTurnSignal = null
3096
3218
  }
@@ -3165,6 +3287,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3165
3287
  await fireSessionIdle(live)
3166
3288
  await recordTodoTurnStart(live, isRealUserTurn)
3167
3289
  await maybeContinueTodosChannel(live)
3290
+ await resolveStagedFallback(live)
3168
3291
  live.lastTurnAuthorIds = new Set(live.currentTurnAuthorIds)
3169
3292
  if (live.currentTurnAuthorId !== null) {
3170
3293
  live.lastTurnAuthorId = live.currentTurnAuthorId
@@ -4486,7 +4609,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4486
4609
  }
4487
4610
 
4488
4611
  // The turn ended via the terminal-reply abort. If that reply promised to keep
4489
- // 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
4490
4613
  // the model gets a second chance to actually do it. The abort already fired
4491
4614
  // (safe default preserved); this only adds an optional nudge. Bounded by
4492
4615
  // MAX_WILLINGNESS_NUDGES and gated on `promptQueue` being empty so a real
@@ -4531,22 +4654,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4531
4654
  live.skippedTurn = null
4532
4655
  logger.info(`[channels] ${live.keyId} skip_contested_by_send recovering reply`)
4533
4656
  }
4534
- const postEmptyTurnFallback = async (cause: string): Promise<void> => {
4535
- logger.warn(`[channels] ${live.keyId} empty_turn_fallback cause=${cause}`)
4536
- live.emptyTurnFallbackTurn = live.turnSeq
4537
- const result = await send(
4538
- {
4539
- adapter: live.key.adapter,
4540
- workspace: live.key.workspace,
4541
- chat: live.key.chat,
4542
- thread: live.key.thread,
4543
- text: EMPTY_TURN_FALLBACK_TEXT,
4544
- },
4545
- { source: 'system' },
4546
- )
4547
- if (!result.ok) {
4548
- logger.warn(`[channels] ${live.keyId}: empty-turn fallback send failed: ${result.error}`)
4549
- }
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 }
4550
4660
  }
4551
4661
 
4552
4662
  // A formal GitHub review already landed this logical turn (APPROVE /
@@ -4588,10 +4698,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4588
4698
  )
4589
4699
  }
4590
4700
 
4591
- // 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`
4592
4702
  // progress reply, kept working, then ENDED with its final answer as plain
4593
4703
  // prose — never calling a channel tool again. The terminal-reply abort fires
4594
- // 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:
4595
4705
  // 'stop'` text leaf is left undelivered and unguarded (the false-receipt
4596
4706
  // guard is github-only). The discriminator is leaf IDENTITY: only when the
4597
4707
  // turn-end `stop` leaf is a DIFFERENT entry than the one in place at the last
@@ -4601,17 +4711,17 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4601
4711
  if (live.successfulChannelSends > successfulSendsBeforePrompt) {
4602
4712
  maybeNudgeContinuationWillingness(live)
4603
4713
 
4604
- // 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
4605
4715
  // machine-readable "I'll keep working" promise — `continueReplyTurn` is stamped
4606
4716
  // by installChannelReplyTerminalHook), the model did more work, then ended on a
4607
4717
  // FRESH empty `stop` — dropping its conclusion. This is the SAME degeneration as
4608
- // 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`
4609
4719
  // FLAG instead of a natural-language willingness phrase. The flag is the robust
4610
4720
  // signal: it fires regardless of the ack's language or register, closing the gap
4611
4721
  // where a persona speaking a phrasing outside the willingness table (e.g. casual
4612
4722
  // Korean "확인해볼게") stranded the user in silence. The `attemptMadeToolCall`
4613
4723
  // half ties the first trigger to real post-ack work; `willingnessNudges > 0`
4614
- // 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
4615
4725
  // budget toward the visible fallback instead of bailing silent. Same
4616
4726
  // MAX_WILLINGNESS_NUDGES bound, same empty-`promptQueue` gate (a coalesced live
4617
4727
  // inbound supersedes this turn's silence), and same nudge/fallback path as the
@@ -4637,7 +4747,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4637
4747
  )
4638
4748
  live.pendingSystemReminders.push(SEND_WILLINGNESS_NUDGE)
4639
4749
  } else {
4640
- await postEmptyTurnFallback('empty_stop_after_continue_reply_nudges_exhausted')
4750
+ stageEmptyTurnFallback('empty_stop_after_continue_reply_nudges_exhausted')
4641
4751
  }
4642
4752
  return
4643
4753
  }
@@ -4673,14 +4783,14 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4673
4783
  )
4674
4784
  live.pendingSystemReminders.push(SEND_WILLINGNESS_NUDGE)
4675
4785
  } else {
4676
- await postEmptyTurnFallback('empty_stop_after_send_ack_nudges_exhausted')
4786
+ stageEmptyTurnFallback('empty_stop_after_send_ack_nudges_exhausted')
4677
4787
  }
4678
4788
  return
4679
4789
  }
4680
4790
 
4681
4791
  const trailing = recoverableAssistantText(live.session)
4682
4792
  if (trailing === null || trailing.source !== 'leaf') {
4683
- // 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
4684
4794
  // unanswered `toolUse` (the post-tool follow-up never produced an
4685
4795
  // assistant message — aborted loop / cancelled stream). The promised
4686
4796
  // work never finished, so the user is left with a bare "checking now…"
@@ -4710,7 +4820,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4710
4820
  )
4711
4821
  live.pendingSystemReminders.push(STRANDED_TOOLUSE_CONTINUATION_NUDGE)
4712
4822
  } else {
4713
- await postEmptyTurnFallback('stranded_toolUse_retries_exhausted')
4823
+ await postEmptyTurnFallback(live, 'stranded_toolUse_retries_exhausted')
4714
4824
  }
4715
4825
  }
4716
4826
  return
@@ -4826,7 +4936,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4826
4936
  live.pendingSystemReminders.push(EMPTY_TURN_RETRY_NUDGE)
4827
4937
  return
4828
4938
  }
4829
- await postEmptyTurnFallback(attemptedSendThisTurn ? 'send_thrash' : 'retries_exhausted')
4939
+ await postEmptyTurnFallback(live, attemptedSendThisTurn ? 'send_thrash' : 'retries_exhausted')
4830
4940
  return
4831
4941
  }
4832
4942
 
@@ -4861,7 +4971,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4861
4971
  live.pendingSystemReminders.push(COLD_START_REPLY_NUDGE)
4862
4972
  return
4863
4973
  }
4864
- await postEmptyTurnFallback('cold_start_solo_bare_empty_retries_exhausted')
4974
+ await postEmptyTurnFallback(live, 'cold_start_solo_bare_empty_retries_exhausted')
4865
4975
  return
4866
4976
  }
4867
4977
  // Deliberately AFTER the cold-start guard (that path has its own nudge). A
@@ -4897,7 +5007,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4897
5007
  live.pendingSystemReminders.push(EMPTY_STOP_AFTER_TOOL_WORK_NUDGE)
4898
5008
  return
4899
5009
  }
4900
- await postEmptyTurnFallback('empty_stop_after_tool_work_retries_exhausted')
5010
+ await postEmptyTurnFallback(live, 'empty_stop_after_tool_work_retries_exhausted')
4901
5011
  return
4902
5012
  }
4903
5013
  const leakedReasoning = !isNoReplySignal(assistantText)
@@ -5061,7 +5171,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5061
5171
  chat: live.key.chat,
5062
5172
  thread: live.key.thread,
5063
5173
  text,
5064
- isContinue: false,
5174
+ moreWorkThisTurn: false,
5065
5175
  resolveReviewThread: false,
5066
5176
  })
5067
5177
  if (falseReceipt.kind === 'block') return falseReceipt.reason
@@ -5073,7 +5183,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5073
5183
  thread: live.key.thread,
5074
5184
  text,
5075
5185
  wantsResolve: false,
5076
- isContinue: false,
5186
+ moreWorkThisTurn: false,
5077
5187
  getReviewState: (req) => getReviewState(req),
5078
5188
  })
5079
5189
  if (rereview.block) return rereview.reason
@@ -5954,6 +6064,16 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5954
6064
  lastTurnAuthorIds: Array.from(live.lastTurnAuthorIds),
5955
6065
  }
5956
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
+ },
5957
6077
  },
5958
6078
  }
5959
6079
  }
@@ -6858,7 +6978,7 @@ function assistantLeafStopReason(session: AgentSession): 'length' | 'error' | 'a
6858
6978
  // alongside its tool call and DID land a real send this turn (that trailing
6859
6979
  // `toolUse` is delivered narration, not a stranded promise — leave it alone).
6860
6980
  // Keys on the model having INTENDED to keep working with nothing yet said; used
6861
- // 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
6862
6982
  // reply instead of ending in silence.
6863
6983
  function leafIsStrandedToolUse(session: AgentSession): boolean {
6864
6984
  const leaf = session.sessionManager.getLeafEntry()
@@ -6888,7 +7008,7 @@ function leafIsStrandedToolUse(session: AgentSession): boolean {
6888
7008
  // (the model did more work, then dropped its conclusion) from a legitimate
6889
7009
  // ack-then-stop where the model meant to wait for the user (leaf unchanged since
6890
7010
  // the send). The two willingness paths below layer their own promise-signal on top
6891
- // of this shape: `channel_reply({ continue: true })` via `continueReplyTurn`, and
7011
+ // of this shape: `channel_reply({ more_work_this_turn: true })` via `continueReplyTurn`, and
6892
7012
  // `channel_send` acks via the willingness phrase table.
6893
7013
  function isFreshEmptyStopAfterSend(live: LiveSession): boolean {
6894
7014
  const leaf = live.session.sessionManager.getLeafEntry()
@@ -6898,10 +7018,10 @@ function isFreshEmptyStopAfterSend(live: LiveSession): boolean {
6898
7018
  return leaf.id !== live.lastSendLeafId
6899
7019
  }
6900
7020
 
6901
- // 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
6902
7022
  // send to this target was a continuation-willingness ack (by phrase), then the
6903
7023
  // model produced a fresh empty stop. `channel_send` keeps the turn alive without a
6904
- // `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
6905
7025
  // only "I promised to keep working" signal available for that shape.
6906
7026
  function isEmptyStopAfterWillingnessAck(live: LiveSession): boolean {
6907
7027
  if (!isFreshEmptyStopAfterSend(live)) return false
package/src/git/run.ts ADDED
@@ -0,0 +1,60 @@
1
+ import { hooklessGitArgs } from './hookless'
2
+
3
+ export type RunGitResult = {
4
+ exitCode: number
5
+ stdout: string
6
+ stderr: string
7
+ }
8
+
9
+ type DrainableProcess = {
10
+ stdout: { text: () => Promise<string> }
11
+ stderr: { text: () => Promise<string> }
12
+ exited: Promise<number>
13
+ }
14
+
15
+ // `proc.exited` only signals child termination; it does not consume or close
16
+ // the piped stdout/stderr streams. A stream left undrained holds its parent
17
+ // read-end fd until GC finalizes it, so awaiting exit alone lets fds accumulate
18
+ // under memory pressure (delayed GC) — the leak this helper exists to stop.
19
+ // Draining both streams to EOF makes `runGit` own the full resource lifecycle:
20
+ // it does not resolve until the process has exited AND both pipes are closed.
21
+ // Both reads are STARTED before we await, so neither can be starved by the
22
+ // other (Bun v1.3.14 buffers subprocess output internally, so this is about
23
+ // deterministic fd release, not an OS pipe-capacity deadlock).
24
+ async function collectProcessOutput(proc: DrainableProcess): Promise<RunGitResult> {
25
+ const stdoutDrain = proc.stdout.text()
26
+ const stderrDrain = proc.stderr.text()
27
+ const exited = proc.exited
28
+ const [exitCode, stdout, stderr] = await Promise.all([exited, stdoutDrain, stderrDrain])
29
+ return { exitCode, stdout, stderr }
30
+ }
31
+
32
+ export async function runGit(
33
+ bun: { spawn: typeof Bun.spawn },
34
+ cwd: string,
35
+ args: readonly string[],
36
+ ): Promise<RunGitResult> {
37
+ const proc = bun.spawn({
38
+ cmd: ['git', ...hooklessGitArgs(args)],
39
+ cwd,
40
+ stdout: 'pipe',
41
+ stderr: 'pipe',
42
+ })
43
+ const drainable: DrainableProcess = {
44
+ stdout: { text: () => Bun.readableStreamToText(proc.stdout) },
45
+ stderr: { text: () => Bun.readableStreamToText(proc.stderr) },
46
+ exited: proc.exited,
47
+ }
48
+ try {
49
+ return await collectProcessOutput(drainable)
50
+ } catch (drainErr) {
51
+ // A pipe-read rejection must not escape while the child may still be
52
+ // running: kill it, then let exit and both drains settle so no fd is left
53
+ // dangling behind the error.
54
+ proc.kill()
55
+ await Promise.allSettled([drainable.exited, drainable.stdout.text(), drainable.stderr.text()])
56
+ throw drainErr
57
+ }
58
+ }
59
+
60
+ export const _internal = { collectProcessOutput }