typeclaw 0.48.6 → 0.48.8
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 +15 -1
- package/package.json +1 -1
- package/secrets.schema.json +15 -1
- package/src/agent/guard-types.ts +25 -0
- package/src/agent/guards.ts +102 -0
- package/src/agent/index.ts +33 -3
- package/src/agent/live-subagents.ts +14 -0
- package/src/agent/multimodal/read-redirect.ts +8 -9
- package/src/agent/plugin-tools.ts +283 -148
- package/src/agent/provider-error.ts +6 -1
- package/src/agent/reload-tool.ts +12 -5
- package/src/agent/retry-same-ref.ts +95 -36
- package/src/agent/session-origin.ts +13 -1
- package/src/agent/system-prompt.ts +14 -3
- package/src/agent/todo/continuation-policy.ts +3 -4
- package/src/agent/tool-file-safety.ts +36 -13
- package/src/agent/tools/channel-reply.ts +39 -2
- package/src/agent/tools/channel-send.ts +45 -2
- package/src/agent/tools/post-github-review.ts +31 -13
- package/src/agent/tools/spawn-subagent.ts +15 -0
- package/src/agent/tools/webfetch/inline-style-visibility.ts +2 -2
- package/src/agent/tools/webfetch/strategies/readability.ts +109 -10
- package/src/agent/turn-runner.ts +23 -19
- package/src/bundled-plugins/backup/git-auth.ts +7 -4
- package/src/bundled-plugins/backup/subagents.ts +1 -1
- package/src/bundled-plugins/bun-hygiene/README.md +23 -20
- package/src/bundled-plugins/bun-hygiene/index.ts +1 -7
- package/src/bundled-plugins/bun-hygiene/policy.ts +111 -35
- package/src/bundled-plugins/github-cli-auth/gh-review-detect.ts +44 -2
- package/src/bundled-plugins/github-cli-auth/gh-store.ts +733 -0
- package/src/bundled-plugins/github-cli-auth/git-askpass.ts +25 -0
- package/src/bundled-plugins/github-cli-auth/git-command.ts +231 -30
- package/src/bundled-plugins/github-cli-auth/git-credential-env.ts +151 -0
- package/src/bundled-plugins/github-cli-auth/index.ts +249 -42
- package/src/bundled-plugins/github-cli-auth/review-recorder.ts +5 -0
- package/src/bundled-plugins/guard/index.ts +2 -25
- package/src/bundled-plugins/guard/keys.ts +8 -0
- package/src/bundled-plugins/guard/policies/non-workspace-write.ts +7 -8
- package/src/bundled-plugins/guard/policy.ts +1 -7
- package/src/bundled-plugins/security/policies/git-exfil.ts +22 -30
- package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +2 -4
- package/src/bundled-plugins/security/policies/private-surface-read.ts +8 -6
- package/src/bundled-plugins/security/policies/secret-exfil-bash.ts +2 -5
- package/src/bundled-plugins/security/policies/secret-exfil-read.ts +2 -4
- package/src/bundled-plugins/security/policies/session-search-secrets.ts +2 -4
- package/src/bundled-plugins/security/policies/system-prompt-leak.ts +2 -4
- package/src/bundled-plugins/security/policy.ts +0 -8
- package/src/channels/adapters/discord-bot-slash-commands.ts +22 -0
- package/src/channels/adapters/discord-bot.ts +2 -1
- package/src/channels/adapters/discord-classify.ts +16 -4
- package/src/channels/adapters/discord.ts +20 -8
- package/src/channels/adapters/github/dedup.ts +37 -8
- package/src/channels/adapters/github/inbound.ts +241 -46
- package/src/channels/adapters/github/review-state.ts +13 -9
- package/src/channels/adapters/github/review-thread-resolver.ts +52 -20
- package/src/channels/adapters/slack-classify.ts +40 -5
- package/src/channels/adapters/slack.ts +3 -9
- package/src/channels/adapters/webex-bot-classify.ts +4 -33
- package/src/channels/adapters/webex-bot.ts +2 -4
- package/src/channels/adapters/webex-classify.ts +4 -33
- package/src/channels/adapters/webex-format.ts +36 -0
- package/src/channels/adapters/webex.ts +2 -4
- package/src/channels/continuation-willingness.ts +64 -39
- package/src/channels/github-rereview-guard.ts +20 -0
- package/src/channels/github-review-turn-ledger.ts +11 -1
- package/src/channels/github-review-verdict-coordinator.ts +475 -41
- package/src/channels/github-verdict-activity.ts +14 -5
- package/src/channels/persistence.ts +89 -5
- package/src/channels/router.ts +1223 -225
- package/src/channels/types.ts +21 -5
- package/src/cli/compose-stats.ts +6 -7
- package/src/cli/compose-status.ts +6 -7
- package/src/cli/compose-usage.ts +6 -7
- package/src/cli/stats.ts +6 -7
- package/src/cli/status.ts +7 -8
- package/src/cli/ui.ts +4 -4
- package/src/container/start.ts +41 -1
- package/src/cron/consumer.ts +30 -9
- package/src/cron/scheduler.ts +24 -9
- package/src/doctor/channel-checks.ts +64 -0
- package/src/doctor/report.ts +8 -8
- package/src/dreams/render.ts +2 -2
- package/src/init/dockerfile.ts +8 -1
- package/src/inspect/render.ts +2 -2
- package/src/path-safety/real-intended-path.ts +14 -1
- package/src/permissions/permissions.ts +10 -2
- package/src/permissions/resolve.ts +8 -2
- package/src/plugin/core-tool-names.ts +15 -0
- package/src/plugin/hooks.ts +37 -3
- package/src/plugin/registry.ts +7 -3
- package/src/run/index.ts +35 -15
- package/src/sandbox/build.ts +19 -3
- package/src/sandbox/policy.ts +1 -0
- package/src/secrets/export-github-cli-store.ts +158 -0
- package/src/secrets/index.ts +19 -1
- package/src/secrets/provision-github-cli-store.ts +322 -0
- package/src/secrets/schema.ts +13 -7
- package/src/secrets/storage.ts +30 -0
- package/src/shared/index.ts +2 -0
- package/src/shared/style-text.ts +13 -0
- package/src/skills/typeclaw-channel-github/SKILL.md +24 -12
- package/src/skills/typeclaw-config/SKILL.md +3 -1
- package/src/skills/typeclaw-github-contributing/SKILL.md +6 -2
- package/src/skills/typeclaw-permissions/SKILL.md +11 -22
- package/src/usage/report.ts +3 -3
package/src/channels/router.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { statSync } from 'node:fs'
|
|
2
2
|
import { basename } from 'node:path'
|
|
3
3
|
|
|
4
|
-
import type
|
|
4
|
+
import { createAssistantMessageEventStream, type AssistantMessage, type ToolResultMessage } from '@mariozechner/pi-ai'
|
|
5
5
|
import { type SessionEntry, SessionManager } from '@mariozechner/pi-coding-agent'
|
|
6
6
|
|
|
7
7
|
import { createSession, renderTurnRoleAnchor, renderTurnTimeAnchor, type AgentSession } from '@/agent'
|
|
@@ -53,7 +53,22 @@ import {
|
|
|
53
53
|
} from './engagement'
|
|
54
54
|
import { checkFalseReceipt } from './github-false-receipt'
|
|
55
55
|
import { evaluateRereviewGuard } from './github-rereview-guard'
|
|
56
|
-
import { resetReviewTurn, type ReviewOutputState } from './github-review-turn-ledger'
|
|
56
|
+
import { resetReviewTurn, type ReviewOutputState, type ReviewRoundOutcome } from './github-review-turn-ledger'
|
|
57
|
+
import {
|
|
58
|
+
canPromoteGithubReviewRoundTo,
|
|
59
|
+
completeGithubReviewRound,
|
|
60
|
+
forgetGithubReviewRound,
|
|
61
|
+
githubReviewRoundKey,
|
|
62
|
+
githubReviewRoundPersistence,
|
|
63
|
+
hasGithubReviewRoundDismissalAttempt,
|
|
64
|
+
isGithubReviewRoundComplete,
|
|
65
|
+
promoteGithubReviewRound,
|
|
66
|
+
registerGithubReviewRound,
|
|
67
|
+
restoreGithubReviewRound,
|
|
68
|
+
resetGithubReviewRoundCompletion,
|
|
69
|
+
resetGithubReviewRoundCompletionForPr,
|
|
70
|
+
validateGithubReviewRound,
|
|
71
|
+
} from './github-review-verdict-coordinator'
|
|
57
72
|
import { renderPrVerdictStandDownReminder } from './github-verdict-activity'
|
|
58
73
|
import {
|
|
59
74
|
MEMBERSHIP_COLD_FETCH_TIMEOUT_MS,
|
|
@@ -98,6 +113,7 @@ import type {
|
|
|
98
113
|
GetMessageResult,
|
|
99
114
|
HistoryCallback,
|
|
100
115
|
InboundAttachment,
|
|
116
|
+
GithubReviewFollowupRound,
|
|
101
117
|
InboundMessage,
|
|
102
118
|
InboundReferenceContext,
|
|
103
119
|
ListCallback,
|
|
@@ -214,7 +230,7 @@ export function disengageReactionEmojiFor(adapter: AdapterId): string {
|
|
|
214
230
|
return DISENGAGE_REACTION_EMOJI_OVERRIDES[adapter] ?? DISENGAGE_REACTION_EMOJI
|
|
215
231
|
}
|
|
216
232
|
|
|
217
|
-
type SilentAckReason = '
|
|
233
|
+
type SilentAckReason = 'github_review_output' | 'awaiting_background_child'
|
|
218
234
|
|
|
219
235
|
// Wake nudge pushed into a resumed channel session at boot so drain() has a
|
|
220
236
|
// non-empty batch and fires a turn. The substantive instruction the model acts
|
|
@@ -626,6 +642,12 @@ function defaultMeasureTranscriptBytes(path: string): number {
|
|
|
626
642
|
// instead of awaiting the same dead promise forever.
|
|
627
643
|
export const ENSURE_LIVE_TIMEOUT_MS = 30_000
|
|
628
644
|
|
|
645
|
+
const RELOAD_HANDOFF_RETENTION_MS = 15 * 60_000
|
|
646
|
+
const MAX_PENDING_RELOAD_HANDOFF_KEYS = 100
|
|
647
|
+
const MAX_PENDING_RELOAD_HANDOFF_ITEMS_PER_KEY = 1_000
|
|
648
|
+
const MAX_PENDING_RELOAD_HANDOFF_BYTES_PER_KEY = 8 * 1024 * 1024
|
|
649
|
+
const MAX_PENDING_RELOAD_HANDOFF_BYTES_TOTAL = 64 * 1024 * 1024
|
|
650
|
+
|
|
629
651
|
// Thrown by ensureLive() when a teardown (roles reload or shutdown) raced
|
|
630
652
|
// ahead of an in-flight creation. route() has no special handling — it
|
|
631
653
|
// propagates to the adapter's outer catch, dropping this one inbound. The
|
|
@@ -747,6 +769,7 @@ type QueuedInbound = {
|
|
|
747
769
|
// happened to dequeue it. Zero means "unknown" (the formatter omits the
|
|
748
770
|
// prefix for those).
|
|
749
771
|
ts: number
|
|
772
|
+
githubReviewRound?: GithubReviewFollowupRound
|
|
750
773
|
}
|
|
751
774
|
|
|
752
775
|
type ObservedInbound = {
|
|
@@ -777,6 +800,52 @@ type TimedAttachment = { ts: number; attachment: InboundAttachment }
|
|
|
777
800
|
|
|
778
801
|
type ChannelAgentSession = AgentSession & { getAbortReason?: () => string | undefined }
|
|
779
802
|
|
|
803
|
+
// Provenance of a queued system reminder, which decides whether the
|
|
804
|
+
// reminder-only drain iteration it drives CONTINUES the current logical turn or
|
|
805
|
+
// OPENS a new one.
|
|
806
|
+
//
|
|
807
|
+
// `retry` — the router's own turn-recovery ladder asking the SAME logical turn
|
|
808
|
+
// to try again (empty-turn, tool-leak, stranded-tooluse, cold-start,
|
|
809
|
+
// empty-stop, willingness). Per-logical-turn attribution and the recovery
|
|
810
|
+
// budgets must survive these, or the ladder would refill its own budget and
|
|
811
|
+
// loop forever.
|
|
812
|
+
//
|
|
813
|
+
// `wakeup` — work injected from OUTSIDE the session's own turn machinery: a
|
|
814
|
+
// finished background subagent, a restart resume, a PR-verdict stand-down.
|
|
815
|
+
// These are a new episode that merely happens to arrive without a user
|
|
816
|
+
// message, so carrying the previous turn's attribution into them is wrong.
|
|
817
|
+
//
|
|
818
|
+
// The todo/idle continuation is deliberately `retry`, not `wakeup`: it is the
|
|
819
|
+
// same work episode continuing, and its turn must keep citing the durable work
|
|
820
|
+
// already completed.
|
|
821
|
+
//
|
|
822
|
+
// Provenance is per ENTRY rather than a single session-level flag because both
|
|
823
|
+
// kinds can coalesce into one iteration; a wakeup in the batch opens a new
|
|
824
|
+
// logical turn regardless of what else it rode in with. Matching on reminder
|
|
825
|
+
// TEXT was rejected: a wakeup body that happened to equal a nudge constant
|
|
826
|
+
// would silently misclassify, and every future enqueue site would inherit the
|
|
827
|
+
// default instead of being forced to choose.
|
|
828
|
+
type PendingSystemReminder = { text: string; kind: 'retry' | 'wakeup'; githubReviewRoundKey?: string }
|
|
829
|
+
|
|
830
|
+
type PendingReloadHandoff = {
|
|
831
|
+
key: ChannelKey
|
|
832
|
+
inbounds: QueuedInbound[]
|
|
833
|
+
observed: ObservedInbound[]
|
|
834
|
+
reminders: PendingSystemReminder[]
|
|
835
|
+
retainedAt: number
|
|
836
|
+
estimatedBytes: number
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
const retryReminder = (text: string): PendingSystemReminder => ({ text, kind: 'retry' })
|
|
840
|
+
|
|
841
|
+
const wakeupReminder = (text: string): PendingSystemReminder => ({ text, kind: 'wakeup' })
|
|
842
|
+
|
|
843
|
+
const githubReviewRoundWakeupReminder = (text: string, round: GithubReviewFollowupRound): PendingSystemReminder => ({
|
|
844
|
+
text,
|
|
845
|
+
kind: 'wakeup',
|
|
846
|
+
githubReviewRoundKey: githubReviewRoundKey(round),
|
|
847
|
+
})
|
|
848
|
+
|
|
780
849
|
type LiveSession = {
|
|
781
850
|
key: ChannelKey
|
|
782
851
|
keyId: string
|
|
@@ -808,6 +877,10 @@ type LiveSession = {
|
|
|
808
877
|
participants: ChannelParticipant[]
|
|
809
878
|
resolvedNames: ResolvedChannelNames
|
|
810
879
|
originRef: { current: SessionOrigin | undefined }
|
|
880
|
+
githubReviewRound: GithubReviewFollowupRound | null
|
|
881
|
+
// Round key of a close-out that arrived while the round was still pending
|
|
882
|
+
// completion. Replayed once the round completes; see replayPendingRoundCloseouts.
|
|
883
|
+
pendingGithubReviewRoundCloseout: string | null
|
|
811
884
|
promptQueue: QueuedInbound[]
|
|
812
885
|
contextBuffer: ObservedInbound[]
|
|
813
886
|
// Attachments of the messages composing the in-flight turn. drain()
|
|
@@ -830,6 +903,12 @@ type LiveSession = {
|
|
|
830
903
|
historyTimedAttachments: readonly TimedAttachment[]
|
|
831
904
|
historyAttachments: InboundAttachment[]
|
|
832
905
|
draining: boolean
|
|
906
|
+
// Every drain invocation still running, including the tail it executes after
|
|
907
|
+
// `draining` flips back to false. `drain()` deliberately no-ops while a drain
|
|
908
|
+
// owns the session, so a fire-and-forget `void drain(live)` is otherwise
|
|
909
|
+
// unobservable; this is the only handle a caller can await to know the turn
|
|
910
|
+
// actually landed. Entries remove themselves on settle.
|
|
911
|
+
activeDrains: Set<Promise<void>>
|
|
833
912
|
debounceTimer: ReturnType<typeof setTimeout> | null
|
|
834
913
|
typingTimer: ReturnType<typeof setInterval> | null
|
|
835
914
|
typingStartedAt: number
|
|
@@ -866,14 +945,13 @@ type LiveSession = {
|
|
|
866
945
|
// `currentTurnReactionRef` points at — last item of the drained batch) was
|
|
867
946
|
// EXPLICITLY addressed to the bot: a DM, an @-mention/alias (`isBotMention`
|
|
868
947
|
// folds plain-name matching in at the adapter classify layer), or a reply to
|
|
869
|
-
// the bot's own message. Gates the PERSISTENT
|
|
870
|
-
// `armSilentTurnAck`):
|
|
871
|
-
//
|
|
872
|
-
//
|
|
873
|
-
//
|
|
874
|
-
//
|
|
875
|
-
//
|
|
876
|
-
// in the drain finally; preserved across reminder-only iterations exactly like it.
|
|
948
|
+
// the bot's own message. Gates the PERSISTENT :eyes: for deferred background
|
|
949
|
+
// work (see `armSilentTurnAck`): an addressed request may retain a progress
|
|
950
|
+
// marker while a child runs, but ambient human-to-human chatter must leave no
|
|
951
|
+
// mark. Explicit NO_REPLY and skip_response turns never use this flag to add a
|
|
952
|
+
// reaction. Computed from the SAME message the reaction targets so eligibility
|
|
953
|
+
// and target cannot disagree. Reset with `currentTurnReactionRef` in the drain
|
|
954
|
+
// finally; preserved across reminder-only iterations exactly like it.
|
|
877
955
|
currentTurnExplicitlyAddressed: boolean
|
|
878
956
|
// Typing-status anchor of the inbound that triggered THIS turn (last item in
|
|
879
957
|
// the drained batch, mirroring `currentTurnReactionRef`). Adapter-opaque ts
|
|
@@ -899,16 +977,12 @@ type LiveSession = {
|
|
|
899
977
|
// discarded on silence (skip_response / empty / errored turns) so the bot never
|
|
900
978
|
// leaves a reaction on a message it merely looked at (e.g. cron lookaround).
|
|
901
979
|
pendingTurnReactions: ReactionRequest[]
|
|
902
|
-
// Armed
|
|
903
|
-
//
|
|
904
|
-
//
|
|
905
|
-
//
|
|
906
|
-
//
|
|
907
|
-
//
|
|
908
|
-
// plumbing leak, a retry, a synthetic turn). Firing after the engage-drop is
|
|
909
|
-
// load-bearing: adapters that collapse a same-actor same-emoji reaction into
|
|
910
|
-
// one toggle would otherwise have the engage-drop remove the only visible
|
|
911
|
-
// :eyes:. See `reactOnSilentAck`.
|
|
980
|
+
// Armed when output landed outside the channel (a GitHub review) or was
|
|
981
|
+
// deliberately deferred to a background child. Explicit NO_REPLY and
|
|
982
|
+
// skip_response turns do not arm it: opting out must leave no reaction behind.
|
|
983
|
+
// Stamped with `turnSeq` so a stale flag from a crashed turn cannot leak into
|
|
984
|
+
// the next one. Fired after the transient engage :eyes: is dropped because
|
|
985
|
+
// adapters may collapse a same-actor same-emoji reaction into one toggle.
|
|
912
986
|
silentAckTurn: { turnSeq: number; reason: SilentAckReason } | null
|
|
913
987
|
// One silent-ack-:eyes:-add promise per PERSISTENT ack `reactOnSilentAck` has
|
|
914
988
|
// planted on a trigger message, each resolving to its removable ref (or null).
|
|
@@ -917,16 +991,15 @@ type LiveSession = {
|
|
|
917
991
|
// sees every in-flight add and awaits it before removing — storing only the
|
|
918
992
|
// resolved ref raced (cleanup could snapshot an empty array, then a slow add
|
|
919
993
|
// append its ref afterward, stranding the :eyes:). Cross-turn state on purpose:
|
|
920
|
-
//
|
|
921
|
-
// conversation gets a genuine reply
|
|
922
|
-
//
|
|
994
|
+
// the mark means output is external or deferred, and once the same sticky
|
|
995
|
+
// conversation gets a genuine reply it reads as stale — so it is retired on
|
|
996
|
+
// the next replied turn (see dropSilentAckReactions).
|
|
923
997
|
// Conversation-scoped, NOT per-trigger-message: coalescing means the silent
|
|
924
998
|
// turn's trigger (message N) and the eventual reply's trigger (message N+1)
|
|
925
999
|
// routinely differ, so exact-message scoping would strand the mark. NOT reset
|
|
926
1000
|
// in drain's outer per-turn finally. On teardown the entries are dropped
|
|
927
|
-
// WITHOUT removing the reactions
|
|
928
|
-
//
|
|
929
|
-
// engage :eyes: which teardown must strip.
|
|
1001
|
+
// WITHOUT removing the reactions, unlike the transient engage :eyes: which
|
|
1002
|
+
// teardown must strip.
|
|
930
1003
|
activeSilentAckReactions: Array<Promise<ReactionRef | null>>
|
|
931
1004
|
// One add promise per willingness status posted by the agent, resolving to
|
|
932
1005
|
// the removable reaction-instance ref. Cross-turn state on purpose: the
|
|
@@ -958,7 +1031,7 @@ type LiveSession = {
|
|
|
958
1031
|
// every `drain()` iteration alongside the regular promptQueue batch;
|
|
959
1032
|
// the drain loop's run condition checks BOTH queues so a system
|
|
960
1033
|
// reminder alone is enough to trigger a turn.
|
|
961
|
-
pendingSystemReminders:
|
|
1034
|
+
pendingSystemReminders: PendingSystemReminder[]
|
|
962
1035
|
// True only for the reminder-only iteration that consumed a willingness
|
|
963
1036
|
// nudge. `willingnessNudges` persists across the logical turn, so it remains
|
|
964
1037
|
// nonzero after a substantive result and would misclassify NO_REPLY from a
|
|
@@ -1004,6 +1077,13 @@ type LiveSession = {
|
|
|
1004
1077
|
// counter is purely monotonic; the matching comparison is what protects
|
|
1005
1078
|
// against stale state.
|
|
1006
1079
|
turnSeq: number
|
|
1080
|
+
// Clock time the current LOGICAL turn opened — stamped only on a real user
|
|
1081
|
+
// batch, so the reminder-only iterations a retry queues stay inside the same
|
|
1082
|
+
// logical turn. Unlike `turnSeq` (which increments per drain iteration) this
|
|
1083
|
+
// gives background-child checks a boundary they can compare a child's
|
|
1084
|
+
// `startedAt` against, to tell "this turn spawned it" from "it was already
|
|
1085
|
+
// running when unrelated work arrived".
|
|
1086
|
+
logicalTurnStartedAt: number
|
|
1007
1087
|
// Snapshot of `successfulChannelSends` taken at turn start (same
|
|
1008
1088
|
// moment `turnSeq` increments). Lets `markTurnSkipped` detect "a
|
|
1009
1089
|
// channel send already landed in this turn" and reject the skip,
|
|
@@ -1051,13 +1131,20 @@ type LiveSession = {
|
|
|
1051
1131
|
// user batch starts (batch.length > 0), NOT on the reminder-only iteration the
|
|
1052
1132
|
// nudge itself queues — same anti-reloop discipline as the empty-turn budget.
|
|
1053
1133
|
willingnessNudges: number
|
|
1054
|
-
// Stashed by `installChannelReplyTerminalHook`
|
|
1055
|
-
//
|
|
1134
|
+
// Stashed by `installChannelReplyTerminalHook` after a successful
|
|
1135
|
+
// `channel_reply` that omitted `more_work_this_turn: true`. Read once
|
|
1056
1136
|
// by `validateChannelTurn` to decide the continuation nudge. `turnSeq`-stamped
|
|
1057
1137
|
// (like `skippedTurn`/`skipLockedSendTurn`) so a stale record from an earlier
|
|
1058
1138
|
// turn can never trigger a nudge on a later one. `null` when no such reply
|
|
1059
1139
|
// ended this turn.
|
|
1060
|
-
|
|
1140
|
+
lastTerminalReplyCompletion: { turnSeq: number; text?: string; tokens: number } | null
|
|
1141
|
+
// Armed after a successful terminal reply. pi-agent-core invokes streamFn
|
|
1142
|
+
// again only after emitting every matching toolResult into its event queue;
|
|
1143
|
+
// the wrapper consumes this marker at that awaited provider boundary and
|
|
1144
|
+
// returns a local aborted response instead of calling the provider. Event
|
|
1145
|
+
// queue ordering then persists every toolResult before the synthetic aborted
|
|
1146
|
+
// assistant. Cleared on consumption, stop, or a fresh user turn.
|
|
1147
|
+
pendingTerminalReplyStop: { turnSeq: number; tokens: number } | null
|
|
1061
1148
|
// Stamped by `installChannelReplyTerminalHook` when a successful `channel_reply`
|
|
1062
1149
|
// set `more_work_this_turn: true` — the machine-readable "I'll keep working this turn"
|
|
1063
1150
|
// promise. `validateChannelTurn` reads it to recover a turn that made that promise,
|
|
@@ -1280,6 +1367,7 @@ export type ExecuteCommandResult =
|
|
|
1280
1367
|
// happened to be live, bypassing role gating entirely.
|
|
1281
1368
|
export type ExecuteCommandOptions = {
|
|
1282
1369
|
invokerId: string
|
|
1370
|
+
parentChat?: string
|
|
1283
1371
|
}
|
|
1284
1372
|
|
|
1285
1373
|
export type SendSource = 'tool' | 'system'
|
|
@@ -1475,9 +1563,21 @@ export type ChannelRouter = {
|
|
|
1475
1563
|
injectPrVerdictActivity: (args: {
|
|
1476
1564
|
workspace: string
|
|
1477
1565
|
prNumber: number
|
|
1478
|
-
verdict:
|
|
1566
|
+
verdict: ReviewRoundOutcome
|
|
1479
1567
|
sessionId: string
|
|
1480
1568
|
}) => { kind: 'delivered'; count: number }
|
|
1569
|
+
completeGithubReviewRound?: (args: {
|
|
1570
|
+
workspace: string
|
|
1571
|
+
prNumber: number
|
|
1572
|
+
verdict: ReviewRoundOutcome
|
|
1573
|
+
sessionId: string
|
|
1574
|
+
}) => Promise<{ kind: 'completed' | 'no-round' }>
|
|
1575
|
+
finishGithubReviewRoundCloseout?: (args: {
|
|
1576
|
+
sessionId: string
|
|
1577
|
+
workspace: string
|
|
1578
|
+
prNumber: number
|
|
1579
|
+
thread: string | null
|
|
1580
|
+
}) => void
|
|
1481
1581
|
noteGithubReviewOutput: (args: {
|
|
1482
1582
|
sessionId: string
|
|
1483
1583
|
workspace: string
|
|
@@ -1549,6 +1649,9 @@ export type ChannelRouter = {
|
|
|
1549
1649
|
isTypingActive: (key: ChannelKey) => boolean
|
|
1550
1650
|
stopTyping: (key: ChannelKey) => Promise<void>
|
|
1551
1651
|
typingHeartbeatIntervalFor: (adapter: ChannelKey['adapter']) => number
|
|
1652
|
+
githubReviewRoundFor: (key: ChannelKey) => GithubReviewFollowupRound | null | undefined
|
|
1653
|
+
pendingReminderCount: (key: ChannelKey) => number | undefined
|
|
1654
|
+
creationTokenCount: () => number
|
|
1552
1655
|
runIdleGc: () => Promise<void>
|
|
1553
1656
|
// Returns the seeded author state on the live session matching
|
|
1554
1657
|
// `key`, or undefined when no live session exists. Tests use this
|
|
@@ -1631,6 +1734,14 @@ export type CreateChannelRouterOptions = {
|
|
|
1631
1734
|
// Test seam: override the ensureLive watchdog ceiling so the timeout path
|
|
1632
1735
|
// is exercisable in <100ms instead of the 30s production default.
|
|
1633
1736
|
ensureLiveTimeoutMs?: number
|
|
1737
|
+
// Test seam for expiring a failed reload handoff without waiting for the
|
|
1738
|
+
// production retention window.
|
|
1739
|
+
handoffRetryRetentionMs?: number
|
|
1740
|
+
// Test seam for exercising the per-key retry-buffer capacity without
|
|
1741
|
+
// manufacturing a production-sized batch.
|
|
1742
|
+
handoffRetryItemLimit?: number
|
|
1743
|
+
// Test seam for the retained payload-size guard.
|
|
1744
|
+
handoffRetryByteLimit?: number
|
|
1634
1745
|
// Test seam: per-callback ceiling for channel name resolvers; mirrors the
|
|
1635
1746
|
// ensureLive seam so timeout paths can be exercised quickly in tests.
|
|
1636
1747
|
resolveChannelNamesTimeoutMs?: number
|
|
@@ -1748,6 +1859,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
1748
1859
|
const now = options.now ?? Date.now
|
|
1749
1860
|
const measureTranscriptBytes = options.measureTranscriptBytes ?? defaultMeasureTranscriptBytes
|
|
1750
1861
|
const ensureLiveTimeoutMs = options.ensureLiveTimeoutMs ?? ENSURE_LIVE_TIMEOUT_MS
|
|
1862
|
+
const handoffRetryRetentionMs = options.handoffRetryRetentionMs ?? RELOAD_HANDOFF_RETENTION_MS
|
|
1863
|
+
const handoffRetryItemLimit = options.handoffRetryItemLimit ?? MAX_PENDING_RELOAD_HANDOFF_ITEMS_PER_KEY
|
|
1864
|
+
const handoffRetryByteLimit = options.handoffRetryByteLimit ?? MAX_PENDING_RELOAD_HANDOFF_BYTES_PER_KEY
|
|
1751
1865
|
const resolveChannelNamesTimeoutMs = options.resolveChannelNamesTimeoutMs ?? RESOLVE_CHANNEL_NAMES_TIMEOUT_MS
|
|
1752
1866
|
const fetchHistoryTimeoutMs = options.fetchHistoryTimeoutMs ?? FETCH_HISTORY_TIMEOUT_MS
|
|
1753
1867
|
const sessionIdleTimeoutMs = options.sessionIdleTimeoutMs ?? SESSION_IDLE_TIMEOUT_MS
|
|
@@ -1759,6 +1873,20 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
1759
1873
|
const newestRunningChildSubagentStartedAt = options.newestRunningChildSubagentStartedAt ?? (() => null)
|
|
1760
1874
|
const liveSessions = new Map<string, LiveSession>()
|
|
1761
1875
|
const creating = new Map<string, Promise<LiveSession>>()
|
|
1876
|
+
let nextCreationToken = 0
|
|
1877
|
+
const activeCreationAttempts = new Map<string, number>()
|
|
1878
|
+
// Unlike `creating`, this marker survives the watchdog cleanup. A timed-out
|
|
1879
|
+
// attempt can keep running after a retry claims the key, so only the latest
|
|
1880
|
+
// monotonic token may persist, install, or adopt queued handoff work.
|
|
1881
|
+
const latestCreationTokens = new Map<string, number>()
|
|
1882
|
+
// A deferred reload splices post-reload work off the stale session before it
|
|
1883
|
+
// recreates the successor. If that recreation times out, returning from the
|
|
1884
|
+
// handoff used to discard the only copy and produce the production symptom
|
|
1885
|
+
// "the agent stopped responding." Keep one ordered batch per channel key so
|
|
1886
|
+
// the next successful ensureLive adopts it before any newer inbound. Entries
|
|
1887
|
+
// expire and the key count is capped; crossing either bound reports the loss
|
|
1888
|
+
// to both logs and the channel instead of silently trimming user work.
|
|
1889
|
+
const pendingReloadHandoffs = new Map<string, PendingReloadHandoff>()
|
|
1762
1890
|
// Restart-resume reservations, keyed by channelKeyId. Installed by
|
|
1763
1891
|
// reserveRestartHandoff BEFORE channel adapters start receiving, so an
|
|
1764
1892
|
// inbound that races the boot resume coalesces onto the reservation (via the
|
|
@@ -1901,6 +2029,34 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
1901
2029
|
await next
|
|
1902
2030
|
}
|
|
1903
2031
|
|
|
2032
|
+
const persistGithubReviewRound = (live: LiveSession, round: GithubReviewFollowupRound | null): void => {
|
|
2033
|
+
if (mappings === null) return
|
|
2034
|
+
const idx = mappings.findIndex(
|
|
2035
|
+
(record) =>
|
|
2036
|
+
record.adapter === live.key.adapter &&
|
|
2037
|
+
record.workspace === live.key.workspace &&
|
|
2038
|
+
record.chat === live.key.chat &&
|
|
2039
|
+
(record.thread ?? null) === (live.key.thread ?? null),
|
|
2040
|
+
)
|
|
2041
|
+
if (idx < 0) return
|
|
2042
|
+
const record = mappings[idx]!
|
|
2043
|
+
if (round === null) {
|
|
2044
|
+
const { githubReviewRound: _removed, ...rest } = record
|
|
2045
|
+
void _removed
|
|
2046
|
+
mappings[idx] = rest
|
|
2047
|
+
} else {
|
|
2048
|
+
const state = githubReviewRoundPersistence(round)
|
|
2049
|
+
if (state === null) {
|
|
2050
|
+
const { githubReviewRound: _expired, ...rest } = record
|
|
2051
|
+
void _expired
|
|
2052
|
+
mappings[idx] = rest
|
|
2053
|
+
} else {
|
|
2054
|
+
mappings[idx] = { ...record, githubReviewRound: { ...round, ...state } }
|
|
2055
|
+
}
|
|
2056
|
+
}
|
|
2057
|
+
void persist()
|
|
2058
|
+
}
|
|
2059
|
+
|
|
1904
2060
|
const createForChannel: CreateSessionForChannel =
|
|
1905
2061
|
options.createSessionForChannel ??
|
|
1906
2062
|
(async ({ key, existingSessionId, existingSessionFile, origin, originRef }) => {
|
|
@@ -2050,6 +2206,23 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2050
2206
|
return false
|
|
2051
2207
|
}
|
|
2052
2208
|
|
|
2209
|
+
// Same question as the GC/rollover pin, asked for a different decision: while a
|
|
2210
|
+
// background child is still working (and inside the stuck backstop), an empty
|
|
2211
|
+
// completion from the parent is the subagent contract being honored, not the
|
|
2212
|
+
// provider degeneration the turn-recovery ladder exists to repair.
|
|
2213
|
+
//
|
|
2214
|
+
// Turn-scoped, unlike the GC pin, which is deliberately session-scoped. Only
|
|
2215
|
+
// the logical turn that spawned the child is waiting on it; a later inbound is
|
|
2216
|
+
// unrelated work whose own recovery, todo continuation and staged fallback must
|
|
2217
|
+
// still run. Session scope would let one long-running child silence every
|
|
2218
|
+
// subsequent turn, and a wedged child would strand them with nothing to revisit
|
|
2219
|
+
// them after the backstop expires.
|
|
2220
|
+
const isAwaitingBackgroundChild = (live: LiveSession, label: string): boolean => {
|
|
2221
|
+
const childStartedAt = newestRunningChildSubagentStartedAt(live.sessionId)
|
|
2222
|
+
if (childStartedAt === null || childStartedAt < live.logicalTurnStartedAt) return false
|
|
2223
|
+
return isPinnedByRunningChild(live.sessionId, live.keyId, label)
|
|
2224
|
+
}
|
|
2225
|
+
|
|
2053
2226
|
const shouldRolloverLive = (live: LiveSession, idleMs: number): boolean => {
|
|
2054
2227
|
// A session mid-prompt looks idle by lastInboundAt (only bumped on engaged
|
|
2055
2228
|
// inbounds) while session.prompt() is still in flight; rolling it over aborts
|
|
@@ -2076,6 +2249,155 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2076
2249
|
return true
|
|
2077
2250
|
}
|
|
2078
2251
|
|
|
2252
|
+
const pendingReloadHandoffItemCount = (pending: PendingReloadHandoff): number =>
|
|
2253
|
+
pending.inbounds.length + pending.observed.length + pending.reminders.length
|
|
2254
|
+
|
|
2255
|
+
const estimateReloadHandoffBytes = (
|
|
2256
|
+
inbounds: QueuedInbound[],
|
|
2257
|
+
observed: ObservedInbound[],
|
|
2258
|
+
reminders: PendingSystemReminder[],
|
|
2259
|
+
): number => {
|
|
2260
|
+
try {
|
|
2261
|
+
const serializableInbounds = inbounds.map(({ engageReaction: _engageReaction, ...inbound }) => inbound)
|
|
2262
|
+
return Buffer.byteLength(JSON.stringify({ inbounds: serializableInbounds, observed, reminders }), 'utf8')
|
|
2263
|
+
} catch {
|
|
2264
|
+
return Number.POSITIVE_INFINITY
|
|
2265
|
+
}
|
|
2266
|
+
}
|
|
2267
|
+
|
|
2268
|
+
const pendingReloadHandoffTotalBytes = (): number => {
|
|
2269
|
+
let total = 0
|
|
2270
|
+
for (const pending of pendingReloadHandoffs.values()) total += pending.estimatedBytes
|
|
2271
|
+
return total
|
|
2272
|
+
}
|
|
2273
|
+
|
|
2274
|
+
const reportDiscardedReloadHandoff = async (pending: PendingReloadHandoff, reason: string): Promise<void> => {
|
|
2275
|
+
const count = pendingReloadHandoffItemCount(pending)
|
|
2276
|
+
const recovery =
|
|
2277
|
+
"Re-send the affected messages. If provider credentials changed, run reload({ scope: 'providers' }); " +
|
|
2278
|
+
'otherwise check the channel logs and retry after session creation is healthy.'
|
|
2279
|
+
logger.error(
|
|
2280
|
+
`[channels] ${channelKeyId(pending.key)}: reload handoff retention policy discarded ${count} queued item(s): ${reason}. ${recovery}`,
|
|
2281
|
+
)
|
|
2282
|
+
await dropPendingReloadHandoffEngageReactions(pending)
|
|
2283
|
+
const result = await send(
|
|
2284
|
+
{
|
|
2285
|
+
adapter: pending.key.adapter,
|
|
2286
|
+
workspace: pending.key.workspace,
|
|
2287
|
+
chat: pending.key.chat,
|
|
2288
|
+
thread: pending.key.thread,
|
|
2289
|
+
text: `⚠️ TypeClaw could not replay ${count} queued item(s) after reload: ${reason}. ${recovery}`,
|
|
2290
|
+
},
|
|
2291
|
+
{ source: 'system', outputKind: 'meta' },
|
|
2292
|
+
).catch((err) => {
|
|
2293
|
+
logger.error(`[channels] ${channelKeyId(pending.key)}: reload handoff loss notice threw: ${describeError(err)}`)
|
|
2294
|
+
return null
|
|
2295
|
+
})
|
|
2296
|
+
if (result !== null && !result.ok) {
|
|
2297
|
+
logger.error(`[channels] ${channelKeyId(pending.key)}: reload handoff loss notice failed: ${result.error}`)
|
|
2298
|
+
}
|
|
2299
|
+
}
|
|
2300
|
+
|
|
2301
|
+
const expirePendingReloadHandoffs = async (): Promise<void> => {
|
|
2302
|
+
const expired: Array<{ pending: PendingReloadHandoff; ageMs: number }> = []
|
|
2303
|
+
for (const [keyId, pending] of pendingReloadHandoffs) {
|
|
2304
|
+
const ageMs = now() - pending.retainedAt
|
|
2305
|
+
if (ageMs < handoffRetryRetentionMs) continue
|
|
2306
|
+
pendingReloadHandoffs.delete(keyId)
|
|
2307
|
+
expired.push({ pending, ageMs })
|
|
2308
|
+
}
|
|
2309
|
+
await Promise.all(
|
|
2310
|
+
expired.map(({ pending, ageMs }) =>
|
|
2311
|
+
reportDiscardedReloadHandoff(pending, `retention limit exceeded after ${ageMs}ms`),
|
|
2312
|
+
),
|
|
2313
|
+
)
|
|
2314
|
+
}
|
|
2315
|
+
|
|
2316
|
+
const retainReloadHandoff = (
|
|
2317
|
+
key: ChannelKey,
|
|
2318
|
+
inbounds: QueuedInbound[],
|
|
2319
|
+
observed: ObservedInbound[],
|
|
2320
|
+
reminders: PendingSystemReminder[],
|
|
2321
|
+
): boolean => {
|
|
2322
|
+
void expirePendingReloadHandoffs()
|
|
2323
|
+
const keyId = channelKeyId(key)
|
|
2324
|
+
const existing = pendingReloadHandoffs.get(keyId)
|
|
2325
|
+
if (existing !== undefined) {
|
|
2326
|
+
const incoming: PendingReloadHandoff = {
|
|
2327
|
+
key,
|
|
2328
|
+
inbounds,
|
|
2329
|
+
observed,
|
|
2330
|
+
reminders,
|
|
2331
|
+
retainedAt: now(),
|
|
2332
|
+
estimatedBytes: estimateReloadHandoffBytes(inbounds, observed, reminders),
|
|
2333
|
+
}
|
|
2334
|
+
if (pendingReloadHandoffItemCount(existing) + pendingReloadHandoffItemCount(incoming) > handoffRetryItemLimit) {
|
|
2335
|
+
void reportDiscardedReloadHandoff(incoming, `per-key item limit ${handoffRetryItemLimit} would be exceeded`)
|
|
2336
|
+
return false
|
|
2337
|
+
}
|
|
2338
|
+
if (existing.estimatedBytes + incoming.estimatedBytes > handoffRetryByteLimit) {
|
|
2339
|
+
void reportDiscardedReloadHandoff(incoming, `per-key byte limit ${handoffRetryByteLimit} would be exceeded`)
|
|
2340
|
+
return false
|
|
2341
|
+
}
|
|
2342
|
+
if (pendingReloadHandoffTotalBytes() + incoming.estimatedBytes > MAX_PENDING_RELOAD_HANDOFF_BYTES_TOTAL) {
|
|
2343
|
+
void reportDiscardedReloadHandoff(
|
|
2344
|
+
incoming,
|
|
2345
|
+
`global byte limit ${MAX_PENDING_RELOAD_HANDOFF_BYTES_TOTAL} would be exceeded`,
|
|
2346
|
+
)
|
|
2347
|
+
return false
|
|
2348
|
+
}
|
|
2349
|
+
existing.inbounds.push(...inbounds)
|
|
2350
|
+
existing.observed.push(...observed)
|
|
2351
|
+
existing.reminders.push(...reminders)
|
|
2352
|
+
existing.estimatedBytes += incoming.estimatedBytes
|
|
2353
|
+
return true
|
|
2354
|
+
}
|
|
2355
|
+
const pending: PendingReloadHandoff = {
|
|
2356
|
+
key,
|
|
2357
|
+
inbounds,
|
|
2358
|
+
observed,
|
|
2359
|
+
reminders,
|
|
2360
|
+
retainedAt: now(),
|
|
2361
|
+
estimatedBytes: estimateReloadHandoffBytes(inbounds, observed, reminders),
|
|
2362
|
+
}
|
|
2363
|
+
if (pendingReloadHandoffItemCount(pending) > handoffRetryItemLimit) {
|
|
2364
|
+
void reportDiscardedReloadHandoff(pending, `per-key item limit ${handoffRetryItemLimit} exceeded`)
|
|
2365
|
+
return false
|
|
2366
|
+
}
|
|
2367
|
+
if (pending.estimatedBytes > handoffRetryByteLimit) {
|
|
2368
|
+
void reportDiscardedReloadHandoff(pending, `per-key byte limit ${handoffRetryByteLimit} exceeded`)
|
|
2369
|
+
return false
|
|
2370
|
+
}
|
|
2371
|
+
if (pendingReloadHandoffTotalBytes() + pending.estimatedBytes > MAX_PENDING_RELOAD_HANDOFF_BYTES_TOTAL) {
|
|
2372
|
+
void reportDiscardedReloadHandoff(pending, `global byte limit ${MAX_PENDING_RELOAD_HANDOFF_BYTES_TOTAL} exceeded`)
|
|
2373
|
+
return false
|
|
2374
|
+
}
|
|
2375
|
+
if (pendingReloadHandoffs.size >= MAX_PENDING_RELOAD_HANDOFF_KEYS) {
|
|
2376
|
+
void reportDiscardedReloadHandoff(pending, `key limit ${MAX_PENDING_RELOAD_HANDOFF_KEYS} reached`)
|
|
2377
|
+
return false
|
|
2378
|
+
}
|
|
2379
|
+
pendingReloadHandoffs.set(keyId, pending)
|
|
2380
|
+
return true
|
|
2381
|
+
}
|
|
2382
|
+
|
|
2383
|
+
const adoptPendingReloadHandoff = (live: LiveSession): void => {
|
|
2384
|
+
const pending = pendingReloadHandoffs.get(live.keyId)
|
|
2385
|
+
if (pending === undefined) return
|
|
2386
|
+
const ageMs = now() - pending.retainedAt
|
|
2387
|
+
if (ageMs >= handoffRetryRetentionMs) {
|
|
2388
|
+
pendingReloadHandoffs.delete(live.keyId)
|
|
2389
|
+
void reportDiscardedReloadHandoff(pending, `retention limit exceeded after ${ageMs}ms`)
|
|
2390
|
+
return
|
|
2391
|
+
}
|
|
2392
|
+
// Delete before enqueueing: once ownership moves to the live queues, a
|
|
2393
|
+
// second ensureLive must not replay the same batch and double-deliver it.
|
|
2394
|
+
pendingReloadHandoffs.delete(live.keyId)
|
|
2395
|
+
live.promptQueue.push(...pending.inbounds)
|
|
2396
|
+
live.contextBuffer.push(...pending.observed)
|
|
2397
|
+
live.pendingSystemReminders.push(...pending.reminders)
|
|
2398
|
+
if ((pending.inbounds.length > 0 || pending.reminders.length > 0) && !live.draining) void drain(live)
|
|
2399
|
+
}
|
|
2400
|
+
|
|
2079
2401
|
const ensureLive = async (
|
|
2080
2402
|
key: ChannelKey,
|
|
2081
2403
|
triggeringMessageId?: string,
|
|
@@ -2097,7 +2419,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2097
2419
|
if (existing && !existing.destroyed) {
|
|
2098
2420
|
// A resume that finds the key already live is a no-op for reopening: the
|
|
2099
2421
|
// session is up, so just hand it back and let the caller enqueue the wake.
|
|
2100
|
-
if (resumeTarget !== undefined)
|
|
2422
|
+
if (resumeTarget !== undefined) {
|
|
2423
|
+
adoptPendingReloadHandoff(existing)
|
|
2424
|
+
return existing
|
|
2425
|
+
}
|
|
2101
2426
|
// Rollover decision (soft TTL → cost-aware grace → hard cap) lives in
|
|
2102
2427
|
// shouldRolloverLive, which also skips draining sessions so a mid-prompt
|
|
2103
2428
|
// turn is never aborted by a follow-up's idle check (PR #359 incident).
|
|
@@ -2127,6 +2452,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2127
2452
|
}
|
|
2128
2453
|
}
|
|
2129
2454
|
} else {
|
|
2455
|
+
adoptPendingReloadHandoff(existing)
|
|
2130
2456
|
return existing
|
|
2131
2457
|
}
|
|
2132
2458
|
}
|
|
@@ -2135,8 +2461,13 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2135
2461
|
if (inFlight) return inFlight
|
|
2136
2462
|
|
|
2137
2463
|
const generation = liveGeneration
|
|
2464
|
+
const creationToken = ++nextCreationToken
|
|
2465
|
+
latestCreationTokens.set(keyId, creationToken)
|
|
2466
|
+
activeCreationAttempts.set(keyId, (activeCreationAttempts.get(keyId) ?? 0) + 1)
|
|
2467
|
+
const isLatestCreation = (): boolean => latestCreationTokens.get(keyId) === creationToken
|
|
2138
2468
|
|
|
2139
|
-
|
|
2469
|
+
let promise!: Promise<LiveSession>
|
|
2470
|
+
promise = (async () => {
|
|
2140
2471
|
await ensureLoaded()
|
|
2141
2472
|
const record = mappings ? findRecord(mappings, key) : undefined
|
|
2142
2473
|
let resolvedRecord = record
|
|
@@ -2161,6 +2492,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2161
2492
|
thread: record.thread,
|
|
2162
2493
|
participants: record.participants,
|
|
2163
2494
|
lastInboundAt: 0,
|
|
2495
|
+
...(record.githubReviewRound !== undefined ? { githubReviewRound: record.githubReviewRound } : {}),
|
|
2164
2496
|
}
|
|
2165
2497
|
if (mappings) {
|
|
2166
2498
|
const idx = mappings.findIndex(
|
|
@@ -2191,6 +2523,28 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2191
2523
|
lastInboundAt: now(),
|
|
2192
2524
|
}
|
|
2193
2525
|
}
|
|
2526
|
+
let restoredRound: GithubReviewFollowupRound | null = null
|
|
2527
|
+
let restoredRoundStatus: 'pending' | 'completed' | null = null
|
|
2528
|
+
if (resolvedRecord?.githubReviewRound !== undefined) {
|
|
2529
|
+
if (
|
|
2530
|
+
await validateGithubReviewRound(resolvedRecord.githubReviewRound, resolvedRecord.githubReviewRound.createdAt)
|
|
2531
|
+
) {
|
|
2532
|
+
restoredRoundStatus = resolvedRecord.githubReviewRound.status
|
|
2533
|
+
restoredRound = restoreGithubReviewRound(
|
|
2534
|
+
resolvedRecord.githubReviewRound,
|
|
2535
|
+
restoredRoundStatus,
|
|
2536
|
+
resolvedRecord.githubReviewRound.attemptedCarriers,
|
|
2537
|
+
resolvedRecord.githubReviewRound.dismissalAttempted === true,
|
|
2538
|
+
resolvedRecord.githubReviewRound.requestChangesAttempted === true,
|
|
2539
|
+
resolvedRecord.githubReviewRound.createdAt,
|
|
2540
|
+
)
|
|
2541
|
+
} else {
|
|
2542
|
+
logger.info(
|
|
2543
|
+
`[channels] ${keyId}: dropped stale or expired persisted github review round pr=${resolvedRecord.githubReviewRound.workspace}#${resolvedRecord.githubReviewRound.prNumber}`,
|
|
2544
|
+
)
|
|
2545
|
+
}
|
|
2546
|
+
}
|
|
2547
|
+
|
|
2194
2548
|
const phase = resolvedRecord?.sessionId === undefined ? 'cold-start' : 'rehydrate'
|
|
2195
2549
|
logger.info(`[channels] ${keyId}: ensureLive begin (${phase})`)
|
|
2196
2550
|
const participants = (resolvedRecord?.participants ?? []) as ChannelParticipant[]
|
|
@@ -2217,6 +2571,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2217
2571
|
chat: key.chat,
|
|
2218
2572
|
...(resolvedNames.chatName !== undefined ? { chatName: resolvedNames.chatName } : {}),
|
|
2219
2573
|
thread: key.thread,
|
|
2574
|
+
...(restoredRound !== null ? { githubReviewRound: restoredRound } : {}),
|
|
2220
2575
|
...(room?.parentChat !== undefined ? { parentChat: room.parentChat } : {}),
|
|
2221
2576
|
...(room?.parentChatName !== undefined ? { parentChatName: room.parentChatName } : {}),
|
|
2222
2577
|
...(triggeringAuthorId !== undefined ? { lastInboundAuthorId: triggeringAuthorId } : {}),
|
|
@@ -2241,6 +2596,15 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2241
2596
|
})
|
|
2242
2597
|
logger.info(`[channels] ${keyId}: ensureLive session-created sessionId=${created.sessionId}`)
|
|
2243
2598
|
|
|
2599
|
+
// A watchdog timeout only releases callers; it cannot cancel the factory.
|
|
2600
|
+
// Check the durable per-key token before this late attempt can overwrite
|
|
2601
|
+
// the retry's mapping. The `creating` entry is intentionally insufficient:
|
|
2602
|
+
// both attempts may have removed their transient entries by now.
|
|
2603
|
+
if (!isLatestCreation()) {
|
|
2604
|
+
await created.dispose()
|
|
2605
|
+
throw new Error(`[channels] ${keyId}: superseded live session creation discarded`)
|
|
2606
|
+
}
|
|
2607
|
+
|
|
2244
2608
|
const transcriptPath = created.getTranscriptPath?.()
|
|
2245
2609
|
const persistedRecord: ChannelSessionRecord = {
|
|
2246
2610
|
adapter: key.adapter,
|
|
@@ -2251,6 +2615,12 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2251
2615
|
...(transcriptPath ? { sessionFile: basename(transcriptPath) } : {}),
|
|
2252
2616
|
lastInboundAt: now(),
|
|
2253
2617
|
participants,
|
|
2618
|
+
...(restoredRound !== null && restoredRoundStatus !== null
|
|
2619
|
+
? (() => {
|
|
2620
|
+
const state = githubReviewRoundPersistence(restoredRound)
|
|
2621
|
+
return state === null ? {} : { githubReviewRound: { ...restoredRound, ...state } }
|
|
2622
|
+
})()
|
|
2623
|
+
: {}),
|
|
2254
2624
|
}
|
|
2255
2625
|
if (mappings) {
|
|
2256
2626
|
const idx = mappings.findIndex(
|
|
@@ -2289,6 +2659,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2289
2659
|
participants,
|
|
2290
2660
|
resolvedNames,
|
|
2291
2661
|
originRef,
|
|
2662
|
+
githubReviewRound: restoredRound,
|
|
2663
|
+
pendingGithubReviewRoundCloseout: null,
|
|
2292
2664
|
promptQueue: [],
|
|
2293
2665
|
pendingSystemReminders: [],
|
|
2294
2666
|
willingnessReminderIteration: false,
|
|
@@ -2297,6 +2669,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2297
2669
|
historyTimedAttachments: [],
|
|
2298
2670
|
historyAttachments: [],
|
|
2299
2671
|
draining: false,
|
|
2672
|
+
activeDrains: new Set(),
|
|
2300
2673
|
debounceTimer: null,
|
|
2301
2674
|
typingTimer: null,
|
|
2302
2675
|
typingStartedAt: 0,
|
|
@@ -2337,6 +2710,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2337
2710
|
sendTimestamps: new Map(),
|
|
2338
2711
|
successfulChannelSends: 0,
|
|
2339
2712
|
turnSeq: 0,
|
|
2713
|
+
logicalTurnStartedAt: now(),
|
|
2340
2714
|
successfulSendsAtTurnStart: 0,
|
|
2341
2715
|
inFlightToolSends: new Map(),
|
|
2342
2716
|
policyDeniedToolSendsThisTurn: new Map(),
|
|
@@ -2344,7 +2718,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2344
2718
|
toolLeakRetries: 0,
|
|
2345
2719
|
emptyStopAfterToolWorkArmed: false,
|
|
2346
2720
|
willingnessNudges: 0,
|
|
2347
|
-
|
|
2721
|
+
lastTerminalReplyCompletion: null,
|
|
2722
|
+
pendingTerminalReplyStop: null,
|
|
2348
2723
|
continueReplyTurn: null,
|
|
2349
2724
|
abortReasonThisTurn: null,
|
|
2350
2725
|
userStoppedTurnSeq: null,
|
|
@@ -2398,7 +2773,29 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2398
2773
|
stampedAbort.reason === 'terminal_after_channel_reply'
|
|
2399
2774
|
? 'terminal-after-channel-reply'
|
|
2400
2775
|
: undefined
|
|
2401
|
-
|
|
2776
|
+
// Keep the same-turn stamp through validateChannelTurn. Clearing it on
|
|
2777
|
+
// the aborted assistant event made the later stranded-toolUse retry log
|
|
2778
|
+
// `abort_reason=unknown`, even though this subscriber had just consumed
|
|
2779
|
+
// the exact internal reason. A fresh user batch clears the stamp, and
|
|
2780
|
+
// every reader also requires a matching turnSeq, so retaining it cannot
|
|
2781
|
+
// attribute a later turn to this abort.
|
|
2782
|
+
// AgentSession processes message events through one serial queue. By
|
|
2783
|
+
// the time this synthetic aborted message_end reaches the subscriber,
|
|
2784
|
+
// every preceding toolResult event has completed extension handling
|
|
2785
|
+
// and SessionManager persistence. Preserve the original assistant
|
|
2786
|
+
// usage rather than recording this local stream's zero-token envelope.
|
|
2787
|
+
const terminalCompletion = live.lastTerminalReplyCompletion
|
|
2788
|
+
if (termination !== undefined && terminalCompletion?.turnSeq === live.turnSeq) {
|
|
2789
|
+
enqueueTodoOutcomeWrite(live, {
|
|
2790
|
+
agentDir: options.agentDir,
|
|
2791
|
+
origin: buildLiveOrigin(live),
|
|
2792
|
+
turnId: live.sessionId,
|
|
2793
|
+
stopReason: usage.stopReason,
|
|
2794
|
+
termination,
|
|
2795
|
+
tokens: terminalCompletion.tokens,
|
|
2796
|
+
})
|
|
2797
|
+
return
|
|
2798
|
+
}
|
|
2402
2799
|
const outcomeArgs = {
|
|
2403
2800
|
agentDir: options.agentDir,
|
|
2404
2801
|
origin: buildLiveOrigin(live),
|
|
@@ -2429,6 +2826,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2429
2826
|
if (isColdStart) {
|
|
2430
2827
|
// Install before the slow prefetch so a concurrent teardown/shutdown can
|
|
2431
2828
|
// see and dispose this session during the network fetch.
|
|
2829
|
+
if (!isLatestCreation()) {
|
|
2830
|
+
await tearDownLive(live)
|
|
2831
|
+
throw new Error(`[channels] ${keyId}: superseded live session creation discarded`)
|
|
2832
|
+
}
|
|
2432
2833
|
liveSessions.set(keyId, live)
|
|
2433
2834
|
const adapterConfig = options.configForAdapter(key.adapter)
|
|
2434
2835
|
// Overlap the disk mapping-write with the network history prefetch —
|
|
@@ -2452,6 +2853,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2452
2853
|
// before installing — a failed persist must fail ensureLive without
|
|
2453
2854
|
// leaving a warm session behind for later inbounds to reuse.
|
|
2454
2855
|
await persistPromise
|
|
2856
|
+
if (!isLatestCreation()) {
|
|
2857
|
+
await tearDownLive(live)
|
|
2858
|
+
throw new Error(`[channels] ${keyId}: superseded live session creation discarded`)
|
|
2859
|
+
}
|
|
2455
2860
|
liveSessions.set(keyId, live)
|
|
2456
2861
|
}
|
|
2457
2862
|
|
|
@@ -2464,29 +2869,31 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2464
2869
|
live.baseContextBytes = measureTranscriptBytes(transcriptPathForBase)
|
|
2465
2870
|
}
|
|
2466
2871
|
|
|
2872
|
+
if (!isLatestCreation()) {
|
|
2873
|
+
await unwindInstalledLive(keyId, live)
|
|
2874
|
+
throw new Error(`[channels] ${keyId}: superseded live session creation discarded`)
|
|
2875
|
+
}
|
|
2876
|
+
adoptPendingReloadHandoff(live)
|
|
2467
2877
|
logger.info(`[channels] ${keyId}: ensureLive done (${phase})`)
|
|
2468
2878
|
return live
|
|
2469
|
-
})()
|
|
2879
|
+
})().finally(() => {
|
|
2880
|
+
const remaining = (activeCreationAttempts.get(keyId) ?? 1) - 1
|
|
2881
|
+
if (remaining > 0) activeCreationAttempts.set(keyId, remaining)
|
|
2882
|
+
else {
|
|
2883
|
+
activeCreationAttempts.delete(keyId)
|
|
2884
|
+
latestCreationTokens.delete(keyId)
|
|
2885
|
+
}
|
|
2886
|
+
})
|
|
2470
2887
|
|
|
2471
2888
|
creating.set(keyId, promise)
|
|
2472
2889
|
try {
|
|
2473
2890
|
return await raceWithTimeout(promise, ensureLiveTimeoutMs, `[channels] ${keyId} ensureLive`)
|
|
2474
2891
|
} catch (err) {
|
|
2475
|
-
//
|
|
2476
|
-
//
|
|
2477
|
-
// which the next inbound's existence-check short-circuit at the top of
|
|
2478
|
-
// ensureLive will treat as a usable warm session — strictly better than
|
|
2479
|
-
// a permanent silent drop. The caller (route() in this file, ultimately
|
|
2480
|
-
// the adapter's outer catch) sees the timeout error and logs it.
|
|
2892
|
+
// A timed-out creation may still settle, but the durable creation token
|
|
2893
|
+
// discards it if a later creation has claimed ownership of this key.
|
|
2481
2894
|
logger.error(`[channels] ${keyId}: ensureLive failed: ${describeError(err)}`)
|
|
2482
2895
|
throw err
|
|
2483
2896
|
} finally {
|
|
2484
|
-
// Owner-checked delete: only clear the in-flight marker if it still points
|
|
2485
|
-
// at THIS promise. A watchdog timeout can orphan a slow creation whose
|
|
2486
|
-
// `finally` runs while a later inbound has already installed its own
|
|
2487
|
-
// `creating` entry for the same key; an unconditional delete would drop
|
|
2488
|
-
// that newer entry and let a third inbound cold-start a duplicate session
|
|
2489
|
-
// (observed: 3 concurrent sessions approving the same PR).
|
|
2490
2897
|
if (creating.get(keyId) === promise) creating.delete(keyId)
|
|
2491
2898
|
}
|
|
2492
2899
|
}
|
|
@@ -2512,6 +2919,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2512
2919
|
const result = await fetchHistory(live.key.adapter, {
|
|
2513
2920
|
chat: live.key.chat,
|
|
2514
2921
|
thread: live.key.thread,
|
|
2922
|
+
...(live.githubReviewRound !== null ? { githubReviewRound: live.githubReviewRound } : {}),
|
|
2515
2923
|
limit: requested,
|
|
2516
2924
|
prefetch: true,
|
|
2517
2925
|
})
|
|
@@ -2719,23 +3127,23 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2719
3127
|
}
|
|
2720
3128
|
|
|
2721
3129
|
// After a successful `channel_reply`, the model has delivered its user-facing
|
|
2722
|
-
// response and the turn is semantically done. pi-agent-core
|
|
2723
|
-
//
|
|
2724
|
-
//
|
|
2725
|
-
//
|
|
2726
|
-
//
|
|
2727
|
-
//
|
|
2728
|
-
//
|
|
2729
|
-
//
|
|
2730
|
-
//
|
|
2731
|
-
//
|
|
2732
|
-
//
|
|
3130
|
+
// response and the turn is semantically done. pi-agent-core otherwise makes
|
|
3131
|
+
// one more LLM call after the tool result (the "post-tool follow-up") so real
|
|
3132
|
+
// multi-step chains can continue. On a terminal reply there is nothing left
|
|
3133
|
+
// to say, and Fireworks' kimi-k2p6-turbo can degenerate that empty follow-up
|
|
3134
|
+
// into a 32000-token repetition loop (see CHANNEL_MAX_OUTPUT_TOKENS).
|
|
3135
|
+
// Suppress the provider only at its next stream boundary. agent-core reaches
|
|
3136
|
+
// that boundary after emitting every toolResult for the batch, and
|
|
3137
|
+
// AgentSession preserves the event order even when extensions delay
|
|
3138
|
+
// persistence. In the 2026-08-28 Discord incident, aborting from afterToolCall
|
|
3139
|
+
// left validation looking at the preceding result as
|
|
3140
|
+
// `stranded_toolUse_after_send` and opened a recovery turn after an
|
|
3141
|
+
// already-complete reply.
|
|
2733
3142
|
//
|
|
2734
3143
|
// Scope is deliberately narrow: only `channel_reply` (the current-chat user-
|
|
2735
3144
|
// facing response), only on success, and only for channel sessions. Read-only
|
|
2736
3145
|
// tools and `channel_send` must keep the follow-up so genuine multi-step turns
|
|
2737
|
-
// continue. A prior non-typeclaw `afterToolCall` (none today)
|
|
2738
|
-
// composed, not clobbered.
|
|
3146
|
+
// continue. A prior non-typeclaw `afterToolCall` (none today) is composed.
|
|
2739
3147
|
//
|
|
2740
3148
|
// `channel_reply({ more_work_this_turn: true })` is the explicit opt-out: a
|
|
2741
3149
|
// mid-turn status reply ("working on it…") that the model follows with more
|
|
@@ -2771,12 +3179,20 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2771
3179
|
live.continueReplyTurn = { turnSeq: live.turnSeq, sendCount: live.successfulChannelSends }
|
|
2772
3180
|
}
|
|
2773
3181
|
}
|
|
2774
|
-
if (succeeded && !keepTurnAlive &&
|
|
2775
|
-
logger.info(
|
|
3182
|
+
if (succeeded && !keepTurnAlive && live.userStoppedTurnSeq !== live.turnSeq) {
|
|
3183
|
+
logger.info(
|
|
3184
|
+
`[channels] ${live.keyId} terminal_after_channel_reply site=terminal_after_channel_reply session=${live.sessionId} reason=terminal_after_channel_reply`,
|
|
3185
|
+
)
|
|
2776
3186
|
const replyText = (context.toolCall.arguments as { text?: unknown } | undefined)?.text
|
|
2777
|
-
live.
|
|
2778
|
-
|
|
2779
|
-
|
|
3187
|
+
live.lastTerminalReplyCompletion = {
|
|
3188
|
+
turnSeq: live.turnSeq,
|
|
3189
|
+
...(typeof replyText === 'string' ? { text: replyText } : {}),
|
|
3190
|
+
tokens: context.assistantMessage.usage.totalTokens,
|
|
3191
|
+
}
|
|
3192
|
+
live.pendingTerminalReplyStop = {
|
|
3193
|
+
turnSeq: live.turnSeq,
|
|
3194
|
+
tokens: context.assistantMessage.usage.totalTokens,
|
|
3195
|
+
}
|
|
2780
3196
|
}
|
|
2781
3197
|
return result
|
|
2782
3198
|
}
|
|
@@ -2793,13 +3209,48 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2793
3209
|
const installChannelOutputCap = (live: LiveSession): void => {
|
|
2794
3210
|
const { agent } = live.session
|
|
2795
3211
|
const inner = agent.streamFn
|
|
2796
|
-
agent.streamFn = (model, context,
|
|
2797
|
-
|
|
3212
|
+
agent.streamFn = async (model, context, streamOptions) => {
|
|
3213
|
+
const pendingTerminalStop = live.pendingTerminalReplyStop
|
|
3214
|
+
if (pendingTerminalStop?.turnSeq === live.turnSeq && live.userStoppedTurnSeq !== pendingTerminalStop.turnSeq) {
|
|
3215
|
+
live.pendingTerminalReplyStop = null
|
|
3216
|
+
live.abortReasonThisTurn = {
|
|
3217
|
+
turnSeq: pendingTerminalStop.turnSeq,
|
|
3218
|
+
reason: 'terminal_after_channel_reply',
|
|
3219
|
+
}
|
|
3220
|
+
// This boundary runs only after agent-core has emitted all toolResults
|
|
3221
|
+
// for the batch. Return a local aborted assistant event instead of
|
|
3222
|
+
// entering the provider. Its later message_end is queued behind those
|
|
3223
|
+
// result events; that persistence-ordered subscriber records the
|
|
3224
|
+
// trusted outcome and original token usage.
|
|
3225
|
+
const message: AssistantMessage = {
|
|
3226
|
+
role: 'assistant',
|
|
3227
|
+
content: [],
|
|
3228
|
+
api: model.api,
|
|
3229
|
+
provider: model.provider,
|
|
3230
|
+
model: model.id,
|
|
3231
|
+
usage: {
|
|
3232
|
+
input: 0,
|
|
3233
|
+
output: 0,
|
|
3234
|
+
cacheRead: 0,
|
|
3235
|
+
cacheWrite: 0,
|
|
3236
|
+
totalTokens: 0,
|
|
3237
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
3238
|
+
},
|
|
3239
|
+
stopReason: 'aborted',
|
|
3240
|
+
errorMessage: 'terminal channel reply completed',
|
|
3241
|
+
timestamp: Date.now(),
|
|
3242
|
+
}
|
|
3243
|
+
const stream = createAssistantMessageEventStream()
|
|
3244
|
+
stream.push({ type: 'start', partial: message })
|
|
3245
|
+
stream.push({ type: 'error', reason: 'aborted', error: message })
|
|
3246
|
+
return stream
|
|
3247
|
+
}
|
|
3248
|
+
let maxTokens = streamOptions?.maxTokens
|
|
2798
3249
|
if (maxTokens === undefined && live.nextPromptMaxTokens !== undefined) {
|
|
2799
3250
|
maxTokens = live.nextPromptMaxTokens
|
|
2800
3251
|
live.nextPromptMaxTokens = undefined
|
|
2801
3252
|
}
|
|
2802
|
-
return inner(model, context, { ...
|
|
3253
|
+
return await inner(model, context, { ...streamOptions, maxTokens: maxTokens ?? CHANNEL_MAX_OUTPUT_TOKENS })
|
|
2803
3254
|
}
|
|
2804
3255
|
}
|
|
2805
3256
|
|
|
@@ -2905,7 +3356,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2905
3356
|
logger.info(`[channels] ${live.keyId}: dropping todo continuation reminder after user stop`)
|
|
2906
3357
|
return
|
|
2907
3358
|
}
|
|
2908
|
-
|
|
3359
|
+
// Self-continuation of the SAME work episode, not external injection:
|
|
3360
|
+
// `qualifyingWorkThisLogicalTurn` must survive it so a follow-up reply
|
|
3361
|
+
// can still cite the durable work this turn already did.
|
|
3362
|
+
live.pendingSystemReminders.push(retryReminder(text))
|
|
2909
3363
|
},
|
|
2910
3364
|
})
|
|
2911
3365
|
} catch (err) {
|
|
@@ -3038,6 +3492,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3038
3492
|
chat: live.key.chat,
|
|
3039
3493
|
...(live.resolvedNames.chatName !== undefined ? { chatName: live.resolvedNames.chatName } : {}),
|
|
3040
3494
|
thread: live.key.thread,
|
|
3495
|
+
...(live.githubReviewRound !== null ? { githubReviewRound: live.githubReviewRound } : {}),
|
|
3041
3496
|
...(live.room?.parentChat !== undefined ? { parentChat: live.room.parentChat } : {}),
|
|
3042
3497
|
...(live.room?.parentChatName !== undefined ? { parentChatName: live.room.parentChatName } : {}),
|
|
3043
3498
|
...(live.currentTurnAuthorId !== null ? { lastInboundAuthorId: live.currentTurnAuthorId } : {}),
|
|
@@ -3048,6 +3503,74 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3048
3503
|
}
|
|
3049
3504
|
}
|
|
3050
3505
|
|
|
3506
|
+
const failoverGithubReviewRound = async (live: LiveSession): Promise<void> => {
|
|
3507
|
+
const round = live.githubReviewRound
|
|
3508
|
+
if (round === null || isGithubReviewRoundComplete(round)) return
|
|
3509
|
+
if (hasGithubReviewRoundDismissalAttempt(round)) {
|
|
3510
|
+
const key = githubReviewRoundKey(round)
|
|
3511
|
+
for (const sibling of liveSessions.values()) {
|
|
3512
|
+
if (sibling.githubReviewRound !== null && githubReviewRoundKey(sibling.githubReviewRound) === key) {
|
|
3513
|
+
persistGithubReviewRound(sibling, sibling.githubReviewRound)
|
|
3514
|
+
}
|
|
3515
|
+
}
|
|
3516
|
+
return
|
|
3517
|
+
}
|
|
3518
|
+
const carrierIsLive = Array.from(liveSessions.values()).some(
|
|
3519
|
+
(candidate) =>
|
|
3520
|
+
!candidate.destroyed &&
|
|
3521
|
+
candidate.githubReviewRound !== null &&
|
|
3522
|
+
githubReviewRoundKey(candidate.githubReviewRound) === githubReviewRoundKey(round) &&
|
|
3523
|
+
candidate.key.thread === round.carrierThread,
|
|
3524
|
+
)
|
|
3525
|
+
if (round.carrierThread !== live.key.thread && carrierIsLive) return
|
|
3526
|
+
|
|
3527
|
+
const candidates = Array.from(liveSessions.values()).filter(
|
|
3528
|
+
(candidate) =>
|
|
3529
|
+
!candidate.destroyed &&
|
|
3530
|
+
candidate.githubReviewRound !== null &&
|
|
3531
|
+
githubReviewRoundKey(candidate.githubReviewRound) === githubReviewRoundKey(round) &&
|
|
3532
|
+
candidate.key.thread !== round.carrierThread,
|
|
3533
|
+
)
|
|
3534
|
+
const waiter = candidates
|
|
3535
|
+
.filter((candidate) => canPromoteGithubReviewRoundTo(round, candidate.key.thread))
|
|
3536
|
+
.sort((a, b) => a.keyId.localeCompare(b.keyId))[0]
|
|
3537
|
+
if (waiter === undefined) {
|
|
3538
|
+
const state = githubReviewRoundPersistence(round)
|
|
3539
|
+
if (candidates.length === 0) {
|
|
3540
|
+
logger.warn(
|
|
3541
|
+
`[channels] github review round failover found no live waiter pr=${round.workspace}#${round.prNumber} head=${round.headSha} carrier=${round.carrierThread ?? 'root'}; retry the review after the round expires`,
|
|
3542
|
+
)
|
|
3543
|
+
} else {
|
|
3544
|
+
logger.warn(
|
|
3545
|
+
`[channels] github review round exhausted all candidate carriers pr=${round.workspace}#${round.prNumber} head=${round.headSha} carrier=${round.carrierThread ?? 'root'} attempted=${(state?.attemptedCarriers ?? []).map((thread) => thread ?? 'root').join(',')}; retry the review after the round expires`,
|
|
3546
|
+
)
|
|
3547
|
+
}
|
|
3548
|
+
return
|
|
3549
|
+
}
|
|
3550
|
+
|
|
3551
|
+
const promoted = promoteGithubReviewRound(round, waiter.key.thread)
|
|
3552
|
+
if (promoted === null) return
|
|
3553
|
+
for (const sibling of liveSessions.values()) {
|
|
3554
|
+
if (
|
|
3555
|
+
sibling.githubReviewRound !== null &&
|
|
3556
|
+
githubReviewRoundKey(sibling.githubReviewRound) === githubReviewRoundKey(round)
|
|
3557
|
+
) {
|
|
3558
|
+
sibling.githubReviewRound = promoted
|
|
3559
|
+
persistGithubReviewRound(sibling, promoted)
|
|
3560
|
+
}
|
|
3561
|
+
}
|
|
3562
|
+
waiter.pendingSystemReminders.push(
|
|
3563
|
+
githubReviewRoundWakeupReminder(
|
|
3564
|
+
`<system-reminder>\nThe designated sibling ended without a verified formal review verdict. ` +
|
|
3565
|
+
`You are now the carrier for PR #${round.prNumber} at ${round.headSha.slice(0, 7)}. ` +
|
|
3566
|
+
`Submit exactly one formal verdict for this follow-up round before closing out your thread.\n</system-reminder>`,
|
|
3567
|
+
promoted,
|
|
3568
|
+
),
|
|
3569
|
+
)
|
|
3570
|
+
logger.info(`[channels] ${waiter.keyId}: github review round carrier promoted`)
|
|
3571
|
+
if (!waiter.draining) void drain(waiter)
|
|
3572
|
+
}
|
|
3573
|
+
|
|
3051
3574
|
const enqueueTodoOutcomeWrite = (
|
|
3052
3575
|
live: LiveSession,
|
|
3053
3576
|
args: Parameters<typeof recordTurnOutcome>[0],
|
|
@@ -3084,7 +3607,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3084
3607
|
|
|
3085
3608
|
const stopCurrentChannelTurn = async (live: LiveSession): Promise<void> => {
|
|
3086
3609
|
live.userStoppedTurnSeq = live.turnSeq
|
|
3087
|
-
live.
|
|
3610
|
+
live.lastTerminalReplyCompletion = null
|
|
3611
|
+
live.pendingTerminalReplyStop = null
|
|
3088
3612
|
live.abortReasonThisTurn = { turnSeq: live.turnSeq, reason: 'user_stop' }
|
|
3089
3613
|
if (live.debounceTimer) clearTimeout(live.debounceTimer)
|
|
3090
3614
|
live.debounceTimer = null
|
|
@@ -3102,7 +3626,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3102
3626
|
await stopTypingHeartbeat(live)
|
|
3103
3627
|
try {
|
|
3104
3628
|
await live.session.abort()
|
|
3105
|
-
logger.info(
|
|
3629
|
+
logger.info(
|
|
3630
|
+
`[channels] ${live.keyId}: command /stop aborted current turn site=user_stop session=${live.sessionId} reason=user_stop`,
|
|
3631
|
+
)
|
|
3106
3632
|
} catch (err) {
|
|
3107
3633
|
logger.warn(`[channels] ${live.keyId}: command /stop abort failed: ${describeError(err)}`)
|
|
3108
3634
|
}
|
|
@@ -3192,8 +3718,50 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3192
3718
|
}
|
|
3193
3719
|
}
|
|
3194
3720
|
|
|
3195
|
-
|
|
3196
|
-
|
|
3721
|
+
// Open a new logical turn for externally-injected work that arrived without a
|
|
3722
|
+
// user message. Deliberately a SUBSET of the fresh-batch reset above: only
|
|
3723
|
+
// state whose meaning is scoped to "the episode that just ended" is cleared.
|
|
3724
|
+
//
|
|
3725
|
+
// `promisedWorkOutstandingThisLogicalTurn` is the notable survivor. A
|
|
3726
|
+
// completion wakeup usually exists BECAUSE the agent promised a later result,
|
|
3727
|
+
// and that promise is exactly what makes a silent death user-visible harm —
|
|
3728
|
+
// clearing it here would re-open the hole this fix closes. It is cleared
|
|
3729
|
+
// authoritatively by a terminal send instead.
|
|
3730
|
+
//
|
|
3731
|
+
// Author identity is restored by the caller's existing reminder branch and
|
|
3732
|
+
// must not be reset: role resolution for the wakeup's own channel_reply
|
|
3733
|
+
// depends on it. `stagedFallbackCause` and the question signals also survive —
|
|
3734
|
+
// a wakeup can be the recovery opportunity a staged fallback was waiting for.
|
|
3735
|
+
//
|
|
3736
|
+
// `logicalTurnStartedAt` deliberately does NOT advance here. It exists solely
|
|
3737
|
+
// as the boundary `isAwaitingBackgroundChild` compares a child's `startedAt`
|
|
3738
|
+
// against, and advancing it would hide an older SIBLING child that is still
|
|
3739
|
+
// running: one child's completion wake would stop counting as "awaiting", and
|
|
3740
|
+
// the recovery ladder, todo continuation and staged fallback would all re-fire
|
|
3741
|
+
// while that sibling still works — exactly the duplicate-comment failure
|
|
3742
|
+
// f1f36462 fixed. The wake for A must stay silent while B runs; B's own
|
|
3743
|
+
// completion is what ends the wait.
|
|
3744
|
+
const beginWakeupTurn = (live: LiveSession): void => {
|
|
3745
|
+
live.pendingProviderError = null
|
|
3746
|
+
live.consecutiveSends.clear()
|
|
3747
|
+
live.lastSentText.clear()
|
|
3748
|
+
live.lastSendLeafId = null
|
|
3749
|
+
// Safe to refill precisely because retry nudges are `kind: 'retry'` and
|
|
3750
|
+
// never reach here: the ladder this wakeup turn may itself queue cannot
|
|
3751
|
+
// refill its own budget, so there is no unbounded loop.
|
|
3752
|
+
live.emptyTurnRetries = 0
|
|
3753
|
+
live.toolLeakRetries = 0
|
|
3754
|
+
live.emptyStopAfterToolWorkArmed = false
|
|
3755
|
+
live.willingnessNudges = 0
|
|
3756
|
+
live.abortReasonThisTurn = null
|
|
3757
|
+
live.userStoppedTurnSeq = null
|
|
3758
|
+
live.nextPromptMaxTokens = undefined
|
|
3759
|
+
live.githubReviewOutputTurn = null
|
|
3760
|
+
live.toolExecutionThisLogicalTurn = false
|
|
3761
|
+
live.qualifyingWorkThisLogicalTurn = false
|
|
3762
|
+
}
|
|
3763
|
+
|
|
3764
|
+
const runDrain = async (live: LiveSession): Promise<void> => {
|
|
3197
3765
|
live.draining = true
|
|
3198
3766
|
try {
|
|
3199
3767
|
// `!live.pendingTeardown`: once a reload marks this draining session for
|
|
@@ -3220,8 +3788,27 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3220
3788
|
const observed = live.contextBuffer.splice(0, live.contextBuffer.length)
|
|
3221
3789
|
const reminders = live.pendingSystemReminders.splice(0, live.pendingSystemReminders.length)
|
|
3222
3790
|
live.currentTurnAttachments = collectTurnAttachments(observed, batch)
|
|
3791
|
+
// A reminder-only iteration carrying externally-injected work opens a
|
|
3792
|
+
// NEW logical turn. Without this, the completed-subagent wakeup that
|
|
3793
|
+
// follows a turn which spawned it inherits that turn's
|
|
3794
|
+
// `toolExecutionThisLogicalTurn`, and a provider failure on the wakeup
|
|
3795
|
+
// is misread as "the turn already ran tools, so it wasn't silent" —
|
|
3796
|
+
// suppressing the notice for a prompt that ran no tool and produced
|
|
3797
|
+
// nothing. Observed in production as a review verdict lost with zero
|
|
3798
|
+
// user-visible signal. Retry nudges deliberately do NOT trip this: they
|
|
3799
|
+
// ARE the same logical turn retrying.
|
|
3800
|
+
const wakeupTurn = batch.length === 0 && reminders.some((r) => r.kind === 'wakeup')
|
|
3801
|
+
// Gated on `!wakeupTurn` because a willingness nudge can coalesce into the
|
|
3802
|
+
// same iteration as a wakeup. The wakeup wins the boundary and clears the
|
|
3803
|
+
// nudge budget, so the willingness bookkeeping now describes a superseded
|
|
3804
|
+
// turn — and a legitimate NO_REPLY from the wake (a PR stand-down, say)
|
|
3805
|
+
// would otherwise post a bogus `no_reply_after_willingness_nudge`
|
|
3806
|
+
// fallback. Same defect the branch that reads this flag already guards
|
|
3807
|
+
// against for later unrelated reminders.
|
|
3223
3808
|
live.willingnessReminderIteration =
|
|
3224
|
-
|
|
3809
|
+
!wakeupTurn &&
|
|
3810
|
+
batch.length === 0 &&
|
|
3811
|
+
reminders.some((r) => r.text === WILLINGNESS_NUDGE || r.text === SEND_WILLINGNESS_NUDGE)
|
|
3225
3812
|
|
|
3226
3813
|
if (batch.length > 0) {
|
|
3227
3814
|
// A fresh user batch starts a NEW logical turn. Drop any provider
|
|
@@ -3238,6 +3825,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3238
3825
|
live.currentTurnAuthorIds = new Set(batch.map((m) => m.authorId))
|
|
3239
3826
|
live.currentTurnReactionRef = batch[batch.length - 1]!.reactionRef ?? null
|
|
3240
3827
|
const trigger = batch[batch.length - 1]!
|
|
3828
|
+
if (trigger.githubReviewRound !== undefined) {
|
|
3829
|
+
live.githubReviewRound = registerGithubReviewRound(trigger.githubReviewRound)
|
|
3830
|
+
}
|
|
3241
3831
|
live.currentTurnExplicitlyAddressed =
|
|
3242
3832
|
trigger.isDm || trigger.isBotMention || trigger.replyToBotMessageId !== null
|
|
3243
3833
|
live.currentTurnTypingThread = batch[batch.length - 1]!.typingThread ?? null
|
|
@@ -3258,6 +3848,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3258
3848
|
live.toolLeakRetries = 0
|
|
3259
3849
|
live.emptyStopAfterToolWorkArmed = false
|
|
3260
3850
|
live.willingnessNudges = 0
|
|
3851
|
+
live.logicalTurnStartedAt = now()
|
|
3261
3852
|
// A fresh batch supersedes a still-pending staged fallback. That staged
|
|
3262
3853
|
// turn produced no usable reply, so it must not leave the PRIOR turn's
|
|
3263
3854
|
// committed lastQuestionSignal behind — otherwise the new question would
|
|
@@ -3269,6 +3860,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3269
3860
|
live.stagedFallbackCause = null
|
|
3270
3861
|
}
|
|
3271
3862
|
live.abortReasonThisTurn = null
|
|
3863
|
+
live.pendingTerminalReplyStop = null
|
|
3272
3864
|
live.userStoppedTurnSeq = null
|
|
3273
3865
|
live.nextPromptMaxTokens = undefined
|
|
3274
3866
|
// Cleared with the retry budgets (NOT beside resetReviewTurn below) so a
|
|
@@ -3297,6 +3889,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3297
3889
|
} else {
|
|
3298
3890
|
live.currentTurnEngageReactions = []
|
|
3299
3891
|
}
|
|
3892
|
+
// After the author-identity restore above, which a wakeup turn still needs.
|
|
3893
|
+
if (wakeupTurn) beginWakeupTurn(live)
|
|
3300
3894
|
|
|
3301
3895
|
// Update the live origin holder so this turn's tool.before events
|
|
3302
3896
|
// carry the current actor's id, and resolve the live role from it for
|
|
@@ -3312,10 +3906,18 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3312
3906
|
adapter: live.key.adapter,
|
|
3313
3907
|
loopGuardActive: live.loopGuardActive,
|
|
3314
3908
|
groupChatNudge: live.multiHumanGroup,
|
|
3315
|
-
systemReminders: reminders,
|
|
3909
|
+
systemReminders: reminders.map((r) => r.text),
|
|
3316
3910
|
role: liveRole,
|
|
3317
3911
|
})
|
|
3318
3912
|
|
|
3913
|
+
const repairedToolCalls = repairDanglingToolUseBranch(live.session, now())
|
|
3914
|
+
if (repairedToolCalls.length > 0) {
|
|
3915
|
+
logger.warn(
|
|
3916
|
+
`[channels] ${live.keyId} branch_repair=missing_tool_result session=${live.sessionId} ` +
|
|
3917
|
+
`count=${repairedToolCalls.length} tools=${repairedToolCalls.join(',')}`,
|
|
3918
|
+
)
|
|
3919
|
+
}
|
|
3920
|
+
|
|
3319
3921
|
// Bracketing logs around the LLM call so a hung prompt() is
|
|
3320
3922
|
// diagnosable from logs alone (we see prompting without prompted).
|
|
3321
3923
|
// text length is a proxy for "did we send something at all".
|
|
@@ -3441,15 +4043,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3441
4043
|
// (observe-after-engage). Leaving it only on the reply path stranded the
|
|
3442
4044
|
// ack permanently on messages the agent looked at but never answered.
|
|
3443
4045
|
const dropDone = dropEngageReactions(live, engageAddPromises)
|
|
3444
|
-
// A
|
|
3445
|
-
//
|
|
3446
|
-
//
|
|
3447
|
-
//
|
|
3448
|
-
// toggle would let a still-in-flight engage removal strip the ack — so
|
|
3449
|
-
// the silent path AWAITS every engage removal reaching the adapter
|
|
3450
|
-
// before adding the persistent one. Only silent turns pay that wait:
|
|
3451
|
-
// normal/reply turns keep the engage drop fire-and-forget (`void`), so
|
|
3452
|
-
// turn-end never blocks on the reaction API off the silent path.
|
|
4046
|
+
// A turn whose output landed outside the channel or was deferred to a
|
|
4047
|
+
// background child leaves a persistent :eyes:. On a typing-less adapter
|
|
4048
|
+
// it reuses the transient engage reaction's message/emoji/actor, so wait
|
|
4049
|
+
// for that removal to reach the adapter before adding the persistent one.
|
|
3453
4050
|
if (live.silentAckTurn?.turnSeq === live.turnSeq) await dropDone
|
|
3454
4051
|
else void dropDone
|
|
3455
4052
|
reactOnSilentAck(live)
|
|
@@ -3487,10 +4084,23 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3487
4084
|
logger.warn(`[channels] ${live.keyId}: skipping todo continuation after failed outcome write`)
|
|
3488
4085
|
} else if (live.userStoppedTurnSeq === live.turnSeq) {
|
|
3489
4086
|
logger.info(`[channels] ${live.keyId}: skipping todo continuation after user stop`)
|
|
4087
|
+
} else if (isAwaitingBackgroundChild(live, 'todo-continuation')) {
|
|
4088
|
+
// The outstanding todo is usually the very work the running child was
|
|
4089
|
+
// spawned to do, so continuing here re-wakes a session that is
|
|
4090
|
+
// deliberately waiting and asks the model to report progress it does
|
|
4091
|
+
// not have yet. The child's completion reminder is the correct wake.
|
|
4092
|
+
logger.info(`[channels] ${live.keyId}: skipping todo continuation while background child runs`)
|
|
3490
4093
|
} else {
|
|
3491
4094
|
await maybeContinueTodosChannel(live)
|
|
3492
4095
|
}
|
|
3493
|
-
|
|
4096
|
+
if (!isAwaitingBackgroundChild(live, 'staged-fallback')) {
|
|
4097
|
+
await resolveStagedFallback(live)
|
|
4098
|
+
}
|
|
4099
|
+
const logicalTurnStillOpen =
|
|
4100
|
+
live.pendingSystemReminders.length > 0 ||
|
|
4101
|
+
live.stagedFallbackCause !== null ||
|
|
4102
|
+
live.promisedWorkOutstandingThisLogicalTurn
|
|
4103
|
+
if (!logicalTurnStillOpen) await failoverGithubReviewRound(live)
|
|
3494
4104
|
live.lastTurnAuthorIds = new Set(live.currentTurnAuthorIds)
|
|
3495
4105
|
if (live.currentTurnAuthorId !== null) {
|
|
3496
4106
|
live.lastTurnAuthorId = live.currentTurnAuthorId
|
|
@@ -3528,9 +4138,47 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3528
4138
|
const carriedInbounds = live.promptQueue.splice(0, live.promptQueue.length)
|
|
3529
4139
|
const carriedObserved = live.contextBuffer.splice(0, live.contextBuffer.length)
|
|
3530
4140
|
const carriedReminders = live.pendingSystemReminders.splice(0, live.pendingSystemReminders.length)
|
|
4141
|
+
const hasCarriedWork = carriedInbounds.length > 0 || carriedObserved.length > 0 || carriedReminders.length > 0
|
|
4142
|
+
const retained =
|
|
4143
|
+
hasCarriedWork && retainReloadHandoff(live.key, carriedInbounds, carriedObserved, carriedReminders)
|
|
3531
4144
|
liveSessions.delete(live.keyId)
|
|
3532
4145
|
await tearDownLive(live)
|
|
3533
|
-
await handOffToSuccessor(live.key
|
|
4146
|
+
if (retained) await handOffToSuccessor(live.key)
|
|
4147
|
+
}
|
|
4148
|
+
}
|
|
4149
|
+
|
|
4150
|
+
// No-op while a drain already owns the session: that loop re-checks both
|
|
4151
|
+
// queues every iteration, so work landing behind it is picked up without a
|
|
4152
|
+
// second concurrent drain. Registers the running invocation on `activeDrains`
|
|
4153
|
+
// so `settleDrains` can await a turn started fire-and-forget.
|
|
4154
|
+
const drain = (live: LiveSession): Promise<void> => {
|
|
4155
|
+
if (live.draining || live.destroyed) return Promise.resolve()
|
|
4156
|
+
const running = runDrain(live)
|
|
4157
|
+
// Attaching this handler marks `running` handled, so a drain-tail throw can
|
|
4158
|
+
// no longer reach the runtime's unhandled-rejection reporter — every
|
|
4159
|
+
// production call site is `void drain(live)` and catches nothing. Log it
|
|
4160
|
+
// here so the failure stays visible rather than disappearing into the
|
|
4161
|
+
// tracking. The settlement copy must still RESOLVE: `settleDrains` waits on
|
|
4162
|
+
// unrelated turns too, and one failed drain must not reject a waiter that
|
|
4163
|
+
// has nothing to do with it. Callers keep `running`, so an awaiting caller
|
|
4164
|
+
// still sees the original rejection.
|
|
4165
|
+
const settled = running.then(
|
|
4166
|
+
() => undefined,
|
|
4167
|
+
(err: unknown) => {
|
|
4168
|
+
logger.error(`[channels] ${live.keyId}: drain failed: ${describeError(err)}`)
|
|
4169
|
+
},
|
|
4170
|
+
)
|
|
4171
|
+
live.activeDrains.add(settled)
|
|
4172
|
+
void settled.then(() => live.activeDrains.delete(settled))
|
|
4173
|
+
return running
|
|
4174
|
+
}
|
|
4175
|
+
|
|
4176
|
+
// Resolves once no drain is running. Loops because a drain's post-`draining`
|
|
4177
|
+
// tail can start a rival, and because work queued during one turn opens the
|
|
4178
|
+
// next; a snapshot `Promise.all` would return with that successor in flight.
|
|
4179
|
+
const settleDrains = async (live: LiveSession): Promise<void> => {
|
|
4180
|
+
while (live.activeDrains.size > 0) {
|
|
4181
|
+
await Promise.all(live.activeDrains)
|
|
3534
4182
|
}
|
|
3535
4183
|
}
|
|
3536
4184
|
|
|
@@ -3540,33 +4188,17 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3540
4188
|
// were enqueued while draining), so they are transplanted straight onto the
|
|
3541
4189
|
// fresh session's queues rather than re-routed through route() — re-routing
|
|
3542
4190
|
// would re-run the claim/command/permission gates and re-derive engagement
|
|
3543
|
-
// from a lossy QueuedInbound projection.
|
|
3544
|
-
//
|
|
3545
|
-
|
|
3546
|
-
|
|
3547
|
-
inbounds: QueuedInbound[],
|
|
3548
|
-
observed: ObservedInbound[],
|
|
3549
|
-
reminders: string[],
|
|
3550
|
-
): Promise<void> => {
|
|
3551
|
-
// Observed context alone is carried too: observe() can buffer post-reload
|
|
3552
|
-
// messages onto contextBuffer with no queued prompt, and dropping them would
|
|
3553
|
-
// lose the successor's "recent context". Only skip when nothing at all was
|
|
3554
|
-
// carried.
|
|
3555
|
-
if (inbounds.length === 0 && reminders.length === 0 && observed.length === 0) return
|
|
3556
|
-
let successor: LiveSession
|
|
4191
|
+
// from a lossy QueuedInbound projection. The batch is retained BEFORE the
|
|
4192
|
+
// recreate attempt so a timeout leaves it available to the next successful
|
|
4193
|
+
// ensureLive rather than dropping the user's messages at the handoff seam.
|
|
4194
|
+
const handOffToSuccessor = async (key: ChannelKey): Promise<void> => {
|
|
3557
4195
|
try {
|
|
3558
|
-
|
|
4196
|
+
await ensureLive(key)
|
|
3559
4197
|
} catch (err) {
|
|
3560
|
-
logger.warn(
|
|
3561
|
-
|
|
4198
|
+
logger.warn(
|
|
4199
|
+
`[channels] ${channelKeyId(key)}: successor recreate after reload failed; queued work retained for the next successful session: ${describeError(err)}`,
|
|
4200
|
+
)
|
|
3562
4201
|
}
|
|
3563
|
-
if (successor.destroyed) return
|
|
3564
|
-
successor.promptQueue.push(...inbounds)
|
|
3565
|
-
successor.contextBuffer.push(...observed)
|
|
3566
|
-
successor.pendingSystemReminders.push(...reminders)
|
|
3567
|
-
// Observed-only context is NOT a turn trigger — it waits on contextBuffer for
|
|
3568
|
-
// a real inbound. Drain only when there is actual work (a prompt or reminder).
|
|
3569
|
-
if ((inbounds.length > 0 || reminders.length > 0) && !successor.draining) void drain(successor)
|
|
3570
4202
|
}
|
|
3571
4203
|
|
|
3572
4204
|
const scheduleDebouncedDrain = (live: LiveSession): void => {
|
|
@@ -3872,6 +4504,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3872
4504
|
workspace: event.workspace,
|
|
3873
4505
|
chat: event.chat,
|
|
3874
4506
|
thread: event.thread,
|
|
4507
|
+
...(event.room?.parentChat !== undefined ? { parentChat: event.room.parentChat } : {}),
|
|
3875
4508
|
lastInboundAuthorId: event.authorId,
|
|
3876
4509
|
})
|
|
3877
4510
|
|
|
@@ -3975,9 +4608,14 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3975
4608
|
replyToBotMessageId: event.replyToBotMessageId,
|
|
3976
4609
|
isDm: event.isDm,
|
|
3977
4610
|
...(event.typingThread !== undefined ? { typingThread: event.typingThread } : {}),
|
|
4611
|
+
...(event.githubReviewRound !== undefined ? { githubReviewRound: event.githubReviewRound } : {}),
|
|
3978
4612
|
receivedAt: now(),
|
|
3979
4613
|
ts: event.ts,
|
|
3980
4614
|
})
|
|
4615
|
+
if (event.githubReviewRound !== undefined) {
|
|
4616
|
+
live.githubReviewRound = registerGithubReviewRound(event.githubReviewRound)
|
|
4617
|
+
persistGithubReviewRound(live, live.githubReviewRound)
|
|
4618
|
+
}
|
|
3981
4619
|
// Make the typing anchor live BEFORE startTypingHeartbeat fires (route()
|
|
3982
4620
|
// starts the heartbeat right after enqueue, ahead of drain). drain() later
|
|
3983
4621
|
// refreshes it to the last inbound of a coalesced batch.
|
|
@@ -4138,7 +4776,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
4138
4776
|
// its persistent :eyes: is added strictly AFTER the transient one is removed
|
|
4139
4777
|
// (see reactOnSilentAck). Fire-and-forget callers just `void` the result.
|
|
4140
4778
|
const dropEngageReactions = (live: LiveSession, addPromises: Array<Promise<ReactionRef | null>>): Promise<void> => {
|
|
4141
|
-
return Promise.all(addPromises.map((addPromise) => dropOneEngageReaction(live, addPromise))).then(
|
|
4779
|
+
return Promise.all(addPromises.map((addPromise) => dropOneEngageReaction(live.key, addPromise))).then(
|
|
4780
|
+
() => undefined,
|
|
4781
|
+
)
|
|
4142
4782
|
}
|
|
4143
4783
|
|
|
4144
4784
|
// Only the LAST engaging inbound of a coalesced batch should carry the eager
|
|
@@ -4153,29 +4793,35 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
4153
4793
|
void dropEngageReactions(live, addPromises)
|
|
4154
4794
|
}
|
|
4155
4795
|
|
|
4156
|
-
const
|
|
4796
|
+
const dropPendingReloadHandoffEngageReactions = (pending: PendingReloadHandoff): Promise<void> => {
|
|
4797
|
+
const addPromises = pending.inbounds.flatMap((item) =>
|
|
4798
|
+
item.engageReaction !== undefined ? [item.engageReaction] : [],
|
|
4799
|
+
)
|
|
4800
|
+
for (const item of pending.inbounds) delete item.engageReaction
|
|
4801
|
+
return Promise.all(addPromises.map((addPromise) => dropOneEngageReaction(pending.key, addPromise))).then(
|
|
4802
|
+
() => undefined,
|
|
4803
|
+
)
|
|
4804
|
+
}
|
|
4805
|
+
|
|
4806
|
+
const dropOneEngageReaction = (key: ChannelKey, addPromise: Promise<ReactionRef | null>): Promise<void> => {
|
|
4157
4807
|
return addPromise
|
|
4158
4808
|
.then((reactionRef) => {
|
|
4159
4809
|
if (reactionRef === null) return undefined
|
|
4160
4810
|
return removeReaction({
|
|
4161
|
-
adapter:
|
|
4162
|
-
workspace:
|
|
4163
|
-
chat:
|
|
4164
|
-
thread:
|
|
4811
|
+
adapter: key.adapter,
|
|
4812
|
+
workspace: key.workspace,
|
|
4813
|
+
chat: key.chat,
|
|
4814
|
+
thread: key.thread,
|
|
4165
4815
|
reactionRef,
|
|
4166
4816
|
})
|
|
4167
4817
|
})
|
|
4168
4818
|
.then((result) => {
|
|
4169
4819
|
if (result && !result.ok && result.code !== 'unsupported' && result.code !== 'not-found') {
|
|
4170
|
-
logger.info(
|
|
4171
|
-
`[channels] engage-unreact failed adapter=${live.key.adapter} chat=${live.key.chat}: ${result.error}`,
|
|
4172
|
-
)
|
|
4820
|
+
logger.info(`[channels] engage-unreact failed adapter=${key.adapter} chat=${key.chat}: ${result.error}`)
|
|
4173
4821
|
}
|
|
4174
4822
|
})
|
|
4175
4823
|
.catch((err) => {
|
|
4176
|
-
logger.info(
|
|
4177
|
-
`[channels] engage-unreact threw adapter=${live.key.adapter} chat=${live.key.chat}: ${describeError(err)}`,
|
|
4178
|
-
)
|
|
4824
|
+
logger.info(`[channels] engage-unreact threw adapter=${key.adapter} chat=${key.chat}: ${describeError(err)}`)
|
|
4179
4825
|
})
|
|
4180
4826
|
}
|
|
4181
4827
|
|
|
@@ -4618,6 +5264,35 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
4618
5264
|
accountingTarget.thread === (msg.thread ?? null)
|
|
4619
5265
|
const keyId = channelKeyId(accountingTarget)
|
|
4620
5266
|
const live = liveSessions.get(keyId)
|
|
5267
|
+
// Credit sticky where the reply was PUBLISHED, not where it was accounted.
|
|
5268
|
+
// The two diverge when a caller answers from one sub-surface but publishes
|
|
5269
|
+
// to another in the same room — `postDuplicateRequestChangesComment` sends
|
|
5270
|
+
// with `thread: null` while passing the review-thread session as
|
|
5271
|
+
// `accountingTarget`. An inbound is keyed from its OWN tuple, so the human's
|
|
5272
|
+
// follow-up consumes the root key and finds nothing: the reply was observed
|
|
5273
|
+
// and silently dropped.
|
|
5274
|
+
//
|
|
5275
|
+
// Delivery-only, not both. A dual grant cannot be undone atomically —
|
|
5276
|
+
// `clearSticky` clears one key, so `channel_disengage` on the originating
|
|
5277
|
+
// thread would strand the root credit. It also buys nothing here: GitHub
|
|
5278
|
+
// review-comment inbounds set `suppressSticky`, so they never reach the
|
|
5279
|
+
// sticky gate and engage via `replyToBotMessageId` instead.
|
|
5280
|
+
//
|
|
5281
|
+
// Same adapter/workspace/chat only. `targets` are authors of the ACCOUNTING
|
|
5282
|
+
// turn and author ids are namespaced per adapter, so redirecting a genuine
|
|
5283
|
+
// cross-channel send would credit ids that cannot appear in that room.
|
|
5284
|
+
const stickyGrantKeyId =
|
|
5285
|
+
!deliveryMatchesAccounting &&
|
|
5286
|
+
accountingTarget.adapter === msg.adapter &&
|
|
5287
|
+
accountingTarget.workspace === msg.workspace &&
|
|
5288
|
+
accountingTarget.chat === msg.chat
|
|
5289
|
+
? channelKeyId({
|
|
5290
|
+
adapter: msg.adapter,
|
|
5291
|
+
workspace: msg.workspace,
|
|
5292
|
+
chat: msg.chat,
|
|
5293
|
+
thread: msg.thread ?? null,
|
|
5294
|
+
})
|
|
5295
|
+
: keyId
|
|
4621
5296
|
const sendKey = consecutiveSendKey(accountingTarget.chat, accountingTarget.thread)
|
|
4622
5297
|
// Tool-source sends consume the captured quote candidate exactly
|
|
4623
5298
|
// once per turn — the intervening-observed check runs HERE against
|
|
@@ -4683,7 +5358,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
4683
5358
|
const count = (live.policyDeniedToolSendsThisTurn.get(sendKey) ?? 0) + 1
|
|
4684
5359
|
live.policyDeniedToolSendsThisTurn.set(sendKey, count)
|
|
4685
5360
|
if (count >= MAX_POLICY_DENIED_CHANNEL_SENDS_PER_TURN) {
|
|
4686
|
-
logger.warn(
|
|
5361
|
+
logger.warn(
|
|
5362
|
+
`[channels] ${live.keyId}: aborting turn — ${count} policy-denied channel sends (last: ${code}) site=policy_denied_send_cap session=${live.sessionId} reason=policy_denied:${code}`,
|
|
5363
|
+
)
|
|
4687
5364
|
live.abortReasonThisTurn = { turnSeq: live.turnSeq, reason: `policy_denied:${code}` }
|
|
4688
5365
|
if (live.session.agent.signal?.aborted !== true) live.session.agent.abort()
|
|
4689
5366
|
}
|
|
@@ -4828,7 +5505,13 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
4828
5505
|
}
|
|
4829
5506
|
}
|
|
4830
5507
|
if (targets.size > 0) {
|
|
4831
|
-
grantStickyForReplyTargets(
|
|
5508
|
+
grantStickyForReplyTargets(
|
|
5509
|
+
stickyLedger,
|
|
5510
|
+
stickyGrantKeyId,
|
|
5511
|
+
Array.from(targets),
|
|
5512
|
+
adapterConfig.engagement,
|
|
5513
|
+
now(),
|
|
5514
|
+
)
|
|
4832
5515
|
}
|
|
4833
5516
|
}
|
|
4834
5517
|
const turnCount = live.consecutiveSends.get(sendKey) ?? 0
|
|
@@ -4848,24 +5531,64 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
4848
5531
|
}
|
|
4849
5532
|
}
|
|
4850
5533
|
|
|
4851
|
-
// The turn ended via
|
|
5534
|
+
// The turn ended via terminal channel_reply completion. If that reply promised to keep
|
|
4852
5535
|
// working but omitted `more_work_this_turn: true`, queue ONE reminder-only re-prompt so
|
|
4853
|
-
// the model gets a second chance to actually do it. The
|
|
4854
|
-
// (safe default preserved); this only adds an optional nudge. Bounded by
|
|
5536
|
+
// the model gets a second chance to actually do it. The tool batch already
|
|
5537
|
+
// terminated (safe default preserved); this only adds an optional nudge. Bounded by
|
|
4855
5538
|
// MAX_WILLINGNESS_NUDGES and gated on `promptQueue` being empty so a real
|
|
4856
5539
|
// inbound that coalesced into this turn is never answered with a stale nudge.
|
|
4857
5540
|
const maybeNudgeContinuationWillingness = (live: LiveSession): void => {
|
|
4858
|
-
const record = live.
|
|
4859
|
-
live.
|
|
5541
|
+
const record = live.lastTerminalReplyCompletion
|
|
5542
|
+
live.lastTerminalReplyCompletion = null
|
|
4860
5543
|
if (record === null || record.turnSeq !== live.turnSeq) return
|
|
4861
5544
|
if (live.willingnessNudges >= MAX_WILLINGNESS_NUDGES) return
|
|
4862
5545
|
if (live.promptQueue.length > 0) return
|
|
5546
|
+
if (record.text === undefined) return
|
|
4863
5547
|
if (!detectContinuationWillingness(record.text)) return
|
|
4864
5548
|
live.willingnessNudges++
|
|
4865
5549
|
logger.info(
|
|
4866
5550
|
`[channels] ${live.keyId} willingness_nudge attempt=${live.willingnessNudges}/${MAX_WILLINGNESS_NUDGES}`,
|
|
4867
5551
|
)
|
|
4868
|
-
live.pendingSystemReminders.push(WILLINGNESS_NUDGE)
|
|
5552
|
+
live.pendingSystemReminders.push(retryReminder(WILLINGNESS_NUDGE))
|
|
5553
|
+
}
|
|
5554
|
+
|
|
5555
|
+
const armRetainedOutputAckIfEligible = (
|
|
5556
|
+
live: LiveSession,
|
|
5557
|
+
successfulSendsBeforePrompt: number,
|
|
5558
|
+
explicitlySkipped: boolean,
|
|
5559
|
+
): boolean => {
|
|
5560
|
+
// A formal GitHub review is user-facing output delivered outside the channel.
|
|
5561
|
+
// Preserve its acknowledgement even when the model closes the turn through
|
|
5562
|
+
// skip_response after publishing the review.
|
|
5563
|
+
if (
|
|
5564
|
+
live.githubReviewOutputTurn === live.turnSeq &&
|
|
5565
|
+
live.successfulChannelSends === successfulSendsBeforePrompt &&
|
|
5566
|
+
live.currentTurnAuthorId !== null
|
|
5567
|
+
) {
|
|
5568
|
+
logger.info(`[channels] ${live.keyId} empty_turn_suppressed cause=github_review_output_this_turn`)
|
|
5569
|
+
armSilentTurnAck(live, 'github_review_output')
|
|
5570
|
+
return true
|
|
5571
|
+
}
|
|
5572
|
+
|
|
5573
|
+
// An active child means delivery is deferred rather than dropped. Normally a
|
|
5574
|
+
// completed prose leaf still goes through reply recovery, but skip_response is
|
|
5575
|
+
// authoritative: its prose is intentionally discarded, while the progress
|
|
5576
|
+
// acknowledgement must remain until the child reports back.
|
|
5577
|
+
const awaitLeaf = recoverableAssistantText(live.session)
|
|
5578
|
+
const awaitLeafIsUnfinishedToolUse = awaitLeaf?.source === 'mid-turn' || awaitLeaf?.source === 'pre-tool'
|
|
5579
|
+
if (
|
|
5580
|
+
live.currentTurnAuthorId !== null &&
|
|
5581
|
+
(explicitlySkipped ||
|
|
5582
|
+
awaitLeaf === null ||
|
|
5583
|
+
awaitLeafIsUnfinishedToolUse ||
|
|
5584
|
+
endsWithNoReplySignal(awaitLeaf.text)) &&
|
|
5585
|
+
isAwaitingBackgroundChild(live, 'empty_turn_recovery')
|
|
5586
|
+
) {
|
|
5587
|
+
logger.info(`[channels] ${live.keyId} empty_turn_suppressed cause=awaiting_background_child`)
|
|
5588
|
+
armSilentTurnAck(live, 'awaiting_background_child')
|
|
5589
|
+
return true
|
|
5590
|
+
}
|
|
5591
|
+
return false
|
|
4869
5592
|
}
|
|
4870
5593
|
|
|
4871
5594
|
const validateChannelTurn = async (live: LiveSession, successfulSendsBeforePrompt: number): Promise<void> => {
|
|
@@ -4885,8 +5608,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
4885
5608
|
if (live.skippedTurn !== null && live.skippedTurn.turnSeq === live.turnSeq && !skipContested) {
|
|
4886
5609
|
const { reason } = live.skippedTurn
|
|
4887
5610
|
live.skippedTurn = null
|
|
5611
|
+
armRetainedOutputAckIfEligible(live, successfulSendsBeforePrompt, true)
|
|
4888
5612
|
logger.info(`[channels] ${live.keyId} skipped_by_tool reason=${JSON.stringify(reason)}`)
|
|
4889
|
-
armSilentTurnAck(live, 'skip_response')
|
|
4890
5613
|
void dropContinuationReactions(live)
|
|
4891
5614
|
return
|
|
4892
5615
|
}
|
|
@@ -4900,23 +5623,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
4900
5623
|
live.stagedFallbackCause = { cause, sendCountAtStage: live.successfulChannelSends }
|
|
4901
5624
|
}
|
|
4902
5625
|
|
|
4903
|
-
|
|
4904
|
-
|
|
4905
|
-
// the turn's user-facing output — it just went through the GitHub review API, not
|
|
4906
|
-
// channel_reply/channel_send, so `successfulChannelSends` never moved. An empty
|
|
4907
|
-
// completion afterward is the agent legitimately having nothing more to say, NOT
|
|
4908
|
-
// a dead turn: skip the empty-turn retries AND the "I got stuck" fallback and
|
|
4909
|
-
// treat it as silent completion. Gated on no channel send this turn so a turn
|
|
4910
|
-
// that ALSO replied in-channel still runs the normal reply-recovery below.
|
|
4911
|
-
if (
|
|
4912
|
-
live.githubReviewOutputTurn === live.turnSeq &&
|
|
4913
|
-
live.successfulChannelSends === successfulSendsBeforePrompt &&
|
|
4914
|
-
live.currentTurnAuthorId !== null
|
|
4915
|
-
) {
|
|
4916
|
-
logger.info(`[channels] ${live.keyId} empty_turn_suppressed cause=github_review_output_this_turn`)
|
|
4917
|
-
armSilentTurnAck(live, 'github_review_output')
|
|
4918
|
-
return
|
|
4919
|
-
}
|
|
5626
|
+
const awaitLeaf = recoverableAssistantText(live.session)
|
|
5627
|
+
if (armRetainedOutputAckIfEligible(live, successfulSendsBeforePrompt, false)) return
|
|
4920
5628
|
|
|
4921
5629
|
// Suppress a leaked tool call (never post the plumbing) and, while budget
|
|
4922
5630
|
// remains, push a self-correction reminder so the same logical turn
|
|
@@ -4930,7 +5638,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
4930
5638
|
`[channels] ${live.keyId}: suppressed plain_text_tool_call_leak (nudge ` +
|
|
4931
5639
|
`attempt=${live.toolLeakRetries}/${MAX_TOOL_LEAK_RETRIES}) text_len=${leakedText.length}`,
|
|
4932
5640
|
)
|
|
4933
|
-
live.pendingSystemReminders.push(TOOL_CALL_LEAK_NUDGE)
|
|
5641
|
+
live.pendingSystemReminders.push(retryReminder(TOOL_CALL_LEAK_NUDGE))
|
|
4934
5642
|
return
|
|
4935
5643
|
}
|
|
4936
5644
|
logger.warn(
|
|
@@ -4939,6 +5647,49 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
4939
5647
|
)
|
|
4940
5648
|
}
|
|
4941
5649
|
|
|
5650
|
+
const retryStrandedToolUse = async (cause: string, exhaustedCause: string): Promise<void> => {
|
|
5651
|
+
if (live.emptyTurnRetries < MAX_EMPTY_TURN_RETRIES) {
|
|
5652
|
+
live.emptyTurnRetries++
|
|
5653
|
+
const routerAbortReason =
|
|
5654
|
+
live.abortReasonThisTurn !== null && live.abortReasonThisTurn.turnSeq === live.turnSeq
|
|
5655
|
+
? live.abortReasonThisTurn.reason
|
|
5656
|
+
: undefined
|
|
5657
|
+
const agentAbortReason =
|
|
5658
|
+
live.session.agent.signal?.aborted === true ? live.session.getAbortReason?.() : undefined
|
|
5659
|
+
const abortReason = routerAbortReason ?? agentAbortReason ?? 'unknown'
|
|
5660
|
+
logger.warn(
|
|
5661
|
+
`[channels] ${live.keyId} empty_turn_retry attempt=${live.emptyTurnRetries}/${MAX_EMPTY_TURN_RETRIES} ` +
|
|
5662
|
+
`cause=${cause} abort_reason=${abortReason}`,
|
|
5663
|
+
)
|
|
5664
|
+
live.pendingSystemReminders.push(retryReminder(STRANDED_TOOLUSE_CONTINUATION_NUDGE))
|
|
5665
|
+
return
|
|
5666
|
+
}
|
|
5667
|
+
await postEmptyTurnFallback(live, exhaustedCause)
|
|
5668
|
+
}
|
|
5669
|
+
|
|
5670
|
+
// A real asker who received nothing cannot distinguish unfinished tool-use
|
|
5671
|
+
// narration from a completed answer. Posting that scratchpad can falsely
|
|
5672
|
+
// claim completion in the wrong language or before the tool result is
|
|
5673
|
+
// interpreted; treating it as deliberate silence strands the asker instead.
|
|
5674
|
+
// Keep both textless and text-bearing unfinished shapes on the established
|
|
5675
|
+
// bounded continuation ladder, while explicit NO_REPLY, queued fresh input,
|
|
5676
|
+
// observation-only turns, and every earlier delivery-deferred guard retain
|
|
5677
|
+
// their narrower silence contracts.
|
|
5678
|
+
const unfinishedToolUse = awaitLeaf
|
|
5679
|
+
const unfinishedToolUseWithoutReply =
|
|
5680
|
+
unfinishedToolUse !== null &&
|
|
5681
|
+
(unfinishedToolUse.source === 'mid-turn' || unfinishedToolUse.source === 'pre-tool') &&
|
|
5682
|
+
(unfinishedToolUse.text.trim() === '' || !endsWithNoReplySignal(unfinishedToolUse.text))
|
|
5683
|
+
if (
|
|
5684
|
+
unfinishedToolUseWithoutReply &&
|
|
5685
|
+
live.successfulChannelSends === successfulSendsBeforePrompt &&
|
|
5686
|
+
live.currentTurnAuthorId !== null &&
|
|
5687
|
+
live.promptQueue.length === 0
|
|
5688
|
+
) {
|
|
5689
|
+
await retryStrandedToolUse('stranded_toolUse_without_send', 'stranded_toolUse_without_send_retries_exhausted')
|
|
5690
|
+
return
|
|
5691
|
+
}
|
|
5692
|
+
|
|
4942
5693
|
// A send landed this turn, but the model may have posted a `more_work_this_turn: true`
|
|
4943
5694
|
// progress reply, kept working, then ENDED with its final answer as plain
|
|
4944
5695
|
// prose — never calling a channel tool again. The terminal-reply abort fires
|
|
@@ -4950,6 +5701,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
4950
5701
|
// the send is narration the model emitted with/before the reply that already
|
|
4951
5702
|
// landed — suppress it, as before.
|
|
4952
5703
|
if (live.successfulChannelSends > successfulSendsBeforePrompt) {
|
|
5704
|
+
const terminalReplyCompletedThisTurn = live.lastTerminalReplyCompletion?.turnSeq === live.turnSeq
|
|
4953
5705
|
maybeNudgeContinuationWillingness(live)
|
|
4954
5706
|
|
|
4955
5707
|
// A `channel_reply({ more_work_this_turn: true })` progress ack landed this turn (the
|
|
@@ -4986,7 +5738,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
4986
5738
|
`[channels] ${live.keyId} send_willingness_nudge attempt=${live.willingnessNudges}/${MAX_WILLINGNESS_NUDGES} ` +
|
|
4987
5739
|
`cause=empty_stop_after_continue_reply`,
|
|
4988
5740
|
)
|
|
4989
|
-
live.pendingSystemReminders.push(SEND_WILLINGNESS_NUDGE)
|
|
5741
|
+
live.pendingSystemReminders.push(retryReminder(SEND_WILLINGNESS_NUDGE))
|
|
4990
5742
|
} else {
|
|
4991
5743
|
stageEmptyTurnFallback('empty_stop_after_continue_reply_nudges_exhausted')
|
|
4992
5744
|
}
|
|
@@ -4997,7 +5749,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
4997
5749
|
// then an EMPTY `stop` leaf: the model computed the answer in its reasoning
|
|
4998
5750
|
// / tool results but never sent it (the Kimi/Fireworks empty-completion
|
|
4999
5751
|
// flake). `maybeNudgeContinuationWillingness` above can't catch this — it
|
|
5000
|
-
// reads `
|
|
5752
|
+
// reads `lastTerminalReplyCompletion`, which only a `channel_reply` sets;
|
|
5001
5753
|
// `channel_send` keeps the turn alive and stamps nothing. And the
|
|
5002
5754
|
// stranded-toolUse retry below requires `source !== 'leaf'`, but an empty
|
|
5003
5755
|
// `stop` leaf recovers as `source: 'leaf'`, so this shape would otherwise
|
|
@@ -5022,13 +5774,24 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
5022
5774
|
`[channels] ${live.keyId} send_willingness_nudge attempt=${live.willingnessNudges}/${MAX_WILLINGNESS_NUDGES} ` +
|
|
5023
5775
|
`cause=empty_stop_after_send_ack`,
|
|
5024
5776
|
)
|
|
5025
|
-
live.pendingSystemReminders.push(SEND_WILLINGNESS_NUDGE)
|
|
5777
|
+
live.pendingSystemReminders.push(retryReminder(SEND_WILLINGNESS_NUDGE))
|
|
5026
5778
|
} else {
|
|
5027
5779
|
stageEmptyTurnFallback('empty_stop_after_send_ack_nudges_exhausted')
|
|
5028
5780
|
}
|
|
5029
5781
|
return
|
|
5030
5782
|
}
|
|
5031
5783
|
|
|
5784
|
+
// A terminal channel_reply now ends the SDK tool batch with
|
|
5785
|
+
// ToolResult.terminate after its matching result is persisted. The leaf
|
|
5786
|
+
// therefore has the same toolResult-under-toolUse shape as genuinely
|
|
5787
|
+
// stranded post-status work, but this turn already delivered its final
|
|
5788
|
+
// answer and explicitly terminated. The 2026-08-28 Discord incident
|
|
5789
|
+
// crossed this distinction: validation re-prompted the completed turn as
|
|
5790
|
+
// `stranded_toolUse_after_send`, then subsequent inbounds accumulated on
|
|
5791
|
+
// the failed recovery branch. Keep willingness nudges queued above, but do
|
|
5792
|
+
// not send terminal completion through stranded-work recovery.
|
|
5793
|
+
if (terminalReplyCompletedThisTurn) return
|
|
5794
|
+
|
|
5032
5795
|
const trailing = recoverableAssistantText(live.session)
|
|
5033
5796
|
if (trailing === null || trailing.source !== 'leaf') {
|
|
5034
5797
|
// A `more_work_this_turn: true` status reply landed, then the turn stranded on an
|
|
@@ -5046,29 +5809,18 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
5046
5809
|
// that accompanied the already-landed reply); only the no-prose strand
|
|
5047
5810
|
// gets a retry-or-fallback.
|
|
5048
5811
|
if (leafIsStrandedToolUse(live.session) && live.currentTurnAuthorId !== null) {
|
|
5049
|
-
|
|
5050
|
-
live.emptyTurnRetries++
|
|
5051
|
-
const routerAbortReason =
|
|
5052
|
-
live.abortReasonThisTurn !== null && live.abortReasonThisTurn.turnSeq === live.turnSeq
|
|
5053
|
-
? live.abortReasonThisTurn.reason
|
|
5054
|
-
: undefined
|
|
5055
|
-
const agentAbortReason =
|
|
5056
|
-
live.session.agent.signal?.aborted === true ? live.session.getAbortReason?.() : undefined
|
|
5057
|
-
const abortReason = routerAbortReason ?? agentAbortReason ?? 'unknown'
|
|
5058
|
-
logger.warn(
|
|
5059
|
-
`[channels] ${live.keyId} empty_turn_retry attempt=${live.emptyTurnRetries}/${MAX_EMPTY_TURN_RETRIES} ` +
|
|
5060
|
-
`cause=stranded_toolUse_after_send abort_reason=${abortReason}`,
|
|
5061
|
-
)
|
|
5062
|
-
live.pendingSystemReminders.push(STRANDED_TOOLUSE_CONTINUATION_NUDGE)
|
|
5063
|
-
} else {
|
|
5064
|
-
await postEmptyTurnFallback(live, 'stranded_toolUse_retries_exhausted')
|
|
5065
|
-
}
|
|
5812
|
+
await retryStrandedToolUse('stranded_toolUse_after_send', 'stranded_toolUse_retries_exhausted')
|
|
5066
5813
|
}
|
|
5067
5814
|
return
|
|
5068
5815
|
}
|
|
5069
5816
|
if (live.session.sessionManager.getLeafEntry()?.id === live.lastSendLeafId) return
|
|
5070
5817
|
}
|
|
5071
5818
|
|
|
5819
|
+
if (unfinishedToolUseWithoutReply) {
|
|
5820
|
+
logger.info(`[channels] ${live.keyId} empty_turn_suppressed cause=unfinished_toolUse_continuation_ineligible`)
|
|
5821
|
+
return
|
|
5822
|
+
}
|
|
5823
|
+
|
|
5072
5824
|
let candidate = recoverableAssistantText(live.session)
|
|
5073
5825
|
// A `length` leaf is recovered ONLY when stripping leaked `<think>…</think>`
|
|
5074
5826
|
// spans actually removed something AND leaves a postable reply. The removal
|
|
@@ -5174,7 +5926,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
5174
5926
|
`[channels] ${live.keyId} empty_turn_retry attempt=${live.emptyTurnRetries}/${MAX_EMPTY_TURN_RETRIES} ` +
|
|
5175
5927
|
`max_tokens=${live.nextPromptMaxTokens ?? CHANNEL_MAX_OUTPUT_TOKENS}`,
|
|
5176
5928
|
)
|
|
5177
|
-
live.pendingSystemReminders.push(EMPTY_TURN_RETRY_NUDGE)
|
|
5929
|
+
live.pendingSystemReminders.push(retryReminder(EMPTY_TURN_RETRY_NUDGE))
|
|
5178
5930
|
return
|
|
5179
5931
|
}
|
|
5180
5932
|
await postEmptyTurnFallback(live, attemptedSendThisTurn ? 'send_thrash' : 'retries_exhausted')
|
|
@@ -5209,7 +5961,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
5209
5961
|
`[channels] ${live.keyId} empty_turn_retry attempt=${live.emptyTurnRetries}/${MAX_EMPTY_TURN_RETRIES} ` +
|
|
5210
5962
|
`cause=cold_start_solo_bare_empty`,
|
|
5211
5963
|
)
|
|
5212
|
-
live.pendingSystemReminders.push(COLD_START_REPLY_NUDGE)
|
|
5964
|
+
live.pendingSystemReminders.push(retryReminder(COLD_START_REPLY_NUDGE))
|
|
5213
5965
|
return
|
|
5214
5966
|
}
|
|
5215
5967
|
await postEmptyTurnFallback(live, 'cold_start_solo_bare_empty_retries_exhausted')
|
|
@@ -5245,7 +5997,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
5245
5997
|
`[channels] ${live.keyId} empty_turn_retry attempt=${live.emptyTurnRetries}/${MAX_EMPTY_TURN_RETRIES} ` +
|
|
5246
5998
|
`cause=empty_stop_after_tool_work`,
|
|
5247
5999
|
)
|
|
5248
|
-
live.pendingSystemReminders.push(EMPTY_STOP_AFTER_TOOL_WORK_NUDGE)
|
|
6000
|
+
live.pendingSystemReminders.push(retryReminder(EMPTY_STOP_AFTER_TOOL_WORK_NUDGE))
|
|
5249
6001
|
return
|
|
5250
6002
|
}
|
|
5251
6003
|
await postEmptyTurnFallback(live, 'empty_stop_after_tool_work_retries_exhausted')
|
|
@@ -5266,7 +6018,6 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
5266
6018
|
}
|
|
5267
6019
|
const leakedReasoning = !isNoReplySignal(assistantText)
|
|
5268
6020
|
logger.info(`[channels] ${live.keyId} no_reply${leakedReasoning ? ' (with_leaked_reasoning)' : ''}`)
|
|
5269
|
-
armSilentTurnAck(live, 'no_reply')
|
|
5270
6021
|
void dropContinuationReactions(live)
|
|
5271
6022
|
return
|
|
5272
6023
|
}
|
|
@@ -5312,7 +6063,6 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
5312
6063
|
logger.warn(
|
|
5313
6064
|
`[channels] ${live.keyId}: suppressed plain_text_tool_call_leak (silent) text_len=${assistantText.length}`,
|
|
5314
6065
|
)
|
|
5315
|
-
armSilentTurnAck(live, 'skip_response_text_leak')
|
|
5316
6066
|
return
|
|
5317
6067
|
}
|
|
5318
6068
|
if (plainTextToolCallKind === 'suppress-warn') {
|
|
@@ -5348,21 +6098,15 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
5348
6098
|
assistantText = extracted
|
|
5349
6099
|
}
|
|
5350
6100
|
|
|
5351
|
-
// `source` distinguishes the
|
|
6101
|
+
// `source` distinguishes the completed recovery shapes for log triage:
|
|
5352
6102
|
// - 'leaf': the assistant message IS the leaf with stopReason 'stop'
|
|
5353
6103
|
// (existing behavior; model ended its turn with text but forgot to
|
|
5354
6104
|
// call channel_reply).
|
|
5355
|
-
// - '
|
|
5356
|
-
//
|
|
5357
|
-
//
|
|
5358
|
-
//
|
|
5359
|
-
//
|
|
5360
|
-
// and the assistant message lives upstream in the branch. This is the
|
|
5361
|
-
// Kimi-on-Fireworks `kimi-k2p6-turbo` failure mode where the post-tool
|
|
5362
|
-
// follow-up LLM call never produced a persisted assistant message, so
|
|
5363
|
-
// the model's pre-tool commentary is the only user-facing text we have.
|
|
5364
|
-
// Recovering it means the user gets *something* — strictly better than
|
|
5365
|
-
// the historical silent drop.
|
|
6105
|
+
// - 'length-leaf': the assistant message hit the output cap, leaked
|
|
6106
|
+
// reasoning was stripped, and a complete-looking answer survived.
|
|
6107
|
+
// Unfinished 'mid-turn' / 'pre-tool' prose never reaches this egress: the
|
|
6108
|
+
// terminal gate above either continues an eligible turn or preserves the
|
|
6109
|
+
// silence contract that made continuation ineligible.
|
|
5366
6110
|
// Egress-level GitHub review guards. The false-receipt and re-review
|
|
5367
6111
|
// stranding guards live inside the channel_reply / channel_send tool
|
|
5368
6112
|
// handlers, but recovery surfaces trailing assistant prose through a
|
|
@@ -5509,8 +6253,16 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
5509
6253
|
live.unsubTodoOutcome?.()
|
|
5510
6254
|
live.unsubTodoOutcome = null
|
|
5511
6255
|
await stopTypingHeartbeat(live)
|
|
6256
|
+
// Captured before the abort call: `draining` flips false in drain()'s own
|
|
6257
|
+
// finally once the turn it was guarding ends, so reading it here is the
|
|
6258
|
+
// only reliable signal that this teardown cut off a turn actually in
|
|
6259
|
+
// flight rather than an already-idle session.
|
|
6260
|
+
const abortedInFlightTurn = live.draining
|
|
5512
6261
|
try {
|
|
5513
6262
|
await live.session.abort()
|
|
6263
|
+
if (abortedInFlightTurn) {
|
|
6264
|
+
logger.warn(`[channels] ${live.keyId} abort site=teardown session=${live.sessionId} reason=teardown`)
|
|
6265
|
+
}
|
|
5514
6266
|
} catch (err) {
|
|
5515
6267
|
logger.warn(`[channels] abort failed for ${live.keyId}: ${describeError(err)}`)
|
|
5516
6268
|
}
|
|
@@ -5530,6 +6282,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
5530
6282
|
}
|
|
5531
6283
|
|
|
5532
6284
|
const runIdleGc = async (): Promise<void> => {
|
|
6285
|
+
await expirePendingReloadHandoffs()
|
|
5533
6286
|
const t = now()
|
|
5534
6287
|
const victims: LiveSession[] = []
|
|
5535
6288
|
for (const live of liveSessions.values()) {
|
|
@@ -5564,6 +6317,11 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
5564
6317
|
if (gcTimer) clearInterval(gcTimer)
|
|
5565
6318
|
gcTimer = null
|
|
5566
6319
|
liveGeneration++
|
|
6320
|
+
const pendingHandoffs = Array.from(pendingReloadHandoffs.values())
|
|
6321
|
+
pendingReloadHandoffs.clear()
|
|
6322
|
+
for (const pending of pendingHandoffs) {
|
|
6323
|
+
await reportDiscardedReloadHandoff(pending, 'router stopped before replay could complete')
|
|
6324
|
+
}
|
|
5567
6325
|
const all = Array.from(liveSessions.values())
|
|
5568
6326
|
liveSessions.clear()
|
|
5569
6327
|
for (const live of all) {
|
|
@@ -5625,6 +6383,11 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
5625
6383
|
)
|
|
5626
6384
|
await live.session
|
|
5627
6385
|
.abort()
|
|
6386
|
+
.then(() => {
|
|
6387
|
+
logger.warn(
|
|
6388
|
+
`[channels] ${live.keyId} abort site=graceful_restart session=${live.sessionId} reason=graceful_restart`,
|
|
6389
|
+
)
|
|
6390
|
+
})
|
|
5628
6391
|
.catch((err) => logger.error(`[channels] graceful-restart abort failed: ${describeError(err)}`))
|
|
5629
6392
|
}
|
|
5630
6393
|
}
|
|
@@ -5800,7 +6563,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
5800
6563
|
// either way. Still skip the generic synthetic wake.
|
|
5801
6564
|
if (reservation.sawInbound) {
|
|
5802
6565
|
if (handoff.interruptedSubagents !== undefined && handoff.interruptedSubagents.length > 0) {
|
|
5803
|
-
live.pendingSystemReminders.push(
|
|
6566
|
+
live.pendingSystemReminders.push(
|
|
6567
|
+
wakeupReminder(buildInterruptedSubagentNotice(handoff.interruptedSubagents)),
|
|
6568
|
+
)
|
|
5804
6569
|
logger.info(
|
|
5805
6570
|
`[channels] ${keyId}: restart-resume coalesced with a real inbound; delivering interrupted-subagent notice`,
|
|
5806
6571
|
)
|
|
@@ -5821,7 +6586,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
5821
6586
|
logger.error(`[channels] ${keyId}: restart-resume clear abort suppression failed: ${describeError(err)}`),
|
|
5822
6587
|
)
|
|
5823
6588
|
|
|
5824
|
-
live.pendingSystemReminders.push(buildRestartResumeWakeReminder(handoff.interruptedSubagents))
|
|
6589
|
+
live.pendingSystemReminders.push(wakeupReminder(buildRestartResumeWakeReminder(handoff.interruptedSubagents)))
|
|
5825
6590
|
logger.info(`[channels] ${keyId}: restart-resume waking session ${live.sessionId}`)
|
|
5826
6591
|
void drain(live)
|
|
5827
6592
|
},
|
|
@@ -5867,6 +6632,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
5867
6632
|
workspace: key.workspace,
|
|
5868
6633
|
chat: key.chat,
|
|
5869
6634
|
thread: key.thread,
|
|
6635
|
+
...(options.parentChat !== undefined ? { parentChat: options.parentChat } : {}),
|
|
5870
6636
|
lastInboundAuthorId: options.invokerId,
|
|
5871
6637
|
}
|
|
5872
6638
|
if (!permissions.has(partial, requiredPermission)) {
|
|
@@ -5882,9 +6648,17 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
5882
6648
|
if (resolved.kind === 'ambiguous') {
|
|
5883
6649
|
return { kind: 'ambiguous', matchCount: resolved.count }
|
|
5884
6650
|
}
|
|
5885
|
-
//
|
|
5886
|
-
//
|
|
5887
|
-
|
|
6651
|
+
// Slack broadcasts slash commands to every installed app, so an idle
|
|
6652
|
+
// fallback/observe-only session must stay silent instead of claiming it
|
|
6653
|
+
// stopped work. Discord interactions are delivered only to the selected
|
|
6654
|
+
// application, and its exact channel key is authoritative even between
|
|
6655
|
+
// prompts. In the 2026-08-28 incident, one exact Discord session consumed
|
|
6656
|
+
// 14 messages into a no-assistant-output branch; each prompt ended in
|
|
6657
|
+
// ~53ms, so /stop landed while `draining`, queues, and reminders were all
|
|
6658
|
+
// empty and incorrectly reported no-live-session. Always pass that exact
|
|
6659
|
+
// session to stopCurrentChannelTurn so the user's escape hatch remains.
|
|
6660
|
+
const exactDiscordSession = key.adapter === 'discord-bot' && resolved.session.keyId === channelKeyId(key)
|
|
6661
|
+
if (lowered === 'stop' && !exactDiscordSession && !hasStoppableWork(resolved.session)) {
|
|
5888
6662
|
return { kind: 'no-live-session' }
|
|
5889
6663
|
}
|
|
5890
6664
|
live = resolved.session
|
|
@@ -5929,7 +6703,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
5929
6703
|
channel: true,
|
|
5930
6704
|
adapter,
|
|
5931
6705
|
})
|
|
5932
|
-
live.pendingSystemReminders.push(text)
|
|
6706
|
+
live.pendingSystemReminders.push(wakeupReminder(text))
|
|
5933
6707
|
// The reminder tells the agent to fetch this result now; clear the
|
|
5934
6708
|
// subagent_output window so an earlier premature-polling streak can't
|
|
5935
6709
|
// hard-block that legitimate fetch.
|
|
@@ -5983,7 +6757,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
5983
6757
|
const injectPrVerdictActivity = (args: {
|
|
5984
6758
|
workspace: string
|
|
5985
6759
|
prNumber: number
|
|
5986
|
-
verdict:
|
|
6760
|
+
verdict: ReviewRoundOutcome
|
|
5987
6761
|
sessionId: string
|
|
5988
6762
|
}): { kind: 'delivered'; count: number } => {
|
|
5989
6763
|
const chat = `pr:${args.prNumber}`
|
|
@@ -5996,7 +6770,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
5996
6770
|
// stand down from its own legitimate review.
|
|
5997
6771
|
if (live.sessionId === args.sessionId) continue
|
|
5998
6772
|
const text = renderPrVerdictStandDownReminder({ prNumber: args.prNumber, verdict: args.verdict })
|
|
5999
|
-
live.pendingSystemReminders.push(text)
|
|
6773
|
+
live.pendingSystemReminders.push(wakeupReminder(text))
|
|
6000
6774
|
logger.info(`[channels] ${live.keyId}: pr-verdict stand-down queued pr=${chat} verdict=${args.verdict}`)
|
|
6001
6775
|
if (!live.draining) void drain(live)
|
|
6002
6776
|
count++
|
|
@@ -6004,6 +6778,162 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
6004
6778
|
return { kind: 'delivered', count }
|
|
6005
6779
|
}
|
|
6006
6780
|
|
|
6781
|
+
const completeRoundForVerifiedVerdict = async (args: {
|
|
6782
|
+
workspace: string
|
|
6783
|
+
prNumber: number
|
|
6784
|
+
verdict: ReviewRoundOutcome
|
|
6785
|
+
sessionId: string
|
|
6786
|
+
}): Promise<{ kind: 'completed' | 'no-round' }> => {
|
|
6787
|
+
const chat = `pr:${args.prNumber}`
|
|
6788
|
+
const publisher = Array.from(liveSessions.values()).find(
|
|
6789
|
+
(live) =>
|
|
6790
|
+
!live.destroyed &&
|
|
6791
|
+
live.sessionId === args.sessionId &&
|
|
6792
|
+
live.key.adapter === 'github' &&
|
|
6793
|
+
live.key.workspace === args.workspace &&
|
|
6794
|
+
live.key.chat === chat &&
|
|
6795
|
+
live.githubReviewRound !== null,
|
|
6796
|
+
)
|
|
6797
|
+
const persistedPublisher = mappings?.find(
|
|
6798
|
+
(record) =>
|
|
6799
|
+
record.sessionId === args.sessionId &&
|
|
6800
|
+
record.adapter === 'github' &&
|
|
6801
|
+
record.workspace === args.workspace &&
|
|
6802
|
+
record.chat === chat &&
|
|
6803
|
+
record.githubReviewRound !== undefined,
|
|
6804
|
+
)
|
|
6805
|
+
const round = publisher?.githubReviewRound ?? persistedPublisher?.githubReviewRound
|
|
6806
|
+
if (round === null || round === undefined) {
|
|
6807
|
+
const resetRound = resetGithubReviewRoundCompletionForPr(args.workspace, args.prNumber)
|
|
6808
|
+
if (resetRound !== null) persistMatchingGithubReviewRound(resetRound)
|
|
6809
|
+
logger.warn(
|
|
6810
|
+
`[channels] github review round completion rejected pr=${args.workspace}#${args.prNumber} verdict=${args.verdict}: no publisher session with round state session=${args.sessionId}`,
|
|
6811
|
+
)
|
|
6812
|
+
return { kind: 'no-round' }
|
|
6813
|
+
}
|
|
6814
|
+
|
|
6815
|
+
const activeRound = registerGithubReviewRound(round)
|
|
6816
|
+
if (activeRound === null) {
|
|
6817
|
+
logger.warn(
|
|
6818
|
+
`[channels] github review round completion rejected pr=${args.workspace}#${args.prNumber} verdict=${args.verdict}: round expired`,
|
|
6819
|
+
)
|
|
6820
|
+
return { kind: 'no-round' }
|
|
6821
|
+
}
|
|
6822
|
+
const publisherThread = publisher?.key.thread ?? persistedPublisher?.thread ?? null
|
|
6823
|
+
if (activeRound.carrierThread !== publisherThread) {
|
|
6824
|
+
resetGithubReviewRoundCompletion(activeRound)
|
|
6825
|
+
persistMatchingGithubReviewRound(activeRound)
|
|
6826
|
+
logger.warn(
|
|
6827
|
+
`[channels] github review round completion rejected pr=${args.workspace}#${args.prNumber} verdict=${args.verdict}: publisher thread=${publisherThread ?? 'root'} is not carrier=${activeRound.carrierThread ?? 'root'}`,
|
|
6828
|
+
)
|
|
6829
|
+
return { kind: 'no-round' }
|
|
6830
|
+
}
|
|
6831
|
+
if (!(await validateGithubReviewRound(activeRound))) {
|
|
6832
|
+
resetGithubReviewRoundCompletion(activeRound)
|
|
6833
|
+
persistMatchingGithubReviewRound(activeRound)
|
|
6834
|
+
logger.warn(
|
|
6835
|
+
`[channels] github review round completion rejected pr=${args.workspace}#${args.prNumber} verdict=${args.verdict}: head mismatch or unavailable expected=${activeRound.headSha}`,
|
|
6836
|
+
)
|
|
6837
|
+
return { kind: 'no-round' }
|
|
6838
|
+
}
|
|
6839
|
+
completeGithubReviewRound(activeRound)
|
|
6840
|
+
const key = githubReviewRoundKey(round)
|
|
6841
|
+
for (const live of liveSessions.values()) {
|
|
6842
|
+
if (live.githubReviewRound === null || githubReviewRoundKey(live.githubReviewRound) !== key) continue
|
|
6843
|
+
live.pendingSystemReminders = live.pendingSystemReminders.filter(
|
|
6844
|
+
(reminder) => reminder.githubReviewRoundKey !== key,
|
|
6845
|
+
)
|
|
6846
|
+
live.githubReviewRound = activeRound
|
|
6847
|
+
}
|
|
6848
|
+
persistMatchingGithubReviewRound(activeRound)
|
|
6849
|
+
replayPendingRoundCloseouts(activeRound)
|
|
6850
|
+
logger.info(`[channels] github review round completed pr=${chat} verdict=${args.verdict}`)
|
|
6851
|
+
return { kind: 'completed' }
|
|
6852
|
+
}
|
|
6853
|
+
|
|
6854
|
+
// Round state must reach every session carrying the round, not only the ones
|
|
6855
|
+
// currently live. An idle-GC'd or not-yet-reopened sibling keeps its persisted
|
|
6856
|
+
// `pending` record, and reopening it restores that stale status over the
|
|
6857
|
+
// completed one, re-arming failover and permitting a second blocking review.
|
|
6858
|
+
const persistMatchingGithubReviewRound = (round: GithubReviewFollowupRound): void => {
|
|
6859
|
+
if (mappings === null) return
|
|
6860
|
+
const key = githubReviewRoundKey(round)
|
|
6861
|
+
const state = githubReviewRoundPersistence(round)
|
|
6862
|
+
let changed = false
|
|
6863
|
+
for (const [idx, record] of mappings.entries()) {
|
|
6864
|
+
if (record.githubReviewRound === undefined) continue
|
|
6865
|
+
if (githubReviewRoundKey(record.githubReviewRound) !== key) continue
|
|
6866
|
+
if (state === null) {
|
|
6867
|
+
const { githubReviewRound: _expired, ...rest } = record
|
|
6868
|
+
void _expired
|
|
6869
|
+
mappings[idx] = rest
|
|
6870
|
+
} else {
|
|
6871
|
+
mappings[idx] = { ...record, githubReviewRound: { ...round, ...state } }
|
|
6872
|
+
}
|
|
6873
|
+
changed = true
|
|
6874
|
+
}
|
|
6875
|
+
if (changed) void persist()
|
|
6876
|
+
}
|
|
6877
|
+
|
|
6878
|
+
// A close-out can land while completion is still awaiting head validation, so
|
|
6879
|
+
// `finishGithubReviewRoundCloseout` sees a pending round and returns without
|
|
6880
|
+
// clearing. Nothing else retries it, which would strand round metadata on the
|
|
6881
|
+
// session and reject its later verdicts — so the close-out is recorded and
|
|
6882
|
+
// replayed here once the round actually completes.
|
|
6883
|
+
const replayPendingRoundCloseouts = (round: GithubReviewFollowupRound): void => {
|
|
6884
|
+
const key = githubReviewRoundKey(round)
|
|
6885
|
+
for (const live of liveSessions.values()) {
|
|
6886
|
+
if (live.pendingGithubReviewRoundCloseout !== key) continue
|
|
6887
|
+
live.pendingGithubReviewRoundCloseout = null
|
|
6888
|
+
finishGithubReviewRoundCloseout({
|
|
6889
|
+
sessionId: live.sessionId,
|
|
6890
|
+
workspace: live.key.workspace,
|
|
6891
|
+
prNumber: Number(live.key.chat.slice('pr:'.length)),
|
|
6892
|
+
thread: live.key.thread ?? null,
|
|
6893
|
+
})
|
|
6894
|
+
}
|
|
6895
|
+
}
|
|
6896
|
+
|
|
6897
|
+
const finishGithubReviewRoundCloseout = (args: {
|
|
6898
|
+
sessionId: string
|
|
6899
|
+
workspace: string
|
|
6900
|
+
prNumber: number
|
|
6901
|
+
thread: string | null
|
|
6902
|
+
}): void => {
|
|
6903
|
+
const chat = `pr:${args.prNumber}`
|
|
6904
|
+
const live = Array.from(liveSessions.values()).find(
|
|
6905
|
+
(candidate) =>
|
|
6906
|
+
!candidate.destroyed &&
|
|
6907
|
+
candidate.sessionId === args.sessionId &&
|
|
6908
|
+
candidate.key.adapter === 'github' &&
|
|
6909
|
+
candidate.key.workspace === args.workspace &&
|
|
6910
|
+
candidate.key.chat === chat &&
|
|
6911
|
+
candidate.key.thread === args.thread,
|
|
6912
|
+
)
|
|
6913
|
+
if (live?.githubReviewRound === null || live?.githubReviewRound === undefined) return
|
|
6914
|
+
const round = live.githubReviewRound
|
|
6915
|
+
if (!isGithubReviewRoundComplete(round)) {
|
|
6916
|
+
live.pendingGithubReviewRoundCloseout = githubReviewRoundKey(round)
|
|
6917
|
+
return
|
|
6918
|
+
}
|
|
6919
|
+
live.pendingGithubReviewRoundCloseout = null
|
|
6920
|
+
live.githubReviewRound = null
|
|
6921
|
+
persistGithubReviewRound(live, null)
|
|
6922
|
+
const stillReferenced =
|
|
6923
|
+
Array.from(liveSessions.values()).some(
|
|
6924
|
+
(candidate) =>
|
|
6925
|
+
candidate.githubReviewRound !== null &&
|
|
6926
|
+
githubReviewRoundKey(candidate.githubReviewRound) === githubReviewRoundKey(round),
|
|
6927
|
+
) ||
|
|
6928
|
+
(mappings?.some(
|
|
6929
|
+
(record) =>
|
|
6930
|
+
record.githubReviewRound !== undefined &&
|
|
6931
|
+
githubReviewRoundKey(record.githubReviewRound) === githubReviewRoundKey(round),
|
|
6932
|
+
) ??
|
|
6933
|
+
false)
|
|
6934
|
+
if (!stillReferenced) forgetGithubReviewRound(round)
|
|
6935
|
+
}
|
|
6936
|
+
|
|
6007
6937
|
// Stamp the review-output flag on the session that just landed a formal GitHub
|
|
6008
6938
|
// review this turn. Matched by sessionId (the recorder records the exact
|
|
6009
6939
|
// event.sessionId), and confirmed to be the right github PR live session so a
|
|
@@ -6096,11 +7026,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
6096
7026
|
}
|
|
6097
7027
|
|
|
6098
7028
|
const armSilentTurnAck = (live: LiveSession, reason: SilentAckReason): void => {
|
|
6099
|
-
// A GitHub review
|
|
6100
|
-
//
|
|
6101
|
-
//
|
|
6102
|
-
// no mark, so a busy room never accumulates stale 👀 on messages the bot
|
|
6103
|
-
// was never part of.
|
|
7029
|
+
// A GitHub review is user-facing output, so it always earns the 👀; deferred
|
|
7030
|
+
// background work earns one only when the triggering message addressed the
|
|
7031
|
+
// bot. Ambient chatter stays unmarked.
|
|
6104
7032
|
const eligible =
|
|
6105
7033
|
reason === 'github_review_output' ? live.key.adapter === 'github' : live.currentTurnExplicitlyAddressed
|
|
6106
7034
|
if (!eligible) return
|
|
@@ -6140,8 +7068,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
6140
7068
|
}
|
|
6141
7069
|
|
|
6142
7070
|
// Retire every persistent silent-ack :eyes: outstanding in this live session
|
|
6143
|
-
// once the agent posts a genuine reply
|
|
6144
|
-
//
|
|
7071
|
+
// once the agent posts a genuine reply. Snapshot-and-clear the promise array
|
|
7072
|
+
// BEFORE awaiting, so a
|
|
6145
7073
|
// concurrent later silent turn appending a fresh add is never swept by this
|
|
6146
7074
|
// in-flight cleanup. Each entry is AWAITED to its resolved ref before removal,
|
|
6147
7075
|
// so an add still in flight when the reply lands is still retired. Failures are
|
|
@@ -6296,6 +7224,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
6296
7224
|
getSelfAliases: computeSelfAliases,
|
|
6297
7225
|
injectSubagentCompletionReminder,
|
|
6298
7226
|
injectPrVerdictActivity,
|
|
7227
|
+
completeGithubReviewRound: completeRoundForVerifiedVerdict,
|
|
7228
|
+
finishGithubReviewRoundCloseout,
|
|
6299
7229
|
noteGithubReviewOutput,
|
|
6300
7230
|
markTurnSkipped,
|
|
6301
7231
|
clearSticky,
|
|
@@ -6307,15 +7237,39 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
6307
7237
|
writeInterruptedSubagentHandoff,
|
|
6308
7238
|
liveCount: () => liveSessions.size,
|
|
6309
7239
|
__testing: {
|
|
7240
|
+
githubReviewRoundFor: (key: ChannelKey) => liveSessions.get(channelKeyId(key))?.githubReviewRound,
|
|
7241
|
+
pendingReminderCount: (key: ChannelKey) => liveSessions.get(channelKeyId(key))?.pendingSystemReminders.length,
|
|
7242
|
+
creationTokenCount: () => latestCreationTokens.size,
|
|
6310
7243
|
flushDebounce: async (key: ChannelKey) => {
|
|
6311
|
-
const
|
|
7244
|
+
const keyId = channelKeyId(key)
|
|
7245
|
+
let live = liveSessions.get(keyId)
|
|
6312
7246
|
if (!live) return
|
|
6313
7247
|
if (live.debounceTimer) {
|
|
6314
7248
|
clearTimeout(live.debounceTimer)
|
|
6315
7249
|
live.debounceTimer = null
|
|
6316
7250
|
}
|
|
6317
7251
|
live.firstUnprocessedAt = 0
|
|
6318
|
-
|
|
7252
|
+
// Settle a drain that is ALREADY in flight before starting our own, then
|
|
7253
|
+
// again after. `drain()` no-ops while one owns the session, so a
|
|
7254
|
+
// fire-and-forget `void drain(live)` raised elsewhere — the restart-resume
|
|
7255
|
+
// lost-work notice, a promoted review carrier, a subagent-completion wake —
|
|
7256
|
+
// would still be mid-turn when this returned, and the caller would assert
|
|
7257
|
+
// on a prompt that has not landed. Same defect shape as the `persist()`
|
|
7258
|
+
// race below: this seam has to mean "settled", not "started".
|
|
7259
|
+
//
|
|
7260
|
+
// Re-resolved by key each round because settling is not a property of one
|
|
7261
|
+
// object: a deferred reload teardown drops this session mid-drain and
|
|
7262
|
+
// `handOffToSuccessor` replays the carried work onto a REPLACEMENT live
|
|
7263
|
+
// session with its own `activeDrains`. Watching only the session captured
|
|
7264
|
+
// at entry would return with the successor's prompt still in flight.
|
|
7265
|
+
for (;;) {
|
|
7266
|
+
await settleDrains(live)
|
|
7267
|
+
await drain(live)
|
|
7268
|
+
await settleDrains(live)
|
|
7269
|
+
const current = liveSessions.get(keyId)
|
|
7270
|
+
if (current === undefined || current === live) break
|
|
7271
|
+
live = current
|
|
7272
|
+
}
|
|
6319
7273
|
// Settle the fire-and-forget `void persist()` from scheduleDebouncedDrain
|
|
6320
7274
|
// (the lastInboundAt write). Draining alone doesn't await that promise, so
|
|
6321
7275
|
// a test reading sessions.json right after would race the disk write — the
|
|
@@ -6380,7 +7334,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
6380
7334
|
injectContinuationReminder: (key: ChannelKey, text: string): void => {
|
|
6381
7335
|
const live = liveSessions.get(channelKeyId(key))
|
|
6382
7336
|
if (!live) return
|
|
6383
|
-
live.pendingSystemReminders.push(text)
|
|
7337
|
+
live.pendingSystemReminders.push(retryReminder(text))
|
|
6384
7338
|
},
|
|
6385
7339
|
enqueueUserInbound: (key: ChannelKey, event: InboundMessage): void => {
|
|
6386
7340
|
const live = liveSessions.get(channelKeyId(key))
|
|
@@ -7164,27 +8118,19 @@ async function raceWithTimeout<T>(work: Promise<T>, ms: number, label: string):
|
|
|
7164
8118
|
// Observed against claude on a channel turn that fell silent (2026-06-12).
|
|
7165
8119
|
//
|
|
7166
8120
|
// - source: 'mid-turn'
|
|
7167
|
-
// The leaf IS an assistant message with `stopReason === 'toolUse'
|
|
7168
|
-
//
|
|
7169
|
-
//
|
|
7170
|
-
//
|
|
7171
|
-
//
|
|
7172
|
-
// loop's post-tool follow-up never landed, or the run was aborted
|
|
7173
|
-
// mid-loop. The model treated its visible prose as ambient narration; in
|
|
7174
|
-
// a channel session that prose is dead text. Recovers it so the user gets
|
|
7175
|
-
// the reply the model thought it had already given. Observed against
|
|
7176
|
-
// Fireworks' `kimi-k2p6-turbo` on KakaoTalk: the agent posted speed-change
|
|
7177
|
-
// status as narration, kept taking screenshots, and the user saw nothing.
|
|
7178
|
-
// This is the leaf-is-assistant twin of the 'pre-tool' shape below.
|
|
8121
|
+
// The leaf IS an assistant message with `stopReason === 'toolUse'`. Its
|
|
8122
|
+
// visible text, if any, is unfinished narration rather than a trustworthy
|
|
8123
|
+
// answer because the planned tool work never reached a follow-up assistant
|
|
8124
|
+
// message. The caller uses this source to enter bounded continuation rather
|
|
8125
|
+
// than publishing the narration.
|
|
7179
8126
|
//
|
|
7180
8127
|
// - source: 'pre-tool'
|
|
7181
8128
|
// The leaf is a `toolResult` and the immediately-prior assistant message
|
|
7182
8129
|
// has `stopReason === 'toolUse'` (it called the tool that produced this
|
|
7183
8130
|
// toolResult). The upstream pi-agent-core loop SHOULD have made a
|
|
7184
8131
|
// follow-up LLM call after the tool returned, but that call either never
|
|
7185
|
-
// happened or produced no persisted message.
|
|
7186
|
-
//
|
|
7187
|
-
// Fireworks' `accounts/fireworks/routers/kimi-k2p6-turbo` on 2026-05-26.
|
|
8132
|
+
// happened or produced no persisted message. The caller treats the
|
|
8133
|
+
// assistant's commentary as unfinished and enters bounded continuation.
|
|
7188
8134
|
//
|
|
7189
8135
|
// Returns null when no recovery is appropriate:
|
|
7190
8136
|
// - No leaf, no messages in branch, branch is malformed
|
|
@@ -7207,9 +8153,8 @@ function recoverableAssistantText(
|
|
|
7207
8153
|
if (leaf.message.stopReason === 'stop') {
|
|
7208
8154
|
return { text: visibleAssistantText(leaf.message), source: 'leaf' }
|
|
7209
8155
|
}
|
|
7210
|
-
//
|
|
7211
|
-
//
|
|
7212
|
-
// tool was persisted. Recover the stranded prose.
|
|
8156
|
+
// Preserve the unfinished shape for the caller's continuation ladder; its
|
|
8157
|
+
// prose is not a final answer and must not be published directly.
|
|
7213
8158
|
if (leaf.message.stopReason === 'toolUse') {
|
|
7214
8159
|
return { text: visibleAssistantText(leaf.message), source: 'mid-turn' }
|
|
7215
8160
|
}
|
|
@@ -7240,7 +8185,9 @@ function recoverableAssistantText(
|
|
|
7240
8185
|
if (!parent) return null
|
|
7241
8186
|
if (parent.type === 'message') {
|
|
7242
8187
|
if (parent.message.role === 'assistant') {
|
|
7243
|
-
return
|
|
8188
|
+
return parent.message.stopReason === 'toolUse'
|
|
8189
|
+
? { text: visibleAssistantText(parent.message), source: 'pre-tool' }
|
|
8190
|
+
: null
|
|
7244
8191
|
}
|
|
7245
8192
|
if (parent.message.role === 'user') return null
|
|
7246
8193
|
}
|
|
@@ -7299,6 +8246,57 @@ function leafIsStrandedToolUse(session: AgentSession): boolean {
|
|
|
7299
8246
|
return false
|
|
7300
8247
|
}
|
|
7301
8248
|
|
|
8249
|
+
// Permanently close a trailing tool batch whose assistant toolUse has one or
|
|
8250
|
+
// more missing results. PR #1386 could recognize this shape and re-prompt, but
|
|
8251
|
+
// the 2026-08-28 Discord fingerprint showed the poisoned branch rejecting each
|
|
8252
|
+
// retry in ~53ms before provider generation: 15 user entries accumulated with
|
|
8253
|
+
// no assistant entry until idle rollover. Append-only error results preserve
|
|
8254
|
+
// the full conversation and any completed sibling results while making both
|
|
8255
|
+
// the live Agent state and persisted SessionManager branch valid again.
|
|
8256
|
+
function repairDanglingToolUseBranch(session: AgentSession, timestamp: number): string[] {
|
|
8257
|
+
const branch = session.sessionManager.getBranch?.()
|
|
8258
|
+
if (!branch) return []
|
|
8259
|
+
const messages = branch.filter(
|
|
8260
|
+
(entry): entry is Extract<SessionEntry, { type: 'message' }> => entry.type === 'message',
|
|
8261
|
+
)
|
|
8262
|
+
if (messages.length === 0) return []
|
|
8263
|
+
|
|
8264
|
+
const completed = new Set<string>()
|
|
8265
|
+
let index = messages.length - 1
|
|
8266
|
+
while (index >= 0) {
|
|
8267
|
+
const message = messages[index]!.message
|
|
8268
|
+
if (message.role !== 'toolResult') break
|
|
8269
|
+
completed.add(message.toolCallId)
|
|
8270
|
+
index--
|
|
8271
|
+
}
|
|
8272
|
+
|
|
8273
|
+
const assistantEntry = messages[index]
|
|
8274
|
+
if (!assistantEntry || assistantEntry.message.role !== 'assistant') return []
|
|
8275
|
+
if (assistantEntry.message.stopReason !== 'toolUse') return []
|
|
8276
|
+
const missing = assistantEntry.message.content.filter(
|
|
8277
|
+
(block): block is Extract<(typeof assistantEntry.message.content)[number], { type: 'toolCall' }> =>
|
|
8278
|
+
block.type === 'toolCall' && !completed.has(block.id),
|
|
8279
|
+
)
|
|
8280
|
+
if (missing.length === 0) return []
|
|
8281
|
+
|
|
8282
|
+
const repairedMessages: ToolResultMessage[] = missing.map((toolCall) => ({
|
|
8283
|
+
role: 'toolResult',
|
|
8284
|
+
toolCallId: toolCall.id,
|
|
8285
|
+
toolName: toolCall.name,
|
|
8286
|
+
content: [
|
|
8287
|
+
{
|
|
8288
|
+
type: 'text',
|
|
8289
|
+
text: 'Tool execution was interrupted before its result was recorded. Continue from the preserved conversation without assuming the tool succeeded.',
|
|
8290
|
+
},
|
|
8291
|
+
],
|
|
8292
|
+
isError: true,
|
|
8293
|
+
timestamp,
|
|
8294
|
+
}))
|
|
8295
|
+
for (const message of repairedMessages) session.sessionManager.appendMessage(message)
|
|
8296
|
+
session.agent.state.messages = [...session.agent.state.messages, ...repairedMessages]
|
|
8297
|
+
return missing.map((toolCall) => toolCall.name)
|
|
8298
|
+
}
|
|
8299
|
+
|
|
7302
8300
|
// The turn-end leaf is a FRESH empty `stop` — an assistant message with no visible
|
|
7303
8301
|
// text and no tool call, distinct from the leaf in place at the last successful
|
|
7304
8302
|
// send. "Fresh" (`!== lastSendLeafId`) is what separates a post-send degeneration
|