Skip to content

Commit 6515f6a

Browse files
authored
refactor(steering): gateway-owned atomic start-or-steer (#125808)
* refactor(steering): gateway-owned start-or-steer via one captured-operation lifecycle chat.send with queue mode steer now atomically captures the selected session's current direct reply operation under the writer barrier and injects into exactly that operation; with no direct owner it starts a new run instead of failing with active-leaf-changed. Client-supplied expectedRunId keeps exact-match semantics; the transcript-branch CAS (expectedLeafEntryId) now guards only non-steer sends. All three steering paths (gateway chat.send, channel queue steering, server /steer) share one begin/finalize lifecycle on the reply-run registry, including the captured-instance abort from 5a15e1a. Deleted: the duplicate accepted/rejected/unconfirmed policy machine in steer adoption, the raw embedded /steer runtime path, the leaf-bound injection identity and reject-before-ack compat, and the dead target tool-authority fingerprint. messageInjectionAttempted becomes a typed messageInjectionDisposition (none | accepted | rejected); rejected injections take one visible followup fallback, so non-injectable runtimes queue instead of silently dropping. Deliberate semantics: a registry-less active embedded run is no longer steered by raw session id (correlation-only authority) - the message becomes a visible followup; /steer injects under its own command authorization instead of the inbound tool-authority gate it could never satisfy. * docs(protocol): describe gateway start-or-steer contract for chat.send Targetless steer is no longer a leaf-bound compatibility path that can reject with active-leaf-changed; it targets the selected session's current state (inject into the direct run, else start a turn). expectedRunId stays an exact-run fence; expectedLeafEntryId is the non-steer transcript-branch CAS. * fix(steering): require matching tool authority for /steer injection The authorized-sender command gate is weaker than tool-authority equality. Make /steer and gateway injection present the same projected evidence as channel steering so mismatches fall back to a normal prompt under the sender’s own authority.
1 parent 774d9e6 commit 6515f6a

25 files changed

Lines changed: 877 additions & 775 deletions

‎docs/gateway/protocol.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -663,7 +663,7 @@ methods. Treat this as feature discovery, not a full enumeration of
663663
Tail responses can include an opaque `deltaCursor`. Pass it back as `cursor` to `chat.history` or `chat.startup` instead of `offset` or `messageId`. A successful catch-up returns `{ kind: "delta", messages, deltaCursor, sessionInfo }`; replay each `messages` entry through the same reducer as a live `session.message` payload. `{ kind: "reset" }` means the cursor is invalid, stale, belongs to another session, crossed a reset or compaction, or is too far behind; fetch a normal tail page. Catch-up never returns a partial page or continuation: more than 200 raw events or the 1 MB payload budget resets to a tail fetch.
664664
- `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.
665665
- `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.
666-
- `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.
666+
- `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"`. A steer send targets the selected session's current state: the Gateway atomically injects the message into that session's direct active run, or starts a new turn when the session is idle. Activity in descendant subagent sessions never makes the selected session busy for this decision. A client that captured an exact run id may additionally pass `expectedRunId` as a fence; the Gateway binds the injection to that exact run and rejects on mismatch instead of redirecting to a successor. `expectedLeafEntryId` is an independent transcript-branch compare-and-swap for non-steer interactive sends: pass the displayed branch leaf (or deliberate `null` for an authoritative empty transcript) and the send rejects with `details.reason: "active-leaf-changed"` if another client switched transcript branches first; steer sends ignore it.
667667

668668
</Accordion>
669669

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

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -164,11 +164,12 @@ export const ChatSendParamsSchema = closedObject({
164164
systemInputProvenance: Type.Optional(InputProvenanceSchema),
165165
systemProvenanceReceipt: Type.Optional(Type.String()),
166166
suppressCommandInterpretation: Type.Optional(Type.Boolean()),
167-
// Client's believed active-branch leaf entry id. Legacy targetless steering
168-
// requires this immutable fence and may reject; null means an authoritative empty transcript.
167+
// Transcript-branch CAS for non-steer interactive sends: the client's displayed
168+
// branch leaf (null = authoritative empty transcript). Steer sends ignore it;
169+
// the Gateway steers the session's direct run or starts a turn when idle.
169170
expectedLeafEntryId: Type.Optional(Type.Union([NonEmptyString, Type.Null()])),
170-
// Optional for wire compatibility. Modern/durable steer clients should always
171-
// send this exact run precondition so a retry cannot move to a successor run.
171+
// Optional exact-run fence for steer sends; on mismatch the send rejects
172+
// instead of reaching a same-key successor run.
172173
expectedRunId: Type.Optional(NonEmptyString),
173174
expectedSessionRoutingContract: Type.Optional(NonEmptyString),
174175
idempotencyKey: NonEmptyString,

‎src/auto-reply/get-reply-options.types.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -134,8 +134,8 @@ export type GetReplyOptions = {
134134
turnAdoptionLifecycle?: TurnAdoptionLifecycle;
135135
/** Shared lifecycle owner for the current user-turn transcript append. */
136136
userTurnTranscriptRecorder?: UserTurnTranscriptRecorder;
137-
/** Gateway already attempted exact active-run injection for this turn. */
138-
messageInjectionAttempted?: true;
137+
/** Gateway-owned start-or-steer decision for this turn. */
138+
messageInjectionDisposition?: "none" | "accepted" | "rejected";
139139
/** Current user turn is already durable; replay it without appending another copy. */
140140
suppressNextUserMessagePersistence?: boolean;
141141
onReplyStart?: () => Promise<void> | void;

‎src/auto-reply/reply/agent-runner-run.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,7 @@ export async function runReplyAgent(
137137
});
138138
const effectiveShouldSteer = !isHeartbeat && !effectiveResetTriggered && shouldSteer;
139139
const effectiveShouldFollowup = !effectiveResetTriggered && shouldFollowup;
140+
const messageInjectionDisposition = opts?.messageInjectionDisposition ?? "none";
140141
const incomingToolAuthorityFingerprint = resolveFollowupRunToolAuthorityFingerprint(followupRun);
141142
const activeReplyOperation = sessionKey
142143
? (replyRunRegistry.get(sessionKey) ?? providedReplyOperation)
@@ -251,11 +252,20 @@ export async function runReplyAgent(
251252
toolProgressDetail,
252253
});
253254

255+
if (messageInjectionDisposition === "accepted") {
256+
if (replyOperationRunState) {
257+
replyOperationRunState.admission = { status: "accepted", mode: "steer" };
258+
}
259+
releaseAdmissionTicket();
260+
typing.cleanup();
261+
return undefined;
262+
}
263+
254264
if (
255265
effectiveShouldSteer &&
256266
isActive &&
257267
!shouldQueueAuthorityMismatch &&
258-
opts?.messageInjectionAttempted !== true
268+
messageInjectionDisposition === "none"
259269
) {
260270
replyRunState.bindQueueDispositionToRunState(followupRun, replyOperationRunState);
261271
await runActiveReplySteer({

‎src/auto-reply/reply/agent-runner-steer-adoption.ts‎

Lines changed: 80 additions & 114 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,8 @@
11
import { expectDefined } from "@openclaw/normalization-core";
22
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
3-
import { ACTIVE_EMBEDDED_RUNS } from "../../agents/embedded-agent-runner/run-state.js";
4-
import {
5-
formatEmbeddedAgentQueueFailureSummary,
6-
queueEmbeddedAgentMessageWithOutcomeAsync,
7-
} from "../../agents/embedded-agent-runner/runs.js";
83
import { isIngressAdoptionLostError } from "../../channels/message/ingress-drain.js";
94
import { logVerbose } from "../../globals.js";
5+
import { formatErrorMessage } from "../../infra/errors.js";
106
import {
117
scheduleFollowupDrainAfterReplyOperationClear,
128
type RunReplyAgentParams,
@@ -19,7 +15,12 @@ import {
1915
type FollowupRun,
2016
} from "./queue.js";
2117
import type { ReplyOperationRunState } from "./reply-operation-run-state.js";
22-
import { type ReplyOperation, replyRunRegistry } from "./reply-run-registry.js";
18+
import {
19+
beginReplyMessageInjectionTarget,
20+
finalizeReplyMessageInjectionAttempt,
21+
type ReplyOperation,
22+
replyRunRegistry,
23+
} from "./reply-run-registry.js";
2324
import { refreshReplyOperationTyping } from "./reply-run-typing.js";
2425
import { buildChannelSourceTurnId } from "./source-turn-id.js";
2526
import type { TypingSignaler } from "./typing-mode.js";
@@ -66,56 +67,6 @@ function resolveAcceptedSteerRunId(params: ActiveReplySteerParams): string {
6667
);
6768
}
6869

69-
async function finalizeAcceptedSteer(params: {
70-
activeReplyOperation: ReplyOperation | undefined;
71-
activeEmbeddedRunAbort: (() => void) | undefined;
72-
cleanupTyping: () => void;
73-
errorMessage: string | undefined;
74-
onAdopted: (() => void | Promise<void>) | undefined;
75-
replyOperationRunState: ReplyOperationRunState | undefined;
76-
steerSessionId: string;
77-
transcriptCommit: "unconfirmed" | undefined;
78-
}): Promise<"continue" | "stop"> {
79-
const transcriptCommitUnconfirmed = params.transcriptCommit === "unconfirmed";
80-
if (params.replyOperationRunState) {
81-
// Harness acceptance has transferred this turn to the active session.
82-
// Replay after an uncertain receipt could run the same user side effects twice.
83-
params.replyOperationRunState.admission = { status: "accepted", mode: "steer" };
84-
}
85-
params.activeReplyOperation?.recordActivity();
86-
const abortActiveRun = () =>
87-
params.activeReplyOperation?.abortByUser() ?? params.activeEmbeddedRunAbort?.();
88-
if (transcriptCommitUnconfirmed) {
89-
// The runtime accepted this message, but exact cancellation could not find it.
90-
// Preserve at-most-once delivery: abort the uncertain owner without replaying.
91-
abortActiveRun();
92-
logVerbose(
93-
`queue: active session ${params.steerSessionId} accepted steering without transcript confirmation; aborting active run without ingress replay (${params.errorMessage ?? "unknown receipt failure"})`,
94-
);
95-
}
96-
const adoptionBoundary = transcriptCommitUnconfirmed ? "harness acceptance" : "transcript commit";
97-
try {
98-
await params.onAdopted?.();
99-
} catch (error) {
100-
if (isIngressAdoptionLostError(error)) {
101-
abortActiveRun();
102-
logVerbose(
103-
`queue: active session ${params.steerSessionId} adoption lost after ${adoptionBoundary} (${error.code}); aborting steered turn without ingress replay`,
104-
);
105-
params.cleanupTyping();
106-
return "stop";
107-
}
108-
logVerbose(
109-
`queue: active session ${params.steerSessionId} adoption finalizer failed after ${adoptionBoundary}: ${String(error)}`,
110-
);
111-
}
112-
if (transcriptCommitUnconfirmed) {
113-
params.cleanupTyping();
114-
return "stop";
115-
}
116-
return "continue";
117-
}
118-
11970
export async function runActiveReplySteer(params: ActiveReplySteerParams): Promise<"handled"> {
12071
const {
12172
followupRun,
@@ -139,6 +90,11 @@ export async function runActiveReplySteer(params: ActiveReplySteerParams): Promi
13990
? params.providedReplyOperation
14091
: (registeredReplyOperation ?? params.providedReplyOperation);
14192
const steerSessionId = activeReplyOperation?.sessionId ?? followupRun.run.sessionId;
93+
// Capture exact injection authority before parking or awaiting admission.
94+
// A same-key successor must never inherit this turn's steer or abort.
95+
const injectionTarget = replyRunRegistry.resolveCurrentMessageInjectionTarget(
96+
activeReplyOperation?.key ?? queueKey,
97+
);
14298
const parked = parkSteerCandidate(queueKey, followupRun, resolvedQueue, runFollowup);
14399
if (!parked) {
144100
releaseAdmissionTicket();
@@ -159,6 +115,18 @@ export async function runActiveReplySteer(params: ActiveReplySteerParams): Promi
159115
};
160116
scheduleParkedFallback();
161117
releaseAdmissionTicket();
118+
const fallback = async (reason?: string): Promise<"handled"> => {
119+
parked.fallback();
120+
if (replyOperationRunState) {
121+
replyOperationRunState.admission = { status: "accepted", mode: "followup" };
122+
}
123+
if (reason) {
124+
logVerbose(`queue: active session ${steerSessionId} rejected steering (${reason})`);
125+
}
126+
await touchActiveSessionEntry();
127+
typing.cleanup();
128+
return "handled";
129+
};
162130
try {
163131
const admission = await parked.admit();
164132
if (admission === "cancelled") {
@@ -167,71 +135,69 @@ export async function runActiveReplySteer(params: ActiveReplySteerParams): Promi
167135
return "handled";
168136
}
169137
if (admission === "fallback") {
170-
parked.fallback();
171-
if (replyOperationRunState) {
172-
replyOperationRunState.admission = { status: "accepted", mode: "followup" };
173-
}
174-
await touchActiveSessionEntry();
175-
typing.cleanup();
176-
return "handled";
138+
return await fallback();
177139
}
178-
// Channel dispatch normally stamps the route-scoped source id. Internal
179-
// callers can derive the same per-message identity from the prepared turn.
180-
const activeEmbeddedRun = ACTIVE_EMBEDDED_RUNS.get(steerSessionId);
181-
const steerOutcome = await queueEmbeddedAgentMessageWithOutcomeAsync(
182-
steerSessionId,
183-
followupRun.prompt,
184-
{
185-
steeringMode: "all",
186-
isInboundUserMessage: true,
187-
toolAuthorityFingerprint: params.toolAuthorityFingerprint,
188-
...(params.pendingInputAuthorityFingerprint
189-
? { pendingInputAuthorityFingerprint: params.pendingInputAuthorityFingerprint }
190-
: {}),
191-
...(followupRun.images?.length ? { images: followupRun.images } : {}),
192-
...(followupRun.imageOrder?.length ? { imageOrder: followupRun.imageOrder } : {}),
193-
...(followupRun.media?.length ? { media: followupRun.media } : {}),
194-
waitForTranscriptCommit: true,
195-
queueIdentity: resolveAcceptedSteerRunId(params),
196-
abortSignal: resolveFollowupAbortSignal(followupRun),
197-
onQueueAccepted: parked.accepted,
198-
...(resolvedQueue.debounceMs !== undefined ? { debounceMs: resolvedQueue.debounceMs } : {}),
199-
...(followupRun.run.sourceReplyDeliveryMode
200-
? { sourceReplyDeliveryMode: followupRun.run.sourceReplyDeliveryMode }
201-
: {}),
202-
taskSuggestionDeliveryMode: followupRun.run.taskSuggestionDeliveryMode,
203-
...(followupRun.userTurnTranscriptRecorder
204-
? { userTurnTranscriptRecorder: followupRun.userTurnTranscriptRecorder }
205-
: {}),
206-
},
207-
);
208-
if (!steerOutcome.queued) {
209-
parked.fallback();
210-
if (replyOperationRunState) {
211-
replyOperationRunState.admission = { status: "accepted", mode: "followup" };
212-
}
213-
const summary = formatEmbeddedAgentQueueFailureSummary(steerOutcome);
214-
logVerbose(`queue: active session ${steerSessionId} rejected steering injection: ${summary}`);
215-
await touchActiveSessionEntry();
216-
typing.cleanup();
217-
return "handled";
140+
if (!injectionTarget) {
141+
return await fallback("no injectable reply operation");
218142
}
219-
const adoptionDisposition = await finalizeAcceptedSteer({
220-
activeEmbeddedRunAbort: activeEmbeddedRun ? () => activeEmbeddedRun.abort() : undefined,
221-
activeReplyOperation,
222-
cleanupTyping: () => typing.cleanup(),
223-
errorMessage: steerOutcome.errorMessage,
143+
const injectionAttempt = beginReplyMessageInjectionTarget(injectionTarget, followupRun.prompt, {
144+
steeringMode: "all",
145+
isInboundUserMessage: true,
146+
toolAuthorityFingerprint: params.toolAuthorityFingerprint,
147+
...(params.pendingInputAuthorityFingerprint
148+
? { pendingInputAuthorityFingerprint: params.pendingInputAuthorityFingerprint }
149+
: {}),
150+
...(followupRun.images?.length ? { images: followupRun.images } : {}),
151+
...(followupRun.imageOrder?.length ? { imageOrder: followupRun.imageOrder } : {}),
152+
...(followupRun.media?.length ? { media: followupRun.media } : {}),
153+
waitForTranscriptCommit: true,
154+
queueIdentity: resolveAcceptedSteerRunId(params),
155+
abortSignal: resolveFollowupAbortSignal(followupRun),
156+
onQueueAccepted: parked.accepted,
157+
...(resolvedQueue.debounceMs !== undefined ? { debounceMs: resolvedQueue.debounceMs } : {}),
158+
...(followupRun.run.sourceReplyDeliveryMode
159+
? { sourceReplyDeliveryMode: followupRun.run.sourceReplyDeliveryMode }
160+
: {}),
161+
taskSuggestionDeliveryMode: followupRun.run.taskSuggestionDeliveryMode,
162+
...(followupRun.userTurnTranscriptRecorder
163+
? { userTurnTranscriptRecorder: followupRun.userTurnTranscriptRecorder }
164+
: {}),
165+
});
166+
const finalization = await finalizeReplyMessageInjectionAttempt({
167+
attempt: injectionAttempt,
168+
target: injectionTarget,
169+
inboundAudio: followupRun.currentInboundAudio === true,
170+
onAccepted: () => {
171+
if (replyOperationRunState) {
172+
replyOperationRunState.admission = { status: "accepted", mode: "steer" };
173+
}
174+
},
224175
onAdopted: () => admitFollowupRunLifecycle(followupRun),
225-
replyOperationRunState,
226-
steerSessionId,
227-
transcriptCommit: steerOutcome.transcriptCommit,
176+
shouldAbortOnAdoptionError: isIngressAdoptionLostError,
228177
});
178+
if (finalization.status === "rejected") {
179+
return await fallback(finalization.outcome.reason);
180+
}
229181
parked.consume();
230-
if (adoptionDisposition === "stop") {
182+
const transcriptCommitUnconfirmed =
183+
finalization.outcome.result?.transcriptCommit === "unconfirmed";
184+
if (finalization.aborted) {
185+
if (replyOperationRunState) {
186+
replyOperationRunState.messageInjectionAborted = true;
187+
}
188+
const reason = transcriptCommitUnconfirmed
189+
? (finalization.outcome.result?.errorMessage ?? "transcript commitment unconfirmed")
190+
: `adoption lost: ${formatErrorMessage(finalization.adoptionError)}`;
191+
logVerbose(
192+
`queue: active session ${steerSessionId} aborted exact steered target without replay (${reason})`,
193+
);
194+
typing.cleanup();
231195
return "handled";
232196
}
233-
if (followupRun.currentInboundAudio === true) {
234-
activeReplyOperation?.markAcceptedSteeredInboundAudio();
197+
if (finalization.adoptionError) {
198+
logVerbose(
199+
`queue: active session ${steerSessionId} adoption finalizer failed: ${formatErrorMessage(finalization.adoptionError)}`,
200+
);
235201
}
236202
if (activeReplyOperation) {
237203
await refreshReplyOperationTyping(activeReplyOperation, {

0 commit comments

Comments
 (0)