[orchestrator-v2] fix(orchestrator): Codex background command completion and subagent resume (#3908)
This commit is contained in:
1 parent
b883940c9a
commit
b6d302cd82
3 files changed
+1030
-34
No files matched your search
@@ -1,38 +1,64 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import {
|
||||
CheckpointId,
|
||||
CodexSettings,
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
type ModelSelection,
|
||||
NodeId,
|
||||
type OrchestrationV2AppThread,
|
||||
type OrchestrationV2ProviderThread,
|
||||
type OrchestrationV2ProviderTurn,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
RunAttemptId,
|
||||
RunId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import { SpawnExecutableResolution } from "@t3tools/shared/shell";
|
||||
import * as CodexClient from "effect-codex-app-server/client";
|
||||
import * as CodexReplay from "effect-codex-app-server/replay";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { TestClock } from "effect/testing";
|
||||
import { ChildProcess } from "effect/unstable/process";
|
||||
|
||||
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
|
||||
import type { EventNdjsonLogger } from "../../provider/Layers/EventNdjsonLogger.ts";
|
||||
import { layer as idAllocatorLayer, IdAllocatorV2 } from "../IdAllocator.ts";
|
||||
import {
|
||||
ProviderAdapterOpenSessionError,
|
||||
ProviderAdapterV2RuntimePolicy,
|
||||
type ProviderAdapterV2Event,
|
||||
type ProviderAdapterV2TurnInput,
|
||||
} from "../ProviderAdapter.ts";
|
||||
import type { ProviderContinuationRequest } from "../ProviderContinuationRequests.ts";
|
||||
import {
|
||||
buildCodexTurnStartParams,
|
||||
CODEX_DEFAULT_INSTANCE_ID,
|
||||
CODEX_DRIVER_KIND,
|
||||
codexBackgroundCommandDetail,
|
||||
codexThreadRuntimeParams,
|
||||
type CodexAgentMessageDeltaUpdate,
|
||||
type CodexAppServerClientFactoryShape,
|
||||
makeCodexAdapterV2,
|
||||
makeCodexAgentMessageDeltaCoalescer,
|
||||
makeCodexAppServerProtocolLogger,
|
||||
makeCodexAppServerSpawnCommand,
|
||||
projectCodexDynamicToolItem,
|
||||
resolveCodexRollbackTurnCount,
|
||||
} from "./CodexAdapterV2.ts";
|
||||
import { makeReplayServerConfig } from "./CodexAdapterV2.testkit.ts";
|
||||
|
||||
describe("CodexAdapterV2 assistant message streaming", () => {
|
||||
it.effect("makes accumulated assistant text visible after the bounded flush interval", () =>
|
||||
@@ -499,3 +525,796 @@ describe("CodexAdapterV2 rollback mapping", () => {
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("CodexAdapterV2 background command detail", () => {
|
||||
it("summarizes command, exit code, and output tail", () => {
|
||||
assert.equal(
|
||||
codexBackgroundCommandDetail({
|
||||
command: "sleep 20 && echo CODEX_BG_WAKE_DONE",
|
||||
exitCode: 0,
|
||||
aggregatedOutput: "CODEX_BG_WAKE_DONE\n",
|
||||
}),
|
||||
"Background command completed (exit 0): sleep 20 && echo CODEX_BG_WAKE_DONE\n\n" +
|
||||
"Output tail:\nCODEX_BG_WAKE_DONE",
|
||||
);
|
||||
});
|
||||
|
||||
it("omits the output section and exit code when absent", () => {
|
||||
assert.equal(
|
||||
codexBackgroundCommandDetail({
|
||||
command: "sleep 20",
|
||||
exitCode: null,
|
||||
aggregatedOutput: null,
|
||||
}),
|
||||
"Background command completed: sleep 20",
|
||||
);
|
||||
});
|
||||
|
||||
it("truncates long commands and keeps only the output tail", () => {
|
||||
const detail = codexBackgroundCommandDetail({
|
||||
command: "x".repeat(300),
|
||||
exitCode: 1,
|
||||
aggregatedOutput: `${"y".repeat(2000)}TAIL`,
|
||||
});
|
||||
assert.include(detail, `(exit 1): ${"x".repeat(200)}...`);
|
||||
assert.include(detail, "Output tail:\n...");
|
||||
assert.include(detail, "TAIL");
|
||||
assert.notInclude(detail, "y".repeat(1001));
|
||||
});
|
||||
});
|
||||
|
||||
const DEFAULT_CODEX_SETTINGS = Schema.decodeSync(CodexSettings)({});
|
||||
const CODEX_TEST_MODEL_SELECTION = {
|
||||
instanceId: CODEX_DEFAULT_INSTANCE_ID,
|
||||
model: "gpt-5.4",
|
||||
} satisfies ModelSelection;
|
||||
const CODEX_TEST_RUNTIME_POLICY = ProviderAdapterV2RuntimePolicy.make({
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
cwd: "/workspace",
|
||||
});
|
||||
|
||||
function makeCodexTestAppThread(input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly providerThread: OrchestrationV2ProviderThread;
|
||||
readonly now: DateTime.Utc;
|
||||
}): OrchestrationV2AppThread {
|
||||
return {
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
id: input.threadId,
|
||||
projectId: ProjectId.make(`project-${input.threadId}`),
|
||||
title: "Codex continuation test",
|
||||
providerInstanceId: CODEX_DEFAULT_INSTANCE_ID,
|
||||
modelSelection: CODEX_TEST_MODEL_SELECTION,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
activeProviderThreadId: input.providerThread.id,
|
||||
lineage: {
|
||||
parentThreadId: null,
|
||||
relationshipToParent: null,
|
||||
rootThreadId: input.threadId,
|
||||
},
|
||||
forkedFrom: null,
|
||||
createdAt: input.now,
|
||||
updatedAt: input.now,
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
};
|
||||
}
|
||||
|
||||
function makeCodexTestTurnInput(input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly providerThread: OrchestrationV2ProviderThread;
|
||||
readonly now: DateTime.Utc;
|
||||
readonly attemptId: RunAttemptId;
|
||||
readonly text: string;
|
||||
}): ProviderAdapterV2TurnInput {
|
||||
return {
|
||||
appThread: makeCodexTestAppThread(input),
|
||||
threadId: input.threadId,
|
||||
runId: RunId.make(`run-${input.attemptId}`),
|
||||
runOrdinal: 1,
|
||||
providerTurnOrdinal: 1,
|
||||
attemptId: input.attemptId,
|
||||
rootNodeId: NodeId.make(`node-${input.attemptId}`),
|
||||
providerThread: input.providerThread,
|
||||
message: {
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
messageId: MessageId.make(`message-${input.attemptId}`),
|
||||
text: input.text,
|
||||
attachments: [],
|
||||
},
|
||||
modelSelection: CODEX_TEST_MODEL_SELECTION,
|
||||
runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
|
||||
};
|
||||
}
|
||||
|
||||
function makeCodexReplayTurn(input: {
|
||||
readonly id: string;
|
||||
readonly status: "inProgress" | "completed";
|
||||
}): Record<string, unknown> {
|
||||
return {
|
||||
id: input.id,
|
||||
items: [],
|
||||
itemsView: "notLoaded",
|
||||
status: input.status,
|
||||
error: null,
|
||||
startedAt: 1782622440,
|
||||
completedAt: input.status === "completed" ? 1782622450 : null,
|
||||
durationMs: null,
|
||||
};
|
||||
}
|
||||
|
||||
function codexReplayPreamble(input: {
|
||||
readonly nativeThreadId: string;
|
||||
readonly nativeTurnId: string;
|
||||
readonly prompt: string;
|
||||
}): Array<CodexReplay.CodexAppServerReplayEntry> {
|
||||
return [
|
||||
{
|
||||
type: "expect_outbound",
|
||||
label: "initialize",
|
||||
frame: {
|
||||
id: 1,
|
||||
method: "initialize",
|
||||
params: {
|
||||
clientInfo: { name: "t3code_desktop", title: "T3 Code Desktop", version: "0.1.0" },
|
||||
capabilities: { experimentalApi: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "emit_inbound",
|
||||
label: "initialize",
|
||||
frame: {
|
||||
id: 1,
|
||||
result: {
|
||||
userAgent: "t3code_desktop/0.144.0",
|
||||
codexHome: "/tmp/codex-home",
|
||||
platformFamily: "unix",
|
||||
platformOs: "macos",
|
||||
},
|
||||
},
|
||||
},
|
||||
{ type: "expect_outbound", label: "initialized", frame: { method: "initialized" } },
|
||||
{
|
||||
type: "expect_outbound",
|
||||
label: "thread/start",
|
||||
frame: { id: 2, method: "thread/start", params: {} },
|
||||
},
|
||||
{
|
||||
type: "emit_inbound",
|
||||
label: "thread/start",
|
||||
frame: {
|
||||
id: 2,
|
||||
result: {
|
||||
thread: {
|
||||
id: input.nativeThreadId,
|
||||
sessionId: input.nativeThreadId,
|
||||
forkedFromId: null,
|
||||
preview: "",
|
||||
ephemeral: false,
|
||||
modelProvider: "openai",
|
||||
createdAt: 1782622440,
|
||||
updatedAt: 1782622440,
|
||||
status: { type: "idle" },
|
||||
path: `/tmp/${input.nativeThreadId}.jsonl`,
|
||||
cwd: "/workspace",
|
||||
cliVersion: "0.144.0",
|
||||
source: "vscode",
|
||||
threadSource: null,
|
||||
agentNickname: null,
|
||||
agentRole: null,
|
||||
gitInfo: null,
|
||||
name: null,
|
||||
turns: [],
|
||||
},
|
||||
model: "gpt-5.4",
|
||||
modelProvider: "openai",
|
||||
serviceTier: null,
|
||||
cwd: "/workspace",
|
||||
instructionSources: [],
|
||||
approvalPolicy: "on-request",
|
||||
approvalsReviewer: "user",
|
||||
sandbox: { type: "workspaceWrite", writableRoots: [], networkAccess: false },
|
||||
reasoningEffort: "medium",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "expect_outbound",
|
||||
label: "turn/start",
|
||||
frame: {
|
||||
id: 3,
|
||||
method: "turn/start",
|
||||
params: {
|
||||
threadId: input.nativeThreadId,
|
||||
input: [{ type: "text", text: input.prompt }],
|
||||
cwd: "/workspace",
|
||||
model: "gpt-5.4",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "emit_inbound",
|
||||
label: "turn/start",
|
||||
frame: {
|
||||
id: 3,
|
||||
result: { turn: makeCodexReplayTurn({ id: input.nativeTurnId, status: "inProgress" }) },
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "emit_inbound",
|
||||
label: "turn/started",
|
||||
frame: {
|
||||
method: "turn/started",
|
||||
params: {
|
||||
threadId: input.nativeThreadId,
|
||||
turn: makeCodexReplayTurn({ id: input.nativeTurnId, status: "inProgress" }),
|
||||
},
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function makeCodexReplayTranscript(input: {
|
||||
readonly scenario: string;
|
||||
readonly entries: ReadonlyArray<CodexReplay.CodexAppServerReplayEntry>;
|
||||
}): CodexReplay.CodexAppServerReplayTranscript {
|
||||
return {
|
||||
provider: "codex",
|
||||
protocol: "codex.app-server",
|
||||
version: "0.144.0",
|
||||
scenario: input.scenario,
|
||||
entries: input.entries,
|
||||
};
|
||||
}
|
||||
|
||||
describe("CodexAdapterV2 post-settle continuation", () => {
|
||||
const awaitUntil = (predicate: () => boolean, label: string): Effect.Effect<void> =>
|
||||
Effect.gen(function* () {
|
||||
for (let attempt = 0; attempt < 5000; attempt++) {
|
||||
if (predicate()) {
|
||||
return;
|
||||
}
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
return yield* Effect.die(`Timed out waiting for ${label}.`);
|
||||
});
|
||||
|
||||
const makeCodexReplayHarness = (transcript: CodexReplay.CodexAppServerReplayTranscript) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const idAllocator = yield* IdAllocatorV2;
|
||||
const serverConfig = yield* makeReplayServerConfig(transcript.scenario).pipe(Effect.orDie);
|
||||
const continuationRequests: Array<ProviderContinuationRequest> = [];
|
||||
const clientFactory: CodexAppServerClientFactoryShape = {
|
||||
open: (openInput) =>
|
||||
Layer.build(CodexReplay.layerReplay(transcript)).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterOpenSessionError({
|
||||
driver: CODEX_DRIVER_KIND,
|
||||
providerSessionId: openInput.providerSessionId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((context) =>
|
||||
Effect.service(CodexClient.CodexAppServerClient).pipe(Effect.provide(context)),
|
||||
),
|
||||
),
|
||||
};
|
||||
const adapter = makeCodexAdapterV2({
|
||||
instanceId: CODEX_DEFAULT_INSTANCE_ID,
|
||||
settings: DEFAULT_CODEX_SETTINGS,
|
||||
environment: {},
|
||||
clientFactory,
|
||||
fileSystem,
|
||||
idAllocator,
|
||||
serverConfig,
|
||||
continuationRequests: {
|
||||
offer: (request) =>
|
||||
Effect.sync(() => {
|
||||
continuationRequests.push(request);
|
||||
}),
|
||||
},
|
||||
});
|
||||
const threadId = ThreadId.make(`thread-${transcript.scenario}`);
|
||||
const runtime = yield* adapter.openSession({
|
||||
threadId,
|
||||
providerSessionId: ProviderSessionId.make(`provider-session-${transcript.scenario}`),
|
||||
modelSelection: CODEX_TEST_MODEL_SELECTION,
|
||||
runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
|
||||
});
|
||||
const providerThread = yield* runtime.ensureThread({
|
||||
threadId,
|
||||
modelSelection: CODEX_TEST_MODEL_SELECTION,
|
||||
runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
|
||||
});
|
||||
const events: Array<ProviderAdapterV2Event> = [];
|
||||
yield* runtime.events.pipe(
|
||||
Stream.runForEach((event) =>
|
||||
Effect.sync(() => {
|
||||
events.push(event);
|
||||
}),
|
||||
),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
if (runtime.hasPendingBackgroundWork === undefined) {
|
||||
return yield* Effect.die("Codex adapter runtime must expose hasPendingBackgroundWork.");
|
||||
}
|
||||
const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork;
|
||||
const terminalEvents = () =>
|
||||
events.filter(
|
||||
(event): event is Extract<ProviderAdapterV2Event, { type: "turn.terminal" }> =>
|
||||
event.type === "turn.terminal",
|
||||
);
|
||||
const subagentUpdates = () =>
|
||||
events.filter(
|
||||
(event): event is Extract<ProviderAdapterV2Event, { type: "subagent.updated" }> =>
|
||||
event.type === "subagent.updated",
|
||||
);
|
||||
return {
|
||||
runtime,
|
||||
providerThread,
|
||||
threadId,
|
||||
events,
|
||||
continuationRequests,
|
||||
terminalEvents,
|
||||
subagentUpdates,
|
||||
hasPendingBackgroundWork,
|
||||
};
|
||||
});
|
||||
|
||||
const BG_SCENARIO = "codex-bg-exec-wake";
|
||||
const BG_NATIVE_THREAD = "native-codex-bg-thread";
|
||||
const BG_NATIVE_TURN = "native-codex-bg-turn";
|
||||
const BG_COMMAND_ITEM = "call-codex-bg-command";
|
||||
const BG_COMMAND = "sleep 20 && echo CODEX_BG_WAKE_DONE";
|
||||
const BG_PROMPT = "Start the sleep in the background and reply STARTED.";
|
||||
|
||||
const backgroundCommandItem = (status: "inProgress" | "completed"): Record<string, unknown> => ({
|
||||
type: "commandExecution",
|
||||
id: BG_COMMAND_ITEM,
|
||||
command: BG_COMMAND,
|
||||
cwd: "/workspace",
|
||||
processId: "4242",
|
||||
source: "unifiedExecStartup",
|
||||
status,
|
||||
commandActions: [{ type: "unknown", command: BG_COMMAND }],
|
||||
aggregatedOutput: status === "completed" ? "CODEX_BG_WAKE_DONE\n" : null,
|
||||
exitCode: status === "completed" ? 0 : null,
|
||||
durationMs: status === "completed" ? 25_000 : null,
|
||||
});
|
||||
|
||||
const backgroundExecTranscript = makeCodexReplayTranscript({
|
||||
scenario: BG_SCENARIO,
|
||||
entries: [
|
||||
...codexReplayPreamble({
|
||||
nativeThreadId: BG_NATIVE_THREAD,
|
||||
nativeTurnId: BG_NATIVE_TURN,
|
||||
prompt: BG_PROMPT,
|
||||
}),
|
||||
{
|
||||
type: "emit_inbound",
|
||||
label: "item/started/command",
|
||||
frame: {
|
||||
method: "item/started",
|
||||
params: {
|
||||
item: backgroundCommandItem("inProgress"),
|
||||
threadId: BG_NATIVE_THREAD,
|
||||
turnId: BG_NATIVE_TURN,
|
||||
startedAtMs: 1782622440500,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "emit_inbound",
|
||||
label: "item/completed/root-answer",
|
||||
frame: {
|
||||
method: "item/completed",
|
||||
params: {
|
||||
item: {
|
||||
type: "agentMessage",
|
||||
id: "root-answer-bg",
|
||||
text: "STARTED",
|
||||
phase: "final_answer",
|
||||
memoryCitation: null,
|
||||
},
|
||||
threadId: BG_NATIVE_THREAD,
|
||||
turnId: BG_NATIVE_TURN,
|
||||
completedAtMs: 1782622441000,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "emit_inbound",
|
||||
label: "turn/completed",
|
||||
frame: {
|
||||
method: "turn/completed",
|
||||
params: {
|
||||
threadId: BG_NATIVE_THREAD,
|
||||
turn: makeCodexReplayTurn({ id: BG_NATIVE_TURN, status: "completed" }),
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "emit_inbound",
|
||||
label: "item/completed/command-late",
|
||||
afterMs: 30_000,
|
||||
frame: {
|
||||
method: "item/completed",
|
||||
params: {
|
||||
item: backgroundCommandItem("completed"),
|
||||
threadId: BG_NATIVE_THREAD,
|
||||
turnId: BG_NATIVE_TURN,
|
||||
completedAtMs: 1782622465500,
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"projects a post-settle background command completion and requests a continuation",
|
||||
() =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* makeCodexReplayHarness(backgroundExecTranscript);
|
||||
const now = yield* DateTime.now;
|
||||
|
||||
yield* harness.runtime.startTurn(
|
||||
makeCodexTestTurnInput({
|
||||
threadId: harness.threadId,
|
||||
providerThread: harness.providerThread,
|
||||
now,
|
||||
attemptId: RunAttemptId.make("attempt-codex-bg-wake"),
|
||||
text: BG_PROMPT,
|
||||
}),
|
||||
);
|
||||
yield* awaitUntil(() => harness.terminalEvents().length === 1, "root turn terminal");
|
||||
assert.equal(harness.terminalEvents()[0]?.status, "completed");
|
||||
assert.isTrue(yield* harness.hasPendingBackgroundWork);
|
||||
assert.lengthOf(harness.continuationRequests, 0);
|
||||
const terminalIndex = harness.events.findIndex((event) => event.type === "turn.terminal");
|
||||
|
||||
yield* TestClock.adjust("30 seconds");
|
||||
yield* awaitUntil(
|
||||
() => harness.continuationRequests.length === 1,
|
||||
"continuation request",
|
||||
);
|
||||
const request = harness.continuationRequests[0];
|
||||
assert.equal(request?.threadId, harness.threadId);
|
||||
assert.equal(request?.providerThreadId, harness.providerThread.id);
|
||||
assert.equal(request?.driver, CODEX_DRIVER_KIND);
|
||||
assert.equal(
|
||||
request?.detail,
|
||||
`Background command completed (exit 0): ${BG_COMMAND}\n\n` +
|
||||
"Output tail:\nCODEX_BG_WAKE_DONE",
|
||||
);
|
||||
|
||||
const lateCommandUpdateIndex = () =>
|
||||
harness.events.findIndex(
|
||||
(event, index) =>
|
||||
index > terminalIndex &&
|
||||
event.type === "turn_item.updated" &&
|
||||
event.turnItem.type === "command_execution" &&
|
||||
event.turnItem.status === "completed" &&
|
||||
event.turnItem.output === "CODEX_BG_WAKE_DONE\n" &&
|
||||
event.turnItem.exitCode === 0,
|
||||
);
|
||||
yield* awaitUntil(
|
||||
() => lateCommandUpdateIndex() > terminalIndex,
|
||||
"post-settle command projection",
|
||||
);
|
||||
assert.lengthOf(harness.terminalEvents(), 1);
|
||||
assert.isFalse(yield* harness.hasPendingBackgroundWork);
|
||||
}).pipe(Effect.provide(Layer.merge(idAllocatorLayer, NodeServices.layer))),
|
||||
),
|
||||
);
|
||||
|
||||
const PRE_SETTLE_SCENARIO = "codex-bg-exec-pre-settle";
|
||||
const PRE_SETTLE_NATIVE_THREAD = "native-codex-pre-settle-thread";
|
||||
const PRE_SETTLE_NATIVE_TURN = "native-codex-pre-settle-turn";
|
||||
|
||||
const preSettleTranscript = makeCodexReplayTranscript({
|
||||
scenario: PRE_SETTLE_SCENARIO,
|
||||
entries: [
|
||||
...codexReplayPreamble({
|
||||
nativeThreadId: PRE_SETTLE_NATIVE_THREAD,
|
||||
nativeTurnId: PRE_SETTLE_NATIVE_TURN,
|
||||
prompt: BG_PROMPT,
|
||||
}),
|
||||
{
|
||||
type: "emit_inbound",
|
||||
label: "item/started/command",
|
||||
frame: {
|
||||
method: "item/started",
|
||||
params: {
|
||||
item: backgroundCommandItem("inProgress"),
|
||||
threadId: PRE_SETTLE_NATIVE_THREAD,
|
||||
turnId: PRE_SETTLE_NATIVE_TURN,
|
||||
startedAtMs: 1782622440500,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "emit_inbound",
|
||||
label: "item/completed/command-pre-settle",
|
||||
frame: {
|
||||
method: "item/completed",
|
||||
params: {
|
||||
item: backgroundCommandItem("completed"),
|
||||
threadId: PRE_SETTLE_NATIVE_THREAD,
|
||||
turnId: PRE_SETTLE_NATIVE_TURN,
|
||||
completedAtMs: 1782622441000,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "emit_inbound",
|
||||
label: "item/completed/root-answer",
|
||||
frame: {
|
||||
method: "item/completed",
|
||||
params: {
|
||||
item: {
|
||||
type: "agentMessage",
|
||||
id: "root-answer-pre-settle",
|
||||
text: "DONE",
|
||||
phase: "final_answer",
|
||||
memoryCitation: null,
|
||||
},
|
||||
threadId: PRE_SETTLE_NATIVE_THREAD,
|
||||
turnId: PRE_SETTLE_NATIVE_TURN,
|
||||
completedAtMs: 1782622441500,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "emit_inbound",
|
||||
label: "turn/completed",
|
||||
frame: {
|
||||
method: "turn/completed",
|
||||
params: {
|
||||
threadId: PRE_SETTLE_NATIVE_THREAD,
|
||||
turn: makeCodexReplayTurn({ id: PRE_SETTLE_NATIVE_TURN, status: "completed" }),
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
it.effect("does not request a continuation for a command that completes before settle", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* makeCodexReplayHarness(preSettleTranscript);
|
||||
const now = yield* DateTime.now;
|
||||
|
||||
yield* harness.runtime.startTurn(
|
||||
makeCodexTestTurnInput({
|
||||
threadId: harness.threadId,
|
||||
providerThread: harness.providerThread,
|
||||
now,
|
||||
attemptId: RunAttemptId.make("attempt-codex-bg-pre-settle"),
|
||||
text: BG_PROMPT,
|
||||
}),
|
||||
);
|
||||
yield* awaitUntil(() => harness.terminalEvents().length === 1, "root turn terminal");
|
||||
assert.equal(harness.terminalEvents()[0]?.status, "completed");
|
||||
yield* awaitUntil(
|
||||
() =>
|
||||
harness.events.some(
|
||||
(event) =>
|
||||
event.type === "turn_item.updated" &&
|
||||
event.turnItem.type === "command_execution" &&
|
||||
event.turnItem.status === "completed" &&
|
||||
event.turnItem.exitCode === 0,
|
||||
),
|
||||
"pre-settle command projection",
|
||||
);
|
||||
|
||||
yield* TestClock.adjust("30 seconds");
|
||||
for (let attempt = 0; attempt < 100; attempt++) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
assert.lengthOf(harness.continuationRequests, 0);
|
||||
assert.isFalse(yield* harness.hasPendingBackgroundWork);
|
||||
assert.lengthOf(harness.terminalEvents(), 1);
|
||||
}).pipe(Effect.provide(Layer.merge(idAllocatorLayer, NodeServices.layer))),
|
||||
),
|
||||
);
|
||||
|
||||
const RESUME_SCENARIO = "codex-resume-subagent";
|
||||
const RESUME_NATIVE_THREAD = "native-codex-resume-thread";
|
||||
const RESUME_NATIVE_TURN = "native-codex-resume-root-turn";
|
||||
const RESUME_CHILD_THREAD = "native-codex-resume-child-thread";
|
||||
const RESUME_CHILD_TURN_1 = "native-codex-resume-child-turn-1";
|
||||
const RESUME_CHILD_TURN_2 = "native-codex-resume-child-turn-2";
|
||||
const RESUME_PROMPT = "Spawn a sub-agent, nudge it, and reply NUDGED.";
|
||||
|
||||
const childAgentMessage = (input: {
|
||||
readonly id: string;
|
||||
readonly text: string;
|
||||
readonly turnId: string;
|
||||
readonly completedAtMs: number;
|
||||
readonly afterMs?: number;
|
||||
}): CodexReplay.CodexAppServerReplayEntry => ({
|
||||
type: "emit_inbound",
|
||||
label: `item/completed/${input.id}`,
|
||||
...(input.afterMs === undefined ? {} : { afterMs: input.afterMs }),
|
||||
frame: {
|
||||
method: "item/completed",
|
||||
params: {
|
||||
item: {
|
||||
type: "agentMessage",
|
||||
id: input.id,
|
||||
text: input.text,
|
||||
phase: "final_answer",
|
||||
memoryCitation: null,
|
||||
},
|
||||
threadId: RESUME_CHILD_THREAD,
|
||||
turnId: input.turnId,
|
||||
completedAtMs: input.completedAtMs,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const childTurnStarted = (
|
||||
turnId: string,
|
||||
afterMs?: number,
|
||||
): CodexReplay.CodexAppServerReplayEntry => ({
|
||||
type: "emit_inbound",
|
||||
label: `turn/started/${turnId}`,
|
||||
...(afterMs === undefined ? {} : { afterMs }),
|
||||
frame: {
|
||||
method: "turn/started",
|
||||
params: {
|
||||
threadId: RESUME_CHILD_THREAD,
|
||||
turn: makeCodexReplayTurn({ id: turnId, status: "inProgress" }),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const childTurnCompleted = (turnId: string): CodexReplay.CodexAppServerReplayEntry => ({
|
||||
type: "emit_inbound",
|
||||
label: `turn/completed/${turnId}`,
|
||||
frame: {
|
||||
method: "turn/completed",
|
||||
params: {
|
||||
threadId: RESUME_CHILD_THREAD,
|
||||
turn: makeCodexReplayTurn({ id: turnId, status: "completed" }),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const resumeSubagentTranscript = makeCodexReplayTranscript({
|
||||
scenario: RESUME_SCENARIO,
|
||||
entries: [
|
||||
...codexReplayPreamble({
|
||||
nativeThreadId: RESUME_NATIVE_THREAD,
|
||||
nativeTurnId: RESUME_NATIVE_TURN,
|
||||
prompt: RESUME_PROMPT,
|
||||
}),
|
||||
{
|
||||
type: "emit_inbound",
|
||||
label: "item/completed/subAgentActivity-started",
|
||||
frame: {
|
||||
method: "item/completed",
|
||||
params: {
|
||||
item: {
|
||||
type: "subAgentActivity",
|
||||
id: "call-codex-resume-spawn",
|
||||
kind: "started",
|
||||
agentThreadId: RESUME_CHILD_THREAD,
|
||||
agentPath: "/root/resume_agent",
|
||||
},
|
||||
threadId: RESUME_NATIVE_THREAD,
|
||||
turnId: RESUME_NATIVE_TURN,
|
||||
completedAtMs: 1782622441000,
|
||||
},
|
||||
},
|
||||
},
|
||||
childTurnStarted(RESUME_CHILD_TURN_1),
|
||||
childAgentMessage({
|
||||
id: "child-first-answer",
|
||||
text: "CODEX_FIRST_DONE",
|
||||
turnId: RESUME_CHILD_TURN_1,
|
||||
completedAtMs: 1782622442000,
|
||||
}),
|
||||
childTurnCompleted(RESUME_CHILD_TURN_1),
|
||||
{
|
||||
type: "emit_inbound",
|
||||
label: "item/completed/root-answer",
|
||||
frame: {
|
||||
method: "item/completed",
|
||||
params: {
|
||||
item: {
|
||||
type: "agentMessage",
|
||||
id: "root-answer-resume",
|
||||
text: "NUDGED",
|
||||
phase: "final_answer",
|
||||
memoryCitation: null,
|
||||
},
|
||||
threadId: RESUME_NATIVE_THREAD,
|
||||
turnId: RESUME_NATIVE_TURN,
|
||||
completedAtMs: 1782622443000,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "emit_inbound",
|
||||
label: "turn/completed/root",
|
||||
frame: {
|
||||
method: "turn/completed",
|
||||
params: {
|
||||
threadId: RESUME_NATIVE_THREAD,
|
||||
turn: makeCodexReplayTurn({ id: RESUME_NATIVE_TURN, status: "completed" }),
|
||||
},
|
||||
},
|
||||
},
|
||||
childTurnStarted(RESUME_CHILD_TURN_2, 30_000),
|
||||
childAgentMessage({
|
||||
id: "child-resume-answer",
|
||||
text: "CODEX_RESUME_DONE",
|
||||
turnId: RESUME_CHILD_TURN_2,
|
||||
completedAtMs: 1782622480000,
|
||||
afterMs: 30_000,
|
||||
}),
|
||||
childTurnCompleted(RESUME_CHILD_TURN_2),
|
||||
],
|
||||
});
|
||||
|
||||
it.effect("re-opens a resumed subagent and hydrates its post-settle result", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* makeCodexReplayHarness(resumeSubagentTranscript);
|
||||
const now = yield* DateTime.now;
|
||||
|
||||
yield* harness.runtime.startTurn(
|
||||
makeCodexTestTurnInput({
|
||||
threadId: harness.threadId,
|
||||
providerThread: harness.providerThread,
|
||||
now,
|
||||
attemptId: RunAttemptId.make("attempt-codex-resume"),
|
||||
text: RESUME_PROMPT,
|
||||
}),
|
||||
);
|
||||
yield* awaitUntil(() => harness.terminalEvents().length === 1, "root turn terminal");
|
||||
assert.equal(harness.terminalEvents()[0]?.status, "completed");
|
||||
const settledUpdates = harness.subagentUpdates();
|
||||
const firstCompletion = settledUpdates[settledUpdates.length - 1];
|
||||
assert.equal(firstCompletion?.subagent.status, "completed");
|
||||
assert.equal(firstCompletion?.subagent.result, "CODEX_FIRST_DONE");
|
||||
assert.isFalse(yield* harness.hasPendingBackgroundWork);
|
||||
const settledUpdateCount = settledUpdates.length;
|
||||
|
||||
yield* TestClock.adjust("30 seconds");
|
||||
yield* awaitUntil(
|
||||
() => harness.subagentUpdates().length > settledUpdateCount,
|
||||
"subagent re-open",
|
||||
);
|
||||
const reopened = harness.subagentUpdates()[settledUpdateCount];
|
||||
assert.equal(reopened?.subagent.status, "running");
|
||||
assert.isTrue(yield* harness.hasPendingBackgroundWork);
|
||||
|
||||
yield* TestClock.adjust("30 seconds");
|
||||
yield* awaitUntil(() => {
|
||||
const updates = harness.subagentUpdates();
|
||||
const latest = updates[updates.length - 1];
|
||||
return (
|
||||
latest !== undefined &&
|
||||
latest.subagent.status === "completed" &&
|
||||
latest.subagent.result === "CODEX_RESUME_DONE"
|
||||
);
|
||||
}, "resumed subagent completion");
|
||||
assert.isFalse(yield* harness.hasPendingBackgroundWork);
|
||||
assert.lengthOf(harness.terminalEvents(), 1);
|
||||
assert.lengthOf(harness.continuationRequests, 0);
|
||||
}).pipe(Effect.provide(Layer.merge(idAllocatorLayer, NodeServices.layer))),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -48,7 +48,7 @@ function metadataFromTranscript(transcript: ProviderReplayTranscript): {
|
||||
};
|
||||
}
|
||||
|
||||
function makeReplayServerConfig(
|
||||
export function makeReplayServerConfig(
|
||||
scenario: string,
|
||||
): Effect.Effect<
|
||||
ServerConfig["Service"],
|
||||
|
||||
@@ -63,6 +63,10 @@ import {
|
||||
type ProviderAdapterDriver,
|
||||
} from "../ProviderAdapterDriver.ts";
|
||||
import { IdAllocatorV2, type IdAllocatorV2Shape } from "../IdAllocator.ts";
|
||||
import {
|
||||
type ProviderContinuationRequest,
|
||||
ProviderContinuationRequests,
|
||||
} from "../ProviderContinuationRequests.ts";
|
||||
import { makeProviderFailure } from "../ProviderFailure.ts";
|
||||
import { turnScopedSelectionTransition } from "../ProviderSelectionTransition.ts";
|
||||
import {
|
||||
@@ -282,6 +286,29 @@ function codexItemStatus(status: "inProgress" | "completed" | "failed" | "declin
|
||||
}
|
||||
}
|
||||
|
||||
const BACKGROUND_COMMAND_DETAIL_COMMAND_MAX_LENGTH = 200;
|
||||
const BACKGROUND_COMMAND_DETAIL_OUTPUT_TAIL_MAX_LENGTH = 1_000;
|
||||
|
||||
export function codexBackgroundCommandDetail(item: {
|
||||
readonly command: string;
|
||||
readonly exitCode?: number | null | undefined;
|
||||
readonly aggregatedOutput?: string | null | undefined;
|
||||
}): string {
|
||||
const command =
|
||||
item.command.length > BACKGROUND_COMMAND_DETAIL_COMMAND_MAX_LENGTH
|
||||
? `${item.command.slice(0, BACKGROUND_COMMAND_DETAIL_COMMAND_MAX_LENGTH)}...`
|
||||
: item.command;
|
||||
const exit =
|
||||
item.exitCode === null || item.exitCode === undefined ? "" : ` (exit ${item.exitCode})`;
|
||||
const output = (item.aggregatedOutput ?? "").trimEnd();
|
||||
const outputTail =
|
||||
output.length > BACKGROUND_COMMAND_DETAIL_OUTPUT_TAIL_MAX_LENGTH
|
||||
? `...${output.slice(-BACKGROUND_COMMAND_DETAIL_OUTPUT_TAIL_MAX_LENGTH)}`
|
||||
: output;
|
||||
const header = `Background command completed${exit}: ${command}`;
|
||||
return outputTail.length === 0 ? header : `${header}\n\nOutput tail:\n${outputTail}`;
|
||||
}
|
||||
|
||||
export interface CodexDynamicToolProjection {
|
||||
readonly toolName: string;
|
||||
readonly input: unknown;
|
||||
@@ -1165,6 +1192,7 @@ export const CodexAdapterV2Driver: ProviderAdapterDriver<CodexSettings, CodexAda
|
||||
create: ({ instanceId, environment, enabled, config }) =>
|
||||
Effect.gen(function* () {
|
||||
const clientFactory = yield* CodexAppServerClientFactory;
|
||||
const continuationRequests = yield* ProviderContinuationRequests;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const hostEnvironment = yield* HostProcessEnvironment;
|
||||
const idAllocator = yield* IdAllocatorV2;
|
||||
@@ -1197,6 +1225,7 @@ export const CodexAdapterV2Driver: ProviderAdapterDriver<CodexSettings, CodexAda
|
||||
fileSystem,
|
||||
idAllocator,
|
||||
serverConfig,
|
||||
continuationRequests,
|
||||
});
|
||||
}),
|
||||
};
|
||||
@@ -1209,6 +1238,7 @@ export const layer: Layer.Layer<
|
||||
ProviderAdapterV2,
|
||||
Effect.gen(function* () {
|
||||
const clientFactory = yield* CodexAppServerClientFactory;
|
||||
const continuationRequests = yield* ProviderContinuationRequests;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const hostEnvironment = yield* HostProcessEnvironment;
|
||||
const idAllocator = yield* IdAllocatorV2;
|
||||
@@ -1222,6 +1252,7 @@ export const layer: Layer.Layer<
|
||||
fileSystem,
|
||||
idAllocator,
|
||||
serverConfig,
|
||||
continuationRequests,
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -1234,10 +1265,19 @@ export interface CodexAdapterV2Options {
|
||||
readonly fileSystem: FileSystem.FileSystem;
|
||||
readonly idAllocator: IdAllocatorV2Shape;
|
||||
readonly serverConfig: ServerConfig["Service"];
|
||||
/**
|
||||
* Sink for post-settle background command completions so the orchestrator
|
||||
* can start a continuation run. Optional: adapters that omit it keep
|
||||
* projection-only handling for late item completions.
|
||||
*/
|
||||
readonly continuationRequests?: {
|
||||
readonly offer: (request: ProviderContinuationRequest) => Effect.Effect<void>;
|
||||
};
|
||||
}
|
||||
|
||||
export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): ProviderAdapterV2Shape {
|
||||
const { clientFactory, fileSystem, idAllocator, serverConfig } = adapterOptions;
|
||||
const continuationRequests = adapterOptions.continuationRequests;
|
||||
|
||||
return ProviderAdapterV2.of({
|
||||
instanceId: adapterOptions.instanceId,
|
||||
@@ -1292,6 +1332,14 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
|
||||
const pendingRuntimeRequests = yield* Ref.make(
|
||||
new Map<string, PendingCodexRuntimeRequest>(),
|
||||
);
|
||||
/**
|
||||
* Turn contexts retained past turn/completed while background command
|
||||
* items started in that turn are still running, so late item events
|
||||
* keep projecting instead of being dropped.
|
||||
*/
|
||||
const settledTurns = yield* Ref.make(new Map<string, ActiveCodexTurnContext>());
|
||||
const runningCommandItemsByTurn = yield* Ref.make(new Map<string, Set<string>>());
|
||||
const offeredContinuationItemsByTurn = yield* Ref.make(new Map<string, Set<string>>());
|
||||
|
||||
const emitProviderEvent = (event: ProviderAdapterV2Event) =>
|
||||
Queue.offer(events, event).pipe(Effect.asVoid);
|
||||
@@ -1376,6 +1424,48 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
|
||||
return yield* awaitActiveTurn(nativeTurnId, attemptsRemaining - 1);
|
||||
});
|
||||
|
||||
/**
|
||||
* Like awaitActiveTurn, but item lifecycle events for a turn that
|
||||
* already settled (background command completions) resolve the
|
||||
* retained settled context instead of dropping.
|
||||
*/
|
||||
const resolveItemEventContext = (nativeTurnId: string) =>
|
||||
Effect.gen(function* () {
|
||||
const settled = (yield* Ref.get(settledTurns)).get(nativeTurnId);
|
||||
if (settled !== undefined) {
|
||||
return { context: settled, settled: true } as const;
|
||||
}
|
||||
const context = yield* awaitActiveTurn(nativeTurnId);
|
||||
return context === undefined ? undefined : ({ context, settled: false } as const);
|
||||
});
|
||||
|
||||
const trackRunningCommandItem = (nativeTurnId: string, nativeItemId: string) =>
|
||||
Ref.update(runningCommandItemsByTurn, (current) => {
|
||||
const updated = new Map(current);
|
||||
const items = new Set(updated.get(nativeTurnId) ?? []);
|
||||
items.add(nativeItemId);
|
||||
updated.set(nativeTurnId, items);
|
||||
return updated;
|
||||
});
|
||||
|
||||
/** Returns true when the turn has no running command items left. */
|
||||
const clearRunningCommandItem = (nativeTurnId: string, nativeItemId: string) =>
|
||||
Ref.modify(runningCommandItemsByTurn, (current) => {
|
||||
const items = current.get(nativeTurnId);
|
||||
if (items === undefined || !items.has(nativeItemId)) {
|
||||
return [items === undefined || items.size === 0, current] as const;
|
||||
}
|
||||
const remaining = new Set(items);
|
||||
remaining.delete(nativeItemId);
|
||||
const updated = new Map(current);
|
||||
if (remaining.size === 0) {
|
||||
updated.delete(nativeTurnId);
|
||||
} else {
|
||||
updated.set(nativeTurnId, remaining);
|
||||
}
|
||||
return [remaining.size === 0, updated] as const;
|
||||
});
|
||||
|
||||
const resolveItemOrdinal = (context: ActiveCodexTurnContext, nativeItemId: string) =>
|
||||
Effect.gen(function* () {
|
||||
const existing = (yield* Ref.get(itemOrdinals)).get(nativeItemId);
|
||||
@@ -1511,6 +1601,13 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
|
||||
updated.set(turn.nativeTurnId, activeContext);
|
||||
return updated;
|
||||
});
|
||||
if (providerTurnOrdinal > 1 && subagent.task.status !== "running") {
|
||||
yield* emitSubagentTaskUpdate({
|
||||
subagent,
|
||||
status: "running",
|
||||
result: null,
|
||||
});
|
||||
}
|
||||
const now = yield* DateTime.now;
|
||||
yield* emitProviderEvent({
|
||||
type: "provider_thread.updated",
|
||||
@@ -3424,6 +3521,9 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
|
||||
}
|
||||
|
||||
if (payload.item.type === "commandExecution") {
|
||||
if (!codexItemStatus(payload.item.status).completed) {
|
||||
yield* trackRunningCommandItem(payload.turnId, payload.item.id);
|
||||
}
|
||||
const artifacts = yield* buildCommandExecutionArtifacts(context, payload.item);
|
||||
yield* emitProviderEvent({
|
||||
type: "node.updated",
|
||||
@@ -3477,10 +3577,11 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
|
||||
|
||||
yield* client.handleServerNotification("item/completed", (payload) =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* awaitActiveTurn(payload.turnId);
|
||||
if (context === undefined) {
|
||||
const resolved = yield* resolveItemEventContext(payload.turnId);
|
||||
if (resolved === undefined) {
|
||||
return;
|
||||
}
|
||||
const { context, settled } = resolved;
|
||||
|
||||
if (payload.item.type === "userMessage") {
|
||||
if (yield* emitSubagentUserMessage(context, payload.item)) {
|
||||
@@ -3489,6 +3590,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
|
||||
}
|
||||
|
||||
if (payload.item.type === "commandExecution") {
|
||||
const turnDrained = yield* clearRunningCommandItem(payload.turnId, payload.item.id);
|
||||
const artifacts = yield* buildCommandExecutionArtifacts(context, payload.item);
|
||||
yield* emitProviderEvent({
|
||||
type: "node.updated",
|
||||
@@ -3500,6 +3602,47 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
|
||||
driver: CODEX_PROVIDER,
|
||||
turnItem: artifacts.turnItem,
|
||||
});
|
||||
if (settled) {
|
||||
if (context.subagent === null && continuationRequests !== undefined) {
|
||||
const alreadyOffered = yield* Ref.modify(
|
||||
offeredContinuationItemsByTurn,
|
||||
(current) => {
|
||||
const items = current.get(payload.turnId);
|
||||
if (items !== undefined && items.has(payload.item.id)) {
|
||||
return [true, current] as const;
|
||||
}
|
||||
const updated = new Map(current);
|
||||
const updatedItems = new Set(items ?? []);
|
||||
updatedItems.add(payload.item.id);
|
||||
updated.set(payload.turnId, updatedItems);
|
||||
return [false, updated] as const;
|
||||
},
|
||||
);
|
||||
if (!alreadyOffered) {
|
||||
yield* continuationRequests.offer({
|
||||
threadId: context.projectionThreadId,
|
||||
providerThreadId: context.providerThread.id,
|
||||
driver: CODEX_PROVIDER,
|
||||
detail: codexBackgroundCommandDetail(payload.item),
|
||||
});
|
||||
}
|
||||
}
|
||||
if (turnDrained) {
|
||||
yield* Ref.update(settledTurns, (current) => {
|
||||
const updated = new Map(current);
|
||||
updated.delete(payload.turnId);
|
||||
return updated;
|
||||
});
|
||||
yield* Ref.update(offeredContinuationItemsByTurn, (current) => {
|
||||
if (!current.has(payload.turnId)) {
|
||||
return current;
|
||||
}
|
||||
const updated = new Map(current);
|
||||
updated.delete(payload.turnId);
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -3627,11 +3770,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
|
||||
itemId: payload.item.id,
|
||||
finalText: payload.item.text,
|
||||
});
|
||||
if (
|
||||
context.subagent !== null &&
|
||||
context.providerTurnOrdinal === 1 &&
|
||||
payload.item.phase !== "commentary"
|
||||
) {
|
||||
if (context.subagent !== null && payload.item.phase !== "commentary") {
|
||||
yield* emitSubagentTaskUpdate({
|
||||
subagent: context.subagent,
|
||||
status: context.subagent.task.status,
|
||||
@@ -4068,34 +4207,32 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
|
||||
updatedAt: completedAt,
|
||||
},
|
||||
});
|
||||
if (context.providerTurnOrdinal === 1) {
|
||||
yield* emitProviderEvent({
|
||||
type: "node.updated",
|
||||
driver: CODEX_PROVIDER,
|
||||
node: {
|
||||
id: context.subagent.subagentNodeId,
|
||||
threadId: context.subagent.parentContext.projectionThreadId,
|
||||
runId: context.subagent.parentContext.projectionRunId,
|
||||
parentNodeId: context.subagent.parentContext.itemParentNodeId,
|
||||
rootNodeId: context.subagent.parentContext.rootNodeId,
|
||||
kind: "subagent",
|
||||
status,
|
||||
countsForRun: false,
|
||||
providerThreadId: context.providerThread.id,
|
||||
providerTurnId: context.subagent.parentContext.providerTurnId,
|
||||
nativeItemRef: context.subagent.task.nativeTaskRef,
|
||||
runtimeRequestId: null,
|
||||
checkpointScopeId: null,
|
||||
startedAt: context.subagent.startedAt,
|
||||
completedAt,
|
||||
},
|
||||
});
|
||||
yield* emitSubagentTaskUpdate({
|
||||
subagent: context.subagent,
|
||||
yield* emitProviderEvent({
|
||||
type: "node.updated",
|
||||
driver: CODEX_PROVIDER,
|
||||
node: {
|
||||
id: context.subagent.subagentNodeId,
|
||||
threadId: context.subagent.parentContext.projectionThreadId,
|
||||
runId: context.subagent.parentContext.projectionRunId,
|
||||
parentNodeId: context.subagent.parentContext.itemParentNodeId,
|
||||
rootNodeId: context.subagent.parentContext.rootNodeId,
|
||||
kind: "subagent",
|
||||
status,
|
||||
countsForRun: false,
|
||||
providerThreadId: context.providerThread.id,
|
||||
providerTurnId: context.subagent.parentContext.providerTurnId,
|
||||
nativeItemRef: context.subagent.task.nativeTaskRef,
|
||||
runtimeRequestId: null,
|
||||
checkpointScopeId: null,
|
||||
startedAt: context.subagent.startedAt,
|
||||
completedAt,
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
yield* emitSubagentTaskUpdate({
|
||||
subagent: context.subagent,
|
||||
status,
|
||||
completedAt,
|
||||
});
|
||||
}
|
||||
if (context.subagent === null) {
|
||||
const terminalStatus = providerTurnStatusToTerminal(status);
|
||||
@@ -4134,11 +4271,34 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
|
||||
if (waiter !== undefined) {
|
||||
yield* Deferred.succeed(waiter, undefined);
|
||||
}
|
||||
const runningItems = (yield* Ref.get(runningCommandItemsByTurn)).get(payload.turn.id);
|
||||
// Failed and interrupted turns intentionally drop background command
|
||||
// tracking: late completions should not wake a turn the user stopped
|
||||
// or that errored, and the session should not stay pinned for them.
|
||||
const retainSettledContext =
|
||||
status === "completed" && runningItems !== undefined && runningItems.size > 0;
|
||||
if (retainSettledContext) {
|
||||
yield* Ref.update(settledTurns, (current) => {
|
||||
const updated = new Map(current);
|
||||
updated.set(payload.turn.id, context);
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
yield* Ref.update(activeTurns, (current) => {
|
||||
const updated = new Map(current);
|
||||
updated.delete(payload.turn.id);
|
||||
return updated;
|
||||
});
|
||||
if (!retainSettledContext) {
|
||||
yield* Ref.update(runningCommandItemsByTurn, (current) => {
|
||||
if (!current.has(payload.turn.id)) {
|
||||
return current;
|
||||
}
|
||||
const updated = new Map(current);
|
||||
updated.delete(payload.turn.id);
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -4148,6 +4308,23 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
|
||||
providerSessionId: input.providerSessionId,
|
||||
providerSession: session,
|
||||
events: Stream.fromEffectRepeat(Queue.take(events)),
|
||||
// Known gap: a subagent that Codex resumes later reads as completed
|
||||
// (not pending) between turns, so idle release can win the race
|
||||
// against a long-delayed resume. Codex emits no resume-expected
|
||||
// signal to pin on.
|
||||
hasPendingBackgroundWork: Effect.gen(function* () {
|
||||
for (const items of (yield* Ref.get(runningCommandItemsByTurn)).values()) {
|
||||
if (items.size > 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
for (const subagent of (yield* Ref.get(subagentThreads)).values()) {
|
||||
if (subagent.task.status === "running") {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}),
|
||||
ensureThread: (threadInput) =>
|
||||
ensureInitialized.pipe(
|
||||
Effect.andThen(
|
||||
|
||||
Reference in new issue
Block a user