Skip to content

Commit 358c06e

Browse files
authored
fix(gateway): persist agent turns before acknowledgement (#124857)
* fix(gateway): persist agent turns before acknowledgement * fix(gateway): revalidate exec approval handoffs * docs(gateway): clarify durable session ownership * fix(gateway): reject stale transcript admission targets
1 parent add30d4 commit 358c06e

11 files changed

Lines changed: 821 additions & 218 deletions

‎src/agents/bash-tools.exec-approval-followup-state.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -181,17 +181,23 @@ export function claimExecApprovalFollowupRuntimeHandoff(params: {
181181
return cloneExecApprovalFollowupRuntimeHandoff(entry);
182182
}
183183

184-
/** Finalize a claimed handoff once its run has been dispatched. */
184+
/** Consume a claimed handoff at its final privileged use. */
185185
export function finalizeExecApprovalFollowupRuntimeHandoff(params: {
186186
handoffId?: string;
187187
claimId?: string;
188+
nowMs?: number;
188189
}): boolean {
189190
const handoffId = normalizeOptionalString(params.handoffId);
190191
const claimId = normalizeOptionalString(params.claimId);
191192
if (!handoffId || !claimId) {
192193
return false;
193194
}
194195
const entry = execApprovalFollowupRuntimeHandoffs.get(handoffId);
196+
const nowMs = params.nowMs ?? Date.now();
197+
if (entry && !isFutureDateTimestampMs(entry.expiresAtMs, { nowMs })) {
198+
execApprovalFollowupRuntimeHandoffs.delete(handoffId);
199+
return false;
200+
}
195201
if (entry?.claimId !== claimId) {
196202
return false;
197203
}

‎src/gateway/agent-turn/agent-content-phase.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@ import {
3030
logAttachmentFailure,
3131
parseMessageWithAttachments,
3232
type ChatAttachment,
33+
type ChatImageContent,
34+
type OffloadedRef,
3335
} from "../chat-attachments.js";
3436
import type { AgentRunRequest } from "../server-methods/agent-request-types.js";
3537
import type { GatewayRequestHandlerOptions } from "../server-methods/types.js";
@@ -53,9 +55,10 @@ type AgentContentPhaseResult = {
5355
requestedSessionKey?: string;
5456
effectiveTranscriptInputText: string;
5557
message: string;
56-
images: Array<{ type: "image"; data: string; mimeType: string }>;
58+
images: ChatImageContent[];
5759
imageOrder: PromptImageOrderEntry[];
5860
media: MediaFact[];
61+
offloadedRefs: OffloadedRef[];
5962
replyTo: string;
6063
recipientChannel?: string;
6164
recipientAccountId?: string;
@@ -89,6 +92,7 @@ export async function prepareAgentContentPhase(params: {
8992
let images: AgentContentPhaseResult["images"] = [];
9093
let imageOrder: PromptImageOrderEntry[] = [];
9194
let media: MediaFact[] = [];
95+
let offloadedRefs: OffloadedRef[] = [];
9296
let agentId = params.agentId;
9397
let requestedSessionKey = params.requestedSessionKey;
9498

@@ -133,6 +137,7 @@ export async function prepareAgentContentPhase(params: {
133137
images = parsed.images;
134138
imageOrder = parsed.imageOrder;
135139
media = parsed.media;
140+
offloadedRefs = parsed.offloadedRefs;
136141
} catch (err) {
137142
logAttachmentFailure(params.context.logGateway, "agent attachment parse failed", err);
138143
params.respond(
@@ -243,6 +248,7 @@ export async function prepareAgentContentPhase(params: {
243248
images,
244249
imageOrder,
245250
media,
251+
offloadedRefs,
246252
replyTo,
247253
recipientChannel,
248254
recipientAccountId,

‎src/gateway/agent-turn/agent-run-admission-phase.ts‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import { claimAgentRunContext } from "../../infra/agent-run-registry.js";
2727
import type { InputProvenance } from "../../sessions/input-provenance.js";
2828
import type { SessionWorkAdmissionLease } from "../../sessions/session-lifecycle-admission.js";
2929
import { registerChatAbortController, resolveAgentRunExpiresAtMs } from "../chat-abort.js";
30+
import type { ChatImageContent, OffloadedRef } from "../chat-attachments.js";
3031
import { errorShapeFromError } from "../error-shape.js";
3132
import type { AgentRunRequest } from "../server-methods/agent-request-types.js";
3233
import {
@@ -49,6 +50,11 @@ import {
4950
} from "./agent-dedupe.js";
5051
import type { AgentDeliveryPhaseResult } from "./agent-delivery-phase.js";
5152
import type { RestoredCronContinuation } from "./agent-handler-helpers.js";
53+
import {
54+
prepareAgentRunUserTurn,
55+
releasePreparedAgentRunUserTurn,
56+
type PreparedAgentRunUserTurn,
57+
} from "./agent-run-user-turn.js";
5258
import type { AgentTurnContext, AgentTurnIo, AgentTurnPrincipal } from "./types.js";
5359

5460
export type PreparedAgentRunDispatch = {
@@ -65,6 +71,7 @@ export type PreparedAgentRunDispatch = {
6571
lifecycleStorePath: string;
6672
resolvedThreadId?: string | number;
6773
dispatchTaskTrackingMode: Exclude<GatewayAgentTaskTrackingMode, "plugin_subagent">;
74+
userTurn: PreparedAgentRunUserTurn;
6875
restoreAdmittedRestartRecoveryInterrupted?: () => Promise<
6976
MainSessionRecoveryPendingTarget | undefined
7077
>;
@@ -76,6 +83,7 @@ export async function prepareAgentRunDispatch(params: {
7683
cfgForAgent?: OpenClawConfig;
7784
sessionEntry?: SessionEntry;
7885
resolvedSessionKey?: string;
86+
requestedSessionKeyRaw?: string;
7987
requestedSessionKey?: string;
8088
preAcceptedReservedSessionKey?: string;
8189
activeSessionAgentId: string;
@@ -97,6 +105,13 @@ export async function prepareAgentRunDispatch(params: {
97105
inputProvenance?: InputProvenance;
98106
isOneShotModelRun: boolean;
99107
isRestartRecoveryResumeRun: boolean;
108+
canUseInternalRuntimeHandoff: boolean;
109+
execApprovalFollowupApprovalId?: string;
110+
message: string;
111+
effectiveTranscriptInputText: string;
112+
images: ChatImageContent[];
113+
offloadedRefs: OffloadedRef[];
114+
requestedPromptPersistenceSuppression: boolean;
100115
runId: string;
101116
agentDedupeKeys: readonly string[];
102117
context: AgentTurnContext;
@@ -436,6 +451,58 @@ export async function prepareAgentRunDispatch(params: {
436451
return undefined;
437452
}
438453
}
454+
let userTurn: PreparedAgentRunUserTurn;
455+
try {
456+
userTurn = await prepareAgentRunUserTurn({
457+
request: params.request,
458+
cfg: params.cfg,
459+
cfgForAgent: params.cfgForAgent,
460+
sessionEntry: params.sessionEntry,
461+
resolvedSessionKey: params.resolvedSessionKey,
462+
requestedSessionKeyRaw: params.requestedSessionKeyRaw,
463+
admittedSessionId: params.getAdmittedSessionId(),
464+
activeSessionAgentId: params.activeSessionAgentId,
465+
resolvedThreadId,
466+
suppressVisibleSessionEffects: params.suppressVisibleSessionEffects,
467+
requestedPromptPersistenceSuppression: params.requestedPromptPersistenceSuppression,
468+
restoredCronContinuation: params.restoredCronContinuation,
469+
canUseInternalRuntimeHandoff: params.canUseInternalRuntimeHandoff,
470+
execApprovalFollowupApprovalId: params.execApprovalFollowupApprovalId,
471+
message: params.message,
472+
effectiveTranscriptInputText: params.effectiveTranscriptInputText,
473+
images: params.images,
474+
offloadedRefs: params.offloadedRefs,
475+
inputProvenance: params.inputProvenance,
476+
runId: params.runId,
477+
client: params.client,
478+
context: params.context,
479+
});
480+
} catch (err) {
481+
activeRunAbort.cleanup({ force: true });
482+
activeGatewayWorkAdmission.release();
483+
params.io.emitAcceptance([false, undefined, errorShapeFromError(ErrorCodes.UNAVAILABLE, err)]);
484+
return undefined;
485+
}
486+
try {
487+
// Transcript persistence can yield. Revalidate the exact live admission
488+
// before its durable turn is allowed to cross the acceptance boundary.
489+
params.assertGatewayWorkAdmissionAllowed();
490+
} catch (err) {
491+
releasePreparedAgentRunUserTurn(userTurn);
492+
activeRunAbort.cleanup({ force: true });
493+
activeGatewayWorkAdmission.release();
494+
params.io.emitAcceptance([
495+
false,
496+
undefined,
497+
errorShapeFromError(ErrorCodes.INVALID_REQUEST, err),
498+
]);
499+
return undefined;
500+
}
501+
if (params.respondToGatewayAdmissionOutcome()) {
502+
releasePreparedAgentRunUserTurn(userTurn);
503+
activeRunAbort.cleanup({ force: true });
504+
return undefined;
505+
}
439506
const accepted = {
440507
runId: params.runId,
441508
sessionKey: params.resolvedSessionKey,
@@ -486,6 +553,7 @@ export async function prepareAgentRunDispatch(params: {
486553
lifecycleStorePath,
487554
resolvedThreadId,
488555
dispatchTaskTrackingMode,
556+
userTurn,
489557
restoreAdmittedRestartRecoveryInterrupted,
490558
};
491559
}

0 commit comments

Comments
 (0)