Skip to content

Commit c500ab7

Browse files
authored
fix: preserve steering after tool-authority checks (#123549)
* fix: preserve authority-bound steering paths * test: preserve heartbeat exports in execution mocks
1 parent 8e398d9 commit c500ab7

9 files changed

Lines changed: 63 additions & 14 deletions

‎src/agents/embedded-agent-runner/run/attempt-queue-message.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -346,7 +346,13 @@ export async function steerActiveSessionWithOptionalDeliveryWait(
346346
log.warn(`failed to cancel ask_user before image steering: ${String(error)}`);
347347
}
348348
}
349-
if (await claimEmbeddedPendingUserInputAnswer(text, options, sessionKey)) {
349+
// Non-user steering must install its transcript listener synchronously; an
350+
// unnecessary await here lets callers emit before subscribe() runs.
351+
if (
352+
isInboundUserMessage &&
353+
isPlainTextAnswer &&
354+
(await claimEmbeddedPendingUserInputAnswer(text, options, sessionKey))
355+
) {
350356
options?.onQueueAccepted?.(true);
351357
return;
352358
}

‎src/auto-reply/reply/agent-runner-execution-cli-sessions.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -193,13 +193,13 @@ describe("executeAgentTurn: CLI session routing", () => {
193193
expect(state.runCliAgentMock).toHaveBeenCalledOnce();
194194
expectMockCallArgFields(state.runCliAgentMock, 0, "CLI runtime", {
195195
sessionKey: "main",
196-
agentId: "agent",
196+
agentId: "main",
197197
sessionId: "session",
198198
suppressNextUserMessagePersistence: false,
199199
persistAssistantTranscript: true,
200200
storePath: "/tmp/sessions.json",
201201
sessionTarget: {
202-
agentId: "agent",
202+
agentId: "main",
203203
sessionId: "session",
204204
sessionKey: "main",
205205
storePath: "/tmp/sessions.json",

‎src/auto-reply/reply/agent-runner-execution.test-support.ts‎

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -236,13 +236,19 @@ vi.mock("../../utils/message-channel.js", async () => ({
236236
isInternalMessageChannel: (value: unknown) => state.isInternalMessageChannelMock(value),
237237
}));
238238

239-
vi.mock("../heartbeat.js", () => ({
240-
stripHeartbeatToken: (text: string) => ({
241-
text,
242-
didStrip: false,
243-
shouldSkip: false,
244-
}),
245-
}));
239+
vi.mock("../heartbeat.js", async () => {
240+
const actual = await vi.importActual<typeof import("../heartbeat.js")>("../heartbeat.js");
241+
return {
242+
DEFAULT_HEARTBEAT_EVERY: actual.DEFAULT_HEARTBEAT_EVERY,
243+
HEARTBEAT_CRON_TASK_GUIDANCE: actual.HEARTBEAT_CRON_TASK_GUIDANCE,
244+
resolveHeartbeatPromptCore: actual.resolveHeartbeatPromptCore,
245+
stripHeartbeatToken: (text: string) => ({
246+
text,
247+
didStrip: false,
248+
shouldSkip: false,
249+
}),
250+
};
251+
});
246252

247253
vi.mock("./current-turn-images.js", () => ({
248254
resolveCurrentTurnImages: (params: unknown) => state.resolveCurrentTurnImagesMock(params),
@@ -451,7 +457,7 @@ export function createFollowupRun(): FollowupRun {
451457
summaryLine: "hello",
452458
enqueuedAt: Date.now(),
453459
run: {
454-
agentId: "agent",
460+
agentId: "main",
455461
agentDir: "/tmp/agent",
456462
sessionId: "session",
457463
sessionKey: "main",

‎src/auto-reply/reply/agent-runner.final-media-runreplyagent.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,7 @@ function createReplyOperation(): ReplyOperation {
116116
lastActivityAtMs: Date.now(),
117117
recordActivity: vi.fn(),
118118
setPhase: vi.fn(),
119+
bindToolAuthorityFingerprint: vi.fn(),
119120
freezeAbort: vi.fn(),
120121
fail: vi.fn(),
121122
complete: vi.fn(),

‎src/auto-reply/reply/agent-runner.media-paths.test.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,11 @@ const resolveOutboundAttachmentFromUrlMock = vi.fn();
5151
const createReplyMediaContextRuntimeMock = vi.fn();
5252
const EXPECTED_STEER_QUEUE_IDENTITY =
5353
"channel-user:v1:6f3f31084a7a2a6ff17176c0c16682e64d9f21301f64ff7e5bf1173b54fadc33";
54+
const TEST_TOOL_AUTHORITY_FINGERPRINT = "test-tool-authority";
55+
56+
vi.mock("./reply-tool-authority.js", () => ({
57+
resolveFollowupRunToolAuthorityFingerprint: () => "test-tool-authority",
58+
}));
5459

5560
vi.mock("../../agents/model-fallback-runner.js", () => ({
5661
runWithModelFallback: (params: {
@@ -292,10 +297,14 @@ const { runReplyAgent } = await import("./agent-runner.js");
292297
function createReplyOperation(): ReplyOperation {
293298
return {
294299
result: undefined,
300+
toolAuthorityFingerprint: TEST_TOOL_AUTHORITY_FINGERPRINT,
301+
abortSignal: new AbortController().signal,
295302
startedAtMs: Date.now(),
296303
lastActivityAtMs: Date.now(),
297304
recordActivity: vi.fn(),
298305
setPhase: vi.fn(),
306+
bindToolAuthorityFingerprint: vi.fn(),
307+
bindToolAuthorityRoute: vi.fn(),
299308
freezeAbort: vi.fn(),
300309
fail: vi.fn(),
301310
complete: vi.fn(),
@@ -486,6 +495,7 @@ describe("runReplyAgent media path normalization", () => {
486495
queueIdentity: EXPECTED_STEER_QUEUE_IDENTITY,
487496
onQueueAccepted: parkedSteerAcceptedMock,
488497
taskSuggestionDeliveryMode: "gateway",
498+
toolAuthorityFingerprint: TEST_TOOL_AUTHORITY_FINGERPRINT,
489499
},
490500
);
491501
expect(enqueueFollowupRunMock).not.toHaveBeenCalled();
@@ -534,6 +544,7 @@ describe("runReplyAgent media path normalization", () => {
534544
images,
535545
media: followupRun.media,
536546
taskSuggestionDeliveryMode: undefined,
547+
toolAuthorityFingerprint: TEST_TOOL_AUTHORITY_FINGERPRINT,
537548
},
538549
);
539550
expect(enqueueFollowupRunMock).not.toHaveBeenCalled();
@@ -580,6 +591,7 @@ describe("runReplyAgent media path normalization", () => {
580591
resetTriggered: false,
581592
});
582593
operation.setPhase("running");
594+
operation.bindToolAuthorityFingerprint(TEST_TOOL_AUTHORITY_FINGERPRINT);
583595
expect(operation.acceptedSteeredInboundAudio).toBe(false);
584596
queueEmbeddedAgentMessageWithOutcomeAsyncMock.mockImplementation(async (sessionId: string) => ({
585597
queued: true,
@@ -615,6 +627,7 @@ describe("runReplyAgent media path normalization", () => {
615627
queueIdentity: EXPECTED_STEER_QUEUE_IDENTITY,
616628
onQueueAccepted: parkedSteerAcceptedMock,
617629
taskSuggestionDeliveryMode: undefined,
630+
toolAuthorityFingerprint: TEST_TOOL_AUTHORITY_FINGERPRINT,
618631
},
619632
);
620633
expect(enqueueFollowupRunMock).not.toHaveBeenCalled();

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,8 @@ export type ReplyMessageInjectionTarget = {
9696
readonly identity: "leaf" | "run";
9797
readonly runId?: string;
9898
readonly originatingLeafEntryId: string | null | undefined;
99+
/** Tool authority captured with the exact active operation. */
100+
readonly toolAuthorityFingerprint?: string;
99101
};
100102

101103
type ReplyMessageInjectionRejectionReason =

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,9 @@ export const replyRunRegistry: ReplyRunRegistry = {
123123
identity: normalizeOptionalString(expectedRunId) ? "run" : "leaf",
124124
...(resolved.backend.runId ? { runId: resolved.backend.runId } : {}),
125125
originatingLeafEntryId,
126+
...(operation?.toolAuthorityFingerprint
127+
? { toolAuthorityFingerprint: operation.toolAuthorityFingerprint }
128+
: {}),
126129
};
127130
return target;
128131
},

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

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,13 +29,16 @@ import type { GatewayRequestContext } from "./types.js";
2929
/** Captures the prepared request data used by both pre-ACK and detached injection attempts. */
3030
export function createChatSendMessageInjectionStarter(params: {
3131
target: ReplyMessageInjectionTarget | undefined;
32-
request: Pick<NormalizedChatSendRequest, "p" | "rawMessage" | "supportsTaskSuggestions">;
32+
request: Pick<
33+
NormalizedChatSendRequest,
34+
"p" | "rawMessage" | "supportsTaskSuggestions" | "toolBindings"
35+
>;
3336
session: Pick<PreparedChatSendSession, "cfg" | "entry">;
3437
turn: ReturnType<typeof prepareChatSendUserTurn>;
3538
imageOrder: ReplyBackendQueueMessageOptions["imageOrder"];
3639
userTurnTranscriptRecorder: ReplyBackendQueueMessageOptions["userTurnTranscriptRecorder"];
3740
}) {
38-
const { p, rawMessage, supportsTaskSuggestions } = params.request;
41+
const { p, rawMessage, supportsTaskSuggestions, toolBindings } = params.request;
3942
const { cfg, entry } = params.session;
4043
const { ctx, isInternalTextSlashCommandTurn, replyOptionImages, replyOptionMedia } = params.turn;
4144
return (): ReplyMessageInjectionAttempt | undefined => {
@@ -57,6 +60,11 @@ export function createChatSendMessageInjectionStarter(params: {
5760
{
5861
steeringMode: "all",
5962
isInboundUserMessage: true,
63+
// chat.send cannot alter per-turn tool policy. Preserve the captured
64+
// active authority only when no request-scoped tool bindings are present.
65+
...(toolBindings === undefined && params.target.toolAuthorityFingerprint
66+
? { toolAuthorityFingerprint: params.target.toolAuthorityFingerprint }
67+
: {}),
6068
...(replyOptionImages?.length ? { images: replyOptionImages } : {}),
6169
...(params.imageOrder?.length ? { imageOrder: params.imageOrder } : {}),
6270
...(replyOptionMedia?.length ? { media: replyOptionMedia } : {}),

‎src/gateway/server-methods/chat.directive-tags.test.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ import { setReplyPayloadMetadata } from "../../auto-reply/reply-payload.js";
2626
import { getTotalPendingReplies } from "../../auto-reply/reply/dispatcher-registry.js";
2727
import { markInboundContextLabel } from "../../auto-reply/reply/inbound-context-marker.js";
2828
import {
29-
replyRunRegistry,
29+
replyRunRegistry as baseReplyRunRegistry,
3030
type ReplyBackendQueueMessageOptions,
3131
} from "../../auto-reply/reply/reply-run-registry.js";
3232
import type { MsgContext } from "../../auto-reply/templating.js";
@@ -62,6 +62,16 @@ type ProjectedDispatchParams = Parameters<
6262
typeof import("../../auto-reply/dispatch.js").dispatchInboundMessageWithProjectedDispatcher
6363
>[0];
6464

65+
const TEST_TOOL_AUTHORITY_FINGERPRINT = "test-tool-authority";
66+
const replyRunRegistry = {
67+
...baseReplyRunRegistry,
68+
begin(...args: Parameters<typeof baseReplyRunRegistry.begin>) {
69+
const operation = baseReplyRunRegistry.begin(...args);
70+
operation.bindToolAuthorityFingerprint(TEST_TOOL_AUTHORITY_FINGERPRINT);
71+
return operation;
72+
},
73+
};
74+
6575
const mockState = vi.hoisted(() => ({
6676
config: {} as Record<string, unknown>,
6777
storePath: "",

0 commit comments

Comments
 (0)