fix(orchestrator): Preserve claude/codex post-interrupt recovery state (#4229)
This commit is contained in:
1 parent
0ab943a5fb
commit
7a26bfc75e
10 files changed
+4563
-277
No files matched your search
@@ -1122,14 +1122,19 @@ describe("ClaudeAdapterV2 background wake turns", () => {
|
||||
uuid: "00000000-0000-4000-8000-000000000101",
|
||||
session_id: WAKE_NATIVE_SESSION,
|
||||
});
|
||||
const makeResultFrame = (input: { readonly uuid: string; readonly result: string }) =>
|
||||
const makeResultFrame = (input: {
|
||||
readonly uuid: string;
|
||||
readonly result: string;
|
||||
readonly numTurns?: number;
|
||||
readonly origin?: { readonly kind: "task-notification" };
|
||||
}) =>
|
||||
claudeSdkFrame({
|
||||
type: "result",
|
||||
subtype: "success",
|
||||
duration_ms: 10,
|
||||
duration_api_ms: 10,
|
||||
is_error: false,
|
||||
num_turns: 1,
|
||||
num_turns: input.numTurns ?? 1,
|
||||
result: input.result,
|
||||
stop_reason: "end_turn",
|
||||
total_cost_usd: 0,
|
||||
@@ -1143,6 +1148,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
|
||||
permission_denials: [],
|
||||
uuid: input.uuid,
|
||||
session_id: WAKE_NATIVE_SESSION,
|
||||
...(input.origin === undefined ? {} : { origin: input.origin }),
|
||||
});
|
||||
const turnOneResult = makeResultFrame({
|
||||
uuid: "00000000-0000-4000-8000-000000000102",
|
||||
@@ -1161,6 +1167,15 @@ describe("ClaudeAdapterV2 background wake turns", () => {
|
||||
const wakeResult = makeResultFrame({
|
||||
uuid: "00000000-0000-4000-8000-000000000104",
|
||||
result: WAKE_RESULT_TEXT,
|
||||
origin: { kind: "task-notification" },
|
||||
});
|
||||
const STALE_TASK_NOTIFICATION_RESULT_TEXT =
|
||||
"Stale task-notification origin text that must not appear.";
|
||||
const staleTaskNotificationResult = makeResultFrame({
|
||||
uuid: "00000000-0000-4000-8000-000000000106",
|
||||
result: STALE_TASK_NOTIFICATION_RESULT_TEXT,
|
||||
numTurns: 0,
|
||||
origin: { kind: "task-notification" },
|
||||
});
|
||||
|
||||
const awaitUntil = (predicate: () => boolean, label: string): Effect.Effect<void> =>
|
||||
@@ -1441,6 +1456,150 @@ describe("ClaudeAdapterV2 background wake turns", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("ignores a live task-notification origin result during a normal user turn", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* makeWakeHarness;
|
||||
const now = yield* DateTime.now;
|
||||
const probeAssistantText = "Probe after stale task-notification result.";
|
||||
const recoveryAssistantText = "Recovered after the interrupt; continuing.";
|
||||
const staleResultText = STALE_TASK_NOTIFICATION_RESULT_TEXT;
|
||||
const hasMessageText = (text: string) =>
|
||||
harness.events.some(
|
||||
(event) => event.type === "message.updated" && event.message.text === text,
|
||||
);
|
||||
|
||||
yield* harness.runtime.startTurn(
|
||||
makeClaudeTestTurnInput({
|
||||
threadId: harness.threadId,
|
||||
providerThread: harness.providerThread,
|
||||
now,
|
||||
attemptId: RunAttemptId.make("attempt-claude-stale-notif-1"),
|
||||
text: "Continue after interrupt.",
|
||||
attachments: [],
|
||||
}),
|
||||
);
|
||||
yield* awaitUntil(() => harness.offeredMessages.length === 1, "recovery prompt offered");
|
||||
|
||||
// Live interleaving seen after interrupt recovery: a stale stopped
|
||||
// task_notification and its task-notification-origin result arrive
|
||||
// before the real root assistant stream.
|
||||
yield* Queue.offer(
|
||||
harness.sdkMessages,
|
||||
claudeSdkFrame({
|
||||
type: "system",
|
||||
subtype: "task_notification",
|
||||
task_id: "task-stale-stopped",
|
||||
status: "stopped",
|
||||
output_file: "/tmp/task-stale-stopped.log",
|
||||
summary: "",
|
||||
uuid: "00000000-0000-4000-8000-000000000107",
|
||||
session_id: WAKE_NATIVE_SESSION,
|
||||
}),
|
||||
);
|
||||
yield* Queue.offer(harness.sdkMessages, staleTaskNotificationResult);
|
||||
// Queue-ordered probe: once this assistant text is emitted, the stale
|
||||
// origin result ahead of it has been consumed.
|
||||
yield* Queue.offer(
|
||||
harness.sdkMessages,
|
||||
claudeSdkFrame({
|
||||
type: "assistant",
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: [{ type: "text", text: probeAssistantText }],
|
||||
},
|
||||
parent_tool_use_id: null,
|
||||
uuid: "00000000-0000-4000-8000-00000000010a",
|
||||
session_id: WAKE_NATIVE_SESSION,
|
||||
}),
|
||||
);
|
||||
|
||||
yield* awaitUntil(
|
||||
() => hasMessageText(probeAssistantText),
|
||||
"probe assistant after stale task-notification result",
|
||||
);
|
||||
assert.lengthOf(harness.terminalEvents(), 0);
|
||||
assert.isFalse(hasMessageText(staleResultText));
|
||||
|
||||
yield* Queue.offer(
|
||||
harness.sdkMessages,
|
||||
claudeSdkFrame({
|
||||
type: "assistant",
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: [{ type: "text", text: recoveryAssistantText }],
|
||||
},
|
||||
parent_tool_use_id: null,
|
||||
uuid: "00000000-0000-4000-8000-000000000108",
|
||||
session_id: WAKE_NATIVE_SESSION,
|
||||
}),
|
||||
);
|
||||
yield* Queue.offer(
|
||||
harness.sdkMessages,
|
||||
makeResultFrame({
|
||||
uuid: "00000000-0000-4000-8000-000000000109",
|
||||
result: recoveryAssistantText,
|
||||
}),
|
||||
);
|
||||
|
||||
yield* awaitUntil(() => harness.terminalEvents().length === 1, "user turn terminal");
|
||||
assert.equal(harness.terminalEvents()[0]?.status, "completed");
|
||||
assert.isTrue(hasMessageText(recoveryAssistantText));
|
||||
assert.isFalse(hasMessageText(staleResultText));
|
||||
}).pipe(Effect.provide(Layer.merge(idAllocatorLayer, NodeServices.layer))),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("terminalizes a continuation turn from a task-notification origin wake result", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* makeWakeHarness;
|
||||
const now = yield* DateTime.now;
|
||||
|
||||
yield* harness.runtime.startTurn(
|
||||
makeClaudeTestTurnInput({
|
||||
threadId: harness.threadId,
|
||||
providerThread: harness.providerThread,
|
||||
now,
|
||||
attemptId: RunAttemptId.make("attempt-claude-notif-origin-2a"),
|
||||
text: "Run the build in the background.",
|
||||
attachments: [],
|
||||
}),
|
||||
);
|
||||
yield* Queue.offer(harness.sdkMessages, wakeTaskStarted);
|
||||
yield* Queue.offer(harness.sdkMessages, turnOneResult);
|
||||
yield* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal");
|
||||
yield* Queue.offer(harness.sdkMessages, wakeNotification);
|
||||
yield* Queue.offer(harness.sdkMessages, wakeResult);
|
||||
yield* awaitUntil(() => harness.continuationRequests.length === 1, "continuation request");
|
||||
|
||||
yield* harness.runtime.startTurn(
|
||||
makeClaudeTestTurnInput({
|
||||
threadId: harness.threadId,
|
||||
providerThread: harness.providerThread,
|
||||
now,
|
||||
attemptId: RunAttemptId.make("attempt-claude-notif-origin-2b"),
|
||||
text: "Background task completed.",
|
||||
attachments: [],
|
||||
providerTurnOrdinal: 2,
|
||||
messageCreatedBy: "agent",
|
||||
messageCreationSource: "provider",
|
||||
}),
|
||||
);
|
||||
|
||||
yield* awaitUntil(() => harness.terminalEvents().length === 2, "continuation terminal");
|
||||
assert.equal(harness.terminalEvents()[1]?.status, "completed");
|
||||
assert.lengthOf(harness.offeredMessages, 1);
|
||||
assert.isTrue(
|
||||
harness.events.some(
|
||||
(event) => event.type === "message.updated" && event.message.text === WAKE_RESULT_TEXT,
|
||||
),
|
||||
);
|
||||
assert.isFalse(yield* harness.hasPendingBackgroundWork);
|
||||
}).pipe(Effect.provide(Layer.merge(idAllocatorLayer, NodeServices.layer))),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("clears the pending task when the wake notification carries no summary", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -1765,6 +1765,19 @@ function isClaudeActiveSteeringAbortResult(message: SDKResultMessage): boolean {
|
||||
return message.terminal_reason === "aborted_streaming";
|
||||
}
|
||||
|
||||
function isClaudeProviderContinuationTurn(input: ProviderAdapterV2TurnInput): boolean {
|
||||
return input.message.createdBy === "agent" && input.message.creationSource === "provider";
|
||||
}
|
||||
|
||||
function isClaudeTaskNotificationOriginResult(message: SDKMessage): message is SDKResultMessage & {
|
||||
readonly origin: Extract<
|
||||
NonNullable<SDKResultMessage["origin"]>,
|
||||
{ readonly kind: "task-notification" }
|
||||
>;
|
||||
} {
|
||||
return message.type === "result" && message.origin?.kind === "task-notification";
|
||||
}
|
||||
|
||||
function providerFailureFromResult(
|
||||
message: SDKResultMessage,
|
||||
): OrchestrationV2ProviderFailure | null {
|
||||
@@ -3266,6 +3279,18 @@ export function makeClaudeAdapterV2(
|
||||
return;
|
||||
}
|
||||
|
||||
// Task-notification-origin results can interleave during a normal
|
||||
// user turn (for example a stale background stop after interrupt
|
||||
// recovery). They must not finalize that turn or supply fallback
|
||||
// assistant text. Provider continuation turns still consume them
|
||||
// when draining buffered wake messages.
|
||||
if (
|
||||
isClaudeTaskNotificationOriginResult(message) &&
|
||||
!isClaudeProviderContinuationTurn(context.input)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
// An is_error result's text is the error message; it belongs on the
|
||||
// terminal-failure item, not on a synthetic assistant message.
|
||||
const resultText =
|
||||
@@ -3549,9 +3574,7 @@ export function makeClaudeAdapterV2(
|
||||
// produced instead of prompting it again: drain the buffered wake
|
||||
// messages into this turn and let any still-streaming messages
|
||||
// follow live. The continuation prompt text never reaches the CLI.
|
||||
const isContinuationTurn =
|
||||
turnInput.message.createdBy === "agent" &&
|
||||
turnInput.message.creationSource === "provider";
|
||||
const isContinuationTurn = isClaudeProviderContinuationTurn(turnInput);
|
||||
const userMessage = isContinuationTurn
|
||||
? null
|
||||
: yield* makeClaudeUserMessageWithAttachments({
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -22,7 +22,7 @@ import {
|
||||
import { IdAllocatorV2 } from "./IdAllocator.ts";
|
||||
import { ProjectionStoreV2 } from "./ProjectionStore.ts";
|
||||
import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
|
||||
import { RunExecutionServiceV2 } from "./RunExecutionService.ts";
|
||||
import { canRouteRelatedSubagent, RunExecutionServiceV2 } from "./RunExecutionService.ts";
|
||||
import { RuntimePolicyV2 } from "./RuntimePolicy.ts";
|
||||
|
||||
export class ProviderTurnStartError extends Schema.TaggedErrorClass<ProviderTurnStartError>()(
|
||||
@@ -403,6 +403,9 @@ export const layer: Layer.Layer<
|
||||
if (!runningWrite.committed) {
|
||||
return;
|
||||
}
|
||||
const routableSubagents = projection.subagents.filter((subagent) =>
|
||||
canRouteRelatedSubagent(subagent.status),
|
||||
);
|
||||
yield* runExecution.startRootRun({
|
||||
commandId: CommandId.make(`command:effect:provider-turn.start:${run.id}`),
|
||||
appThread: projection.thread,
|
||||
@@ -414,10 +417,10 @@ export const layer: Layer.Layer<
|
||||
providerThread: runningProviderThread,
|
||||
attempt: runningAttempt,
|
||||
attemptId: attempt.id,
|
||||
relatedThreadIds: projection.subagents.flatMap((subagent) =>
|
||||
relatedThreadIds: routableSubagents.flatMap((subagent) =>
|
||||
subagent.childThreadId === null ? [] : [subagent.childThreadId],
|
||||
),
|
||||
relatedProviderThreadIds: projection.subagents.flatMap((subagent) =>
|
||||
relatedProviderThreadIds: routableSubagents.flatMap((subagent) =>
|
||||
subagent.providerThreadId === null ? [] : [subagent.providerThreadId],
|
||||
),
|
||||
providerTurnOrdinal:
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,9 +1,11 @@
|
||||
import {
|
||||
CommandId,
|
||||
type EventId,
|
||||
type ModelSelection,
|
||||
type NodeId,
|
||||
type OrchestrationV2AppThread,
|
||||
type OrchestrationV2CheckpointScope,
|
||||
type OrchestrationV2DomainEvent,
|
||||
type OrchestrationV2ExecutionNode,
|
||||
type OrchestrationV2ProviderFailure,
|
||||
type OrchestrationV2ProviderThread,
|
||||
@@ -17,6 +19,7 @@ import {
|
||||
type ProviderTurnId,
|
||||
type RunAttemptId,
|
||||
type ThreadId,
|
||||
type TurnItemId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Cause from "effect/Cause";
|
||||
@@ -31,7 +34,11 @@ import * as Stream from "effect/Stream";
|
||||
import { ServerSettingsService } from "../serverSettings.ts";
|
||||
import { CheckpointServiceV2 } from "./CheckpointService.ts";
|
||||
import { EventSinkV2 } from "./EventSink.ts";
|
||||
import { IdAllocatorV2, type IdAllocatorV2Shape } from "./IdAllocator.ts";
|
||||
import {
|
||||
IdAllocatorV2,
|
||||
type IdAllocatorV2AllocationError,
|
||||
type IdAllocatorV2Shape,
|
||||
} from "./IdAllocator.ts";
|
||||
import type {
|
||||
ProviderAdapterV2Event,
|
||||
ProviderAdapterV2RuntimePolicy,
|
||||
@@ -94,6 +101,170 @@ function isTerminalTurnItemStatus(status: OrchestrationV2TurnItem["status"]): bo
|
||||
);
|
||||
}
|
||||
|
||||
type SubagentTurnItem = Extract<OrchestrationV2TurnItem, { readonly type: "subagent" }>;
|
||||
|
||||
type OpenRunOwnedSubagentProjection = {
|
||||
readonly subagents: ReadonlyMap<NodeId, OrchestrationV2Subagent>;
|
||||
readonly turnItems: ReadonlyMap<NodeId, SubagentTurnItem>;
|
||||
readonly childTurnItems: ReadonlyMap<TurnItemId, OrchestrationV2TurnItem>;
|
||||
readonly nodes: ReadonlyMap<NodeId, OrchestrationV2ExecutionNode>;
|
||||
/** Child threads once linked by a root-run subagent row; kept for cascade. */
|
||||
readonly linkedChildThreadIds: ReadonlySet<ThreadId>;
|
||||
};
|
||||
|
||||
type RunOwnedSubagentTerminalStatus = Extract<
|
||||
OrchestrationV2Subagent["status"],
|
||||
"interrupted" | "failed" | "cancelled"
|
||||
>;
|
||||
|
||||
function isOpenExecutionNodeStatus(status: OrchestrationV2ExecutionNode["status"]): boolean {
|
||||
return status === "pending" || status === "running" || status === "waiting";
|
||||
}
|
||||
|
||||
function isRunOwnedSubagentTerminalStatus(
|
||||
status: ProviderTerminalEvent["status"],
|
||||
): status is RunOwnedSubagentTerminalStatus {
|
||||
return status === "interrupted" || status === "failed" || status === "cancelled";
|
||||
}
|
||||
|
||||
export function canRouteRelatedSubagent(status: OrchestrationV2Subagent["status"]): boolean {
|
||||
return status !== "interrupted" && status !== "failed" && status !== "cancelled";
|
||||
}
|
||||
|
||||
function emptyOpenRunOwnedSubagentProjection(): OpenRunOwnedSubagentProjection {
|
||||
return {
|
||||
subagents: new Map(),
|
||||
turnItems: new Map(),
|
||||
childTurnItems: new Map(),
|
||||
nodes: new Map(),
|
||||
linkedChildThreadIds: new Set(),
|
||||
};
|
||||
}
|
||||
|
||||
function withLinkedChildThreadId(
|
||||
current: OpenRunOwnedSubagentProjection,
|
||||
childThreadId: ThreadId | null,
|
||||
): OpenRunOwnedSubagentProjection {
|
||||
if (childThreadId === null || current.linkedChildThreadIds.has(childThreadId)) {
|
||||
return current;
|
||||
}
|
||||
const linkedChildThreadIds = new Set(current.linkedChildThreadIds);
|
||||
linkedChildThreadIds.add(childThreadId);
|
||||
return { ...current, linkedChildThreadIds };
|
||||
}
|
||||
|
||||
export function cascadeTerminalizeRunOwnedSubagents(input: {
|
||||
readonly run: OrchestrationV2Run;
|
||||
readonly open: OpenRunOwnedSubagentProjection;
|
||||
readonly status: RunOwnedSubagentTerminalStatus;
|
||||
readonly completedAt: DateTime.Utc;
|
||||
readonly allocateEventId: () => Effect.Effect<EventId, IdAllocatorV2AllocationError>;
|
||||
}): Effect.Effect<ReadonlyArray<OrchestrationV2DomainEvent>, IdAllocatorV2AllocationError> {
|
||||
return Effect.gen(function* () {
|
||||
const events: Array<OrchestrationV2DomainEvent> = [];
|
||||
// Prefer lifetime linkage over currently-open rows: subagent/turn-item
|
||||
// snapshots may terminalize before the linked child-thread node settles.
|
||||
const childThreadIds = new Set(input.open.linkedChildThreadIds);
|
||||
for (const item of [...input.open.subagents.values(), ...input.open.turnItems.values()]) {
|
||||
if (item.childThreadId !== null) {
|
||||
childThreadIds.add(item.childThreadId);
|
||||
}
|
||||
}
|
||||
const keys = new Set<NodeId>([
|
||||
...input.open.subagents.keys(),
|
||||
...input.open.turnItems.keys(),
|
||||
...input.open.nodes.keys(),
|
||||
]);
|
||||
for (const key of keys) {
|
||||
const subagent = input.open.subagents.get(key);
|
||||
if (subagent !== undefined && !isTerminalSubagentStatus(subagent.status)) {
|
||||
events.push({
|
||||
id: yield* input.allocateEventId(),
|
||||
type: "subagent.updated",
|
||||
threadId: subagent.threadId,
|
||||
runId: input.run.id,
|
||||
nodeId: subagent.id,
|
||||
driver: subagent.driver,
|
||||
providerInstanceId: subagent.providerInstanceId,
|
||||
occurredAt: input.completedAt,
|
||||
payload: {
|
||||
...subagent,
|
||||
status: input.status,
|
||||
completedAt: input.completedAt,
|
||||
updatedAt: input.completedAt,
|
||||
},
|
||||
});
|
||||
}
|
||||
const node = input.open.nodes.get(key);
|
||||
if (
|
||||
node !== undefined &&
|
||||
((node.threadId === input.run.threadId && node.runId === input.run.id) ||
|
||||
childThreadIds.has(node.threadId)) &&
|
||||
isOpenExecutionNodeStatus(node.status)
|
||||
) {
|
||||
events.push({
|
||||
id: yield* input.allocateEventId(),
|
||||
type: "node.updated",
|
||||
threadId: node.threadId,
|
||||
runId: node.runId ?? input.run.id,
|
||||
nodeId: node.id,
|
||||
providerInstanceId: input.run.providerInstanceId,
|
||||
occurredAt: input.completedAt,
|
||||
payload: {
|
||||
...node,
|
||||
status: input.status,
|
||||
completedAt: input.completedAt,
|
||||
},
|
||||
});
|
||||
}
|
||||
const turnItem = input.open.turnItems.get(key);
|
||||
if (
|
||||
turnItem !== undefined &&
|
||||
turnItem.runId === input.run.id &&
|
||||
!isTerminalTurnItemStatus(turnItem.status)
|
||||
) {
|
||||
events.push({
|
||||
id: yield* input.allocateEventId(),
|
||||
type: "turn-item.updated",
|
||||
threadId: turnItem.threadId,
|
||||
runId: input.run.id,
|
||||
...(turnItem.nodeId === null ? {} : { nodeId: turnItem.nodeId }),
|
||||
providerInstanceId: input.run.providerInstanceId,
|
||||
occurredAt: input.completedAt,
|
||||
payload: {
|
||||
...turnItem,
|
||||
status: input.status,
|
||||
completedAt: input.completedAt,
|
||||
updatedAt: input.completedAt,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
for (const turnItem of input.open.childTurnItems.values()) {
|
||||
if (!childThreadIds.has(turnItem.threadId) || isTerminalTurnItemStatus(turnItem.status)) {
|
||||
continue;
|
||||
}
|
||||
events.push({
|
||||
id: yield* input.allocateEventId(),
|
||||
type: "turn-item.updated",
|
||||
threadId: turnItem.threadId,
|
||||
runId: turnItem.runId ?? input.run.id,
|
||||
...(turnItem.nodeId === null ? {} : { nodeId: turnItem.nodeId }),
|
||||
providerInstanceId: input.run.providerInstanceId,
|
||||
occurredAt: input.completedAt,
|
||||
payload: {
|
||||
...turnItem,
|
||||
...("streaming" in turnItem ? { streaming: false } : {}),
|
||||
status: input.status,
|
||||
completedAt: input.completedAt,
|
||||
updatedAt: input.completedAt,
|
||||
},
|
||||
});
|
||||
}
|
||||
return events;
|
||||
});
|
||||
}
|
||||
|
||||
export function finalProviderThreadStatus(
|
||||
disposition: ProviderTerminalEvent["threadDisposition"],
|
||||
): OrchestrationV2ProviderThread["status"] {
|
||||
@@ -325,6 +496,7 @@ export const layer: Layer.Layer<
|
||||
readonly attempt: OrchestrationV2RunAttempt;
|
||||
readonly shouldFinalizeRun?: () => Effect.Effect<boolean, never>;
|
||||
readonly hasUnpairedRunInterruptRequest?: () => Effect.Effect<boolean, never>;
|
||||
readonly openRunOwnedSubagents?: OpenRunOwnedSubagentProjection;
|
||||
readonly terminal: ProviderTerminalEvent;
|
||||
readonly failureItemPersisted: boolean;
|
||||
}) =>
|
||||
@@ -372,6 +544,23 @@ export const layer: Layer.Layer<
|
||||
}
|
||||
return;
|
||||
}
|
||||
const allocateEventId = () => idAllocator.allocate.event({ threadId: input.run.threadId });
|
||||
const open = input.openRunOwnedSubagents ?? emptyOpenRunOwnedSubagentProjection();
|
||||
const hasOpenSubagentProjection =
|
||||
open.subagents.size > 0 ||
|
||||
open.turnItems.size > 0 ||
|
||||
open.childTurnItems.size > 0 ||
|
||||
open.nodes.size > 0;
|
||||
const cascadedSubagentEvents =
|
||||
isRunOwnedSubagentTerminalStatus(input.terminal.status) && hasOpenSubagentProjection
|
||||
? yield* cascadeTerminalizeRunOwnedSubagents({
|
||||
run: input.run,
|
||||
open,
|
||||
status: input.terminal.status,
|
||||
completedAt,
|
||||
allocateEventId,
|
||||
})
|
||||
: [];
|
||||
const persistedStatus =
|
||||
input.terminal.status === "completed" ? "waiting" : input.terminal.status;
|
||||
const finalizedRun: OrchestrationV2Run = {
|
||||
@@ -390,11 +579,9 @@ export const layer: Layer.Layer<
|
||||
status: finalProviderThreadStatus(input.terminal.threadDisposition),
|
||||
updatedAt: completedAt,
|
||||
};
|
||||
const runEventId = yield* idAllocator.allocate.event({ threadId: input.run.threadId });
|
||||
const nodeEventId = yield* idAllocator.allocate.event({ threadId: input.run.threadId });
|
||||
const providerThreadEventId = yield* idAllocator.allocate.event({
|
||||
threadId: input.run.threadId,
|
||||
});
|
||||
const runEventId = yield* allocateEventId();
|
||||
const nodeEventId = yield* allocateEventId();
|
||||
const providerThreadEventId = yield* allocateEventId();
|
||||
const checkpointCaptureCommandId = CommandId.make(
|
||||
`command:effect:checkpoint.capture:${input.run.id}`,
|
||||
);
|
||||
@@ -415,11 +602,14 @@ export const layer: Layer.Layer<
|
||||
]
|
||||
: [],
|
||||
events: [
|
||||
// Terminalize open run-owned subagent rows before the root run
|
||||
// settles so projections never keep a forever-running subagent card.
|
||||
...cascadedSubagentEvents,
|
||||
...(finalizedAttempt === null
|
||||
? []
|
||||
: [
|
||||
{
|
||||
id: yield* idAllocator.allocate.event({ threadId: input.run.threadId }),
|
||||
id: yield* allocateEventId(),
|
||||
type: "run-attempt.updated" as const,
|
||||
threadId: input.run.threadId,
|
||||
runId: input.run.id,
|
||||
@@ -432,7 +622,7 @@ export const layer: Layer.Layer<
|
||||
...(input.terminal.status === "interrupted"
|
||||
? [
|
||||
{
|
||||
id: yield* idAllocator.allocate.event({ threadId: input.run.threadId }),
|
||||
id: yield* allocateEventId(),
|
||||
type: "turn-item.updated" as const,
|
||||
threadId: input.run.threadId,
|
||||
runId: input.run.id,
|
||||
@@ -452,7 +642,7 @@ export const layer: Layer.Layer<
|
||||
...(input.terminal.status === "failed" && !input.failureItemPersisted
|
||||
? [
|
||||
{
|
||||
id: yield* idAllocator.allocate.event({ threadId: input.run.threadId }),
|
||||
id: yield* allocateEventId(),
|
||||
type: "turn-item.updated" as const,
|
||||
threadId: input.run.threadId,
|
||||
runId: input.run.id,
|
||||
@@ -588,12 +778,14 @@ export const layer: Layer.Layer<
|
||||
const activeBackgroundTurnItems = yield* Ref.make<
|
||||
ReadonlySet<OrchestrationV2TurnItem["id"]>
|
||||
>(new Set());
|
||||
const openRunOwnedSubagents = yield* Ref.make(emptyOpenRunOwnedSubagentProjection());
|
||||
const finalizeRootRun = (terminal: ProviderTerminalEvent) =>
|
||||
Effect.gen(function* () {
|
||||
if (yield* Ref.get(rootRunFinalized)) {
|
||||
return;
|
||||
}
|
||||
const providerThread = yield* Ref.get(latestProviderThread);
|
||||
const openSubagents = yield* Ref.get(openRunOwnedSubagents);
|
||||
yield* writeFinalRunEvents({
|
||||
run: input.run,
|
||||
rootNode: input.rootNode,
|
||||
@@ -608,6 +800,7 @@ export const layer: Layer.Layer<
|
||||
: {
|
||||
hasUnpairedRunInterruptRequest: input.hasUnpairedRunInterruptRequest,
|
||||
}),
|
||||
openRunOwnedSubagents: openSubagents,
|
||||
terminal,
|
||||
failureItemPersisted: terminal.status === "failed",
|
||||
}).pipe(
|
||||
@@ -615,9 +808,12 @@ export const layer: Layer.Layer<
|
||||
(cause) => new RunExecutionIngestError({ runId: input.run.id, cause }),
|
||||
),
|
||||
);
|
||||
if (isRunOwnedSubagentTerminalStatus(terminal.status)) {
|
||||
yield* Ref.set(openRunOwnedSubagents, emptyOpenRunOwnedSubagentProjection());
|
||||
}
|
||||
yield* Ref.set(rootRunFinalized, true);
|
||||
});
|
||||
const trackChildLifecycle = (event: ProviderAdapterV2Event) =>
|
||||
const trackChildLifecycle = (event: ProviderAdapterV2Event, deliverable: boolean) =>
|
||||
Effect.gen(function* () {
|
||||
const routing = yield* Ref.get(eventRouting);
|
||||
if (event.type === "provider_turn.updated") {
|
||||
@@ -652,16 +848,51 @@ export const layer: Layer.Layer<
|
||||
return next;
|
||||
});
|
||||
}
|
||||
// Snapshot run-owned subagents for interrupt cascade.
|
||||
// Preserve childThreadId linkage for the root-run lifetime even
|
||||
// after the subagent row terminalizes, so open child-thread
|
||||
// nodes can still be proven linked on a later root interrupt.
|
||||
if (belongsToRootRun) {
|
||||
yield* Ref.update(openRunOwnedSubagents, (current) => {
|
||||
const withLink = withLinkedChildThreadId(current, event.subagent.childThreadId);
|
||||
const subagents = new Map(withLink.subagents);
|
||||
if (isTerminalSubagentStatus(event.subagent.status)) {
|
||||
subagents.delete(event.subagent.id);
|
||||
} else {
|
||||
subagents.set(event.subagent.id, event.subagent);
|
||||
}
|
||||
return { ...withLink, subagents };
|
||||
});
|
||||
}
|
||||
}
|
||||
if (
|
||||
event.type === "turn_item.updated" &&
|
||||
backgroundCapableTurnItemTypes.has(event.turnItem.type)
|
||||
) {
|
||||
if (event.type === "node.updated") {
|
||||
const belongsToRootSubagent =
|
||||
event.node.kind === "subagent" && event.node.runId === input.run.id;
|
||||
const belongsToOwnedChildThread =
|
||||
event.node.threadId !== input.run.threadId &&
|
||||
routing.ownedThreadIds.has(event.node.threadId);
|
||||
if (!belongsToRootSubagent && !belongsToOwnedChildThread) {
|
||||
return;
|
||||
}
|
||||
yield* Ref.update(openRunOwnedSubagents, (current) => {
|
||||
const nodes = new Map(current.nodes);
|
||||
if (isOpenExecutionNodeStatus(event.node.status)) {
|
||||
nodes.set(event.node.id, event.node);
|
||||
} else {
|
||||
nodes.delete(event.node.id);
|
||||
}
|
||||
return { ...current, nodes };
|
||||
});
|
||||
}
|
||||
if (event.type === "turn_item.updated") {
|
||||
const belongsToRootRun = event.turnItem.runId === input.run.id;
|
||||
const belongsToOwnedChildThread =
|
||||
event.turnItem.threadId !== input.run.threadId &&
|
||||
routing.ownedThreadIds.has(event.turnItem.threadId);
|
||||
if (belongsToRootRun || belongsToOwnedChildThread) {
|
||||
if (
|
||||
backgroundCapableTurnItemTypes.has(event.turnItem.type) &&
|
||||
(belongsToRootRun || belongsToOwnedChildThread)
|
||||
) {
|
||||
yield* Ref.update(activeBackgroundTurnItems, (current) => {
|
||||
const next = new Set(current);
|
||||
if (isTerminalTurnItemStatus(event.turnItem.status)) {
|
||||
@@ -672,12 +903,40 @@ export const layer: Layer.Layer<
|
||||
return next;
|
||||
});
|
||||
}
|
||||
if (belongsToOwnedChildThread && deliverable) {
|
||||
yield* Ref.update(openRunOwnedSubagents, (current) => {
|
||||
const childTurnItems = new Map(current.childTurnItems);
|
||||
if (isTerminalTurnItemStatus(event.turnItem.status)) {
|
||||
childTurnItems.delete(event.turnItem.id);
|
||||
} else {
|
||||
childTurnItems.set(event.turnItem.id, event.turnItem);
|
||||
}
|
||||
return { ...current, childTurnItems };
|
||||
});
|
||||
}
|
||||
if (belongsToRootRun && event.turnItem.type === "subagent") {
|
||||
const subagentItem = event.turnItem;
|
||||
yield* Ref.update(openRunOwnedSubagents, (current) => {
|
||||
const withLink = withLinkedChildThreadId(current, subagentItem.childThreadId);
|
||||
const turnItems = new Map(withLink.turnItems);
|
||||
if (isTerminalTurnItemStatus(subagentItem.status)) {
|
||||
turnItems.delete(subagentItem.subagentId);
|
||||
} else {
|
||||
turnItems.set(subagentItem.subagentId, subagentItem);
|
||||
}
|
||||
return { ...withLink, turnItems };
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
const shouldStopProviderEventIngestion = Effect.gen(function* () {
|
||||
if (!(yield* Ref.get(rootTerminalSeen))) {
|
||||
return false;
|
||||
}
|
||||
const terminal = yield* Ref.get(terminalEvent);
|
||||
if (terminal !== null && terminal.status !== "completed") {
|
||||
return true;
|
||||
}
|
||||
const childProviderTurns = yield* Ref.get(activeChildProviderTurns);
|
||||
if (childProviderTurns.size > 0) {
|
||||
return false;
|
||||
@@ -694,12 +953,8 @@ export const layer: Layer.Layer<
|
||||
// rather than pinning the stream open. Assumes adapters emit an
|
||||
// item's non-terminal event before the root terminal; an item
|
||||
// first seen after the terminal is not pinned.
|
||||
const terminal = yield* Ref.get(terminalEvent);
|
||||
if (terminal !== null && terminal.status === "completed") {
|
||||
const backgroundItems = yield* Ref.get(activeBackgroundTurnItems);
|
||||
return backgroundItems.size === 0;
|
||||
}
|
||||
return true;
|
||||
const backgroundItems = yield* Ref.get(activeBackgroundTurnItems);
|
||||
return backgroundItems.size === 0;
|
||||
});
|
||||
const eventSubscription =
|
||||
input.session.subscribeEvents === undefined
|
||||
@@ -712,7 +967,8 @@ export const layer: Layer.Layer<
|
||||
Stream.tap((event) =>
|
||||
Effect.gen(function* () {
|
||||
let storedEventCount = 0;
|
||||
if (shouldDeliverProviderEvent(event, assistantStreamingEnabled)) {
|
||||
const shouldDeliver = shouldDeliverProviderEvent(event, assistantStreamingEnabled);
|
||||
if (shouldDeliver) {
|
||||
const storedEvents = yield* providerEventIngestor.ingestNormalized({
|
||||
providerSessionId: input.providerSessionId,
|
||||
providerInstanceId: input.run.providerInstanceId,
|
||||
@@ -752,7 +1008,7 @@ export const layer: Layer.Layer<
|
||||
yield* Ref.set(rootTerminalSeen, true);
|
||||
yield* finalizeRootRun(event);
|
||||
}
|
||||
yield* trackChildLifecycle(event);
|
||||
yield* trackChildLifecycle(event, shouldDeliver);
|
||||
}),
|
||||
),
|
||||
Stream.takeUntilEffect(() => shouldStopProviderEventIngestion),
|
||||
@@ -781,30 +1037,35 @@ export const layer: Layer.Layer<
|
||||
Effect.flatMap((providerThread) =>
|
||||
Ref.get(latestTurnItemOrdinal).pipe(
|
||||
Effect.flatMap((latestItemOrdinal) =>
|
||||
writeFinalRunEvents({
|
||||
run: input.run,
|
||||
rootNode: input.rootNode,
|
||||
checkpointScope: input.checkpointScope,
|
||||
providerThread,
|
||||
attempt: input.attempt,
|
||||
...(input.shouldFinalizeRun === undefined
|
||||
? {}
|
||||
: { shouldFinalizeRun: input.shouldFinalizeRun }),
|
||||
...(input.hasUnpairedRunInterruptRequest === undefined
|
||||
? {}
|
||||
: {
|
||||
hasUnpairedRunInterruptRequest:
|
||||
input.hasUnpairedRunInterruptRequest,
|
||||
}),
|
||||
terminal: makeFailedTerminalEvent(
|
||||
makeProviderFailure({
|
||||
cause: Cause.squash(cause),
|
||||
class: "unknown",
|
||||
Ref.get(openRunOwnedSubagents).pipe(
|
||||
Effect.flatMap((openSubagents) =>
|
||||
writeFinalRunEvents({
|
||||
run: input.run,
|
||||
rootNode: input.rootNode,
|
||||
checkpointScope: input.checkpointScope,
|
||||
providerThread,
|
||||
attempt: input.attempt,
|
||||
...(input.shouldFinalizeRun === undefined
|
||||
? {}
|
||||
: { shouldFinalizeRun: input.shouldFinalizeRun }),
|
||||
...(input.hasUnpairedRunInterruptRequest === undefined
|
||||
? {}
|
||||
: {
|
||||
hasUnpairedRunInterruptRequest:
|
||||
input.hasUnpairedRunInterruptRequest,
|
||||
}),
|
||||
openRunOwnedSubagents: openSubagents,
|
||||
terminal: makeFailedTerminalEvent(
|
||||
makeProviderFailure({
|
||||
cause: Cause.squash(cause),
|
||||
class: "unknown",
|
||||
}),
|
||||
latestItemOrdinal + 1,
|
||||
),
|
||||
failureItemPersisted: false,
|
||||
}),
|
||||
latestItemOrdinal + 1,
|
||||
),
|
||||
failureItemPersisted: false,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -858,30 +1119,35 @@ export const layer: Layer.Layer<
|
||||
Effect.flatMap((providerThread) =>
|
||||
Ref.get(latestTurnItemOrdinal).pipe(
|
||||
Effect.flatMap((latestItemOrdinal) =>
|
||||
writeFinalRunEvents({
|
||||
run: input.run,
|
||||
rootNode: input.rootNode,
|
||||
checkpointScope: input.checkpointScope,
|
||||
providerThread,
|
||||
attempt: input.attempt,
|
||||
...(input.shouldFinalizeRun === undefined
|
||||
? {}
|
||||
: { shouldFinalizeRun: input.shouldFinalizeRun }),
|
||||
...(input.hasUnpairedRunInterruptRequest === undefined
|
||||
? {}
|
||||
: {
|
||||
hasUnpairedRunInterruptRequest:
|
||||
input.hasUnpairedRunInterruptRequest,
|
||||
}),
|
||||
terminal: makeFailedTerminalEvent(
|
||||
makeProviderFailure({
|
||||
cause: Cause.squash(cause),
|
||||
class: "provider_error",
|
||||
Ref.get(openRunOwnedSubagents).pipe(
|
||||
Effect.flatMap((openSubagents) =>
|
||||
writeFinalRunEvents({
|
||||
run: input.run,
|
||||
rootNode: input.rootNode,
|
||||
checkpointScope: input.checkpointScope,
|
||||
providerThread,
|
||||
attempt: input.attempt,
|
||||
...(input.shouldFinalizeRun === undefined
|
||||
? {}
|
||||
: { shouldFinalizeRun: input.shouldFinalizeRun }),
|
||||
...(input.hasUnpairedRunInterruptRequest === undefined
|
||||
? {}
|
||||
: {
|
||||
hasUnpairedRunInterruptRequest:
|
||||
input.hasUnpairedRunInterruptRequest,
|
||||
}),
|
||||
openRunOwnedSubagents: openSubagents,
|
||||
terminal: makeFailedTerminalEvent(
|
||||
makeProviderFailure({
|
||||
cause: Cause.squash(cause),
|
||||
class: "provider_error",
|
||||
}),
|
||||
latestItemOrdinal + 1,
|
||||
),
|
||||
failureItemPersisted: false,
|
||||
}),
|
||||
latestItemOrdinal + 1,
|
||||
),
|
||||
failureItemPersisted: false,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -228,7 +228,14 @@ const scenarioExpectations = {
|
||||
approvalRequestCount: 0,
|
||||
},
|
||||
turn_interrupt_mid_tool: {
|
||||
outgoing: ["initialize", "initialized", "thread/start", "turn/start", "turn/interrupt"],
|
||||
outgoing: [
|
||||
"initialize",
|
||||
"initialized",
|
||||
"thread/start",
|
||||
"turn/start",
|
||||
"turn/interrupt",
|
||||
"thread/backgroundTerminals/terminate",
|
||||
],
|
||||
incoming: ["turn/started", "item/started", "turn/completed"],
|
||||
turnStartCount: 1,
|
||||
turnCompletedCount: 1,
|
||||
|
||||
+53
-1
@@ -38,6 +38,16 @@ function isCommandExecutionStartedFrame(frame: unknown): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
function frameParams(frame: unknown): Record<string, unknown> | undefined {
|
||||
if (typeof frame !== "object" || frame === null || !("params" in frame)) {
|
||||
return undefined;
|
||||
}
|
||||
const params = (frame as { readonly params?: unknown }).params;
|
||||
return typeof params === "object" && params !== null
|
||||
? (params as Record<string, unknown>)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function assertCodexInterruptAfterCommandExecution(transcript: ProviderReplayTranscript) {
|
||||
const commandIndex = transcript.entries.findIndex(
|
||||
(entry) => entry.type === "emit_inbound" && isCommandExecutionStartedFrame(entry.frame),
|
||||
@@ -45,12 +55,40 @@ function assertCodexInterruptAfterCommandExecution(transcript: ProviderReplayTra
|
||||
const interruptIndex = transcript.entries.findIndex(
|
||||
(entry) => entry.type === "expect_outbound" && protocolMethod(entry.frame) === "turn/interrupt",
|
||||
);
|
||||
const completedIndex = transcript.entries.findIndex(
|
||||
(entry) => entry.type === "emit_inbound" && protocolMethod(entry.frame) === "turn/completed",
|
||||
);
|
||||
const terminateIndex = transcript.entries.findIndex(
|
||||
(entry) =>
|
||||
entry.type === "expect_outbound" &&
|
||||
protocolMethod(entry.frame) === "thread/backgroundTerminals/terminate",
|
||||
);
|
||||
assert.isAtLeast(commandIndex, 0, "Codex interrupt fixture must record command execution start");
|
||||
assert.isAbove(
|
||||
interruptIndex,
|
||||
commandIndex,
|
||||
"Codex interrupt must be issued after command execution starts in replay",
|
||||
);
|
||||
assert.isAtLeast(
|
||||
completedIndex,
|
||||
0,
|
||||
"Codex interrupt fixture must record turn/completed before terminal cleanup",
|
||||
);
|
||||
assert.isAtLeast(
|
||||
terminateIndex,
|
||||
0,
|
||||
"Codex interrupt fixture must record background terminal terminate",
|
||||
);
|
||||
assert.isAbove(
|
||||
terminateIndex,
|
||||
completedIndex,
|
||||
"This recorded Codex interrupt fixture terminates background terminals after turn/completed",
|
||||
);
|
||||
const terminateEntry = transcript.entries[terminateIndex];
|
||||
const terminateParams =
|
||||
terminateEntry?.type === "expect_outbound" ? frameParams(terminateEntry.frame) : undefined;
|
||||
assert.equal(terminateParams?.threadId, "019e03b8-9e5c-7b32-88ab-f742a29b75b8");
|
||||
assert.equal(terminateParams?.processId, "4275");
|
||||
}
|
||||
|
||||
export function assertTurnInterruptMidToolCodexOutput(
|
||||
@@ -80,7 +118,10 @@ export function assertTurnInterruptMidToolCodexOutput(
|
||||
assert.isDefined(commandItem);
|
||||
assert.isDefined(interruptRequest);
|
||||
assert.isDefined(interruptResult);
|
||||
assert.include(["running", "completed", "failed"], commandItem.status);
|
||||
// Interrupted Codex turns must terminalize mid-flight commandExecution items so
|
||||
// the projected card is never left running forever after turn.terminal.
|
||||
assert.equal(commandItem.status, "interrupted");
|
||||
assert.isNotNull(commandItem.completedAt);
|
||||
assert.include(commandItem.input, "node -e");
|
||||
assert.equal(interruptRequest.status, "completed");
|
||||
assert.equal(interruptResult.status, "interrupted");
|
||||
@@ -91,4 +132,15 @@ export function assertTurnInterruptMidToolCodexOutput(
|
||||
);
|
||||
assert.equal(projection.providerThreads[0]?.status, "idle");
|
||||
assert.include(["interrupted", "cancelled"], projection.providerTurns[0]?.status);
|
||||
|
||||
const runningCommands = projection.turnItems.filter(
|
||||
(item) => item.type === "command_execution" && item.status === "running",
|
||||
);
|
||||
assert.lengthOf(runningCommands, 0, "interrupted turn must not leave running command items");
|
||||
|
||||
const toolNodes = projection.nodes.filter((node) => node.kind === "tool_call");
|
||||
for (const node of toolNodes) {
|
||||
assert.notEqual(node.status, "running", "interrupted turn tool nodes must be terminal");
|
||||
assert.isNotNull(node.completedAt);
|
||||
}
|
||||
}
|
||||
+2
@@ -30,4 +30,6 @@
|
||||
{"type":"emit_inbound","label":"turn/interrupt","frame":{"id":4,"result":{}}}
|
||||
{"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019e03b8-9e5c-7b32-88ab-f742a29b75b8","status":{"type":"idle"}}}}
|
||||
{"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"019e03b8-9e5c-7b32-88ab-f742a29b75b8","turn":{"id":"019e03b8-9f34-7bb1-8267-ad79b7e2e69a","items":[],"status":"interrupted","error":null,"startedAt":1778178891,"completedAt":1778178895,"durationMs":3792}}}}
|
||||
{"type":"expect_outbound","label":"thread/backgroundTerminals/terminate","frame":{"id":5,"method":"thread/backgroundTerminals/terminate","params":{"threadId":"019e03b8-9e5c-7b32-88ab-f742a29b75b8","processId":"4275"}}}
|
||||
{"type":"emit_inbound","label":"thread/backgroundTerminals/terminate","frame":{"id":5,"result":{"terminated":true}}}
|
||||
{"type":"runtime_exit","status":"success"}
|
||||
Reference in new issue
Block a user