Skip to content

Commit fae44d9

Browse files
committed
fix(auto-reply): decide no-visible-reply fallback from settled delivery
Replace the nine scattered admission-based visibility signals in finalizeDispatchAndAudit with a per-dispatch turn ledger that records transport settlement: dispatcher sends settle through captured delivery outcomes, routed sends settle at the routeReplyToOriginating choke point, and the fallback gate awaits settlement of admitted payloads before declaring a turn silent. Fixes the three #114531 corners: suppressed routed finals counting as visible, failed/cancelled streamed blocks suppressing the fallback, and beforeDeliver hooks cancelling the fallback after its delivered flag was set. Closes #114768
1 parent 455e728 commit fae44d9

11 files changed

Lines changed: 487 additions & 76 deletions

‎src/auto-reply/reply/dispatch-from-config.choose-route.ts‎

Lines changed: 13 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,7 @@ import {
2727
mirrorTranscriptAfterDispatcherSettled,
2828
transcriptMirrorForDeliveredPayload,
2929
} from "./dispatch-from-config.transcript.js";
30-
import {
31-
captureReplyDispatchDeliveryOutcome,
32-
type ReplyDispatchDeliveryOutcome,
33-
} from "./reply-dispatcher.js";
30+
import type { ReplyDispatchDeliveryOutcome } from "./reply-dispatcher.js";
3431

3532
export async function chooseDispatchRoute(state: PrepareDispatchOperationReadyState) {
3633
const {
@@ -84,6 +81,7 @@ export async function chooseDispatchRoute(state: PrepareDispatchOperationReadySt
8481
suppressHookUserDelivery,
8582
traceReplyPhase,
8683
trackDispatchLifecycleWork,
84+
turnLedger,
8785
} = state;
8886
const shouldSuppressProgressDelivery = () =>
8987
sendPolicyDenied ||
@@ -179,7 +177,7 @@ export async function chooseDispatchRoute(state: PrepareDispatchOperationReadySt
179177
await sendPayloadAsync(payload, undefined, false);
180178
} else {
181179
markInboundDedupeReplayUnsafe();
182-
dispatcher.sendToolResult(payload);
180+
turnLedger.sendQueued("tool", payload);
183181
}
184182
};
185183
const flushPendingCommentaryProgress = async () => {
@@ -229,18 +227,17 @@ export async function chooseDispatchRoute(state: PrepareDispatchOperationReadySt
229227
>();
230228
const sendTrackedBlockReply = (payload: ReplyPayload): boolean => {
231229
const contentKey = createBlockReplyContentKey(payload);
232-
const delivery = captureReplyDispatchDeliveryOutcome(payload);
233-
const queued = dispatcher.sendBlockReply(payload);
234-
if (!queued || !delivery.isTracked()) {
235-
return queued;
230+
const delivery = turnLedger.sendQueued("block", payload);
231+
if (!delivery.queued || !delivery.outcome) {
232+
return delivery.queued;
236233
}
237234
const outcomes = pendingBlockDeliveryOutcomes.get(contentKey);
238235
if (outcomes) {
239-
outcomes.push(delivery.promise);
236+
outcomes.push(delivery.outcome);
240237
} else {
241-
pendingBlockDeliveryOutcomes.set(contentKey, [delivery.promise]);
238+
pendingBlockDeliveryOutcomes.set(contentKey, [delivery.outcome]);
242239
}
243-
return queued;
240+
return delivery.queued;
244241
};
245242
const recordRoutedBlockReplyDelivery = (
246243
payload: ReplyPayload,
@@ -250,9 +247,6 @@ export async function chooseDispatchRoute(state: PrepareDispatchOperationReadySt
250247
deliveredBlockContentKeys.add(createBlockReplyContentKey(payload));
251248
}
252249
};
253-
// Routed blocks bypass dispatcher queue counts entirely; this is the only
254-
// settled-delivery fact for them (media-only blocks never touch blockCount).
255-
const hasDeliveredRoutedBlockReply = (): boolean => deliveredBlockContentKeys.size > 0;
256250
const wasReplyDeliveredAsBlock = async (
257251
payload: ReplyPayload,
258252
abortSignal?: AbortSignal,
@@ -435,10 +429,10 @@ export async function chooseDispatchRoute(state: PrepareDispatchOperationReadySt
435429
if (finalDeliveryCapture) {
436430
setReplyPayloadMetadata(normalizedPayload, { finalDeliveryCapture });
437431
}
438-
const deliveryOutcome = captureReplyDispatchDeliveryOutcome(normalizedPayload);
439-
const queuedFinal = dispatcher.sendFinalReply(normalizedPayload);
440-
const dispatcherOutcome =
441-
queuedFinal && deliveryOutcome.isTracked() ? deliveryOutcome.promise : undefined;
432+
const { queued: queuedFinal, outcome: dispatcherOutcome } = turnLedger.sendQueued(
433+
"final",
434+
normalizedPayload,
435+
);
442436
if (queuedFinal && deliveredTranscriptMirror && finalOutcomeBefore) {
443437
// The common settle owner runs this after successful delivery or
444438
// cancellation. Keeping reconciliation out of the reply operation lets a
@@ -613,7 +607,6 @@ export async function chooseDispatchRoute(state: PrepareDispatchOperationReadySt
613607
sendTrackedBlockReply,
614608
recordRoutedBlockReplyDelivery,
615609
wasReplyDeliveredAsBlock,
616-
hasDeliveredRoutedBlockReply,
617610
sendFinalPayload,
618611
},
619612
{

‎src/auto-reply/reply/dispatch-from-config.execute.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,7 @@ export async function executeDispatch(state: PrepareDispatchExecutionReadyState)
110110
suppressToolErrorWarnings,
111111
traceReplyPhase,
112112
trackDispatchLifecycleWork,
113+
turnLedger,
113114
typing,
114115
waitForPendingDirectBlockReplyDelivery,
115116
wrapProgressCallback,
@@ -312,7 +313,7 @@ export async function executeDispatch(state: PrepareDispatchExecutionReadyState)
312313
await sendPayloadAsync(deliveryPayload, undefined, false);
313314
} else {
314315
markInboundDedupeReplayUnsafe();
315-
const delivered = dispatcher.sendToolResult(deliveryPayload);
316+
const delivered = turnLedger.sendQueued("tool", deliveryPayload).queued;
316317
if (delivered && hasAskUserPayload(deliveryPayload)) {
317318
// ask_user blocks until this callback resolves; drain its prompt now
318319
// or the answerable UI can remain queued behind the blocked agent run.

‎src/auto-reply/reply/dispatch-from-config.finalize.ts‎

Lines changed: 35 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,6 @@ export async function finalizeDispatchAndAudit(state: ExecuteDispatchReadyState)
4040
flushPendingCommentaryProgress,
4141
getDispatchAbortSignal,
4242
getObservedReplyDelivery,
43-
hasDeliveredRoutedBlockReply,
4443
isRoutedReplyDelivered,
4544
markIdle,
4645
markInboundDedupeReplayUnsafe,
@@ -63,6 +62,7 @@ export async function finalizeDispatchAndAudit(state: ExecuteDispatchReadyState)
6362
suppressAutomaticSourceDelivery,
6463
suppressDelivery,
6564
throwIfDispatchOperationAborted,
65+
turnLedger,
6666
waitForPendingDirectBlockReplyDelivery,
6767
} = state;
6868
const replies = replyResult ? (Array.isArray(replyResult) ? replyResult : [replyResult]) : [];
@@ -112,8 +112,6 @@ export async function finalizeDispatchAndAudit(state: ExecuteDispatchReadyState)
112112
getReplyPayloadMetadata(reply)?.deliverDespiteSourceReplySuppression === true &&
113113
(ctx.InboundEventKind !== "room_event" || explicitCommandTurnCtx);
114114
const sentFinalPayloadDedupeKeys = new Set<string>();
115-
let sawDedupedAgainstBlock = false;
116-
let sawVisibleFinalDelivery = false;
117115
for (const [replyIndex, reply] of replies.entries()) {
118116
throwIfDispatchOperationAborted();
119117
// Durable reasoning is a channel-owned lane; generic channels keep the
@@ -148,20 +146,12 @@ export async function finalizeDispatchAndAudit(state: ExecuteDispatchReadyState)
148146
sentFinalPayloadDedupeKeys.add(finalPayloadDedupeKey);
149147
const finalReply = await sendFinalPayload(reply, { deliveryId: String(replyIndex) });
150148
if (finalReply.dedupedAgainstBlock) {
151-
sawDedupedAgainstBlock = true;
149+
// The delivering block already settled into the turn ledger.
152150
continue;
153151
}
154152
attemptedFinalDelivery = true;
155153
queuedFinal = finalReply.queuedFinal || queuedFinal;
156154
routedFinalCount += finalReply.routedFinalCount;
157-
// Routed drops of empty payloads report ok without sending anything; only a
158-
// contentful final proves visibility for the no-visible-reply fallback gate.
159-
if (
160-
hasOutboundReplyContent(reply, { trimText: true }) &&
161-
(finalReply.queuedFinal || finalReply.routedFinalCount > 0)
162-
) {
163-
sawVisibleFinalDelivery = true;
164-
}
165155
if (finalReply.queuedFinal) {
166156
if (finalReply.dispatcherOutcome) {
167157
finalDeliveries.push({ outcome: finalReply.dispatcherOutcome, payload: reply });
@@ -263,7 +253,6 @@ export async function finalizeDispatchAndAudit(state: ExecuteDispatchReadyState)
263253
queuedFinal = result.ok || queuedFinal;
264254
if (isRoutedReplyDelivered(result)) {
265255
routedFinalCount += 1;
266-
sawVisibleFinalDelivery = true;
267256
}
268257
if (!result.ok) {
269258
logVerbose(
@@ -273,9 +262,8 @@ export async function finalizeDispatchAndAudit(state: ExecuteDispatchReadyState)
273262
} else {
274263
throwIfDispatchOperationAborted();
275264
markInboundDedupeReplayUnsafe();
276-
const didQueue = dispatcher.sendFinalReply(normalizedTtsOnlyPayload);
277-
queuedFinal = didQueue || queuedFinal;
278-
sawVisibleFinalDelivery = didQueue || sawVisibleFinalDelivery;
265+
queuedFinal =
266+
turnLedger.sendQueued("final", normalizedTtsOnlyPayload).queued || queuedFinal;
279267
}
280268
}
281269
} catch (err) {
@@ -290,26 +278,29 @@ export async function finalizeDispatchAndAudit(state: ExecuteDispatchReadyState)
290278
}
291279

292280
await waitForPendingDirectBlockReplyDelivery(getDispatchAbortSignal());
293-
let counts = dispatcher.getQueuedCounts();
294-
let noVisibleReplyFallbackDelivered = false;
295-
// Visible agent turns must never end silently: empty model completions get a
296-
// core fallback final. emptyFinalAllowedAsSilent is the only sanctioned silence.
297-
// Routed streamed blocks bypass dispatcher counts, so blockCount and the
298-
// deduped-against-block signal must also prove the turn was empty before falling back.
299-
if (
281+
// Observed delivery is plugin-attested visibility, a trust level the transport
282+
// ledger intentionally does not own.
283+
const noVisibleReplyFallbackAllowed = () =>
300284
!suppressDelivery &&
301285
!sendPolicyDenied &&
302286
sourceReplyDeliveryMode !== "message_tool_only" &&
303-
!sawVisibleFinalDelivery &&
304-
!getObservedReplyDelivery() &&
305287
!emptyFinalAllowedAsSilent &&
306-
!sawDedupedAgainstBlock &&
307-
!hasDeliveredRoutedBlockReply() &&
308-
state.blockCount === 0 &&
309-
counts.tool === 0 &&
310-
counts.block === 0 &&
311-
counts.final === 0
312-
) {
288+
!getObservedReplyDelivery() &&
289+
!turnLedger.hasVisibleDelivery() &&
290+
!turnLedger.hasForeignQueuedAdmissions();
291+
if (noVisibleReplyFallbackAllowed()) {
292+
// Only a turn that still looks empty pays for settlement: pending admissions
293+
// must resolve (beforeDeliver cancellation, transport failure) before the
294+
// silence verdict. Turns with settled visibility or a policy-suppressed
295+
// fallback skip the wait, so deliveries that legitimately outlive the turn
296+
// (queued same-session mirroring) cannot deadlock the gate on themselves.
297+
await turnLedger.settleQueued(getDispatchAbortSignal());
298+
}
299+
let counts = dispatcher.getQueuedCounts();
300+
let noVisibleReplyFallbackDelivered = false;
301+
// Visible agent turns must never end silently: empty model completions get a
302+
// core fallback final. emptyFinalAllowedAsSilent is the only sanctioned silence.
303+
if (noVisibleReplyFallbackAllowed()) {
313304
try {
314305
throwIfDispatchOperationAborted();
315306
const fallbackPayload: ReplyPayload = { text: NO_VISIBLE_REPLY_FALLBACK_TEXT };
@@ -332,14 +323,16 @@ export async function finalizeDispatchAndAudit(state: ExecuteDispatchReadyState)
332323
} else {
333324
throwIfDispatchOperationAborted();
334325
markInboundDedupeReplayUnsafe();
335-
// Queue admission, not settled delivery: a beforeDeliver hook can still
336-
// cancel this payload. Accepted tradeoff until a unified visible-delivery
337-
// signal exists; every sibling in this function shares the semantics.
338-
const didQueue = dispatcher.sendFinalReply(fallbackPayload);
339-
if (didQueue) {
326+
const fallbackSend = turnLedger.sendQueued("final", fallbackPayload);
327+
// Settlement decides the flag: a beforeDeliver hook can still cancel the
328+
// admitted fallback, and a cancelled fallback must keep the eligibility
329+
// flag alive for channel-level recovery. Dispatchers without settlement
330+
// tracking keep admission as their strongest fact.
331+
const fallbackOutcome = fallbackSend.outcome ? await fallbackSend.outcome : "delivered";
332+
if (fallbackSend.queued && fallbackOutcome === "delivered") {
340333
queuedFinal = true;
341334
noVisibleReplyFallbackDelivered = true;
342-
// Re-snapshot so the queued fallback is reflected in reported counts,
335+
// Re-snapshot so the delivered fallback is reflected in reported counts,
343336
// matching the TTS-only path which enqueues before the snapshot.
344337
counts = dispatcher.getQueuedCounts();
345338
}
@@ -371,11 +364,10 @@ export async function finalizeDispatchAndAudit(state: ExecuteDispatchReadyState)
371364
? { sessionMetadataChanges: state.sessionMetadataChangesForResult }
372365
: {}),
373366
...(getObservedReplyDelivery() ? { observedReplyDelivery: true } : {}),
374-
// Eligibility keys off visible delivery, not queue/route admission: an
375-
// empty routed final reports ok without sending, and must not mask a
376-
// failed fallback from channel-level recovery.
377-
...(!sawVisibleFinalDelivery &&
378-
!noVisibleReplyFallbackDelivered &&
367+
// Eligibility keys off settled visible delivery: a suppressed or cancelled
368+
// final (including the core fallback itself) leaves channel-level recovery
369+
// eligible, while any settled visible delivery clears it.
370+
...(!turnLedger.hasVisibleDelivery() &&
379371
!getObservedReplyDelivery() &&
380372
!emptyFinalAllowedAsSilent
381373
? { noVisibleReplyFallbackEligible: true }

‎src/auto-reply/reply/dispatch-from-config.gather.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -343,6 +343,7 @@ export async function gatherDispatchRequest(
343343
runWithDispatchLifecycleAdmission,
344344
throwIfDispatchOperationAborted,
345345
trackDispatchLifecycleWork,
346+
turnLedger,
346347
} = replyOperationCoordinator;
347348
const maybeApplyTtsWithFinalizationLease = createFinalizationAwareTtsPayloadApplier({
348349
getReplyOperation: getDispatchReplyOperation,
@@ -470,6 +471,7 @@ export async function gatherDispatchRequest(
470471
runWithDispatchLifecycleAdmission,
471472
throwIfDispatchOperationAborted,
472473
trackDispatchLifecycleWork,
474+
turnLedger,
473475
maybeApplyTtsWithFinalizationLease,
474476
hookRunner,
475477
timestamp,

0 commit comments

Comments
 (0)