Skip to content

Commit d54d0b4

Browse files
authored
refactor(agents): simplify embedded subscription and block state (#121896)
* refactor(agents): remove subscription params identity seam * refactor(agents): remove dead attempt fallback flag * refactor(agents): inline attempt fast mode type * refactor(agents): derive before-agent block state from owner * refactor(agents): localize finalize revision cap * fix(agents): preserve public harness attempt contract
1 parent ea06d72 commit d54d0b4

11 files changed

Lines changed: 116 additions & 146 deletions

‎src/agents/embedded-agent-runner/run/attempt-execution-phase.test.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,6 @@ function createFixture() {
2626
const result = { messages: [] };
2727
const preparedStreamRuntime = { stream: { queueHandle: { kind: "embedded" } } };
2828
const state = {
29-
beforeAgentRunBlocked: false,
3029
beforeAgentRunBlockedBy: undefined,
3130
terminal: { kind: "ok" as const },
3231
trajectoryEndRecorded: false,

‎src/agents/embedded-agent-runner/run/attempt-execution-settle.test.ts‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,6 @@ function createFixture() {
5858
systemPromptText: "system prompt",
5959
};
6060
const state: SettledInput["state"] = {
61-
beforeAgentRunBlocked: false,
6261
beforeAgentRunBlockedBy: undefined,
6362
terminal: { kind: "ok" },
6463
trajectoryEndRecorded: false,
@@ -258,7 +257,6 @@ describe("runEmbeddedAttemptSettledPhase", () => {
258257
]);
259258
expect(fixture.state).toEqual(
260259
expect.objectContaining({
261-
beforeAgentRunBlocked: true,
262260
beforeAgentRunBlockedBy: "before_agent",
263261
terminal: { kind: "ok" },
264262
trajectoryEndRecorded: true,

‎src/agents/embedded-agent-runner/run/attempt-execution-types.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@ type StreamRuntimeInput = Parameters<typeof prepareEmbeddedAttemptStreamRuntime>
2222
type AttemptContextEngine = NonNullable<StreamRuntimeInput["history"]["activeContextEngine"]>;
2323

2424
export type EmbeddedAttemptExecutionState = {
25-
beforeAgentRunBlocked: boolean;
2625
beforeAgentRunBlockedBy: string | undefined;
2726
terminal: AgentRunAttemptTerminal;
2827
trajectoryEndRecorded: boolean;

‎src/agents/embedded-agent-runner/run/attempt-session-cleanup.test.ts‎

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,6 @@ function createInput(overrides: Record<string, unknown> = {}) {
4848
timedOutDuringToolExecution: false,
4949
timedOutByRunBudget: false,
5050
promptError: null,
51-
beforeAgentRunBlocked: false,
5251
};
5352
return {
5453
attempt,
@@ -98,6 +97,28 @@ describe("cleanupEmbeddedAttemptSessionPhase", () => {
9897
expect(input.emitDiagnosticRunCompleted).toHaveBeenCalledWith("completed", null, undefined);
9998
});
10099

100+
it("emits the before-agent blocked status and owner", async () => {
101+
const input = createInput({
102+
readState: () => ({
103+
aborted: false,
104+
externalAbort: false,
105+
timedOut: false,
106+
idleTimedOut: false,
107+
timedOutDuringCompaction: false,
108+
timedOutDuringToolExecution: false,
109+
timedOutByRunBudget: false,
110+
promptError: null,
111+
beforeAgentRunBlockedBy: "before_agent",
112+
}),
113+
});
114+
115+
await cleanupEmbeddedAttemptSessionPhase(input as never);
116+
117+
expect(input.emitDiagnosticRunCompleted).toHaveBeenCalledWith("blocked", null, {
118+
blockedBy: "before_agent",
119+
});
120+
});
121+
101122
it("re-reads abort state after trajectory flushing", async () => {
102123
let aborted = false;
103124
hoisted.flushEmbeddedAttemptTrajectoryRecorder.mockImplementation(async () => {
@@ -113,7 +134,6 @@ describe("cleanupEmbeddedAttemptSessionPhase", () => {
113134
timedOutDuringToolExecution: false,
114135
timedOutByRunBudget: false,
115136
promptError: aborted ? new Error("request aborted") : null,
116-
beforeAgentRunBlocked: false,
117137
}),
118138
});
119139

‎src/agents/embedded-agent-runner/run/attempt-session-settle.ts‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,6 @@ type CleanupEmbeddedAttemptSessionInput = {
9191
timedOutDuringToolExecution: boolean;
9292
timedOutByRunBudget: boolean;
9393
promptError: unknown;
94-
beforeAgentRunBlocked: boolean;
9594
beforeAgentRunBlockedBy?: string;
9695
};
9796
};
@@ -175,10 +174,11 @@ export async function cleanupEmbeddedAttemptSessionPhase(
175174

176175
const finalState = input.readState();
177176
const cleanupFailure = cleanupError;
177+
const beforeAgentRunBlocked = finalState.beforeAgentRunBlockedBy !== undefined;
178178
input.emitDiagnosticRunCompleted?.(
179179
cleanupFailure
180180
? "error"
181-
: finalState.beforeAgentRunBlocked
181+
: beforeAgentRunBlocked
182182
? "blocked"
183183
: finalState.promptError
184184
? "error"
@@ -189,9 +189,7 @@ export async function cleanupEmbeddedAttemptSessionPhase(
189189
? "aborted"
190190
: "completed",
191191
cleanupFailure ?? finalState.promptError,
192-
finalState.beforeAgentRunBlocked
193-
? { blockedBy: finalState.beforeAgentRunBlockedBy ?? "before_agent_run" }
194-
: undefined,
192+
beforeAgentRunBlocked ? { blockedBy: finalState.beforeAgentRunBlockedBy } : undefined,
195193
);
196194

197195
if (!cleanupFailure) {

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

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -292,7 +292,6 @@ export async function runEmbeddedAttemptSettledPhase(
292292
finalPromptText = prompt;
293293
},
294294
markBeforeAgentRunBlocked: (outcome) => {
295-
state.beforeAgentRunBlocked = true;
296295
state.beforeAgentRunBlockedBy = outcome.blockedBy;
297296
},
298297
markYieldAborted: () => {

‎src/agents/embedded-agent-runner/run/attempt-stream-prepare.test.ts‎

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@ import {
1414
} from "../../tool-search.js";
1515

1616
const mocks = vi.hoisted(() => ({
17-
buildSubscriptionParams: vi.fn(),
1817
clearActiveRun: vi.fn(),
1918
notifyToolActivity: vi.fn(),
2019
runBeforeFinalizeHook: vi.fn(),
@@ -29,9 +28,6 @@ vi.mock("../runs.js", () => ({
2928
clearActiveEmbeddedRun: mocks.clearActiveRun,
3029
setActiveEmbeddedRun: mocks.setActiveRun,
3130
}));
32-
vi.mock("./attempt-subscription-cleanup.js", () => ({
33-
buildEmbeddedSubscriptionParams: mocks.buildSubscriptionParams,
34-
}));
3531
vi.mock("./tool-activity-heartbeat.js", () => ({
3632
notifyToolActivity: mocks.notifyToolActivity,
3733
}));
@@ -104,7 +100,6 @@ function prepareCatalogExecutor(
104100
describe("prepareEmbeddedAttemptStream", () => {
105101
beforeEach(() => {
106102
vi.clearAllMocks();
107-
mocks.buildSubscriptionParams.mockImplementation((params) => params);
108103
mocks.subscribe.mockReturnValue({
109104
toolMetas: [],
110105
runToolLifecycle: vi.fn(async ({ execute }) => await execute()),
@@ -158,7 +153,7 @@ describe("prepareEmbeddedAttemptStream", () => {
158153
builtinToolNames: new Set(),
159154
replaySafeToolNames: new Set(),
160155
});
161-
const subscriptionInput = mocks.buildSubscriptionParams.mock.calls.at(-1)?.[0] as {
156+
const subscriptionInput = mocks.subscribe.mock.calls.at(-1)?.[0] as {
162157
onBeforeTerminalDelivery?: (event: unknown) => Promise<unknown>;
163158
};
164159
const decision = subscriptionInput.onBeforeTerminalDelivery?.({
@@ -237,7 +232,7 @@ describe("prepareEmbeddedAttemptStream", () => {
237232
replaySafeToolNames: new Set(),
238233
});
239234
const queued = prepared.queueHandle.queueMessage("new user input");
240-
const subscriptionInput = mocks.buildSubscriptionParams.mock.calls.at(-1)?.[0] as {
235+
const subscriptionInput = mocks.subscribe.mock.calls.at(-1)?.[0] as {
241236
onBeforeTerminalDelivery?: (event: unknown) => Promise<unknown>;
242237
};
243238

@@ -271,7 +266,7 @@ describe("prepareEmbeddedAttemptStream", () => {
271266
sandboxSessionKey: "agent:main:main",
272267
});
273268

274-
expect(mocks.buildSubscriptionParams).toHaveBeenCalledWith(
269+
expect(mocks.subscribe).toHaveBeenCalledWith(
275270
expect.objectContaining({
276271
sessionKey: "agent:main:internal-session-effects:companion-run",
277272
}),

‎src/agents/embedded-agent-runner/run/attempt-stream-prepare.ts‎

Lines changed: 75 additions & 78 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,6 @@ import {
4545
} from "./attempt-async-tasks.js";
4646
import { steerActiveSessionWithOptionalDeliveryWait } from "./attempt-queue-message.js";
4747
import type { EmbeddedAttemptClientToolCallSlot } from "./attempt-result.js";
48-
import { buildEmbeddedSubscriptionParams } from "./attempt-subscription-cleanup.js";
4948
import {
5049
resolveFinalAssistantRawText,
5150
resolveFinalAssistantVisibleText,
@@ -243,83 +242,81 @@ export function prepareEmbeddedAttemptStream(input: {
243242
// Terminal callbacks run after queue construction; keep the queue in this
244243
// phase so active-run clearing and subscription teardown share one owner.
245244
const getQueueHandle = (): AttemptStreamQueueHandle => queueHandle;
246-
const subscription = subscribeEmbeddedAgentSession(
247-
buildEmbeddedSubscriptionParams({
248-
session: input.activeSession,
249-
runId: attempt.runId,
250-
lifecycleGeneration: attempt.lifecycleGeneration,
251-
messageChannel: input.runtimeChannel,
252-
initialReplayState: attempt.initialReplayState,
253-
hookRunner: getGlobalHookRunner() ?? undefined,
254-
verboseLevel: attempt.verboseLevel,
255-
reasoningMode: attempt.reasoningLevel ?? "off",
256-
thinkingLevel: attempt.thinkLevel,
257-
toolResultFormat: attempt.toolResultFormat,
258-
shouldEmitToolResult: attempt.shouldEmitToolResult,
259-
shouldEmitToolOutput: attempt.shouldEmitToolOutput,
260-
sourceReplyDeliveryMode: attempt.sourceReplyDeliveryMode,
261-
hasDeliveredMessageToolOnlySourceReply: input.hasDeliveredSourceReply,
262-
onDeliveredMessageToolOnlySourceReply: input.markSourceReplyDelivered,
263-
onAgentToolResult: attempt.onAgentToolResult,
264-
observeToolTerminal: attempt.observeToolTerminal,
265-
onToolResult: attempt.onToolResult,
266-
onReasoningStream: attempt.onReasoningStream,
267-
streamReasoningInNonStreamModes: attempt.streamReasoningInNonStreamModes,
268-
onReasoningEnd: attempt.onReasoningEnd,
269-
onBlockReply: input.onBlockReply,
270-
onBlockReplyFlush: input.onBlockReplyFlush,
271-
onBeforeTerminalDelivery,
272-
blockReplyBreak: attempt.blockReplyBreak,
273-
blockReplyChunking: attempt.blockReplyChunking,
274-
onPartialReply: attempt.onPartialReply,
275-
onAssistantMessageStart: attempt.onAssistantMessageStart,
276-
onExecutionPhase: attempt.onExecutionPhase,
277-
onAgentEvent: attempt.onAgentEvent,
278-
terminalLifecyclePhase: attempt.deferTerminalLifecycle ? "finishing" : "end",
279-
onToolStreamBoundary: attempt.onToolStreamBoundary,
280-
isTerminalAborted: () => input.getRunState().aborted,
281-
resolveTerminalStopReason: () =>
282-
isAgentRunRestartAbortReason(input.runAbortController.signal.reason)
283-
? AGENT_RUN_RESTART_ABORT_STOP_REASON
284-
: undefined,
285-
onBeforeLifecycleTerminal: () => {
286-
if (
287-
requiresCompletionRequiredAsyncTaskWait({
288-
sessionKey: attempt.sessionKey,
289-
toolMetas: toolMetasForTerminal,
290-
})
291-
) {
292-
return;
293-
}
294-
// Clear embedded-run activity before emitting terminal lifecycle events so
295-
// post-completion cleanup does not observe a logically finished run as active.
296-
clearActiveEmbeddedRun(
297-
attempt.sessionId,
298-
getQueueHandle(),
299-
attempt.sessionKey,
300-
attempt.sessionFile,
301-
);
302-
},
303-
enforceFinalTag: attempt.enforceFinalTag,
304-
silentExpected: attempt.silentExpected,
305-
suppressLiveStreamOutput: attempt.suppressLiveStreamOutput,
306-
config: attempt.config,
307-
// Live events belong to the transcript session. The sandbox key is only
308-
// authority context and may intentionally point at a visible parent.
309-
sessionKey: attempt.sessionKey,
310-
currentChannelId: attempt.currentChannelId,
311-
currentMessagingTarget: attempt.currentMessagingTarget,
312-
currentThreadId: attempt.currentThreadTs,
313-
currentMessageId: attempt.currentMessageId,
314-
replyToMode: attempt.replyToMode,
315-
hasRepliedRef: attempt.hasRepliedRef,
316-
sessionId: attempt.sessionId,
317-
agentId: input.hookAgentId,
318-
builtinToolNames: input.builtinToolNames,
319-
replaySafeToolNames: input.replaySafeToolNames,
320-
internalEvents: attempt.internalEvents,
321-
}),
322-
);
245+
const subscription = subscribeEmbeddedAgentSession({
246+
session: input.activeSession,
247+
runId: attempt.runId,
248+
lifecycleGeneration: attempt.lifecycleGeneration,
249+
messageChannel: input.runtimeChannel,
250+
initialReplayState: attempt.initialReplayState,
251+
hookRunner: getGlobalHookRunner() ?? undefined,
252+
verboseLevel: attempt.verboseLevel,
253+
reasoningMode: attempt.reasoningLevel ?? "off",
254+
thinkingLevel: attempt.thinkLevel,
255+
toolResultFormat: attempt.toolResultFormat,
256+
shouldEmitToolResult: attempt.shouldEmitToolResult,
257+
shouldEmitToolOutput: attempt.shouldEmitToolOutput,
258+
sourceReplyDeliveryMode: attempt.sourceReplyDeliveryMode,
259+
hasDeliveredMessageToolOnlySourceReply: input.hasDeliveredSourceReply,
260+
onDeliveredMessageToolOnlySourceReply: input.markSourceReplyDelivered,
261+
onAgentToolResult: attempt.onAgentToolResult,
262+
observeToolTerminal: attempt.observeToolTerminal,
263+
onToolResult: attempt.onToolResult,
264+
onReasoningStream: attempt.onReasoningStream,
265+
streamReasoningInNonStreamModes: attempt.streamReasoningInNonStreamModes,
266+
onReasoningEnd: attempt.onReasoningEnd,
267+
onBlockReply: input.onBlockReply,
268+
onBlockReplyFlush: input.onBlockReplyFlush,
269+
onBeforeTerminalDelivery,
270+
blockReplyBreak: attempt.blockReplyBreak,
271+
blockReplyChunking: attempt.blockReplyChunking,
272+
onPartialReply: attempt.onPartialReply,
273+
onAssistantMessageStart: attempt.onAssistantMessageStart,
274+
onExecutionPhase: attempt.onExecutionPhase,
275+
onAgentEvent: attempt.onAgentEvent,
276+
terminalLifecyclePhase: attempt.deferTerminalLifecycle ? "finishing" : "end",
277+
onToolStreamBoundary: attempt.onToolStreamBoundary,
278+
isTerminalAborted: () => input.getRunState().aborted,
279+
resolveTerminalStopReason: () =>
280+
isAgentRunRestartAbortReason(input.runAbortController.signal.reason)
281+
? AGENT_RUN_RESTART_ABORT_STOP_REASON
282+
: undefined,
283+
onBeforeLifecycleTerminal: () => {
284+
if (
285+
requiresCompletionRequiredAsyncTaskWait({
286+
sessionKey: attempt.sessionKey,
287+
toolMetas: toolMetasForTerminal,
288+
})
289+
) {
290+
return;
291+
}
292+
// Clear embedded-run activity before emitting terminal lifecycle events so
293+
// post-completion cleanup does not observe a logically finished run as active.
294+
clearActiveEmbeddedRun(
295+
attempt.sessionId,
296+
getQueueHandle(),
297+
attempt.sessionKey,
298+
attempt.sessionFile,
299+
);
300+
},
301+
enforceFinalTag: attempt.enforceFinalTag,
302+
silentExpected: attempt.silentExpected,
303+
suppressLiveStreamOutput: attempt.suppressLiveStreamOutput,
304+
config: attempt.config,
305+
// Live events belong to the transcript session. The sandbox key is only
306+
// authority context and may intentionally point at a visible parent.
307+
sessionKey: attempt.sessionKey,
308+
currentChannelId: attempt.currentChannelId,
309+
currentMessagingTarget: attempt.currentMessagingTarget,
310+
currentThreadId: attempt.currentThreadTs,
311+
currentMessageId: attempt.currentMessageId,
312+
replyToMode: attempt.replyToMode,
313+
hasRepliedRef: attempt.hasRepliedRef,
314+
sessionId: attempt.sessionId,
315+
agentId: input.hookAgentId,
316+
builtinToolNames: input.builtinToolNames,
317+
replaySafeToolNames: input.replaySafeToolNames,
318+
internalEvents: attempt.internalEvents,
319+
});
323320
toolMetasForTerminal = subscription.toolMetas;
324321

325322
const toolSearchCatalogExecutor: ToolSearchCatalogToolExecutor = async (toolParams) => {

‎src/agents/embedded-agent-runner/run/attempt-subscription-cleanup.ts‎

Lines changed: 1 addition & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,4 @@
1-
/**
2-
* Builds subscription params and cleans up embedded attempt resources.
3-
*/
4-
import type { SubscribeEmbeddedAgentSessionParams } from "../../embedded-agent-subscribe.types.js";
1+
/** Cleans up embedded attempt subscription resources. */
52
import { log } from "../logger.js";
63
import { resolveEmbeddedAbortSettleTimeoutMs } from "./attempt-finalize.js";
74

@@ -52,17 +49,6 @@ async function waitForEmbeddedAbortSettle(params: {
5249
}
5350
}
5451

55-
/**
56-
* Identity helper that preserves the concrete subscription params type at call
57-
* sites. Keeping this as a named helper lets tests assert the exact shape passed
58-
* into the subscription layer without widening the object inline.
59-
*/
60-
export function buildEmbeddedSubscriptionParams(
61-
params: SubscribeEmbeddedAgentSessionParams,
62-
): SubscribeEmbeddedAgentSessionParams {
63-
return params;
64-
}
65-
6652
/**
6753
* Tears down per-attempt resources after the transcript lifecycle has drained:
6854
* remove guards, settle aborted prompts, flush tool results, then dispose runtimes.

0 commit comments

Comments
 (0)