typeclaw 0.39.2 → 0.39.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 (102) hide show
  1. package/auth.schema.json +110 -0
  2. package/package.json +2 -2
  3. package/secrets.schema.json +110 -0
  4. package/src/agent/index.ts +39 -18
  5. package/src/agent/model-fallback.ts +13 -4
  6. package/src/agent/plugin-tools.ts +12 -12
  7. package/src/agent/provider-error.ts +36 -1
  8. package/src/agent/session-origin.ts +2 -0
  9. package/src/agent/subagents.ts +29 -2
  10. package/src/agent/throttle-circuit.ts +50 -0
  11. package/src/agent/todo/store.ts +21 -1
  12. package/src/agent/tools/channel-reply.ts +18 -5
  13. package/src/agent/tools/channel-send.ts +13 -2
  14. package/src/agent/turn-runner.ts +162 -0
  15. package/src/bundled-plugins/doc-render/render.ts +2 -2
  16. package/src/bundled-plugins/github-cli-auth/approve-idempotency.ts +40 -18
  17. package/src/bundled-plugins/memory/README.md +12 -12
  18. package/src/bundled-plugins/memory/append-tool.ts +58 -6
  19. package/src/bundled-plugins/memory/dreaming.ts +1 -1
  20. package/src/bundled-plugins/memory/fragment-parser.ts +10 -3
  21. package/src/bundled-plugins/memory/load-memory.ts +28 -2
  22. package/src/bundled-plugins/memory/memory-logger.ts +14 -2
  23. package/src/bundled-plugins/memory/search-tool.ts +50 -7
  24. package/src/bundled-plugins/memory/stream-events.ts +23 -0
  25. package/src/bundled-plugins/memory/vector/hybrid.ts +9 -2
  26. package/src/bundled-plugins/security/index.ts +24 -1
  27. package/src/bundled-plugins/security/policies/cron-promotion.ts +94 -62
  28. package/src/bundled-plugins/security/policies/plugin-addition.ts +2 -4
  29. package/src/bundled-plugins/security/policies/role-promotion.ts +2 -4
  30. package/src/channels/adapters/discord-author-resolver.ts +52 -0
  31. package/src/channels/adapters/discord-bot.ts +1 -1
  32. package/src/channels/adapters/discord-channel-resolver.ts +44 -0
  33. package/src/channels/adapters/discord-classify.ts +121 -0
  34. package/src/channels/adapters/discord-reactions.ts +138 -0
  35. package/src/channels/adapters/discord.ts +416 -0
  36. package/src/channels/adapters/github/outbound.ts +23 -4
  37. package/src/channels/adapters/kakaotalk.ts +8 -1
  38. package/src/channels/adapters/line.ts +1 -1
  39. package/src/channels/adapters/slack-author-resolver.ts +54 -0
  40. package/src/channels/adapters/slack-bot.ts +3 -1
  41. package/src/channels/adapters/slack-channel-resolver.ts +49 -0
  42. package/src/channels/adapters/slack-classify.ts +83 -0
  43. package/src/channels/adapters/slack-reactions.ts +126 -0
  44. package/src/channels/adapters/slack.ts +416 -0
  45. package/src/channels/adapters/telegram-bot.ts +2 -1
  46. package/src/channels/adapters/webex-bot.ts +31 -27
  47. package/src/channels/adapters/webex-prefetch-limiter.ts +120 -0
  48. package/src/channels/adapters/webex.ts +81 -31
  49. package/src/channels/github-review-turn-ledger.ts +32 -0
  50. package/src/channels/github-verdict-activity.ts +60 -0
  51. package/src/channels/index.ts +6 -0
  52. package/src/channels/manager.ts +168 -37
  53. package/src/channels/pr-verdict-activity-bridge.ts +43 -0
  54. package/src/channels/router.ts +295 -13
  55. package/src/channels/schema.ts +4 -0
  56. package/src/channels/types.ts +25 -2
  57. package/src/cli/builtins.ts +6 -31
  58. package/src/cli/channel.ts +170 -18
  59. package/src/cli/command-meta.ts +93 -0
  60. package/src/cli/help.ts +24 -0
  61. package/src/cli/index.ts +45 -10
  62. package/src/cli/init.ts +2 -0
  63. package/src/cli/update-check.ts +14 -0
  64. package/src/cli/update-notify.ts +91 -0
  65. package/src/cli/update-suppression.ts +19 -0
  66. package/src/config/channels-mutation.ts +3 -1
  67. package/src/config/config.ts +78 -1
  68. package/src/config/index.ts +1 -0
  69. package/src/container/start.ts +52 -8
  70. package/src/doctor/channel-checks.ts +57 -3
  71. package/src/hostd/daemon.ts +77 -31
  72. package/src/hostd/index.ts +11 -1
  73. package/src/hostd/paths.ts +4 -0
  74. package/src/hostd/protocol.ts +15 -2
  75. package/src/hostd/spawn.ts +53 -19
  76. package/src/init/cli-version.ts +1 -1
  77. package/src/init/discord-auth.ts +50 -0
  78. package/src/init/index.ts +94 -4
  79. package/src/init/reconcile-plugin-deps.ts +30 -5
  80. package/src/init/run-owner-claim.ts +2 -0
  81. package/src/init/slack-auth.ts +51 -0
  82. package/src/mcp/manager.ts +94 -7
  83. package/src/mcp/tools.ts +7 -4
  84. package/src/permissions/permissions.ts +12 -0
  85. package/src/permissions/resolve.ts +2 -0
  86. package/src/role-claim/match-rule.ts +2 -0
  87. package/src/run/codex-fetch-observer.ts +11 -6
  88. package/src/run/index.ts +74 -29
  89. package/src/secrets/discord-store.ts +96 -0
  90. package/src/secrets/oauth-xai.ts +2 -2
  91. package/src/secrets/schema.ts +34 -0
  92. package/src/secrets/slack-store.ts +96 -0
  93. package/src/server/command-runner.ts +21 -0
  94. package/src/server/index.ts +27 -2
  95. package/src/skills/typeclaw-channels/SKILL.md +1 -1
  96. package/src/skills/typeclaw-config/SKILL.md +1 -0
  97. package/src/skills/typeclaw-cron/SKILL.md +20 -4
  98. package/src/skills/typeclaw-permissions/SKILL.md +18 -6
  99. package/src/tui/format.ts +0 -19
  100. package/src/tui/index.ts +2 -8
  101. package/src/update/check.ts +192 -0
  102. package/typeclaw.schema.json +332 -0
@@ -2,12 +2,14 @@ import { statSync } from 'node:fs'
2
2
  import { basename } from 'node:path'
3
3
 
4
4
  import type { AssistantMessage } from '@mariozechner/pi-ai'
5
- import { SessionManager } from '@mariozechner/pi-coding-agent'
5
+ import { type SessionEntry, SessionManager } from '@mariozechner/pi-coding-agent'
6
6
 
7
7
  import { createSession, renderTurnRoleAnchor, renderTurnTimeAnchor, type AgentSession } from '@/agent'
8
8
  import { applyTurnThinkingLevel, getQuestionSignal, type QuestionSignal } from '@/agent/attention-escalation'
9
+ import { resolveFallbackChain } from '@/agent/model-fallback'
10
+ import { applyModelRuntimeOverrides } from '@/agent/model-overrides'
9
11
  import { forgetSharedLoopGuardTool } from '@/agent/plugin-tools'
10
- import { subscribeProviderErrors } from '@/agent/provider-error'
12
+ import { isThrottleOrOverload, subscribeProviderErrors } from '@/agent/provider-error'
11
13
  import type { RestartHandoff } from '@/agent/restart-handoff'
12
14
  import type { ChannelParticipant, SessionOrigin } from '@/agent/session-origin'
13
15
  import { renderSubagentCompletionReminder } from '@/agent/subagent-completion-reminder'
@@ -19,7 +21,9 @@ import {
19
21
  runIdleContinuation,
20
22
  } from '@/agent/todo/continuation-wiring'
21
23
  import { SUBAGENT_OUTPUT_TOOL_NAME } from '@/agent/tools/subagent-output'
24
+ import { promptPersistentTurnWithFallback } from '@/agent/turn-runner'
22
25
  import { type Command, type CommandPermission, type CommandResult, createCommandRegistry } from '@/commands'
26
+ import { getConfig, resolveModel } from '@/config'
23
27
  import { CORE_PERMISSIONS, type PermissionService } from '@/permissions'
24
28
  import type { HookBus } from '@/plugin'
25
29
  import { extractClaimCode } from '@/role-claim'
@@ -39,6 +43,7 @@ import {
39
43
  import { checkFalseReceipt } from './github-false-receipt'
40
44
  import { evaluateRereviewGuard } from './github-rereview-guard'
41
45
  import { resetReviewTurn } from './github-review-turn-ledger'
46
+ import { renderPrVerdictStandDownReminder } from './github-verdict-activity'
42
47
  import {
43
48
  MEMBERSHIP_COLD_FETCH_TIMEOUT_MS,
44
49
  type MembershipCount,
@@ -261,6 +266,31 @@ export const EMPTY_TURN_RETRY_NUDGE = [
261
266
  '',
262
267
  '---',
263
268
  ].join('\n')
269
+ // Reminder-only nudge for the stranded-toolUse-after-send retry. Distinct from
270
+ // EMPTY_TURN_RETRY_NUDGE: that one diagnoses output-budget exhaustion and tells
271
+ // the model to "answer directly", which makes a stranded investigation RE-RUN
272
+ // its tools and strand again. Here the model already sent a `continue: true`
273
+ // status ack and did real tool work; the turn just ended on an unanswered
274
+ // toolUse before final prose. The prior toolUse/toolResult entries are still in
275
+ // this session's branch on the re-prompt, so the recovery is to STOP, read what
276
+ // it already gathered, and reply — not to start the investigation over.
277
+ export const STRANDED_TOOLUSE_CONTINUATION_NUDGE = [
278
+ '---',
279
+ '**[SYSTEM MESSAGE — not from a human]**',
280
+ '',
281
+ 'Your previous turn sent a brief status reply, did some tool work, then ended',
282
+ 'before sending the answer it promised. This is an automated signal from the',
283
+ 'channel router, not a message from anyone in the chat. **Do not acknowledge or',
284
+ 'reply to this notice itself.**',
285
+ '',
286
+ 'Do NOT start the investigation over. The tool results you already gathered are',
287
+ 'still in this conversation above — read them, summarize what you found, and',
288
+ 'send your reply now via your channel reply tool. Only call more tools if a',
289
+ 'specific fact is genuinely still missing. If you truly have nothing to say,',
290
+ 'reply with `NO_REPLY`.',
291
+ '',
292
+ '---',
293
+ ].join('\n')
264
294
  // Posted to the channel (via the `source:'system'` one-shot bypass) when an
265
295
  // empty turn cannot be recovered AND retries are exhausted (or are skipped
266
296
  // because the turn thrashed the send path). Replaces the historical silent
@@ -289,6 +319,32 @@ export const COLD_START_REPLY_NUDGE = [
289
319
  '',
290
320
  '---',
291
321
  ].join('\n')
322
+ // Reminder-only nudge for the empty-stop-after-tool-work retry. Distinct from
323
+ // both EMPTY_TURN_RETRY_NUDGE (which misdiagnoses a clean `stop` as output-budget
324
+ // exhaustion and, per its own docstring, makes the model RE-RUN its tools and
325
+ // strand again) and STRANDED_TOOLUSE_CONTINUATION_NUDGE (which assumes a `continue:
326
+ // true` status reply already landed). Here NO send landed, the model gathered real
327
+ // tool results, then the final completion came back as a bare empty `stop` — the
328
+ // Fireworks/gpt empty-completion degeneration. The recovery is to READ the results
329
+ // already in this branch, summarize, and reply — NOT to re-investigate. The
330
+ // trailing NO_REPLY escape is what makes the rare research-then-decline false
331
+ // positive self-correct on the first retry instead of forcing the fallback.
332
+ export const EMPTY_STOP_AFTER_TOOL_WORK_NUDGE = [
333
+ '---',
334
+ '**[SYSTEM MESSAGE — not from a human]**',
335
+ '',
336
+ 'Your previous turn gathered information with your tools, then ended without',
337
+ 'sending any reply — the final completion came back empty. This is an automated',
338
+ 'signal from the channel router, not a message from anyone in the chat. **Do not',
339
+ 'acknowledge or reply to this notice itself.**',
340
+ '',
341
+ 'Do NOT re-run your tools. The results you already gathered are still in this',
342
+ 'conversation above — read them, summarize what you found, and send your reply',
343
+ 'now via your channel reply tool. Only call more tools if a specific fact is',
344
+ 'genuinely still missing. If you truly have nothing to say, reply with `NO_REPLY`.',
345
+ '',
346
+ '---',
347
+ ].join('\n')
292
348
  // At most one continuation nudge per logical turn. Stricter than the empty-turn
293
349
  // retry budget (2) because the turn ALREADY delivered a user-facing reply — this
294
350
  // is a one-shot correction offer, not recovery from no output.
@@ -380,6 +436,23 @@ export const SESSION_FRESHNESS_TTL_MS = 5 * 60 * 1000
380
436
  */
381
437
  export const SESSION_GRACE_HARD_TTL_MS = 10 * 60 * 1000
382
438
 
439
+ /**
440
+ * Absolute ceiling on how long a running background subagent may pin its parent
441
+ * channel session against idle GC and stale-rollover. A still-running child defers
442
+ * teardown because the next inbound otherwise starts a fresh session that has lost
443
+ * track of the in-flight task and spawns a DUPLICATE child for the same work. The
444
+ * pin is bounded so a stuck/never-completing child cannot make the session
445
+ * immortal: past this age the session is GC'd / rolled over anyway, falling back
446
+ * to the completion-reroute behavior. Measured from the child's start.
447
+ *
448
+ * Set above SESSION_IDLE_MS (30m) — not equal — so a child spawned at session
449
+ * birth still pins the session through its first idle sweep instead of the two
450
+ * windows coinciding. Comfortably above SESSION_GRACE_HARD_TTL_MS (10m) too:
451
+ * real research runs can exceed it (an observed run took 9m18s), so the 10m cap
452
+ * is far too tight to bound the pin.
453
+ */
454
+ export const SESSION_CHILD_PIN_MAX_MS = 45 * 60 * 1000
455
+
383
456
  /**
384
457
  * Cost-aware grace decision for the soft→hard TTL band. Returns true when reusing
385
458
  * the (now cache-cold) live session is cheaper than a fresh cold-start.
@@ -512,7 +585,7 @@ export type CreateSessionForChannel = (params: {
512
585
  // `options.originRef`.
513
586
  originRef: { current: SessionOrigin | undefined }
514
587
  }) => Promise<{
515
- session: AgentSession
588
+ session: ChannelAgentSession
516
589
  sessionId: string
517
590
  dispose: () => Promise<void>
518
591
  hooks?: HookBus
@@ -570,10 +643,13 @@ type ObservedInbound = {
570
643
 
571
644
  type TimedAttachment = { ts: number; attachment: InboundAttachment }
572
645
 
646
+ type ChannelAgentSession = AgentSession & { getAbortReason?: () => string | undefined }
647
+
573
648
  type LiveSession = {
574
649
  key: ChannelKey
575
650
  keyId: string
576
- session: AgentSession
651
+ session: ChannelAgentSession
652
+ activeModelRef: ReturnType<typeof resolveFallbackChain>[number]
577
653
  // The session's creation-time thinking level, captured once. A later escalated
578
654
  // turn moves `session.thinkingLevel` to `high`, so the live getter can't be the
579
655
  // reset target — this preserves the real default across the session's lifetime.
@@ -746,6 +822,14 @@ type LiveSession = {
746
822
  // increments it before injecting EMPTY_TURN_RETRY_NUDGE and reads it to decide
747
823
  // retry-vs-fallback. See the candidate===null branch.
748
824
  emptyTurnRetries: number
825
+ // Latches once a bare-empty `stop` has been classified as empty-stop-after-tool-work
826
+ // this logical turn. The recovery nudge tells the model NOT to re-run its tools, so
827
+ // a compliant retry is expected to land another bare-empty `stop` with NO new tool
828
+ // call — `attemptMadeToolCall` would then be false and the turn would silently bail
829
+ // with budget unspent. Once armed, the cause persists for the turn so later bare-empty
830
+ // stops keep spending the shared retry budget toward the visible fallback. Reset
831
+ // alongside `emptyTurnRetries` on a real user batch only (anti-reloop discipline).
832
+ emptyStopAfterToolWorkArmed: boolean
749
833
  // Count of continuation nudges spent on the CURRENT logical turn, bounded by
750
834
  // MAX_WILLINGNESS_NUDGES. Reset alongside `emptyTurnRetries` only when a real
751
835
  // user batch starts (batch.length > 0), NOT on the reminder-only iteration the
@@ -758,6 +842,10 @@ type LiveSession = {
758
842
  // turn can never trigger a nudge on a later one. `null` when no such reply
759
843
  // ended this turn.
760
844
  lastTerminalReplyAbort: { turnSeq: number; text: string } | null
845
+ // Stamped by router abort sites and read by `validateChannelTurn` for
846
+ // reason-specific stranded-toolUse recovery logs. `turnSeq`-stamped so stale
847
+ // abort provenance from an earlier turn can never leak into a later retry.
848
+ abortReasonThisTurn: { turnSeq: number; reason: string } | null
761
849
  // One-shot output-token budget for the NEXT `session.prompt()` only.
762
850
  // `installChannelOutputCap` reads and clears it per stream call, so it
763
851
  // overrides the default backstop for exactly one re-prompt. Set by the
@@ -1019,6 +1107,19 @@ export type ChannelRouter = {
1019
1107
  error?: string
1020
1108
  channelKey?: { adapter: string; workspace: string; chat: string; thread: string | null }
1021
1109
  }) => { kind: 'delivered'; keyId: string } | { kind: 'no-live-session' }
1110
+ // Fan a LANDED formal review verdict out to the OTHER live sessions reviewing
1111
+ // the same PR so they stand down from posting a redundant verdict. Targets every
1112
+ // live github session whose chat is `pr:<prNumber>` in `workspace`, EXCLUDING the
1113
+ // publisher (`sessionId`). Routes by (workspace, prNumber) across all threads —
1114
+ // the duplicate-review fan-out is exactly the per-thread sibling sessions. The
1115
+ // injected reminder is advisory (verdict-only stand-down); the hard idempotency
1116
+ // guards remain the correctness boundary. Returns how many siblings were nudged.
1117
+ injectPrVerdictActivity: (args: {
1118
+ workspace: string
1119
+ prNumber: number
1120
+ verdict: 'APPROVE' | 'REQUEST_CHANGES'
1121
+ sessionId: string
1122
+ }) => { kind: 'delivered'; count: number }
1022
1123
  // Record that the agent invoked `skip_response` during the current turn
1023
1124
  // for the channel session identified by `parentSessionId`. The reason is
1024
1125
  // logged at INFO level inside `validateChannelTurn` (single log line per
@@ -1183,6 +1284,16 @@ export type CreateChannelRouterOptions = {
1183
1284
  // saveChannelSessions (which swallows its own I/O errors). Tests inject a
1184
1285
  // throwing impl to exercise the persist-failure unwind in ensureLive.
1185
1286
  saveChannelSessions?: (agentDir: string, sessions: readonly ChannelSessionRecord[]) => Promise<void>
1287
+ // Returns the start time (epoch ms) of the NEWEST still-running background
1288
+ // subagent spawned from `sessionId`, or null when none is running. Lets idle
1289
+ // GC and stale-rollover pin a session whose child is still working (the next
1290
+ // inbound would otherwise spawn a duplicate child), bounded by
1291
+ // SESSION_CHILD_PIN_MAX_MS measured from that start. Newest — not oldest — so a
1292
+ // long-running child that crossed the cap cannot unpin the session while a more
1293
+ // recently spawned child is still inside its own protection window. Production
1294
+ // wiring forwards the LiveSubagentRegistry; omitted (tests, no-subagent setups)
1295
+ // means no pin.
1296
+ newestRunningChildSubagentStartedAt?: (sessionId: string) => number | null
1186
1297
  }
1187
1298
 
1188
1299
  export type RestartCommandContext = {
@@ -1222,6 +1333,7 @@ const GRANT_ALL_PERMISSIONS: PermissionService = {
1222
1333
  has: () => true,
1223
1334
  resolveRole: () => 'owner',
1224
1335
  compareRoleSeverity: () => 1,
1336
+ permissionsForRole: () => [CORE_PERMISSIONS.channelRespond],
1225
1337
  describe: () => ({ role: 'owner', permissions: [CORE_PERMISSIONS.channelRespond] }),
1226
1338
  replaceRoles: () => {},
1227
1339
  }
@@ -1239,6 +1351,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1239
1351
  const stream = options.stream
1240
1352
  const onReload = options.onReload
1241
1353
  const onRestart = options.onRestart
1354
+ const newestRunningChildSubagentStartedAt = options.newestRunningChildSubagentStartedAt ?? (() => null)
1242
1355
  const liveSessions = new Map<string, LiveSession>()
1243
1356
  const creating = new Map<string, Promise<LiveSession>>()
1244
1357
  // Restart-resume reservations, keyed by channelKeyId. Installed by
@@ -1483,11 +1596,30 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1483
1596
  return membership
1484
1597
  }
1485
1598
 
1599
+ // True while a background child spawned from this session is still running AND
1600
+ // the newest such child is within SESSION_CHILD_PIN_MAX_MS of its start. Using
1601
+ // the newest child keeps the session pinned as long as ANY running child is
1602
+ // still inside its protection window — an older child that already crossed the
1603
+ // cap must not unpin the session out from under a freshly spawned one. Tearing
1604
+ // the session down mid-child lets the next inbound spawn a duplicate child, so
1605
+ // GC/rollover defer to this. `label` only annotates the override log.
1606
+ const isPinnedByRunningChild = (sessionId: string, keyId: string, label: string): boolean => {
1607
+ const childStartedAt = newestRunningChildSubagentStartedAt(sessionId)
1608
+ if (childStartedAt === null) return false
1609
+ const pinnedForMs = now() - childStartedAt
1610
+ if (pinnedForMs <= SESSION_CHILD_PIN_MAX_MS) return true
1611
+ logger.info(
1612
+ `[channels] ${keyId}: ${label} despite running child (newest pinned ${pinnedForMs}ms, past child-pin cap)`,
1613
+ )
1614
+ return false
1615
+ }
1616
+
1486
1617
  const shouldRolloverLive = (live: LiveSession, idleMs: number): boolean => {
1487
1618
  // A session mid-prompt looks idle by lastInboundAt (only bumped on engaged
1488
1619
  // inbounds) while session.prompt() is still in flight; rolling it over aborts
1489
1620
  // that work. The runIdleGc path skips draining sessions for the same reason.
1490
1621
  if (live.draining) return false
1622
+ if (isPinnedByRunningChild(live.sessionId, live.keyId, 'stale-rollover')) return false
1491
1623
  if (idleMs <= SESSION_FRESHNESS_TTL_MS) return false
1492
1624
  if (idleMs > SESSION_GRACE_HARD_TTL_MS) {
1493
1625
  logger.info(`[channels] ${live.keyId}: stale-rollover (live: ${idleMs}ms idle, past grace cap)`)
@@ -1572,7 +1704,13 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1572
1704
  resumeTarget === undefined &&
1573
1705
  record?.sessionId !== undefined &&
1574
1706
  existing === undefined &&
1575
- now() - (record.lastInboundAt ?? 0) > SESSION_FRESHNESS_TTL_MS
1707
+ now() - (record.lastInboundAt ?? 0) > SESSION_FRESHNESS_TTL_MS &&
1708
+ // The live session is already gone here, but a background child it spawned
1709
+ // may still be running under its (old) sessionId. Wiping the mapping would
1710
+ // start a fresh session that re-spawns the same child. Keep the mapping so
1711
+ // the reopen continues the same sessionId until the child finishes (or the
1712
+ // pin cap elapses).
1713
+ !isPinnedByRunningChild(record.sessionId, keyId, 'stale-rollover (persisted)')
1576
1714
  ) {
1577
1715
  const idleMs = now() - (record.lastInboundAt ?? 0)
1578
1716
  logger.info(`[channels] ${keyId}: stale-rollover (persisted: ${idleMs}ms idle)`)
@@ -1697,6 +1835,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1697
1835
  key,
1698
1836
  keyId,
1699
1837
  session: created.session,
1838
+ activeModelRef: resolveFallbackChain(getConfig().models, undefined)[0]!,
1700
1839
  turnThinkingDefault: created.session.thinkingLevel,
1701
1840
  lastQuestionSignal: null,
1702
1841
  pendingUserTurnSignal: null,
@@ -1751,8 +1890,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1751
1890
  inFlightToolSends: new Map(),
1752
1891
  policyDeniedToolSendsThisTurn: new Map(),
1753
1892
  emptyTurnRetries: 0,
1893
+ emptyStopAfterToolWorkArmed: false,
1754
1894
  willingnessNudges: 0,
1755
1895
  lastTerminalReplyAbort: null,
1896
+ abortReasonThisTurn: null,
1756
1897
  nextPromptMaxTokens: undefined,
1757
1898
  skippedTurn: null,
1758
1899
  skipLockedSendTurn: null,
@@ -1900,10 +2041,18 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1900
2041
  chat: live.key.chat,
1901
2042
  thread: live.key.thread,
1902
2043
  limit: requested,
2044
+ prefetch: true,
1903
2045
  })
1904
2046
 
1905
2047
  if (!result.ok) {
1906
- logger.warn(`[channels] ${live.keyId}: prefetch skipped (history fetch failed: ${result.error})`)
2048
+ // An adapter that declined a best-effort read to avoid hammering a
2049
+ // rate-limited resource is expected optional-context loss, not a failure —
2050
+ // log it at info so it does not masquerade as an auth/network warning.
2051
+ if (result.skipReason === 'rate-limited') {
2052
+ logger.info(`[channels] ${live.keyId}: prefetch skipped (rate limited: ${result.error})`)
2053
+ } else {
2054
+ logger.warn(`[channels] ${live.keyId}: prefetch skipped (history fetch failed: ${result.error})`)
2055
+ }
1907
2056
  return
1908
2057
  }
1909
2058
 
@@ -2104,6 +2253,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2104
2253
  logger.info(`[channels] ${live.keyId} terminal_after_channel_reply`)
2105
2254
  const replyText = (context.toolCall.arguments as { text?: unknown } | undefined)?.text
2106
2255
  live.lastTerminalReplyAbort = typeof replyText === 'string' ? { turnSeq: live.turnSeq, text: replyText } : null
2256
+ live.abortReasonThisTurn = { turnSeq: live.turnSeq, reason: 'terminal_after_channel_reply' }
2107
2257
  agent.abort()
2108
2258
  }
2109
2259
  return result
@@ -2404,7 +2554,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2404
2554
  // iterations the retry itself queues do not refill the budget and loop
2405
2555
  // forever (and the raised cap stays scoped to the turn that set it).
2406
2556
  live.emptyTurnRetries = 0
2557
+ live.emptyStopAfterToolWorkArmed = false
2407
2558
  live.willingnessNudges = 0
2559
+ live.abortReasonThisTurn = null
2408
2560
  live.nextPromptMaxTokens = undefined
2409
2561
  } else if (live.lastTurnAuthorId !== null) {
2410
2562
  live.currentTurnEngageReactions = []
@@ -2474,7 +2626,26 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2474
2626
  applyTurnThinkingLevel(live.session, retrievalQuery, live.turnThinkingDefault, live.lastQuestionSignal)
2475
2627
  live.promptInFlight = true
2476
2628
  try {
2477
- await live.session.prompt(promptText)
2629
+ const result = await promptPersistentTurnWithFallback({
2630
+ refs: resolveFallbackChain(getConfig().models, undefined),
2631
+ currentModelRef: live.activeModelRef,
2632
+ session: live.session,
2633
+ text: promptText,
2634
+ shouldFailover: (err) => isThrottleOrOverload(err.message),
2635
+ setModelForRef: async (ref) => {
2636
+ await live.session.setModel(applyModelRuntimeOverrides(resolveModel(ref), ref))
2637
+ live.activeModelRef = ref
2638
+ },
2639
+ beforeAttempt: () => {
2640
+ applyTurnThinkingLevel(live.session, retrievalQuery, live.turnThinkingDefault, live.lastQuestionSignal)
2641
+ },
2642
+ onAttemptFailed: (attempt) => {
2643
+ logger.warn(
2644
+ `[channels] ${live.keyId}: ${attempt.outcome} failure on ${attempt.ref}: ${attempt.errorMessage ?? 'unknown'}; falling back`,
2645
+ )
2646
+ },
2647
+ })
2648
+ if (result.success) live.activeModelRef = result.refUsed
2478
2649
  await validateChannelTurn(live, successfulSendsBeforePrompt)
2479
2650
  live.consecutiveAborts = 0
2480
2651
  // Resolve the pending logical-turn signal on a binary rule: ONLY a
@@ -3441,6 +3612,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3441
3612
  live.policyDeniedToolSendsThisTurn.set(sendKey, count)
3442
3613
  if (count >= MAX_POLICY_DENIED_CHANNEL_SENDS_PER_TURN) {
3443
3614
  logger.warn(`[channels] ${live.keyId}: aborting turn — ${count} policy-denied channel sends (last: ${code})`)
3615
+ live.abortReasonThisTurn = { turnSeq: live.turnSeq, reason: `policy_denied:${code}` }
3444
3616
  if (live.session.agent.signal?.aborted !== true) live.session.agent.abort()
3445
3617
  }
3446
3618
  return { ok: false, error, code }
@@ -3489,11 +3661,15 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3489
3661
  const snapshot = Array.from(callbacks)
3490
3662
  let lastError: string | undefined
3491
3663
  let delivered = false
3664
+ let messageId: string | undefined
3665
+ let messageIds: readonly string[] | undefined
3492
3666
  try {
3493
3667
  for (const cb of snapshot) {
3494
3668
  const result = await cb(msg)
3495
3669
  if (result.ok) {
3496
3670
  delivered = true
3671
+ messageId = result.messageId
3672
+ messageIds = result.messageIds
3497
3673
  break
3498
3674
  }
3499
3675
  lastError = result.error
@@ -3574,7 +3750,11 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3574
3750
  logger[level](`[channels] ${live.keyId} send ${fields}${warn}`)
3575
3751
  }
3576
3752
 
3577
- return { ok: true }
3753
+ return {
3754
+ ok: true,
3755
+ ...(messageId !== undefined ? { messageId } : {}),
3756
+ ...(messageIds !== undefined ? { messageIds } : {}),
3757
+ }
3578
3758
  }
3579
3759
 
3580
3760
  // The turn ended via the terminal-reply abort. If that reply promised to keep
@@ -3695,9 +3875,11 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3695
3875
  // unanswered `toolUse` (the post-tool follow-up never produced an
3696
3876
  // assistant message — aborted loop / cancelled stream). The promised
3697
3877
  // work never finished, so the user is left with a bare "checking now…"
3698
- // and nothing after it. Re-prompt the same logical turn so the model
3699
- // completes its investigation and actually replies, instead of ending
3700
- // in silence. On retry-exhaustion post the fallback rather than
3878
+ // and nothing after it. Re-prompt the same logical turn with the
3879
+ // continuation nudge so the model SUMMARIZES the tool results it already
3880
+ // gathered (still in this branch) and replies, instead of re-running the
3881
+ // investigation under EMPTY_TURN_RETRY_NUDGE's "answer directly" framing
3882
+ // and stranding again. On retry-exhaustion post the fallback rather than
3701
3883
  // returning silently — a retry turn that re-sends a status and re-strands
3702
3884
  // on the same no-prose shape must not deadair the user. Any postable
3703
3885
  // pre-tool/mid-turn prose is suppressed here as before (it was narration
@@ -3706,11 +3888,18 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3706
3888
  if (leafIsStrandedToolUse(live.session) && live.currentTurnAuthorId !== null) {
3707
3889
  if (live.emptyTurnRetries < MAX_EMPTY_TURN_RETRIES) {
3708
3890
  live.emptyTurnRetries++
3891
+ const routerAbortReason =
3892
+ live.abortReasonThisTurn !== null && live.abortReasonThisTurn.turnSeq === live.turnSeq
3893
+ ? live.abortReasonThisTurn.reason
3894
+ : undefined
3895
+ const agentAbortReason =
3896
+ live.session.agent.signal?.aborted === true ? live.session.getAbortReason?.() : undefined
3897
+ const abortReason = routerAbortReason ?? agentAbortReason ?? 'unknown'
3709
3898
  logger.warn(
3710
3899
  `[channels] ${live.keyId} empty_turn_retry attempt=${live.emptyTurnRetries}/${MAX_EMPTY_TURN_RETRIES} ` +
3711
- `cause=stranded_toolUse_after_send`,
3900
+ `cause=stranded_toolUse_after_send abort_reason=${abortReason}`,
3712
3901
  )
3713
- live.pendingSystemReminders.push(EMPTY_TURN_RETRY_NUDGE)
3902
+ live.pendingSystemReminders.push(STRANDED_TOOLUSE_CONTINUATION_NUDGE)
3714
3903
  } else {
3715
3904
  await postEmptyTurnFallback('stranded_toolUse_retries_exhausted')
3716
3905
  }
@@ -3866,6 +4055,42 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3866
4055
  await postEmptyTurnFallback('cold_start_solo_bare_empty_retries_exhausted')
3867
4056
  return
3868
4057
  }
4058
+ // Deliberately AFTER the cold-start guard (that path has its own nudge). A
4059
+ // bare-empty stop that followed real tool work — but landed no send — is the
4060
+ // no-send sibling of the willingness-ack / stranded-toolUse degenerations
4061
+ // above: the model gathered results then emitted an empty completion instead
4062
+ // of the answer. Retry telling it to summarize what it already has; on
4063
+ // exhaustion post the visible fallback rather than stranding the asker on
4064
+ // silence. The cause LATCHES for the logical turn (`emptyStopAfterToolWorkArmed`):
4065
+ // the nudge tells the model not to re-run tools, so a compliant retry lands
4066
+ // another bare-empty stop with NO new tool call — requiring fresh tool work on
4067
+ // every attempt would silently drop exactly that shape with budget unspent.
4068
+ // Once armed, subsequent bare-empty stops keep spending the shared retry budget
4069
+ // toward the fallback. An explicit non-empty NO_REPLY still escapes to silence
4070
+ // (its `trim()` is non-empty, so the first condition fails and it falls through
4071
+ // to no_reply below); a bare-empty stop with no tool work AND never-armed stays
4072
+ // silent too.
4073
+ if (
4074
+ assistantText.trim() === '' &&
4075
+ source === 'leaf' &&
4076
+ (live.emptyStopAfterToolWorkArmed || attemptMadeToolCall(live.session)) &&
4077
+ live.currentTurnAuthorId !== null &&
4078
+ live.successfulChannelSends === successfulSendsBeforePrompt &&
4079
+ live.promptQueue.length === 0
4080
+ ) {
4081
+ live.emptyStopAfterToolWorkArmed = true
4082
+ if (live.emptyTurnRetries < MAX_EMPTY_TURN_RETRIES) {
4083
+ live.emptyTurnRetries++
4084
+ logger.warn(
4085
+ `[channels] ${live.keyId} empty_turn_retry attempt=${live.emptyTurnRetries}/${MAX_EMPTY_TURN_RETRIES} ` +
4086
+ `cause=empty_stop_after_tool_work`,
4087
+ )
4088
+ live.pendingSystemReminders.push(EMPTY_STOP_AFTER_TOOL_WORK_NUDGE)
4089
+ return
4090
+ }
4091
+ await postEmptyTurnFallback('empty_stop_after_tool_work_retries_exhausted')
4092
+ return
4093
+ }
3869
4094
  const leakedReasoning = !isNoReplySignal(assistantText)
3870
4095
  logger.info(`[channels] ${live.keyId} no_reply${leakedReasoning ? ' (with_leaked_reasoning)' : ''}`)
3871
4096
  return
@@ -4113,6 +4338,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4113
4338
  // waking the drain loop.
4114
4339
  if (live.pendingSystemReminders.length > 0) continue
4115
4340
  if (t - live.lastInboundAt <= SESSION_IDLE_MS) continue
4341
+ if (isPinnedByRunningChild(live.sessionId, live.keyId, 'idle_gc evicting')) continue
4116
4342
  victims.push(live)
4117
4343
  }
4118
4344
  for (const live of victims) {
@@ -4428,6 +4654,30 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4428
4654
  return { kind: 'no-live-session' }
4429
4655
  }
4430
4656
 
4657
+ const injectPrVerdictActivity = (args: {
4658
+ workspace: string
4659
+ prNumber: number
4660
+ verdict: 'APPROVE' | 'REQUEST_CHANGES'
4661
+ sessionId: string
4662
+ }): { kind: 'delivered'; count: number } => {
4663
+ const chat = `pr:${args.prNumber}`
4664
+ let count = 0
4665
+ for (const live of liveSessions.values()) {
4666
+ if (live.destroyed) continue
4667
+ if (live.key.adapter !== 'github') continue
4668
+ if (live.key.workspace !== args.workspace || live.key.chat !== chat) continue
4669
+ // Self-exclude: the session that just landed the verdict must not be told to
4670
+ // stand down from its own legitimate review.
4671
+ if (live.sessionId === args.sessionId) continue
4672
+ const text = renderPrVerdictStandDownReminder({ prNumber: args.prNumber, verdict: args.verdict })
4673
+ live.pendingSystemReminders.push(text)
4674
+ logger.info(`[channels] ${live.keyId}: pr-verdict stand-down queued pr=${chat} verdict=${args.verdict}`)
4675
+ if (!live.draining) void drain(live)
4676
+ count++
4677
+ }
4678
+ return { kind: 'delivered', count }
4679
+ }
4680
+
4431
4681
  const markTurnSkipped = (args: {
4432
4682
  parentSessionId: string
4433
4683
  reason: string
@@ -4535,6 +4785,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4535
4785
  executeCommand,
4536
4786
  getSelfAliases: computeSelfAliases,
4537
4787
  injectSubagentCompletionReminder,
4788
+ injectPrVerdictActivity,
4538
4789
  markTurnSkipped,
4539
4790
  clearSticky,
4540
4791
  reserveRestartHandoff,
@@ -4552,6 +4803,11 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4552
4803
  }
4553
4804
  live.firstUnprocessedAt = 0
4554
4805
  await drain(live)
4806
+ // Settle the fire-and-forget `void persist()` from scheduleDebouncedDrain
4807
+ // (the lastInboundAt write). Draining alone doesn't await that promise, so
4808
+ // a test reading sessions.json right after would race the disk write — the
4809
+ // flake that forced wall-clock polling on slow (Windows CI) filesystems.
4810
+ await persistChain
4555
4811
  },
4556
4812
  fireTypingHeartbeat: async (key: ChannelKey, phase: 'tick' | 'stop' = 'tick') => {
4557
4813
  const live = liveSessions.get(channelKeyId(key))
@@ -4865,7 +5121,9 @@ export type { QuoteAnchorSource } from './types'
4865
5121
  function formatAuthorReference(adapter: AdapterId, authorId: string, authorName: string): string {
4866
5122
  const displayName = authorName.trim() !== '' ? authorName.trim() : authorId
4867
5123
  switch (adapter) {
5124
+ case 'slack':
4868
5125
  case 'slack-bot':
5126
+ case 'discord':
4869
5127
  case 'discord-bot':
4870
5128
  return `<@${authorId}>`
4871
5129
  case 'github':
@@ -5419,6 +5677,30 @@ function hasToolCall(message: AssistantMessage): boolean {
5419
5677
  return message.content.some((block) => block.type === 'toolCall')
5420
5678
  }
5421
5679
 
5680
+ // True when any assistant message in the CURRENT prompt-attempt carries a
5681
+ // toolCall block. "This attempt" is bounded by walking the parentId chain back
5682
+ // to the first user message — which INCLUDES an injected retry nudge, since
5683
+ // that lands as a user-side entry — so each retry is scored on its own tool
5684
+ // work, not the original turn's. validateChannelTurn uses this to tell a
5685
+ // bare-empty `stop` that followed real tool work (Fireworks/gpt empty-completion
5686
+ // degeneration → retry) apart from a bare-empty `stop` that produced nothing
5687
+ // from nothing (deliberate silence → honor it). The `source === 'leaf'` +
5688
+ // `stopReason: 'stop'` invariant at the call site guarantees any tool called
5689
+ // this attempt already returned a toolResult; otherwise the leaf would be
5690
+ // `toolUse`, not `stop`. Depth-bounded like the other branch walks so a
5691
+ // malformed session can't loop.
5692
+ function attemptMadeToolCall(session: AgentSession): boolean {
5693
+ let cursor: SessionEntry | undefined = session.sessionManager.getLeafEntry()
5694
+ for (let depth = 0; depth < 32 && cursor; depth++) {
5695
+ if (cursor.type === 'message') {
5696
+ if (cursor.message.role === 'user') return false
5697
+ if (cursor.message.role === 'assistant' && hasToolCall(cursor.message)) return true
5698
+ }
5699
+ cursor = cursor.parentId ? session.sessionManager.getEntry(cursor.parentId) : undefined
5700
+ }
5701
+ return false
5702
+ }
5703
+
5422
5704
  // Lenient on purpose: distilled / smaller models routinely drift off the
5423
5705
  // documented `NO_REPLY` form. We additionally accept `(NO_REPLY)` (Claude-style
5424
5706
  // hedging) and empty visible text (e.g. Kimi-distilled models that emit only a
@@ -1,10 +1,12 @@
1
1
  import { z } from 'zod'
2
2
 
3
3
  export const ADAPTER_IDS = [
4
+ 'discord',
4
5
  'discord-bot',
5
6
  'github',
6
7
  'line',
7
8
  'kakaotalk',
9
+ 'slack',
8
10
  'slack-bot',
9
11
  'telegram-bot',
10
12
  'webex',
@@ -261,6 +263,7 @@ const githubChannelSchema = adapterSchema.extend({
261
263
  // kakaotalk adapter only on dedicated agent accounts you can afford to lose.
262
264
  export const channelsSchema = z
263
265
  .object({
266
+ discord: adapterSchema.optional(),
264
267
  'discord-bot': adapterSchema.optional(),
265
268
  github: githubChannelSchema.optional(),
266
269
  // LINE is a personal-account channel like KakaoTalk: plain-text only,
@@ -269,6 +272,7 @@ export const channelsSchema = z
269
272
  // token-renewal cron — it persists a long-lived auth token + certificate.
270
273
  line: adapterSchema.optional(),
271
274
  kakaotalk: adapterSchema.optional(),
275
+ slack: adapterSchema.optional(),
272
276
  'slack-bot': adapterSchema.optional(),
273
277
  'telegram-bot': adapterSchema.optional(),
274
278
  webex: adapterSchema.optional(),
@@ -242,7 +242,23 @@ export type SendErrorCode =
242
242
  | 'callback-rejected'
243
243
  | 'skip-locked'
244
244
 
245
- export type SendResult = { ok: true } | { ok: false; error: string; code?: SendErrorCode }
245
+ // `messageId` is the platform-native id of the posted message (Slack `ts`,
246
+ // Discord snowflake, Telegram `message_id`, Webex/GitHub comment id, KakaoTalk
247
+ // `log_id`, LINE `message_id`). It is the SAME id shape an inbound carries as
248
+ // `externalMessageId`, so an agent can feed it straight back into a follow-up
249
+ // `thread` / `replyTo` to keep posting into one conversation. For a send the
250
+ // adapter splits into multiple posts (long text chunked, or attachments +
251
+ // text), `messageId` is the post a reply should anchor to — usually the FIRST
252
+ // post, but adapter-specific: KakaoTalk uploads files BEFORE the text, so the
253
+ // text post (the message a human replies to) is the anchor even though it is
254
+ // last. `messageIds` always lists every post in send order, so a caller that
255
+ // needs a specific post (rather than the reply anchor) can index it directly.
256
+ // Optional throughout: an adapter whose SDK does not hand back an id (legacy
257
+ // slack/discord user-account adapters) omits both, and callers must treat a
258
+ // missing id as "not available", never as an error.
259
+ export type SendResult =
260
+ | { ok: true; messageId?: string; messageIds?: readonly string[] }
261
+ | { ok: false; error: string; code?: SendErrorCode }
246
262
 
247
263
  export type OutboundCallback = (msg: OutboundMessage) => Promise<SendResult>
248
264
 
@@ -323,11 +339,18 @@ export type FetchHistoryArgs = {
323
339
  thread: string | null
324
340
  limit: number
325
341
  cursor?: string
342
+ // Set by best-effort callers (cold-start prefetch, membership fallback) to opt
343
+ // into adapter-side rate-limit backpressure. Explicit reads (channel_history)
344
+ // leave it unset so they always attempt the fetch under the router's timeout.
345
+ prefetch?: boolean
326
346
  }
327
347
 
328
348
  export type FetchHistoryResult =
329
349
  | { ok: true; messages: ChannelHistoryMessage[]; nextCursor?: string }
330
- | { ok: false; error: string }
350
+ // `skipReason: 'rate-limited'` marks an expected, optional-context skip (the
351
+ // adapter declined a best-effort read to avoid hammering a rate-limited
352
+ // resource) so callers can log it at info instead of warn.
353
+ | { ok: false; error: string; skipReason?: 'rate-limited' }
331
354
 
332
355
  // Registered per-adapter on the ChannelRouter alongside outbound/typing
333
356
  // callbacks. Adapters that cannot fetch history (e.g. webhook-only future