typeclaw 0.43.0 → 0.44.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/README.md +1 -1
- package/auth.schema.json +92 -0
- package/package.json +2 -2
- package/secrets.schema.json +92 -0
- package/src/agent/index.ts +23 -4
- package/src/agent/multimodal/look-at.ts +27 -9
- package/src/agent/plugin-tools.ts +9 -4
- package/src/agent/session-origin.ts +1 -0
- package/src/agent/system-prompt.ts +36 -0
- package/src/agent/tools/channel-fetch-attachment.ts +45 -3
- package/src/agent/tools/channel-reply.ts +41 -18
- package/src/agent/tools/channel-send.ts +82 -13
- package/src/bundled-plugins/github-cli-auth/gh-review-detect.ts +101 -1
- package/src/bundled-plugins/github-cli-auth/review-recorder.ts +44 -3
- package/src/bundled-plugins/guard/policies/managed-config.ts +20 -4
- package/src/bundled-plugins/memory/README.md +9 -9
- package/src/bundled-plugins/memory/index.ts +40 -9
- package/src/channels/adapters/discord-bot.ts +76 -3
- package/src/channels/adapters/discord.ts +15 -2
- package/src/channels/adapters/github/inbound.ts +20 -14
- package/src/channels/adapters/github/review-thread-resolver.ts +38 -4
- package/src/channels/adapters/teams-classify.ts +144 -0
- package/src/channels/adapters/teams-id-token.ts +112 -0
- package/src/channels/adapters/teams-key.ts +32 -0
- package/src/channels/adapters/teams.ts +519 -0
- package/src/channels/github-review-turn-ledger.ts +43 -0
- package/src/channels/index.ts +1 -1
- package/src/channels/manager.ts +63 -2
- package/src/channels/router.ts +664 -112
- package/src/channels/schema.ts +33 -0
- package/src/channels/types.ts +8 -5
- package/src/cli/channel.ts +131 -16
- package/src/cli/hostd.ts +41 -0
- package/src/cli/init.ts +58 -1
- package/src/config/channels-mutation.ts +9 -1
- package/src/cron/index.ts +16 -4
- package/src/cron/reloadable.ts +25 -7
- package/src/cron/scheduler.ts +4 -0
- package/src/cron/schema.ts +143 -35
- package/src/doctor/channel-checks.ts +27 -0
- package/src/hostd/daemon.ts +23 -3
- package/src/hostd/protocol.ts +2 -0
- package/src/hostd/teams-renewal-manager.ts +212 -0
- package/src/init/checkpoint.ts +1 -1
- package/src/init/index.ts +68 -1
- package/src/init/run-owner-claim.ts +1 -0
- package/src/init/teams-auth.ts +111 -0
- package/src/inspect/label.ts +4 -0
- package/src/permissions/match-rule.ts +11 -1
- package/src/permissions/resolve.ts +1 -0
- package/src/role-claim/match-rule.ts +2 -1
- package/src/run/index.ts +35 -8
- package/src/run/llm-fetch-observer.ts +27 -5
- package/src/sandbox/build.ts +12 -0
- package/src/sandbox/policy.ts +13 -0
- package/src/sandbox/writable-zones.ts +46 -10
- package/src/secrets/schema.ts +32 -0
- package/src/secrets/teams-renewal.ts +229 -0
- package/src/secrets/teams-store.ts +108 -0
- package/typeclaw.schema.json +163 -3
package/src/channels/router.ts
CHANGED
|
@@ -44,7 +44,7 @@ import {
|
|
|
44
44
|
} from './engagement'
|
|
45
45
|
import { checkFalseReceipt } from './github-false-receipt'
|
|
46
46
|
import { evaluateRereviewGuard } from './github-rereview-guard'
|
|
47
|
-
import { resetReviewTurn } from './github-review-turn-ledger'
|
|
47
|
+
import { resetReviewTurn, type ReviewOutputState } from './github-review-turn-ledger'
|
|
48
48
|
import { renderPrVerdictStandDownReminder } from './github-verdict-activity'
|
|
49
49
|
import {
|
|
50
50
|
MEMBERSHIP_COLD_FETCH_TIMEOUT_MS,
|
|
@@ -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' | 'github_review_output'
|
|
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
|
|
@@ -445,21 +482,26 @@ export const SESSION_FRESHNESS_TTL_MS = 5 * 60 * 1000
|
|
|
445
482
|
export const SESSION_GRACE_HARD_TTL_MS = 10 * 60 * 1000
|
|
446
483
|
|
|
447
484
|
/**
|
|
448
|
-
*
|
|
449
|
-
* channel session against idle GC and stale-rollover
|
|
450
|
-
*
|
|
451
|
-
* track of the in-flight task and spawns a DUPLICATE child
|
|
452
|
-
*
|
|
453
|
-
*
|
|
454
|
-
*
|
|
485
|
+
* Leak guard — NOT a freshness cap. A running background subagent pins its parent
|
|
486
|
+
* channel session against idle GC and stale-rollover for as long as the child is
|
|
487
|
+
* actually running, because the next inbound would otherwise start a fresh session
|
|
488
|
+
* that has lost track of the in-flight task and spawns a DUPLICATE child, and — the
|
|
489
|
+
* bug this backstop is sized around — a completion arriving after teardown has no
|
|
490
|
+
* live session to deliver its system-reminder to and is silently dropped.
|
|
491
|
+
*
|
|
492
|
+
* The pin is bounded only so a genuinely stuck/wedged child cannot make the session
|
|
493
|
+
* immortal. Subagent `timeoutMs` is optional (operator declares none), so a hung
|
|
494
|
+
* child stays `status: 'running'` forever; without this ceiling its parent session
|
|
495
|
+
* would leak indefinitely. Past this age the child is treated as stuck: GC/rollover
|
|
496
|
+
* proceeds and the session falls back to completion-reroute.
|
|
455
497
|
*
|
|
456
|
-
*
|
|
457
|
-
*
|
|
458
|
-
*
|
|
459
|
-
*
|
|
460
|
-
* is
|
|
498
|
+
* Sized as an ANOMALY threshold, deliberately far above any legitimate run (deep
|
|
499
|
+
* operator work is minutes-to-an-hour, not hours), so it never fires for real work.
|
|
500
|
+
* The prior 45m value was close enough to plausible deep work to turn a legitimate
|
|
501
|
+
* long run into a routine drop — the reported 65m completion loss. 6h is clearly
|
|
502
|
+
* "this child is wedged," not "this child is busy".
|
|
461
503
|
*/
|
|
462
|
-
export const
|
|
504
|
+
export const SESSION_CHILD_STUCK_BACKSTOP_MS = 6 * 60 * 60 * 1000
|
|
463
505
|
|
|
464
506
|
/**
|
|
465
507
|
* Cost-aware grace decision for the soft→hard TTL band. Returns true when reusing
|
|
@@ -711,6 +753,13 @@ type LiveSession = {
|
|
|
711
753
|
typingStartedAt: number
|
|
712
754
|
typingTimedOut: boolean
|
|
713
755
|
typingStopPromise: Promise<void> | null
|
|
756
|
+
// Monotonic heartbeat generation. Captured when a heartbeat starts and
|
|
757
|
+
// bumped when it stops. `clearInterval` cannot cancel a timer callback that
|
|
758
|
+
// already came due, so a stale 'tick' can still run AFTER stopTypingHeartbeat
|
|
759
|
+
// enqueued its clear — on Slack that re-sets "is typing..." after the empty-
|
|
760
|
+
// string clear and strands the indicator (Slack's status has no auto-expiry).
|
|
761
|
+
// A 'tick' fired with a stale epoch is dropped before it reaches the adapter.
|
|
762
|
+
typingEpoch: number
|
|
714
763
|
// True only while `live.session.prompt()` is actively running. Gates the
|
|
715
764
|
// deferred typing revival: a revival queued behind an in-flight cap-trip
|
|
716
765
|
// 'stop' must NOT re-arm the heartbeat once the prompt has finished, or it
|
|
@@ -736,6 +785,15 @@ type LiveSession = {
|
|
|
736
785
|
// carried only to the typing path; null when the triggering inbound supplied
|
|
737
786
|
// none (every non-DM inbound, and reminder-only turns).
|
|
738
787
|
currentTurnTypingThread: string | null
|
|
788
|
+
// Every flat-DM typingThread anchor a 'tick' set a non-expiring status on but
|
|
789
|
+
// that has not yet been cleared. In a flat DM each inbound stamps its OWN ts
|
|
790
|
+
// as `typingThread`, so `currentTurnTypingThread` migrates from ts=A to ts=B
|
|
791
|
+
// when a second message coalesces a new turn before the first turn's stop. A
|
|
792
|
+
// single-anchor stop would then clear only B and strand A's "is typing..."
|
|
793
|
+
// forever (Slack has no auto-expiry). Recording every ticked anchor lets the
|
|
794
|
+
// stop clear ALL of them, not just the latest. An anchor is added when its
|
|
795
|
+
// 'tick' dispatches and removed when its 'stop' clear dispatches.
|
|
796
|
+
dirtyTypingThreads: Set<string>
|
|
739
797
|
// One engage-:eyes:-add promise per inbound coalesced into THIS turn, each
|
|
740
798
|
// resolving to its removable per-instance ref (or null). A debounced turn can
|
|
741
799
|
// batch several inbounds that each got their own :eyes:, so every entry is
|
|
@@ -746,6 +804,35 @@ type LiveSession = {
|
|
|
746
804
|
// discarded on silence (skip_response / empty / errored turns) so the bot never
|
|
747
805
|
// leaves a reaction on a message it merely looked at (e.g. cron lookaround).
|
|
748
806
|
pendingTurnReactions: ReactionRequest[]
|
|
807
|
+
// Armed by `validateChannelTurn` on a DELIBERATE silent turn (skip_response or
|
|
808
|
+
// an explicit NO_REPLY), stamped with `turnSeq` so a stale flag from a crashed
|
|
809
|
+
// turn cannot leak into the next one. Read in drain's per-turn finally — AFTER
|
|
810
|
+
// the transient engage :eyes: is dropped — to leave a PERSISTENT :eyes: on the
|
|
811
|
+
// triggering message: "I saw this and intentionally chose not to reply." Null
|
|
812
|
+
// on every non-deliberate outcome (a real reply, a model malfunction, a
|
|
813
|
+
// plumbing leak, a retry, a synthetic turn). Firing after the engage-drop is
|
|
814
|
+
// load-bearing: adapters that collapse a same-actor same-emoji reaction into
|
|
815
|
+
// one toggle would otherwise have the engage-drop remove the only visible
|
|
816
|
+
// :eyes:. See `reactOnSilentAck`.
|
|
817
|
+
silentAckTurn: { turnSeq: number; reason: SilentAckReason } | null
|
|
818
|
+
// One silent-ack-:eyes:-add promise per PERSISTENT ack `reactOnSilentAck` has
|
|
819
|
+
// planted on a trigger message, each resolving to its removable ref (or null).
|
|
820
|
+
// Mirrors `currentTurnEngageReactions`: the PROMISE is pushed synchronously at
|
|
821
|
+
// arm time, so a later replied-turn cleanup that snapshots this array always
|
|
822
|
+
// sees every in-flight add and awaits it before removing — storing only the
|
|
823
|
+
// resolved ref raced (cleanup could snapshot an empty array, then a slow add
|
|
824
|
+
// append its ref afterward, stranding the :eyes:). Cross-turn state on purpose:
|
|
825
|
+
// a silent turn means "seen, not replying FOR NOW", and once the same sticky
|
|
826
|
+
// conversation gets a genuine reply those marks read as stale/contradictory —
|
|
827
|
+
// so they are retired on the next replied turn (see dropSilentAckReactions).
|
|
828
|
+
// Conversation-scoped, NOT per-trigger-message: coalescing means the silent
|
|
829
|
+
// turn's trigger (message N) and the eventual reply's trigger (message N+1)
|
|
830
|
+
// routinely differ, so exact-message scoping would strand the mark. NOT reset
|
|
831
|
+
// in drain's outer per-turn finally. On teardown the entries are dropped
|
|
832
|
+
// WITHOUT removing the reactions: a session that ends without ever replying
|
|
833
|
+
// legitimately keeps its "seen, not replying" ack, unlike the transient
|
|
834
|
+
// engage :eyes: which teardown must strip.
|
|
835
|
+
activeSilentAckReactions: Array<Promise<ReactionRef | null>>
|
|
749
836
|
lastTurnAuthorIds: Set<string>
|
|
750
837
|
// Mirror of currentTurnAuthorId at end-of-turn (the LAST speaker of the
|
|
751
838
|
// prior batch), preserved across the drain finally-block which resets
|
|
@@ -840,6 +927,11 @@ type LiveSession = {
|
|
|
840
927
|
// increments it before injecting EMPTY_TURN_RETRY_NUDGE and reads it to decide
|
|
841
928
|
// retry-vs-fallback. See the candidate===null branch.
|
|
842
929
|
emptyTurnRetries: number
|
|
930
|
+
// Count of tool-call-leak self-correction re-prompts spent this logical turn,
|
|
931
|
+
// bounded by MAX_TOOL_LEAK_RETRIES. Separate from emptyTurnRetries so the two
|
|
932
|
+
// failure modes can't drain each other's budget. Reset with the rest on a
|
|
933
|
+
// fresh user batch.
|
|
934
|
+
toolLeakRetries: number
|
|
843
935
|
// Latches once a bare-empty `stop` has been classified as empty-stop-after-tool-work
|
|
844
936
|
// this logical turn. The recovery nudge tells the model NOT to re-run its tools, so
|
|
845
937
|
// a compliant retry is expected to land another bare-empty `stop` with NO new tool
|
|
@@ -910,6 +1002,19 @@ type LiveSession = {
|
|
|
910
1002
|
// question escalation. Compared by `turnSeq` so a stale value can't leak across
|
|
911
1003
|
// turns.
|
|
912
1004
|
emptyTurnFallbackTurn: number | null
|
|
1005
|
+
// Stamped with `turnSeq` when a formal GitHub review (APPROVE / REQUEST_CHANGES /
|
|
1006
|
+
// COMMENT) lands during this LOGICAL turn, via noteGithubReviewOutput off the
|
|
1007
|
+
// review-output observer. On a github PR channel the agent's real deliverable is
|
|
1008
|
+
// the review — posted through the GitHub API by the bash tool, NOT through
|
|
1009
|
+
// channel_reply/channel_send — so it never bumps `successfulChannelSends`. An
|
|
1010
|
+
// empty completion afterward would otherwise look like a dead turn and fire the
|
|
1011
|
+
// "I got stuck" empty-turn fallback (a real verdict, then a contradictory fallback
|
|
1012
|
+
// seconds later). validateChannelTurn reads this to treat such an empty stop as a
|
|
1013
|
+
// legitimate silent completion. Reset ONLY on a real user batch (with the retry
|
|
1014
|
+
// budgets) so it survives reminder-only retry iterations — the review lands in an
|
|
1015
|
+
// EARLIER iteration than the fallback; resetting per-iteration (beside
|
|
1016
|
+
// resetReviewTurn) would recreate the bug.
|
|
1017
|
+
githubReviewOutputTurn: number | null
|
|
913
1018
|
// Captured by drain() at batch dequeue; read+cleared by send() on the
|
|
914
1019
|
// first tool-source send of the turn. The anchor decision (delay
|
|
915
1020
|
// threshold + intervening-observed check) is evaluated at SEND time
|
|
@@ -958,6 +1063,13 @@ type LiveSession = {
|
|
|
958
1063
|
// crashed prior turn can't leak into the next.
|
|
959
1064
|
pendingProviderError: { turnSeq: number; safeMessage: string } | null
|
|
960
1065
|
destroyed: boolean
|
|
1066
|
+
// Set by tearDownAllLive when a reload/roles/auth swap wants to recreate this
|
|
1067
|
+
// session but a turn is mid-flight. Aborting now would strand the in-flight
|
|
1068
|
+
// reply (the reload's own turn goes silent). Instead the session stays live
|
|
1069
|
+
// and finishes its current reply with pre-reload state; the drain loop's
|
|
1070
|
+
// finally tears it down once the turn drains, so the next inbound rehydrates
|
|
1071
|
+
// with fresh role/auth/prompt state. Idle sessions are torn down immediately.
|
|
1072
|
+
pendingTeardown: boolean
|
|
961
1073
|
unsubProviderErrors: (() => void) | null
|
|
962
1074
|
unsubTypingActivity: (() => void) | null
|
|
963
1075
|
unsubTodoOutcome: (() => void) | null
|
|
@@ -1056,6 +1168,17 @@ export type ChannelRouter = {
|
|
|
1056
1168
|
// the wrong signal. autoReactOnEngage reads this to post :eyes: only as a
|
|
1057
1169
|
// fallback when no visible typing exists. Unset defaults to false.
|
|
1058
1170
|
setTypingCapability: (adapter: ChannelKey['adapter'], supported: boolean) => void
|
|
1171
|
+
// Set by the manager for every adapter present in typeclaw.json#channels,
|
|
1172
|
+
// independent of whether the adapter's start() succeeded (a failed login never
|
|
1173
|
+
// registers callbacks). Combined with the adapter's static read-capability set
|
|
1174
|
+
// (ADAPTER_READ_CAPABILITIES), fetchHistory/getMessage/listChannels tell three
|
|
1175
|
+
// cases apart for a missing callback: not configured → *-not-supported;
|
|
1176
|
+
// configured but the capability isn't one this adapter implements →
|
|
1177
|
+
// *-not-supported; configured AND the adapter should implement it but no
|
|
1178
|
+
// callback is live (e.g. auth failure at startup) → *-adapter-unavailable. So
|
|
1179
|
+
// the agent only sees the actionable error when re-auth would actually help.
|
|
1180
|
+
// Unset defaults to not-configured.
|
|
1181
|
+
setAdapterConfigured: (adapter: ChannelKey['adapter'], configured: boolean) => void
|
|
1059
1182
|
registerChannelNameResolver: (adapter: ChannelKey['adapter'], resolver: ChannelNameResolver) => void
|
|
1060
1183
|
unregisterChannelNameResolver: (adapter: ChannelKey['adapter'], resolver: ChannelNameResolver) => void
|
|
1061
1184
|
// Self-identity is a per-adapter singleton (one bot account per adapter),
|
|
@@ -1153,6 +1276,12 @@ export type ChannelRouter = {
|
|
|
1153
1276
|
verdict: 'APPROVE' | 'REQUEST_CHANGES'
|
|
1154
1277
|
sessionId: string
|
|
1155
1278
|
}) => { kind: 'delivered'; count: number }
|
|
1279
|
+
noteGithubReviewOutput: (args: {
|
|
1280
|
+
sessionId: string
|
|
1281
|
+
workspace: string
|
|
1282
|
+
prNumber: number
|
|
1283
|
+
state: ReviewOutputState
|
|
1284
|
+
}) => { kind: 'stamped' | 'no-live-session' }
|
|
1156
1285
|
// Record that the agent invoked `skip_response` during the current turn
|
|
1157
1286
|
// for the channel session identified by `parentSessionId`. The reason is
|
|
1158
1287
|
// logged at INFO level inside `validateChannelTurn` (single log line per
|
|
@@ -1209,6 +1338,8 @@ export type ChannelRouter = {
|
|
|
1209
1338
|
flushDebounce: (key: ChannelKey) => Promise<void>
|
|
1210
1339
|
fireTypingHeartbeat: (key: ChannelKey, phase?: 'tick' | 'stop') => Promise<void>
|
|
1211
1340
|
fireTypingInterval: (key: ChannelKey) => Promise<void>
|
|
1341
|
+
fireTypingTick: (key: ChannelKey, epoch: number) => Promise<void>
|
|
1342
|
+
typingEpoch: (key: ChannelKey) => number | undefined
|
|
1212
1343
|
isTypingActive: (key: ChannelKey) => boolean
|
|
1213
1344
|
stopTyping: (key: ChannelKey) => Promise<void>
|
|
1214
1345
|
runIdleGc: () => Promise<void>
|
|
@@ -1323,12 +1454,12 @@ export type CreateChannelRouterOptions = {
|
|
|
1323
1454
|
// Returns the start time (epoch ms) of the NEWEST still-running background
|
|
1324
1455
|
// subagent spawned from `sessionId`, or null when none is running. Lets idle
|
|
1325
1456
|
// GC and stale-rollover pin a session whose child is still working (the next
|
|
1326
|
-
// inbound would otherwise spawn a duplicate child
|
|
1327
|
-
//
|
|
1328
|
-
//
|
|
1329
|
-
//
|
|
1330
|
-
//
|
|
1331
|
-
// means no pin.
|
|
1457
|
+
// inbound would otherwise spawn a duplicate child, and a completion arriving
|
|
1458
|
+
// after teardown is dropped), bounded only by SESSION_CHILD_STUCK_BACKSTOP_MS
|
|
1459
|
+
// measured from that start. Newest — not oldest — so a long-running child that
|
|
1460
|
+
// crossed the stuck backstop cannot unpin the session while a more recently
|
|
1461
|
+
// spawned child is still inside its window. Production wiring forwards the
|
|
1462
|
+
// LiveSubagentRegistry; omitted (tests, no-subagent setups) means no pin.
|
|
1332
1463
|
newestRunningChildSubagentStartedAt?: (sessionId: string) => number | null
|
|
1333
1464
|
}
|
|
1334
1465
|
|
|
@@ -1411,6 +1542,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
1411
1542
|
const removeReactionCallbacks = new Map<ChannelKey['adapter'], Set<RemoveReactionCallback>>()
|
|
1412
1543
|
const typingCallbacks = new Map<ChannelKey['adapter'], Set<TypingCallback>>()
|
|
1413
1544
|
const typingCapableAdapters = new Set<ChannelKey['adapter']>()
|
|
1545
|
+
const configuredAdapters = new Set<ChannelKey['adapter']>()
|
|
1414
1546
|
const channelNameResolvers = new Map<ChannelKey['adapter'], Set<ChannelNameResolver>>()
|
|
1415
1547
|
const membershipResolvers = new Map<ChannelKey['adapter'], Set<MembershipResolver>>()
|
|
1416
1548
|
const selfIdentityResolvers = new Map<ChannelKey['adapter'], ChannelSelfIdentityResolver>()
|
|
@@ -1657,19 +1789,21 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
1657
1789
|
}
|
|
1658
1790
|
|
|
1659
1791
|
// True while a background child spawned from this session is still running AND
|
|
1660
|
-
// the newest such child
|
|
1661
|
-
//
|
|
1662
|
-
//
|
|
1663
|
-
//
|
|
1664
|
-
//
|
|
1665
|
-
// GC/rollover defer to this.
|
|
1792
|
+
// the newest such child has not outlived the stuck backstop. Using the newest
|
|
1793
|
+
// child keeps the session pinned as long as ANY running child is still inside
|
|
1794
|
+
// its window — an older child past the backstop must not unpin the session out
|
|
1795
|
+
// from under a freshly spawned one. Tearing the session down mid-child lets the
|
|
1796
|
+
// next inbound spawn a duplicate child AND drops the child's completion when it
|
|
1797
|
+
// lands after teardown, so GC/rollover defer to this. Crossing the backstop is
|
|
1798
|
+
// an anomaly (a wedged, timeout-less child), logged at warn. `label` only
|
|
1799
|
+
// annotates the override log.
|
|
1666
1800
|
const isPinnedByRunningChild = (sessionId: string, keyId: string, label: string): boolean => {
|
|
1667
1801
|
const childStartedAt = newestRunningChildSubagentStartedAt(sessionId)
|
|
1668
1802
|
if (childStartedAt === null) return false
|
|
1669
1803
|
const pinnedForMs = now() - childStartedAt
|
|
1670
|
-
if (pinnedForMs <=
|
|
1671
|
-
logger.
|
|
1672
|
-
`[channels] ${keyId}: ${label} despite running child (newest pinned ${pinnedForMs}ms, past child
|
|
1804
|
+
if (pinnedForMs <= SESSION_CHILD_STUCK_BACKSTOP_MS) return true
|
|
1805
|
+
logger.warn(
|
|
1806
|
+
`[channels] ${keyId}: ${label} despite running child (newest pinned ${pinnedForMs}ms, past stuck-child backstop; suspected stuck running child)`,
|
|
1673
1807
|
)
|
|
1674
1808
|
return false
|
|
1675
1809
|
}
|
|
@@ -1923,6 +2057,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
1923
2057
|
typingStartedAt: 0,
|
|
1924
2058
|
typingTimedOut: false,
|
|
1925
2059
|
typingStopPromise: null,
|
|
2060
|
+
typingEpoch: 0,
|
|
1926
2061
|
promptInFlight: false,
|
|
1927
2062
|
lastInboundAt: now(),
|
|
1928
2063
|
baseContextBytes: 0,
|
|
@@ -1931,8 +2066,11 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
1931
2066
|
currentTurnAuthorIds: new Set(),
|
|
1932
2067
|
currentTurnReactionRef: null,
|
|
1933
2068
|
currentTurnTypingThread: null,
|
|
2069
|
+
dirtyTypingThreads: new Set(),
|
|
1934
2070
|
currentTurnEngageReactions: [],
|
|
1935
2071
|
pendingTurnReactions: [],
|
|
2072
|
+
silentAckTurn: null,
|
|
2073
|
+
activeSilentAckReactions: [],
|
|
1936
2074
|
// `lastTurnAuthorId` (string, used for `lastInboundAuthorId` in
|
|
1937
2075
|
// origin) and `lastTurnAuthorIds` (Set, used by
|
|
1938
2076
|
// `grantStickyForReplyTargets` as the fallback when
|
|
@@ -1956,6 +2094,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
1956
2094
|
inFlightToolSends: new Map(),
|
|
1957
2095
|
policyDeniedToolSendsThisTurn: new Map(),
|
|
1958
2096
|
emptyTurnRetries: 0,
|
|
2097
|
+
toolLeakRetries: 0,
|
|
1959
2098
|
emptyStopAfterToolWorkArmed: false,
|
|
1960
2099
|
willingnessNudges: 0,
|
|
1961
2100
|
lastTerminalReplyAbort: null,
|
|
@@ -1965,6 +2104,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
1965
2104
|
skipLockedSendTurn: null,
|
|
1966
2105
|
disengagedTurn: null,
|
|
1967
2106
|
emptyTurnFallbackTurn: null,
|
|
2107
|
+
githubReviewOutputTurn: null,
|
|
1968
2108
|
pendingQuoteCandidate: null,
|
|
1969
2109
|
recentEngagedPeerBotTurns: [],
|
|
1970
2110
|
consecutiveEngagedPeerBotTurns: 0,
|
|
@@ -1975,6 +2115,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
1975
2115
|
membershipFetch,
|
|
1976
2116
|
pendingProviderError: null,
|
|
1977
2117
|
destroyed: false,
|
|
2118
|
+
pendingTeardown: false,
|
|
1978
2119
|
unsubProviderErrors: null,
|
|
1979
2120
|
unsubTypingActivity: null,
|
|
1980
2121
|
unsubTodoOutcome: null,
|
|
@@ -2188,9 +2329,24 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2188
2329
|
await persist()
|
|
2189
2330
|
}
|
|
2190
2331
|
|
|
2191
|
-
const fireTyping = async (
|
|
2332
|
+
const fireTyping = async (
|
|
2333
|
+
live: LiveSession,
|
|
2334
|
+
phase: 'tick' | 'stop',
|
|
2335
|
+
epoch?: number,
|
|
2336
|
+
typingThreadOverride?: string,
|
|
2337
|
+
): Promise<void> => {
|
|
2338
|
+
// Drop a stale 'tick' that a since-cancelled interval still dispatched:
|
|
2339
|
+
// once the heartbeat stopped (or a new one started) the captured epoch no
|
|
2340
|
+
// longer matches, and forwarding it would re-set the indicator after the
|
|
2341
|
+
// stop clear. 'stop' is never epoch-gated — it must always clear. Marking
|
|
2342
|
+
// dirty happens after this gate so a dropped tick is never recorded.
|
|
2343
|
+
if (phase === 'tick' && epoch !== undefined && epoch !== live.typingEpoch) return
|
|
2192
2344
|
const callbacks = typingCallbacks.get(live.key.adapter)
|
|
2193
2345
|
if (!callbacks || callbacks.size === 0) return
|
|
2346
|
+
// A 'stop' clears an explicit anchor (fireTypingStop's per-dirty-thread
|
|
2347
|
+
// clear); a 'tick' always targets the live turn anchor.
|
|
2348
|
+
const typingThread = typingThreadOverride ?? live.currentTurnTypingThread
|
|
2349
|
+
if (phase === 'tick' && typingThread !== null) live.dirtyTypingThreads.add(typingThread)
|
|
2194
2350
|
// Snapshot before iterating: a callback could unregister mid-call.
|
|
2195
2351
|
const snapshot = Array.from(callbacks)
|
|
2196
2352
|
const target = {
|
|
@@ -2198,7 +2354,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2198
2354
|
workspace: live.key.workspace,
|
|
2199
2355
|
chat: live.key.chat,
|
|
2200
2356
|
thread: live.key.thread,
|
|
2201
|
-
...(
|
|
2357
|
+
...(typingThread !== null ? { typingThread } : {}),
|
|
2202
2358
|
phase,
|
|
2203
2359
|
}
|
|
2204
2360
|
await Promise.all(
|
|
@@ -2208,6 +2364,21 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2208
2364
|
}),
|
|
2209
2365
|
),
|
|
2210
2366
|
)
|
|
2367
|
+
if (phase === 'stop' && typingThread !== null) live.dirtyTypingThreads.delete(typingThread)
|
|
2368
|
+
}
|
|
2369
|
+
|
|
2370
|
+
// A 'stop' must clear EVERY flat-DM typingThread a tick set a status on this
|
|
2371
|
+
// session — not just the current anchor — or a migrated-away anchor strands
|
|
2372
|
+
// its "is typing..." (see `dirtyTypingThreads`). Clears run concurrently; each
|
|
2373
|
+
// dirty thread is dispatched once and removed by fireTyping's stop path.
|
|
2374
|
+
const fireTypingStop = async (live: LiveSession): Promise<void> => {
|
|
2375
|
+
const dirty = new Set(live.dirtyTypingThreads)
|
|
2376
|
+
if (live.currentTurnTypingThread !== null) dirty.add(live.currentTurnTypingThread)
|
|
2377
|
+
if (dirty.size === 0) {
|
|
2378
|
+
await fireTyping(live, 'stop')
|
|
2379
|
+
return
|
|
2380
|
+
}
|
|
2381
|
+
await Promise.all(Array.from(dirty, (typingThread) => fireTyping(live, 'stop', undefined, typingThread)))
|
|
2211
2382
|
}
|
|
2212
2383
|
|
|
2213
2384
|
const bumpTypingActivity = (live: LiveSession): void => {
|
|
@@ -2354,11 +2525,16 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2354
2525
|
bumpTypingActivity(live)
|
|
2355
2526
|
return
|
|
2356
2527
|
}
|
|
2528
|
+
const epoch = ++live.typingEpoch
|
|
2357
2529
|
live.typingStartedAt = now()
|
|
2358
2530
|
// Fire immediately so the indicator appears on the very first inbound,
|
|
2359
2531
|
// not 8 seconds later.
|
|
2360
|
-
void fireTyping(live, 'tick')
|
|
2532
|
+
void fireTyping(live, 'tick', epoch)
|
|
2361
2533
|
live.typingTimer = setInterval(() => {
|
|
2534
|
+
// A due callback can run one last time after stopTypingHeartbeat's
|
|
2535
|
+
// clearInterval; the epoch mismatch makes fireTyping drop the tick so it
|
|
2536
|
+
// can't re-set the indicator after the stop clear.
|
|
2537
|
+
if (epoch !== live.typingEpoch) return
|
|
2362
2538
|
if (live.destroyed) {
|
|
2363
2539
|
void stopTypingHeartbeat(live)
|
|
2364
2540
|
return
|
|
@@ -2371,11 +2547,15 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2371
2547
|
void stopTypingHeartbeat(live)
|
|
2372
2548
|
return
|
|
2373
2549
|
}
|
|
2374
|
-
void fireTyping(live, 'tick')
|
|
2550
|
+
void fireTyping(live, 'tick', epoch)
|
|
2375
2551
|
}, TYPING_HEARTBEAT_MS)
|
|
2376
2552
|
}
|
|
2377
2553
|
|
|
2378
2554
|
const stopTypingHeartbeat = async (live: LiveSession): Promise<void> => {
|
|
2555
|
+
// Bump first, before any early return: a stop must invalidate the current
|
|
2556
|
+
// generation so a due-but-not-yet-run interval tick is dropped by
|
|
2557
|
+
// fireTyping's epoch guard even if the timer was already cleared.
|
|
2558
|
+
live.typingEpoch++
|
|
2379
2559
|
if (!live.typingTimer) {
|
|
2380
2560
|
await live.typingStopPromise
|
|
2381
2561
|
return
|
|
@@ -2387,7 +2567,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2387
2567
|
// clear platform-side state (e.g. Slack's 2-min server timeout) on
|
|
2388
2568
|
// teardown. The FIFO inside the slack adapter ensures this clear lands
|
|
2389
2569
|
// AFTER any in-flight 'tick' from the heartbeat that just stopped.
|
|
2390
|
-
const stopped =
|
|
2570
|
+
const stopped = fireTypingStop(live).finally(() => {
|
|
2391
2571
|
if (live.typingStopPromise === stopped) live.typingStopPromise = null
|
|
2392
2572
|
})
|
|
2393
2573
|
live.typingStopPromise = stopped
|
|
@@ -2579,7 +2759,17 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2579
2759
|
if (live.draining || live.destroyed) return
|
|
2580
2760
|
live.draining = true
|
|
2581
2761
|
try {
|
|
2582
|
-
|
|
2762
|
+
// `!live.pendingTeardown`: once a reload marks this draining session for
|
|
2763
|
+
// teardown, finish ONLY the in-flight prompt (its batch was already
|
|
2764
|
+
// spliced out of promptQueue at the top of the current iteration) and
|
|
2765
|
+
// stop — do NOT splice a fresh batch of post-reload inbounds onto the
|
|
2766
|
+
// stale, about-to-be-recreated session. Those queued inbounds are handed
|
|
2767
|
+
// to the fresh successor in the teardown block below.
|
|
2768
|
+
while (
|
|
2769
|
+
(live.promptQueue.length > 0 || live.pendingSystemReminders.length > 0) &&
|
|
2770
|
+
!live.destroyed &&
|
|
2771
|
+
!live.pendingTeardown
|
|
2772
|
+
) {
|
|
2583
2773
|
live.typingTimedOut = false
|
|
2584
2774
|
// Each turn starts with no held reactions; the model re-requests them
|
|
2585
2775
|
// via channel_react during this turn, and the finally flushes or drops.
|
|
@@ -2623,10 +2813,15 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2623
2813
|
// iterations the retry itself queues do not refill the budget and loop
|
|
2624
2814
|
// forever (and the raised cap stays scoped to the turn that set it).
|
|
2625
2815
|
live.emptyTurnRetries = 0
|
|
2816
|
+
live.toolLeakRetries = 0
|
|
2626
2817
|
live.emptyStopAfterToolWorkArmed = false
|
|
2627
2818
|
live.willingnessNudges = 0
|
|
2628
2819
|
live.abortReasonThisTurn = null
|
|
2629
2820
|
live.nextPromptMaxTokens = undefined
|
|
2821
|
+
// Cleared with the retry budgets (NOT beside resetReviewTurn below) so a
|
|
2822
|
+
// review landed earlier in this logical turn keeps suppressing the
|
|
2823
|
+
// empty-turn fallback across the reminder-only retry iterations.
|
|
2824
|
+
live.githubReviewOutputTurn = null
|
|
2630
2825
|
} else if (live.lastTurnAuthorId !== null) {
|
|
2631
2826
|
live.currentTurnEngageReactions = []
|
|
2632
2827
|
// Reminder-only turn (batch.length === 0, reminders.length > 0):
|
|
@@ -2672,6 +2867,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2672
2867
|
const promptStart = now()
|
|
2673
2868
|
const successfulSendsBeforePrompt = live.successfulChannelSends
|
|
2674
2869
|
const emptyTurnRetriesBeforePrompt = live.emptyTurnRetries
|
|
2870
|
+
const toolLeakRetriesBeforePrompt = live.toolLeakRetries
|
|
2675
2871
|
const engageAddPromises = live.currentTurnEngageReactions
|
|
2676
2872
|
live.turnSeq++
|
|
2677
2873
|
live.successfulSendsAtTurnStart = successfulSendsBeforePrompt
|
|
@@ -2721,14 +2917,19 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2721
2917
|
// usable assistant reply (real model prose the user saw) seeds the next
|
|
2722
2918
|
// turn's escalation. Every other terminal outcome CLEARS lastQuestionSignal
|
|
2723
2919
|
// so an older question can't leak across the failed/silent turn:
|
|
2724
|
-
// - retry queued (`length`/`aborted`, budget left
|
|
2725
|
-
//
|
|
2920
|
+
// - retry queued (`length`/`aborted`, budget left, OR a tool-call
|
|
2921
|
+
// leak nudged a self-correction retry): turn still in flight →
|
|
2922
|
+
// leave both for the reminder-only iteration that ends it.
|
|
2726
2923
|
// - usable reply → commit the pending signal.
|
|
2727
2924
|
// - provider error / empty-turn fallback / NO_REPLY / skip (no usable
|
|
2728
2925
|
// reply) → clear BOTH (pending and lastQuestionSignal).
|
|
2729
2926
|
// A fallback sends via source:'system', which also bumps
|
|
2730
|
-
// successfulChannelSends, so it must be excluded explicitly.
|
|
2731
|
-
|
|
2927
|
+
// successfulChannelSends, so it must be excluded explicitly. Both retry
|
|
2928
|
+
// budgets keep the logical turn open, so both must count here — a
|
|
2929
|
+
// tool-leak retry that later replies must commit the signal AT the
|
|
2930
|
+
// successful retry, not clear it after the first suppressed attempt.
|
|
2931
|
+
const retryQueuedThisTurn =
|
|
2932
|
+
live.emptyTurnRetries > emptyTurnRetriesBeforePrompt || live.toolLeakRetries > toolLeakRetriesBeforePrompt
|
|
2732
2933
|
const providerErrorThisTurn = assistantLeafStopReason(live.session) === 'error'
|
|
2733
2934
|
const fallbackPostedThisTurn = live.emptyTurnFallbackTurn === live.turnSeq
|
|
2734
2935
|
const sentReplyThisTurn = live.successfulChannelSends > successfulSendsBeforePrompt
|
|
@@ -2759,7 +2960,24 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2759
2960
|
} finally {
|
|
2760
2961
|
live.promptInFlight = false
|
|
2761
2962
|
const sentReplyThisTurn = live.successfulChannelSends > successfulSendsBeforePrompt
|
|
2762
|
-
|
|
2963
|
+
// The eager :eyes: ack is a "looking at this" signal, not a "replied"
|
|
2964
|
+
// one, so it comes off at turn end no matter the outcome — a reply, but
|
|
2965
|
+
// also silence, skip_response, an empty turn, or a provider error
|
|
2966
|
+
// (observe-after-engage). Leaving it only on the reply path stranded the
|
|
2967
|
+
// ack permanently on messages the agent looked at but never answered.
|
|
2968
|
+
const dropDone = dropEngageReactions(live, engageAddPromises)
|
|
2969
|
+
// A DELIBERATE silent turn (skip_response / NO_REPLY) leaves a
|
|
2970
|
+
// PERSISTENT :eyes: acking "seen, intentionally not replying". On a
|
|
2971
|
+
// typing-less adapter it reuses the same message/emoji/actor as the
|
|
2972
|
+
// transient engage :eyes:, and adapters that collapse that into one
|
|
2973
|
+
// toggle would let a still-in-flight engage removal strip the ack — so
|
|
2974
|
+
// the silent path AWAITS every engage removal reaching the adapter
|
|
2975
|
+
// before adding the persistent one. Only silent turns pay that wait:
|
|
2976
|
+
// normal/reply turns keep the engage drop fire-and-forget (`void`), so
|
|
2977
|
+
// turn-end never blocks on the reaction API off the silent path.
|
|
2978
|
+
if (live.silentAckTurn?.turnSeq === live.turnSeq) await dropDone
|
|
2979
|
+
else void dropDone
|
|
2980
|
+
reactOnSilentAck(live)
|
|
2763
2981
|
// Held channel_react reactions apply only when the agent posted a
|
|
2764
2982
|
// genuine reply this turn — NOT an empty-turn fallback or provider-
|
|
2765
2983
|
// error notice, both of which send via source:'system' and bump
|
|
@@ -2771,10 +2989,15 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2771
2989
|
sentReplyThisTurn &&
|
|
2772
2990
|
live.emptyTurnFallbackTurn !== live.turnSeq &&
|
|
2773
2991
|
assistantLeafStopReason(live.session) !== 'error'
|
|
2774
|
-
if (usableReplyThisTurn)
|
|
2775
|
-
|
|
2776
|
-
|
|
2777
|
-
|
|
2992
|
+
if (usableReplyThisTurn) {
|
|
2993
|
+
flushPendingReactions(live)
|
|
2994
|
+
void dropSilentAckReactions(live)
|
|
2995
|
+
} else live.pendingTurnReactions = []
|
|
2996
|
+
// Either retry budget keeps the turn in flight, so a deferred provider
|
|
2997
|
+
// error must wait for the reminder-only iteration that actually ends it.
|
|
2998
|
+
const retryQueuedThisTurn =
|
|
2999
|
+
live.emptyTurnRetries > emptyTurnRetriesBeforePrompt || live.toolLeakRetries > toolLeakRetriesBeforePrompt
|
|
3000
|
+
await maybePostDeferredProviderError(live, sentReplyThisTurn, retryQueuedThisTurn)
|
|
2778
3001
|
await fireSessionTurnEnd(live)
|
|
2779
3002
|
}
|
|
2780
3003
|
await fireSessionIdle(live)
|
|
@@ -2801,6 +3024,60 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2801
3024
|
await stopTypingHeartbeat(live)
|
|
2802
3025
|
live.currentTurnTypingThread = null
|
|
2803
3026
|
}
|
|
3027
|
+
// A reload deferred this session's teardown so its in-flight reply could
|
|
3028
|
+
// land; now that the turn drained (and the loop stopped BEFORE draining any
|
|
3029
|
+
// post-reload inbound), complete the recreate so the fresh session picks up
|
|
3030
|
+
// the swapped role/auth/prompt state. Guarded on !destroyed so a concurrent
|
|
3031
|
+
// stop()/idle-gc that already tore it down wins the race without a double
|
|
3032
|
+
// teardown.
|
|
3033
|
+
if (live.pendingTeardown && !live.destroyed) {
|
|
3034
|
+
live.pendingTeardown = false
|
|
3035
|
+
// Snapshot the post-reload inbounds that arrived during the held prompt
|
|
3036
|
+
// BEFORE tearDownLive (its clearQueuedEngageReactions must not drop the
|
|
3037
|
+
// engage acks we are handing to the successor). Clear the source arrays so
|
|
3038
|
+
// the dying session owns nothing we are moving forward.
|
|
3039
|
+
const carriedInbounds = live.promptQueue.splice(0, live.promptQueue.length)
|
|
3040
|
+
const carriedObserved = live.contextBuffer.splice(0, live.contextBuffer.length)
|
|
3041
|
+
const carriedReminders = live.pendingSystemReminders.splice(0, live.pendingSystemReminders.length)
|
|
3042
|
+
liveSessions.delete(live.keyId)
|
|
3043
|
+
await tearDownLive(live)
|
|
3044
|
+
await handOffToSuccessor(live.key, carriedInbounds, carriedObserved, carriedReminders)
|
|
3045
|
+
}
|
|
3046
|
+
}
|
|
3047
|
+
|
|
3048
|
+
// Rebuild a live session for a channel key after a reload tore its predecessor
|
|
3049
|
+
// down mid-drain, and replay the post-reload work that predecessor never got
|
|
3050
|
+
// to process. The carried inbounds already have their engagement decided (they
|
|
3051
|
+
// were enqueued while draining), so they are transplanted straight onto the
|
|
3052
|
+
// fresh session's queues rather than re-routed through route() — re-routing
|
|
3053
|
+
// would re-run the claim/command/permission gates and re-derive engagement
|
|
3054
|
+
// from a lossy QueuedInbound projection. Best-effort: a recreate failure logs
|
|
3055
|
+
// and drops the batch rather than throwing out of the predecessor's drain.
|
|
3056
|
+
const handOffToSuccessor = async (
|
|
3057
|
+
key: ChannelKey,
|
|
3058
|
+
inbounds: QueuedInbound[],
|
|
3059
|
+
observed: ObservedInbound[],
|
|
3060
|
+
reminders: string[],
|
|
3061
|
+
): Promise<void> => {
|
|
3062
|
+
// Observed context alone is carried too: observe() can buffer post-reload
|
|
3063
|
+
// messages onto contextBuffer with no queued prompt, and dropping them would
|
|
3064
|
+
// lose the successor's "recent context". Only skip when nothing at all was
|
|
3065
|
+
// carried.
|
|
3066
|
+
if (inbounds.length === 0 && reminders.length === 0 && observed.length === 0) return
|
|
3067
|
+
let successor: LiveSession
|
|
3068
|
+
try {
|
|
3069
|
+
successor = await ensureLive(key)
|
|
3070
|
+
} catch (err) {
|
|
3071
|
+
logger.warn(`[channels] ${channelKeyId(key)}: successor recreate after reload failed: ${describe(err)}`)
|
|
3072
|
+
return
|
|
3073
|
+
}
|
|
3074
|
+
if (successor.destroyed) return
|
|
3075
|
+
successor.promptQueue.push(...inbounds)
|
|
3076
|
+
successor.contextBuffer.push(...observed)
|
|
3077
|
+
successor.pendingSystemReminders.push(...reminders)
|
|
3078
|
+
// Observed-only context is NOT a turn trigger — it waits on contextBuffer for
|
|
3079
|
+
// a real inbound. Drain only when there is actual work (a prompt or reminder).
|
|
3080
|
+
if ((inbounds.length > 0 || reminders.length > 0) && !successor.draining) void drain(successor)
|
|
2804
3081
|
}
|
|
2805
3082
|
|
|
2806
3083
|
const scheduleDebouncedDrain = (live: LiveSession): void => {
|
|
@@ -3364,8 +3641,12 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3364
3641
|
return addReactionRef
|
|
3365
3642
|
}
|
|
3366
3643
|
|
|
3367
|
-
|
|
3368
|
-
|
|
3644
|
+
// Returns a promise that settles only once every engage removal has REACHED
|
|
3645
|
+
// the adapter, not merely been scheduled. The silent-ack path awaits this so
|
|
3646
|
+
// its persistent :eyes: is added strictly AFTER the transient one is removed
|
|
3647
|
+
// (see reactOnSilentAck). Fire-and-forget callers just `void` the result.
|
|
3648
|
+
const dropEngageReactions = (live: LiveSession, addPromises: Array<Promise<ReactionRef | null>>): Promise<void> => {
|
|
3649
|
+
return Promise.all(addPromises.map((addPromise) => dropOneEngageReaction(live, addPromise))).then(() => undefined)
|
|
3369
3650
|
}
|
|
3370
3651
|
|
|
3371
3652
|
// Only the LAST engaging inbound of a coalesced batch should carry the eager
|
|
@@ -3377,11 +3658,11 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3377
3658
|
const addPromises = live.promptQueue.flatMap((m) => (m.engageReaction !== undefined ? [m.engageReaction] : []))
|
|
3378
3659
|
if (addPromises.length === 0) return
|
|
3379
3660
|
for (const item of live.promptQueue) delete item.engageReaction
|
|
3380
|
-
dropEngageReactions(live, addPromises)
|
|
3661
|
+
void dropEngageReactions(live, addPromises)
|
|
3381
3662
|
}
|
|
3382
3663
|
|
|
3383
|
-
const dropOneEngageReaction = (live: LiveSession, addPromise: Promise<ReactionRef | null>): void => {
|
|
3384
|
-
|
|
3664
|
+
const dropOneEngageReaction = (live: LiveSession, addPromise: Promise<ReactionRef | null>): Promise<void> => {
|
|
3665
|
+
return addPromise
|
|
3385
3666
|
.then((reactionRef) => {
|
|
3386
3667
|
if (reactionRef === null) return undefined
|
|
3387
3668
|
return removeReaction({
|
|
@@ -3428,6 +3709,11 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3428
3709
|
else typingCapableAdapters.delete(adapter)
|
|
3429
3710
|
}
|
|
3430
3711
|
|
|
3712
|
+
const setAdapterConfigured = (adapter: ChannelKey['adapter'], configured: boolean): void => {
|
|
3713
|
+
if (configured) configuredAdapters.add(adapter)
|
|
3714
|
+
else configuredAdapters.delete(adapter)
|
|
3715
|
+
}
|
|
3716
|
+
|
|
3431
3717
|
const registerChannelNameResolver = (adapter: ChannelKey['adapter'], resolver: ChannelNameResolver): void => {
|
|
3432
3718
|
let set = channelNameResolvers.get(adapter)
|
|
3433
3719
|
if (!set) {
|
|
@@ -3492,10 +3778,18 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3492
3778
|
historyCallbacks.get(adapter)?.delete(cb)
|
|
3493
3779
|
}
|
|
3494
3780
|
|
|
3781
|
+
const isReadCapabilityUnavailable = (adapter: ChannelKey['adapter'], capability: ReadCapability): boolean =>
|
|
3782
|
+
configuredAdapters.has(adapter) && ADAPTER_READ_CAPABILITIES[adapter].includes(capability)
|
|
3783
|
+
|
|
3784
|
+
const missingCallbackError = (adapter: ChannelKey['adapter'], capability: ReadCapability): string =>
|
|
3785
|
+
isReadCapabilityUnavailable(adapter, capability)
|
|
3786
|
+
? `${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)`
|
|
3787
|
+
: `${capability}-not-supported`
|
|
3788
|
+
|
|
3495
3789
|
const fetchHistory = async (adapter: ChannelKey['adapter'], args: FetchHistoryArgs): Promise<FetchHistoryResult> => {
|
|
3496
3790
|
const callbacks = historyCallbacks.get(adapter)
|
|
3497
3791
|
if (!callbacks || callbacks.size === 0) {
|
|
3498
|
-
return { ok: false, error: 'history
|
|
3792
|
+
return { ok: false, error: missingCallbackError(adapter, 'history') }
|
|
3499
3793
|
}
|
|
3500
3794
|
// Snapshot before iterating, mirroring `send`: a callback that mutates
|
|
3501
3795
|
// the set (e.g. unregisters mid-call) must not skip siblings.
|
|
@@ -3524,7 +3818,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3524
3818
|
|
|
3525
3819
|
const getMessage = async (adapter: ChannelKey['adapter'], args: GetMessageArgs): Promise<GetMessageResult> => {
|
|
3526
3820
|
const cb = messageGetCallbacks.get(adapter)
|
|
3527
|
-
if (cb === undefined)
|
|
3821
|
+
if (cb === undefined)
|
|
3822
|
+
return isReadCapabilityUnavailable(adapter, 'message-get')
|
|
3823
|
+
? { ok: false, error: missingCallbackError(adapter, 'message-get'), code: 'adapter-unavailable' }
|
|
3824
|
+
: { ok: false, error: 'message-get-not-supported', code: 'not-supported' }
|
|
3528
3825
|
try {
|
|
3529
3826
|
return await raceWithTimeout(cb(args), fetchHistoryTimeoutMs, `[channels] ${adapter} message get`)
|
|
3530
3827
|
} catch (err) {
|
|
@@ -3543,7 +3840,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3543
3840
|
|
|
3544
3841
|
const listChannels = async (adapter: ChannelKey['adapter'], args: ListChannelsArgs): Promise<ListChannelsResult> => {
|
|
3545
3842
|
const cb = listCallbacks.get(adapter)
|
|
3546
|
-
if (cb === undefined)
|
|
3843
|
+
if (cb === undefined)
|
|
3844
|
+
return isReadCapabilityUnavailable(adapter, 'list')
|
|
3845
|
+
? { ok: false, error: missingCallbackError(adapter, 'list'), code: 'adapter-unavailable' }
|
|
3846
|
+
: { ok: false, error: 'list-not-supported', code: 'not-supported' }
|
|
3547
3847
|
try {
|
|
3548
3848
|
return await raceWithTimeout(cb(args), fetchHistoryTimeoutMs, `[channels] ${adapter} list channels`)
|
|
3549
3849
|
} catch (err) {
|
|
@@ -3978,6 +4278,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3978
4278
|
const { reason } = live.skippedTurn
|
|
3979
4279
|
live.skippedTurn = null
|
|
3980
4280
|
logger.info(`[channels] ${live.keyId} skipped_by_tool reason=${JSON.stringify(reason)}`)
|
|
4281
|
+
armSilentTurnAck(live, 'skip_response')
|
|
3981
4282
|
return
|
|
3982
4283
|
}
|
|
3983
4284
|
if (live.skippedTurn !== null && live.skippedTurn.turnSeq === live.turnSeq) {
|
|
@@ -4003,6 +4304,45 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
4003
4304
|
}
|
|
4004
4305
|
}
|
|
4005
4306
|
|
|
4307
|
+
// A formal GitHub review already landed this logical turn (APPROVE /
|
|
4308
|
+
// REQUEST_CHANGES / COMMENT, stamped via noteGithubReviewOutput). That review IS
|
|
4309
|
+
// the turn's user-facing output — it just went through the GitHub review API, not
|
|
4310
|
+
// channel_reply/channel_send, so `successfulChannelSends` never moved. An empty
|
|
4311
|
+
// completion afterward is the agent legitimately having nothing more to say, NOT
|
|
4312
|
+
// a dead turn: skip the empty-turn retries AND the "I got stuck" fallback and
|
|
4313
|
+
// treat it as silent completion. Gated on no channel send this turn so a turn
|
|
4314
|
+
// that ALSO replied in-channel still runs the normal reply-recovery below.
|
|
4315
|
+
if (
|
|
4316
|
+
live.githubReviewOutputTurn === live.turnSeq &&
|
|
4317
|
+
live.successfulChannelSends === successfulSendsBeforePrompt &&
|
|
4318
|
+
live.currentTurnAuthorId !== null
|
|
4319
|
+
) {
|
|
4320
|
+
logger.info(`[channels] ${live.keyId} empty_turn_suppressed cause=github_review_output_this_turn`)
|
|
4321
|
+
armSilentTurnAck(live, 'github_review_output')
|
|
4322
|
+
return
|
|
4323
|
+
}
|
|
4324
|
+
|
|
4325
|
+
// Suppress a leaked tool call (never post the plumbing) and, while budget
|
|
4326
|
+
// remains, push a self-correction reminder so the same logical turn
|
|
4327
|
+
// re-prompts and the model can redo it with a real tool call. On exhaustion
|
|
4328
|
+
// we stay silent — a persistently-leaking model must not livelock, and
|
|
4329
|
+
// silence is safer than posting a fallback the user didn't ask for.
|
|
4330
|
+
const suppressToolLeakAndNudge = (live: LiveSession, leakedText: string): void => {
|
|
4331
|
+
if (live.toolLeakRetries < MAX_TOOL_LEAK_RETRIES) {
|
|
4332
|
+
live.toolLeakRetries++
|
|
4333
|
+
logger.warn(
|
|
4334
|
+
`[channels] ${live.keyId}: suppressed plain_text_tool_call_leak (nudge ` +
|
|
4335
|
+
`attempt=${live.toolLeakRetries}/${MAX_TOOL_LEAK_RETRIES}) text_len=${leakedText.length}`,
|
|
4336
|
+
)
|
|
4337
|
+
live.pendingSystemReminders.push(TOOL_CALL_LEAK_NUDGE)
|
|
4338
|
+
return
|
|
4339
|
+
}
|
|
4340
|
+
logger.warn(
|
|
4341
|
+
`[channels] ${live.keyId}: suppressed plain_text_tool_call_leak (retries exhausted, silent) ` +
|
|
4342
|
+
`text_len=${leakedText.length}`,
|
|
4343
|
+
)
|
|
4344
|
+
}
|
|
4345
|
+
|
|
4006
4346
|
// A send landed this turn, but the model may have posted a `continue: true`
|
|
4007
4347
|
// progress reply, kept working, then ENDED with its final answer as plain
|
|
4008
4348
|
// prose — never calling a channel tool again. The terminal-reply abort fires
|
|
@@ -4276,6 +4616,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
4276
4616
|
}
|
|
4277
4617
|
const leakedReasoning = !isNoReplySignal(assistantText)
|
|
4278
4618
|
logger.info(`[channels] ${live.keyId} no_reply${leakedReasoning ? ' (with_leaked_reasoning)' : ''}`)
|
|
4619
|
+
armSilentTurnAck(live, 'no_reply')
|
|
4279
4620
|
return
|
|
4280
4621
|
}
|
|
4281
4622
|
|
|
@@ -4291,28 +4632,34 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
4291
4632
|
return
|
|
4292
4633
|
}
|
|
4293
4634
|
|
|
4294
|
-
// Plain-text tool-call leak: the model serialized a
|
|
4295
|
-
//
|
|
4296
|
-
//
|
|
4297
|
-
//
|
|
4298
|
-
//
|
|
4299
|
-
//
|
|
4300
|
-
//
|
|
4635
|
+
// Plain-text tool-call leak: the model serialized a tool call as ordinary
|
|
4636
|
+
// message text instead of producing a real tool call. Default is SUPPRESS —
|
|
4637
|
+
// that raw plumbing must never reach the channel. The two exceptions are
|
|
4638
|
+
// `channel_reply` / `channel_send`, whose leaked form carries a salvageable
|
|
4639
|
+
// user message: extract the `text` arg and recover the actual reply.
|
|
4640
|
+
// `suppress-silent` (skip_response) drops without a nudge because the model
|
|
4641
|
+
// already got the silence it asked for; `suppress-warn` (every other leaked
|
|
4642
|
+
// call) drops AND re-prompts the model to redo the turn with a real tool
|
|
4643
|
+
// call, bounded by MAX_TOOL_LEAK_RETRIES so it can't livelock.
|
|
4301
4644
|
const plainTextToolCallKind = getPlainTextChannelToolCallKind(assistantText)
|
|
4302
|
-
if (plainTextToolCallKind === '
|
|
4645
|
+
if (plainTextToolCallKind === 'suppress-silent') {
|
|
4303
4646
|
logger.warn(
|
|
4304
|
-
`[channels] ${live.keyId}: suppressed
|
|
4647
|
+
`[channels] ${live.keyId}: suppressed plain_text_tool_call_leak (silent) text_len=${assistantText.length}`,
|
|
4305
4648
|
)
|
|
4649
|
+
armSilentTurnAck(live, 'skip_response_text_leak')
|
|
4650
|
+
return
|
|
4651
|
+
}
|
|
4652
|
+
if (plainTextToolCallKind === 'suppress-warn') {
|
|
4653
|
+
suppressToolLeakAndNudge(live, assistantText)
|
|
4306
4654
|
return
|
|
4307
4655
|
}
|
|
4308
4656
|
if (plainTextToolCallKind !== null) {
|
|
4309
4657
|
const extracted = extractPlainTextChannelToolCallText(assistantText)
|
|
4310
|
-
//
|
|
4311
|
-
//
|
|
4658
|
+
// A reply/send leak with no recoverable `text` (missing arg, empty value,
|
|
4659
|
+
// or fully-truncated) still owes the user a real message — treat it as a
|
|
4660
|
+
// warn-worthy leak, not a silent drop, so the model retries properly.
|
|
4312
4661
|
if (extracted === null) {
|
|
4313
|
-
|
|
4314
|
-
`[channels] ${live.keyId}: suppressed unextractable_plain_text_channel_tool_call text_len=${assistantText.length}`,
|
|
4315
|
-
)
|
|
4662
|
+
suppressToolLeakAndNudge(live, assistantText)
|
|
4316
4663
|
return
|
|
4317
4664
|
}
|
|
4318
4665
|
// The extracted value is still untrusted model output: if it is itself a
|
|
@@ -4571,11 +4918,26 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
4571
4918
|
const tearDownAllLive = async (): Promise<void> => {
|
|
4572
4919
|
liveGeneration++
|
|
4573
4920
|
const all = Array.from(liveSessions.values())
|
|
4921
|
+
// A session mid-turn is deferred, not aborted: tearing it down here calls
|
|
4922
|
+
// session.abort(), which kills the in-flight reply — including the very turn
|
|
4923
|
+
// that triggered this reload, leaving the user in silence. Such a session
|
|
4924
|
+
// stays in liveSessions (so a concurrent inbound coalesces into the running
|
|
4925
|
+
// turn instead of spawning a duplicate) and is torn down by the drain
|
|
4926
|
+
// finally once its turn drains. Idle sessions tear down immediately below.
|
|
4927
|
+
const deferred: LiveSession[] = []
|
|
4928
|
+
const immediate: LiveSession[] = []
|
|
4929
|
+
for (const live of all) {
|
|
4930
|
+
if (live.draining && !live.destroyed) {
|
|
4931
|
+
live.pendingTeardown = true
|
|
4932
|
+
deferred.push(live)
|
|
4933
|
+
} else immediate.push(live)
|
|
4934
|
+
}
|
|
4574
4935
|
liveSessions.clear()
|
|
4936
|
+
for (const live of deferred) liveSessions.set(live.keyId, live)
|
|
4575
4937
|
// Seal only around the flush — unlike stop() the router keeps serving after a
|
|
4576
4938
|
// roles reload, so re-enable persist() once pending writes have drained.
|
|
4577
4939
|
closing = true
|
|
4578
|
-
for (const live of
|
|
4940
|
+
for (const live of immediate) {
|
|
4579
4941
|
await tearDownLive(live)
|
|
4580
4942
|
}
|
|
4581
4943
|
await persistChain
|
|
@@ -4890,6 +5252,30 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
4890
5252
|
return { kind: 'delivered', count }
|
|
4891
5253
|
}
|
|
4892
5254
|
|
|
5255
|
+
// Stamp the review-output flag on the session that just landed a formal GitHub
|
|
5256
|
+
// review this turn. Matched by sessionId (the recorder records the exact
|
|
5257
|
+
// event.sessionId), and confirmed to be the right github PR live session so a
|
|
5258
|
+
// stray/mismatched signal can't suppress an unrelated turn's fallback. See
|
|
5259
|
+
// `githubReviewOutputTurn`.
|
|
5260
|
+
const noteGithubReviewOutput = (args: {
|
|
5261
|
+
sessionId: string
|
|
5262
|
+
workspace: string
|
|
5263
|
+
prNumber: number
|
|
5264
|
+
state: ReviewOutputState
|
|
5265
|
+
}): { kind: 'stamped' | 'no-live-session' } => {
|
|
5266
|
+
const chat = `pr:${args.prNumber}`
|
|
5267
|
+
for (const live of liveSessions.values()) {
|
|
5268
|
+
if (live.destroyed) continue
|
|
5269
|
+
if (live.sessionId !== args.sessionId) continue
|
|
5270
|
+
if (live.key.adapter !== 'github') continue
|
|
5271
|
+
if (live.key.workspace !== args.workspace || live.key.chat !== chat) continue
|
|
5272
|
+
live.githubReviewOutputTurn = live.turnSeq
|
|
5273
|
+
logger.info(`[channels] ${live.keyId}: github_review_output state=${args.state} turn=${live.turnSeq}`)
|
|
5274
|
+
return { kind: 'stamped' }
|
|
5275
|
+
}
|
|
5276
|
+
return { kind: 'no-live-session' }
|
|
5277
|
+
}
|
|
5278
|
+
|
|
4893
5279
|
const markTurnSkipped = (args: {
|
|
4894
5280
|
parentSessionId: string
|
|
4895
5281
|
reason: string
|
|
@@ -4957,6 +5343,82 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
4957
5343
|
})
|
|
4958
5344
|
}
|
|
4959
5345
|
|
|
5346
|
+
const armSilentTurnAck = (live: LiveSession, reason: SilentAckReason): void => {
|
|
5347
|
+
live.silentAckTurn = { turnSeq: live.turnSeq, reason }
|
|
5348
|
+
}
|
|
5349
|
+
|
|
5350
|
+
const reactOnSilentAck = (live: LiveSession): void => {
|
|
5351
|
+
if (live.silentAckTurn?.turnSeq !== live.turnSeq) return
|
|
5352
|
+
const { reason } = live.silentAckTurn
|
|
5353
|
+
live.silentAckTurn = null
|
|
5354
|
+
const reactionRef = live.currentTurnReactionRef
|
|
5355
|
+
if (reactionRef === null) return
|
|
5356
|
+
const addResult = react({
|
|
5357
|
+
adapter: live.key.adapter,
|
|
5358
|
+
workspace: live.key.workspace,
|
|
5359
|
+
chat: live.key.chat,
|
|
5360
|
+
thread: live.key.thread,
|
|
5361
|
+
reactionRef,
|
|
5362
|
+
emoji: ENGAGE_REACTION_EMOJI,
|
|
5363
|
+
})
|
|
5364
|
+
void addResult
|
|
5365
|
+
.then((result) => {
|
|
5366
|
+
if (!result.ok && result.code !== 'unsupported') {
|
|
5367
|
+
logger.info(
|
|
5368
|
+
`[channels] silent-ack-react failed reason=${reason} adapter=${live.key.adapter} chat=${live.key.chat}: ${result.error}`,
|
|
5369
|
+
)
|
|
5370
|
+
}
|
|
5371
|
+
})
|
|
5372
|
+
.catch((err) => {
|
|
5373
|
+
logger.info(
|
|
5374
|
+
`[channels] silent-ack-react threw reason=${reason} adapter=${live.key.adapter} chat=${live.key.chat}: ${describe(err)}`,
|
|
5375
|
+
)
|
|
5376
|
+
})
|
|
5377
|
+
// Register the add promise (not its resolved ref) SYNCHRONOUSLY, so a later
|
|
5378
|
+
// replied-turn cleanup can never race ahead of a still-in-flight add.
|
|
5379
|
+
live.activeSilentAckReactions.push(addResult.then((r) => (r.ok ? (r.reactionRef ?? null) : null)).catch(() => null))
|
|
5380
|
+
}
|
|
5381
|
+
|
|
5382
|
+
// Retire every persistent silent-ack :eyes: outstanding in this live session
|
|
5383
|
+
// once the agent posts a genuine reply — the "seen, not replying" mark is now
|
|
5384
|
+
// contradicted. Snapshot-and-clear the promise array BEFORE awaiting, so a
|
|
5385
|
+
// concurrent later silent turn appending a fresh add is never swept by this
|
|
5386
|
+
// in-flight cleanup. Each entry is AWAITED to its resolved ref before removal,
|
|
5387
|
+
// so an add still in flight when the reply lands is still retired. Failures are
|
|
5388
|
+
// logged, never retried: stale emoji cleanup must never block routing.
|
|
5389
|
+
const dropSilentAckReactions = (live: LiveSession): Promise<void> => {
|
|
5390
|
+
const addPromises = live.activeSilentAckReactions
|
|
5391
|
+
if (addPromises.length === 0) return Promise.resolve()
|
|
5392
|
+
live.activeSilentAckReactions = []
|
|
5393
|
+
return Promise.all(
|
|
5394
|
+
addPromises.map((addPromise) =>
|
|
5395
|
+
addPromise
|
|
5396
|
+
.then((reactionRef) => {
|
|
5397
|
+
if (reactionRef === null) return undefined
|
|
5398
|
+
return removeReaction({
|
|
5399
|
+
adapter: live.key.adapter,
|
|
5400
|
+
workspace: live.key.workspace,
|
|
5401
|
+
chat: live.key.chat,
|
|
5402
|
+
thread: live.key.thread,
|
|
5403
|
+
reactionRef,
|
|
5404
|
+
})
|
|
5405
|
+
})
|
|
5406
|
+
.then((result) => {
|
|
5407
|
+
if (result && !result.ok && result.code !== 'unsupported' && result.code !== 'not-found') {
|
|
5408
|
+
logger.info(
|
|
5409
|
+
`[channels] silent-ack-unreact failed adapter=${live.key.adapter} chat=${live.key.chat}: ${result.error}`,
|
|
5410
|
+
)
|
|
5411
|
+
}
|
|
5412
|
+
})
|
|
5413
|
+
.catch((err) => {
|
|
5414
|
+
logger.info(
|
|
5415
|
+
`[channels] silent-ack-unreact threw adapter=${live.key.adapter} chat=${live.key.chat}: ${describe(err)}`,
|
|
5416
|
+
)
|
|
5417
|
+
}),
|
|
5418
|
+
),
|
|
5419
|
+
).then(() => undefined)
|
|
5420
|
+
}
|
|
5421
|
+
|
|
4960
5422
|
return {
|
|
4961
5423
|
route,
|
|
4962
5424
|
send,
|
|
@@ -4974,6 +5436,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
4974
5436
|
registerTyping,
|
|
4975
5437
|
unregisterTyping,
|
|
4976
5438
|
setTypingCapability,
|
|
5439
|
+
setAdapterConfigured,
|
|
4977
5440
|
registerChannelNameResolver,
|
|
4978
5441
|
unregisterChannelNameResolver,
|
|
4979
5442
|
registerSelfIdentity,
|
|
@@ -5005,6 +5468,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
5005
5468
|
getSelfAliases: computeSelfAliases,
|
|
5006
5469
|
injectSubagentCompletionReminder,
|
|
5007
5470
|
injectPrVerdictActivity,
|
|
5471
|
+
noteGithubReviewOutput,
|
|
5008
5472
|
markTurnSkipped,
|
|
5009
5473
|
clearSticky,
|
|
5010
5474
|
reserveRestartHandoff,
|
|
@@ -5051,6 +5515,12 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
5051
5515
|
}
|
|
5052
5516
|
await fireTyping(live, 'tick')
|
|
5053
5517
|
},
|
|
5518
|
+
fireTypingTick: async (key: ChannelKey, epoch: number) => {
|
|
5519
|
+
const live = liveSessions.get(channelKeyId(key))
|
|
5520
|
+
if (!live) return
|
|
5521
|
+
await fireTyping(live, 'tick', epoch)
|
|
5522
|
+
},
|
|
5523
|
+
typingEpoch: (key: ChannelKey) => liveSessions.get(channelKeyId(key))?.typingEpoch,
|
|
5054
5524
|
isTypingActive: (key: ChannelKey) => {
|
|
5055
5525
|
const live = liveSessions.get(channelKeyId(key))
|
|
5056
5526
|
return live?.typingTimer !== null && live?.typingTimer !== undefined
|
|
@@ -5349,6 +5819,7 @@ export function formatAuthorAttribution(adapter: AdapterId, authorId: string, au
|
|
|
5349
5819
|
case 'telegram-bot':
|
|
5350
5820
|
case 'webex':
|
|
5351
5821
|
case 'webex-bot':
|
|
5822
|
+
case 'teams':
|
|
5352
5823
|
case 'instagram':
|
|
5353
5824
|
case 'line':
|
|
5354
5825
|
case 'kakaotalk':
|
|
@@ -5382,6 +5853,7 @@ function formatAuthorReference(adapter: AdapterId, authorId: string, authorName:
|
|
|
5382
5853
|
case 'telegram-bot':
|
|
5383
5854
|
case 'webex':
|
|
5384
5855
|
case 'webex-bot':
|
|
5856
|
+
case 'teams':
|
|
5385
5857
|
case 'instagram':
|
|
5386
5858
|
case 'line':
|
|
5387
5859
|
case 'kakaotalk':
|
|
@@ -5547,20 +6019,23 @@ export type ReplyRenderMode = 'native' | 'quote'
|
|
|
5547
6019
|
// because native support is not uniform within an adapter — Telegram's
|
|
5548
6020
|
// `sendMessage` accepts `reply_to_message_id` but `sendDocument` does not, so
|
|
5549
6021
|
// an attachment-only Telegram reply must quote; the same text-only restriction
|
|
5550
|
-
// holds for
|
|
5551
|
-
// land bare) and KakaoTalk. Slack's primitive is `thread`, not a per-message
|
|
6022
|
+
// holds for KakaoTalk. Slack's primitive is `thread`, not a per-message
|
|
5552
6023
|
// reply, so it stays quote; GitHub's PR-review reply already rides on `thread`.
|
|
5553
6024
|
//
|
|
5554
6025
|
// KakaoTalk is `native` here even though its reply payload can fail to resolve
|
|
5555
6026
|
// at send time — the adapter degrades to the blockquote fallback itself using
|
|
5556
6027
|
// `replyTo.source`, so the router still routes it down the native branch.
|
|
5557
|
-
const NATIVE_REPLY_TEXT_ADAPTERS = new Set<AdapterId>(['telegram-bot', '
|
|
6028
|
+
const NATIVE_REPLY_TEXT_ADAPTERS = new Set<AdapterId>(['telegram-bot', 'kakaotalk'])
|
|
5558
6029
|
|
|
5559
6030
|
// Webex's `parentId` rides on both `sendMessage` and `uploadFile`, so a reply is
|
|
5560
6031
|
// native for every shape — including attachment-only, which the text-gated set
|
|
5561
|
-
// above cannot express.
|
|
5562
|
-
// `
|
|
5563
|
-
|
|
6032
|
+
// above cannot express. Both Discord adapters join this set because each carries
|
|
6033
|
+
// `message_reference` on BOTH the text send (`sendMessage`) and the attachment
|
|
6034
|
+
// send (`payload_json` on the first file upload), so an attachment-only Discord
|
|
6035
|
+
// reply is a native reply-arrow, not a bare blockquote. Special-cased before the
|
|
6036
|
+
// text gate so the router sets `replyTo` (not a blockquote) even when the reply
|
|
6037
|
+
// carries no text.
|
|
6038
|
+
const NATIVE_REPLY_EVERY_SHAPE_ADAPTERS = new Set<AdapterId>(['webex', 'webex-bot', 'discord-bot', 'discord'])
|
|
5564
6039
|
|
|
5565
6040
|
export function resolveReplyRenderMode(msg: OutboundMessage): ReplyRenderMode {
|
|
5566
6041
|
if (NATIVE_REPLY_EVERY_SHAPE_ADAPTERS.has(msg.adapter)) return 'native'
|
|
@@ -5953,15 +6428,27 @@ function attemptMadeToolCall(session: AgentSession): boolean {
|
|
|
5953
6428
|
return false
|
|
5954
6429
|
}
|
|
5955
6430
|
|
|
6431
|
+
// Peels a single symmetric markdown-emphasis wrapper off a token: bold/italic
|
|
6432
|
+
// asterisks (`*`, `**`, `***`), underscores (`_`, `__`), or inline-code
|
|
6433
|
+
// backticks. Only strips when the SAME run brackets both ends, so `**NO_REPLY**`
|
|
6434
|
+
// → `NO_REPLY` while an asymmetric `*NO_REPLY` or a non-wrapping `NO_REPLY_MODE`
|
|
6435
|
+
// is returned unchanged. Not recursive — one layer is enough for the observed
|
|
6436
|
+
// `**...**` / `` `...` `` "loud" drift; anything more nested is not a real form.
|
|
6437
|
+
function stripEmphasisWrapper(token: string): string {
|
|
6438
|
+
const match = /^([*_`]{1,3})([^*_`].*?[^*_`]|[^*_`])\1$/.exec(token)
|
|
6439
|
+
return match ? match[2]! : token
|
|
6440
|
+
}
|
|
6441
|
+
|
|
5956
6442
|
// Lenient on purpose: distilled / smaller models routinely drift off the
|
|
5957
6443
|
// documented `NO_REPLY` form. We additionally accept `(NO_REPLY)` (Claude-style
|
|
5958
|
-
// hedging)
|
|
5959
|
-
//
|
|
5960
|
-
//
|
|
6444
|
+
// hedging), markdown-emphasized "loud" forms (`**NO_REPLY**`, `` `NO_REPLY` ``,
|
|
6445
|
+
// `*NO_REPLY*`), and empty visible text (e.g. Kimi-distilled models that emit
|
|
6446
|
+
// only a thinking block and end the turn) — without the empty case we'd recover
|
|
6447
|
+
// an empty string into the chat. The prompt contract still teaches the strict
|
|
5961
6448
|
// literal; this just widens what we accept. Shared with channel_send /
|
|
5962
6449
|
// channel_reply so all three call sites stay in lockstep.
|
|
5963
6450
|
export function isNoReplySignal(text: string): boolean {
|
|
5964
|
-
const trimmed = text.trim()
|
|
6451
|
+
const trimmed = stripEmphasisWrapper(text.trim())
|
|
5965
6452
|
if (trimmed === '') return true
|
|
5966
6453
|
if (trimmed === 'NO_REPLY') return true
|
|
5967
6454
|
if (trimmed === '(NO_REPLY)') return true
|
|
@@ -5990,21 +6477,31 @@ export function isNoReplySignal(text: string): boolean {
|
|
|
5990
6477
|
// "... end with NO_REPLY." (+ sentence punctuation)
|
|
5991
6478
|
// "... end with NO_REPLY.NO_REPLY" (model-doubled terminator, glued)
|
|
5992
6479
|
// "... and stop. (NO_REPLY)" (parenthesized at end)
|
|
6480
|
+
// "... nothing to add. **NO_REPLY**"(markdown-emphasized "loud" form)
|
|
6481
|
+
// "... nothing here. `NO_REPLY`" (inline-code "loud" form)
|
|
5993
6482
|
// Does not match (returns false):
|
|
5994
6483
|
// "NO_REPLY means do nothing" (token at start, prose after)
|
|
5995
6484
|
// "the env var is NO_REPLY_MODE" (substring, not whole token)
|
|
6485
|
+
// "the flag is FOO_NO_REPLY" (identifier — `_` is not a token boundary)
|
|
6486
|
+
// "the **NO_REPLY** token is how..."(emphasized but mid-sentence, prose after)
|
|
5996
6487
|
// "no reply needed" (case-sensitive on purpose)
|
|
5997
6488
|
export function endsWithNoReplySignal(text: string): boolean {
|
|
5998
6489
|
if (isNoReplySignal(text)) return true
|
|
5999
6490
|
const trimmed = text.trim()
|
|
6000
6491
|
if (trimmed === '') return false
|
|
6001
|
-
//
|
|
6002
|
-
//
|
|
6003
|
-
//
|
|
6004
|
-
//
|
|
6005
|
-
//
|
|
6492
|
+
// Isolate the final token, then defer to isNoReplySignal (which strips a
|
|
6493
|
+
// symmetric emphasis wrapper). Boundaries are whitespace / sentence
|
|
6494
|
+
// punctuation / opening bracket only — `.NO_REPLY` splits off the preceding
|
|
6495
|
+
// sentence (covering the model-doubled `...NO_REPLY.NO_REPLY` shape), while
|
|
6496
|
+
// `_` is deliberately NOT a boundary so an identifier like `FOO_NO_REPLY`
|
|
6497
|
+
// stays one token and reads as prose, not a signal.
|
|
6006
6498
|
const tail = trimmed.replace(/[.!?)\]\s]+$/, '')
|
|
6007
|
-
|
|
6499
|
+
const lastToken = tail.split(/[\s.!?([]/).pop() ?? ''
|
|
6500
|
+
// An empty final token means the text ended on an opening bracket (e.g. a
|
|
6501
|
+
// leaked `skip_response()` call), not a signal — don't hand it to
|
|
6502
|
+
// isNoReplySignal, whose empty-string case reads as deliberate silence.
|
|
6503
|
+
if (lastToken === '') return false
|
|
6504
|
+
return isNoReplySignal(lastToken)
|
|
6008
6505
|
}
|
|
6009
6506
|
|
|
6010
6507
|
// Detects the upstream "empty response" debug sentinel: when the LLM ends a
|
|
@@ -6110,44 +6607,99 @@ export function isLikelyKimiChannelToolLeak(text: string): boolean {
|
|
|
6110
6607
|
// posts its own "I'm staying silent" plumbing to the channel, the exact
|
|
6111
6608
|
// opposite of the intended no-op. It is never a legitimate user-facing reply.
|
|
6112
6609
|
//
|
|
6113
|
-
//
|
|
6114
|
-
//
|
|
6115
|
-
//
|
|
6116
|
-
//
|
|
6117
|
-
//
|
|
6118
|
-
//
|
|
6119
|
-
//
|
|
6120
|
-
//
|
|
6121
|
-
//
|
|
6122
|
-
//
|
|
6123
|
-
// the
|
|
6610
|
+
// Detection is a SINGLE whole-message boundary for every tool, then a per-name
|
|
6611
|
+
// disposition. reply/send RECOVER (their leaked form holds a salvageable user
|
|
6612
|
+
// message the extractor re-posts); everything else SUPPRESSES.
|
|
6613
|
+
//
|
|
6614
|
+
// SUPPRESS is the default and is detected by SHAPE, not a curated name list — a
|
|
6615
|
+
// `toolname(...)` that is the model's ENTIRE turn output is always a protocol
|
|
6616
|
+
// malfunction (the model narrated a call instead of emitting it), and that raw
|
|
6617
|
+
// plumbing must never reach the channel. No allowlist to keep in sync as tools
|
|
6618
|
+
// are added.
|
|
6619
|
+
//
|
|
6620
|
+
// The false-positive boundary is "the WHOLE trimmed message is a single call
|
|
6621
|
+
// expression" — NOT "starts with a call". A developer-facing reply like
|
|
6622
|
+
// `read({ ... }) lets you load a file` has text after the closing paren, so it
|
|
6623
|
+
// is prose and reaches the user. Only a message that is *nothing but* the call
|
|
6624
|
+
// (`skip_response({ ... })`, `channel_react({ emoji: "eyes" })`, bare
|
|
6625
|
+
// `channel_disengage()`) is a leak. This is what lets the rule cover every tool
|
|
6626
|
+
// — including future ones and generic tools like `bash(...)` — without risking
|
|
6627
|
+
// legitimate replies, because a real reply is never *only* a bare tool call.
|
|
6124
6628
|
//
|
|
6125
|
-
//
|
|
6126
|
-
//
|
|
6127
|
-
//
|
|
6128
|
-
|
|
6629
|
+
// `isWholeMessageToolCall` (below) is the bracket-aware parser; it returns the
|
|
6630
|
+
// called tool's name so the caller can apply the one intrinsic distinction that
|
|
6631
|
+
// survives: `skip_response` suppresses SILENTLY (the model wanted silence, and
|
|
6632
|
+
// suppression already delivered it — warning would be noise), while every other
|
|
6633
|
+
// suppressed leak pushes a self-correction reminder so the model retries with a
|
|
6634
|
+
// real tool call or a real reply.
|
|
6635
|
+
const SKIP_RESPONSE_TOOL_NAME = 'skip_response'
|
|
6129
6636
|
|
|
6130
|
-
export type PlainTextChannelToolCallKind = 'reply' | 'send' | '
|
|
6637
|
+
export type PlainTextChannelToolCallKind = 'reply' | 'send' | 'suppress-silent' | 'suppress-warn'
|
|
6131
6638
|
|
|
6132
6639
|
export function getPlainTextChannelToolCallKind(text: string): PlainTextChannelToolCallKind | null {
|
|
6133
|
-
|
|
6134
|
-
|
|
6135
|
-
|
|
6136
|
-
|
|
6137
|
-
|
|
6138
|
-
|
|
6139
|
-
|
|
6140
|
-
|
|
6141
|
-
|
|
6142
|
-
|
|
6143
|
-
|
|
6144
|
-
|
|
6640
|
+
// Everything routes through the SAME whole-message boundary, including
|
|
6641
|
+
// reply/send recovery — a prefix match there would false-positive prose like
|
|
6642
|
+
// `channel_reply({"text":"hi"}) is the serialized form`, recovering `hi` and
|
|
6643
|
+
// dropping the explanation. `isWholeMessageToolCall` returns the tool name
|
|
6644
|
+
// only when the entire trimmed message is the call (or a truncated one), so a
|
|
6645
|
+
// reply/send leak still recovers while a mention-with-trailing-prose falls
|
|
6646
|
+
// through to the user.
|
|
6647
|
+
const toolName = isWholeMessageToolCall(text)
|
|
6648
|
+
if (toolName === null) return null
|
|
6649
|
+
if (toolName === 'channel_reply') return 'reply'
|
|
6650
|
+
if (toolName === 'channel_send') return 'send'
|
|
6651
|
+
// `skip_response` already got what it wanted once suppressed (silence), so
|
|
6652
|
+
// warning would be noise. Every other leaked call dropped a real action or
|
|
6653
|
+
// reply, so nudge the model to redo it properly.
|
|
6654
|
+
return toolName === SKIP_RESPONSE_TOOL_NAME ? 'suppress-silent' : 'suppress-warn'
|
|
6145
6655
|
}
|
|
6146
6656
|
|
|
6147
6657
|
export function isLikelyPlainTextChannelToolCall(text: string): boolean {
|
|
6148
6658
|
return getPlainTextChannelToolCallKind(text) !== null
|
|
6149
6659
|
}
|
|
6150
6660
|
|
|
6661
|
+
// Bracket-aware parser: returns the called tool's name when the ENTIRE trimmed
|
|
6662
|
+
// text is a single call expression `identifier(...)` — empty args `()` or a
|
|
6663
|
+
// single object-literal `({ ... })` — with nothing but optional whitespace and
|
|
6664
|
+
// a trailing `;` after the closing paren. Returns null for anything else, which
|
|
6665
|
+
// is what keeps prose safe: `read({...}) loads a file` has trailing text, and
|
|
6666
|
+
// `bash` alone (no parens) is a bare word, so neither is a call. A naive
|
|
6667
|
+
// `^ident\(.*\)$` regex can't tell the closing paren of the arg object from a
|
|
6668
|
+
// paren inside a quoted string, so this walks the string honoring quotes and
|
|
6669
|
+
// brace/bracket/paren depth.
|
|
6670
|
+
export function isWholeMessageToolCall(text: string): string | null {
|
|
6671
|
+
const trimmed = text.trim()
|
|
6672
|
+
const nameMatch = /^([A-Za-z_][A-Za-z0-9_]*)\s*\(/.exec(trimmed)
|
|
6673
|
+
if (nameMatch === null) return null
|
|
6674
|
+
const name = nameMatch[1]!
|
|
6675
|
+
|
|
6676
|
+
let i = nameMatch[0].length - 1
|
|
6677
|
+
let depth = 0
|
|
6678
|
+
for (; i < trimmed.length; i++) {
|
|
6679
|
+
const ch = trimmed[i]!
|
|
6680
|
+
if (ch === '"' || ch === "'" || ch === '`') {
|
|
6681
|
+
i = skipStringLiteral(trimmed, i, ch)
|
|
6682
|
+
continue
|
|
6683
|
+
}
|
|
6684
|
+
if (ch === '(' || ch === '{' || ch === '[') {
|
|
6685
|
+
depth++
|
|
6686
|
+
continue
|
|
6687
|
+
}
|
|
6688
|
+
if (ch === ')' || ch === '}' || ch === ']') {
|
|
6689
|
+
depth--
|
|
6690
|
+
if (depth === 0) break
|
|
6691
|
+
continue
|
|
6692
|
+
}
|
|
6693
|
+
}
|
|
6694
|
+
|
|
6695
|
+
// Unbalanced (truncated mid-serialization) — still a leaked call, not prose.
|
|
6696
|
+
if (depth !== 0) return name
|
|
6697
|
+
|
|
6698
|
+
const rest = trimmed.slice(i + 1).trim()
|
|
6699
|
+
if (rest === '' || rest === ';') return name
|
|
6700
|
+
return null
|
|
6701
|
+
}
|
|
6702
|
+
|
|
6151
6703
|
// Tolerant single-purpose scanner that pulls the `text` argument out of a
|
|
6152
6704
|
// plain-text-serialized `channel_reply(...)` / `channel_send(...)` leak. A
|
|
6153
6705
|
// single regex covering every shape (double/single/unquoted keys, escaped
|