typeclaw 0.42.1 → 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.
- package/auth.schema.json +16 -0
- package/package.json +1 -1
- package/secrets.schema.json +16 -0
- package/src/agent/live-subagents.ts +4 -4
- package/src/agent/plugin-tools.ts +8 -2
- package/src/agent/session-origin.ts +6 -3
- package/src/agent/system-prompt.ts +5 -3
- package/src/agent/tools/channel-react.ts +5 -4
- package/src/agent/tools/spawn-subagent.ts +80 -24
- package/src/bundled-plugins/planner/planner.ts +1 -1
- package/src/bundled-plugins/researcher/researcher.ts +2 -2
- package/src/bundled-plugins/reviewer/reviewer.ts +1 -1
- package/src/channels/adapters/discord-bot-thread-room.ts +73 -0
- package/src/channels/adapters/discord-bot.ts +9 -1
- package/src/channels/adapters/slack-bot-classify.ts +1 -0
- package/src/channels/adapters/slack-classify.ts +1 -0
- package/src/channels/engagement.ts +33 -0
- package/src/channels/router.ts +139 -19
- package/src/channels/types.ts +10 -0
- package/src/cli/command-meta.ts +2 -0
- package/src/cli/index.ts +1 -0
- package/src/cli/mcp.ts +233 -0
- package/src/hostd/daemon.ts +28 -9
- package/src/hostd/protocol.ts +12 -9
- package/src/mcp/client.ts +15 -5
- package/src/mcp/index.ts +12 -0
- package/src/mcp/manager.ts +9 -4
- package/src/mcp/oauth.ts +212 -0
- package/src/run/index.ts +15 -2
- package/src/sandbox/hidden-paths.ts +59 -0
- package/src/sandbox/index.ts +1 -1
- package/src/secrets/index.ts +1 -1
- package/src/secrets/schema.ts +13 -0
- package/src/secrets/secrets-provider.ts +2 -2
- package/src/secrets/storage.ts +108 -1
- package/src/skills/typeclaw-channel-github/SKILL.md +2 -2
- package/src/skills/typeclaw-troubleshooting/SKILL.md +1 -1
package/src/channels/router.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
|
1606
|
+
const scoped = membershipScopeKey(key, room)
|
|
1607
|
+
const cache = membershipCaches.get(scoped.adapter)
|
|
1572
1608
|
if (cache === undefined) return null
|
|
1573
|
-
return cache.warmUp(
|
|
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
|
|
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(
|
|
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(
|
|
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,
|
|
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
|
|
@@ -2713,7 +2759,20 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2713
2759
|
} finally {
|
|
2714
2760
|
live.promptInFlight = false
|
|
2715
2761
|
const sentReplyThisTurn = live.successfulChannelSends > successfulSendsBeforePrompt
|
|
2716
|
-
if (sentReplyThisTurn)
|
|
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 = []
|
|
2717
2776
|
const emptyTurnRetryQueued = live.emptyTurnRetries > emptyTurnRetriesBeforePrompt
|
|
2718
2777
|
await maybePostDeferredProviderError(live, sentReplyThisTurn, emptyTurnRetryQueued)
|
|
2719
2778
|
await fireSessionTurnEnd(live)
|
|
@@ -2732,6 +2791,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2732
2791
|
live.currentTurnAuthorIds = new Set()
|
|
2733
2792
|
live.currentTurnReactionRef = null
|
|
2734
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 = []
|
|
2735
2798
|
live.currentTurnAttachments = []
|
|
2736
2799
|
// Reset AFTER stopTypingHeartbeat: its final 'stop' tick reads the anchor
|
|
2737
2800
|
// to clear a flat-DM status; clearing it first would strand the indicator.
|
|
@@ -2941,7 +3004,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2941
3004
|
const reservation = restartReservations.get(channelKeyId(key))
|
|
2942
3005
|
if (reservation !== undefined) reservation.sawInbound = true
|
|
2943
3006
|
|
|
2944
|
-
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
|
|
2945
3009
|
|
|
2946
3010
|
const isNewAuthor = !live.participants.some((p) => p.authorId === event.authorId)
|
|
2947
3011
|
live.participants = updateParticipants(
|
|
@@ -2960,10 +3024,11 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2960
3024
|
// *next* turn sees fresh data, but the current turn still gets a
|
|
2961
3025
|
// fast answer (cache miss → cold fetch with timeout, or stale-ok).
|
|
2962
3026
|
if (isNewAuthor && live.key.workspace !== '@dm') {
|
|
2963
|
-
const
|
|
3027
|
+
const scoped = membershipScopeKey(live.key, live.room)
|
|
3028
|
+
const cache = membershipCaches.get(scoped.adapter)
|
|
2964
3029
|
if (cache !== undefined) {
|
|
2965
|
-
cache.invalidate(
|
|
2966
|
-
void cache.warmUp(
|
|
3030
|
+
cache.invalidate(scoped)
|
|
3031
|
+
void cache.warmUp(scoped).catch((err) => {
|
|
2967
3032
|
logger.warn(`[channels] membership warmup after new author failed for ${live.keyId}: ${describe(err)}`)
|
|
2968
3033
|
})
|
|
2969
3034
|
}
|
|
@@ -3128,6 +3193,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3128
3193
|
event: InboundMessage,
|
|
3129
3194
|
engageReaction: Promise<ReactionRef | null> | null,
|
|
3130
3195
|
): void => {
|
|
3196
|
+
clearQueuedEngageReactions(live)
|
|
3131
3197
|
live.promptQueue.push({
|
|
3132
3198
|
text: event.text,
|
|
3133
3199
|
...(event.referenceContext !== undefined ? { referenceContext: event.referenceContext } : {}),
|
|
@@ -3210,6 +3276,41 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3210
3276
|
return lastError ?? { ok: false, error: 'no reaction callback handled request', code: 'unsupported' }
|
|
3211
3277
|
}
|
|
3212
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
|
+
|
|
3213
3314
|
const removeReaction = async (req: RemoveReactionRequest): Promise<ReactionResult> => {
|
|
3214
3315
|
if (req.reactionRef.adapter !== req.adapter) {
|
|
3215
3316
|
return { ok: false, error: 'reaction ref adapter mismatch', code: 'unsupported' }
|
|
@@ -3263,11 +3364,23 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3263
3364
|
return addReactionRef
|
|
3264
3365
|
}
|
|
3265
3366
|
|
|
3266
|
-
const
|
|
3267
|
-
for (const addPromise of addPromises)
|
|
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)
|
|
3268
3381
|
}
|
|
3269
3382
|
|
|
3270
|
-
const
|
|
3383
|
+
const dropOneEngageReaction = (live: LiveSession, addPromise: Promise<ReactionRef | null>): void => {
|
|
3271
3384
|
void addPromise
|
|
3272
3385
|
.then((reactionRef) => {
|
|
3273
3386
|
if (reactionRef === null) return undefined
|
|
@@ -4363,6 +4476,12 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
4363
4476
|
|
|
4364
4477
|
const tearDownLive = async (live: LiveSession): Promise<void> => {
|
|
4365
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 = []
|
|
4366
4485
|
if (live.debounceTimer) clearTimeout(live.debounceTimer)
|
|
4367
4486
|
live.debounceTimer = null
|
|
4368
4487
|
live.unsubProviderErrors?.()
|
|
@@ -4848,6 +4967,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
4848
4967
|
registerReaction,
|
|
4849
4968
|
unregisterReaction,
|
|
4850
4969
|
react,
|
|
4970
|
+
queueReactionAfterReply,
|
|
4851
4971
|
registerRemoveReaction,
|
|
4852
4972
|
unregisterRemoveReaction,
|
|
4853
4973
|
removeReaction,
|
package/src/channels/types.ts
CHANGED
|
@@ -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.
|
package/src/cli/command-meta.ts
CHANGED
|
@@ -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/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/mcp.ts
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
|
|
4
|
+
import { isCancel, log, note, text } from '@clack/prompts'
|
|
5
|
+
import { UnauthorizedError } from '@modelcontextprotocol/sdk/client/auth.js'
|
|
6
|
+
import { Client } from '@modelcontextprotocol/sdk/client/index.js'
|
|
7
|
+
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'
|
|
8
|
+
import { defineCommand } from 'citty'
|
|
9
|
+
|
|
10
|
+
import { loadConfigSync } from '@/config'
|
|
11
|
+
import { findAgentDir, isInitialized } from '@/init'
|
|
12
|
+
import { createFileMcpOAuthStore, TypeClawMcpOAuthProvider, listMcpCredentials } from '@/mcp'
|
|
13
|
+
import { SecretsBackend } from '@/secrets'
|
|
14
|
+
|
|
15
|
+
import { c, done, errorLine } from './ui'
|
|
16
|
+
|
|
17
|
+
const DEFAULT_CALLBACK_PORT = 1456
|
|
18
|
+
|
|
19
|
+
const authSub = defineCommand({
|
|
20
|
+
meta: {
|
|
21
|
+
name: 'auth',
|
|
22
|
+
description: 'authenticate an HTTP MCP server with OAuth',
|
|
23
|
+
},
|
|
24
|
+
args: {
|
|
25
|
+
server: { type: 'positional', description: 'MCP server name from typeclaw.json', required: true },
|
|
26
|
+
},
|
|
27
|
+
async run({ args }) {
|
|
28
|
+
const cwd = ensureAgentDir()
|
|
29
|
+
const result = await runMcpAuthFlow(cwd, args.server)
|
|
30
|
+
if (!result.ok) {
|
|
31
|
+
console.error(errorLine(result.reason))
|
|
32
|
+
process.exit(1)
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
const listSub = defineCommand({
|
|
38
|
+
meta: {
|
|
39
|
+
name: 'list',
|
|
40
|
+
description: 'show configured MCP servers and OAuth credential state',
|
|
41
|
+
},
|
|
42
|
+
run() {
|
|
43
|
+
const cwd = ensureAgentDir()
|
|
44
|
+
const config = loadConfigSync(cwd)
|
|
45
|
+
const credentials = listMcpCredentials(join(cwd, 'secrets.json'))
|
|
46
|
+
if (config.mcpServers.length === 0) {
|
|
47
|
+
console.log(c.dim('No MCP servers configured in typeclaw.json.'))
|
|
48
|
+
return
|
|
49
|
+
}
|
|
50
|
+
const nameWidth = Math.max(4, ...config.mcpServers.map((server) => server.name.length))
|
|
51
|
+
const typeWidth = 5
|
|
52
|
+
console.log(c.dim(`${'NAME'.padEnd(nameWidth)} ${'TYPE'.padEnd(typeWidth)} OAUTH`))
|
|
53
|
+
for (const server of config.mcpServers) {
|
|
54
|
+
const type = server.url === undefined ? 'stdio' : 'http'
|
|
55
|
+
const oauth = credentials[server.name] === undefined ? 'not configured' : 'configured'
|
|
56
|
+
console.log(`${server.name.padEnd(nameWidth)} ${type.padEnd(typeWidth)} ${oauth}`)
|
|
57
|
+
}
|
|
58
|
+
},
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
const logoutSub = defineCommand({
|
|
62
|
+
meta: {
|
|
63
|
+
name: 'logout',
|
|
64
|
+
description: 'remove OAuth credentials for an MCP server',
|
|
65
|
+
},
|
|
66
|
+
args: {
|
|
67
|
+
server: { type: 'positional', description: 'MCP server name from typeclaw.json', required: true },
|
|
68
|
+
},
|
|
69
|
+
run({ args }) {
|
|
70
|
+
const cwd = ensureAgentDir()
|
|
71
|
+
const removed = new SecretsBackend(join(cwd, 'secrets.json')).removeMcpCredentialSync(args.server)
|
|
72
|
+
if (!removed) log.info(`No OAuth credentials found for MCP server "${args.server}".`)
|
|
73
|
+
done({
|
|
74
|
+
title: c.green(`Removed OAuth credentials for MCP server "${args.server}".`),
|
|
75
|
+
hints: [{ label: 'Apply the secrets.json change:', command: 'typeclaw reload' }],
|
|
76
|
+
})
|
|
77
|
+
},
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
export const mcpCommand = defineCommand({
|
|
81
|
+
meta: {
|
|
82
|
+
name: 'mcp',
|
|
83
|
+
description: 'manage MCP server OAuth credentials',
|
|
84
|
+
},
|
|
85
|
+
subCommands: {
|
|
86
|
+
auth: authSub,
|
|
87
|
+
list: listSub,
|
|
88
|
+
logout: logoutSub,
|
|
89
|
+
},
|
|
90
|
+
})
|
|
91
|
+
|
|
92
|
+
export type McpAuthFlowResult = { ok: true } | { ok: false; reason: string }
|
|
93
|
+
|
|
94
|
+
export async function runMcpAuthFlow(cwd: string, serverName: string): Promise<McpAuthFlowResult> {
|
|
95
|
+
const config = loadConfigSync(cwd)
|
|
96
|
+
const server = config.mcpServers.find((candidate) => candidate.name === serverName)
|
|
97
|
+
if (server === undefined) return { ok: false, reason: `MCP server "${serverName}" is not configured.` }
|
|
98
|
+
if (server.url === undefined)
|
|
99
|
+
return { ok: false, reason: `MCP server "${serverName}" is stdio-only; OAuth is HTTP-only.` }
|
|
100
|
+
|
|
101
|
+
const redirectUrl = `http://localhost:${DEFAULT_CALLBACK_PORT}/callback`
|
|
102
|
+
let authorizationUrl: URL | undefined
|
|
103
|
+
const provider = new TypeClawMcpOAuthProvider(serverName, createFileMcpOAuthStore(join(cwd, 'secrets.json')), {
|
|
104
|
+
mode: 'host',
|
|
105
|
+
redirectUrl,
|
|
106
|
+
clientName: 'typeclaw',
|
|
107
|
+
onRedirect: (url) => {
|
|
108
|
+
authorizationUrl = url
|
|
109
|
+
},
|
|
110
|
+
})
|
|
111
|
+
const callback = createCallbackServer(DEFAULT_CALLBACK_PORT)
|
|
112
|
+
try {
|
|
113
|
+
const transport = new StreamableHTTPClientTransport(new URL(server.url), { authProvider: provider })
|
|
114
|
+
const client = new Client({ name: 'typeclaw', version: '0.17.0' }, { capabilities: {} })
|
|
115
|
+
try {
|
|
116
|
+
await client.connect(transport)
|
|
117
|
+
await client.close()
|
|
118
|
+
done({ title: c.green(`MCP server "${serverName}" is already authenticated.`), hints: [] })
|
|
119
|
+
return { ok: true }
|
|
120
|
+
} catch (cause) {
|
|
121
|
+
await client.close().catch(() => undefined)
|
|
122
|
+
if (!(cause instanceof UnauthorizedError)) throw cause
|
|
123
|
+
}
|
|
124
|
+
if (authorizationUrl === undefined)
|
|
125
|
+
return { ok: false, reason: 'OAuth server did not provide an authorization URL.' }
|
|
126
|
+
renderAuthorizationUrl(serverName, authorizationUrl)
|
|
127
|
+
openBrowserBestEffort(authorizationUrl)
|
|
128
|
+
const expectedState = await provider.state()
|
|
129
|
+
const codeResult = await Promise.race([callback.code, promptForCodeOrUrl()])
|
|
130
|
+
if (expectedState !== undefined && codeResult.state !== undefined && codeResult.state !== expectedState) {
|
|
131
|
+
return { ok: false, reason: 'OAuth callback state did not match the authorization request.' }
|
|
132
|
+
}
|
|
133
|
+
await transport.finishAuth(codeResult.code)
|
|
134
|
+
await verifyMcpAuth(server.url, provider)
|
|
135
|
+
done({
|
|
136
|
+
title: c.green(`Authenticated MCP server "${serverName}".`),
|
|
137
|
+
hints: [{ label: 'Apply the secrets.json change:', command: 'typeclaw reload' }],
|
|
138
|
+
})
|
|
139
|
+
return { ok: true }
|
|
140
|
+
} catch (cause) {
|
|
141
|
+
return { ok: false, reason: cause instanceof Error ? cause.message : String(cause) }
|
|
142
|
+
} finally {
|
|
143
|
+
callback.stop()
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function ensureAgentDir(): string {
|
|
148
|
+
const cwd = findAgentDir(process.cwd()) ?? process.cwd()
|
|
149
|
+
if (!isInitialized(cwd)) {
|
|
150
|
+
console.error(errorLine('TypeClaw config file not found. Run `typeclaw init` first, or cd into an agent folder.'))
|
|
151
|
+
process.exit(1)
|
|
152
|
+
}
|
|
153
|
+
return cwd
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function createCallbackServer(port: number): { code: Promise<{ code: string; state?: string }>; stop(): void } {
|
|
157
|
+
let resolveCode!: (value: { code: string; state?: string }) => void
|
|
158
|
+
const code = new Promise<{ code: string; state?: string }>((resolve) => {
|
|
159
|
+
resolveCode = resolve
|
|
160
|
+
})
|
|
161
|
+
const server = Bun.serve({
|
|
162
|
+
hostname: '127.0.0.1',
|
|
163
|
+
port,
|
|
164
|
+
fetch(req) {
|
|
165
|
+
const url = new URL(req.url)
|
|
166
|
+
if (url.pathname !== '/callback') return new Response('Not found', { status: 404 })
|
|
167
|
+
const parsed = parseCodeInput(url)
|
|
168
|
+
if (parsed === null) return new Response('Missing OAuth code', { status: 400 })
|
|
169
|
+
resolveCode(parsed)
|
|
170
|
+
return new Response('TypeClaw MCP OAuth complete. You can close this tab.')
|
|
171
|
+
},
|
|
172
|
+
})
|
|
173
|
+
return { code, stop: () => server.stop(true) }
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function renderAuthorizationUrl(serverName: string, url: URL): void {
|
|
177
|
+
note(
|
|
178
|
+
[
|
|
179
|
+
`Open this URL in your browser to authenticate MCP server "${serverName}".`,
|
|
180
|
+
'',
|
|
181
|
+
'If the browser cannot reach localhost after sign-in, copy the full redirect URL or code and paste it below.',
|
|
182
|
+
].join('\n'),
|
|
183
|
+
'MCP OAuth',
|
|
184
|
+
)
|
|
185
|
+
console.log(url.toString())
|
|
186
|
+
console.log('')
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function openBrowserBestEffort(url: URL): void {
|
|
190
|
+
const command = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'cmd' : 'xdg-open'
|
|
191
|
+
const args = process.platform === 'win32' ? ['/c', 'start', '', url.toString()] : [url.toString()]
|
|
192
|
+
const child = spawn(command, args, { stdio: 'ignore', detached: true })
|
|
193
|
+
child.on('error', () => undefined)
|
|
194
|
+
child.unref()
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
async function promptForCodeOrUrl(): Promise<{ code: string; state?: string }> {
|
|
198
|
+
const value = await text({
|
|
199
|
+
message: 'After signing in, paste the code or full redirect URL:',
|
|
200
|
+
placeholder: 'code, or http://localhost:1456/callback?code=...&state=...',
|
|
201
|
+
})
|
|
202
|
+
if (isCancel(value)) throw new Error('OAuth login cancelled by user')
|
|
203
|
+
const parsed = parseCodeInput(value)
|
|
204
|
+
if (parsed === null) throw new Error('OAuth callback did not include a code')
|
|
205
|
+
return parsed
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function parseCodeInput(input: string | URL): { code: string; state?: string } | null {
|
|
209
|
+
if (input instanceof URL) {
|
|
210
|
+
const code = input.searchParams.get('code')
|
|
211
|
+
if (code === null || code.trim() === '') return null
|
|
212
|
+
const state = input.searchParams.get('state') ?? undefined
|
|
213
|
+
return { code, ...(state === undefined ? {} : { state }) }
|
|
214
|
+
}
|
|
215
|
+
const trimmed = input.trim()
|
|
216
|
+
if (trimmed === '') return null
|
|
217
|
+
try {
|
|
218
|
+
return parseCodeInput(new URL(trimmed))
|
|
219
|
+
} catch {
|
|
220
|
+
return { code: trimmed }
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
async function verifyMcpAuth(url: string, authProvider: TypeClawMcpOAuthProvider): Promise<void> {
|
|
225
|
+
const client = new Client({ name: 'typeclaw', version: '0.17.0' }, { capabilities: {} })
|
|
226
|
+
try {
|
|
227
|
+
const transport = new StreamableHTTPClientTransport(new URL(url), { authProvider })
|
|
228
|
+
await client.connect(transport)
|
|
229
|
+
await client.listTools()
|
|
230
|
+
} finally {
|
|
231
|
+
await client.close().catch(() => undefined)
|
|
232
|
+
}
|
|
233
|
+
}
|
package/src/hostd/daemon.ts
CHANGED
|
@@ -11,6 +11,7 @@ import {
|
|
|
11
11
|
instagramChannelBlockSchema,
|
|
12
12
|
kakaoChannelBlockSchema,
|
|
13
13
|
lineChannelBlockSchema,
|
|
14
|
+
mcpCredentialSchema,
|
|
14
15
|
slackChannelBlockSchema,
|
|
15
16
|
webexChannelBlockSchema,
|
|
16
17
|
} from '@/secrets/schema'
|
|
@@ -527,19 +528,37 @@ export async function startDaemon(opts: DaemonOptions = {}): Promise<Daemon> {
|
|
|
527
528
|
|
|
528
529
|
const handleSecretsPatch = async (req: {
|
|
529
530
|
containerName: string
|
|
530
|
-
patch:
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
531
|
+
patch:
|
|
532
|
+
| {
|
|
533
|
+
channels:
|
|
534
|
+
| { kakaotalk: unknown }
|
|
535
|
+
| { discord: unknown }
|
|
536
|
+
| { instagram: unknown }
|
|
537
|
+
| { line: unknown }
|
|
538
|
+
| { webex: unknown }
|
|
539
|
+
| { slack: unknown }
|
|
540
|
+
mcp?: never
|
|
541
|
+
}
|
|
542
|
+
| { mcp: { server: unknown; credential: unknown }; channels?: never }
|
|
539
543
|
}): Promise<RpcResponse> =>
|
|
540
544
|
runSerially(req.containerName, async () => {
|
|
541
545
|
const cwd = cwds.get(req.containerName)
|
|
542
546
|
if (!cwd) return { ok: false, reason: `not registered: ${req.containerName}` }
|
|
547
|
+
if (req.patch.mcp !== undefined) {
|
|
548
|
+
const server = req.patch.mcp.server
|
|
549
|
+
if (typeof server !== 'string' || server.length === 0) return { ok: false, reason: 'mcp.server is required' }
|
|
550
|
+
const parsed = mcpCredentialSchema.safeParse(req.patch.mcp.credential)
|
|
551
|
+
if (!parsed.success) {
|
|
552
|
+
return { ok: false, reason: parsed.error.issues.map((issue) => issue.message).join('; ') }
|
|
553
|
+
}
|
|
554
|
+
const backend = new SecretsBackend(join(cwd, 'secrets.json'))
|
|
555
|
+
await backend.updateMcpAsync(async (mcp) => ({
|
|
556
|
+
result: undefined,
|
|
557
|
+
next: { ...mcp, [server]: parsed.data },
|
|
558
|
+
}))
|
|
559
|
+
const result: SecretsPatchResult = { containerName: req.containerName, patched: true }
|
|
560
|
+
return { ok: true, result }
|
|
561
|
+
}
|
|
543
562
|
const channelsPatch = req.patch?.channels
|
|
544
563
|
// Exactly one personal-account channel block per patch. KakaoTalk, LINE,
|
|
545
564
|
// and Webex write their structured account block through this RPC; the
|