fix(orchestrator): harden provider edge cases
Co-authored-by: codex <[email protected]>
This commit is contained in:
1 parent
c2a1c56596
commit
d9ea5b182c
9 files changed
+180
-112
No files matched your search
@@ -7,6 +7,8 @@ import * as NodeURL from "node:url";
|
||||
|
||||
import { expect, it } from "vite-plus/test";
|
||||
|
||||
import { acpReplayAgentArgs } from "../src/orchestration-v2/Adapters/AcpAdapterV2.testkit.ts";
|
||||
|
||||
const replayAgentPath = NodeURL.fileURLToPath(new URL("./acp-replay-agent.ts", import.meta.url));
|
||||
|
||||
async function runRuntimeExit(status: "success" | "error" | "cancelled") {
|
||||
@@ -16,7 +18,8 @@ async function runRuntimeExit(status: "success" | "error" | "cancelled") {
|
||||
scenario: `${status}-runtime-exit`,
|
||||
entries: [{ type: "runtime_exit", status }],
|
||||
};
|
||||
const child = NodeChildProcess.spawn(process.execPath, [replayAgentPath], {
|
||||
const args = acpReplayAgentArgs(replayAgentPath);
|
||||
const child = NodeChildProcess.spawn(process.execPath, args, {
|
||||
env: {
|
||||
...process.env,
|
||||
T3_ACP_REPLAY_STATUS_PATH: statusPath,
|
||||
@@ -42,6 +45,7 @@ async function runRuntimeExit(status: "success" | "error" | "cancelled") {
|
||||
status: JSON.parse(NodeFS.readFileSync(statusPath, "utf8")) as unknown,
|
||||
stderr,
|
||||
transcript,
|
||||
args,
|
||||
};
|
||||
} finally {
|
||||
NodeFS.rmSync(scratch, { recursive: true, force: true });
|
||||
@@ -51,6 +55,7 @@ async function runRuntimeExit(status: "success" | "error" | "cancelled") {
|
||||
it("accepts a recorded cancelled runtime exit", async () => {
|
||||
const result = await runRuntimeExit("cancelled");
|
||||
expect(result.code, result.stderr).toBe(0);
|
||||
expect(result.args).toEqual(["--experimental-strip-types", replayAgentPath]);
|
||||
expect(result.status).toEqual({
|
||||
scenario: result.transcript.scenario,
|
||||
cursor: 1,
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
|
||||
import { codexReplayRecordingOutputRecords } from "./codexReplayRecordingRecords.ts";
|
||||
|
||||
it("preserves monotonic request ids across native Codex forks", () => {
|
||||
const records = [
|
||||
{
|
||||
type: "expect_outbound",
|
||||
label: "initialize",
|
||||
frame: { id: 1, method: "initialize" },
|
||||
},
|
||||
{
|
||||
type: "expect_outbound",
|
||||
label: "thread/fork",
|
||||
frame: { id: 4, method: "thread/fork" },
|
||||
},
|
||||
{
|
||||
type: "expect_outbound",
|
||||
label: "turn/start",
|
||||
frame: { id: 5, method: "turn/start" },
|
||||
},
|
||||
];
|
||||
|
||||
const output = codexReplayRecordingOutputRecords(records);
|
||||
|
||||
assert.deepEqual(output, records);
|
||||
assert.deepEqual(
|
||||
output.map((record) => record.label),
|
||||
["initialize", "thread/fork", "turn/start"],
|
||||
);
|
||||
assert.deepEqual(
|
||||
output.map((record) => (record.frame as { readonly id: number }).id),
|
||||
[1, 4, 5],
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* Codex supports multiple provider threads in one app-server session, so native
|
||||
* fork recording keeps the request ids emitted by that single client.
|
||||
*/
|
||||
export function codexReplayRecordingOutputRecords(
|
||||
records: ReadonlyArray<Record<string, unknown>>,
|
||||
): ReadonlyArray<Record<string, unknown>> {
|
||||
return [...records];
|
||||
}
|
||||
@@ -51,6 +51,7 @@ import {
|
||||
TURN_INTERRUPT_MID_TOOL_PROMPT,
|
||||
TURN_INTERRUPT_PROMPT,
|
||||
} from "../src/orchestration-v2/testkit/fixtures/shared.ts";
|
||||
import { codexReplayRecordingOutputRecords } from "./codexReplayRecordingRecords.ts";
|
||||
import { makeReplayRecorderDeferredRegistry } from "./replayRecorderDeferredRegistry.ts";
|
||||
|
||||
const CODEX_REPLAY_PLAN_MODE_DEVELOPER_INSTRUCTIONS =
|
||||
@@ -859,10 +860,7 @@ function makeRecorder({
|
||||
records.push(record);
|
||||
});
|
||||
const flush = () => {
|
||||
const outputRecords = sessionizeForkReplayRecords({
|
||||
scenario: scenario.name,
|
||||
records,
|
||||
});
|
||||
const outputRecords = codexReplayRecordingOutputRecords(records);
|
||||
return fs.writeFileString(
|
||||
outPath,
|
||||
`${[
|
||||
@@ -889,96 +887,6 @@ function makeRecorder({
|
||||
});
|
||||
}
|
||||
|
||||
function sessionizeForkReplayRecords(input: {
|
||||
readonly scenario: ScenarioName;
|
||||
readonly records: ReadonlyArray<Record<string, unknown>>;
|
||||
}): ReadonlyArray<Record<string, unknown>> {
|
||||
if (
|
||||
input.scenario !== "thread_merge_back_continue" &&
|
||||
input.scenario !== "thread_merge_back_siblings"
|
||||
) {
|
||||
return input.records;
|
||||
}
|
||||
const initializeRequest = input.records.find(
|
||||
(record) => record.type === "expect_outbound" && record.label === "initialize",
|
||||
);
|
||||
const initializeResponse = input.records.find(
|
||||
(record) => record.type === "emit_inbound" && record.label === "initialize",
|
||||
);
|
||||
const initializedNotification = input.records.find(
|
||||
(record) => record.type === "expect_outbound" && record.label === "initialized",
|
||||
);
|
||||
if (
|
||||
initializeRequest === undefined ||
|
||||
initializeResponse === undefined ||
|
||||
initializedNotification === undefined
|
||||
) {
|
||||
throw new Error(`Scenario ${input.scenario} is missing initialization records.`);
|
||||
}
|
||||
|
||||
let nextRequestId = 1;
|
||||
let forkSessionOrdinal = 0;
|
||||
const requestIdMap = new Map<number, number>();
|
||||
const output: Array<Record<string, unknown>> = [];
|
||||
const appendRequest = (record: Record<string, unknown>, id: number) => {
|
||||
const frame = record.frame as Record<string, unknown>;
|
||||
output.push({ ...record, frame: { ...frame, id } });
|
||||
};
|
||||
const appendResponse = (record: Record<string, unknown>, id: number) => {
|
||||
const frame = record.frame as Record<string, unknown>;
|
||||
output.push({ ...record, frame: { ...frame, id } });
|
||||
};
|
||||
|
||||
for (const record of input.records) {
|
||||
const frame = record.frame;
|
||||
if (record.type === "expect_outbound" && isRecord(frame) && frame.method === "thread/fork") {
|
||||
forkSessionOrdinal += 1;
|
||||
const initializeId = nextRequestId++;
|
||||
appendRequest(
|
||||
{ ...initializeRequest, label: `initialize/fork:${forkSessionOrdinal}` },
|
||||
initializeId,
|
||||
);
|
||||
appendResponse(
|
||||
{ ...initializeResponse, label: `initialize/fork:${forkSessionOrdinal}` },
|
||||
initializeId,
|
||||
);
|
||||
output.push({
|
||||
...initializedNotification,
|
||||
label: `initialized/fork:${forkSessionOrdinal}`,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
record.type === "expect_outbound" &&
|
||||
isRecord(frame) &&
|
||||
typeof frame.id === "number" &&
|
||||
typeof frame.method === "string"
|
||||
) {
|
||||
const requestId = nextRequestId++;
|
||||
requestIdMap.set(frame.id, requestId);
|
||||
appendRequest(record, requestId);
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
record.type === "emit_inbound" &&
|
||||
isRecord(frame) &&
|
||||
typeof frame.id === "number" &&
|
||||
!("method" in frame)
|
||||
) {
|
||||
const responseId = requestIdMap.get(frame.id);
|
||||
if (responseId === undefined) {
|
||||
throw new Error(
|
||||
`Scenario ${input.scenario} has an unmatched response id ${String(frame.id)}.`,
|
||||
);
|
||||
}
|
||||
appendResponse(record, responseId);
|
||||
continue;
|
||||
}
|
||||
output.push(record);
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
function makeCodexLayer({ recorder }: { readonly recorder: Recorder }) {
|
||||
const clientRequestMethodById = new Map<string, string>();
|
||||
const serverRequestMethodById = new Map<string, string>();
|
||||
|
||||
@@ -773,7 +773,7 @@ const make = Effect.gen(function* () {
|
||||
);
|
||||
}
|
||||
const childProjection = yield* loadProjection(task.childThreadId);
|
||||
const childRun = childProjection.runs[0];
|
||||
const childRun = latestRun(childProjection);
|
||||
const status = taskStatusForRun(childRun);
|
||||
const derivedResult =
|
||||
task.result !== null
|
||||
|
||||
@@ -817,6 +817,38 @@ describe("orchestrator MCP toolkit", () => {
|
||||
expect(delegatedStatus.status).toBe("completed");
|
||||
expect(delegatedStatus.resultContextTransferId).not.toBeNull();
|
||||
|
||||
const childFollowupCall = yield* invoke("t3_thread_send", {
|
||||
threadId: delegated.childThreadId,
|
||||
message: "Confirm the delegated API boundary remains inspected.",
|
||||
clientRequestId: "delegated-child-followup-1",
|
||||
});
|
||||
const childFollowup = yield* decodeThreadSendResult(
|
||||
childFollowupCall.structuredContent,
|
||||
).pipe(Effect.orDie);
|
||||
const childFollowupWaitCall = yield* invoke("t3_thread_wait", {
|
||||
threadId: delegated.childThreadId,
|
||||
runId: childFollowup.runId,
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
const childFollowupWait = yield* decodeThreadWaitResult(
|
||||
childFollowupWaitCall.structuredContent,
|
||||
).pipe(Effect.orDie);
|
||||
expect(childFollowupWait).toMatchObject({
|
||||
runId: childFollowup.runId,
|
||||
status: "completed",
|
||||
timedOut: false,
|
||||
});
|
||||
const delegatedStatusAfterFollowupCall = yield* invoke("task_status", {
|
||||
taskId: delegated.taskId,
|
||||
});
|
||||
const delegatedStatusAfterFollowup = yield* decodeDelegateTaskResult(
|
||||
delegatedStatusAfterFollowupCall.structuredContent,
|
||||
).pipe(Effect.orDie);
|
||||
expect(delegatedStatusAfterFollowup).toMatchObject({
|
||||
childRunId: childFollowup.runId,
|
||||
status: "completed",
|
||||
});
|
||||
|
||||
// A wait-mode child (completionWake settled_only) that completes
|
||||
// while the parent run is live does not offer a wake: the
|
||||
// blocking delegate_task call above already returned the result.
|
||||
|
||||
@@ -59,6 +59,7 @@ import {
|
||||
} from "../../provider/acp/XAiAcpExtension.ts";
|
||||
import { layer as idAllocatorLayer, IdAllocatorV2 } from "../IdAllocator.ts";
|
||||
import {
|
||||
ProviderAdapterProtocolError,
|
||||
ProviderAdapterV2RuntimePolicy,
|
||||
type ProviderAdapterV2Event,
|
||||
type ProviderAdapterV2TurnInput,
|
||||
@@ -998,6 +999,10 @@ describe("AcpAdapterV2", () => {
|
||||
|
||||
assert.isTrue(runtime.providerSession.capabilities.threads.canForkThread);
|
||||
assert.isTrue(runtime.providerSession.capabilities.threads.canReadThreadSnapshot);
|
||||
assert.isTrue(runtime.providerSession.capabilities.sessions.supportsModelSwitchInSession);
|
||||
assert.isFalse(
|
||||
runtime.providerSession.capabilities.sessions.supportsRuntimeModeSwitchInSession,
|
||||
);
|
||||
|
||||
const sourceProviderThread = yield* runtime.ensureThread({
|
||||
threadId: sourceThreadId,
|
||||
@@ -1040,6 +1045,66 @@ describe("AcpAdapterV2", () => {
|
||||
}).pipe(Effect.provide(testLayer), Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("fails missing native ACP session ids through the typed start-turn error channel", () =>
|
||||
Effect.gen(function* () {
|
||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const idAllocator = yield* IdAllocatorV2;
|
||||
const path = yield* Path.Path;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const mockAgentPath = yield* path.fromFileUrl(
|
||||
new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
|
||||
);
|
||||
const instanceId = ProviderInstanceId.make("acp-test-missing-native-thread");
|
||||
const adapter = makeAcpAdapterV2({
|
||||
crypto: yield* Crypto.Crypto,
|
||||
instanceId,
|
||||
flavor: {
|
||||
driver: ACP_TEST_DRIVER,
|
||||
capabilities: AcpProviderCapabilitiesV2,
|
||||
makeRuntime: makeMockRuntime({ childProcessSpawner, mockAgentPath }),
|
||||
},
|
||||
fileSystem,
|
||||
idAllocator,
|
||||
serverConfig,
|
||||
});
|
||||
const threadId = ThreadId.make("thread-acp-missing-native-thread");
|
||||
const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
cwd: process.cwd(),
|
||||
});
|
||||
const modelSelection = { instanceId, model: "default" } as const;
|
||||
const runtime = yield* adapter.openSession({
|
||||
threadId,
|
||||
providerSessionId: ProviderSessionId.make("provider-session-acp-missing-native-thread"),
|
||||
modelSelection,
|
||||
runtimePolicy,
|
||||
});
|
||||
const providerThread = yield* runtime.ensureThread({
|
||||
threadId,
|
||||
modelSelection,
|
||||
runtimePolicy,
|
||||
});
|
||||
const now = yield* DateTime.now;
|
||||
const error = yield* runtime
|
||||
.startTurn(
|
||||
makeTurnInput({
|
||||
threadId,
|
||||
providerThread: { ...providerThread, nativeThreadRef: null },
|
||||
instanceId,
|
||||
runtimePolicy,
|
||||
now,
|
||||
}),
|
||||
)
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.equal(error._tag, "ProviderAdapterTurnStartError");
|
||||
assert.instanceOf(error.cause, ProviderAdapterProtocolError);
|
||||
assert.include(String(error.cause), "missing its ACP session id");
|
||||
}).pipe(Effect.provide(testLayer), Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("closes an idle ACP session exactly once through the transition permit", () =>
|
||||
Effect.gen(function* () {
|
||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
@@ -145,6 +145,10 @@ export function makeAcpReplayCompletenessAssertion(
|
||||
);
|
||||
}
|
||||
|
||||
export function acpReplayAgentArgs(scriptPath: string): ReadonlyArray<string> {
|
||||
return ["--experimental-strip-types", scriptPath];
|
||||
}
|
||||
|
||||
export function makeAcpReplayRuntime(input: {
|
||||
readonly transcript: AcpReplayTranscript;
|
||||
readonly statusPath: string;
|
||||
@@ -167,7 +171,7 @@ export function makeAcpReplayRuntime(input: {
|
||||
...runtimeInput,
|
||||
spawn: {
|
||||
command: process.execPath,
|
||||
args: [input.scriptPath],
|
||||
args: acpReplayAgentArgs(input.scriptPath),
|
||||
cwd: runtimeInput.cwd,
|
||||
env: {
|
||||
...process.env,
|
||||
|
||||
@@ -474,7 +474,6 @@ function negotiatedCapabilities(
|
||||
const setup = started.sessionSetupResult;
|
||||
const hasModelConfig =
|
||||
setup.configOptions?.some((option) => option.category === "model") === true;
|
||||
const hasModeConfig = setup.configOptions?.some((option) => option.category === "mode") === true;
|
||||
const supportsMcp = agent.mcpCapabilities?.http === true || agent.mcpCapabilities?.sse === true;
|
||||
const canLoad = agent.loadSession === true;
|
||||
const canFork = session?.fork != null;
|
||||
@@ -483,7 +482,6 @@ function negotiatedCapabilities(
|
||||
sessions: {
|
||||
...base.sessions,
|
||||
supportsModelSwitchInSession: setup.models != null || hasModelConfig,
|
||||
supportsRuntimeModeSwitchInSession: setup.modes != null || hasModeConfig,
|
||||
},
|
||||
threads: {
|
||||
...base.threads,
|
||||
@@ -523,15 +521,20 @@ function acpMcpServers(threadId: ThreadId | null): ReadonlyArray<EffectAcpSchema
|
||||
];
|
||||
}
|
||||
|
||||
function nativeThreadId(driver: ProviderDriverKind, thread: OrchestrationV2ProviderThread): string {
|
||||
function nativeThreadId(
|
||||
driver: ProviderDriverKind,
|
||||
thread: OrchestrationV2ProviderThread,
|
||||
): Effect.Effect<string, ProviderAdapterProtocolError> {
|
||||
const id = thread.nativeThreadRef?.nativeId;
|
||||
if (id === null || id === undefined || id.trim().length === 0) {
|
||||
throw new ProviderAdapterProtocolError({
|
||||
driver,
|
||||
detail: `Provider thread ${thread.id} is missing its ACP session id`,
|
||||
});
|
||||
return Effect.fail(
|
||||
new ProviderAdapterProtocolError({
|
||||
driver,
|
||||
detail: `Provider thread ${thread.id} is missing its ACP session id`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
return id;
|
||||
return Effect.succeed(id);
|
||||
}
|
||||
|
||||
function makeProviderThread(input: {
|
||||
@@ -960,6 +963,7 @@ interface ActiveTextStream {
|
||||
interface ActiveAcpTurn {
|
||||
readonly input: ProviderAdapterV2TurnInput;
|
||||
readonly providerTurnId: OrchestrationV2ProviderTurn["id"];
|
||||
readonly nativeThreadId: string;
|
||||
readonly nativeTurnId: string;
|
||||
readonly startedAt: DateTime.Utc;
|
||||
readonly completed: Deferred.Deferred<void, never>;
|
||||
@@ -1990,7 +1994,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
|
||||
existing?.childThreadId ??
|
||||
idAllocator.derive.threadFromProviderThread({
|
||||
driver,
|
||||
nativeThreadId: `${nativeThreadId(driver, context.input.providerThread)}:task:${nativeTaskId}`,
|
||||
nativeThreadId: `${context.nativeThreadId}:task:${nativeTaskId}`,
|
||||
});
|
||||
const childRootNodeId =
|
||||
existing?.childRootNodeId ??
|
||||
@@ -2478,7 +2482,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
|
||||
}
|
||||
const status = projectedStatus ?? toolStatus(toolCall.status);
|
||||
const now = yield* DateTime.now;
|
||||
const nativeItemId = `${nativeThreadId(driver, context.input.providerThread)}:tool:${toolCall.toolCallId}`;
|
||||
const nativeItemId = `${context.nativeThreadId}:tool:${toolCall.toolCallId}`;
|
||||
const ordinal = yield* resolveItemOrdinal(context, nativeItemId);
|
||||
const nodeId = idAllocator.derive.nodeFromProviderItem({ driver, nativeItemId });
|
||||
const turnItemId = idAllocator.derive.turnItemFromProviderItem({
|
||||
@@ -4522,7 +4526,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
|
||||
detail: `ACP provider turn ${existing.providerTurnId} is still active`,
|
||||
});
|
||||
}
|
||||
const requestedSessionId = nativeThreadId(driver, turnInput.providerThread);
|
||||
const requestedSessionId = yield* nativeThreadId(driver, turnInput.providerThread);
|
||||
const restartAfterInterrupt = yield* restartRuntimeAfterTeardownIfRequired();
|
||||
const needsSessionActivation =
|
||||
(yield* Ref.get(activeSessionId)) !== requestedSessionId || restartAfterInterrupt;
|
||||
@@ -4603,6 +4607,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
|
||||
const context: ActiveAcpTurn = {
|
||||
input: turnInput,
|
||||
providerTurnId,
|
||||
nativeThreadId: requestedSessionId,
|
||||
nativeTurnId,
|
||||
startedAt,
|
||||
completed,
|
||||
@@ -4922,7 +4927,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
|
||||
Effect.gen(function* () {
|
||||
yield* awaitRuntimeTeardown();
|
||||
const restartAfterInterrupt = yield* restartRuntimeAfterTeardownIfRequired();
|
||||
const sessionId = nativeThreadId(driver, threadInput.providerThread);
|
||||
const sessionId = yield* nativeThreadId(driver, threadInput.providerThread);
|
||||
if ((yield* Ref.get(activeSessionId)) !== sessionId || restartAfterInterrupt) {
|
||||
yield* Ref.set(snapshot, {
|
||||
order: [],
|
||||
@@ -5327,7 +5332,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
|
||||
Effect.gen(function* () {
|
||||
yield* awaitRuntimeTeardown();
|
||||
yield* restartRuntimeAfterTeardownIfRequired();
|
||||
const sessionId = nativeThreadId(driver, snapshotInput.providerThread);
|
||||
const sessionId = yield* nativeThreadId(driver, snapshotInput.providerThread);
|
||||
if ((yield* Ref.get(activeSessionId)) !== sessionId) {
|
||||
if (!capabilities.threads.canReadThreadSnapshot) {
|
||||
return yield* new ProviderAdapterProtocolError({
|
||||
@@ -5405,8 +5410,13 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
|
||||
detail: "ACP session/fork can only fork the current session head",
|
||||
});
|
||||
}
|
||||
const sourceSessionId = nativeThreadId(driver, forkInput.sourceProviderThread);
|
||||
const forked = yield* runtime.forkSession(sourceSessionId);
|
||||
const sourceSessionId = yield* nativeThreadId(
|
||||
driver,
|
||||
forkInput.sourceProviderThread,
|
||||
);
|
||||
const forked = yield* runtime.forkSession(sourceSessionId, {
|
||||
mcpServers: acpMcpServers(forkInput.targetThreadId),
|
||||
});
|
||||
yield* Ref.set(activeSessionId, forked.sessionId);
|
||||
yield* Ref.set(activeSessionSetup, forked);
|
||||
yield* Ref.set(activeSelection, null);
|
||||
|
||||
Reference in new issue
Block a user