typeclaw 0.39.1 → 0.39.3

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 (79) 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 +44 -19
  5. package/src/agent/plugin-tools.ts +12 -12
  6. package/src/agent/session-origin.ts +2 -0
  7. package/src/agent/todo/store.ts +21 -1
  8. package/src/agent/tools/channel-reply.ts +18 -5
  9. package/src/agent/tools/channel-send.ts +13 -2
  10. package/src/bundled-plugins/doc-render/render.ts +2 -2
  11. package/src/bundled-plugins/github-cli-auth/approve-idempotency.ts +40 -18
  12. package/src/channels/adapters/discord-author-resolver.ts +52 -0
  13. package/src/channels/adapters/discord-bot.ts +1 -1
  14. package/src/channels/adapters/discord-channel-resolver.ts +44 -0
  15. package/src/channels/adapters/discord-classify.ts +121 -0
  16. package/src/channels/adapters/discord-reactions.ts +138 -0
  17. package/src/channels/adapters/discord.ts +416 -0
  18. package/src/channels/adapters/github/outbound.ts +23 -4
  19. package/src/channels/adapters/kakaotalk.ts +8 -1
  20. package/src/channels/adapters/line.ts +1 -1
  21. package/src/channels/adapters/slack-author-resolver.ts +54 -0
  22. package/src/channels/adapters/slack-bot.ts +3 -1
  23. package/src/channels/adapters/slack-channel-resolver.ts +49 -0
  24. package/src/channels/adapters/slack-classify.ts +83 -0
  25. package/src/channels/adapters/slack-reactions.ts +126 -0
  26. package/src/channels/adapters/slack.ts +416 -0
  27. package/src/channels/adapters/telegram-bot.ts +2 -1
  28. package/src/channels/adapters/webex-bot.ts +5 -2
  29. package/src/channels/adapters/webex.ts +55 -2
  30. package/src/channels/github-review-turn-ledger.ts +32 -0
  31. package/src/channels/github-verdict-activity.ts +60 -0
  32. package/src/channels/index.ts +6 -0
  33. package/src/channels/manager.ts +130 -6
  34. package/src/channels/pr-verdict-activity-bridge.ts +43 -0
  35. package/src/channels/router.ts +218 -20
  36. package/src/channels/schema.ts +4 -0
  37. package/src/channels/types.ts +17 -1
  38. package/src/cli/builtins.ts +1 -0
  39. package/src/cli/channel.ts +170 -18
  40. package/src/cli/index.ts +11 -0
  41. package/src/cli/init.ts +2 -0
  42. package/src/cli/update-check.ts +14 -0
  43. package/src/cli/update-notify.ts +91 -0
  44. package/src/cli/update-suppression.ts +19 -0
  45. package/src/compose/logs.ts +20 -6
  46. package/src/config/channels-mutation.ts +3 -1
  47. package/src/config/config.ts +51 -0
  48. package/src/config/index.ts +1 -0
  49. package/src/container/logs.ts +19 -4
  50. package/src/container/shared.ts +108 -5
  51. package/src/container/start.ts +218 -33
  52. package/src/doctor/channel-checks.ts +57 -3
  53. package/src/hostd/daemon.ts +22 -5
  54. package/src/hostd/index.ts +11 -1
  55. package/src/hostd/paths.ts +4 -0
  56. package/src/hostd/protocol.ts +15 -2
  57. package/src/init/auto-upgrade.ts +38 -4
  58. package/src/init/cli-version.ts +31 -2
  59. package/src/init/discord-auth.ts +50 -0
  60. package/src/init/dockerfile.ts +18 -5
  61. package/src/init/index.ts +140 -42
  62. package/src/init/reconcile-plugin-deps.ts +30 -5
  63. package/src/init/run-owner-claim.ts +2 -0
  64. package/src/init/slack-auth.ts +51 -0
  65. package/src/init/windows-dev-link.ts +64 -0
  66. package/src/mcp/manager.ts +94 -7
  67. package/src/mcp/tools.ts +7 -4
  68. package/src/permissions/resolve.ts +2 -0
  69. package/src/role-claim/match-rule.ts +2 -0
  70. package/src/run/index.ts +74 -29
  71. package/src/secrets/discord-store.ts +96 -0
  72. package/src/secrets/schema.ts +34 -0
  73. package/src/secrets/slack-store.ts +96 -0
  74. package/src/server/command-runner.ts +21 -0
  75. package/src/skills/typeclaw-cron/SKILL.md +13 -2
  76. package/src/tui/format.ts +0 -19
  77. package/src/tui/index.ts +2 -8
  78. package/src/update/check.ts +192 -0
  79. package/typeclaw.schema.json +332 -0
@@ -39,6 +39,7 @@ import {
39
39
  import { checkFalseReceipt } from './github-false-receipt'
40
40
  import { evaluateRereviewGuard } from './github-rereview-guard'
41
41
  import { resetReviewTurn } from './github-review-turn-ledger'
42
+ import { renderPrVerdictStandDownReminder } from './github-verdict-activity'
42
43
  import {
43
44
  MEMBERSHIP_COLD_FETCH_TIMEOUT_MS,
44
45
  type MembershipCount,
@@ -261,6 +262,31 @@ export const EMPTY_TURN_RETRY_NUDGE = [
261
262
  '',
262
263
  '---',
263
264
  ].join('\n')
265
+ // Reminder-only nudge for the stranded-toolUse-after-send retry. Distinct from
266
+ // EMPTY_TURN_RETRY_NUDGE: that one diagnoses output-budget exhaustion and tells
267
+ // the model to "answer directly", which makes a stranded investigation RE-RUN
268
+ // its tools and strand again. Here the model already sent a `continue: true`
269
+ // status ack and did real tool work; the turn just ended on an unanswered
270
+ // toolUse before final prose. The prior toolUse/toolResult entries are still in
271
+ // this session's branch on the re-prompt, so the recovery is to STOP, read what
272
+ // it already gathered, and reply — not to start the investigation over.
273
+ export const STRANDED_TOOLUSE_CONTINUATION_NUDGE = [
274
+ '---',
275
+ '**[SYSTEM MESSAGE — not from a human]**',
276
+ '',
277
+ 'Your previous turn sent a brief status reply, did some tool work, then ended',
278
+ 'before sending the answer it promised. This is an automated signal from the',
279
+ 'channel router, not a message from anyone in the chat. **Do not acknowledge or',
280
+ 'reply to this notice itself.**',
281
+ '',
282
+ 'Do NOT start the investigation over. The tool results you already gathered are',
283
+ 'still in this conversation above — read them, summarize what you found, and',
284
+ 'send your reply now via your channel reply tool. Only call more tools if a',
285
+ 'specific fact is genuinely still missing. If you truly have nothing to say,',
286
+ 'reply with `NO_REPLY`.',
287
+ '',
288
+ '---',
289
+ ].join('\n')
264
290
  // Posted to the channel (via the `source:'system'` one-shot bypass) when an
265
291
  // empty turn cannot be recovered AND retries are exhausted (or are skipped
266
292
  // because the turn thrashed the send path). Replaces the historical silent
@@ -380,6 +406,23 @@ export const SESSION_FRESHNESS_TTL_MS = 5 * 60 * 1000
380
406
  */
381
407
  export const SESSION_GRACE_HARD_TTL_MS = 10 * 60 * 1000
382
408
 
409
+ /**
410
+ * Absolute ceiling on how long a running background subagent may pin its parent
411
+ * channel session against idle GC and stale-rollover. A still-running child defers
412
+ * teardown because the next inbound otherwise starts a fresh session that has lost
413
+ * track of the in-flight task and spawns a DUPLICATE child for the same work. The
414
+ * pin is bounded so a stuck/never-completing child cannot make the session
415
+ * immortal: past this age the session is GC'd / rolled over anyway, falling back
416
+ * to the completion-reroute behavior. Measured from the child's start.
417
+ *
418
+ * Set above SESSION_IDLE_MS (30m) — not equal — so a child spawned at session
419
+ * birth still pins the session through its first idle sweep instead of the two
420
+ * windows coinciding. Comfortably above SESSION_GRACE_HARD_TTL_MS (10m) too:
421
+ * real research runs can exceed it (an observed run took 9m18s), so the 10m cap
422
+ * is far too tight to bound the pin.
423
+ */
424
+ export const SESSION_CHILD_PIN_MAX_MS = 45 * 60 * 1000
425
+
383
426
  /**
384
427
  * Cost-aware grace decision for the soft→hard TTL band. Returns true when reusing
385
428
  * the (now cache-cold) live session is cheaper than a fresh cold-start.
@@ -512,7 +555,7 @@ export type CreateSessionForChannel = (params: {
512
555
  // `options.originRef`.
513
556
  originRef: { current: SessionOrigin | undefined }
514
557
  }) => Promise<{
515
- session: AgentSession
558
+ session: ChannelAgentSession
516
559
  sessionId: string
517
560
  dispose: () => Promise<void>
518
561
  hooks?: HookBus
@@ -570,10 +613,12 @@ type ObservedInbound = {
570
613
 
571
614
  type TimedAttachment = { ts: number; attachment: InboundAttachment }
572
615
 
616
+ type ChannelAgentSession = AgentSession & { getAbortReason?: () => string | undefined }
617
+
573
618
  type LiveSession = {
574
619
  key: ChannelKey
575
620
  keyId: string
576
- session: AgentSession
621
+ session: ChannelAgentSession
577
622
  // The session's creation-time thinking level, captured once. A later escalated
578
623
  // turn moves `session.thinkingLevel` to `high`, so the live getter can't be the
579
624
  // reset target — this preserves the real default across the session's lifetime.
@@ -758,6 +803,10 @@ type LiveSession = {
758
803
  // turn can never trigger a nudge on a later one. `null` when no such reply
759
804
  // ended this turn.
760
805
  lastTerminalReplyAbort: { turnSeq: number; text: string } | null
806
+ // Stamped by router abort sites and read by `validateChannelTurn` for
807
+ // reason-specific stranded-toolUse recovery logs. `turnSeq`-stamped so stale
808
+ // abort provenance from an earlier turn can never leak into a later retry.
809
+ abortReasonThisTurn: { turnSeq: number; reason: string } | null
761
810
  // One-shot output-token budget for the NEXT `session.prompt()` only.
762
811
  // `installChannelOutputCap` reads and clears it per stream call, so it
763
812
  // overrides the default backstop for exactly one re-prompt. Set by the
@@ -1019,6 +1068,19 @@ export type ChannelRouter = {
1019
1068
  error?: string
1020
1069
  channelKey?: { adapter: string; workspace: string; chat: string; thread: string | null }
1021
1070
  }) => { kind: 'delivered'; keyId: string } | { kind: 'no-live-session' }
1071
+ // Fan a LANDED formal review verdict out to the OTHER live sessions reviewing
1072
+ // the same PR so they stand down from posting a redundant verdict. Targets every
1073
+ // live github session whose chat is `pr:<prNumber>` in `workspace`, EXCLUDING the
1074
+ // publisher (`sessionId`). Routes by (workspace, prNumber) across all threads —
1075
+ // the duplicate-review fan-out is exactly the per-thread sibling sessions. The
1076
+ // injected reminder is advisory (verdict-only stand-down); the hard idempotency
1077
+ // guards remain the correctness boundary. Returns how many siblings were nudged.
1078
+ injectPrVerdictActivity: (args: {
1079
+ workspace: string
1080
+ prNumber: number
1081
+ verdict: 'APPROVE' | 'REQUEST_CHANGES'
1082
+ sessionId: string
1083
+ }) => { kind: 'delivered'; count: number }
1022
1084
  // Record that the agent invoked `skip_response` during the current turn
1023
1085
  // for the channel session identified by `parentSessionId`. The reason is
1024
1086
  // logged at INFO level inside `validateChannelTurn` (single log line per
@@ -1179,6 +1241,20 @@ export type CreateChannelRouterOptions = {
1179
1241
  // resumes on the next boot; when absent (cold channel / native slash with no
1180
1242
  // session) it should just bounce the container with no handoff.
1181
1243
  onRestart?: (ctx?: RestartCommandContext) => Promise<string>
1244
+ // Test seam: override the sessions.json writer. Defaults to the disk-backed
1245
+ // saveChannelSessions (which swallows its own I/O errors). Tests inject a
1246
+ // throwing impl to exercise the persist-failure unwind in ensureLive.
1247
+ saveChannelSessions?: (agentDir: string, sessions: readonly ChannelSessionRecord[]) => Promise<void>
1248
+ // Returns the start time (epoch ms) of the NEWEST still-running background
1249
+ // subagent spawned from `sessionId`, or null when none is running. Lets idle
1250
+ // GC and stale-rollover pin a session whose child is still working (the next
1251
+ // inbound would otherwise spawn a duplicate child), bounded by
1252
+ // SESSION_CHILD_PIN_MAX_MS measured from that start. Newest — not oldest — so a
1253
+ // long-running child that crossed the cap cannot unpin the session while a more
1254
+ // recently spawned child is still inside its own protection window. Production
1255
+ // wiring forwards the LiveSubagentRegistry; omitted (tests, no-subagent setups)
1256
+ // means no pin.
1257
+ newestRunningChildSubagentStartedAt?: (sessionId: string) => number | null
1182
1258
  }
1183
1259
 
1184
1260
  export type RestartCommandContext = {
@@ -1235,6 +1311,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1235
1311
  const stream = options.stream
1236
1312
  const onReload = options.onReload
1237
1313
  const onRestart = options.onRestart
1314
+ const newestRunningChildSubagentStartedAt = options.newestRunningChildSubagentStartedAt ?? (() => null)
1238
1315
  const liveSessions = new Map<string, LiveSession>()
1239
1316
  const creating = new Map<string, Promise<LiveSession>>()
1240
1317
  // Restart-resume reservations, keyed by channelKeyId. Installed by
@@ -1356,13 +1433,18 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1356
1433
  await loadOnce
1357
1434
  }
1358
1435
 
1436
+ const saveSessions = options.saveChannelSessions
1437
+ ? options.saveChannelSessions
1438
+ : (agentDir: string, sessions: readonly ChannelSessionRecord[]): Promise<void> =>
1439
+ saveChannelSessions(agentDir, sessions, logger)
1440
+
1359
1441
  const persist = async (): Promise<void> => {
1360
1442
  if (mappings === null || closing) return
1361
1443
  // Caller awaits `next` un-caught to observe write errors; the chain holds the
1362
1444
  // caught version so one rejection can't poison it or escape as unhandled.
1363
1445
  const next = persistChain.then(async () => {
1364
1446
  if (mappings === null) return
1365
- await saveChannelSessions(options.agentDir, mappings, logger)
1447
+ await saveSessions(options.agentDir, mappings)
1366
1448
  })
1367
1449
  persistChain = next.catch(() => {})
1368
1450
  await next
@@ -1474,11 +1556,30 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1474
1556
  return membership
1475
1557
  }
1476
1558
 
1559
+ // True while a background child spawned from this session is still running AND
1560
+ // the newest such child is within SESSION_CHILD_PIN_MAX_MS of its start. Using
1561
+ // the newest child keeps the session pinned as long as ANY running child is
1562
+ // still inside its protection window — an older child that already crossed the
1563
+ // cap must not unpin the session out from under a freshly spawned one. Tearing
1564
+ // the session down mid-child lets the next inbound spawn a duplicate child, so
1565
+ // GC/rollover defer to this. `label` only annotates the override log.
1566
+ const isPinnedByRunningChild = (sessionId: string, keyId: string, label: string): boolean => {
1567
+ const childStartedAt = newestRunningChildSubagentStartedAt(sessionId)
1568
+ if (childStartedAt === null) return false
1569
+ const pinnedForMs = now() - childStartedAt
1570
+ if (pinnedForMs <= SESSION_CHILD_PIN_MAX_MS) return true
1571
+ logger.info(
1572
+ `[channels] ${keyId}: ${label} despite running child (newest pinned ${pinnedForMs}ms, past child-pin cap)`,
1573
+ )
1574
+ return false
1575
+ }
1576
+
1477
1577
  const shouldRolloverLive = (live: LiveSession, idleMs: number): boolean => {
1478
1578
  // A session mid-prompt looks idle by lastInboundAt (only bumped on engaged
1479
1579
  // inbounds) while session.prompt() is still in flight; rolling it over aborts
1480
1580
  // that work. The runIdleGc path skips draining sessions for the same reason.
1481
1581
  if (live.draining) return false
1582
+ if (isPinnedByRunningChild(live.sessionId, live.keyId, 'stale-rollover')) return false
1482
1583
  if (idleMs <= SESSION_FRESHNESS_TTL_MS) return false
1483
1584
  if (idleMs > SESSION_GRACE_HARD_TTL_MS) {
1484
1585
  logger.info(`[channels] ${live.keyId}: stale-rollover (live: ${idleMs}ms idle, past grace cap)`)
@@ -1563,7 +1664,13 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1563
1664
  resumeTarget === undefined &&
1564
1665
  record?.sessionId !== undefined &&
1565
1666
  existing === undefined &&
1566
- now() - (record.lastInboundAt ?? 0) > SESSION_FRESHNESS_TTL_MS
1667
+ now() - (record.lastInboundAt ?? 0) > SESSION_FRESHNESS_TTL_MS &&
1668
+ // The live session is already gone here, but a background child it spawned
1669
+ // may still be running under its (old) sessionId. Wiping the mapping would
1670
+ // start a fresh session that re-spawns the same child. Keep the mapping so
1671
+ // the reopen continues the same sessionId until the child finishes (or the
1672
+ // pin cap elapses).
1673
+ !isPinnedByRunningChild(record.sessionId, keyId, 'stale-rollover (persisted)')
1567
1674
  ) {
1568
1675
  const idleMs = now() - (record.lastInboundAt ?? 0)
1569
1676
  logger.info(`[channels] ${keyId}: stale-rollover (persisted: ${idleMs}ms idle)`)
@@ -1608,10 +1715,12 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1608
1715
  logger.info(`[channels] ${keyId}: ensureLive begin (${phase})`)
1609
1716
  const participants = (resolvedRecord?.participants ?? []) as ChannelParticipant[]
1610
1717
  const membershipFetch = warmMembership(key)
1611
- const resolvedNames = await resolveChannelNames(key)
1612
- logger.info(`[channels] ${keyId}: ensureLive resolved-names`)
1613
- const membership = await membershipForPrompt(key, membershipFetch)
1614
- logger.info(`[channels] ${keyId}: ensureLive resolved-membership`)
1718
+ // Independent platform lookups — overlap so the chain pays max(), not sum().
1719
+ const [resolvedNames, membership] = await Promise.all([
1720
+ resolveChannelNames(key),
1721
+ membershipForPrompt(key, membershipFetch),
1722
+ ])
1723
+ logger.info(`[channels] ${keyId}: ensureLive resolved-names-and-membership`)
1615
1724
  // The session-creation origin is what the resource loader sees when it
1616
1725
  // renders the role/permissions block into the system prompt. It must
1617
1726
  // include the triggering author so author-scoped roles
@@ -1674,7 +1783,13 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1674
1783
  } else {
1675
1784
  mappings = [persistedRecord]
1676
1785
  }
1677
- await persist()
1786
+ // Kick off the mapping write now but don't block on it — the disk write is
1787
+ // independent of the synchronous `live` build below and the cold-start
1788
+ // network prefetch, so we overlap it. Every exit path below MUST settle
1789
+ // `persistPromise` (the immediate .catch is only an unhandled-rejection
1790
+ // guard; write errors are still surfaced by awaiting it later).
1791
+ const persistPromise = persist()
1792
+ void persistPromise.catch(() => {})
1678
1793
 
1679
1794
  const live: LiveSession = {
1680
1795
  key,
@@ -1736,6 +1851,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1736
1851
  emptyTurnRetries: 0,
1737
1852
  willingnessNudges: 0,
1738
1853
  lastTerminalReplyAbort: null,
1854
+ abortReasonThisTurn: null,
1739
1855
  nextPromptMaxTokens: undefined,
1740
1856
  skippedTurn: null,
1741
1857
  skipLockedSendTurn: null,
@@ -1791,16 +1907,38 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1791
1907
  `[channels] ${keyId}: discarding session created across a teardown (gen ${generation} → ${liveGeneration})`,
1792
1908
  )
1793
1909
  await tearDownLive(live)
1910
+ // Settle the in-flight mapping write before bailing — preserves the
1911
+ // pre-overlap contract that a persist failure fails ensureLive.
1912
+ await persistPromise
1794
1913
  throw new StaleLiveSessionError(keyId)
1795
1914
  }
1796
- liveSessions.set(keyId, live)
1797
-
1798
1915
  if (isColdStart) {
1916
+ // Install before the slow prefetch so a concurrent teardown/shutdown can
1917
+ // see and dispose this session during the network fetch.
1918
+ liveSessions.set(keyId, live)
1799
1919
  const adapterConfig = options.configForAdapter(key.adapter)
1800
- if (adapterConfig) {
1801
- await prefetchChannelContext(live, adapterConfig, triggeringMessageId)
1802
- logger.info(`[channels] ${keyId}: ensureLive prefetched-context`)
1920
+ // Overlap the disk mapping-write with the network history prefetch —
1921
+ // they are independent. allSettled lets a persist failure take priority
1922
+ // (and unwind the install) even if prefetch also rejects.
1923
+ const prefetchPromise = adapterConfig
1924
+ ? prefetchChannelContext(live, adapterConfig, triggeringMessageId)
1925
+ : Promise.resolve()
1926
+ const [persistResult, prefetchResult] = await Promise.allSettled([persistPromise, prefetchPromise])
1927
+ if (persistResult.status === 'rejected') {
1928
+ await unwindInstalledLive(keyId, live)
1929
+ throw persistResult.reason
1930
+ }
1931
+ if (prefetchResult.status === 'rejected') {
1932
+ await unwindInstalledLive(keyId, live)
1933
+ throw prefetchResult.reason
1803
1934
  }
1935
+ if (adapterConfig) logger.info(`[channels] ${keyId}: ensureLive prefetched-context`)
1936
+ } else {
1937
+ // Rehydrate has no prefetch to overlap, so settle the mapping write
1938
+ // before installing — a failed persist must fail ensureLive without
1939
+ // leaving a warm session behind for later inbounds to reuse.
1940
+ await persistPromise
1941
+ liveSessions.set(keyId, live)
1804
1942
  }
1805
1943
 
1806
1944
  // Snapshot the rendered base context size now, after prefetch and before
@@ -2065,6 +2203,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2065
2203
  logger.info(`[channels] ${live.keyId} terminal_after_channel_reply`)
2066
2204
  const replyText = (context.toolCall.arguments as { text?: unknown } | undefined)?.text
2067
2205
  live.lastTerminalReplyAbort = typeof replyText === 'string' ? { turnSeq: live.turnSeq, text: replyText } : null
2206
+ live.abortReasonThisTurn = { turnSeq: live.turnSeq, reason: 'terminal_after_channel_reply' }
2068
2207
  agent.abort()
2069
2208
  }
2070
2209
  return result
@@ -2366,6 +2505,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2366
2505
  // forever (and the raised cap stays scoped to the turn that set it).
2367
2506
  live.emptyTurnRetries = 0
2368
2507
  live.willingnessNudges = 0
2508
+ live.abortReasonThisTurn = null
2369
2509
  live.nextPromptMaxTokens = undefined
2370
2510
  } else if (live.lastTurnAuthorId !== null) {
2371
2511
  live.currentTurnEngageReactions = []
@@ -3402,6 +3542,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3402
3542
  live.policyDeniedToolSendsThisTurn.set(sendKey, count)
3403
3543
  if (count >= MAX_POLICY_DENIED_CHANNEL_SENDS_PER_TURN) {
3404
3544
  logger.warn(`[channels] ${live.keyId}: aborting turn — ${count} policy-denied channel sends (last: ${code})`)
3545
+ live.abortReasonThisTurn = { turnSeq: live.turnSeq, reason: `policy_denied:${code}` }
3405
3546
  if (live.session.agent.signal?.aborted !== true) live.session.agent.abort()
3406
3547
  }
3407
3548
  return { ok: false, error, code }
@@ -3450,11 +3591,15 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3450
3591
  const snapshot = Array.from(callbacks)
3451
3592
  let lastError: string | undefined
3452
3593
  let delivered = false
3594
+ let messageId: string | undefined
3595
+ let messageIds: readonly string[] | undefined
3453
3596
  try {
3454
3597
  for (const cb of snapshot) {
3455
3598
  const result = await cb(msg)
3456
3599
  if (result.ok) {
3457
3600
  delivered = true
3601
+ messageId = result.messageId
3602
+ messageIds = result.messageIds
3458
3603
  break
3459
3604
  }
3460
3605
  lastError = result.error
@@ -3535,7 +3680,11 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3535
3680
  logger[level](`[channels] ${live.keyId} send ${fields}${warn}`)
3536
3681
  }
3537
3682
 
3538
- return { ok: true }
3683
+ return {
3684
+ ok: true,
3685
+ ...(messageId !== undefined ? { messageId } : {}),
3686
+ ...(messageIds !== undefined ? { messageIds } : {}),
3687
+ }
3539
3688
  }
3540
3689
 
3541
3690
  // The turn ended via the terminal-reply abort. If that reply promised to keep
@@ -3656,9 +3805,11 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3656
3805
  // unanswered `toolUse` (the post-tool follow-up never produced an
3657
3806
  // assistant message — aborted loop / cancelled stream). The promised
3658
3807
  // work never finished, so the user is left with a bare "checking now…"
3659
- // and nothing after it. Re-prompt the same logical turn so the model
3660
- // completes its investigation and actually replies, instead of ending
3661
- // in silence. On retry-exhaustion post the fallback rather than
3808
+ // and nothing after it. Re-prompt the same logical turn with the
3809
+ // continuation nudge so the model SUMMARIZES the tool results it already
3810
+ // gathered (still in this branch) and replies, instead of re-running the
3811
+ // investigation under EMPTY_TURN_RETRY_NUDGE's "answer directly" framing
3812
+ // and stranding again. On retry-exhaustion post the fallback rather than
3662
3813
  // returning silently — a retry turn that re-sends a status and re-strands
3663
3814
  // on the same no-prose shape must not deadair the user. Any postable
3664
3815
  // pre-tool/mid-turn prose is suppressed here as before (it was narration
@@ -3667,11 +3818,18 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3667
3818
  if (leafIsStrandedToolUse(live.session) && live.currentTurnAuthorId !== null) {
3668
3819
  if (live.emptyTurnRetries < MAX_EMPTY_TURN_RETRIES) {
3669
3820
  live.emptyTurnRetries++
3821
+ const routerAbortReason =
3822
+ live.abortReasonThisTurn !== null && live.abortReasonThisTurn.turnSeq === live.turnSeq
3823
+ ? live.abortReasonThisTurn.reason
3824
+ : undefined
3825
+ const agentAbortReason =
3826
+ live.session.agent.signal?.aborted === true ? live.session.getAbortReason?.() : undefined
3827
+ const abortReason = routerAbortReason ?? agentAbortReason ?? 'unknown'
3670
3828
  logger.warn(
3671
3829
  `[channels] ${live.keyId} empty_turn_retry attempt=${live.emptyTurnRetries}/${MAX_EMPTY_TURN_RETRIES} ` +
3672
- `cause=stranded_toolUse_after_send`,
3830
+ `cause=stranded_toolUse_after_send abort_reason=${abortReason}`,
3673
3831
  )
3674
- live.pendingSystemReminders.push(EMPTY_TURN_RETRY_NUDGE)
3832
+ live.pendingSystemReminders.push(STRANDED_TOOLUSE_CONTINUATION_NUDGE)
3675
3833
  } else {
3676
3834
  await postEmptyTurnFallback('stranded_toolUse_retries_exhausted')
3677
3835
  }
@@ -4051,6 +4209,13 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4051
4209
  }
4052
4210
  }
4053
4211
 
4212
+ // Roll back an install when a post-install step (persist/prefetch) fails, so a
4213
+ // rejected ensureLive never leaves a warm session behind for later inbounds.
4214
+ const unwindInstalledLive = async (keyId: string, live: LiveSession): Promise<void> => {
4215
+ if (liveSessions.get(keyId) === live) liveSessions.delete(keyId)
4216
+ if (!live.destroyed) await tearDownLive(live)
4217
+ }
4218
+
4054
4219
  const runIdleGc = async (): Promise<void> => {
4055
4220
  const t = now()
4056
4221
  const victims: LiveSession[] = []
@@ -4067,6 +4232,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4067
4232
  // waking the drain loop.
4068
4233
  if (live.pendingSystemReminders.length > 0) continue
4069
4234
  if (t - live.lastInboundAt <= SESSION_IDLE_MS) continue
4235
+ if (isPinnedByRunningChild(live.sessionId, live.keyId, 'idle_gc evicting')) continue
4070
4236
  victims.push(live)
4071
4237
  }
4072
4238
  for (const live of victims) {
@@ -4382,6 +4548,30 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4382
4548
  return { kind: 'no-live-session' }
4383
4549
  }
4384
4550
 
4551
+ const injectPrVerdictActivity = (args: {
4552
+ workspace: string
4553
+ prNumber: number
4554
+ verdict: 'APPROVE' | 'REQUEST_CHANGES'
4555
+ sessionId: string
4556
+ }): { kind: 'delivered'; count: number } => {
4557
+ const chat = `pr:${args.prNumber}`
4558
+ let count = 0
4559
+ for (const live of liveSessions.values()) {
4560
+ if (live.destroyed) continue
4561
+ if (live.key.adapter !== 'github') continue
4562
+ if (live.key.workspace !== args.workspace || live.key.chat !== chat) continue
4563
+ // Self-exclude: the session that just landed the verdict must not be told to
4564
+ // stand down from its own legitimate review.
4565
+ if (live.sessionId === args.sessionId) continue
4566
+ const text = renderPrVerdictStandDownReminder({ prNumber: args.prNumber, verdict: args.verdict })
4567
+ live.pendingSystemReminders.push(text)
4568
+ logger.info(`[channels] ${live.keyId}: pr-verdict stand-down queued pr=${chat} verdict=${args.verdict}`)
4569
+ if (!live.draining) void drain(live)
4570
+ count++
4571
+ }
4572
+ return { kind: 'delivered', count }
4573
+ }
4574
+
4385
4575
  const markTurnSkipped = (args: {
4386
4576
  parentSessionId: string
4387
4577
  reason: string
@@ -4489,6 +4679,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4489
4679
  executeCommand,
4490
4680
  getSelfAliases: computeSelfAliases,
4491
4681
  injectSubagentCompletionReminder,
4682
+ injectPrVerdictActivity,
4492
4683
  markTurnSkipped,
4493
4684
  clearSticky,
4494
4685
  reserveRestartHandoff,
@@ -4506,6 +4697,11 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4506
4697
  }
4507
4698
  live.firstUnprocessedAt = 0
4508
4699
  await drain(live)
4700
+ // Settle the fire-and-forget `void persist()` from scheduleDebouncedDrain
4701
+ // (the lastInboundAt write). Draining alone doesn't await that promise, so
4702
+ // a test reading sessions.json right after would race the disk write — the
4703
+ // flake that forced wall-clock polling on slow (Windows CI) filesystems.
4704
+ await persistChain
4509
4705
  },
4510
4706
  fireTypingHeartbeat: async (key: ChannelKey, phase: 'tick' | 'stop' = 'tick') => {
4511
4707
  const live = liveSessions.get(channelKeyId(key))
@@ -4819,7 +5015,9 @@ export type { QuoteAnchorSource } from './types'
4819
5015
  function formatAuthorReference(adapter: AdapterId, authorId: string, authorName: string): string {
4820
5016
  const displayName = authorName.trim() !== '' ? authorName.trim() : authorId
4821
5017
  switch (adapter) {
5018
+ case 'slack':
4822
5019
  case 'slack-bot':
5020
+ case 'discord':
4823
5021
  case 'discord-bot':
4824
5022
  return `<@${authorId}>`
4825
5023
  case 'github':
@@ -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
 
@@ -27,6 +27,7 @@ export const BUILTIN_COMMAND_NAMES = [
27
27
  'usage',
28
28
  'update',
29
29
  '_hostd',
30
+ '_update-check',
30
31
  ] as const
31
32
 
32
33
  export type BuiltinCommandName = (typeof BUILTIN_COMMAND_NAMES)[number]