Skip to content

Commit 4f98126

Browse files
committed
fix(steering): preserve exact targets through replies
1 parent 5e50b11 commit 4f98126

9 files changed

Lines changed: 354 additions & 50 deletions

‎src/auto-reply/reply/reply-run-registry.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ export type ReplyMessageInjectionOutcome =
116116
| { status: "accepted"; result?: ReplyBackendQueueMessageResult }
117117
| { status: "rejected"; reason: ReplyMessageInjectionRejectionReason; errorMessage?: string };
118118

119-
type ReplyMessageInjectionAttempt = {
119+
export type ReplyMessageInjectionAttempt = {
120120
/** Native run identity captured with the opaque operation target. */
121121
targetRunId: string | undefined;
122122
/** Leaf-bound compatibility must reject before ACK instead of falling through. */

‎src/gateway/server-methods/chat-send-dispatch-errors.ts‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { setGatewayDedupeEntry } from "./agent-job.js";
1010
import { buildAbortedChatSendPayload } from "./chat-abort-authorization.js";
1111
import { broadcastChatError, broadcastChatFinal } from "./chat-broadcast.js";
1212
import type { AdmittedChatSend } from "./chat-send-admission.js";
13+
import { ACTIVE_RUN_CHANGED_ERROR_REASON } from "./chat-send-pre-admission.js";
1314
import type { PreparedChatSendSession } from "./chat-send-session.js";
1415
import { hasTrackedActiveSessionRun } from "./session-active-runs.js";
1516
import { emitSessionsChanged } from "./session-change-event.js";
@@ -115,6 +116,11 @@ export function createChatSendDispatchErrorLifecycle(params: {
115116

116117
const handleError = async (err: unknown) => {
117118
const errorMessage = String(err);
119+
const activeRunChanged =
120+
err instanceof Error && err.message === ACTIVE_RUN_CHANGED_ERROR_REASON;
121+
const visibleErrorMessage = activeRunChanged
122+
? "active run changed; review and retry"
123+
: errorMessage;
118124
const queuedFollowupEnqueued = isQueuedFollowupEnqueued();
119125
if (queuedFollowupEnqueued) {
120126
context.logGateway.warn(
@@ -239,15 +245,19 @@ export function createChatSendDispatchErrorLifecycle(params: {
239245
) {
240246
pendingDispatchLifecycleError = {
241247
endedAt: Date.now(),
242-
error: errorMessage,
248+
error: visibleErrorMessage,
243249
sessionId: activeRunAbort.entry?.sessionId ?? backingSessionId ?? clientRunId,
244250
startedAt: activeRunAbort.entry?.startedAtMs ?? now,
245251
};
246252
}
247253
if (!agentTerminalPersistenceOwnedAtDispatchReject) {
248254
// The lifecycle owner may have already cached its authoritative
249255
// terminal; a late dispatch error must not replace that replay result.
250-
const error = errorShape(ErrorCodes.UNAVAILABLE, errorMessage);
256+
const error = activeRunChanged
257+
? errorShape(ErrorCodes.INVALID_REQUEST, visibleErrorMessage, {
258+
details: { reason: ACTIVE_RUN_CHANGED_ERROR_REASON },
259+
})
260+
: errorShape(ErrorCodes.UNAVAILABLE, visibleErrorMessage);
251261
setGatewayDedupeEntry({
252262
dedupe: context.dedupe,
253263
key: `chat:${clientRunId}`,
@@ -257,7 +267,7 @@ export function createChatSendDispatchErrorLifecycle(params: {
257267
payload: {
258268
runId: clientRunId,
259269
status: "error" as const,
260-
summary: errorMessage,
270+
summary: visibleErrorMessage,
261271
},
262272
error,
263273
},
@@ -267,7 +277,7 @@ export function createChatSendDispatchErrorLifecycle(params: {
267277
runId: clientRunId,
268278
sessionKey,
269279
agentId,
270-
errorMessage,
280+
errorMessage: visibleErrorMessage,
271281
});
272282
}
273283
};

‎src/gateway/server-methods/chat-send-handler.ts‎

Lines changed: 39 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,6 @@ import { resolveDefaultAgentId } from "../../agents/agent-scope.js";
99
import { resolveProviderIdForAuth } from "../../agents/provider-auth-aliases.js";
1010
import { createAgentRunRestartAbortError } from "../../agents/run-termination.js";
1111
import { dispatchInboundMessageWithProjectedDispatcher } from "../../auto-reply/dispatch.js";
12-
import { resolveQueueSettings } from "../../auto-reply/reply/queue/settings-runtime.js";
13-
import { beginReplyMessageInjectionTarget } from "../../auto-reply/reply/reply-run-registry.js";
1412
import { getAgentEventLifecycleGeneration } from "../../infra/agent-events.js";
1513
import {
1614
emitDiagnosticsTimelineEvent,
@@ -38,8 +36,12 @@ import {
3836
createChatSendDispatchErrorLifecycle,
3937
handleChatSendSetupError,
4038
} from "./chat-send-dispatch-errors.js";
41-
import { finalizeAcceptedChatSendMessageInjection } from "./chat-send-message-injection.js";
39+
import {
40+
beginChatSendMessageInjection,
41+
finalizeAcceptedChatSendMessageInjection,
42+
} from "./chat-send-message-injection.js";
4243
import { finalizeChatSendNonAgentReplies } from "./chat-send-nonagent-finalization.js";
44+
import { ACTIVE_RUN_CHANGED_ERROR_REASON } from "./chat-send-pre-admission.js";
4345
import {
4446
applyChatSendReplyContextFields,
4547
resolveChatSendReplyContext,
@@ -228,39 +230,35 @@ export async function handleChatSend(
228230
logGateway: context.logGateway,
229231
userTurn,
230232
});
231-
const queueSettings = resolveQueueSettings({
232-
cfg,
233-
channel: ctx.Provider,
234-
sessionEntry: entry,
235-
inlineMode: p.queueMode,
236-
});
237-
const messageInjectionAttempt =
238-
messageInjectionTarget && !isInternalTextSlashCommandTurn && !p.replyToId
239-
? beginReplyMessageInjectionTarget(
240-
messageInjectionTarget,
241-
ctx.BodyForAgent ?? ctx.Body ?? rawMessage,
242-
{
243-
steeringMode: "all",
244-
isInboundUserMessage: true,
245-
...(replyOptionImages?.length ? { images: replyOptionImages } : {}),
246-
...(imageOrder.length > 0 ? { imageOrder } : {}),
247-
...(replyOptionMedia?.length ? { media: replyOptionMedia } : {}),
248-
waitForTranscriptCommit: true,
249-
...(queueSettings.debounceMs !== undefined
250-
? { debounceMs: queueSettings.debounceMs }
251-
: {}),
252-
taskSuggestionDeliveryMode: supportsTaskSuggestions ? "gateway" : undefined,
253-
userTurnTranscriptRecorder: userTurnRecorder,
233+
const beginCapturedMessageInjection = () =>
234+
messageInjectionTarget && !isInternalTextSlashCommandTurn
235+
? beginChatSendMessageInjection({
236+
target: messageInjectionTarget,
237+
text: ctx.BodyForAgent ?? ctx.Body ?? rawMessage,
238+
replyContext: p.replyToId
239+
? { body: ctx.BodyForAgent ?? ctx.Body ?? rawMessage, cfg, ctx, sessionEntry: entry }
240+
: undefined,
241+
images: replyOptionImages,
242+
imageOrder,
243+
media: replyOptionMedia,
244+
queueSettings: {
245+
cfg,
246+
channel: ctx.Provider,
247+
sessionEntry: entry,
248+
inlineMode: p.queueMode,
254249
},
255-
)
250+
taskSuggestionDeliveryMode: supportsTaskSuggestions ? "gateway" : undefined,
251+
userTurnTranscriptRecorder: userTurnRecorder,
252+
})
256253
: undefined;
257-
if (messageInjectionAttempt) {
254+
let messageInjectionAttempt = p.replyToId ? undefined : beginCapturedMessageInjection();
255+
if (messageInjectionTarget && !isInternalTextSlashCommandTurn) {
258256
// Accepted injection never consumes plugin-bound media, but the shared
259257
// persistence promise still needs a rejection observer.
260258
void pluginBoundMediaPromise.catch(() => undefined);
261-
if (messageInjectionAttempt.rejectBeforeAck) {
262-
return admitted.value.rejectActiveLeafChanged();
263-
}
259+
}
260+
if (messageInjectionAttempt?.rejectBeforeAck) {
261+
return admitted.value.rejectActiveLeafChanged();
264262
}
265263

266264
const serverTiming = shouldIncludeChatSendAckServerTiming(clientInfo)
@@ -393,6 +391,10 @@ export async function handleChatSend(
393391
measureDiagnosticsTimelineSpan(
394392
"gateway.chat_send.dispatch_inbound",
395393
async () => {
394+
if (replyContextFieldsPromise) {
395+
applyChatSendReplyContextFields(ctx, await replyContextFieldsPromise);
396+
messageInjectionAttempt = beginCapturedMessageInjection();
397+
}
396398
if (messageInjectionAttempt) {
397399
const outcome = await messageInjectionAttempt.outcome;
398400
if (outcome.status === "accepted") {
@@ -412,11 +414,11 @@ export async function handleChatSend(
412414
counts: { tool: 0, block: 0, final: 0 },
413415
};
414416
}
417+
if (p.replyToId) {
418+
throw new Error(ACTIVE_RUN_CHANGED_ERROR_REASON);
419+
}
415420
}
416421
applyChatSendManagedMedia(ctx, await pluginBoundMediaPromise);
417-
if (replyContextFieldsPromise) {
418-
applyChatSendReplyContextFields(ctx, await replyContextFieldsPromise);
419-
}
420422
const dispatchResult = await dispatchInboundMessageWithProjectedDispatcher({
421423
ctx,
422424
cfg,
@@ -517,7 +519,9 @@ export async function handleChatSend(
517519
fastModeOverride: p.fastMode,
518520
queueModeOverride: p.queueMode,
519521
userTurnTranscriptRecorder: userTurnRecorder,
520-
...(messageInjectionAttempt ? { messageInjectionAttempted: true as const } : {}),
522+
...(messageInjectionTarget && !isInternalTextSlashCommandTurn
523+
? { messageInjectionAttempted: true as const }
524+
: {}),
521525
...(restartSafeAdmission ? { suppressNextUserMessagePersistence: true } : {}),
522526
fastModeAutoOnSecondsOverride: p.fastAutoOnSeconds,
523527
onAgentRunStart: (runId) => {

‎src/gateway/server-methods/chat-send-message-injection.ts‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,13 @@ import { emitInboundMessageAuditTerminal } from "../../auto-reply/reply/dispatch
33
import { finalizeInboundContext } from "../../auto-reply/reply/inbound-context.js";
44
import { hasInboundAudio } from "../../auto-reply/reply/inbound-media.js";
55
import { emitMessageReceivedHooks } from "../../auto-reply/reply/message-received-hooks.js";
6+
import { resolveQueueSettings } from "../../auto-reply/reply/queue/settings-runtime.js";
67
import {
78
abortReplyMessageInjectionTarget,
9+
beginReplyMessageInjectionTarget,
810
recordAcceptedReplyMessageInjectionTarget,
11+
type ReplyBackendQueueMessageOptions,
12+
type ReplyMessageInjectionAttempt,
913
type ReplyMessageInjectionOutcome,
1014
type ReplyMessageInjectionTarget,
1115
} from "../../auto-reply/reply/reply-run-registry.js";
@@ -16,9 +20,40 @@ import { logMessageProcessed, logMessageReceived } from "../../logging/diagnosti
1620
import { getGlobalHookRunner } from "../../plugins/hook-runner-global.js";
1721
import { setGatewayDedupeEntry } from "./agent-job.js";
1822
import { broadcastChatFinal } from "./chat-broadcast.js";
23+
import { buildChatSendReplyInjectionText } from "./chat-send-reply-context.js";
1924
import type { PreparedChatSendSession } from "./chat-send-session.js";
2025
import type { GatewayRequestContext } from "./types.js";
2126

27+
/** Starts injection with the exact admission-captured target and prepared turn data. */
28+
export function beginChatSendMessageInjection(params: {
29+
target: ReplyMessageInjectionTarget;
30+
text: string;
31+
replyContext?: Parameters<typeof buildChatSendReplyInjectionText>[0];
32+
images: ReplyBackendQueueMessageOptions["images"];
33+
imageOrder: ReplyBackendQueueMessageOptions["imageOrder"];
34+
media: ReplyBackendQueueMessageOptions["media"];
35+
queueSettings: Parameters<typeof resolveQueueSettings>[0];
36+
taskSuggestionDeliveryMode: ReplyBackendQueueMessageOptions["taskSuggestionDeliveryMode"];
37+
userTurnTranscriptRecorder: ReplyBackendQueueMessageOptions["userTurnTranscriptRecorder"];
38+
}): ReplyMessageInjectionAttempt {
39+
const { debounceMs } = resolveQueueSettings(params.queueSettings);
40+
return beginReplyMessageInjectionTarget(
41+
params.target,
42+
params.replyContext ? buildChatSendReplyInjectionText(params.replyContext) : params.text,
43+
{
44+
steeringMode: "all",
45+
isInboundUserMessage: true,
46+
...(params.images?.length ? { images: params.images } : {}),
47+
...(params.imageOrder?.length ? { imageOrder: params.imageOrder } : {}),
48+
...(params.media?.length ? { media: params.media } : {}),
49+
waitForTranscriptCommit: true,
50+
...(debounceMs !== undefined ? { debounceMs } : {}),
51+
taskSuggestionDeliveryMode: params.taskSuggestionDeliveryMode,
52+
userTurnTranscriptRecorder: params.userTurnTranscriptRecorder,
53+
},
54+
);
55+
}
56+
2257
/** Finish an irrevocably accepted steer without entering reply dispatch. */
2358
export async function finalizeAcceptedChatSendMessageInjection(params: {
2459
context: GatewayRequestContext;

‎src/gateway/server-methods/chat-send-reply-context.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
// Discord path (reply_to_id + "Reply target of current user message" block).
44
import { asOptionalRecord } from "@openclaw/normalization-core/record-coerce";
55
import { truncateUtf16Safe } from "@openclaw/normalization-core/utf16-slice";
6+
import { resolveEnvelopeFormatOptions } from "../../auto-reply/envelope.js";
7+
import { buildInboundUserContextPrefix } from "../../auto-reply/reply/inbound-meta.js";
68
import type { MsgContext } from "../../auto-reply/templating.js";
79
import type { OpenClawConfig } from "../../config/types.openclaw.js";
810
import { sanitizeAssistantVisibleTextWithProfile } from "../../shared/text/assistant-visible-text.js";
@@ -21,6 +23,21 @@ type ChatSendReplyContextFields = Partial<
2123
Pick<MsgContext, "ReplyToId" | "ReplyToBody" | "ReplyToSender">
2224
>;
2325

26+
/** Adds hydrated reply metadata to the direct-injection user prompt. */
27+
export function buildChatSendReplyInjectionText(params: {
28+
body: string;
29+
cfg: OpenClawConfig;
30+
ctx: MsgContext;
31+
sessionEntry?: Parameters<typeof buildInboundUserContextPrefix>[2];
32+
}): string {
33+
const prefix = buildInboundUserContextPrefix(
34+
params.ctx,
35+
resolveEnvelopeFormatOptions(params.cfg),
36+
params.sessionEntry,
37+
);
38+
return prefix ? `${prefix}\n\n${params.body}` : params.body;
39+
}
40+
2441
function extractReplyTargetText(message: unknown): string | undefined {
2542
const entry = asOptionalRecord(message);
2643
if (!entry) {

0 commit comments

Comments
 (0)