Skip to content

Commit 408abcd

Browse files
authored
refactor(reply): unify turn lifecycle state ownership (#117145)
* refactor(reply): unify turn lifecycle state ownership * fix(reply): declare unbound-safe session getter contract
1 parent 5f91afa commit 408abcd

12 files changed

Lines changed: 594 additions & 924 deletions

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

Lines changed: 67 additions & 86 deletions
Original file line numberDiff line numberDiff line change
@@ -39,22 +39,12 @@ export async function chooseDispatchRoute(state: PrepareDispatchOperationReadySt
3939
completeDispatchReplyOperation,
4040
ctx,
4141
deliveryChannel,
42-
dispatchHookDispatcher,
4342
dispatcher,
44-
ensureDispatchReplyOperation,
45-
finishReplyOperationAbortedDispatch,
46-
finishReplyOperationBusyDispatch,
47-
getDispatchAbortSignal,
4843
getPreDispatchAbortSignal,
4944
hookRunner,
50-
inboundAudio,
5145
isRoutedReplyDelivered,
5246
markIdle,
5347
markInboundDedupeReplayUnsafe,
54-
maybeApplyTtsWithFinalizationLease,
55-
messageIdForHook,
56-
normalizeReplyMediaPayload,
57-
normalizedCurrentSurface,
5848
params,
5949
recordProcessed,
6050
replyContextAccountId,
@@ -63,23 +53,18 @@ export async function chooseDispatchRoute(state: PrepareDispatchOperationReadySt
6353
routeReplyChannel,
6454
routeReplyThreadId,
6555
routeReplyTo,
66-
routeReplyToOriginating,
6756
runWithDispatchLifecycleAdmission,
6857
sendPayloadAsync,
69-
sendPolicy,
7058
sendPolicyDenied,
7159
sessionAgentId,
7260
sessionKey,
7361
sessionStoreEntry,
7462
sessionTtsAuto,
75-
shouldEmitFullVerboseProgress,
7663
shouldEmitVerboseProgress,
7764
shouldRouteToOriginating,
7865
sourceReplyDeliveryMode,
7966
suppressAutomaticSourceDelivery,
8067
suppressDelivery,
81-
suppressHookReplyLifecycle,
82-
suppressHookUserDelivery,
8368
traceReplyPhase,
8469
trackDispatchLifecycleWork,
8570
turnLedger,
@@ -92,7 +77,7 @@ export async function chooseDispatchRoute(state: PrepareDispatchOperationReadySt
9277
const shouldSendToolSummaries = () => shouldSendVerboseProgressMessages();
9378
const shouldSendToolStartStatuses = false;
9479
const notifiedSessionMetadataChangeKeys = new Set<string>();
95-
let sessionMetadataChangesForResult: CommandSessionMetadataChange[] | undefined;
80+
const routeState: { sessionMetadataChangesForResult?: CommandSessionMetadataChange[] } = {};
9681
const notifySessionMetadataChanges = (
9782
changes: CommandSessionMetadataChange[] | undefined,
9883
): void => {
@@ -111,7 +96,10 @@ export async function chooseDispatchRoute(state: PrepareDispatchOperationReadySt
11196
if (freshChanges.length === 0) {
11297
return;
11398
}
114-
sessionMetadataChangesForResult = [...(sessionMetadataChangesForResult ?? []), ...freshChanges];
99+
routeState.sessionMetadataChangesForResult = [
100+
...(routeState.sessionMetadataChangesForResult ?? []),
101+
...freshChanges,
102+
];
115103
params.onSessionMetadataChanges?.(freshChanges);
116104
};
117105
const shouldDeliverVerboseProgressDespiteSourceSuppression = () =>
@@ -216,7 +204,7 @@ export async function chooseDispatchRoute(state: PrepareDispatchOperationReadySt
216204
const shouldSuppressMessageToolOnlyTextErrorProgress = (payload: ReplyPayload) => {
217205
if (
218206
sourceReplyDeliveryMode !== "message_tool_only" ||
219-
shouldEmitFullVerboseProgress() ||
207+
state.shouldEmitFullVerboseProgress() ||
220208
payload.isError !== true
221209
) {
222210
return false;
@@ -300,7 +288,7 @@ export async function chooseDispatchRoute(state: PrepareDispatchOperationReadySt
300288
routedFinalCount: number;
301289
dispatcherOutcome?: Promise<ReplyDispatchDeliveryOutcome>;
302290
}> => {
303-
const abortSignal = options.abortSignal ?? getDispatchAbortSignal();
291+
const abortSignal = options.abortSignal ?? state.getDispatchAbortSignal();
304292
const throwIfFinalDeliveryAborted = () => {
305293
if (abortSignal?.aborted) {
306294
throw new DispatchReplyOperationAbortedError();
@@ -334,7 +322,7 @@ export async function chooseDispatchRoute(state: PrepareDispatchOperationReadySt
334322
const ttsPayload =
335323
payload.isReasoning === true || payload.isCommentary === true
336324
? payload
337-
: await maybeApplyTtsWithFinalizationLease({
325+
: await state.maybeApplyTtsWithFinalizationLease({
338326
payload,
339327
cfg,
340328
channel: deliveryChannel,
@@ -344,7 +332,7 @@ export async function chooseDispatchRoute(state: PrepareDispatchOperationReadySt
344332
accountId: replyRoute.accountId,
345333
});
346334
throwIfFinalDeliveryAborted();
347-
let normalizedPayload = await normalizeReplyMediaPayload(ttsPayload);
335+
let normalizedPayload = await state.normalizeReplyMediaPayload(ttsPayload);
348336
throwIfFinalDeliveryAborted();
349337
const deliveredAsBlock = await wasReplyDeliveredAsBlock(payload, abortSignal);
350338
throwIfFinalDeliveryAborted();
@@ -362,7 +350,7 @@ export async function chooseDispatchRoute(state: PrepareDispatchOperationReadySt
362350
return { dedupedAgainstBlock: true, queuedFinal: false, routedFinalCount: 0 };
363351
}
364352
}
365-
const result = await routeReplyToOriginating(normalizedPayload, {
353+
const result = await state.routeReplyToOriginating(normalizedPayload, {
366354
abortSignal,
367355
kind: "final",
368356
...(hasTranscriptOwner ? { mirror: false } : {}),
@@ -388,14 +376,16 @@ export async function chooseDispatchRoute(state: PrepareDispatchOperationReadySt
388376
const transcriptMirrorSessionKey =
389377
acpDispatchSessionKey ?? sessionStoreEntry.sessionKey ?? sessionKey;
390378
const transcriptMirrorSourceId =
391-
normalizeOptionalString(messageIdForHook) ??
379+
normalizeOptionalString(state.messageIdForHook) ??
392380
normalizeOptionalString(params.replyOptions?.runId);
393381
const transcriptMirrorSessionBinding = resolvePreparedTranscriptBinding(
394382
transcriptMirrorSessionKey,
395383
);
396384
const transcriptMirror =
397385
sourceReplyTranscriptMirror ??
398-
(normalizedCurrentSurface === "slack" && hasVisibleFinalContent && transcriptMirrorSessionKey
386+
(state.normalizedCurrentSurface === "slack" &&
387+
hasVisibleFinalContent &&
388+
transcriptMirrorSessionKey
399389
? transcriptMirrorForDeliveredPayload(
400390
{
401391
sessionKey: transcriptMirrorSessionKey,
@@ -479,32 +469,33 @@ export async function chooseDispatchRoute(state: PrepareDispatchOperationReadySt
479469
() =>
480470
hookRunner.runBeforeDispatch(
481471
{
482-
messageId: state.hookContext.messageId,
483-
content: state.hookContext.content,
484-
body: state.hookContext.bodyForAgent ?? state.hookContext.body,
485-
channel: state.hookContext.channelId,
472+
messageId: state.hookState.hookContext.messageId,
473+
content: state.hookState.hookContext.content,
474+
body:
475+
state.hookState.hookContext.bodyForAgent ?? state.hookState.hookContext.body,
476+
channel: state.hookState.hookContext.channelId,
486477
sessionKey: beforeDispatchSessionKey,
487-
senderId: state.hookContext.senderId,
488-
replyToId: state.hookContext.replyToId,
489-
replyToIdFull: state.hookContext.replyToIdFull,
490-
replyToBody: state.hookContext.replyToBody,
491-
replyToSender: state.hookContext.replyToSender,
492-
replyToIsQuote: state.hookContext.replyToIsQuote,
493-
isGroup: state.hookContext.isGroup,
494-
timestamp: state.hookContext.timestamp,
478+
senderId: state.hookState.hookContext.senderId,
479+
replyToId: state.hookState.hookContext.replyToId,
480+
replyToIdFull: state.hookState.hookContext.replyToIdFull,
481+
replyToBody: state.hookState.hookContext.replyToBody,
482+
replyToSender: state.hookState.hookContext.replyToSender,
483+
replyToIsQuote: state.hookState.hookContext.replyToIsQuote,
484+
isGroup: state.hookState.hookContext.isGroup,
485+
timestamp: state.hookState.hookContext.timestamp,
495486
},
496487
{
497-
messageId: state.hookContext.messageId,
498-
channelId: state.hookContext.channelId,
499-
accountId: state.hookContext.accountId,
500-
conversationId: state.inboundClaimContext.conversationId,
488+
messageId: state.hookState.hookContext.messageId,
489+
channelId: state.hookState.hookContext.channelId,
490+
accountId: state.hookState.hookContext.accountId,
491+
conversationId: state.hookState.inboundClaimContext.conversationId,
501492
sessionKey: beforeDispatchSessionKey,
502-
senderId: state.hookContext.senderId,
503-
replyToId: state.hookContext.replyToId,
504-
replyToIdFull: state.hookContext.replyToIdFull,
505-
replyToBody: state.hookContext.replyToBody,
506-
replyToSender: state.hookContext.replyToSender,
507-
replyToIsQuote: state.hookContext.replyToIsQuote,
493+
senderId: state.hookState.hookContext.senderId,
494+
replyToId: state.hookState.hookContext.replyToId,
495+
replyToIdFull: state.hookState.hookContext.replyToIdFull,
496+
replyToBody: state.hookState.hookContext.replyToBody,
497+
replyToSender: state.hookState.hookContext.replyToSender,
498+
replyToIsQuote: state.hookState.hookContext.replyToIsQuote,
508499
},
509500
pluginSubagentRequester,
510501
),
@@ -554,11 +545,11 @@ export async function chooseDispatchRoute(state: PrepareDispatchOperationReadySt
554545
sessionKey: acpDispatchSessionKey,
555546
toolsAllow: params.replyOptions?.toolsAllow,
556547
images: params.replyOptions?.images,
557-
inboundAudio,
548+
inboundAudio: state.inboundAudio,
558549
sessionTtsAuto,
559550
ttsChannel: deliveryChannel,
560-
suppressUserDelivery: suppressHookUserDelivery,
561-
suppressReplyLifecycle: suppressHookReplyLifecycle,
551+
suppressUserDelivery: state.suppressHookUserDelivery,
552+
suppressReplyLifecycle: state.suppressHookReplyLifecycle,
562553
sourceReplyDeliveryMode,
563554
shouldRouteToOriginating,
564555
originatingChannel: routeReplyChannel,
@@ -567,11 +558,11 @@ export async function chooseDispatchRoute(state: PrepareDispatchOperationReadySt
567558
originatingThreadId: routeReplyThreadId,
568559
originatingChatType: replyRoute.chatType,
569560
shouldSendToolSummaries,
570-
sendPolicy,
561+
sendPolicy: state.sendPolicy,
571562
}),
572563
{
573564
cfg,
574-
dispatcher: dispatchHookDispatcher,
565+
dispatcher: state.dispatchHookDispatcher,
575566
abortSignal: getPreDispatchAbortSignal() ?? params.replyOptions?.abortSignal,
576567
onReplyStart: params.replyOptions?.onReplyStart,
577568
recordProcessed,
@@ -595,48 +586,38 @@ export async function chooseDispatchRoute(state: PrepareDispatchOperationReadySt
595586
}
596587
}
597588

598-
const dispatchAcquisition = await ensureDispatchReplyOperation("dispatch");
589+
const dispatchAcquisition = await state.ensureDispatchReplyOperation("dispatch");
599590
if (dispatchAcquisition.status === "aborted") {
600-
return { status: "complete" as const, result: finishReplyOperationAbortedDispatch() };
591+
return { status: "complete" as const, result: state.finishReplyOperationAbortedDispatch() };
601592
}
602593
if (dispatchAcquisition.status === "busy") {
603594
return {
604595
status: "complete" as const,
605-
result: finishReplyOperationBusyDispatch({ dedupeDisposition: "release" }),
596+
result: state.finishReplyOperationBusyDispatch({ dedupeDisposition: "release" }),
606597
};
607598
}
608-
const nextState = extendPreparedDispatchState(
609-
state,
610-
{
611-
shouldSuppressDefaultToolProgressMessages,
612-
shouldSendVerboseProgressMessages,
613-
shouldSendToolSummaries,
614-
shouldSendToolStartStatuses,
615-
notifySessionMetadataChanges,
616-
shouldDeliverVerboseProgressDespiteSourceSuppression,
617-
shouldDeliverForcedToolProgressDespiteSourceSuppression,
618-
shouldDeliverFastModeAutoProgressDespiteSourceSuppression,
619-
hasExecApprovalPayload,
620-
hasAskUserPayload,
621-
readAskUserQuestionId,
622-
shouldSuppressLateTextOnlyToolProgress,
623-
flushPendingCommentaryProgress,
624-
noteCommentaryProgress,
625-
shouldSuppressMessageToolOnlyTextErrorProgress,
626-
sendTrackedBlockReply,
627-
recordRoutedBlockReplyDelivery,
628-
wasReplyDeliveredAsBlock,
629-
sendFinalPayload,
630-
},
631-
{
632-
sessionMetadataChangesForResult: {
633-
get: () => sessionMetadataChangesForResult,
634-
set: (value: typeof sessionMetadataChangesForResult) => {
635-
sessionMetadataChangesForResult = value;
636-
},
637-
},
638-
},
639-
);
599+
const nextState = extendPreparedDispatchState(state, {
600+
shouldSuppressDefaultToolProgressMessages,
601+
shouldSendVerboseProgressMessages,
602+
shouldSendToolSummaries,
603+
shouldSendToolStartStatuses,
604+
notifySessionMetadataChanges,
605+
shouldDeliverVerboseProgressDespiteSourceSuppression,
606+
shouldDeliverForcedToolProgressDespiteSourceSuppression,
607+
shouldDeliverFastModeAutoProgressDespiteSourceSuppression,
608+
hasExecApprovalPayload,
609+
hasAskUserPayload,
610+
readAskUserQuestionId,
611+
shouldSuppressLateTextOnlyToolProgress,
612+
flushPendingCommentaryProgress,
613+
noteCommentaryProgress,
614+
shouldSuppressMessageToolOnlyTextErrorProgress,
615+
sendTrackedBlockReply,
616+
recordRoutedBlockReplyDelivery,
617+
wasReplyDeliveredAsBlock,
618+
sendFinalPayload,
619+
routeState,
620+
});
640621
return { status: "ready" as const, state: nextState };
641622
}
642623

0 commit comments

Comments
 (0)