typeclaw 0.42.1 → 0.43.1
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 +2 -2
- package/secrets.schema.json +16 -0
- package/src/agent/index.ts +9 -2
- 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 +41 -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 +85 -4
- package/src/channels/adapters/discord.ts +15 -2
- 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/manager.ts +9 -1
- package/src/channels/router.ts +500 -91
- package/src/channels/schema.ts +24 -0
- package/src/channels/types.ts +18 -5
- package/src/cli/channel.ts +40 -13
- 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
|
@@ -62,7 +62,13 @@ import {
|
|
|
62
62
|
saveChannelSessions,
|
|
63
63
|
type ChannelSessionRecord,
|
|
64
64
|
} from './persistence'
|
|
65
|
-
import {
|
|
65
|
+
import {
|
|
66
|
+
ADAPTER_READ_CAPABILITIES,
|
|
67
|
+
QUOTED_REPLY_EXCERPT_MAX_CHARS,
|
|
68
|
+
type AdapterId,
|
|
69
|
+
type ChannelAdapterConfig,
|
|
70
|
+
type ReadCapability,
|
|
71
|
+
} from './schema'
|
|
66
72
|
import type {
|
|
67
73
|
ChannelHistoryMessage,
|
|
68
74
|
ChannelKey,
|
|
@@ -179,6 +185,8 @@ export function disengageReactionEmojiFor(adapter: AdapterId): string {
|
|
|
179
185
|
return DISENGAGE_REACTION_EMOJI_OVERRIDES[adapter] ?? DISENGAGE_REACTION_EMOJI
|
|
180
186
|
}
|
|
181
187
|
|
|
188
|
+
type SilentAckReason = 'skip_response' | 'no_reply' | 'skip_response_text_leak'
|
|
189
|
+
|
|
182
190
|
// Wake nudge pushed into a resumed channel session at boot so drain() has a
|
|
183
191
|
// non-empty batch and fires a turn. The substantive instruction the model acts
|
|
184
192
|
// on is the `typeclaw.restart-self` entry already in the reopened JSONL (pi
|
|
@@ -251,6 +259,35 @@ export const CHANNEL_EMPTY_TURN_RETRY_MAX_OUTPUT_TOKENS = 16384
|
|
|
251
259
|
// thrashed the send path, so a re-prompt would just re-thrash; they skip
|
|
252
260
|
// straight to the fallback. See validateChannelTurn's candidate===null branch.
|
|
253
261
|
export const MAX_EMPTY_TURN_RETRIES = 2
|
|
262
|
+
|
|
263
|
+
// Separate, tiny budget for the tool-call-leak self-correction retry. Kept
|
|
264
|
+
// apart from MAX_EMPTY_TURN_RETRIES so a persistently-leaking model cannot
|
|
265
|
+
// consume the empty-turn budget (or vice versa) and so it can't livelock: one
|
|
266
|
+
// nudged retry, then on a second leak we suppress and stay silent. A leaked
|
|
267
|
+
// call is a clean protocol miss, not budget exhaustion — one reminder is
|
|
268
|
+
// usually enough, and silence is safer than an unbounded re-prompt loop.
|
|
269
|
+
export const MAX_TOOL_LEAK_RETRIES = 1
|
|
270
|
+
// Reminder-only nudge injected before a tool-call-leak retry. The model wrote a
|
|
271
|
+
// tool call as its visible message text instead of actually calling the tool,
|
|
272
|
+
// so we suppressed the plumbing and ask it to redo the turn properly. Same
|
|
273
|
+
// SYSTEM MESSAGE framing as the other reminder-only nudges.
|
|
274
|
+
export const TOOL_CALL_LEAK_NUDGE = [
|
|
275
|
+
'---',
|
|
276
|
+
'**[SYSTEM MESSAGE — not from a human]**',
|
|
277
|
+
'',
|
|
278
|
+
'Your previous turn wrote a tool call (e.g. `channel_reply(...)`,',
|
|
279
|
+
'`channel_react(...)`, `skip_response(...)`) as plain message TEXT instead of',
|
|
280
|
+
'actually invoking the tool. That text was suppressed — it was NOT sent to the',
|
|
281
|
+
'channel — because raw tool-call syntax must never be posted as a message. This',
|
|
282
|
+
'is an automated signal from the channel router, not a message from anyone in',
|
|
283
|
+
'the chat. **Do not acknowledge or reply to this notice itself.**',
|
|
284
|
+
'',
|
|
285
|
+
'Redo the turn correctly: to reply, call your channel reply tool; to react or',
|
|
286
|
+
'disengage, call that tool; to stay silent, call `skip_response({ reason })`.',
|
|
287
|
+
'Emit a real tool call — do not type its syntax as your answer.',
|
|
288
|
+
'',
|
|
289
|
+
'---',
|
|
290
|
+
].join('\n')
|
|
254
291
|
// Reminder-only nudge injected before an empty-turn retry. Uses the repo's
|
|
255
292
|
// SYSTEM MESSAGE framing (see composeTurnPrompt) so persona-rich models do not
|
|
256
293
|
// reply to the notice itself. Names the actual failure (the prior turn ran out
|
|
@@ -656,6 +693,11 @@ type ChannelAgentSession = AgentSession & { getAbortReason?: () => string | unde
|
|
|
656
693
|
type LiveSession = {
|
|
657
694
|
key: ChannelKey
|
|
658
695
|
keyId: string
|
|
696
|
+
// Structural room shape from the inbound (thread + optional parent channel).
|
|
697
|
+
// Kept on the session so membership scoping can reach the parent channel for
|
|
698
|
+
// platforms (Discord) where the thread is its own channel and the key alone
|
|
699
|
+
// cannot express "this is a thread in channel X". Updated per inbound in route().
|
|
700
|
+
room: InboundMessage['room']
|
|
659
701
|
session: ChannelAgentSession
|
|
660
702
|
activeModelRef: ReturnType<typeof resolveFallbackChain>[number]
|
|
661
703
|
// The session's creation-time thinking level, captured once. A later escalated
|
|
@@ -706,6 +748,13 @@ type LiveSession = {
|
|
|
706
748
|
typingStartedAt: number
|
|
707
749
|
typingTimedOut: boolean
|
|
708
750
|
typingStopPromise: Promise<void> | null
|
|
751
|
+
// Monotonic heartbeat generation. Captured when a heartbeat starts and
|
|
752
|
+
// bumped when it stops. `clearInterval` cannot cancel a timer callback that
|
|
753
|
+
// already came due, so a stale 'tick' can still run AFTER stopTypingHeartbeat
|
|
754
|
+
// enqueued its clear — on Slack that re-sets "is typing..." after the empty-
|
|
755
|
+
// string clear and strands the indicator (Slack's status has no auto-expiry).
|
|
756
|
+
// A 'tick' fired with a stale epoch is dropped before it reaches the adapter.
|
|
757
|
+
typingEpoch: number
|
|
709
758
|
// True only while `live.session.prompt()` is actively running. Gates the
|
|
710
759
|
// deferred typing revival: a revival queued behind an in-flight cap-trip
|
|
711
760
|
// 'stop' must NOT re-arm the heartbeat once the prompt has finished, or it
|
|
@@ -736,6 +785,22 @@ type LiveSession = {
|
|
|
736
785
|
// batch several inbounds that each got their own :eyes:, so every entry is
|
|
737
786
|
// removed after the reply. Empty on turns with no reactable inbound.
|
|
738
787
|
currentTurnEngageReactions: Array<Promise<ReactionRef | null>>
|
|
788
|
+
// Model-requested `channel_react` reactions for THIS turn, held until the turn
|
|
789
|
+
// ends. Flushed to the adapter only if the agent actually replied this turn;
|
|
790
|
+
// discarded on silence (skip_response / empty / errored turns) so the bot never
|
|
791
|
+
// leaves a reaction on a message it merely looked at (e.g. cron lookaround).
|
|
792
|
+
pendingTurnReactions: ReactionRequest[]
|
|
793
|
+
// Armed by `validateChannelTurn` on a DELIBERATE silent turn (skip_response or
|
|
794
|
+
// an explicit NO_REPLY), stamped with `turnSeq` so a stale flag from a crashed
|
|
795
|
+
// turn cannot leak into the next one. Read in drain's per-turn finally — AFTER
|
|
796
|
+
// the transient engage :eyes: is dropped — to leave a PERSISTENT :eyes: on the
|
|
797
|
+
// triggering message: "I saw this and intentionally chose not to reply." Null
|
|
798
|
+
// on every non-deliberate outcome (a real reply, a model malfunction, a
|
|
799
|
+
// plumbing leak, a retry, a synthetic turn). Firing after the engage-drop is
|
|
800
|
+
// load-bearing: adapters that collapse a same-actor same-emoji reaction into
|
|
801
|
+
// one toggle would otherwise have the engage-drop remove the only visible
|
|
802
|
+
// :eyes:. See `reactOnSilentAck`.
|
|
803
|
+
silentAckTurn: { turnSeq: number; reason: SilentAckReason } | null
|
|
739
804
|
lastTurnAuthorIds: Set<string>
|
|
740
805
|
// Mirror of currentTurnAuthorId at end-of-turn (the LAST speaker of the
|
|
741
806
|
// prior batch), preserved across the drain finally-block which resets
|
|
@@ -830,6 +895,11 @@ type LiveSession = {
|
|
|
830
895
|
// increments it before injecting EMPTY_TURN_RETRY_NUDGE and reads it to decide
|
|
831
896
|
// retry-vs-fallback. See the candidate===null branch.
|
|
832
897
|
emptyTurnRetries: number
|
|
898
|
+
// Count of tool-call-leak self-correction re-prompts spent this logical turn,
|
|
899
|
+
// bounded by MAX_TOOL_LEAK_RETRIES. Separate from emptyTurnRetries so the two
|
|
900
|
+
// failure modes can't drain each other's budget. Reset with the rest on a
|
|
901
|
+
// fresh user batch.
|
|
902
|
+
toolLeakRetries: number
|
|
833
903
|
// Latches once a bare-empty `stop` has been classified as empty-stop-after-tool-work
|
|
834
904
|
// this logical turn. The recovery nudge tells the model NOT to re-run its tools, so
|
|
835
905
|
// a compliant retry is expected to land another bare-empty `stop` with NO new tool
|
|
@@ -1031,6 +1101,11 @@ export type ChannelRouter = {
|
|
|
1031
1101
|
registerReaction: (adapter: ChannelKey['adapter'], cb: ReactionCallback) => void
|
|
1032
1102
|
unregisterReaction: (adapter: ChannelKey['adapter'], cb: ReactionCallback) => void
|
|
1033
1103
|
react: (req: ReactionRequest) => Promise<ReactionResult>
|
|
1104
|
+
// Buffer a model-requested reaction for the current turn instead of firing it
|
|
1105
|
+
// immediately. It reaches the adapter only if the agent actually replies this
|
|
1106
|
+
// turn (drain's finally); a silent/skipped turn discards it. Keeps the bot from
|
|
1107
|
+
// leaving reactions on messages it looked at but never answered.
|
|
1108
|
+
queueReactionAfterReply: (req: ReactionRequest) => Promise<ReactionResult>
|
|
1034
1109
|
registerRemoveReaction: (adapter: ChannelKey['adapter'], cb: RemoveReactionCallback) => void
|
|
1035
1110
|
unregisterRemoveReaction: (adapter: ChannelKey['adapter'], cb: RemoveReactionCallback) => void
|
|
1036
1111
|
removeReaction: (req: RemoveReactionRequest) => Promise<ReactionResult>
|
|
@@ -1041,6 +1116,17 @@ export type ChannelRouter = {
|
|
|
1041
1116
|
// the wrong signal. autoReactOnEngage reads this to post :eyes: only as a
|
|
1042
1117
|
// fallback when no visible typing exists. Unset defaults to false.
|
|
1043
1118
|
setTypingCapability: (adapter: ChannelKey['adapter'], supported: boolean) => void
|
|
1119
|
+
// Set by the manager for every adapter present in typeclaw.json#channels,
|
|
1120
|
+
// independent of whether the adapter's start() succeeded (a failed login never
|
|
1121
|
+
// registers callbacks). Combined with the adapter's static read-capability set
|
|
1122
|
+
// (ADAPTER_READ_CAPABILITIES), fetchHistory/getMessage/listChannels tell three
|
|
1123
|
+
// cases apart for a missing callback: not configured → *-not-supported;
|
|
1124
|
+
// configured but the capability isn't one this adapter implements →
|
|
1125
|
+
// *-not-supported; configured AND the adapter should implement it but no
|
|
1126
|
+
// callback is live (e.g. auth failure at startup) → *-adapter-unavailable. So
|
|
1127
|
+
// the agent only sees the actionable error when re-auth would actually help.
|
|
1128
|
+
// Unset defaults to not-configured.
|
|
1129
|
+
setAdapterConfigured: (adapter: ChannelKey['adapter'], configured: boolean) => void
|
|
1044
1130
|
registerChannelNameResolver: (adapter: ChannelKey['adapter'], resolver: ChannelNameResolver) => void
|
|
1045
1131
|
unregisterChannelNameResolver: (adapter: ChannelKey['adapter'], resolver: ChannelNameResolver) => void
|
|
1046
1132
|
// Self-identity is a per-adapter singleton (one bot account per adapter),
|
|
@@ -1194,6 +1280,8 @@ export type ChannelRouter = {
|
|
|
1194
1280
|
flushDebounce: (key: ChannelKey) => Promise<void>
|
|
1195
1281
|
fireTypingHeartbeat: (key: ChannelKey, phase?: 'tick' | 'stop') => Promise<void>
|
|
1196
1282
|
fireTypingInterval: (key: ChannelKey) => Promise<void>
|
|
1283
|
+
fireTypingTick: (key: ChannelKey, epoch: number) => Promise<void>
|
|
1284
|
+
typingEpoch: (key: ChannelKey) => number | undefined
|
|
1197
1285
|
isTypingActive: (key: ChannelKey) => boolean
|
|
1198
1286
|
stopTyping: (key: ChannelKey) => Promise<void>
|
|
1199
1287
|
runIdleGc: () => Promise<void>
|
|
@@ -1396,6 +1484,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
1396
1484
|
const removeReactionCallbacks = new Map<ChannelKey['adapter'], Set<RemoveReactionCallback>>()
|
|
1397
1485
|
const typingCallbacks = new Map<ChannelKey['adapter'], Set<TypingCallback>>()
|
|
1398
1486
|
const typingCapableAdapters = new Set<ChannelKey['adapter']>()
|
|
1487
|
+
const configuredAdapters = new Set<ChannelKey['adapter']>()
|
|
1399
1488
|
const channelNameResolvers = new Map<ChannelKey['adapter'], Set<ChannelNameResolver>>()
|
|
1400
1489
|
const membershipResolvers = new Map<ChannelKey['adapter'], Set<MembershipResolver>>()
|
|
1401
1490
|
const selfIdentityResolvers = new Map<ChannelKey['adapter'], ChannelSelfIdentityResolver>()
|
|
@@ -1561,16 +1650,37 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
1561
1650
|
return merged
|
|
1562
1651
|
}
|
|
1563
1652
|
|
|
1564
|
-
|
|
1653
|
+
// Membership is a ROOM property, not a thread property: every human in the
|
|
1654
|
+
// parent channel can see and join a thread, so a thread has the same
|
|
1655
|
+
// effective human count as its parent channel. The engagement key carries the
|
|
1656
|
+
// thread suffix (`channelKeyId`) to give each thread its own live session and
|
|
1657
|
+
// sticky ledger, but scoping membership by that same key would give a fresh
|
|
1658
|
+
// thread a cold, thread-local count (≤1) and misfire the solo-human fallback.
|
|
1659
|
+
// Resolve/cache/invalidate membership under the PARENT-channel key so a thread
|
|
1660
|
+
// reuses the channel's warm count. Two platform shapes:
|
|
1661
|
+
// - Slack: the thread ts rides `key.thread`, so stripping it to null reaches
|
|
1662
|
+
// the parent channel (`key.chat` is already the parent).
|
|
1663
|
+
// - Discord: the thread is its OWN channel (`key.chat` = thread id,
|
|
1664
|
+
// `key.thread` = null), so we must repoint `chat` to `room.parentChat`.
|
|
1665
|
+
// DMs keep their own key — a DM's `@dm` workspace short-circuits before this.
|
|
1666
|
+
const membershipScopeKey = (key: ChannelKey, room?: InboundMessage['room']): ChannelKey => {
|
|
1667
|
+
if (key.workspace === '@dm') return key
|
|
1668
|
+
if (room?.parentChat !== undefined) return { ...key, chat: room.parentChat, thread: null }
|
|
1669
|
+
return key.thread === null ? key : { ...key, thread: null }
|
|
1670
|
+
}
|
|
1671
|
+
|
|
1672
|
+
const readMembership = (key: ChannelKey, room?: InboundMessage['room']): MembershipCount | null => {
|
|
1565
1673
|
if (key.workspace === '@dm') return dmMembership(now())
|
|
1566
|
-
|
|
1674
|
+
const scoped = membershipScopeKey(key, room)
|
|
1675
|
+
return membershipCaches.get(scoped.adapter)?.get(scoped) ?? null
|
|
1567
1676
|
}
|
|
1568
1677
|
|
|
1569
|
-
const warmMembership = (key: ChannelKey): Promise<MembershipCount | null> | null => {
|
|
1678
|
+
const warmMembership = (key: ChannelKey, room?: InboundMessage['room']): Promise<MembershipCount | null> | null => {
|
|
1570
1679
|
if (key.workspace === '@dm') return Promise.resolve(dmMembership(now()))
|
|
1571
|
-
const
|
|
1680
|
+
const scoped = membershipScopeKey(key, room)
|
|
1681
|
+
const cache = membershipCaches.get(scoped.adapter)
|
|
1572
1682
|
if (cache === undefined) return null
|
|
1573
|
-
return cache.warmUp(
|
|
1683
|
+
return cache.warmUp(scoped)
|
|
1574
1684
|
}
|
|
1575
1685
|
|
|
1576
1686
|
const resolveThroughRegisteredMembership = async (key: ChannelKey): Promise<MembershipResolverResult> => {
|
|
@@ -1599,22 +1709,23 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
1599
1709
|
|
|
1600
1710
|
const membershipForEngagement = async (live: LiveSession): Promise<MembershipCount | null> => {
|
|
1601
1711
|
if (live.key.workspace === '@dm') return dmMembership(now())
|
|
1602
|
-
const
|
|
1712
|
+
const scoped = membershipScopeKey(live.key, live.room)
|
|
1713
|
+
const cache = membershipCaches.get(scoped.adapter)
|
|
1603
1714
|
if (cache === undefined) return null
|
|
1604
1715
|
|
|
1605
|
-
const cached = cache.read(
|
|
1716
|
+
const cached = cache.read(scoped)
|
|
1606
1717
|
if (cached.kind === 'hit') return cached.membership
|
|
1607
1718
|
if (cached.kind === 'stale') {
|
|
1608
|
-
void cache.warmUp(
|
|
1719
|
+
void cache.warmUp(scoped).catch((err) => {
|
|
1609
1720
|
logger.warn(`[channels] membership refresh failed for ${live.keyId}: ${describe(err)}`)
|
|
1610
1721
|
})
|
|
1611
1722
|
return cached.membership
|
|
1612
1723
|
}
|
|
1613
1724
|
|
|
1614
|
-
const fetchPromise = live.membershipFetch ?? warmMembership(live.key)
|
|
1725
|
+
const fetchPromise = live.membershipFetch ?? warmMembership(live.key, live.room)
|
|
1615
1726
|
live.membershipFetch = fetchPromise
|
|
1616
1727
|
if (fetchPromise === null) return null
|
|
1617
|
-
const membership = await withMembershipTimeout(fetchPromise,
|
|
1728
|
+
const membership = await withMembershipTimeout(fetchPromise, scoped, logger)
|
|
1618
1729
|
if (live.membershipFetch === fetchPromise) live.membershipFetch = null
|
|
1619
1730
|
return membership
|
|
1620
1731
|
}
|
|
@@ -1674,6 +1785,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
1674
1785
|
// is persisted only through the normal success path below — no pre-mutation
|
|
1675
1786
|
// — so a reopen failure leaves the durable mapping untouched.
|
|
1676
1787
|
resumeTarget?: { sessionId: string; sessionFile: string },
|
|
1788
|
+
// Inbound room shape, passed so the COLD-START membership warm below is
|
|
1789
|
+
// parent-scoped from the first fetch (Discord threads resolve `chat` to the
|
|
1790
|
+
// thread id, so an unscoped warm would prime the cache against the thread).
|
|
1791
|
+
room?: InboundMessage['room'],
|
|
1677
1792
|
): Promise<LiveSession> => {
|
|
1678
1793
|
const keyId = channelKeyId(key)
|
|
1679
1794
|
const existing = liveSessions.get(keyId)
|
|
@@ -1777,7 +1892,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
1777
1892
|
const phase = resolvedRecord?.sessionId === undefined ? 'cold-start' : 'rehydrate'
|
|
1778
1893
|
logger.info(`[channels] ${keyId}: ensureLive begin (${phase})`)
|
|
1779
1894
|
const participants = (resolvedRecord?.participants ?? []) as ChannelParticipant[]
|
|
1780
|
-
const membershipFetch = warmMembership(key)
|
|
1895
|
+
const membershipFetch = warmMembership(key, room)
|
|
1781
1896
|
// Independent platform lookups — overlap so the chain pays max(), not sum().
|
|
1782
1897
|
const [resolvedNames, membership] = await Promise.all([
|
|
1783
1898
|
resolveChannelNames(key),
|
|
@@ -1857,6 +1972,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
1857
1972
|
const live: LiveSession = {
|
|
1858
1973
|
key,
|
|
1859
1974
|
keyId,
|
|
1975
|
+
room,
|
|
1860
1976
|
session: created.session,
|
|
1861
1977
|
activeModelRef: resolveFallbackChain(getConfig().models, undefined)[0]!,
|
|
1862
1978
|
turnThinkingDefault: created.session.thinkingLevel,
|
|
@@ -1881,6 +1997,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
1881
1997
|
typingStartedAt: 0,
|
|
1882
1998
|
typingTimedOut: false,
|
|
1883
1999
|
typingStopPromise: null,
|
|
2000
|
+
typingEpoch: 0,
|
|
1884
2001
|
promptInFlight: false,
|
|
1885
2002
|
lastInboundAt: now(),
|
|
1886
2003
|
baseContextBytes: 0,
|
|
@@ -1890,6 +2007,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
1890
2007
|
currentTurnReactionRef: null,
|
|
1891
2008
|
currentTurnTypingThread: null,
|
|
1892
2009
|
currentTurnEngageReactions: [],
|
|
2010
|
+
pendingTurnReactions: [],
|
|
2011
|
+
silentAckTurn: null,
|
|
1893
2012
|
// `lastTurnAuthorId` (string, used for `lastInboundAuthorId` in
|
|
1894
2013
|
// origin) and `lastTurnAuthorIds` (Set, used by
|
|
1895
2014
|
// `grantStickyForReplyTargets` as the fallback when
|
|
@@ -1913,6 +2032,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
1913
2032
|
inFlightToolSends: new Map(),
|
|
1914
2033
|
policyDeniedToolSendsThisTurn: new Map(),
|
|
1915
2034
|
emptyTurnRetries: 0,
|
|
2035
|
+
toolLeakRetries: 0,
|
|
1916
2036
|
emptyStopAfterToolWorkArmed: false,
|
|
1917
2037
|
willingnessNudges: 0,
|
|
1918
2038
|
lastTerminalReplyAbort: null,
|
|
@@ -2145,7 +2265,12 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2145
2265
|
await persist()
|
|
2146
2266
|
}
|
|
2147
2267
|
|
|
2148
|
-
const fireTyping = async (live: LiveSession, phase: 'tick' | 'stop'): Promise<void> => {
|
|
2268
|
+
const fireTyping = async (live: LiveSession, phase: 'tick' | 'stop', epoch?: number): Promise<void> => {
|
|
2269
|
+
// Drop a stale 'tick' that a since-cancelled interval still dispatched:
|
|
2270
|
+
// once the heartbeat stopped (or a new one started) the captured epoch no
|
|
2271
|
+
// longer matches, and forwarding it would re-set the indicator after the
|
|
2272
|
+
// stop clear. 'stop' is never epoch-gated — it must always clear.
|
|
2273
|
+
if (phase === 'tick' && epoch !== undefined && epoch !== live.typingEpoch) return
|
|
2149
2274
|
const callbacks = typingCallbacks.get(live.key.adapter)
|
|
2150
2275
|
if (!callbacks || callbacks.size === 0) return
|
|
2151
2276
|
// Snapshot before iterating: a callback could unregister mid-call.
|
|
@@ -2311,11 +2436,16 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2311
2436
|
bumpTypingActivity(live)
|
|
2312
2437
|
return
|
|
2313
2438
|
}
|
|
2439
|
+
const epoch = ++live.typingEpoch
|
|
2314
2440
|
live.typingStartedAt = now()
|
|
2315
2441
|
// Fire immediately so the indicator appears on the very first inbound,
|
|
2316
2442
|
// not 8 seconds later.
|
|
2317
|
-
void fireTyping(live, 'tick')
|
|
2443
|
+
void fireTyping(live, 'tick', epoch)
|
|
2318
2444
|
live.typingTimer = setInterval(() => {
|
|
2445
|
+
// A due callback can run one last time after stopTypingHeartbeat's
|
|
2446
|
+
// clearInterval; the epoch mismatch makes fireTyping drop the tick so it
|
|
2447
|
+
// can't re-set the indicator after the stop clear.
|
|
2448
|
+
if (epoch !== live.typingEpoch) return
|
|
2319
2449
|
if (live.destroyed) {
|
|
2320
2450
|
void stopTypingHeartbeat(live)
|
|
2321
2451
|
return
|
|
@@ -2328,11 +2458,15 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2328
2458
|
void stopTypingHeartbeat(live)
|
|
2329
2459
|
return
|
|
2330
2460
|
}
|
|
2331
|
-
void fireTyping(live, 'tick')
|
|
2461
|
+
void fireTyping(live, 'tick', epoch)
|
|
2332
2462
|
}, TYPING_HEARTBEAT_MS)
|
|
2333
2463
|
}
|
|
2334
2464
|
|
|
2335
2465
|
const stopTypingHeartbeat = async (live: LiveSession): Promise<void> => {
|
|
2466
|
+
// Bump first, before any early return: a stop must invalidate the current
|
|
2467
|
+
// generation so a due-but-not-yet-run interval tick is dropped by
|
|
2468
|
+
// fireTyping's epoch guard even if the timer was already cleared.
|
|
2469
|
+
live.typingEpoch++
|
|
2336
2470
|
if (!live.typingTimer) {
|
|
2337
2471
|
await live.typingStopPromise
|
|
2338
2472
|
return
|
|
@@ -2538,6 +2672,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2538
2672
|
try {
|
|
2539
2673
|
while ((live.promptQueue.length > 0 || live.pendingSystemReminders.length > 0) && !live.destroyed) {
|
|
2540
2674
|
live.typingTimedOut = false
|
|
2675
|
+
// Each turn starts with no held reactions; the model re-requests them
|
|
2676
|
+
// via channel_react during this turn, and the finally flushes or drops.
|
|
2677
|
+
live.pendingTurnReactions = []
|
|
2541
2678
|
// Heartbeat must run during generation as well as during debounce.
|
|
2542
2679
|
// Because new inbounds during a turn just push into promptQueue
|
|
2543
2680
|
// without re-entering route(), the route() call site alone wouldn't
|
|
@@ -2577,6 +2714,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2577
2714
|
// iterations the retry itself queues do not refill the budget and loop
|
|
2578
2715
|
// forever (and the raised cap stays scoped to the turn that set it).
|
|
2579
2716
|
live.emptyTurnRetries = 0
|
|
2717
|
+
live.toolLeakRetries = 0
|
|
2580
2718
|
live.emptyStopAfterToolWorkArmed = false
|
|
2581
2719
|
live.willingnessNudges = 0
|
|
2582
2720
|
live.abortReasonThisTurn = null
|
|
@@ -2626,6 +2764,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2626
2764
|
const promptStart = now()
|
|
2627
2765
|
const successfulSendsBeforePrompt = live.successfulChannelSends
|
|
2628
2766
|
const emptyTurnRetriesBeforePrompt = live.emptyTurnRetries
|
|
2767
|
+
const toolLeakRetriesBeforePrompt = live.toolLeakRetries
|
|
2629
2768
|
const engageAddPromises = live.currentTurnEngageReactions
|
|
2630
2769
|
live.turnSeq++
|
|
2631
2770
|
live.successfulSendsAtTurnStart = successfulSendsBeforePrompt
|
|
@@ -2675,14 +2814,19 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2675
2814
|
// usable assistant reply (real model prose the user saw) seeds the next
|
|
2676
2815
|
// turn's escalation. Every other terminal outcome CLEARS lastQuestionSignal
|
|
2677
2816
|
// so an older question can't leak across the failed/silent turn:
|
|
2678
|
-
// - retry queued (`length`/`aborted`, budget left
|
|
2679
|
-
//
|
|
2817
|
+
// - retry queued (`length`/`aborted`, budget left, OR a tool-call
|
|
2818
|
+
// leak nudged a self-correction retry): turn still in flight →
|
|
2819
|
+
// leave both for the reminder-only iteration that ends it.
|
|
2680
2820
|
// - usable reply → commit the pending signal.
|
|
2681
2821
|
// - provider error / empty-turn fallback / NO_REPLY / skip (no usable
|
|
2682
2822
|
// reply) → clear BOTH (pending and lastQuestionSignal).
|
|
2683
2823
|
// A fallback sends via source:'system', which also bumps
|
|
2684
|
-
// successfulChannelSends, so it must be excluded explicitly.
|
|
2685
|
-
|
|
2824
|
+
// successfulChannelSends, so it must be excluded explicitly. Both retry
|
|
2825
|
+
// budgets keep the logical turn open, so both must count here — a
|
|
2826
|
+
// tool-leak retry that later replies must commit the signal AT the
|
|
2827
|
+
// successful retry, not clear it after the first suppressed attempt.
|
|
2828
|
+
const retryQueuedThisTurn =
|
|
2829
|
+
live.emptyTurnRetries > emptyTurnRetriesBeforePrompt || live.toolLeakRetries > toolLeakRetriesBeforePrompt
|
|
2686
2830
|
const providerErrorThisTurn = assistantLeafStopReason(live.session) === 'error'
|
|
2687
2831
|
const fallbackPostedThisTurn = live.emptyTurnFallbackTurn === live.turnSeq
|
|
2688
2832
|
const sentReplyThisTurn = live.successfulChannelSends > successfulSendsBeforePrompt
|
|
@@ -2713,9 +2857,42 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2713
2857
|
} finally {
|
|
2714
2858
|
live.promptInFlight = false
|
|
2715
2859
|
const sentReplyThisTurn = live.successfulChannelSends > successfulSendsBeforePrompt
|
|
2716
|
-
|
|
2717
|
-
|
|
2718
|
-
|
|
2860
|
+
// The eager :eyes: ack is a "looking at this" signal, not a "replied"
|
|
2861
|
+
// one, so it comes off at turn end no matter the outcome — a reply, but
|
|
2862
|
+
// also silence, skip_response, an empty turn, or a provider error
|
|
2863
|
+
// (observe-after-engage). Leaving it only on the reply path stranded the
|
|
2864
|
+
// ack permanently on messages the agent looked at but never answered.
|
|
2865
|
+
const dropDone = dropEngageReactions(live, engageAddPromises)
|
|
2866
|
+
// A DELIBERATE silent turn (skip_response / NO_REPLY) leaves a
|
|
2867
|
+
// PERSISTENT :eyes: acking "seen, intentionally not replying". On a
|
|
2868
|
+
// typing-less adapter it reuses the same message/emoji/actor as the
|
|
2869
|
+
// transient engage :eyes:, and adapters that collapse that into one
|
|
2870
|
+
// toggle would let a still-in-flight engage removal strip the ack — so
|
|
2871
|
+
// the silent path AWAITS every engage removal reaching the adapter
|
|
2872
|
+
// before adding the persistent one. Only silent turns pay that wait:
|
|
2873
|
+
// normal/reply turns keep the engage drop fire-and-forget (`void`), so
|
|
2874
|
+
// turn-end never blocks on the reaction API off the silent path.
|
|
2875
|
+
if (live.silentAckTurn?.turnSeq === live.turnSeq) await dropDone
|
|
2876
|
+
else void dropDone
|
|
2877
|
+
reactOnSilentAck(live)
|
|
2878
|
+
// Held channel_react reactions apply only when the agent posted a
|
|
2879
|
+
// genuine reply this turn — NOT an empty-turn fallback or provider-
|
|
2880
|
+
// error notice, both of which send via source:'system' and bump
|
|
2881
|
+
// successfulChannelSends. Otherwise a silent/skipped/errored turn
|
|
2882
|
+
// would still stamp a reaction on a message it never really answered.
|
|
2883
|
+
// Computed BEFORE maybePostDeferredProviderError so its error send
|
|
2884
|
+
// cannot flip the decision.
|
|
2885
|
+
const usableReplyThisTurn =
|
|
2886
|
+
sentReplyThisTurn &&
|
|
2887
|
+
live.emptyTurnFallbackTurn !== live.turnSeq &&
|
|
2888
|
+
assistantLeafStopReason(live.session) !== 'error'
|
|
2889
|
+
if (usableReplyThisTurn) flushPendingReactions(live)
|
|
2890
|
+
else live.pendingTurnReactions = []
|
|
2891
|
+
// Either retry budget keeps the turn in flight, so a deferred provider
|
|
2892
|
+
// error must wait for the reminder-only iteration that actually ends it.
|
|
2893
|
+
const retryQueuedThisTurn =
|
|
2894
|
+
live.emptyTurnRetries > emptyTurnRetriesBeforePrompt || live.toolLeakRetries > toolLeakRetriesBeforePrompt
|
|
2895
|
+
await maybePostDeferredProviderError(live, sentReplyThisTurn, retryQueuedThisTurn)
|
|
2719
2896
|
await fireSessionTurnEnd(live)
|
|
2720
2897
|
}
|
|
2721
2898
|
await fireSessionIdle(live)
|
|
@@ -2732,6 +2909,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2732
2909
|
live.currentTurnAuthorIds = new Set()
|
|
2733
2910
|
live.currentTurnReactionRef = null
|
|
2734
2911
|
live.currentTurnEngageReactions = []
|
|
2912
|
+
// Drop any still-held reactions if the loop exited without running the
|
|
2913
|
+
// per-turn finally (e.g. session destroyed mid-drain): never leave a
|
|
2914
|
+
// reaction attached to a turn that never completed a reply.
|
|
2915
|
+
live.pendingTurnReactions = []
|
|
2735
2916
|
live.currentTurnAttachments = []
|
|
2736
2917
|
// Reset AFTER stopTypingHeartbeat: its final 'stop' tick reads the anchor
|
|
2737
2918
|
// to clear a flat-DM status; clearing it first would strand the indicator.
|
|
@@ -2941,7 +3122,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2941
3122
|
const reservation = restartReservations.get(channelKeyId(key))
|
|
2942
3123
|
if (reservation !== undefined) reservation.sawInbound = true
|
|
2943
3124
|
|
|
2944
|
-
const live = await ensureLive(key, event.externalMessageId, event.authorId)
|
|
3125
|
+
const live = await ensureLive(key, event.externalMessageId, event.authorId, undefined, event.room)
|
|
3126
|
+
live.room = event.room
|
|
2945
3127
|
|
|
2946
3128
|
const isNewAuthor = !live.participants.some((p) => p.authorId === event.authorId)
|
|
2947
3129
|
live.participants = updateParticipants(
|
|
@@ -2960,10 +3142,11 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2960
3142
|
// *next* turn sees fresh data, but the current turn still gets a
|
|
2961
3143
|
// fast answer (cache miss → cold fetch with timeout, or stale-ok).
|
|
2962
3144
|
if (isNewAuthor && live.key.workspace !== '@dm') {
|
|
2963
|
-
const
|
|
3145
|
+
const scoped = membershipScopeKey(live.key, live.room)
|
|
3146
|
+
const cache = membershipCaches.get(scoped.adapter)
|
|
2964
3147
|
if (cache !== undefined) {
|
|
2965
|
-
cache.invalidate(
|
|
2966
|
-
void cache.warmUp(
|
|
3148
|
+
cache.invalidate(scoped)
|
|
3149
|
+
void cache.warmUp(scoped).catch((err) => {
|
|
2967
3150
|
logger.warn(`[channels] membership warmup after new author failed for ${live.keyId}: ${describe(err)}`)
|
|
2968
3151
|
})
|
|
2969
3152
|
}
|
|
@@ -3128,6 +3311,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3128
3311
|
event: InboundMessage,
|
|
3129
3312
|
engageReaction: Promise<ReactionRef | null> | null,
|
|
3130
3313
|
): void => {
|
|
3314
|
+
clearQueuedEngageReactions(live)
|
|
3131
3315
|
live.promptQueue.push({
|
|
3132
3316
|
text: event.text,
|
|
3133
3317
|
...(event.referenceContext !== undefined ? { referenceContext: event.referenceContext } : {}),
|
|
@@ -3210,6 +3394,41 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3210
3394
|
return lastError ?? { ok: false, error: 'no reaction callback handled request', code: 'unsupported' }
|
|
3211
3395
|
}
|
|
3212
3396
|
|
|
3397
|
+
// Hold a model reaction until the turn proves it engaged (i.e. actually
|
|
3398
|
+
// replied). Buffered on the live session for this target; drain's finally
|
|
3399
|
+
// flushes it via react() on a real reply or drops it on silence. No live
|
|
3400
|
+
// session (or a stale ref that is not this turn's trigger) → nothing to pair
|
|
3401
|
+
// the reaction with, so it is refused rather than fired blind.
|
|
3402
|
+
const queueReactionAfterReply = async (req: ReactionRequest): Promise<ReactionResult> => {
|
|
3403
|
+
if (req.reactionRef.adapter !== req.adapter) {
|
|
3404
|
+
return { ok: false, error: 'reaction ref adapter mismatch', code: 'unsupported' }
|
|
3405
|
+
}
|
|
3406
|
+
const live = liveSessions.get(
|
|
3407
|
+
channelKeyId({ adapter: req.adapter, workspace: req.workspace, chat: req.chat, thread: req.thread ?? null }),
|
|
3408
|
+
)
|
|
3409
|
+
if (!live || live.destroyed) {
|
|
3410
|
+
return { ok: false, error: 'no live turn to attach this reaction to', code: 'unsupported' }
|
|
3411
|
+
}
|
|
3412
|
+
live.pendingTurnReactions.push(req)
|
|
3413
|
+
return { ok: true }
|
|
3414
|
+
}
|
|
3415
|
+
|
|
3416
|
+
const flushPendingReactions = (live: LiveSession): void => {
|
|
3417
|
+
const pending = live.pendingTurnReactions
|
|
3418
|
+
live.pendingTurnReactions = []
|
|
3419
|
+
for (const req of pending) {
|
|
3420
|
+
void react(req)
|
|
3421
|
+
.then((result) => {
|
|
3422
|
+
if (!result.ok && result.code !== 'unsupported') {
|
|
3423
|
+
logger.info(`[channels] react-after-reply failed adapter=${req.adapter} chat=${req.chat}: ${result.error}`)
|
|
3424
|
+
}
|
|
3425
|
+
})
|
|
3426
|
+
.catch((err) => {
|
|
3427
|
+
logger.info(`[channels] react-after-reply threw adapter=${req.adapter} chat=${req.chat}: ${describe(err)}`)
|
|
3428
|
+
})
|
|
3429
|
+
}
|
|
3430
|
+
}
|
|
3431
|
+
|
|
3213
3432
|
const removeReaction = async (req: RemoveReactionRequest): Promise<ReactionResult> => {
|
|
3214
3433
|
if (req.reactionRef.adapter !== req.adapter) {
|
|
3215
3434
|
return { ok: false, error: 'reaction ref adapter mismatch', code: 'unsupported' }
|
|
@@ -3263,12 +3482,28 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3263
3482
|
return addReactionRef
|
|
3264
3483
|
}
|
|
3265
3484
|
|
|
3266
|
-
|
|
3267
|
-
|
|
3485
|
+
// Returns a promise that settles only once every engage removal has REACHED
|
|
3486
|
+
// the adapter, not merely been scheduled. The silent-ack path awaits this so
|
|
3487
|
+
// its persistent :eyes: is added strictly AFTER the transient one is removed
|
|
3488
|
+
// (see reactOnSilentAck). Fire-and-forget callers just `void` the result.
|
|
3489
|
+
const dropEngageReactions = (live: LiveSession, addPromises: Array<Promise<ReactionRef | null>>): Promise<void> => {
|
|
3490
|
+
return Promise.all(addPromises.map((addPromise) => dropOneEngageReaction(live, addPromise))).then(() => undefined)
|
|
3491
|
+
}
|
|
3492
|
+
|
|
3493
|
+
// Only the LAST engaging inbound of a coalesced batch should carry the eager
|
|
3494
|
+
// :eyes:. Called from enqueue() before the new inbound is pushed to roll the
|
|
3495
|
+
// ack off earlier queued-but-not-yet-drained inbounds. `delete` (not
|
|
3496
|
+
// overwrite) is load-bearing: a newer engaging inbound that has no reactionRef
|
|
3497
|
+
// must still strip the previous :eyes: rather than leave it stranded.
|
|
3498
|
+
const clearQueuedEngageReactions = (live: LiveSession): void => {
|
|
3499
|
+
const addPromises = live.promptQueue.flatMap((m) => (m.engageReaction !== undefined ? [m.engageReaction] : []))
|
|
3500
|
+
if (addPromises.length === 0) return
|
|
3501
|
+
for (const item of live.promptQueue) delete item.engageReaction
|
|
3502
|
+
void dropEngageReactions(live, addPromises)
|
|
3268
3503
|
}
|
|
3269
3504
|
|
|
3270
|
-
const
|
|
3271
|
-
|
|
3505
|
+
const dropOneEngageReaction = (live: LiveSession, addPromise: Promise<ReactionRef | null>): Promise<void> => {
|
|
3506
|
+
return addPromise
|
|
3272
3507
|
.then((reactionRef) => {
|
|
3273
3508
|
if (reactionRef === null) return undefined
|
|
3274
3509
|
return removeReaction({
|
|
@@ -3315,6 +3550,11 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3315
3550
|
else typingCapableAdapters.delete(adapter)
|
|
3316
3551
|
}
|
|
3317
3552
|
|
|
3553
|
+
const setAdapterConfigured = (adapter: ChannelKey['adapter'], configured: boolean): void => {
|
|
3554
|
+
if (configured) configuredAdapters.add(adapter)
|
|
3555
|
+
else configuredAdapters.delete(adapter)
|
|
3556
|
+
}
|
|
3557
|
+
|
|
3318
3558
|
const registerChannelNameResolver = (adapter: ChannelKey['adapter'], resolver: ChannelNameResolver): void => {
|
|
3319
3559
|
let set = channelNameResolvers.get(adapter)
|
|
3320
3560
|
if (!set) {
|
|
@@ -3379,10 +3619,18 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3379
3619
|
historyCallbacks.get(adapter)?.delete(cb)
|
|
3380
3620
|
}
|
|
3381
3621
|
|
|
3622
|
+
const isReadCapabilityUnavailable = (adapter: ChannelKey['adapter'], capability: ReadCapability): boolean =>
|
|
3623
|
+
configuredAdapters.has(adapter) && ADAPTER_READ_CAPABILITIES[adapter].includes(capability)
|
|
3624
|
+
|
|
3625
|
+
const missingCallbackError = (adapter: ChannelKey['adapter'], capability: ReadCapability): string =>
|
|
3626
|
+
isReadCapabilityUnavailable(adapter, capability)
|
|
3627
|
+
? `${capability}-adapter-unavailable: the "${adapter}" adapter is configured but not currently running (it likely failed to start, e.g. an expired token or auth error — check the container logs and re-authenticate)`
|
|
3628
|
+
: `${capability}-not-supported`
|
|
3629
|
+
|
|
3382
3630
|
const fetchHistory = async (adapter: ChannelKey['adapter'], args: FetchHistoryArgs): Promise<FetchHistoryResult> => {
|
|
3383
3631
|
const callbacks = historyCallbacks.get(adapter)
|
|
3384
3632
|
if (!callbacks || callbacks.size === 0) {
|
|
3385
|
-
return { ok: false, error: 'history
|
|
3633
|
+
return { ok: false, error: missingCallbackError(adapter, 'history') }
|
|
3386
3634
|
}
|
|
3387
3635
|
// Snapshot before iterating, mirroring `send`: a callback that mutates
|
|
3388
3636
|
// the set (e.g. unregisters mid-call) must not skip siblings.
|
|
@@ -3411,7 +3659,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3411
3659
|
|
|
3412
3660
|
const getMessage = async (adapter: ChannelKey['adapter'], args: GetMessageArgs): Promise<GetMessageResult> => {
|
|
3413
3661
|
const cb = messageGetCallbacks.get(adapter)
|
|
3414
|
-
if (cb === undefined)
|
|
3662
|
+
if (cb === undefined)
|
|
3663
|
+
return isReadCapabilityUnavailable(adapter, 'message-get')
|
|
3664
|
+
? { ok: false, error: missingCallbackError(adapter, 'message-get'), code: 'adapter-unavailable' }
|
|
3665
|
+
: { ok: false, error: 'message-get-not-supported', code: 'not-supported' }
|
|
3415
3666
|
try {
|
|
3416
3667
|
return await raceWithTimeout(cb(args), fetchHistoryTimeoutMs, `[channels] ${adapter} message get`)
|
|
3417
3668
|
} catch (err) {
|
|
@@ -3430,7 +3681,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3430
3681
|
|
|
3431
3682
|
const listChannels = async (adapter: ChannelKey['adapter'], args: ListChannelsArgs): Promise<ListChannelsResult> => {
|
|
3432
3683
|
const cb = listCallbacks.get(adapter)
|
|
3433
|
-
if (cb === undefined)
|
|
3684
|
+
if (cb === undefined)
|
|
3685
|
+
return isReadCapabilityUnavailable(adapter, 'list')
|
|
3686
|
+
? { ok: false, error: missingCallbackError(adapter, 'list'), code: 'adapter-unavailable' }
|
|
3687
|
+
: { ok: false, error: 'list-not-supported', code: 'not-supported' }
|
|
3434
3688
|
try {
|
|
3435
3689
|
return await raceWithTimeout(cb(args), fetchHistoryTimeoutMs, `[channels] ${adapter} list channels`)
|
|
3436
3690
|
} catch (err) {
|
|
@@ -3865,6 +4119,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3865
4119
|
const { reason } = live.skippedTurn
|
|
3866
4120
|
live.skippedTurn = null
|
|
3867
4121
|
logger.info(`[channels] ${live.keyId} skipped_by_tool reason=${JSON.stringify(reason)}`)
|
|
4122
|
+
armSilentTurnAck(live, 'skip_response')
|
|
3868
4123
|
return
|
|
3869
4124
|
}
|
|
3870
4125
|
if (live.skippedTurn !== null && live.skippedTurn.turnSeq === live.turnSeq) {
|
|
@@ -3890,6 +4145,27 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3890
4145
|
}
|
|
3891
4146
|
}
|
|
3892
4147
|
|
|
4148
|
+
// Suppress a leaked tool call (never post the plumbing) and, while budget
|
|
4149
|
+
// remains, push a self-correction reminder so the same logical turn
|
|
4150
|
+
// re-prompts and the model can redo it with a real tool call. On exhaustion
|
|
4151
|
+
// we stay silent — a persistently-leaking model must not livelock, and
|
|
4152
|
+
// silence is safer than posting a fallback the user didn't ask for.
|
|
4153
|
+
const suppressToolLeakAndNudge = (live: LiveSession, leakedText: string): void => {
|
|
4154
|
+
if (live.toolLeakRetries < MAX_TOOL_LEAK_RETRIES) {
|
|
4155
|
+
live.toolLeakRetries++
|
|
4156
|
+
logger.warn(
|
|
4157
|
+
`[channels] ${live.keyId}: suppressed plain_text_tool_call_leak (nudge ` +
|
|
4158
|
+
`attempt=${live.toolLeakRetries}/${MAX_TOOL_LEAK_RETRIES}) text_len=${leakedText.length}`,
|
|
4159
|
+
)
|
|
4160
|
+
live.pendingSystemReminders.push(TOOL_CALL_LEAK_NUDGE)
|
|
4161
|
+
return
|
|
4162
|
+
}
|
|
4163
|
+
logger.warn(
|
|
4164
|
+
`[channels] ${live.keyId}: suppressed plain_text_tool_call_leak (retries exhausted, silent) ` +
|
|
4165
|
+
`text_len=${leakedText.length}`,
|
|
4166
|
+
)
|
|
4167
|
+
}
|
|
4168
|
+
|
|
3893
4169
|
// A send landed this turn, but the model may have posted a `continue: true`
|
|
3894
4170
|
// progress reply, kept working, then ENDED with its final answer as plain
|
|
3895
4171
|
// prose — never calling a channel tool again. The terminal-reply abort fires
|
|
@@ -4163,6 +4439,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
4163
4439
|
}
|
|
4164
4440
|
const leakedReasoning = !isNoReplySignal(assistantText)
|
|
4165
4441
|
logger.info(`[channels] ${live.keyId} no_reply${leakedReasoning ? ' (with_leaked_reasoning)' : ''}`)
|
|
4442
|
+
armSilentTurnAck(live, 'no_reply')
|
|
4166
4443
|
return
|
|
4167
4444
|
}
|
|
4168
4445
|
|
|
@@ -4178,28 +4455,34 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
4178
4455
|
return
|
|
4179
4456
|
}
|
|
4180
4457
|
|
|
4181
|
-
// Plain-text tool-call leak: the model serialized a
|
|
4182
|
-
//
|
|
4183
|
-
//
|
|
4184
|
-
//
|
|
4185
|
-
//
|
|
4186
|
-
//
|
|
4187
|
-
//
|
|
4458
|
+
// Plain-text tool-call leak: the model serialized a tool call as ordinary
|
|
4459
|
+
// message text instead of producing a real tool call. Default is SUPPRESS —
|
|
4460
|
+
// that raw plumbing must never reach the channel. The two exceptions are
|
|
4461
|
+
// `channel_reply` / `channel_send`, whose leaked form carries a salvageable
|
|
4462
|
+
// user message: extract the `text` arg and recover the actual reply.
|
|
4463
|
+
// `suppress-silent` (skip_response) drops without a nudge because the model
|
|
4464
|
+
// already got the silence it asked for; `suppress-warn` (every other leaked
|
|
4465
|
+
// call) drops AND re-prompts the model to redo the turn with a real tool
|
|
4466
|
+
// call, bounded by MAX_TOOL_LEAK_RETRIES so it can't livelock.
|
|
4188
4467
|
const plainTextToolCallKind = getPlainTextChannelToolCallKind(assistantText)
|
|
4189
|
-
if (plainTextToolCallKind === '
|
|
4468
|
+
if (plainTextToolCallKind === 'suppress-silent') {
|
|
4190
4469
|
logger.warn(
|
|
4191
|
-
`[channels] ${live.keyId}: suppressed
|
|
4470
|
+
`[channels] ${live.keyId}: suppressed plain_text_tool_call_leak (silent) text_len=${assistantText.length}`,
|
|
4192
4471
|
)
|
|
4472
|
+
armSilentTurnAck(live, 'skip_response_text_leak')
|
|
4473
|
+
return
|
|
4474
|
+
}
|
|
4475
|
+
if (plainTextToolCallKind === 'suppress-warn') {
|
|
4476
|
+
suppressToolLeakAndNudge(live, assistantText)
|
|
4193
4477
|
return
|
|
4194
4478
|
}
|
|
4195
4479
|
if (plainTextToolCallKind !== null) {
|
|
4196
4480
|
const extracted = extractPlainTextChannelToolCallText(assistantText)
|
|
4197
|
-
//
|
|
4198
|
-
//
|
|
4481
|
+
// A reply/send leak with no recoverable `text` (missing arg, empty value,
|
|
4482
|
+
// or fully-truncated) still owes the user a real message — treat it as a
|
|
4483
|
+
// warn-worthy leak, not a silent drop, so the model retries properly.
|
|
4199
4484
|
if (extracted === null) {
|
|
4200
|
-
|
|
4201
|
-
`[channels] ${live.keyId}: suppressed unextractable_plain_text_channel_tool_call text_len=${assistantText.length}`,
|
|
4202
|
-
)
|
|
4485
|
+
suppressToolLeakAndNudge(live, assistantText)
|
|
4203
4486
|
return
|
|
4204
4487
|
}
|
|
4205
4488
|
// The extracted value is still untrusted model output: if it is itself a
|
|
@@ -4363,6 +4646,12 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
4363
4646
|
|
|
4364
4647
|
const tearDownLive = async (live: LiveSession): Promise<void> => {
|
|
4365
4648
|
live.destroyed = true
|
|
4649
|
+
// A teardown before the queued/in-flight turn ever replies would otherwise
|
|
4650
|
+
// strand its eager :eyes: forever (dropEngageReactions only runs after a
|
|
4651
|
+
// successful send). Remove both the queued and current-turn acks here.
|
|
4652
|
+
clearQueuedEngageReactions(live)
|
|
4653
|
+
dropEngageReactions(live, live.currentTurnEngageReactions)
|
|
4654
|
+
live.currentTurnEngageReactions = []
|
|
4366
4655
|
if (live.debounceTimer) clearTimeout(live.debounceTimer)
|
|
4367
4656
|
live.debounceTimer = null
|
|
4368
4657
|
live.unsubProviderErrors?.()
|
|
@@ -4838,6 +5127,38 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
4838
5127
|
})
|
|
4839
5128
|
}
|
|
4840
5129
|
|
|
5130
|
+
const armSilentTurnAck = (live: LiveSession, reason: SilentAckReason): void => {
|
|
5131
|
+
live.silentAckTurn = { turnSeq: live.turnSeq, reason }
|
|
5132
|
+
}
|
|
5133
|
+
|
|
5134
|
+
const reactOnSilentAck = (live: LiveSession): void => {
|
|
5135
|
+
if (live.silentAckTurn?.turnSeq !== live.turnSeq) return
|
|
5136
|
+
const { reason } = live.silentAckTurn
|
|
5137
|
+
live.silentAckTurn = null
|
|
5138
|
+
const reactionRef = live.currentTurnReactionRef
|
|
5139
|
+
if (reactionRef === null) return
|
|
5140
|
+
void react({
|
|
5141
|
+
adapter: live.key.adapter,
|
|
5142
|
+
workspace: live.key.workspace,
|
|
5143
|
+
chat: live.key.chat,
|
|
5144
|
+
thread: live.key.thread,
|
|
5145
|
+
reactionRef,
|
|
5146
|
+
emoji: ENGAGE_REACTION_EMOJI,
|
|
5147
|
+
})
|
|
5148
|
+
.then((result) => {
|
|
5149
|
+
if (!result.ok && result.code !== 'unsupported') {
|
|
5150
|
+
logger.info(
|
|
5151
|
+
`[channels] silent-ack-react failed reason=${reason} adapter=${live.key.adapter} chat=${live.key.chat}: ${result.error}`,
|
|
5152
|
+
)
|
|
5153
|
+
}
|
|
5154
|
+
})
|
|
5155
|
+
.catch((err) => {
|
|
5156
|
+
logger.info(
|
|
5157
|
+
`[channels] silent-ack-react threw reason=${reason} adapter=${live.key.adapter} chat=${live.key.chat}: ${describe(err)}`,
|
|
5158
|
+
)
|
|
5159
|
+
})
|
|
5160
|
+
}
|
|
5161
|
+
|
|
4841
5162
|
return {
|
|
4842
5163
|
route,
|
|
4843
5164
|
send,
|
|
@@ -4848,12 +5169,14 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
4848
5169
|
registerReaction,
|
|
4849
5170
|
unregisterReaction,
|
|
4850
5171
|
react,
|
|
5172
|
+
queueReactionAfterReply,
|
|
4851
5173
|
registerRemoveReaction,
|
|
4852
5174
|
unregisterRemoveReaction,
|
|
4853
5175
|
removeReaction,
|
|
4854
5176
|
registerTyping,
|
|
4855
5177
|
unregisterTyping,
|
|
4856
5178
|
setTypingCapability,
|
|
5179
|
+
setAdapterConfigured,
|
|
4857
5180
|
registerChannelNameResolver,
|
|
4858
5181
|
unregisterChannelNameResolver,
|
|
4859
5182
|
registerSelfIdentity,
|
|
@@ -4931,6 +5254,12 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
4931
5254
|
}
|
|
4932
5255
|
await fireTyping(live, 'tick')
|
|
4933
5256
|
},
|
|
5257
|
+
fireTypingTick: async (key: ChannelKey, epoch: number) => {
|
|
5258
|
+
const live = liveSessions.get(channelKeyId(key))
|
|
5259
|
+
if (!live) return
|
|
5260
|
+
await fireTyping(live, 'tick', epoch)
|
|
5261
|
+
},
|
|
5262
|
+
typingEpoch: (key: ChannelKey) => liveSessions.get(channelKeyId(key))?.typingEpoch,
|
|
4934
5263
|
isTypingActive: (key: ChannelKey) => {
|
|
4935
5264
|
const live = liveSessions.get(channelKeyId(key))
|
|
4936
5265
|
return live?.typingTimer !== null && live?.typingTimer !== undefined
|
|
@@ -5427,20 +5756,23 @@ export type ReplyRenderMode = 'native' | 'quote'
|
|
|
5427
5756
|
// because native support is not uniform within an adapter — Telegram's
|
|
5428
5757
|
// `sendMessage` accepts `reply_to_message_id` but `sendDocument` does not, so
|
|
5429
5758
|
// an attachment-only Telegram reply must quote; the same text-only restriction
|
|
5430
|
-
// holds for
|
|
5431
|
-
// land bare) and KakaoTalk. Slack's primitive is `thread`, not a per-message
|
|
5759
|
+
// holds for KakaoTalk. Slack's primitive is `thread`, not a per-message
|
|
5432
5760
|
// reply, so it stays quote; GitHub's PR-review reply already rides on `thread`.
|
|
5433
5761
|
//
|
|
5434
5762
|
// KakaoTalk is `native` here even though its reply payload can fail to resolve
|
|
5435
5763
|
// at send time — the adapter degrades to the blockquote fallback itself using
|
|
5436
5764
|
// `replyTo.source`, so the router still routes it down the native branch.
|
|
5437
|
-
const NATIVE_REPLY_TEXT_ADAPTERS = new Set<AdapterId>(['telegram-bot', '
|
|
5765
|
+
const NATIVE_REPLY_TEXT_ADAPTERS = new Set<AdapterId>(['telegram-bot', 'kakaotalk'])
|
|
5438
5766
|
|
|
5439
5767
|
// Webex's `parentId` rides on both `sendMessage` and `uploadFile`, so a reply is
|
|
5440
5768
|
// native for every shape — including attachment-only, which the text-gated set
|
|
5441
|
-
// above cannot express.
|
|
5442
|
-
// `
|
|
5443
|
-
|
|
5769
|
+
// above cannot express. Both Discord adapters join this set because each carries
|
|
5770
|
+
// `message_reference` on BOTH the text send (`sendMessage`) and the attachment
|
|
5771
|
+
// send (`payload_json` on the first file upload), so an attachment-only Discord
|
|
5772
|
+
// reply is a native reply-arrow, not a bare blockquote. Special-cased before the
|
|
5773
|
+
// text gate so the router sets `replyTo` (not a blockquote) even when the reply
|
|
5774
|
+
// carries no text.
|
|
5775
|
+
const NATIVE_REPLY_EVERY_SHAPE_ADAPTERS = new Set<AdapterId>(['webex', 'webex-bot', 'discord-bot', 'discord'])
|
|
5444
5776
|
|
|
5445
5777
|
export function resolveReplyRenderMode(msg: OutboundMessage): ReplyRenderMode {
|
|
5446
5778
|
if (NATIVE_REPLY_EVERY_SHAPE_ADAPTERS.has(msg.adapter)) return 'native'
|
|
@@ -5833,15 +6165,27 @@ function attemptMadeToolCall(session: AgentSession): boolean {
|
|
|
5833
6165
|
return false
|
|
5834
6166
|
}
|
|
5835
6167
|
|
|
6168
|
+
// Peels a single symmetric markdown-emphasis wrapper off a token: bold/italic
|
|
6169
|
+
// asterisks (`*`, `**`, `***`), underscores (`_`, `__`), or inline-code
|
|
6170
|
+
// backticks. Only strips when the SAME run brackets both ends, so `**NO_REPLY**`
|
|
6171
|
+
// → `NO_REPLY` while an asymmetric `*NO_REPLY` or a non-wrapping `NO_REPLY_MODE`
|
|
6172
|
+
// is returned unchanged. Not recursive — one layer is enough for the observed
|
|
6173
|
+
// `**...**` / `` `...` `` "loud" drift; anything more nested is not a real form.
|
|
6174
|
+
function stripEmphasisWrapper(token: string): string {
|
|
6175
|
+
const match = /^([*_`]{1,3})([^*_`].*?[^*_`]|[^*_`])\1$/.exec(token)
|
|
6176
|
+
return match ? match[2]! : token
|
|
6177
|
+
}
|
|
6178
|
+
|
|
5836
6179
|
// Lenient on purpose: distilled / smaller models routinely drift off the
|
|
5837
6180
|
// documented `NO_REPLY` form. We additionally accept `(NO_REPLY)` (Claude-style
|
|
5838
|
-
// hedging)
|
|
5839
|
-
//
|
|
5840
|
-
//
|
|
6181
|
+
// hedging), markdown-emphasized "loud" forms (`**NO_REPLY**`, `` `NO_REPLY` ``,
|
|
6182
|
+
// `*NO_REPLY*`), and empty visible text (e.g. Kimi-distilled models that emit
|
|
6183
|
+
// only a thinking block and end the turn) — without the empty case we'd recover
|
|
6184
|
+
// an empty string into the chat. The prompt contract still teaches the strict
|
|
5841
6185
|
// literal; this just widens what we accept. Shared with channel_send /
|
|
5842
6186
|
// channel_reply so all three call sites stay in lockstep.
|
|
5843
6187
|
export function isNoReplySignal(text: string): boolean {
|
|
5844
|
-
const trimmed = text.trim()
|
|
6188
|
+
const trimmed = stripEmphasisWrapper(text.trim())
|
|
5845
6189
|
if (trimmed === '') return true
|
|
5846
6190
|
if (trimmed === 'NO_REPLY') return true
|
|
5847
6191
|
if (trimmed === '(NO_REPLY)') return true
|
|
@@ -5870,21 +6214,31 @@ export function isNoReplySignal(text: string): boolean {
|
|
|
5870
6214
|
// "... end with NO_REPLY." (+ sentence punctuation)
|
|
5871
6215
|
// "... end with NO_REPLY.NO_REPLY" (model-doubled terminator, glued)
|
|
5872
6216
|
// "... and stop. (NO_REPLY)" (parenthesized at end)
|
|
6217
|
+
// "... nothing to add. **NO_REPLY**"(markdown-emphasized "loud" form)
|
|
6218
|
+
// "... nothing here. `NO_REPLY`" (inline-code "loud" form)
|
|
5873
6219
|
// Does not match (returns false):
|
|
5874
6220
|
// "NO_REPLY means do nothing" (token at start, prose after)
|
|
5875
6221
|
// "the env var is NO_REPLY_MODE" (substring, not whole token)
|
|
6222
|
+
// "the flag is FOO_NO_REPLY" (identifier — `_` is not a token boundary)
|
|
6223
|
+
// "the **NO_REPLY** token is how..."(emphasized but mid-sentence, prose after)
|
|
5876
6224
|
// "no reply needed" (case-sensitive on purpose)
|
|
5877
6225
|
export function endsWithNoReplySignal(text: string): boolean {
|
|
5878
6226
|
if (isNoReplySignal(text)) return true
|
|
5879
6227
|
const trimmed = text.trim()
|
|
5880
6228
|
if (trimmed === '') return false
|
|
5881
|
-
//
|
|
5882
|
-
//
|
|
5883
|
-
//
|
|
5884
|
-
//
|
|
5885
|
-
//
|
|
6229
|
+
// Isolate the final token, then defer to isNoReplySignal (which strips a
|
|
6230
|
+
// symmetric emphasis wrapper). Boundaries are whitespace / sentence
|
|
6231
|
+
// punctuation / opening bracket only — `.NO_REPLY` splits off the preceding
|
|
6232
|
+
// sentence (covering the model-doubled `...NO_REPLY.NO_REPLY` shape), while
|
|
6233
|
+
// `_` is deliberately NOT a boundary so an identifier like `FOO_NO_REPLY`
|
|
6234
|
+
// stays one token and reads as prose, not a signal.
|
|
5886
6235
|
const tail = trimmed.replace(/[.!?)\]\s]+$/, '')
|
|
5887
|
-
|
|
6236
|
+
const lastToken = tail.split(/[\s.!?([]/).pop() ?? ''
|
|
6237
|
+
// An empty final token means the text ended on an opening bracket (e.g. a
|
|
6238
|
+
// leaked `skip_response()` call), not a signal — don't hand it to
|
|
6239
|
+
// isNoReplySignal, whose empty-string case reads as deliberate silence.
|
|
6240
|
+
if (lastToken === '') return false
|
|
6241
|
+
return isNoReplySignal(lastToken)
|
|
5888
6242
|
}
|
|
5889
6243
|
|
|
5890
6244
|
// Detects the upstream "empty response" debug sentinel: when the LLM ends a
|
|
@@ -5990,44 +6344,99 @@ export function isLikelyKimiChannelToolLeak(text: string): boolean {
|
|
|
5990
6344
|
// posts its own "I'm staying silent" plumbing to the channel, the exact
|
|
5991
6345
|
// opposite of the intended no-op. It is never a legitimate user-facing reply.
|
|
5992
6346
|
//
|
|
5993
|
-
//
|
|
5994
|
-
//
|
|
5995
|
-
//
|
|
5996
|
-
//
|
|
5997
|
-
//
|
|
5998
|
-
//
|
|
5999
|
-
//
|
|
6000
|
-
//
|
|
6001
|
-
//
|
|
6002
|
-
// but...") reach the user — that false-positive class is already locked in by
|
|
6003
|
-
// the `still recovers prose that mentions channel_reply` test.
|
|
6347
|
+
// Detection is a SINGLE whole-message boundary for every tool, then a per-name
|
|
6348
|
+
// disposition. reply/send RECOVER (their leaked form holds a salvageable user
|
|
6349
|
+
// message the extractor re-posts); everything else SUPPRESSES.
|
|
6350
|
+
//
|
|
6351
|
+
// SUPPRESS is the default and is detected by SHAPE, not a curated name list — a
|
|
6352
|
+
// `toolname(...)` that is the model's ENTIRE turn output is always a protocol
|
|
6353
|
+
// malfunction (the model narrated a call instead of emitting it), and that raw
|
|
6354
|
+
// plumbing must never reach the channel. No allowlist to keep in sync as tools
|
|
6355
|
+
// are added.
|
|
6004
6356
|
//
|
|
6005
|
-
// The
|
|
6006
|
-
//
|
|
6007
|
-
//
|
|
6008
|
-
|
|
6357
|
+
// The false-positive boundary is "the WHOLE trimmed message is a single call
|
|
6358
|
+
// expression" — NOT "starts with a call". A developer-facing reply like
|
|
6359
|
+
// `read({ ... }) lets you load a file` has text after the closing paren, so it
|
|
6360
|
+
// is prose and reaches the user. Only a message that is *nothing but* the call
|
|
6361
|
+
// (`skip_response({ ... })`, `channel_react({ emoji: "eyes" })`, bare
|
|
6362
|
+
// `channel_disengage()`) is a leak. This is what lets the rule cover every tool
|
|
6363
|
+
// — including future ones and generic tools like `bash(...)` — without risking
|
|
6364
|
+
// legitimate replies, because a real reply is never *only* a bare tool call.
|
|
6365
|
+
//
|
|
6366
|
+
// `isWholeMessageToolCall` (below) is the bracket-aware parser; it returns the
|
|
6367
|
+
// called tool's name so the caller can apply the one intrinsic distinction that
|
|
6368
|
+
// survives: `skip_response` suppresses SILENTLY (the model wanted silence, and
|
|
6369
|
+
// suppression already delivered it — warning would be noise), while every other
|
|
6370
|
+
// suppressed leak pushes a self-correction reminder so the model retries with a
|
|
6371
|
+
// real tool call or a real reply.
|
|
6372
|
+
const SKIP_RESPONSE_TOOL_NAME = 'skip_response'
|
|
6009
6373
|
|
|
6010
|
-
export type PlainTextChannelToolCallKind = 'reply' | 'send' | '
|
|
6374
|
+
export type PlainTextChannelToolCallKind = 'reply' | 'send' | 'suppress-silent' | 'suppress-warn'
|
|
6011
6375
|
|
|
6012
6376
|
export function getPlainTextChannelToolCallKind(text: string): PlainTextChannelToolCallKind | null {
|
|
6013
|
-
|
|
6014
|
-
|
|
6015
|
-
|
|
6016
|
-
|
|
6017
|
-
|
|
6018
|
-
|
|
6019
|
-
|
|
6020
|
-
|
|
6021
|
-
|
|
6022
|
-
|
|
6023
|
-
|
|
6024
|
-
|
|
6377
|
+
// Everything routes through the SAME whole-message boundary, including
|
|
6378
|
+
// reply/send recovery — a prefix match there would false-positive prose like
|
|
6379
|
+
// `channel_reply({"text":"hi"}) is the serialized form`, recovering `hi` and
|
|
6380
|
+
// dropping the explanation. `isWholeMessageToolCall` returns the tool name
|
|
6381
|
+
// only when the entire trimmed message is the call (or a truncated one), so a
|
|
6382
|
+
// reply/send leak still recovers while a mention-with-trailing-prose falls
|
|
6383
|
+
// through to the user.
|
|
6384
|
+
const toolName = isWholeMessageToolCall(text)
|
|
6385
|
+
if (toolName === null) return null
|
|
6386
|
+
if (toolName === 'channel_reply') return 'reply'
|
|
6387
|
+
if (toolName === 'channel_send') return 'send'
|
|
6388
|
+
// `skip_response` already got what it wanted once suppressed (silence), so
|
|
6389
|
+
// warning would be noise. Every other leaked call dropped a real action or
|
|
6390
|
+
// reply, so nudge the model to redo it properly.
|
|
6391
|
+
return toolName === SKIP_RESPONSE_TOOL_NAME ? 'suppress-silent' : 'suppress-warn'
|
|
6025
6392
|
}
|
|
6026
6393
|
|
|
6027
6394
|
export function isLikelyPlainTextChannelToolCall(text: string): boolean {
|
|
6028
6395
|
return getPlainTextChannelToolCallKind(text) !== null
|
|
6029
6396
|
}
|
|
6030
6397
|
|
|
6398
|
+
// Bracket-aware parser: returns the called tool's name when the ENTIRE trimmed
|
|
6399
|
+
// text is a single call expression `identifier(...)` — empty args `()` or a
|
|
6400
|
+
// single object-literal `({ ... })` — with nothing but optional whitespace and
|
|
6401
|
+
// a trailing `;` after the closing paren. Returns null for anything else, which
|
|
6402
|
+
// is what keeps prose safe: `read({...}) loads a file` has trailing text, and
|
|
6403
|
+
// `bash` alone (no parens) is a bare word, so neither is a call. A naive
|
|
6404
|
+
// `^ident\(.*\)$` regex can't tell the closing paren of the arg object from a
|
|
6405
|
+
// paren inside a quoted string, so this walks the string honoring quotes and
|
|
6406
|
+
// brace/bracket/paren depth.
|
|
6407
|
+
export function isWholeMessageToolCall(text: string): string | null {
|
|
6408
|
+
const trimmed = text.trim()
|
|
6409
|
+
const nameMatch = /^([A-Za-z_][A-Za-z0-9_]*)\s*\(/.exec(trimmed)
|
|
6410
|
+
if (nameMatch === null) return null
|
|
6411
|
+
const name = nameMatch[1]!
|
|
6412
|
+
|
|
6413
|
+
let i = nameMatch[0].length - 1
|
|
6414
|
+
let depth = 0
|
|
6415
|
+
for (; i < trimmed.length; i++) {
|
|
6416
|
+
const ch = trimmed[i]!
|
|
6417
|
+
if (ch === '"' || ch === "'" || ch === '`') {
|
|
6418
|
+
i = skipStringLiteral(trimmed, i, ch)
|
|
6419
|
+
continue
|
|
6420
|
+
}
|
|
6421
|
+
if (ch === '(' || ch === '{' || ch === '[') {
|
|
6422
|
+
depth++
|
|
6423
|
+
continue
|
|
6424
|
+
}
|
|
6425
|
+
if (ch === ')' || ch === '}' || ch === ']') {
|
|
6426
|
+
depth--
|
|
6427
|
+
if (depth === 0) break
|
|
6428
|
+
continue
|
|
6429
|
+
}
|
|
6430
|
+
}
|
|
6431
|
+
|
|
6432
|
+
// Unbalanced (truncated mid-serialization) — still a leaked call, not prose.
|
|
6433
|
+
if (depth !== 0) return name
|
|
6434
|
+
|
|
6435
|
+
const rest = trimmed.slice(i + 1).trim()
|
|
6436
|
+
if (rest === '' || rest === ';') return name
|
|
6437
|
+
return null
|
|
6438
|
+
}
|
|
6439
|
+
|
|
6031
6440
|
// Tolerant single-purpose scanner that pulls the `text` argument out of a
|
|
6032
6441
|
// plain-text-serialized `channel_reply(...)` / `channel_send(...)` leak. A
|
|
6033
6442
|
// single regex covering every shape (double/single/unquoted keys, escaped
|