Skip to content

Commit fa9626c

Browse files
authored
refactor(steering): make active-run admission exact and atomic (#120285)
* refactor(steering): make admission exact and atomic * fix(steering): bind targets by run identity * fix(steering): inject before reply dispatch * fix(steering): preserve backend injection modes * fix(steering): target session suggestions * fix(steering): preserve sibling delivery contracts * style(steering): satisfy exact-head lint * fix(steering): preserve targetless protocol compatibility * fix(steering): preserve exact targets through replies
1 parent b921139 commit fa9626c

65 files changed

Lines changed: 2622 additions & 800 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/shared/OpenClawKit/Sources/OpenClawProtocol/GatewayModels.swift‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17435,6 +17435,7 @@ public struct ChatSendParams: Codable, Sendable {
1743517435
public let systemprovenancereceipt: String?
1743617436
public let suppresscommandinterpretation: Bool?
1743717437
public let expectedleafentryid: AnyCodable?
17438+
public let expectedrunid: String?
1743817439
public let expectedsessionroutingcontract: String?
1743917440
public let idempotencykey: String
1744017441

@@ -17460,6 +17461,7 @@ public struct ChatSendParams: Codable, Sendable {
1746017461
systemprovenancereceipt: String? = nil,
1746117462
suppresscommandinterpretation: Bool? = nil,
1746217463
expectedleafentryid: AnyCodable? = nil,
17464+
expectedrunid: String? = nil,
1746317465
expectedsessionroutingcontract: String? = nil,
1746417466
idempotencykey: String)
1746517467
{
@@ -17484,6 +17486,7 @@ public struct ChatSendParams: Codable, Sendable {
1748417486
self.systemprovenancereceipt = systemprovenancereceipt
1748517487
self.suppresscommandinterpretation = suppresscommandinterpretation
1748617488
self.expectedleafentryid = expectedleafentryid
17489+
self.expectedrunid = expectedrunid
1748717490
self.expectedsessionroutingcontract = expectedsessionroutingcontract
1748817491
self.idempotencykey = idempotencykey
1748917492
}
@@ -17509,6 +17512,7 @@ public struct ChatSendParams: Codable, Sendable {
1750917512
systemprovenancereceipt: String? = nil,
1751017513
suppresscommandinterpretation: Bool? = nil,
1751117514
expectedleafentryid: AnyCodable? = nil,
17515+
expectedrunid: String? = nil,
1751217516
expectedsessionroutingcontract: String? = nil,
1751317517
idempotencykey: String)
1751417518
{
@@ -17534,6 +17538,7 @@ public struct ChatSendParams: Codable, Sendable {
1753417538
systemprovenancereceipt: systemprovenancereceipt,
1753517539
suppresscommandinterpretation: suppresscommandinterpretation,
1753617540
expectedleafentryid: expectedleafentryid,
17541+
expectedrunid: expectedrunid,
1753717542
expectedsessionroutingcontract: expectedsessionroutingcontract,
1753817543
idempotencykey: idempotencykey)
1753917544
}
@@ -17560,6 +17565,7 @@ public struct ChatSendParams: Codable, Sendable {
1756017565
case systemprovenancereceipt = "systemProvenanceReceipt"
1756117566
case suppresscommandinterpretation = "suppressCommandInterpretation"
1756217567
case expectedleafentryid = "expectedLeafEntryId"
17568+
case expectedrunid = "expectedRunId"
1756317569
case expectedsessionroutingcontract = "expectedSessionRoutingContract"
1756417570
case idempotencykey = "idempotencyKey"
1756517571
}

‎docs/gateway/protocol.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -632,7 +632,7 @@ methods. Treat this as feature discovery, not a full enumeration of
632632
- Chat execution still uses `chat.history`, `chat.send`, `chat.abort`, and `chat.inject`. `chat.history` is display-normalized for UI clients: inline directive tags are stripped from visible text, plain-text tool-call XML payloads (`<tool_call>...</tool_call>`, `<function_call>...</function_call>`, `<tool_calls>...</tool_calls>`, `<function_calls>...</function_calls>`, and truncated tool-call blocks) and leaked ASCII/full-width model control tokens are stripped, pure silent-token assistant rows (exact `NO_REPLY` / `no_reply`) are omitted, and oversized rows can be replaced with placeholders.
633633
- `chat.message.get` is the additive bounded full-message reader for a single visible transcript entry. Pass `sessionKey`, optional `agentId` when session selection is agent-scoped, and a transcript `messageId` previously surfaced through `chat.history`; the gateway returns the same display-normalized projection without the lightweight history truncation cap when the stored entry is still available and not oversized.
634634
- `chat.toolTitles` returns short purpose titles for tool calls rendered in the Control UI (batched, max 24 items with bounded inputs). The feature is opt-in via `gateway.controlUi.toolTitles` (default off); disabled gateways answer `{ titles: {}, disabled: true }` with no model call so clients stop asking. When enabled, titles use standard utility-model routing: an explicitly configured `utilityModel` (an operator decision that, like all utility tasks, may send bounded task content to the chosen provider), else the session provider's declared small-model default so no new egress destination appears implicitly; an empty `utilityModel` disables them entirely. Titles never fall back to the primary model. Results cache in the per-agent state database keyed by tool name + input, so repeated views never re-bill the same calls.
635-
- `chat.send` accepts one-turn `fastMode: "auto"` to use fast mode for model calls started before the auto cutoff, then start later retry, fallback, tool-result, or continuation calls without fast mode. The cutoff defaults to 60 seconds (`DEFAULT_FAST_MODE_AUTO_ON_SECONDS`) and can be configured per model with `agents.defaults.models["<provider>/<model>"].params.fastAutoOnSeconds`. A `chat.send` caller can pass one-turn `fastAutoOnSeconds` to override the cutoff for that request. Pass `queueMode` (`steer`, `followup`, `collect`, or `interrupt`) to override the stored queue mode for this request only; explicit Control UI steer actions use `queueMode: "steer"`. Interactive clients can pass `expectedLeafEntryId` with the active transcript-branch leaf they display, or `null` for an authoritative empty transcript; the Gateway rejects the send with `details.reason: "active-leaf-changed"` if another client switched branches first.
635+
- `chat.send` accepts one-turn `fastMode: "auto"` to use fast mode for model calls started before the auto cutoff, then start later retry, fallback, tool-result, or continuation calls without fast mode. The cutoff defaults to 60 seconds (`DEFAULT_FAST_MODE_AUTO_ON_SECONDS`) and can be configured per model with `agents.defaults.models["<provider>/<model>"].params.fastAutoOnSeconds`. A `chat.send` caller can pass one-turn `fastAutoOnSeconds` to override the cutoff for that request. Pass `queueMode` (`steer`, `followup`, `collect`, or `interrupt`) to override the stored queue mode for this request only; explicit Control UI steer actions use `queueMode: "steer"`. Modern clients, especially clients that persist or retry a steer, should also pass the active `expectedRunId`; the Gateway binds it to one exact run so a retry cannot reach a successor. Older targetless `queueMode: "steer"` requests remain accepted only as a leaf-bound compatibility path: they must pass the active operation's immutable `expectedLeafEntryId` (or deliberate `null` for an authoritative empty transcript), and can reject with `details.reason: "active-leaf-changed"` when the leaf, owner, freshness, or injection capability cannot be proven. Other interactive sends may pass `expectedLeafEntryId` to reject if another client switched transcript branches first.
636636

637637
</Accordion>
638638

‎extensions/codex/src/app-server/run-attempt-active-turn.ts‎

Lines changed: 40 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -171,44 +171,49 @@ export async function activateCodexAttemptTurn(
171171
signal: runAbortController.signal,
172172
});
173173
steeringQueueRef.current = activeSteeringQueue;
174-
const handle = {
175-
kind: "embedded" as const,
176-
runId: params.runId,
177-
queueMessage: async (text: string, optionsLocal?: CodexSteeringQueueOptions) => {
178-
const isInboundUserMessage = optionsLocal?.isInboundUserMessage === true;
179-
if (isInboundUserMessage && !optionsLocal?.images?.length) {
180-
const claimed = await claimPendingAgentQuestionAnswer({
181-
sessionKey: params.sessionKey ?? params.sessionId,
182-
text,
183-
});
184-
if (claimed) {
185-
return undefined;
186-
}
187-
} else if (isInboundUserMessage) {
188-
try {
189-
await cancelPendingAgentQuestionForSession({
190-
sessionKey: params.sessionKey ?? params.sessionId,
191-
resolvedBy: "image-reply",
192-
});
193-
} catch (error) {
194-
// Cleanup failure must not drop the user's image turn.
195-
embeddedAgentLog.warn("failed to cancel codex gateway question before image steering", {
196-
error,
197-
});
198-
}
174+
const queueMessage = async (text: string, optionsLocal?: CodexSteeringQueueOptions) => {
175+
const isInboundUserMessage = optionsLocal?.isInboundUserMessage === true;
176+
if (isInboundUserMessage && !optionsLocal?.images?.length) {
177+
const claimed = await claimPendingAgentQuestionAnswer({
178+
sessionKey: params.sessionKey ?? params.sessionId,
179+
text,
180+
});
181+
if (claimed) {
182+
return undefined;
199183
}
184+
} else if (isInboundUserMessage) {
200185
try {
201-
await activeSteeringQueue.queue(text, optionsLocal);
186+
await cancelPendingAgentQuestionForSession({
187+
sessionKey: params.sessionKey ?? params.sessionId,
188+
resolvedBy: "image-reply",
189+
});
202190
} catch (error) {
203-
if (error instanceof CodexSteeringAcceptedUnconfirmedError) {
204-
return {
205-
transcriptCommit: "unconfirmed" as const,
206-
errorMessage: formatErrorMessage(error),
207-
};
208-
}
209-
throw error;
191+
// Cleanup failure must not drop the user's image turn.
192+
embeddedAgentLog.warn("failed to cancel codex gateway question before image steering", {
193+
error,
194+
});
195+
}
196+
}
197+
try {
198+
await activeSteeringQueue.queue(text, optionsLocal);
199+
} catch (error) {
200+
if (error instanceof CodexSteeringAcceptedUnconfirmedError) {
201+
return {
202+
transcriptCommit: "unconfirmed" as const,
203+
errorMessage: formatErrorMessage(error),
204+
};
210205
}
211-
return undefined;
206+
throw error;
207+
}
208+
return undefined;
209+
};
210+
const handle = {
211+
kind: "embedded" as const,
212+
runId: params.runId,
213+
queueMessage,
214+
messageInjection: {
215+
isAvailable: () => !state.completed && !state.timedOut && !runAbortController.signal.aborted,
216+
queueMessage,
212217
},
213218
isStreaming: () => !state.completed && !runAbortController.signal.aborted,
214219
isAborted: () => runAbortController.signal.aborted,
@@ -221,6 +226,7 @@ export async function activateCodexAttemptTurn(
221226
supportsTranscriptCommitWait: true,
222227
supportsQueueMessageImages: true,
223228
sourceReplyDeliveryMode: params.sourceReplyDeliveryMode,
229+
taskSuggestionDeliveryMode: params.taskSuggestionDeliveryMode,
224230
cancel: () => abortExplicitly("cancelled"),
225231
abort: () => abortExplicitly("aborted"),
226232
};

‎extensions/codex/src/app-server/run-attempt.steering.test.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,17 +145,27 @@ describe("runCodexAppServerAttempt steering", () => {
145145
it("accepts Gateway transcript-backed steering for the active Codex turn", async () => {
146146
const { requests, waitForMethod, completeTurn, notify } = createStartedThreadHarness();
147147
const params = createSteeringParams();
148+
params.taskSuggestionDeliveryMode = "gateway";
148149

149150
const run = runCodexAppServerAttempt(params, {
150151
pluginConfig: { appServer: { mode: "yolo" } },
151152
});
152153
await waitForMethod("turn/start");
153154

155+
await vi.waitFor(() => {
156+
expect(
157+
activeRunRegistrationMocks.setActiveEmbeddedRun.mock.calls.findLast(
158+
(call) => call[0] === params.sessionId,
159+
)?.[1],
160+
).toMatchObject({ taskSuggestionDeliveryMode: "gateway" });
161+
}, fastWait);
162+
154163
// This public queue returns immediate eligibility; the handle's delivery
155164
// promise stays pending until the matching item/completed notification below.
156165
await waitAndQueueActiveRunMessage(params.sessionId, "steer this active turn", {
157166
debounceMs: 0,
158167
isInboundUserMessage: true,
168+
taskSuggestionDeliveryMode: "gateway",
159169
waitForTranscriptCommit: true,
160170
});
161171
await vi.waitFor(

‎extensions/copilot/src/attempt-active-run.ts‎

Lines changed: 47 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -33,47 +33,53 @@ export function registerCopilotActiveRun(params: {
3333
embeddedAgentLog.warn("failed to cancel copilot gateway question during shutdown", { error });
3434
});
3535
};
36+
const queueMessage = async (text: string, options?: CopilotQueueMessageOptions) => {
37+
if (
38+
options?.isInboundUserMessage === true &&
39+
(await claimPendingAgentQuestionAnswer({
40+
sessionKey: params.input.sessionKey ?? params.input.sessionId,
41+
text,
42+
persist: options.userTurnTranscriptRecorder
43+
? async () => {
44+
await options.userTurnTranscriptRecorder?.persistApproved();
45+
}
46+
: undefined,
47+
}))
48+
) {
49+
return undefined;
50+
}
51+
if (params.isSettled() || params.isAborted()) {
52+
throw new Error("Copilot steering is unavailable after the active run ended");
53+
}
54+
if (!params.canAcceptSteering()) {
55+
throw new Error("Copilot steering is unavailable before initial user validation");
56+
}
57+
const messageId = await params.session.send({ prompt: text });
58+
if (options?.waitForTranscriptCommit === true) {
59+
try {
60+
await waitForPersistenceReceipt(
61+
params.transcriptJournal.waitForSdkUserPersisted(messageId),
62+
options.deliveryTimeoutMs,
63+
);
64+
} catch (error) {
65+
return {
66+
transcriptCommit: "unconfirmed" as const,
67+
errorMessage:
68+
error instanceof Error
69+
? error.message
70+
: "Copilot accepted steering but its transcript receipt was not confirmed",
71+
};
72+
}
73+
}
74+
return undefined;
75+
};
3676
const activeRunHandle = {
3777
kind: "embedded" as const,
38-
queueMessage: async (text: string, options?: CopilotQueueMessageOptions) => {
39-
if (
40-
options?.isInboundUserMessage === true &&
41-
(await claimPendingAgentQuestionAnswer({
42-
sessionKey: params.input.sessionKey ?? params.input.sessionId,
43-
text,
44-
persist: options.userTurnTranscriptRecorder
45-
? async () => {
46-
await options.userTurnTranscriptRecorder?.persistApproved();
47-
}
48-
: undefined,
49-
}))
50-
) {
51-
return undefined;
52-
}
53-
if (params.isSettled() || params.isAborted()) {
54-
throw new Error("Copilot steering is unavailable after the active run ended");
55-
}
56-
if (!params.canAcceptSteering()) {
57-
throw new Error("Copilot steering is unavailable before initial user validation");
58-
}
59-
const messageId = await params.session.send({ prompt: text });
60-
if (options?.waitForTranscriptCommit === true) {
61-
try {
62-
await waitForPersistenceReceipt(
63-
params.transcriptJournal.waitForSdkUserPersisted(messageId),
64-
options.deliveryTimeoutMs,
65-
);
66-
} catch (error) {
67-
return {
68-
transcriptCommit: "unconfirmed" as const,
69-
errorMessage:
70-
error instanceof Error
71-
? error.message
72-
: "Copilot accepted steering but its transcript receipt was not confirmed",
73-
};
74-
}
75-
}
76-
return undefined;
78+
runId: params.input.runId,
79+
queueMessage,
80+
messageInjection: {
81+
isAvailable: () => params.canAcceptSteering() && !params.isSettled() && !params.isAborted(),
82+
queueMessage,
7783
},
7884
isStreaming: () => params.canAcceptSteering() && !params.isSettled() && !params.isAborted(),
7985
isAborted: params.isAborted,
@@ -82,6 +88,7 @@ export function registerCopilotActiveRun(params: {
8288
// receipt resolves only after that exact SDK event reaches canonical history.
8389
supportsTranscriptCommitWait: true,
8490
sourceReplyDeliveryMode: params.input.sourceReplyDeliveryMode,
91+
taskSuggestionDeliveryMode: params.input.taskSuggestionDeliveryMode,
8592
cancel: () => {
8693
cancelGatewayQuestionBestEffort("run-cancel");
8794
params.userInputBridge.cancelPending();
@@ -99,6 +106,7 @@ export function registerCopilotActiveRun(params: {
99106
params.input.sessionKey,
100107
params.input.sessionFile,
101108
);
109+
params.input.replyOperation?.attachBackend(activeRunHandle);
102110
return activeRunHandle;
103111
}
104112

‎extensions/copilot/src/attempt-execution.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ export async function runCopilotExecution(context: {
114114
now,
115115
scope: input.agentHarnessTaskRuntimeScope,
116116
});
117-
let activeRunHandleRef: Parameters<typeof clearActiveEmbeddedRun>[1] | undefined;
117+
let activeRunHandleRef: ReturnType<typeof registerCopilotActiveRun> | undefined;
118118
let userInputBridgeRef: CopilotUserInputBridge | undefined;
119119
let cleanupToolBridge: (() => void) | undefined;
120120
let releaseError: Error | undefined;
@@ -539,6 +539,7 @@ export async function runCopilotExecution(context: {
539539
}
540540
userInputBridgeRef?.cancelPending();
541541
if (activeRunHandleRef) {
542+
input.replyOperation?.detachBackend(activeRunHandleRef);
542543
clearActiveEmbeddedRun(
543544
input.sessionId,
544545
activeRunHandleRef,

‎extensions/copilot/src/attempt.test.ts‎

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2001,7 +2001,9 @@ describe("runCopilotAttempt", () => {
20012001
});
20022002
},
20032003
});
2004-
const attempt = runCopilotAttempt(makeParams(), { pool: makeFakePool(sdk) });
2004+
const attempt = runCopilotAttempt(makeParams({ taskSuggestionDeliveryMode: "gateway" }), {
2005+
pool: makeFakePool(sdk),
2006+
});
20052007

20062008
await vi.waitFor(() => {
20072009
expect(requireSession(sdk).sendAndWait).toHaveBeenCalledTimes(1);
@@ -2016,22 +2018,29 @@ describe("runCopilotAttempt", () => {
20162018
},
20172019
) => Promise<void>;
20182020
supportsTranscriptCommitWait?: boolean;
2021+
taskSuggestionDeliveryMode?: "gateway";
20192022
}
20202023
| undefined;
20212024
expect(handle?.supportsTranscriptCommitWait).toBe(true);
2025+
expect(handle?.taskSuggestionDeliveryMode).toBe("gateway");
20222026

2023-
await handle?.queueMessage("change course", {
2024-
deliveryTimeoutMs: 1_000,
2025-
waitForTranscriptCommit: true,
2026-
});
2027-
2028-
expect(requireSession(sdk).send).toHaveBeenCalledWith({ prompt: "change course" });
2029-
expect(transcriptRuntimeMock.appendStrict).toHaveBeenCalledWith(
2030-
expect.objectContaining({
2031-
eventId: "steered-user",
2032-
message: expect.objectContaining({ role: "user", content: "change course" }),
2027+
expect(
2028+
queueAgentHarnessMessage("session-1", "change course", {
2029+
deliveryTimeoutMs: 1_000,
2030+
taskSuggestionDeliveryMode: "gateway",
2031+
waitForTranscriptCommit: true,
20332032
}),
2034-
);
2033+
).toBe(true);
2034+
2035+
await vi.waitFor(() => {
2036+
expect(requireSession(sdk).send).toHaveBeenCalledWith({ prompt: "change course" });
2037+
expect(transcriptRuntimeMock.appendStrict).toHaveBeenCalledWith(
2038+
expect.objectContaining({
2039+
eventId: "steered-user",
2040+
message: expect.objectContaining({ role: "user", content: "change course" }),
2041+
}),
2042+
);
2043+
});
20352044

20362045
initialTurn.resolve(makeAssistantMessageEvent("done"));
20372046
await expect(attempt).resolves.toMatchObject({ terminal: { kind: "ok" } });

‎packages/gateway-protocol/src/schema/audit-activity.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -259,6 +259,7 @@ const inboundCompletedReasonSchema = Type.Union([
259259
Type.Literal("before_dispatch_handled"),
260260
Type.Literal("acp_dispatch_completed"),
261261
Type.Literal("acp_dispatch_empty"),
262+
Type.Literal("active_run_injected"),
262263
]);
263264

264265
const inboundSkippedReasonSchema = Type.Union([
@@ -524,7 +525,8 @@ type AuditActivityInboundMessageV1Terminal =
524525
| "plugin_bound_declined"
525526
| "before_dispatch_handled"
526527
| "acp_dispatch_completed"
527-
| "acp_dispatch_empty";
528+
| "acp_dispatch_empty"
529+
| "active_run_injected";
528530
}
529531
| {
530532
status: "blocked";

‎packages/gateway-protocol/src/schema/logs-chat.test.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,14 @@ describe("ChatSendParamsSchema", () => {
4949
true,
5050
);
5151
expect(Value.Check(ChatSendParamsSchema, { ...send, expectedLeafEntryId: null })).toBe(true);
52+
expect(
53+
Value.Check(ChatSendParamsSchema, {
54+
...send,
55+
queueMode: "steer",
56+
expectedLeafEntryId: "leaf-1",
57+
}),
58+
).toBe(true);
59+
expect(Value.Check(ChatSendParamsSchema, { ...send, expectedRunId: "run-1" })).toBe(true);
5260
expect(Value.Check(ChatSendParamsSchema, { ...send, unknown: true })).toBe(false);
5361
});
5462
});

0 commit comments

Comments
 (0)