typeclaw 0.42.0 → 0.43.0

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 (89) hide show
  1. package/auth.schema.json +16 -0
  2. package/package.json +3 -3
  3. package/secrets.schema.json +16 -0
  4. package/src/agent/adaptive-thinking-compat.ts +79 -0
  5. package/src/agent/index.ts +79 -101
  6. package/src/agent/live-subagents.ts +4 -4
  7. package/src/agent/plugin-tools.ts +85 -132
  8. package/src/agent/provider-error.ts +37 -0
  9. package/src/agent/reload-tool.ts +1 -1
  10. package/src/agent/session-origin.ts +6 -3
  11. package/src/agent/subagents.ts +2 -2
  12. package/src/agent/system-prompt.ts +24 -8
  13. package/src/agent/tool-result-budget.ts +1 -1
  14. package/src/agent/tools/channel-react.ts +5 -4
  15. package/src/agent/tools/spawn-subagent.ts +80 -24
  16. package/src/agent/tools/stream-snapshot.ts +8 -3
  17. package/src/bundled-plugins/agent-browser/index.ts +18 -8
  18. package/src/bundled-plugins/memory/README.md +4 -1
  19. package/src/bundled-plugins/memory/belief-sentence.ts +50 -0
  20. package/src/bundled-plugins/memory/dreaming.ts +13 -6
  21. package/src/bundled-plugins/memory/load-memory.ts +22 -2
  22. package/src/bundled-plugins/memory/memory-logger.ts +1 -1
  23. package/src/bundled-plugins/planner/planner.ts +1 -1
  24. package/src/bundled-plugins/researcher/researcher.ts +2 -2
  25. package/src/bundled-plugins/reviewer/reviewer.ts +1 -1
  26. package/src/capabilities/control-plane.ts +24 -0
  27. package/src/capabilities/index.ts +2 -0
  28. package/src/capabilities/runtime.ts +30 -0
  29. package/src/channels/adapters/discord-bot-thread-room.ts +73 -0
  30. package/src/channels/adapters/discord-bot.ts +9 -1
  31. package/src/channels/adapters/slack-bot-classify.ts +1 -0
  32. package/src/channels/adapters/slack-classify.ts +1 -0
  33. package/src/channels/engagement.ts +33 -0
  34. package/src/channels/manager.ts +41 -47
  35. package/src/channels/router.ts +150 -21
  36. package/src/channels/types.ts +10 -0
  37. package/src/cli/channel.ts +49 -12
  38. package/src/cli/command-meta.ts +2 -0
  39. package/src/cli/hostd.ts +4 -3
  40. package/src/cli/index.ts +1 -0
  41. package/src/cli/logs.ts +2 -2
  42. package/src/cli/mcp.ts +233 -0
  43. package/src/cli/restart.ts +5 -3
  44. package/src/cli/shell.ts +2 -2
  45. package/src/cli/start.ts +2 -2
  46. package/src/cli/status.ts +2 -2
  47. package/src/cli/stop.ts +2 -2
  48. package/src/compose/restart.ts +4 -3
  49. package/src/compose/start.ts +2 -2
  50. package/src/compose/stop.ts +2 -2
  51. package/src/config/config.ts +10 -1
  52. package/src/config/providers.ts +61 -9
  53. package/src/container/controller.ts +104 -0
  54. package/src/container/index.ts +9 -0
  55. package/src/hostd/daemon.ts +28 -9
  56. package/src/hostd/protocol.ts +12 -9
  57. package/src/init/index.ts +1 -1
  58. package/src/init/instagram-auth.ts +189 -34
  59. package/src/inspect/logs-item.ts +2 -2
  60. package/src/mcp/client.ts +16 -6
  61. package/src/mcp/index.ts +12 -0
  62. package/src/mcp/manager.ts +9 -4
  63. package/src/mcp/oauth.ts +212 -0
  64. package/src/run/index.ts +36 -11
  65. package/src/run/{codex-fetch-observer.ts → llm-fetch-observer.ts} +182 -82
  66. package/src/sandbox/availability.ts +2 -2
  67. package/src/sandbox/build.ts +1 -1
  68. package/src/sandbox/hidden-paths.ts +59 -0
  69. package/src/sandbox/index.ts +1 -1
  70. package/src/sandbox/policy.ts +2 -2
  71. package/src/secrets/discord-store.ts +4 -13
  72. package/src/secrets/index.ts +1 -1
  73. package/src/secrets/instagram-store.ts +4 -13
  74. package/src/secrets/kakao-store.ts +4 -13
  75. package/src/secrets/line-store.ts +4 -13
  76. package/src/secrets/schema.ts +13 -0
  77. package/src/secrets/secrets-provider.ts +86 -0
  78. package/src/secrets/slack-store.ts +4 -13
  79. package/src/secrets/storage.ts +108 -1
  80. package/src/secrets/webex-store.ts +4 -13
  81. package/src/server/index.ts +2 -2
  82. package/src/skills/typeclaw-channel-github/SKILL.md +2 -2
  83. package/src/skills/typeclaw-channel-instagram/SKILL.md +1 -1
  84. package/src/skills/typeclaw-config/SKILL.md +5 -3
  85. package/src/skills/typeclaw-plugins/SKILL.md +1 -1
  86. package/src/skills/typeclaw-troubleshooting/SKILL.md +1 -1
  87. package/src/stream/broker.ts +4 -3
  88. package/src/stream/types.ts +1 -0
  89. package/typeclaw.schema.json +14 -0
@@ -9,7 +9,7 @@ import { applyTurnThinkingLevel, getQuestionSignal, type QuestionSignal } from '
9
9
  import { resolveFallbackChain } from '@/agent/model-fallback'
10
10
  import { applyModelRuntimeOverrides } from '@/agent/model-overrides'
11
11
  import { forgetSharedLoopGuardTool } from '@/agent/plugin-tools'
12
- import { isThrottleOrOverload, subscribeProviderErrors } from '@/agent/provider-error'
12
+ import { detectHardProviderError, isFailoverWorthy, subscribeProviderErrors } from '@/agent/provider-error'
13
13
  import type { RestartHandoff } from '@/agent/restart-handoff'
14
14
  import type { ChannelParticipant, SessionOrigin } from '@/agent/session-origin'
15
15
  import { renderSubagentCompletionReminder } from '@/agent/subagent-completion-reminder'
@@ -656,6 +656,11 @@ type ChannelAgentSession = AgentSession & { getAbortReason?: () => string | unde
656
656
  type LiveSession = {
657
657
  key: ChannelKey
658
658
  keyId: string
659
+ // Structural room shape from the inbound (thread + optional parent channel).
660
+ // Kept on the session so membership scoping can reach the parent channel for
661
+ // platforms (Discord) where the thread is its own channel and the key alone
662
+ // cannot express "this is a thread in channel X". Updated per inbound in route().
663
+ room: InboundMessage['room']
659
664
  session: ChannelAgentSession
660
665
  activeModelRef: ReturnType<typeof resolveFallbackChain>[number]
661
666
  // The session's creation-time thinking level, captured once. A later escalated
@@ -736,6 +741,11 @@ type LiveSession = {
736
741
  // batch several inbounds that each got their own :eyes:, so every entry is
737
742
  // removed after the reply. Empty on turns with no reactable inbound.
738
743
  currentTurnEngageReactions: Array<Promise<ReactionRef | null>>
744
+ // Model-requested `channel_react` reactions for THIS turn, held until the turn
745
+ // ends. Flushed to the adapter only if the agent actually replied this turn;
746
+ // discarded on silence (skip_response / empty / errored turns) so the bot never
747
+ // leaves a reaction on a message it merely looked at (e.g. cron lookaround).
748
+ pendingTurnReactions: ReactionRequest[]
739
749
  lastTurnAuthorIds: Set<string>
740
750
  // Mirror of currentTurnAuthorId at end-of-turn (the LAST speaker of the
741
751
  // prior batch), preserved across the drain finally-block which resets
@@ -1031,6 +1041,11 @@ export type ChannelRouter = {
1031
1041
  registerReaction: (adapter: ChannelKey['adapter'], cb: ReactionCallback) => void
1032
1042
  unregisterReaction: (adapter: ChannelKey['adapter'], cb: ReactionCallback) => void
1033
1043
  react: (req: ReactionRequest) => Promise<ReactionResult>
1044
+ // Buffer a model-requested reaction for the current turn instead of firing it
1045
+ // immediately. It reaches the adapter only if the agent actually replies this
1046
+ // turn (drain's finally); a silent/skipped turn discards it. Keeps the bot from
1047
+ // leaving reactions on messages it looked at but never answered.
1048
+ queueReactionAfterReply: (req: ReactionRequest) => Promise<ReactionResult>
1034
1049
  registerRemoveReaction: (adapter: ChannelKey['adapter'], cb: RemoveReactionCallback) => void
1035
1050
  unregisterRemoveReaction: (adapter: ChannelKey['adapter'], cb: RemoveReactionCallback) => void
1036
1051
  removeReaction: (req: RemoveReactionRequest) => Promise<ReactionResult>
@@ -1561,16 +1576,37 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1561
1576
  return merged
1562
1577
  }
1563
1578
 
1564
- const readMembership = (key: ChannelKey): MembershipCount | null => {
1579
+ // Membership is a ROOM property, not a thread property: every human in the
1580
+ // parent channel can see and join a thread, so a thread has the same
1581
+ // effective human count as its parent channel. The engagement key carries the
1582
+ // thread suffix (`channelKeyId`) to give each thread its own live session and
1583
+ // sticky ledger, but scoping membership by that same key would give a fresh
1584
+ // thread a cold, thread-local count (≤1) and misfire the solo-human fallback.
1585
+ // Resolve/cache/invalidate membership under the PARENT-channel key so a thread
1586
+ // reuses the channel's warm count. Two platform shapes:
1587
+ // - Slack: the thread ts rides `key.thread`, so stripping it to null reaches
1588
+ // the parent channel (`key.chat` is already the parent).
1589
+ // - Discord: the thread is its OWN channel (`key.chat` = thread id,
1590
+ // `key.thread` = null), so we must repoint `chat` to `room.parentChat`.
1591
+ // DMs keep their own key — a DM's `@dm` workspace short-circuits before this.
1592
+ const membershipScopeKey = (key: ChannelKey, room?: InboundMessage['room']): ChannelKey => {
1593
+ if (key.workspace === '@dm') return key
1594
+ if (room?.parentChat !== undefined) return { ...key, chat: room.parentChat, thread: null }
1595
+ return key.thread === null ? key : { ...key, thread: null }
1596
+ }
1597
+
1598
+ const readMembership = (key: ChannelKey, room?: InboundMessage['room']): MembershipCount | null => {
1565
1599
  if (key.workspace === '@dm') return dmMembership(now())
1566
- return membershipCaches.get(key.adapter)?.get(key) ?? null
1600
+ const scoped = membershipScopeKey(key, room)
1601
+ return membershipCaches.get(scoped.adapter)?.get(scoped) ?? null
1567
1602
  }
1568
1603
 
1569
- const warmMembership = (key: ChannelKey): Promise<MembershipCount | null> | null => {
1604
+ const warmMembership = (key: ChannelKey, room?: InboundMessage['room']): Promise<MembershipCount | null> | null => {
1570
1605
  if (key.workspace === '@dm') return Promise.resolve(dmMembership(now()))
1571
- const cache = membershipCaches.get(key.adapter)
1606
+ const scoped = membershipScopeKey(key, room)
1607
+ const cache = membershipCaches.get(scoped.adapter)
1572
1608
  if (cache === undefined) return null
1573
- return cache.warmUp(key)
1609
+ return cache.warmUp(scoped)
1574
1610
  }
1575
1611
 
1576
1612
  const resolveThroughRegisteredMembership = async (key: ChannelKey): Promise<MembershipResolverResult> => {
@@ -1599,22 +1635,23 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1599
1635
 
1600
1636
  const membershipForEngagement = async (live: LiveSession): Promise<MembershipCount | null> => {
1601
1637
  if (live.key.workspace === '@dm') return dmMembership(now())
1602
- const cache = membershipCaches.get(live.key.adapter)
1638
+ const scoped = membershipScopeKey(live.key, live.room)
1639
+ const cache = membershipCaches.get(scoped.adapter)
1603
1640
  if (cache === undefined) return null
1604
1641
 
1605
- const cached = cache.read(live.key)
1642
+ const cached = cache.read(scoped)
1606
1643
  if (cached.kind === 'hit') return cached.membership
1607
1644
  if (cached.kind === 'stale') {
1608
- void cache.warmUp(live.key).catch((err) => {
1645
+ void cache.warmUp(scoped).catch((err) => {
1609
1646
  logger.warn(`[channels] membership refresh failed for ${live.keyId}: ${describe(err)}`)
1610
1647
  })
1611
1648
  return cached.membership
1612
1649
  }
1613
1650
 
1614
- const fetchPromise = live.membershipFetch ?? warmMembership(live.key)
1651
+ const fetchPromise = live.membershipFetch ?? warmMembership(live.key, live.room)
1615
1652
  live.membershipFetch = fetchPromise
1616
1653
  if (fetchPromise === null) return null
1617
- const membership = await withMembershipTimeout(fetchPromise, live.key, logger)
1654
+ const membership = await withMembershipTimeout(fetchPromise, scoped, logger)
1618
1655
  if (live.membershipFetch === fetchPromise) live.membershipFetch = null
1619
1656
  return membership
1620
1657
  }
@@ -1674,6 +1711,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1674
1711
  // is persisted only through the normal success path below — no pre-mutation
1675
1712
  // — so a reopen failure leaves the durable mapping untouched.
1676
1713
  resumeTarget?: { sessionId: string; sessionFile: string },
1714
+ // Inbound room shape, passed so the COLD-START membership warm below is
1715
+ // parent-scoped from the first fetch (Discord threads resolve `chat` to the
1716
+ // thread id, so an unscoped warm would prime the cache against the thread).
1717
+ room?: InboundMessage['room'],
1677
1718
  ): Promise<LiveSession> => {
1678
1719
  const keyId = channelKeyId(key)
1679
1720
  const existing = liveSessions.get(keyId)
@@ -1777,7 +1818,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1777
1818
  const phase = resolvedRecord?.sessionId === undefined ? 'cold-start' : 'rehydrate'
1778
1819
  logger.info(`[channels] ${keyId}: ensureLive begin (${phase})`)
1779
1820
  const participants = (resolvedRecord?.participants ?? []) as ChannelParticipant[]
1780
- const membershipFetch = warmMembership(key)
1821
+ const membershipFetch = warmMembership(key, room)
1781
1822
  // Independent platform lookups — overlap so the chain pays max(), not sum().
1782
1823
  const [resolvedNames, membership] = await Promise.all([
1783
1824
  resolveChannelNames(key),
@@ -1857,6 +1898,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1857
1898
  const live: LiveSession = {
1858
1899
  key,
1859
1900
  keyId,
1901
+ room,
1860
1902
  session: created.session,
1861
1903
  activeModelRef: resolveFallbackChain(getConfig().models, undefined)[0]!,
1862
1904
  turnThinkingDefault: created.session.thinkingLevel,
@@ -1890,6 +1932,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1890
1932
  currentTurnReactionRef: null,
1891
1933
  currentTurnTypingThread: null,
1892
1934
  currentTurnEngageReactions: [],
1935
+ pendingTurnReactions: [],
1893
1936
  // `lastTurnAuthorId` (string, used for `lastInboundAuthorId` in
1894
1937
  // origin) and `lastTurnAuthorIds` (Set, used by
1895
1938
  // `grantStickyForReplyTargets` as the fallback when
@@ -2538,6 +2581,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2538
2581
  try {
2539
2582
  while ((live.promptQueue.length > 0 || live.pendingSystemReminders.length > 0) && !live.destroyed) {
2540
2583
  live.typingTimedOut = false
2584
+ // Each turn starts with no held reactions; the model re-requests them
2585
+ // via channel_react during this turn, and the finally flushes or drops.
2586
+ live.pendingTurnReactions = []
2541
2587
  // Heartbeat must run during generation as well as during debounce.
2542
2588
  // Because new inbounds during a turn just push into promptQueue
2543
2589
  // without re-entering route(), the route() call site alone wouldn't
@@ -2654,7 +2700,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2654
2700
  currentModelRef: live.activeModelRef,
2655
2701
  session: live.session,
2656
2702
  text: promptText,
2657
- shouldFailover: (err) => isThrottleOrOverload(err.message),
2703
+ shouldFailover: (err) => isFailoverWorthy(err.message),
2658
2704
  setModelForRef: async (ref) => {
2659
2705
  await live.session.setModel(applyModelRuntimeOverrides(resolveModel(ref), ref))
2660
2706
  live.activeModelRef = ref
@@ -2694,6 +2740,15 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2694
2740
  logger.info(`[channels] ${live.keyId} prompted elapsed_ms=${now() - promptStart}`)
2695
2741
  } catch (err) {
2696
2742
  logger.error(`[channels] ${live.keyId}: prompt threw: ${describe(err)}`)
2743
+ // Fallback is exhausted by now (promptPersistentTurnWithFallback only
2744
+ // throws after rotating every eligible ref), so a recognizable provider
2745
+ // failure is terminal for this turn. Stage a redacted notice for the
2746
+ // `finally` poster — but never clobber a soft error already captured for
2747
+ // this turnSeq by subscribeProviderErrors (first-detected wins).
2748
+ const hardProviderError = detectHardProviderError(err)
2749
+ if (hardProviderError !== null && live.pendingProviderError?.turnSeq !== live.turnSeq) {
2750
+ live.pendingProviderError = { turnSeq: live.turnSeq, safeMessage: hardProviderError.safeMessage }
2751
+ }
2697
2752
  live.consecutiveSends.clear()
2698
2753
  live.lastSentText.clear()
2699
2754
  live.lastSendLeafId = null
@@ -2704,7 +2759,20 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2704
2759
  } finally {
2705
2760
  live.promptInFlight = false
2706
2761
  const sentReplyThisTurn = live.successfulChannelSends > successfulSendsBeforePrompt
2707
- if (sentReplyThisTurn) dropEngageReactionsAfterReply(live, engageAddPromises)
2762
+ if (sentReplyThisTurn) dropEngageReactions(live, engageAddPromises)
2763
+ // Held channel_react reactions apply only when the agent posted a
2764
+ // genuine reply this turn — NOT an empty-turn fallback or provider-
2765
+ // error notice, both of which send via source:'system' and bump
2766
+ // successfulChannelSends. Otherwise a silent/skipped/errored turn
2767
+ // would still stamp a reaction on a message it never really answered.
2768
+ // Computed BEFORE maybePostDeferredProviderError so its error send
2769
+ // cannot flip the decision.
2770
+ const usableReplyThisTurn =
2771
+ sentReplyThisTurn &&
2772
+ live.emptyTurnFallbackTurn !== live.turnSeq &&
2773
+ assistantLeafStopReason(live.session) !== 'error'
2774
+ if (usableReplyThisTurn) flushPendingReactions(live)
2775
+ else live.pendingTurnReactions = []
2708
2776
  const emptyTurnRetryQueued = live.emptyTurnRetries > emptyTurnRetriesBeforePrompt
2709
2777
  await maybePostDeferredProviderError(live, sentReplyThisTurn, emptyTurnRetryQueued)
2710
2778
  await fireSessionTurnEnd(live)
@@ -2723,6 +2791,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2723
2791
  live.currentTurnAuthorIds = new Set()
2724
2792
  live.currentTurnReactionRef = null
2725
2793
  live.currentTurnEngageReactions = []
2794
+ // Drop any still-held reactions if the loop exited without running the
2795
+ // per-turn finally (e.g. session destroyed mid-drain): never leave a
2796
+ // reaction attached to a turn that never completed a reply.
2797
+ live.pendingTurnReactions = []
2726
2798
  live.currentTurnAttachments = []
2727
2799
  // Reset AFTER stopTypingHeartbeat: its final 'stop' tick reads the anchor
2728
2800
  // to clear a flat-DM status; clearing it first would strand the indicator.
@@ -2932,7 +3004,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2932
3004
  const reservation = restartReservations.get(channelKeyId(key))
2933
3005
  if (reservation !== undefined) reservation.sawInbound = true
2934
3006
 
2935
- const live = await ensureLive(key, event.externalMessageId, event.authorId)
3007
+ const live = await ensureLive(key, event.externalMessageId, event.authorId, undefined, event.room)
3008
+ live.room = event.room
2936
3009
 
2937
3010
  const isNewAuthor = !live.participants.some((p) => p.authorId === event.authorId)
2938
3011
  live.participants = updateParticipants(
@@ -2951,10 +3024,11 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2951
3024
  // *next* turn sees fresh data, but the current turn still gets a
2952
3025
  // fast answer (cache miss → cold fetch with timeout, or stale-ok).
2953
3026
  if (isNewAuthor && live.key.workspace !== '@dm') {
2954
- const cache = membershipCaches.get(live.key.adapter)
3027
+ const scoped = membershipScopeKey(live.key, live.room)
3028
+ const cache = membershipCaches.get(scoped.adapter)
2955
3029
  if (cache !== undefined) {
2956
- cache.invalidate(live.key)
2957
- void cache.warmUp(live.key).catch((err) => {
3030
+ cache.invalidate(scoped)
3031
+ void cache.warmUp(scoped).catch((err) => {
2958
3032
  logger.warn(`[channels] membership warmup after new author failed for ${live.keyId}: ${describe(err)}`)
2959
3033
  })
2960
3034
  }
@@ -3119,6 +3193,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3119
3193
  event: InboundMessage,
3120
3194
  engageReaction: Promise<ReactionRef | null> | null,
3121
3195
  ): void => {
3196
+ clearQueuedEngageReactions(live)
3122
3197
  live.promptQueue.push({
3123
3198
  text: event.text,
3124
3199
  ...(event.referenceContext !== undefined ? { referenceContext: event.referenceContext } : {}),
@@ -3201,6 +3276,41 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3201
3276
  return lastError ?? { ok: false, error: 'no reaction callback handled request', code: 'unsupported' }
3202
3277
  }
3203
3278
 
3279
+ // Hold a model reaction until the turn proves it engaged (i.e. actually
3280
+ // replied). Buffered on the live session for this target; drain's finally
3281
+ // flushes it via react() on a real reply or drops it on silence. No live
3282
+ // session (or a stale ref that is not this turn's trigger) → nothing to pair
3283
+ // the reaction with, so it is refused rather than fired blind.
3284
+ const queueReactionAfterReply = async (req: ReactionRequest): Promise<ReactionResult> => {
3285
+ if (req.reactionRef.adapter !== req.adapter) {
3286
+ return { ok: false, error: 'reaction ref adapter mismatch', code: 'unsupported' }
3287
+ }
3288
+ const live = liveSessions.get(
3289
+ channelKeyId({ adapter: req.adapter, workspace: req.workspace, chat: req.chat, thread: req.thread ?? null }),
3290
+ )
3291
+ if (!live || live.destroyed) {
3292
+ return { ok: false, error: 'no live turn to attach this reaction to', code: 'unsupported' }
3293
+ }
3294
+ live.pendingTurnReactions.push(req)
3295
+ return { ok: true }
3296
+ }
3297
+
3298
+ const flushPendingReactions = (live: LiveSession): void => {
3299
+ const pending = live.pendingTurnReactions
3300
+ live.pendingTurnReactions = []
3301
+ for (const req of pending) {
3302
+ void react(req)
3303
+ .then((result) => {
3304
+ if (!result.ok && result.code !== 'unsupported') {
3305
+ logger.info(`[channels] react-after-reply failed adapter=${req.adapter} chat=${req.chat}: ${result.error}`)
3306
+ }
3307
+ })
3308
+ .catch((err) => {
3309
+ logger.info(`[channels] react-after-reply threw adapter=${req.adapter} chat=${req.chat}: ${describe(err)}`)
3310
+ })
3311
+ }
3312
+ }
3313
+
3204
3314
  const removeReaction = async (req: RemoveReactionRequest): Promise<ReactionResult> => {
3205
3315
  if (req.reactionRef.adapter !== req.adapter) {
3206
3316
  return { ok: false, error: 'reaction ref adapter mismatch', code: 'unsupported' }
@@ -3254,11 +3364,23 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3254
3364
  return addReactionRef
3255
3365
  }
3256
3366
 
3257
- const dropEngageReactionsAfterReply = (live: LiveSession, addPromises: Array<Promise<ReactionRef | null>>): void => {
3258
- for (const addPromise of addPromises) dropOneEngageReactionAfterReply(live, addPromise)
3367
+ const dropEngageReactions = (live: LiveSession, addPromises: Array<Promise<ReactionRef | null>>): void => {
3368
+ for (const addPromise of addPromises) dropOneEngageReaction(live, addPromise)
3369
+ }
3370
+
3371
+ // Only the LAST engaging inbound of a coalesced batch should carry the eager
3372
+ // :eyes:. Called from enqueue() before the new inbound is pushed to roll the
3373
+ // ack off earlier queued-but-not-yet-drained inbounds. `delete` (not
3374
+ // overwrite) is load-bearing: a newer engaging inbound that has no reactionRef
3375
+ // must still strip the previous :eyes: rather than leave it stranded.
3376
+ const clearQueuedEngageReactions = (live: LiveSession): void => {
3377
+ const addPromises = live.promptQueue.flatMap((m) => (m.engageReaction !== undefined ? [m.engageReaction] : []))
3378
+ if (addPromises.length === 0) return
3379
+ for (const item of live.promptQueue) delete item.engageReaction
3380
+ dropEngageReactions(live, addPromises)
3259
3381
  }
3260
3382
 
3261
- const dropOneEngageReactionAfterReply = (live: LiveSession, addPromise: Promise<ReactionRef | null>): void => {
3383
+ const dropOneEngageReaction = (live: LiveSession, addPromise: Promise<ReactionRef | null>): void => {
3262
3384
  void addPromise
3263
3385
  .then((reactionRef) => {
3264
3386
  if (reactionRef === null) return undefined
@@ -4354,6 +4476,12 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4354
4476
 
4355
4477
  const tearDownLive = async (live: LiveSession): Promise<void> => {
4356
4478
  live.destroyed = true
4479
+ // A teardown before the queued/in-flight turn ever replies would otherwise
4480
+ // strand its eager :eyes: forever (dropEngageReactions only runs after a
4481
+ // successful send). Remove both the queued and current-turn acks here.
4482
+ clearQueuedEngageReactions(live)
4483
+ dropEngageReactions(live, live.currentTurnEngageReactions)
4484
+ live.currentTurnEngageReactions = []
4357
4485
  if (live.debounceTimer) clearTimeout(live.debounceTimer)
4358
4486
  live.debounceTimer = null
4359
4487
  live.unsubProviderErrors?.()
@@ -4839,6 +4967,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4839
4967
  registerReaction,
4840
4968
  unregisterReaction,
4841
4969
  react,
4970
+ queueReactionAfterReply,
4842
4971
  registerRemoveReaction,
4843
4972
  unregisterRemoveReaction,
4844
4973
  removeReaction,
@@ -51,6 +51,16 @@ export type InboundMessage = {
51
51
  workspace: string
52
52
  chat: string
53
53
  thread: string | null
54
+ // Structural "this message lives in a thread room" signal, kept SEPARATE
55
+ // from `thread`. `thread` is a reply-routing field whose meaning differs per
56
+ // platform: Slack puts the thread ts here (so `thread !== null` ⇒ thread
57
+ // room), but Discord models a thread as its own channel — the thread's id is
58
+ // in `chat` and `thread` stays null. The engagement gate and membership
59
+ // scoping need "is this a thread room?" independent of routing, so adapters
60
+ // set this explicitly. `parentChat` carries the parent channel id when the
61
+ // adapter knows it, so membership can be scoped to the room (channel), not
62
+ // the thread. Absent ⇒ not a thread room (or the adapter cannot tell).
63
+ room?: { kind: 'thread'; parentChat?: string }
54
64
  text: string
55
65
  // Prompt-only context for replied-to / quoted / linked messages. Kept out
56
66
  // of `text` so the engagement gate sees only the human-authored body.
@@ -12,7 +12,7 @@ import {
12
12
  type ChannelListEntry,
13
13
  type GithubConfigCleanup,
14
14
  } from '@/config/channels-mutation'
15
- import { start, status, stop } from '@/container'
15
+ import { resolveController } from '@/container'
16
16
  import {
17
17
  CHANNEL_KINDS,
18
18
  appendOrReplaceEnvKey,
@@ -37,7 +37,7 @@ import {
37
37
  type WebexAuthResult,
38
38
  } from '@/init'
39
39
  import { runDiscordBootstrap } from '@/init/discord-auth'
40
- import { runInstagramBootstrap } from '@/init/instagram-auth'
40
+ import { runInstagramBootstrap, type InstagramLoginCallbacks } from '@/init/instagram-auth'
41
41
  import { runKakaotalkBootstrap } from '@/init/kakaotalk-auth'
42
42
  import { runLineBootstrap } from '@/init/line-auth'
43
43
  import { runSlackBootstrap } from '@/init/slack-auth'
@@ -469,7 +469,12 @@ async function runInstagramReauth(cwd: string): Promise<void> {
469
469
  const creds = await promptInstagramCredentials()
470
470
  const s = spinner()
471
471
  s.start('Logging in to Instagram...')
472
- const result = await runInstagramBootstrap({ username: creds.username, password: creds.password, agentDir: cwd })
472
+ const result = await runInstagramBootstrap({
473
+ username: creds.username,
474
+ password: creds.password,
475
+ agentDir: cwd,
476
+ callbacks: instagramLoginCallbacks({ pause: () => s.stop(), resume: (message) => s.start(message) }),
477
+ })
473
478
  if (!result.ok) {
474
479
  s.stop(`Instagram login failed: ${result.reason}`)
475
480
  process.exit(1)
@@ -575,7 +580,8 @@ async function maybePromptCredentialRefresh(
575
580
  label: string,
576
581
  verbPast: 're-authenticated' | 'credentials updated',
577
582
  ): Promise<void> {
578
- const current = await status({ cwd }).catch(() => null)
583
+ const controller = resolveController()
584
+ const current = await controller.status({ cwd }).catch(() => null)
579
585
  if (current === null || current.kind !== 'running') {
580
586
  done({
581
587
  title: c.green(`${label} ${verbPast}.`),
@@ -603,12 +609,12 @@ async function maybePromptCredentialRefresh(
603
609
  return
604
610
  }
605
611
 
606
- const stopped = await stop({ cwd })
612
+ const stopped = await controller.stop({ cwd })
607
613
  if (!stopped.ok) {
608
614
  console.error(errorLine(`Restart failed during stop: ${stopped.reason}`))
609
615
  process.exit(1)
610
616
  }
611
- const started = await start({ cwd, preferredHostPort: config.port, cliEntry: process.argv[1] })
617
+ const started = await controller.start({ cwd, preferredHostPort: config.port, cliEntry: process.argv[1] })
612
618
  if (!started.ok) {
613
619
  console.error(errorLine(`Restart failed during start: ${started.reason}`))
614
620
  process.exit(1)
@@ -1018,10 +1024,11 @@ async function collectCredentials(
1018
1024
  return { channel, webexBotToken: await promptWebexToken() }
1019
1025
  case 'instagram': {
1020
1026
  const creds = await promptInstagramCredentials()
1027
+ const callbacks = instagramLoginCallbacks(lineSpinnerHolder ? holderSpinnerControl(lineSpinnerHolder) : undefined)
1021
1028
  return {
1022
1029
  channel,
1023
1030
  runInstagramAuth: ({ cwd: agentDir }) =>
1024
- runInstagramBootstrap({ username: creds.username, password: creds.password, agentDir }),
1031
+ runInstagramBootstrap({ username: creds.username, password: creds.password, agentDir, callbacks }),
1025
1032
  }
1026
1033
  }
1027
1034
  case 'line': {
@@ -1558,7 +1565,7 @@ async function promptInstagramCredentials(): Promise<{ username: string; passwor
1558
1565
  [
1559
1566
  'Instagram authentication uses a personal account.',
1560
1567
  'Messages will be sent and received under this account.',
1561
- '2FA/checkpointed accounts are not supported; use a dedicated account without those challenges.',
1568
+ 'If the account has 2FA or triggers a checkpoint, you will be prompted for the verification code here.',
1562
1569
  ].join('\n'),
1563
1570
  'About to log in to Instagram',
1564
1571
  )
@@ -1581,6 +1588,32 @@ async function promptInstagramCredentials(): Promise<{ username: string; passwor
1581
1588
  return { username, password: pwd }
1582
1589
  }
1583
1590
 
1591
+ // The login spinner ('Logging in to Instagram...') keeps animating while
1592
+ // Instagram's 2FA/checkpoint step waits on a human, and would repaint over the
1593
+ // code prompt. Pause it around the prompt so the input line stays legible, then
1594
+ // resume with a "waiting" message — same control the LINE PIN flow uses.
1595
+ function instagramLoginCallbacks(spinnerControl?: LineAuthSpinnerControl): InstagramLoginCallbacks {
1596
+ const promptCode = async (message: string): Promise<string | null> => {
1597
+ spinnerControl?.pause()
1598
+ const code = await text({
1599
+ message,
1600
+ validate: (value) => (value && value.trim().length > 0 ? undefined : 'A verification code is required'),
1601
+ })
1602
+ if (isCancel(code)) return null
1603
+ spinnerControl?.resume('Verifying the Instagram code...')
1604
+ return code
1605
+ }
1606
+
1607
+ return {
1608
+ onTwoFactorCode: () => promptCode('Enter the Instagram 2FA code from your authenticator app or SMS'),
1609
+ onChallengeCode: async ({ contactPoint }) => {
1610
+ const where = contactPoint === '' ? 'your email or phone' : contactPoint
1611
+ const code = await promptCode(`Enter the Instagram verification code sent to ${where}`)
1612
+ return code === null ? null : { code }
1613
+ },
1614
+ }
1615
+ }
1616
+
1584
1617
  type LinePromptResult =
1585
1618
  | { method: 'qr'; callbacks: { onQRUrl: (url: string) => Promise<void>; onPincode: (pin: string) => void } }
1586
1619
  | {
@@ -1735,7 +1768,9 @@ function reportProgress(
1735
1768
  const s = spinner()
1736
1769
  s.start(START_MESSAGES[event.step])
1737
1770
  spinners[event.step] = s
1738
- if (event.step === 'line-auth' && lineSpinnerHolder) lineSpinnerHolder.current = s
1771
+ if ((event.step === 'line-auth' || event.step === 'instagram-auth') && lineSpinnerHolder) {
1772
+ lineSpinnerHolder.current = s
1773
+ }
1739
1774
  return
1740
1775
  }
1741
1776
 
@@ -1748,6 +1783,7 @@ function reportProgress(
1748
1783
  s.stop(reportLineAuth(event.result))
1749
1784
  break
1750
1785
  case 'instagram-auth':
1786
+ if (lineSpinnerHolder) lineSpinnerHolder.current = null
1751
1787
  s.stop(reportInstagramAuth(event.result))
1752
1788
  break
1753
1789
  case 'kakaotalk-auth':
@@ -1823,7 +1859,8 @@ async function maybePromptRestart(
1823
1859
  verb: 'added' | 'removed' = 'added',
1824
1860
  ): Promise<void> {
1825
1861
  const label = CHANNEL_LABELS[channel]
1826
- const current = await status({ cwd }).catch(() => null)
1862
+ const controller = resolveController()
1863
+ const current = await controller.status({ cwd }).catch(() => null)
1827
1864
  if (current === null || current.kind !== 'running') {
1828
1865
  done({
1829
1866
  title: c.green(`${label} channel ${verb}.`),
@@ -1850,12 +1887,12 @@ async function maybePromptRestart(
1850
1887
  return
1851
1888
  }
1852
1889
 
1853
- const stopped = await stop({ cwd })
1890
+ const stopped = await controller.stop({ cwd })
1854
1891
  if (!stopped.ok) {
1855
1892
  console.error(errorLine(`Restart failed during stop: ${stopped.reason}`))
1856
1893
  process.exit(1)
1857
1894
  }
1858
- const started = await start({ cwd, preferredHostPort: config.port, cliEntry: process.argv[1] })
1895
+ const started = await controller.start({ cwd, preferredHostPort: config.port, cliEntry: process.argv[1] })
1859
1896
  if (!started.ok) {
1860
1897
  console.error(errorLine(`Restart failed during start: ${started.reason}`))
1861
1898
  process.exit(1)
@@ -27,6 +27,7 @@ export type BuiltinCommandName =
27
27
  | 'tunnel'
28
28
  | 'role'
29
29
  | 'provider'
30
+ | 'mcp'
30
31
  | 'model'
31
32
  | 'mount'
32
33
  | 'doctor'
@@ -60,6 +61,7 @@ export const BUILTIN_COMMANDS: readonly BuiltinCommandMeta[] = [
60
61
  { name: 'tunnel', description: 'manage public tunnels for channels and manual upstreams' },
61
62
  { name: 'role', description: 'manage role memberships on this agent' },
62
63
  { name: 'provider', description: 'manage LLM provider credentials in secrets.json' },
64
+ { name: 'mcp', description: 'manage MCP server OAuth credentials' },
63
65
  { name: 'model', description: 'manage model profiles in typeclaw.json (models.default, ...)' },
64
66
  { name: 'mount', description: 'manage host files and directories mounted into the agent container' },
65
67
  { name: 'doctor', description: 'diagnose host, agent folder, and plugins; suggest fixes' },
package/src/cli/hostd.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { defineCommand } from 'citty'
2
2
 
3
3
  import { loadConfigSync, validateConfig, type Config, type ValidateConfigResult } from '@/config'
4
- import { start, stop, type StartOptions, type StartResult, type StopResult } from '@/container'
4
+ import { resolveController, type StartOptions, type StartResult, type StopResult } from '@/container'
5
5
  import { createCurrentHostDaemonHolder } from '@/hostd/current-host-daemon'
6
6
  import { startDaemon, type DaemonLogEvent, type RestartPreflight } from '@/hostd/daemon'
7
7
  import { createKakaoRenewalManager } from '@/hostd/kakao-renewal-manager'
@@ -92,11 +92,12 @@ export type HostdRestartDeps = {
92
92
  start: (opts: StartOptions) => Promise<StartResult>
93
93
  }
94
94
 
95
+ const controller = resolveController()
95
96
  const defaultRestartDeps: HostdRestartDeps = {
96
97
  validateConfig,
97
- stop,
98
+ stop: (opts) => controller.stop(opts),
98
99
  loadConfigSync,
99
- start,
100
+ start: (opts) => controller.start(opts),
100
101
  }
101
102
 
102
103
  export function buildHostdRestart(
package/src/cli/index.ts CHANGED
@@ -33,6 +33,7 @@ const main = defineCommand({
33
33
  tunnel: () => import('./tunnel').then((m) => m.tunnelCommand),
34
34
  role: () => import('./role').then((m) => m.roleCommand),
35
35
  provider: () => import('./provider').then((m) => m.providerCommand),
36
+ mcp: () => import('./mcp').then((m) => m.mcpCommand),
36
37
  model: () => import('./model').then((m) => m.modelCommand),
37
38
  mount: () => import('./mount').then((m) => m.mountCommand),
38
39
  doctor: () => import('./doctor').then((m) => m.doctorCommand),
package/src/cli/logs.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { defineCommand } from 'citty'
2
2
 
3
- import { logs, parseTailValue } from '@/container'
3
+ import { parseTailValue, resolveController } from '@/container'
4
4
 
5
5
  import { preflightDocker, printDockerGuidance } from './docker-preflight'
6
6
  import { runInspectViewer } from './inspect'
@@ -64,7 +64,7 @@ export const logsCommand = defineCommand({
64
64
  console.log(c.dim('Showing container logs.'))
65
65
  }
66
66
 
67
- const result = await logs({ cwd, follow: args.follow, tail })
67
+ const result = await resolveController().logs({ cwd, follow: args.follow, tail })
68
68
  if (!result.ok) {
69
69
  console.error(errorLine(result.reason))
70
70
  process.exit(1)